Skip to content

Leave Slack thread replies alone when they open by mentioning someone else - #86

Open
josephschorr wants to merge 10 commits into
mainfrom
slack-skip-replies-addressed-elsewhere
Open

josephschorr wants to merge 10 commits into
mainfrom
slack-skip-replies-addressed-elsewhere

Conversation

@josephschorr

@josephschorr josephschorr commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

In a Slack thread the agent was brought into directly, every reply is sent to the agent, with no mention needed. That included replies one person wrote to another: "@bob can you take this one?" got a response from the agent.

A thread reply that opens by @-mentioning someone other than the agent is now left alone: the agent does not take a turn on it. The next time someone addresses the agent in that thread, the skipped replies are shown to it as background, marked as conversation between other people that it should use only if asked about it.

What still reaches the agent as a message of its own:

  • A reply that mentions the agent anywhere, including one that opens with someone else's mention.
  • A reply that mentions another person later in the message ("loop in @bob on this").
  • A reply that opens with a group or channel-wide mention (@oncall, @here).
  • A message from another agent, where the agent is set up to take part in threads alongside other agents. Only a person's reply is ever left alone; where the agent is not set up that way, other agents' messages are ignored as before and are not shown as background either.

Things to know:

  • The agent is told not to reply to or act on that background. That is an instruction to the agent, not a guarantee.
  • Only the text of a skipped reply is carried, not its attachments.
  • A skipped reply stays in the thread, so the agent can still come across it if it reads the thread's history itself.
  • The background is fetched only when something was skipped, so a thread with no such replies costs nothing extra.
  • Replies skipped after the agent's session has finished are kept too. When someone next addresses the agent and the thread continues in a new session, they are shown ahead of that message, so the agent has them before it answers.
  • The exception is a thread picked up by someone else after the previous session was stopped for a policy or security reason. That new session deliberately starts with none of the earlier history, and it gets no background either.
  • In a very long thread, the skipped replies can arrive over more than one message rather than all at once. None are dropped.
  • A reply is judged by its text when the background is fetched. One edited after it was posted can therefore be shown twice, or not at all, if the edit added or removed the opening mention.
  • Direct messages and threads that already require a mention are unchanged.

Testing

Unit tests cover each case above through the Slack listener, the thread-history reader and the inbound pipeline: a skipped reply starts no turn, another agent's message is never skipped or shown as background, the next message to the agent carries exactly the skipped replies ahead of itself, and a failure to fetch them still delivers the message and retries on the following one. They also cover a thread too long to fetch in one go, replies skipped after a session has finished (for the same person continuing and for someone else taking over), and a session being tested alongside the thread's own. A further test runs the round trip against a real API server, with several skipped replies arriving at once. The new tests fail without the change.

In a thread the agent was brought into directly, every plain reply is
routed to it. A reply that opens by @-mentioning another person is one
person talking to another, and the agent took a turn on it anyway.

The listener now drops a thread reply whose text starts with a mention of
a user other than the agent. A reply that mentions the agent anywhere still
arrives through the app_mention path, and a mention later in the message
does not count. With the agent's own id unknown, nothing is dropped.
@vercel

vercel Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated
openagentprimitives Ignored Ignored Preview Dec 4, 2026 7:00pm UTC

Request Review

A thread reply that opens by @-mentioning someone other than the agent was
dropped by the listener, so the agent never saw it, even as context when a
later message asked about it.

The listener now hands such a reply to the pipeline as an aside. The
pipeline starts no turn for it: nothing is appended, published or stamped,
no permission is checked and no session is created or continued. It only
records on the thread's active session the cursor of the earliest aside
not yet seeded.

The next message addressed to the agent reads the thread from that cursor,
keeps the messages the kind marks as asides, and seeds them as one turn
ahead of itself, framed as conversation between other people to use only
if asked. A mention-only thread is unchanged: its existing catch-up
already carries every message it was not sent.

The Slack history reader marks asides with the listener's own rule, and
resolves the bot's id the way the listener does, so the two agree on which
replies were withheld.
A session that noted asides and then ended before anyone addressed the
agent again took its cursor with it, so the continuation never showed
them. The fork now copies the cursor when the child resumes the same
thread (an inherit continuation or a takeover). A restart-from-here
branches into a new thread, where the cursor would name messages that
are not in it, so it is not carried there.
@josephschorr
josephschorr requested a review from samkim December 1, 2026 20:47

@samkim samkim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This PR makes the Slack listener skip thread replies that open by @-mentioning someone other than the agent, so the agent no longer takes a turn on a message one person wrote to another. The core behavior works and the new unit tests pass.

Verdict: ready after the inline fixes.

Issues:

  1. Major: with cross-agent participation on, another agent's message that opens with a human or peer mention is also dropped, so the receiving agent loses that context. See inline.
  2. Minor: the agent's own mention in the <@BOT|label> form is treated as someone else's and dropped, with a misleading log line. See inline.
  3. Minor: the code comment says a dropped reply is never visible later, but thread-history readers can still return it. See inline.

