Repository navigation
feat(dash,proxy): record wait cause and wake cause per request (#424 record half) - #453
Merged
Merged
Conversation
This was referenced Oct 11, 2026
amiddavid
added a commit
that referenced
this pull request
Oct 11, 2026
…ross compaction Two more fixes to #453, both decided by the user. 1. internal/waitcause no longer carries its own per-provider body parser (messageEntries, blocksOf's old gjson-based version). It now builds its wait signals from apply.NormalizeMessages(provider, orig) — the same normalization the compaction pipeline itself uses for all three dialects (Anthropic Messages, OpenAI chat, OpenAI Responses). Role- based system-noise detection (isNoiseEntry) now reads bschemas.ChatMessageRoleSystem directly instead of guessing from content. Found in the process, and deliberately NOT fixed here (a defect on main affecting every component gets its own issue and PR, not a fix riding a feature branch — the user is tracking it separately): apply.normalize's Anthropic branch drops any OTHER content block sibling to a tool_result in the same user message. Pinned by apply/normalize_siblingblock_test.go, written to fail once that normalizer gap is fixed. 2. The open-background-task and open-teammate state now survives the agent compacting its own history. Previously every request did a fresh rescan of the current body with no memory of earlier requests, so a Monitor's own start marker scrolling out of a compacted body read as "closed" even though the task was still running. The Tracker's per-thread state is now the source of truth (threadState. openBackground / openTeammates), updated by applying each request's open/close signals onto it rather than rebuilt from scratch; an item leaves only on its own finish signal, a TaskStop, a stated Monitor expiry, or a cap for one with none (noExpiryCap, matched to the existing teammateWaitCap). Every write is naturally safe to repeat against the same historical signal (every request resends the whole conversation) except the Skill-anonymous close fallback, which is explicitly guarded by a bounded appliedCloses set. Also fixes a real latency regression the user's own test caught: TestDashboardAddsNoRequestLatencyWithContentCapture failed because the body rescan (waitcause.Tracker.Observe, ~11ms on a 783 KB body) was running inline in finish(), which runs on the handler's own defer before it returns — delaying the NEXT request on a keep-alive connection by that amount. The scan now runs as a closure (dash.Event.WaitCause) invoked by the dashboard's writer goroutine, right beside Event.Redact() and for the identical reason. RecordOutcome is folded into the same closure so it still runs strictly after Observe reads the previous state, in the same order requests arrived. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
amiddavid
force-pushed
the
feat/wait-cause-record
branch
from
October 11, 2026 15:31
189f458 to
043f82c
Compare
amiddavid
added a commit
that referenced
this pull request
Oct 11, 2026
…ot human Found live, in #453's own live test: a backgrounded Agent's hand-back wakes the thread with ONLY an `<agent-message from="X">...</agent-message>` tag (plus the harness's own boilerplate explaining what it is) — no `<task-notification>`, no plain human text. classifyWake had no case for this tag at all, so it fell through to hasPlainText and reported wake_cause=human instead of background. Fixed by reusing agentMessageFromRE (already used to CLOSE an open background task in scanOpenState) as a presence check in classifyWake too, in the same bucket as <task-notification>: both are a background task's own finish signal arriving with nothing typed by a human. Confirmed fixed live: the same scenario that showed wake_cause=human before this fix now shows wake_cause=background. Regression test added (TestObserveWakeCauseAgentMessageIsBackground). Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
…424 record half) Add internal/waitcause, which reads the request body and the response's own stop reason and tool calls, by string match and structural tool_use reads only, no LLM. It writes waiting_for, wait_tool, wake_cause, open_background, open_teammate and monitor_expiry_ms on every request, so a later change can choose a keep-alive ping budget from real production data. This is RECORD only. It never reads these fields back, never changes the keep-alive ping budget (still a fixed 2 per thread, PR #426), and never changes compaction behaviour. Fails open throughout: a panic or a shape this package does not recognise leaves every field "unknown"/0 and never touches the request or its timing. Also adds waiting_for and wake_cause as /api/breakdown dimensions. Found during the live test and fixed here: a trailing bare {"role":"system"} entry some Claude Code builds append after every turn (even right after the real tool_result or human text) was hiding the actual wake signal behind it; classifyWake now skips trailing role=="system" entries structurally rather than guessing from content. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Issue #424's RECORD half scanned the pristine body (waitcause.Tracker. Observe, ~11ms on a 783 KB body) before forwarding the request upstream. Move it to finish(), after the response has already gone out, by stashing the body (one slice-header copy) with noteWaitBody instead of scanning it inline. The request path's own cost is now independent of body size — see BenchmarkNoteWaitBodyLargeBody alongside internal/waitcause's own BenchmarkObserveLargeBody. Also adds a test pinning that keep-alive ping rows (plain, and the cache_aware_summarizer's #402 summary-substitute) never get a waiting_for or wake_cause: both reach dash.Event construction through dashEmitter. KeepAlivePing, which holds no *waitcause.Tracker at all, so there was never a path from a ping to this package's state. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
…ross compaction Two more fixes to #453, both decided by the user. 1. internal/waitcause no longer carries its own per-provider body parser (messageEntries, blocksOf's old gjson-based version). It now builds its wait signals from apply.NormalizeMessages(provider, orig) — the same normalization the compaction pipeline itself uses for all three dialects (Anthropic Messages, OpenAI chat, OpenAI Responses). Role- based system-noise detection (isNoiseEntry) now reads bschemas.ChatMessageRoleSystem directly instead of guessing from content. Found in the process, and deliberately NOT fixed here (a defect on main affecting every component gets its own issue and PR, not a fix riding a feature branch — the user is tracking it separately): apply.normalize's Anthropic branch drops any OTHER content block sibling to a tool_result in the same user message. Pinned by apply/normalize_siblingblock_test.go, written to fail once that normalizer gap is fixed. 2. The open-background-task and open-teammate state now survives the agent compacting its own history. Previously every request did a fresh rescan of the current body with no memory of earlier requests, so a Monitor's own start marker scrolling out of a compacted body read as "closed" even though the task was still running. The Tracker's per-thread state is now the source of truth (threadState. openBackground / openTeammates), updated by applying each request's open/close signals onto it rather than rebuilt from scratch; an item leaves only on its own finish signal, a TaskStop, a stated Monitor expiry, or a cap for one with none (noExpiryCap, matched to the existing teammateWaitCap). Every write is naturally safe to repeat against the same historical signal (every request resends the whole conversation) except the Skill-anonymous close fallback, which is explicitly guarded by a bounded appliedCloses set. Also fixes a real latency regression the user's own test caught: TestDashboardAddsNoRequestLatencyWithContentCapture failed because the body rescan (waitcause.Tracker.Observe, ~11ms on a 783 KB body) was running inline in finish(), which runs on the handler's own defer before it returns — delaying the NEXT request on a keep-alive connection by that amount. The scan now runs as a closure (dash.Event.WaitCause) invoked by the dashboard's writer goroutine, right beside Event.Redact() and for the identical reason. RecordOutcome is folded into the same closure so it still runs strictly after Observe reads the previous state, in the same order requests arrived. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
…ot human Found live, in #453's own live test: a backgrounded Agent's hand-back wakes the thread with ONLY an `<agent-message from="X">...</agent-message>` tag (plus the harness's own boilerplate explaining what it is) — no `<task-notification>`, no plain human text. classifyWake had no case for this tag at all, so it fell through to hasPlainText and reported wake_cause=human instead of background. Fixed by reusing agentMessageFromRE (already used to CLOSE an open background task in scanOpenState) as a presence check in classifyWake too, in the same bucket as <task-notification>: both are a background task's own finish signal arriving with nothing typed by a human. Confirmed fixed live: the same scenario that showed wake_cause=human before this fix now shows wake_cause=background. Regression test added (TestObserveWakeCauseAgentMessageIsBackground). Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
…ecycle Per policy, no live tests on an individual PR; the live teammate-reply scenario moves to the merged-main integration check. Replaces it with a unit test that exercises the same lifecycle: own_tool/SendMessage opens the wait, waiting_for=teammate once the turn ends with nothing else to do, and a <teammate-message> reply gives wake_cause=teammate and closes open_teammate back to 0. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
…lings #460 (fix/normalizer-siblings) merged, closing #457: apply.normalize now keeps a sibling block beside a tool_result in the normalized view, as its own synthetic role=user message in wire order, instead of dropping it. apply's own normalizer_siblings_test.go (TestNormalizeKeepsSiblingTextBlocksInOrder and friends) already covers the normalizer directly, so the pinning test this PR added before #460 existed (apply/normalize_siblingblock_test.go, which asserted the OLD, dropped behaviour) is deleted rather than flipped — keeping it would either duplicate #460's own coverage or assert the wrong thing. internal/waitcause gets three new tests instead, for what THIS package needs to get right now that the sibling reaches it: a tool_result plus mid-turn user text gives wake_cause=human, a tool_result plus a <task-notification> sibling gives wake_cause=background (both read off the LAST normalized entry, which is now the sibling, not the tool_result), and a sibling that is ONLY a <system-reminder> block does NOT read as human — apply.normalize's synthetic sibling message is always role=user, so isNoiseEntry's role check does not catch it; classifyWake's content-based hasSystemMarker check already does, and this pins that it keeps doing so. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
amiddavid
force-pushed
the
feat/wait-cause-record
branch
from
October 11, 2026 17:32
ce5aa5b to
d33080b
Compare
OsherElhadad
pushed a commit
that referenced
this pull request
Oct 11, 2026
Behind --dashboard-lifecycle-signals (default off), a request_lifecycle side table stores the gap from the previous response end on the same thread, the granted cache TTL tier, the incoming tool_result count/bytes/error flag, and the keep-alive ping ordinal. The thread id, previous stop reason and tool names are the requests columns from #426 and #453 and are no longer duplicated. The body is read through apply.NormalizeMessages on the dashboard writer goroutine; stale thread state is evicted by age, amortised to once a minute; Lifecycles is scoped by tenant. Signed-off-by: Osher-Elhadad <[email protected]>
amiddavid
added a commit
that referenced
this pull request
Oct 11, 2026
Fix a bug found on production data (contextguru2): DB-only mode reported "28 real pings seen" when the DB actually held 351 ping rows (keepalive=1) across 75 sessions. Root cause: both modes counted pings via keepalive_pings, a column the Go proxy writes once -- on whichever real request a ping run ends with. That misses every ping whose session never sent another real request at all: there is no "next real row" to carry a count, so the ping just disappears from the total. It also priced every ping at a fixed 0.1x estimate, never the ping's own real cost_usd. Fix: - DBRow gains max_tokens and thread_id (the latter optional -- #423's column, not present on either local DB yet; read_db_rows() detects its absence via PRAGMA table_info and fails open to the (session_id, model) fallback the rest of this script already uses). - DBIndex.pings_for() and a new pings_in_range() read ping ROWS directly, matched to the gap they fall inside by timestamp (thread_id when the DB has one, else session_id+model), and sum their REAL cost_usd instead of estimating 0.1x * count. Used by both run_transcript_mode and db_only_report, so a ping is counted the same way in both. - ping_rows_summary(): every ping row in the DB, regardless of whether it falls in a measured gap -- count, sessions, total cost, and the max_tokens=0 "summary-substitute" (issue #458) subset, still counted as a ping slot, priced from its own cost_usd. - DBIndex.ping_orphans() / db_only_report's own matching: ping rows never attributed to a gap, reported separately as "pings for sessions that did not return" (count, sessions, cost) instead of silently vanishing from the total. - is_keepalive_substitute_strategy(): documents the extraction_calls strategy suffixes ('/keepalive_substitute_billed', '/keepalive_substitute') that must be excluded from any future "LLM spend" total built from that table, so a substitute ping's cost (already counted once here, from requests.cost_usd) is never added twice. This script does not read extraction_calls today, so nothing calls this yet. On both local DBs: 360 real ping rows (not 28), 305 attributed to a measured gap in DB-only mode (256 in transcript mode's exact per-thread gaps), the rest reported as pings for sessions that did not return ($2.83-$5.05 of $25.53 total, depending on mode). Extended --self-test: a synthetic DB with a ping row inside a gap, a summary-substitute ping also inside it, and an orphan ping after the session's last request, in both modes. Asserts the counts and the cost exactly. Rebased onto origin/main (issue #423/#453 and other work landed there since this branch was last pushed); no conflicts, this PR only touches scripts/analysis. Assisted-By: Claude Opus 5.5 (1M context) <[email protected]> Co-Authored-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID AMID <[email protected]>
This was referenced Oct 11, 2026
amiddavid
added a commit
that referenced
this pull request
Oct 13, 2026
…adow mode Part A of #404 (the cold path). The sweep asks its question in place of the keep-alive ping and holds the answer per thread. Nothing applies a held answer yet: it changes no request. - Ask at the ping, no timer of its own. The time-window trigger and pre_expiry_seconds are removed (the key is refused with the reason). - Ask with one candidate or more. min_inventory defaults to 1. - Hold per thread in the Store (cg:swh:, pinned), with tool_use_id and a SpanHash of the agent's message for each judged output, the judged length and the wait cause (#453). Stored only; nothing decides on it. - recheckHeld drops a verdict when the conversation is shorter, the output is gone or changed, a later turn referenced it (coref), or the agent expanded it. PR C calls it on the cold request. - shadow: true (off, in no preset) reports asked, proposed, still valid at the cold request, and the reasons, as request_components events and a cg.sweep.shadow log line. - evidence is on by default. - Plain ping, counted as sweep_model_declined, where the question breaks the cache (#422). - extract.Ask composes the question from lists, so #490 and #485 can add theirs. An output in two lists is judged once. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
amiddavid
added a commit
that referenced
this pull request
Oct 13, 2026
…adow mode Part A of #404 (the cold path). The sweep asks its question in place of the keep-alive ping and holds the answer per thread. Nothing applies a held answer yet: it changes no request. - Ask at the ping, no timer of its own. The time-window trigger and pre_expiry_seconds are removed (the key is refused with the reason). - Ask with one candidate or more. min_inventory defaults to 1. - Hold per thread in the Store (cg:swh:, pinned), with tool_use_id and a SpanHash of the agent's message for each judged output, the judged length and the wait cause (#453). Stored only; nothing decides on it. - recheckHeld drops a verdict when the conversation is shorter, the output is gone or changed, a later turn referenced it (coref), or the agent expanded it. PR C calls it on the cold request. - shadow: true (off, in no preset) reports asked, proposed, still valid at the cold request, and the reasons, as request_components events and a cg.sweep.shadow log line. - evidence is on by default. - Plain ping, counted as sweep_model_declined, where the question breaks the cache (#422). - Ask only when shadow is on, until the cold apply exists (PR C). Counted as sweep_ask_needs_shadow. - Remove econ_trigger, the in-request ask and the full-price fallback. The keys econ_trigger, econ_ignore_ask_cost, reward_premium, min_pressure and block_fallback are refused with a reason. - extract.Ask composes the question from lists, so #490 and #485 can add theirs. An output in two lists is judged once. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
amiddavid
added a commit
that referenced
this pull request
Oct 13, 2026
…adow mode Part A of #404 (the cold path). The sweep asks its question in place of the keep-alive ping and holds the answer per thread. Nothing applies a held answer yet: it changes no request. - Ask at the ping, no timer of its own. The time-window trigger and pre_expiry_seconds are removed (the key is refused with the reason). - Ask with one candidate or more. min_inventory defaults to 1. - Hold per thread in the Store (cg:swh:, pinned), with tool_use_id and a SpanHash of the agent's message for each judged output, the judged length and the wait cause (#453). Stored only; nothing decides on it. - recheckHeld drops a verdict when the conversation is shorter, the output is gone or changed, a later turn referenced it (coref), or the agent expanded it. PR C calls it on the cold request. - shadow: true (off, in no preset) reports asked, proposed, still valid at the cold request, and the reasons, as request_components events and a cg.sweep.shadow log line. - evidence is on by default. - Plain ping, counted as sweep_model_declined, where the question breaks the cache (#422). - Ask only when shadow is on, until the cold apply exists (PR C). Counted as sweep_ask_needs_shadow. - Remove econ_trigger, the in-request ask and the full-price fallback. The keys econ_trigger, econ_ignore_ask_cost, reward_premium, min_pressure and block_fallback are ignored with a warning and a count, so an old config still loads. - extract.Ask composes the question from lists, so #490 and #485 can add theirs. An output in two lists is judged once. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
amiddavid
added a commit
that referenced
this pull request
Oct 13, 2026
…adow mode Part A of #404 (the cold path). The sweep asks its question in place of the keep-alive ping and holds the answer per thread. Nothing applies a held answer yet: it changes no request. - Ask at the ping, no timer of its own. The time-window trigger and pre_expiry_seconds are removed (the key is refused with the reason). - Ask with one candidate or more. min_inventory defaults to 1. - Hold per thread in the Store (cg:swh:, pinned), with tool_use_id and a SpanHash of the agent's message for each judged output, the judged length and the wait cause (#453). Stored only; nothing decides on it. - recheckHeld drops a verdict when the conversation is shorter, the output is gone or changed, a later turn referenced it (coref), or the agent expanded it. PR C calls it on the cold request. - shadow: true (off, in no preset) reports asked, proposed, still valid at the cold request, and the reasons, as request_components events and a cg.sweep.shadow log line. - evidence is on by default. - Plain ping, counted as sweep_model_declined, where the question breaks the cache (#422). - Ask only when shadow is on, until the cold apply exists (PR C). Counted as sweep_ask_needs_shadow. - Remove econ_trigger, the in-request ask and the full-price fallback. The keys econ_trigger, econ_ignore_ask_cost, reward_premium, min_pressure and block_fallback are ignored with a warning and a count, so an old config still loads. - extract.Ask composes the question from lists, so #490 and #485 can add theirs. An output in two lists is judged once. - Recover from a panic in the ping question: the ping stays plain, the panic is counted, and the next ping is plain too. Check the concurrency bound before collecting candidates. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
amiddavid
added a commit
that referenced
this pull request
Oct 25, 2026
…adow mode Part A of #404 (the cold path). The sweep asks its question in place of the keep-alive ping and holds the answer per thread. Nothing applies a held answer yet: it changes no request. - Ask at the ping, no timer of its own. The time-window trigger and pre_expiry_seconds are removed (the key is refused with the reason). - Ask with one candidate or more. min_inventory defaults to 1. - Hold per thread in the Store (cg:swh:, pinned), with tool_use_id and a SpanHash of the agent's message for each judged output, the judged length and the wait cause (#453). Stored only; nothing decides on it. - recheckHeld drops a verdict when the conversation is shorter, the output is gone or changed, a later turn referenced it (coref), or the agent expanded it. PR C calls it on the cold request. - shadow: true (off, in no preset) reports asked, proposed, still valid at the cold request, and the reasons, as request_components events and a cg.sweep.shadow log line. - evidence is on by default. - Plain ping, counted as sweep_model_declined, where the question breaks the cache (#422). - Ask only when shadow is on, until the cold apply exists (PR C). Counted as sweep_ask_needs_shadow. - Remove econ_trigger, the in-request ask and the full-price fallback. The keys econ_trigger, econ_ignore_ask_cost, reward_premium, min_pressure and block_fallback are ignored with a warning and a count, so an old config still loads. - extract.Ask composes the question from lists, so #490 and #485 can add theirs. An output in two lists is judged once. - Recover from a panic in the ping question: the ping stays plain, the panic is counted, and the next ping is plain too. Check the concurrency bound before collecting candidates. - Rebased onto #507. Point 11 now uses askStripsThinkingShipped. The keeper changes live in package keepalive (main moved the keeper there); the wait cause reaches it through Options.OpenTasks and Record.ToolUseNames. The question is framed with the shared opening line (resolveAsk.Frame) and asked through AskCovered when the asker supports it. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
amiddavid
added a commit
that referenced
this pull request
Oct 25, 2026
…adow mode Part A of #404 (the cold path). The sweep asks its question in place of the keep-alive ping and holds the answer per thread. Nothing applies a held answer yet: it changes no request. - Ask at the ping, no timer of its own. The time-window trigger and pre_expiry_seconds are removed (the key is refused with the reason). - Ask with one candidate or more. min_inventory defaults to 1. - Hold per thread in the Store (cg:swh:, pinned), with tool_use_id and a SpanHash of the agent's message for each judged output, the judged length and the wait cause (#453). Stored only; nothing decides on it. - recheckHeld drops a verdict when the conversation is shorter, the output is gone or changed, a later turn referenced it (coref), or the agent expanded it. PR C calls it on the cold request. - shadow: true (off, in no preset) reports asked, proposed, still valid at the cold request, and the reasons, as request_components events and a cg.sweep.shadow log line. - evidence is on by default. - Plain ping, counted as sweep_model_declined, where the question breaks the cache (#422). - Ask only when shadow is on, until the cold apply exists (PR C). Counted as sweep_ask_needs_shadow. - Remove econ_trigger, the in-request ask and the full-price fallback. The keys econ_trigger, econ_ignore_ask_cost, reward_premium, min_pressure and block_fallback are ignored with a warning and a count, so an old config still loads. - extract.Ask composes the question from lists, so #490 and #485 can add theirs. An output in two lists is judged once. - Recover from a panic in the ping question: the ping stays plain, the panic is counted, and the next ping is plain too. Check the concurrency bound before collecting candidates. - Rebased onto #507. Point 11 now uses askStripsThinkingShipped. The keeper changes live in package keepalive (main moved the keeper there); the wait cause reaches it through Options.OpenTasks and Record.ToolUseNames. The question is framed with the shared opening line (resolveAsk.Frame) and asked through AskCovered when the asker supports it. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
amiddavid
added a commit
that referenced
this pull request
Oct 25, 2026
…adow mode Part A of #404 (the cold path). The sweep asks its question in place of the keep-alive ping and holds the answer per thread. Nothing applies a held answer yet: it changes no request. - Ask at the ping, no timer of its own. The time-window trigger and pre_expiry_seconds are removed (the key is refused with the reason). - Ask with one candidate or more. min_inventory defaults to 1. - Hold per thread in the Store (cg:swh:, pinned), with tool_use_id and a SpanHash of the agent's message for each judged output, the judged length and the wait cause (#453). Stored only; nothing decides on it. - recheckHeld drops a verdict when the conversation is shorter, the output is gone or changed, a later turn referenced it (coref), or the agent expanded it. PR C calls it on the cold request. - shadow: true (off, in no preset) reports asked, proposed, still valid at the cold request, and the reasons, as request_components events and a cg.sweep.shadow log line. - evidence is on by default. - Plain ping, counted as sweep_model_declined, where the question breaks the cache (#422). - Ask only when shadow is on, until the cold apply exists (PR C). Counted as sweep_ask_needs_shadow. - Remove econ_trigger, the in-request ask and the full-price fallback. The keys econ_trigger, econ_ignore_ask_cost, reward_premium, min_pressure and block_fallback are ignored with a warning and a count, so an old config still loads. - extract.Ask composes the question from lists, so #490 and #485 can add theirs. An output in two lists is judged once. - Recover from a panic in the ping question: the ping stays plain, the panic is counted, and the next ping is plain too. Check the concurrency bound before collecting candidates. - Rebased onto #507. Point 11 now uses askStripsThinkingShipped. The keeper changes live in package keepalive (main moved the keeper there); the wait cause reaches it through Options.OpenTasks and Record.ToolUseNames. The question is framed with the shared opening line (resolveAsk.Frame) and asked through AskCovered when the asker supports it. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
amiddavid
added a commit
that referenced
this pull request
Oct 25, 2026
…adow mode Part A of #404 (the cold path). The sweep asks its question in place of the keep-alive ping and holds the answer per thread. Nothing applies a held answer yet: it changes no request. - Ask at the ping, no timer of its own. The time-window trigger and pre_expiry_seconds are removed (the key is refused with the reason). - Ask with one candidate or more. min_inventory defaults to 1. - Hold per thread in the Store (cg:swh:, pinned), with tool_use_id and a SpanHash of the agent's message for each judged output, the judged length and the wait cause (#453). Stored only; nothing decides on it. - recheckHeld drops a verdict when the conversation is shorter, the output is gone or changed, a later turn referenced it (coref), or the agent expanded it. PR C calls it on the cold request. - shadow: true (off, in no preset) reports asked, proposed, still valid at the cold request, and the reasons, as request_components events and a cg.sweep.shadow log line. - evidence is on by default. - Plain ping, counted as sweep_model_declined, where the question breaks the cache (#422). - Ask only when shadow is on, until the cold apply exists (PR C). Counted as sweep_ask_needs_shadow. - Remove econ_trigger, the in-request ask and the full-price fallback. The keys econ_trigger, econ_ignore_ask_cost, reward_premium, min_pressure and block_fallback are ignored with a warning and a count, so an old config still loads. - extract.Ask composes the question from lists, so #490 and #485 can add theirs. An output in two lists is judged once. - Recover from a panic in the ping question: the ping stays plain, the panic is counted, and the next ping is plain too. Check the concurrency bound before collecting candidates. - Rebased onto #507. Point 11 now uses askStripsThinkingShipped. The keeper changes live in package keepalive (main moved the keeper there); the wait cause reaches it through Options.OpenTasks and Record.ToolUseNames. The question is framed with the shared opening line (resolveAsk.Frame) and asked through AskCovered when the asker supports it. - Review round 1: keep the conversation copies only for a thread the keep-alive can ping (Ctx.CanKeepAlive). Take the collection slot before collecting and release it on every exit. Count the result-cache miss in collect, and count sweep_concurrency_full. Report the shadow ask and the cold recheck once, under a mutex. Rewrite the sweep rows of docs/data-dependence.md and drop the stale counters and prose from advanced-offload.md. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
amiddavid
added a commit
that referenced
this pull request
Oct 25, 2026
…adow mode (#508) feat(sweep): ask at the keep-alive ping, hold the answer, recheck, shadow mode Part A of #404 (the cold path). The sweep asks its question in place of the keep-alive ping and holds the answer per thread. Nothing applies a held answer yet: it changes no request. - Ask at the ping, no timer of its own. The time-window trigger and pre_expiry_seconds are removed (the key is refused with the reason). - Ask with one candidate or more. min_inventory defaults to 1. - Hold per thread in the Store (cg:swh:, pinned), with tool_use_id and a SpanHash of the agent's message for each judged output, the judged length and the wait cause (#453). Stored only; nothing decides on it. - recheckHeld drops a verdict when the conversation is shorter, the output is gone or changed, a later turn referenced it (coref), or the agent expanded it. PR C calls it on the cold request. - shadow: true (off, in no preset) reports asked, proposed, still valid at the cold request, and the reasons, as request_components events and a cg.sweep.shadow log line. - evidence is on by default. - Plain ping, counted as sweep_model_declined, where the question breaks the cache (#422). - Ask only when shadow is on, until the cold apply exists (PR C). Counted as sweep_ask_needs_shadow. - Remove econ_trigger, the in-request ask and the full-price fallback. The keys econ_trigger, econ_ignore_ask_cost, reward_premium, min_pressure and block_fallback are ignored with a warning and a count, so an old config still loads. - extract.Ask composes the question from lists, so #490 and #485 can add theirs. An output in two lists is judged once. - Recover from a panic in the ping question: the ping stays plain, the panic is counted, and the next ping is plain too. Check the concurrency bound before collecting candidates. - Rebased onto #507. Point 11 now uses askStripsThinkingShipped. The keeper changes live in package keepalive (main moved the keeper there); the wait cause reaches it through Options.OpenTasks and Record.ToolUseNames. The question is framed with the shared opening line (resolveAsk.Frame) and asked through AskCovered when the asker supports it. - Review round 1: keep the conversation copies only for a thread the keep-alive can ping (Ctx.CanKeepAlive). Take the collection slot before collecting and release it on every exit. Count the result-cache miss in collect, and count sweep_concurrency_full. Report the shadow ask and the cold recheck once, under a mutex. Rewrite the sweep rows of docs/data-dependence.md and drop the stale counters and prose from advanced-offload.md. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]> docs(data-dependence): record David's approval of the sweep change (#508) The ping-time question and the held answer in cg:swh: (metadata only) are approved, with the two in-memory conversation copies per thread kept only while the keep-alive can ping the thread, for at most 256 threads and 30 minutes. Assisted-By: Claude Opus 5.5 Signed-off-by: DAVID AMID <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR adds the RECORD half of issue #424. The proxy now writes why each
thread waits and why it wakes up, on every request. It does not choose a
keep-alive ping budget. It does not change keep-alive or compaction
behaviour. The keep-alive still sends a fixed 2 pings per thread (PR #426).
Part of #424.
What changed
New package
internal/waitcause. It reads two things, by string match andstructural tool_use reads only — no LLM:
waiting_for: what a thread is about to wait on, set on the row whoseOWN response ends a turn. One of
own_tool(with the last tool's namekept in
wait_tool),human,background,teammate,retry,unknown.wake_cause: what ended a wait, set on the row that starts the nextturn. One of
tool_result,background,teammate,human,system,retry,unknown.open_background/open_teammate/monitor_expiry_ms: the openbackground-task count, open-teammate-wait count, and the latest known
Monitor expiry, as of that request's own body.
All six are new nullable columns on
requests(additive, no schema versionbump — same pattern as
thread_idandkeepalive_strategy_id). A row frombefore this feature existed reads NULL, not a guessed value.
waiting_forandwake_causeare also new dimensions of/api/breakdown,so a dashboard user can split cost and request count by them. No new panel.
No second body parser.
internal/waitcausebuilds its signals fromapply.NormalizeMessages(provider, orig)— the same normalization thecompaction pipeline itself already uses for all three providers the issue
names (Anthropic Messages, OpenAI chat, OpenAI Responses). Where a Claude
Code marker does not apply — another agent, another provider, a shape this
package does not recognise — the fields read "unknown", never a guess.
The open-task/open-teammate state survives the agent compacting its own
history. An item (a Monitor, a backgrounded Bash, a pending SendMessage)
stays "open" until its own finish signal, a
TaskStop, a stated Monitorexpiry, or a cap for one with none — never merely because its start marker
scrolled out of a since-compacted body.
Fails open. Every exported
waitcausefunction recovers internallyfrom a panic and returns the zero value. A bug here can only degrade this
data; it can never block, change, or slow the request.
Off the request path, entirely. The actual body rescan
(
waitcause.Tracker.Observe) never runs on the path that forwards therequest, and never runs inline in
finish()either — both were measuredto add real latency (see "A real latency regression" below). It runs as a
closure (
dash.Event.WaitCause) the dashboard's own WRITER goroutineinvokes right before the insert, the same place and for the same reason
Event.Redact()already runs there.How it was tested
Unit tests (
internal/waitcause,go test -race, all green): everyvalue of
waiting_forandwake_cause, on Anthropic Messages, OpenAI chatand OpenAI Responses bodies. Both teammate marker forms
(
<teammate-message>,<cross-session-message>). An async-agent/Skillfinish (
<agent-message from="X">) and a<task-notification>, both aswake_cause=background. A Monitor's mid-watch notice (not a finish) vs.its expired notice (a finish) vs. its own stated expiry elapsing with no
notice at all. A backgrounded Bash, an async agent, and an anonymous
backgrounded Skill launch (its real id lives only in a transcript field no
API body carries).
TaskStop. TheAskUserQuestion/ExitPlanModeexception, both for
waiting_forand for the baretool_resultthatanswers them. The retry rule (same thread, non-200 previous status, same
message count) and its two negatives (success, or a grown conversation).
An item surviving a compacted body with no start marker (fix 6, see
below). A trailing
role:"system"noise entry hiding the real signalbehind it (found live — see "A real defect" below), for all three cases
(tool_result, human, the
AskUserQuestionexception). The full teammatelifecycle in one test — own_tool/SendMessage opens the wait,
waiting_for=teammate once the turn ends with nothing else to do, and a
<teammate-message>reply gives wake_cause=teammate and closesopen_teammate back to 0
(
TestTeammateReplyClosesAnOpenWaitAndWakesTheThread). A sibling blockbeside a tool_result in the same wire message (#457/#460, see "Open
questions"): mid-turn user text gives human, a
<task-notification>sibling gives background, and a
<system-reminder>-only sibling doesNOT give human. Fail-open on a malformed body and on a nil tracker.
Added latency (
BenchmarkObserveLargeBody, on the eval box): ~11ms for a 783 KB body (2,000 turn pairs) — the full per-request rescan.
This is real work, which is exactly why it does NOT run on the request
path or in
finish()— see the two latency fixes below.go test -race -count=1oninternal/waitcause,apply,proxy,dash,cmd/...on the eval box: all green, no cache. The existingkeep-alive tests pass unchanged (
-run 'KeepAlive|Keepalive|Keeper'),and
TestDashboardAddsNoRequestLatencyWithContentCapture(the test thatcaught the first latency regression — see below) now passes with ~1 ms
added, well inside budget. Also ran, specifically, the tests this
package's new dependency on
apply.NormalizeMessagestouches:TestXHighPresetCommitsACacheAwareSummary,TestCacheAwarePipelineOrderMinimalTextCleanCase,TestSweepGuardUsesRawCoordinatesNotPipelinePosition,TestCacheAwareStalePrefixThroughARealOversizedTurn, andapply'sTestResponsesSetsRawInputBeforeThePipelineRewrites— none dropped to 0summary/ask calls.
Live traffic during development (not a release gate for this PR).
Per policy, an individual PR does not carry its own live test; a merged-
main integration check covers that, run separately. Before that policy
was set for this PR, a proxy built from this branch — pointed at the real
provider gateway, not Context Guru — drove a real Claude Code session
through it in a scratch config, specifically to shake out shapes a unit
test would not have thought to write. It found both real defects below.
That exploration is also why
waiting_for=teammate's CLOSE path(a genuine
<teammate-message>reply) is unit-tested here(
TestTeammateReplyClosesAnOpenWaitAndWakesTheThread, covering the wholeopen → waiting_for=teammate → wake_cause=teammate → closed lifecycle in
one test) rather than claimed from a live run: this environment's actual
backgrounded-Agent hand-back turned out to use a DIFFERENT signal
(
<agent-message from="X">, see the first defect below) than theagent-team
<teammate-message>tag the issue's own design was writtenagainst, and reaching a genuine peer-session
<teammate-message>closelive would need a fuller agent-team setup than a scratch sandbox gives
cheaply. The live teammate-reply CLOSE case is checked in the
merged-main integration run, not here.
A real defect, found live, not assumed in advance — and fixed. A
backgrounded Agent's hand-back wakes the thread with ONLY an
<agent-message from="X">...</agent-message>tag (plus the harness's ownboilerplate) — no
<task-notification>, no plain text.classifyWakehadno case for this tag at all, so it fell through to "plain text" and
reported
wake_cause=humaninstead ofbackground. Fixed by reusing thesame
<agent-message from="X">pattern already used to CLOSE an openbackground task, now also as a
wake_cause=backgroundsignal — confirmedfixed live (re-ran the identical scenario; the row that read
humanbefore now reads
background), with a regression test(
TestObserveWakeCauseAgentMessageIsBackground).A second real defect, found earlier in the same live test, also
fixed. This org's Claude Code build appends a bare
{"role":"system","content":"<total_tokens>...tokens left</total_tokens>"}entry after every turn, including right after the real tool_result or
human text that is the actual wake signal — confirmed by
schema.SessionHead's own doc comment in this repo, which names theClaude Agent SDK as the source. The first version of
classifyWakereadonly the last message and misread the Bash-finishing wait as
wake_cause=human. Fixed by skipping trailingrole=="system"entriesstructurally (
isNoiseEntry) rather than guessing from content — the roleitself is a stronger signal than a
<system-reminder>string match.Confirmed fixed live and covered by regression tests.
Open questions
apply.NormalizeMessages(
apply.normalize's Anthropic branch dropped any OTHER content blocksitting beside a
tool_resultin the same user message — mid-turnuser text, a system-reminder, a task notification) got its own issue
and PR, per this repo's rule that a defect on
mainaffecting everycomponent does not ride a feature branch: apply.normalize drops text blocks that share a user message with a tool_result #457, fixed by fix(apply): keep sibling text blocks beside a tool_result in the normalized view #460
(
fix/normalizer-siblings), now merged tomainand rebased ontohere.
apply.normalizenow keeps the sibling as its own syntheticrole=usermessage, in wire order — this PR's own pinning test(
apply/normalize_siblingblock_test.go, which asserted the OLD,dropped behaviour) is deleted rather than flipped: fix(apply): keep sibling text blocks beside a tool_result in the normalized view #460's own
apply/normalizer_siblings_test.goalready covers the normalizerdirectly.
internal/waitcausegets three new tests instead, for whatTHIS package needs to get right now that the sibling reaches it: a
tool_result plus mid-turn user text gives
wake_cause=human, atool_result plus a
<task-notification>sibling giveswake_cause=background, and a sibling that is ONLY a<system-reminder>block does NOT read as human — the syntheticsibling message is always
role=user(neverrole=system), soisNoiseEntry's role check does not catch it;classifyWake'scontent-based
hasSystemMarkercheck already does, independent ofrole, and that is what these new tests pin.
responseToolUseNames, new fieldon
Usage) is best-effort on a streamed response: it reads whatever thesniffer's bounded head+tail window holds (see
newSniffer), so atool_use far into a very long streamed response can fall outside it. That
under-reports
own_tool; it never invents one.with no stated expiry, and the per-thread persistent state are all new,
small, in-memory-only (never persisted, never logged — no names, no task
ids, only counts and labels reach the database). Bounded the same crude
way
internal/threadbounds its own maps, but has not run under thekind of long-lived-thread load that package has.
in a transcript's own
toolUseResult.agentId), so it is trackedanonymously (oldest-matches-first, now persistent across compaction
too). This is the same imprecise, documented choice
scripts/analysis/wait_causes.py(feat(analysis): add wait-cause and ping-budget analysis script #425) makes for the same case.Agentteammate's hand-back (seen during development)is not the same code path the issue's own
<teammate-message>/SendMessagedesign was written against (that is a peer Claudesession, not a backgrounded subagent) — see the first defect above.
waiting_for=teammateand theSendMessage-open path are unit-testedhere; the live, merged-main integration run is where a genuine peer-
session
<teammate-message>close gets checked end to end.Technical notes
open-teammate counts: the body already carries the whole conversation,
so a fresh scan is self-correcting from anything an earlier request
missed (a restart, a dropped event) where incremental state would stay
wrong forever. What DOES persist across requests, per thread: the
open-background/open-teammate sets themselves (fix 6, so compaction
can't silently close them), a small map from a stable id to the
wall-clock time this process first saw it open (needed because the body
itself carries no timestamps at all), a bounded set of already-applied
close signals (so replaying the same historical signal — every request
resends the whole conversation — can't repeatedly pop an unrelated
anonymous Skill entry), and the previous request's status and message
count, for the retry rule.
teammate/cross-session message tags, background Bash/async-agent/Skill
start text,
<agent-message from="X">) are exactlyscripts/analysis/wait_causes.py's (feat(analysis): add wait-cause and ping-budget analysis script #425), verified there against realClaude Code transcripts, plus the two fixes this PR's own live test
found (the
<agent-message>wake and therole:"system"noise entry).The proxy sees the API request body, not a transcript, so there is no
isMetaflag: system-injected text is told apart by content(
<system-reminder,Base directory for this skill:, …) for auser-role entry, and structurally (the role itself) for a barerole: "system"entry.Usage.ToolUseNamesis new, filled at the same pointUsage.StopReasonalready is (
responseStopReason), off the same buffered/sniffed bytes,for Anthropic Messages (buffered and streamed
content_block_start),OpenAI chat (buffered
tool_callsand streameddelta.tool_calls), andOpenAI Responses (buffered
output[].function_call).request path, and not inline in
finish(). First version: the scanran inline in
finish(), which runs on the handler's own defer, BEFOREthe handler returns — so it delayed the NEXT request on a keep-alive
connection by exactly the scan's own cost, which
TestDashboardAddsNoRequestLatencyWithContentCapturecaught (added~97ms against a ~34ms budget). Fixed by building a closure around
everything the scan needs and handing it to
dash.Event.WaitCause,invoked by the writer right beside
Event.Redact()for the identicalreason.
Tracker.RecordOutcome(this request's own status/messagecount, for the next request's retry check) is folded into the same
closure so it still runs strictly after
Observereads the previousstate, in the writer's own FIFO order — the one trade-off is that a row
DROPPED under a full capture channel also skips
RecordOutcomefor it,which can miss a retry label; fail-open, same as everywhere else here.
proxy/keepalive_test.go: one test'su == (Usage{})struct-equalitycheck stopped compiling once
Usagegained a slice field; changed to anequivalent field-by-field zero check, no behaviour change.
by a special-case check: a ping's
dash.Eventis built entirely indashEmitter.KeepAlivePing(cmd/context-guru-proxy), which never setsEvent.WaitCause— there is no*waitcause.Trackerreference anywhereon that path for either a plain ping (
record1) or thecache_aware_summarizer's keep-alive-substitute ping (feat(offload): give cache_aware_summarizer a real trigger and feed the keep-alive #402,recordSummarySubstitute), both of which reach the identicalKeepAlivePingcall. Pinned byTestDashEmitterKeepAlivePingCarriesNoWaitCauseandTestDashEmitterSummarySubstitutePingCarriesNoWaitCause.🤖 Generated with Claude Code