Questions for the author:

  1. When a person answers the agent's question with a leading mention (for example <@U_ALICE> go with B), the agent never sees it. Is that accepted, or should such replies be appended without waking the agent?
  2. Should this routing change be configurable per Channel or AgentClass, since it changes behavior for every existing Slack install?

Drafted by an automated review pipeline and checked before submission.

…belled mention

A thread reply that opens by mentioning someone else is held back as an aside
only when a person wrote it. Another agent's message is delivered as an
ordinary one whenever cross-agent participation admits it, including a report
that opens by naming the person it answers: that feature's contract is that an
admitted message always reaches the session, and only the wake is bounded.

The thread-history reader now marks as an aside exactly what the listener would
have handed over as one. It replays the listener's subtype gate and sender
classification before applying the shared rule, so a bot's post that opens with
a user mention is no longer seeded as background, whether or not cross-agent
participation is on.

The agent's own mention is recognised in both forms Slack writes it, `<@U…>`
and `<@U…|label>`. A reply opening with the labelled form was classified as
addressed to someone else; it is now left to the app_mention event like any
other mention of the agent, and counts toward the missing-subscription hint.
@josephschorr

Copy link
Copy Markdown
Member Author

The review was written against the first commit, and three later commits changed what happens to a skipped reply: it is no longer dropped, it is recorded and shown to the agent as background on the next message addressed to it in that thread. The three inline findings are answered in their threads; 8b89e58 has the fixes.

On the two questions:

  1. A reply like <@U_ALICE> go with B is no longer lost: it is shown to the agent as background, marked as conversation between other people, the next time someone addresses it. The agent still does not take a turn on it, so it does not act on that answer until it is addressed.
  2. This is not configurable in this PR, per Channel or per AgentClass; it applies to every thread the agent was brought into directly. Whether it should become a setting is a product decision that has not been made here.

@josephschorr
josephschorr requested a review from samkim December 2, 2026 19:36

@samkim samkim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What this round checked. Round 2, four commits since 333be701 (a4422d7a..8b89e58f). All three earlier threads are verified, 3 of 3. The PR no longer drops a leading-mention reply: it records it as an "aside" and shows it to the agent as background on the next message addressed to it. That scope is new in this round, so it was reviewed as new code.

Verdict: ready after the inline fixes. The listener, pipeline and Slack reader hang together and the targeted tests pass (go test on the slack, pipeline and agentsession packages, filtered to the aside and history tests). The remaining issues are about asides being lost or arriving late at edges; none breaks the normal path.

Issues, highest impact first

  1. Asides posted after a session has ended are ignored, but the next message forks and continues the same thread, so those asides never reach the child. See inline, asides.go:71.
  2. For an inherit or takeover fork, the carried cursor only takes effect on the child's second message, so the agent answers the forking message before it has the asides. See inline, restart_decide.go:167.
  3. If Slack has no botUserId recorded and auth.test fails once, the read marks no asides and the pipeline clears the marker, so they are lost silently. See inline, slack/history.go:96.
  4. catchUpAsides reads one page, ignores HasMore, and clears the marker. Asides beyond the first page are lost if the thread is long. See inline, asides.go:208 (not reproduced; needs the page size check).
  5. Smaller points: a policy-halt takeover still carries the cursor into the deliberately fresh child (restart_decide.go:168); edited replies can be marked differently than the listener judged them, and the "cannot disagree" comment overclaims (slack/history.go:241); asides during a live attended child stay on the root (pipeline.go:1048); noteAside skips the Channel re-fetch and re-reads transcripts per aside (asides.go:66).

Questions for the author

  1. When a message forks a new session in the same thread (inherit or takeover), should the asides be in front of the agent before it answers the forking message? Today they arrive on the next message. Options are to seed them at fork time, or to accept and document the delay. See inline, restart_decide.go:167.
  2. Should an aside that arrives while an attended delegation child is live be shown to that child, or is it intended to wait for the root?

Not anchored to a diff line: none.

Round-1 questions are answered by the author's changes (the leading-mention reply is carried as background; making it configurable is out of scope for this PR).

This review was drafted by an automated pipeline and checked before submission.

return
}

page, err := p.ReadHistory(ctx, ev.Channel, ev.ChannelKey, channelkinds.ReadHistoryOpts{

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[minor] catchUpAsides reads one history page, ignores HasMore, then clears the marker

Problem: p.ReadHistory is called once and page.HasMore is never looked at (the Slack reader returns it from conversations.replies, pkg/channels/channelkinds/slack/history.go:68). The marker is then cleared unconditionally (asides.go:242). If the thread has more replies after the first aside than one page holds (Slack caps page size for some app types), the asides on later pages are never seeded and the cursor that named them is gone. This is silent loss, the case the function's own comment says it avoids ("biased toward seeding twice rather than never"). Existing catchUp (backfill.go:435) has the same single read, but it advances to the trigger ts and does not clear a cursor naming an unseeded message, so the new code is worse.
Verify: confirm what page size GetConversationRepliesContext returns with Limit: 0 for the bound app, and that Slack returns the OLDEST replies first (so HasMore means later asides were cut off). If the page is always large enough in practice, downgrade to a comment.
Fix: if page.HasMore, either loop on the reader's cursor until exhausted (add cursor support to ReadHistoryOpts if the Slack reader lacks it for replies), or seed what was read and move the marker to the first unread aside's ts (the last returned message ts) instead of clearing it. Do not clear when HasMore is true.
Test: in pkg/channels/channelsd/pipeline/asides_test.go add TestDeliver_AsideCatchUpKeepsMarkerWhenHistoryHasMore with a fake ReadHistory returning HasMore: true; assert the marker is not removed (or advanced). Run go test ./pkg/channels/channelsd/pipeline/ -run Aside.
Constraints: AGENTS.md "Never silently drop errors" (a dropped page is a silent loss; log at INFO at minimum).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The catch-up now follows the reader's cursor until HasMore is false, bounded at 10 pages or 1000 messages (0125e43; the Slack reader passes the cursor through in a20c93b). If it stops early (a bound, a failed later page, or HasMore with no cursor) it seeds what it read and moves the marker to the newest message read instead of clearing it, holding that one message back so the next read seeds it exactly once. I did not verify Slack's page size for the bound app; the fix does not depend on it.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified at 0125e43b: readAsideWindow follows NextCursor until HasMore is false, bounded by maxAsidePages/maxAsideMessages (pipeline/asides.go:348-434). An early stop seeds what was read, holds back the newest message, and catchUpAsides moves the marker to it instead of clearing (:324-332). The Slack reader passes Cursor through (slack/history.go:57-75). TestDeliver_AsideCatchUpReadsEveryPage and TestReadHistory_PagesByCursor cover it.

if err != nil {
return channelkinds.InboundDecision{Outcome: channelkinds.OutcomeInternalError}, err
}
active, _, _ := p.classifyCorrelated(ctx, &sessions)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[minor] An aside posted after the session ended is ignored, but the next message forks and continues the same thread

Problem: noteAside returns early when classifyCorrelated finds no active session (asides.go:71-75). But the next message to the agent in that thread forks via the inherit/takeover path (pipeline.go:1405, writeInheritForkTrigger), and restart_decide.go:167 carries the parent's AnnotationAsidesSinceTS into the child for exactly that reason. The carried marker only exists if an aside was noted BEFORE the parent ended. Scenario: session completes with no marker, Alice and Bob trade two asides, Sam asks the agent "who took it?", the child is created with no marker and never sees them. Asides before the end are carried; asides after it are lost.
Fix: use the second return of classifyCorrelated (archived, with its disposition). When active == nil and archived would be continued in the same thread (disposition DispNewInheriting, or the takeover case at pipeline.go:1289), call p.markAsidesSince(ctx, client.ObjectKeyFromObject(archived), ts) and return OutcomeAside. Do not mark a parent that a restart-from-here would branch away from (restart_decide.go:167 already drops the cursor there). Check this together with the design question in the review body about when asides reach the child.
Test: in asides_test.go add TestDeliver_AsideAfterSessionEndMarksTheArchivedParent (Completed parent, aside, assert marker on the parent) and a BuildChildSession round trip. Run go test ./pkg/channels/channelsd/pipeline/ -run Aside.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

An aside with no active session is now noted on the conversation's most recent finished session, the one the next message forks from (0125e43). It is skipped for a held session and for one ended by a policy halt, since nothing continues those with their history. TestDeliver_AsidesAfterASessionEndsAreSeededAheadOfTheFork covers the scenario you describe, for inherit and takeover.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified at 0125e43b: with no active session noteAside marks the newest finished session, skipping held and policy-halted ones (pipeline/asides.go:102-119), and the fork path seeds before the trigger (pipeline.go:1309-1311, :1426). TestDeliver_AsidesAfterASessionEndsAreSeededAheadOfTheFork covers inherit and takeover. See the new inline comment on seedAsidesBeforeFork for one side effect of this seeding.

"channel", channelRefForLog(ev.Channel), "channelKey", ev.ChannelKey)
return ignored, nil
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[nit] noteAside correlates before Deliver's Channel re-fetch, and runs the per-session transcript read on every aside

Problem: Deliver re-Gets the Channel at pipeline.go:~687 so an in-place spec.agentClass patch takes effect. noteAside returns before that, so correlateSessions (pipeline.go:~540, the output-key fallback filter on ev.Channel.Spec.AgentClass) uses the listener's cached spec, and a cron-spawned thread can resolve to no session or the wrong one. classifyCorrelated also does Memory.ReadAll for every archived-by-sweep session on every aside, which the aside path is meant to keep cheap.
Fix: lift the Channel re-Get at pipeline.go:~687 into a small helper and call it at the top of noteAside. Optionally skip classifyCorrelated's transcript read here by only needing "is there a session a runner will serve" (an archived-by-sweep session with a transcript can be treated as a hit without reading it twice).
Test: extend TestDeliver_AsideStartsNoTurn (asides_test.go:79) with a cron-spawned session found by output key after a class patch. Run go test ./pkg/channels/channelsd/pipeline/ -run Aside.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

noteAside now re-reads the Channel before correlating, through the same helper Deliver uses, and classifies without any transcript read (0125e43). A session archived by the sweep is taken as resumable there: whether it is resumed or forked, it is the session the next message goes through, so the marker lands on the same one either way. The cron-spawned case after a class patch is TestDeliver_AsideCorrelatesAgainstTheCurrentChannelSpec.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified at 0125e43b: noteAside re-reads the Channel through freshChannel (pipeline/asides.go:97) and classifies with sweptResumable = true, so no transcript read (:102). TestDeliver_AsideCorrelatesAgainstTheCurrentChannelSpec covers the class-patch case.

if mentionOnly(active) {
p.catchUp(ctx, active, ev)
} else if active.Annotations[spiceboxv1alpha1.AnnotationAsidesSinceTS] != "" {
p.catchUpAsides(ctx, active, ev)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[nit] Asides noted while an attended child is live stay on the root and never reach the child

Problem: noteAside deliberately does not follow the attended-child redirect (asides.go doc, "the marker waits on the thread's own session"). While the attended child is live and the human converses with it, an aside is marked on the root and catchUpAsides runs only for active, which is the child after the redirect at pipeline.go:~770. The child's agent never sees the asides during its life, and they surface on the root only when the root next takes a turn, possibly long after.
Verify: confirm the root's marker is ever consumed while the child is live (the root only watches, per attended_watch.go).
Fix: if the marker should follow the conversation, mark the live attended child (liveAttendedChildOf) in noteAside (an aside carries no human subject, so the !nonHumanSubject guard at pipeline.go:~766 does not apply); otherwise state this limit in the noteAside doc comment so it is a recorded decision.
Test: in asides_test.go add a case with a live attended child. Run go test ./pkg/channels/channelsd/pipeline/ -run Aside.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

An aside is now noted on the live attended child as well as on the thread's own session (0125e43), so the child is shown it ahead of the next message redirected to it. The root keeps its own marker because it has not seen the asides either, and the child's seeded turn is not mirrored to it, so nothing is delivered twice. If the child cannot be resolved the root is still marked and the miss is logged.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified at 0125e43b: noteAsideOnAttendedChild marks the live attended child via liveAttendedChildOf (pipeline/asides.go:148-181), and the redirected message runs catchUpAsides on the child (pipeline.go:1058-1062). TestDeliver_AsideDuringALiveAttendedChildReachesTheChild covers it.

// owns it, so the cursor is carried and the child seeds them as background
// on its next inbound. A branching fork starts a new thread, where the
// parent's cursor names messages that are not in it.
if v := parent.Annotations[spiceboxv1alpha1.AnnotationAsidesSinceTS]; v != "" && !branchesThread {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[minor] The carried aside cursor takes effect one turn late, after the agent has answered the forking message

Problem: for an inherit or takeover fork the forking message is PendingRestart.NewUserText, which CopyMemoryPrefix appends as the child's first turn (restart.go:~594). It never passes through Deliver, so catchUpAsides (pipeline.go:1048) does not run for it. The child's cursor first takes effect on the child's SECOND inbound. If the forking message is "who took it?" about the asides, the agent answers without them and receives them afterwards.
Fix (pick one per the author's answer to question 1 in the review body; if unanswered, do (c)): (a) when Deliver writes the fork trigger (pipeline.go:~1405 and :1289), read the asides and prepend them to NewUserText or seed them into the child scope before the new turn; (b) seed them in ReconcileRestart before CopyMemoryPrefix appends NewUserText; (c) accept the one-turn delay and document it at this line. Option (a) or (b) means moving the history read to the fork path.
Test: whichever option is chosen, add a case where the first child turn must be preceded by the aside background, in restart_decide_test.go or asides_test.go. Run go test ./pkg/controllers/agentsession/ ./pkg/channels/channelsd/pipeline/.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Went with seeding at fork time, a variant of your (a): when Deliver is about to write an inherit or history-carrying takeover trigger, it runs the aside catch-up against the finished session first, so the background turn is in the transcript the operator copies and sits ahead of NewUserText (0125e43). The marker and its signature are untouched and no CRD field was added. The cursor carry stays as the fallback for whatever that could not seed (a failed read, the tail of a long thread, a fork already pending), which still arrives one message late.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified at 0125e43b (fixed differently, your variant of option a): seedAsidesBeforeFork (pipeline/asides.go:463-473) appends the background to the parent before both fork triggers (pipeline.go:1309-1311, :1426), so the operator's copy carries it ahead of NewUserText. It is skipped when a PendingRestart already exists. TestReconcileRestart_BackgroundAppendedBeforeTheForkPrecedesTheNewMessage shows the order. One side effect is raised in a new inline comment on seedAsidesBeforeFork.

// listener ignored it, and marking it here would show the agent a bot it was
// configured not to hear. Either way the answer does not depend on the setting,
// which is why this reader does not need to know it.
func handedOverAsAside(m slackapi.Message, selfBotUserID string) bool {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[nit] handedOverAsAside judges the message's current (possibly edited) text, and the comment says the listener and reader "cannot disagree"

Problem: the listener judged the text as first posted and ignores message_changed (routesMessageSubType, listener.go:1251). conversations.replies returns the CURRENT text. A reply edited to add a leading mention was delivered to the agent live and is marked an aside here, so it is seeded a second time. A reply edited to remove the leading mention was withheld live and is not marked here, so it is never seen. The comment at :231 overclaims.
Fix: reword the comment at :231 to name the edit case (accepted: duplicate background is the stated direction) and leave behaviour alone, unless Slack's edited field is set on the message, in which case treat the message as not-an-aside only for the first (duplicate) direction by skipping marking when m.Edited != nil.
Test: in history_test.go add TestHistory_EditedReplyAsideMarking documenting whichever behaviour is chosen. Run go test ./pkg/channels/channelkinds/slack/ -run History.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Reworded the comment to state the real guarantee and both edit directions (a20c93b); HistoryMessage.Aside says the same. I left behaviour alone rather than skip marking when Edited is set: that would permanently withhold any aside whose author only fixed a typo, which trades a duplicate for a loss. TestReadHistory_JudgesAnEditedReplyByItsCurrentText documents it.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified at 0125e43b: the comments at channelkinds/history.go:93-99 and slack/history.go state both edit directions. Keeping the behaviour is the right call: skipping an edited reply would turn a typo fix into a permanent loss. TestReadHistory_JudgesAnEditedReplyByItsCurrentText documents it.

return deps.Channel.Spec.Slack.BotUserID
resp, err := at.AuthTestContext(ctx)
if err != nil {
log.FromContext(ctx).Info("slack: auth.test failed; this read cannot tell the bot's own messages, or replies addressed to others, apart",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[minor] A transient auth.test failure makes the read mark no asides, and the pipeline then clears the marker

Problem: when the Channel records no botUserId, selfBotUserID calls auth.test on every read, uncached, and returns "" on failure (history.go:94-99). With "" every message gets Aside: false and FromSelf: false (addressedElsewhere returns false for an empty bot id, listener.go:~1318). catchUpAsides sees a successful read with no asides and clears the marker (asides.go:242). The asides are lost without any error reaching the pipeline.
Fix: make ReadHistory return an error when no bot user id can be established (recorded id empty and auth.test failed or returned an empty UserID), so catchUpAsides and catchUp take their existing "ReadHistory failed" path and retry on the next message. Optionally cache a successful auth.test result per Channel (namespace/name) to avoid the call on every read.
Test: in history_test.go add TestReadHistory_AuthTestFailureIsAnError using a fake client whose AuthTestContext errors and a Channel with no botUserId. Run go test ./pkg/channels/channelkinds/slack/ -run History.
Constraints: AGENTS.md "Never silently drop errors".

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed, with a signal on the page instead of an error: when no bot user id can be established the read sets HistoryPage.AsidesUnknown (a20c93b), and catchUpAsides treats that like a failed read, keeping the marker and retrying on the next message (0125e43). An error would also have failed thread-adoption backfill, which does not need the bot id to be useful and does not retry. An empty UserID from auth.test is covered and logged too; I did not add the cache.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified at 0125e43b (fixed differently): AsidesUnknown: selfID == "" (slack/history.go:82), an empty UserID is logged (:117-120), and readAsideWindow returns not-ok on AsidesUnknown so the marker is kept (pipeline/asides.go:384-388). A page signal rather than an error is sound, since thread backfill should not fail on it. The history_test.go rows and TestDeliver_AsideCatchUpKeepsTheMarkerWhenTheReadCannotAnswer cover it.

The Slack thread reader returned one page of a thread and threw away the
cursor for the next, so a caller could see that more existed and had no
way to ask for it. It now accepts a cursor and hands back the one Slack
returns.

A read made without the bot's own user id marks no reply as an aside,
because the rule cannot be applied without it. That happens when the
Channel records no bot id and auth.test fails or returns none. The page
looked exactly like one from a thread with no asides in it. It now says
so (AsidesUnknown), so a caller that acts on the absence of asides can
tell the two apart. The messages are still returned: a thread backfill
wants them either way.

The comment claiming the reader and the listener cannot disagree was too
strong. They agree about a reply whose text has not changed; the reader
judges an edited reply by its current text, which can differ from what
the listener saw in either direction. The comment now says that, and why
the edited flag is not used to second-guess it.
…and attended children

Replies people address to each other in a thread are held back from the
agent and shown to it later as background. Several edges dropped them or
delivered them late.

A catch-up read one page of history and then cleared its marker, so the
asides past the first page were gone. It now reads to the end of the
window. If it has to stop early (a later page fails, or a bound on pages
or messages is reached) it seeds what it read and moves the marker to
where it stopped, so the next message carries on from there.

A read that could not tell asides apart was taken to mean there were
none, and the marker was cleared. The marker is now kept and the read is
retried on the next message.

An aside posted after a session had ended was ignored, though the next
message continues the same thread in a new session. It is now noted on
the finished session that message would continue.

A message that continues a finished session is handed to the new session
by the operator, not through delivery, so the background reached the
agent only on the message after it. The background is now appended to
the finished session's transcript before the fork is requested, so it is
copied with the history and sits ahead of the message that caused the
fork. The cursor is still carried to the new session for whatever that
could not seed.

A takeover that follows a policy halt starts a new session with no
history. It no longer gets the aside cursor either, and nothing is noted
on a session that ended that way.

While an attended child is live a person's next message goes to the
child. An aside is now noted on the child as well as on the thread's own
session, so the child is shown it too.

Noting an aside now correlates against a fresh read of the Channel, as a
routed message does, and no longer reads a transcript to do it.
@josephschorr
josephschorr requested a review from samkim December 2, 2026 21:48

@samkim samkim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Round 3 review of PR 86 (commits 8b89e58f..0125e43b: aside catch-up paging, asides after a session ends, attended children, fork-time seeding).

This round checked the 8 threads still open from round 2. All 8 are verified fixed (8 of 8), and the 3 earlier resolved threads stay resolved. The author's changes are sound and well covered by new tests (I reran the aside, restart and Slack history tests; all pass).

Verdict: ready after the inline fixes. One narrow race and one comment nit remain, neither touching the verified threads.

Issues that matter:

  1. [minor] Seeding the aside turn into an idle-archived session whose transcript was reclaimed makes that session look resumable while its fork is still pending. A message arriving in that short window is delivered to the old session instead of the fork, so the resumed agent sees only the asides. The trigger is narrow (reclaimed transcript, an aside marker, a second message before the operator reconciles). See inline on pkg/channels/channelsd/pipeline/asides.go.
  2. [nit] The NextCursor doc in pkg/channels/channelkinds/history.go still says the thread reader has no cursor and pages older, while the new paragraph says it pages forward. See inline.

Questions for the author: none. The two questions from round 2 (when asides reach the forking message, and live attended children) are answered in the code.

Nothing confirmed that could not be anchored to a diff line.

This review was drafted by an automated pipeline and checked before submission.

if p.ReadHistory == nil || mentionOnly(parent) || parent.Annotations[spiceboxv1alpha1.AnnotationAsidesSinceTS] == "" {
return
}
if parent.Status.PendingRestart != nil {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[minor] Seeding asides into a swept parent whose transcript was reclaimed lets the next message resume that parent while its fork is pending

Problem: Deliver forks a swept (idle-archived) session only because its transcript is empty or unreadable (classifyCorrelated, pipeline.go:592-602, sweptResumable = len(turns) > 0). seedAsidesBeforeFork then appends the aside turn to that parent (via catchUpAsides, asides.go:313-321), so the parent now has one turn. SupersededBy is only set later by the operator's ReconcileRestart, so ArchivedBySweep(parent) stays true (pkg/apis/v1alpha1/archive.go:13-18). If another message arrives in that window, classifyCorrelated sees one turn, classifies the parent as resumable, and routes the message into it (append plus wake, since WakeEligible is true for a swept Succeeded session, pkg/apis/v1alpha1/wake.go:22-34) instead of the pending fork. The resumed parent's runner has only the asides in memory while the operator also creates the child. Before this change the parent stayed at zero turns and the second message hit the pending fork (first-writer-wins, pipeline.go:2279). The Deliver resume path has no PendingRestart guard.
Fix: in seedAsidesBeforeFork (asides.go:463), return early when spiceboxv1alpha1.ArchivedBySweep(parent) is true, leaving the marker on the parent for BuildChildSession's carry (restart_decide.go:167). A swept parent that reaches the fork path is by construction one whose transcript could not be used, so there is nothing for the seeded turn to sit ahead of. Optionally also make the sweptResumable callback in classifyCorrelated return false when s.Status.PendingRestart != nil, so no later append can make a parent with a pending fork look resumable.
Test: in pkg/channels/channelsd/pipeline/asides_test.go add TestDeliver_AsideSeedingDoesNotMakeASweptParentResumable: a Succeeded parent with the Idle condition reason Archived, an empty transcript, and the aside marker set. Deliver M1 and expect OutcomeForkPending with no turn appended to the parent. Deliver M2 and expect it still routed to the pending fork (no append to the parent for M2, no wake annotation). Run go test ./pkg/channels/channelsd/pipeline/ -run Aside.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 362a395: seedAsidesBeforeFork now returns early when ArchivedBySweep(parent) is true, so nothing is appended to the parent and the marker stays for BuildChildSession's carry, which does not depend on sweep state and so hands it to the child on both the inherit fork and a history-inheriting takeover; TestDeliver_AsideSeedingDoesNotMakeASweptParentResumable covers M1 and M2 as described. I left the optional PendingRestart check out of sweptResumable: with no append to a swept parent it would only change windows this PR does not create (a transient transcript read error, a restart-from-here marker), turning an append into a first-writer-wins drop there, and an Idle parent with a pending restart has the same unguarded resume path, so that is better handled as its own change.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified at ee9b4620: seedAsidesBeforeFork returns before catchUpAsides when ArchivedBySweep(parent) (pkg/channels/channelsd/pipeline/asides.go:478), so a swept parent gets no appended turn and stays non-resumable while its fork is pending; the marker is left for BuildChildSession's carry. TestDeliver_AsideSeedingDoesNotMakeASweptParentResumable (asides_test.go:964) covers the two-message case and passes. Leaving the optional PendingRestart guard out is reasonable now that this change no longer creates that window.

// returns response_metadata.next_cursor). Empty when the kind paginates by
// message TS instead (the thread reader). Callers prefer NextCursor when
// non-empty, else fall back to the oldest message's TS.
//

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[nit] NextCursor doc contradicts itself about the thread reader

Problem: lines 53-56 (unchanged) say NextCursor names the next older page and is "Empty when the kind paginates by message TS instead (the thread reader)". The paragraph added at lines 58-63 and slack/history.go:55-57 say the thread reader now returns a cursor whose next page holds LATER messages. A future caller that follows the first paragraph would page the thread reader by oldest TS or assume older-first ordering. No current caller misreads it (historyresp/responder.go ignores NextCursor).
Fix: reword lines 53-56 so they cover both readers: channel history pages older by cursor (Slack conversations.history), and the bounded thread reader pages forward, oldest-first, by cursor. Drop the "(the thread reader)" clause from the TS-fallback sentence.
Test: none (comment only). Run go build ./pkg/channels/channelkinds/.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Reworded in ee9b462: the NextCursor doc now covers both readers (whole-channel history pages older by cursor, with the oldest-TS fallback; the bounded thread read pages forward, oldest-first, by cursor), and the "(the thread reader)" clause is gone from the TS-fallback sentence.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified at ee9b4620: the NextCursor doc (pkg/channels/channelkinds/history.go:53-68) now describes whole-channel history paging older with the TS fallback, and the bounded thread read paging forward oldest-first. The "(the thread reader)" clause is gone.

return
}

page, err := p.ReadHistory(ctx, ev.Channel, ev.ChannelKey, channelkinds.ReadHistoryOpts{

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified at 0125e43b: readAsideWindow follows NextCursor until HasMore is false, bounded by maxAsidePages/maxAsideMessages (pipeline/asides.go:348-434). An early stop seeds what was read, holds back the newest message, and catchUpAsides moves the marker to it instead of clearing (:324-332). The Slack reader passes Cursor through (slack/history.go:57-75). TestDeliver_AsideCatchUpReadsEveryPage and TestReadHistory_PagesByCursor cover it.

if err != nil {
return channelkinds.InboundDecision{Outcome: channelkinds.OutcomeInternalError}, err
}
active, _, _ := p.classifyCorrelated(ctx, &sessions)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified at 0125e43b: with no active session noteAside marks the newest finished session, skipping held and policy-halted ones (pipeline/asides.go:102-119), and the fork path seeds before the trigger (pipeline.go:1309-1311, :1426). TestDeliver_AsidesAfterASessionEndsAreSeededAheadOfTheFork covers inherit and takeover. See the new inline comment on seedAsidesBeforeFork for one side effect of this seeding.

"channel", channelRefForLog(ev.Channel), "channelKey", ev.ChannelKey)
return ignored, nil
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified at 0125e43b: noteAside re-reads the Channel through freshChannel (pipeline/asides.go:97) and classifies with sweptResumable = true, so no transcript read (:102). TestDeliver_AsideCorrelatesAgainstTheCurrentChannelSpec covers the class-patch case.

if mentionOnly(active) {
p.catchUp(ctx, active, ev)
} else if active.Annotations[spiceboxv1alpha1.AnnotationAsidesSinceTS] != "" {
p.catchUpAsides(ctx, active, ev)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified at 0125e43b: noteAsideOnAttendedChild marks the live attended child via liveAttendedChildOf (pipeline/asides.go:148-181), and the redirected message runs catchUpAsides on the child (pipeline.go:1058-1062). TestDeliver_AsideDuringALiveAttendedChildReachesTheChild covers it.

// owns it, so the cursor is carried and the child seeds them as background
// on its next inbound. A branching fork starts a new thread, where the
// parent's cursor names messages that are not in it.
if v := parent.Annotations[spiceboxv1alpha1.AnnotationAsidesSinceTS]; v != "" && !branchesThread {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified at 0125e43b (fixed differently, your variant of option a): seedAsidesBeforeFork (pipeline/asides.go:463-473) appends the background to the parent before both fork triggers (pipeline.go:1309-1311, :1426), so the operator's copy carries it ahead of NewUserText. It is skipped when a PendingRestart already exists. TestReconcileRestart_BackgroundAppendedBeforeTheForkPrecedesTheNewMessage shows the order. One side effect is raised in a new inline comment on seedAsidesBeforeFork.

// on its next inbound. A branching fork starts a new thread, where the
// parent's cursor names messages that are not in it.
if v := parent.Annotations[spiceboxv1alpha1.AnnotationAsidesSinceTS]; v != "" && !branchesThread {
childAnnotations[spiceboxv1alpha1.AnnotationAsidesSinceTS] = v

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified at 0125e43b: the cursor carries only when the child inherits history (restart_decide.go:178), the pipeline seeds only for inheritHistory (pipeline.go:1309), and noteAside skips policy-halted sessions. Both takeover rows are in TestBuildChildSession_CarriesUnseededAsidesWithinTheSameThread.

// listener ignored it, and marking it here would show the agent a bot it was
// configured not to hear. Either way the answer does not depend on the setting,
// which is why this reader does not need to know it.
func handedOverAsAside(m slackapi.Message, selfBotUserID string) bool {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified at 0125e43b: the comments at channelkinds/history.go:93-99 and slack/history.go state both edit directions. Keeping the behaviour is the right call: skipping an edited reply would turn a typo fix into a permanent loss. TestReadHistory_JudgesAnEditedReplyByItsCurrentText documents it.

return deps.Channel.Spec.Slack.BotUserID
resp, err := at.AuthTestContext(ctx)
if err != nil {
log.FromContext(ctx).Info("slack: auth.test failed; this read cannot tell the bot's own messages, or replies addressed to others, apart",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified at 0125e43b (fixed differently): AsidesUnknown: selfID == "" (slack/history.go:82), an empty UserID is logged (:117-120), and readAsideWindow returns not-ok on AsidesUnknown so the marker is kept (pipeline/asides.go:384-388). A page signal rather than an error is sound, since thread backfill should not fail on it. The history_test.go rows and TestDeliver_AsideCatchUpKeepsTheMarkerWhenTheReadCannotAnswer cover it.

…ved by the idle sweep

A session the idle sweep archived is continued in a fresh one only when
its transcript is gone or could not be read, and it stays wakeable until
the operator marks it superseded. Seeding the background turn into it
gave it a transcript of one turn, so a second message arriving before
the fork completed found it resumable, was appended to it and asked for
its runner back, instead of meeting the pending fork.

The marker now stays on such a parent and is carried to the child, which
seeds the asides on its next message.
The NextCursor doc described the cursor as naming an older page and the
thread reader as having none, next to a paragraph saying the thread
reader pages forward by cursor. It now covers both readers: whole-channel
history pages older, a bounded thread read pages forward, oldest-first.
@josephschorr
josephschorr requested a review from samkim December 4, 2026 20:14

@samkim samkim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Round 4 re-review (commits since round 3: 362a395, ee9b462, plus a clean merge of origin/main).

Earlier issues: all verified fixed, including the two that were still open this round (the swept-parent aside seeding in asides.go and the NextCursor doc in channelkinds/history.go). The merge of main keeps the order between seedAsidesBeforeFork and armForkTrigger. No new findings.

Verdict: ready.

Still open: nothing. Questions for the author: none.

This review was drafted by an automated pipeline and checked before submission.

if p.ReadHistory == nil || mentionOnly(parent) || parent.Annotations[spiceboxv1alpha1.AnnotationAsidesSinceTS] == "" {
return
}
if parent.Status.PendingRestart != nil {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified at ee9b4620: seedAsidesBeforeFork returns before catchUpAsides when ArchivedBySweep(parent) (pkg/channels/channelsd/pipeline/asides.go:478), so a swept parent gets no appended turn and stays non-resumable while its fork is pending; the marker is left for BuildChildSession's carry. TestDeliver_AsideSeedingDoesNotMakeASweptParentResumable (asides_test.go:964) covers the two-message case and passes. Leaving the optional PendingRestart guard out is reasonable now that this change no longer creates that window.

// returns response_metadata.next_cursor). Empty when the kind paginates by
// message TS instead (the thread reader). Callers prefer NextCursor when
// non-empty, else fall back to the oldest message's TS.
//

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Verified at ee9b4620: the NextCursor doc (pkg/channels/channelkinds/history.go:53-68) now describes whole-channel history paging older with the TS fallback, and the bounded thread read paging forward oldest-first. The "(the thread reader)" clause is gone.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants