Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6516 fix(channels): enforce durable context boundaries for /new (#7362)

YYClaw1cc46b2697bb
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index a7765cf8d9..f4e2d4334d 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -244,6 +244,7 @@ var concurrentIndexCleanups = map[string]string{
"361_issue_last_activity_index": "idx_issue_workspace_last_activity",
"363_plugin_invocation_installation_index": "idx_plugin_invocation_installation_created",
"364_plugin_invocation_created_at_index": "idx_plugin_invocation_created_at",
+ "378_channel_chat_context_generation_key": "channel_chat_context_generation_session_revision_idx",
"390_agent_task_queue_dispatched_reclaim_v2_index": "idx_agent_task_queue_dispatched_reclaim_v2",
"393_plugin_package_workspace_key_index": "idx_plugin_package_workspace_key",
"394_plugin_package_version_unique_index": "idx_plugin_package_version_unique",
diff --git a/server/cmd/server/retired_session_test.go b/server/cmd/server/retired_session_test.go
index bbd237f8e2..8a879cd062 100644
--- a/server/cmd/server/retired_session_test.go
+++ b/server/cmd/server/retired_session_test.go
@@ -31,6 +31,12 @@ func newPoisonTestChatSession(t *testing.T, agentID, runtimeID, title string) st
return chatSessionID
}
+func lastChatTaskSessionParams(chatSessionID string) db.GetLastChatTaskSessionParams {
+ return db.GetLastChatTaskSessionParams{
+ ChatSessionID: pgtype.UUID{Bytes: parseUUIDBytes(chatSessionID), Valid: true},
+ }
+}
+
// TestGetLastChatTaskSessionDoesNotResurrectFromOlderCompletedRow is the Chat
// half of the GH #5975 wormhole, which the issue query closed and the chat
// query never did. Task A completed on session S; task B then resumed S, hit
@@ -61,7 +67,7 @@ func TestGetLastChatTaskSessionDoesNotResurrectFromOlderCompletedRow(t *testing.
}
queries := db.New(testPool)
- prior, err := queries.GetLastChatTaskSession(ctx, pgtype.UUID{Bytes: parseUUIDBytes(chatSessionID), Valid: true})
+ prior, err := queries.GetLastChatTaskSession(ctx, lastChatTaskSessionParams(chatSessionID))
requireSessionExcluded(t, prior.SessionID, err)
}
@@ -92,7 +98,7 @@ func TestGetLastChatTaskSessionKeepsHealthyDistinctSession(t *testing.T) {
}
queries := db.New(testPool)
- prior, err := queries.GetLastChatTaskSession(ctx, pgtype.UUID{Bytes: parseUUIDBytes(chatSessionID), Valid: true})
+ prior, err := queries.GetLastChatTaskSession(ctx, lastChatTaskSessionParams(chatSessionID))
if err != nil {
t.Fatalf("GetLastChatTaskSession failed: %v", err)
}
@@ -124,7 +130,7 @@ func TestGetLastChatTaskSessionExcludesAuthResolutionFailure(t *testing.T) {
}
queries := db.New(testPool)
- prior, err := queries.GetLastChatTaskSession(ctx, pgtype.UUID{Bytes: parseUUIDBytes(chatSessionID), Valid: true})
+ prior, err := queries.GetLastChatTaskSession(ctx, lastChatTaskSessionParams(chatSessionID))
requireSessionExcluded(t, prior.SessionID, err)
}
@@ -150,7 +156,7 @@ func TestGetLastChatTaskSessionKeepsSessionOnAuthAdjacentError(t *testing.T) {
}
queries := db.New(testPool)
- prior, err := queries.GetLastChatTaskSession(ctx, pgtype.UUID{Bytes: parseUUIDBytes(chatSessionID), Valid: true})
+ prior, err := queries.GetLastChatTaskSession(ctx, lastChatTaskSessionParams(chatSessionID))
if err != nil {
t.Fatalf("GetLastChatTaskSession failed: %v", err)
}
@@ -221,7 +227,7 @@ func TestRetiredSessionExcludedFromChatResume(t *testing.T) {
}
queries := db.New(testPool)
- prior, err := queries.GetLastChatTaskSession(ctx, pgtype.UUID{Bytes: parseUUIDBytes(chatSessionID), Valid: true})
+ prior, err := queries.GetLastChatTaskSession(ctx, lastChatTaskSessionParams(chatSessionID))
requireSessionExcluded(t, prior.SessionID, err)
}
@@ -354,6 +360,6 @@ func TestGetLastChatTaskSessionExcludesOverflowedResumeFromOlderCompletedRow(t *
}
queries := db.New(testPool)
- prior, err := queries.GetLastChatTaskSession(ctx, pgtype.UUID{Bytes: parseUUIDBytes(chatSessionID), Valid: true})
+ prior, err := queries.GetLastChatTaskSession(ctx, lastChatTaskSessionParams(chatSessionID))
requireSessionExcluded(t, prior.SessionID, err)
}
diff --git a/server/internal/handler/channel_context_lock_order_test.go b/server/internal/handler/channel_context_lock_order_test.go
new file mode 100644
index 0000000000..fc68188e44
--- /dev/null
+++ b/server/internal/handler/channel_context_lock_order_test.go
@@ -0,0 +1,203 @@
+package handler
+
+import (
+ "context"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/internal/service"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+type contextLockTestStarter struct {
+ pool *pgxpool.Pool
+ pauseAfter string
+ paused chan struct{}
+ release chan struct{}
+ observeBefore string
+ observed chan struct{}
+}
+
+func (s *contextLockTestStarter) Begin(ctx context.Context) (pgx.Tx, error) {
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return &contextLockTestTx{Tx: tx, starter: s}, nil
+}
+
+type contextLockTestTx struct {
+ pgx.Tx
+ starter *contextLockTestStarter
+}
+
+func (tx *contextLockTestTx) QueryRow(ctx context.Context, query string, args ...any) pgx.Row {
+ if tx.starter.observeBefore != "" && strings.Contains(query, tx.starter.observeBefore) {
+ close(tx.starter.observed)
+ }
+ row := tx.Tx.QueryRow(ctx, query, args...)
+ switch {
+ case tx.starter.pauseAfter != "" && strings.Contains(query, tx.starter.pauseAfter):
+ return &contextLockPauseRow{Row: row, paused: tx.starter.paused, release: tx.starter.release}
+ default:
+ return row
+ }
+}
+
+type contextLockPauseRow struct {
+ pgx.Row
+ paused chan struct{}
+ release chan struct{}
+}
+
+func (row *contextLockPauseRow) Scan(dest ...any) error {
+ if err := row.Row.Scan(dest...); err != nil {
+ return err
+ }
+ close(row.paused)
+ <-row.release
+ return nil
+}
+
+// TestChannelContextLockOrder serializes the production enqueue and append
+// paths at the exact lock edge that previously formed an ABBA cycle. Enqueue
+// pauses while holding the target generation; a concurrent append then starts
+// its binding lock. Both must complete after enqueue is released, proving that
+// enqueue already owns binding before generation and append cannot invert it.
+func TestChannelContextLockOrder(t *testing.T) {
+ if testHandler == nil {
+ t.Fatal("database-backed handler test fixture is required")
+ }
+
+ ctx := context.Background()
+ agentID, _, _ := createRuntimeGuardAgent(t, ctx)
+ queries := db.New(testPool)
+ installationID := uuid.NewString()
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO channel_installation (
+ id, workspace_id, agent_id, channel_type, config, status, installer_user_id
+ ) VALUES ($1, $2, $3, 'slack', '{}'::jsonb, 'active', $4)
+ `, installationID, testWorkspaceID, agentID, testUserID); err != nil {
+ t.Fatalf("seed channel installation: %v", err)
+ }
+
+ session := engine.NewChatSession(queries, testPool, channel.Type("slack"), engine.SessionTitles{Direct: "Lock order test"})
+ sessionID, err := session.EnsureSession(ctx, engine.EnsureSessionInput{
+ WorkspaceID: util.MustParseUUID(testWorkspaceID),
+ AgentID: util.MustParseUUID(agentID),
+ InstallationID: util.MustParseUUID(installationID),
+ Sender: util.MustParseUUID(testUserID),
+ BindingKey: "lock-order-" + uuid.NewString(),
+ ChatType: channel.ChatTypeP2P,
+ })
+ if err != nil {
+ t.Fatalf("ensure channel session: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM channel_chat_context_generation WHERE chat_session_id = $1`, sessionID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM channel_chat_session_binding WHERE chat_session_id = $1`, sessionID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM channel_installation WHERE id = $1`, installationID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, sessionID)
+ })
+
+ if err := session.MarkPendingFresh(ctx, sessionID, "new-boundary"); err != nil {
+ t.Fatalf("mark pending fresh: %v", err)
+ }
+ initiator := util.MustParseUUID(testUserID)
+ if _, err := session.AppendUserMessage(ctx, engine.AppendInput{
+ SessionID: sessionID, Sender: initiator, InstallationID: util.MustParseUUID(installationID),
+ Body: "first post-new message", MessageID: "first-" + uuid.NewString(),
+ }); err != nil {
+ t.Fatalf("append first post-new message: %v", err)
+ }
+ chatSession, err := queries.GetChatSession(ctx, sessionID)
+ if err != nil {
+ t.Fatalf("load chat session: %v", err)
+ }
+
+ generationLocked := make(chan struct{})
+ releaseEnqueue := make(chan struct{})
+ var releaseOnce sync.Once
+ release := func() { releaseOnce.Do(func() { close(releaseEnqueue) }) }
+ defer release()
+ enqueueService := &service.TaskService{
+ Queries: queries,
+ TxStarter: &contextLockTestStarter{
+ pool: testPool, pauseAfter: "LockChannelChatContextGenerationByRevision",
+ paused: generationLocked, release: releaseEnqueue,
+ },
+ Bus: events.New(),
+ }
+ enqueueResult := make(chan error, 1)
+ go func() {
+ _, err := enqueueService.EnqueueChannelChatTask(ctx, chatSession, initiator, true, 2)
+ enqueueResult <- err
+ }()
+ waitContextLockSignal(t, generationLocked, "enqueue did not lock generation")
+
+ bindingAttempted := make(chan struct{})
+ appendSession := engine.NewChatSession(queries, &contextLockTestStarter{
+ pool: testPool, observeBefore: "LockChannelChatSessionBindingForContext", observed: bindingAttempted,
+ }, channel.Type("slack"), engine.SessionTitles{Direct: "Lock order test"})
+ appendResult := make(chan error, 1)
+ go func() {
+ _, err := appendSession.AppendUserMessage(ctx, engine.AppendInput{
+ SessionID: sessionID, Sender: initiator, InstallationID: util.MustParseUUID(installationID),
+ Body: "racing append", MessageID: "racing-" + uuid.NewString(),
+ })
+ appendResult <- err
+ }()
+ waitContextLockSignal(t, bindingAttempted, "append did not attempt binding lock")
+ release()
+
+ if err := waitContextLockResult(t, enqueueResult, "enqueue"); err != nil {
+ t.Fatalf("enqueue failed: %v", err)
+ }
+ if err := waitContextLockResult(t, appendResult, "append"); err != nil {
+ t.Fatalf("append failed: %v", err)
+ }
+
+ var unowned int
+ var revision pgtype.Int8
+ if err := testPool.QueryRow(ctx, `
+ SELECT count(*), max(channel_context_revision)
+ FROM chat_message
+ WHERE chat_session_id = $1 AND role = 'user' AND task_id IS NULL
+ `, sessionID).Scan(&unowned, &revision); err != nil {
+ t.Fatalf("inspect racing append: %v", err)
+ }
+ if unowned != 1 || !revision.Valid || revision.Int64 != 2 {
+ t.Fatalf("racing append state = unowned:%d revision:%v, want 1/revision 2", unowned, revision)
+ }
+}
+
+func waitContextLockSignal(t *testing.T, signal <-chan struct{}, failure string) {
+ t.Helper()
+ select {
+ case <-signal:
+ case <-time.After(10 * time.Second):
+ t.Fatal(failure)
+ }
+}
+
+func waitContextLockResult(t *testing.T, result <-chan error, label string) error {
+ t.Helper()
+ select {
+ case err := <-result:
+ return err
+ case <-time.After(10 * time.Second):
+ t.Fatalf("%s did not complete", label)
+ return nil
+ }
+}
diff --git a/server/internal/handler/channel_new_e2e_test.go b/server/internal/handler/channel_new_e2e_test.go
index 478501d257..b0fe4007ca 100644
--- a/server/internal/handler/channel_new_e2e_test.go
+++ b/server/internal/handler/channel_new_e2e_test.go
@@ -170,6 +170,17 @@ func runChannelNewCommandE2E(t *testing.T, channelType channel.Type, text, comma
`, sessionID, runtimeID); err != nil {
t.Fatalf("seed prior provider context: %v", err)
}
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO agent_task_queue (
+ agent_id, runtime_id, chat_session_id, status, priority,
+ started_at, completed_at, session_id, work_dir,
+ channel_context_revision
+ )
+ VALUES ($1, $2, $3, 'completed', 0, now(), now(),
+ 'old-provider-session', '/tmp/old-provider-workdir', 1)
+ `, agentID, runtimeID, sessionID); err != nil {
+ t.Fatalf("seed prior provider task: %v", err)
+ }
router := engine.NewRouter(nil, testHandler.TaskService, queries, engine.RouterConfig{})
router.Register(channelType, engine.ResolverSet{
@@ -200,7 +211,10 @@ func runChannelNewCommandE2E(t *testing.T, channelType channel.Type, text, comma
if followUpText != "" {
var taskCount, userMessageCount int
var pendingFresh bool
- if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE chat_session_id = $1`, sessionID).Scan(&taskCount); err != nil {
+ if err := testPool.QueryRow(ctx, `
+ SELECT count(*) FROM agent_task_queue
+ WHERE chat_session_id = $1 AND status NOT IN ('completed', 'failed', 'cancelled')
+ `, sessionID).Scan(&taskCount); err != nil {
t.Fatalf("count tasks after bare /new: %v", err)
}
if err := testPool.QueryRow(ctx, `SELECT count(*) FROM chat_message WHERE chat_session_id = $1 AND role = 'user'`, sessionID).Scan(&userMessageCount); err != nil {
@@ -232,18 +246,26 @@ func runChannelNewCommandE2E(t *testing.T, channelType channel.Type, text, comma
var taskID string
var forceFresh bool
+ var contextRevision int64
if err := testPool.QueryRow(ctx, `
- SELECT id, force_fresh_session
+ SELECT id, force_fresh_session, channel_context_revision
FROM agent_task_queue
WHERE chat_session_id = $1
ORDER BY created_at DESC
LIMIT 1
- `, sessionID).Scan(&taskID, &forceFresh); err != nil {
+ `, sessionID).Scan(&taskID, &forceFresh, &contextRevision); err != nil {
t.Fatalf("load queued chat task: %v", err)
}
if forceFresh != wantForceFresh {
t.Fatalf("queued task %s: force_fresh_session = %t, want %t", taskID, forceFresh, wantForceFresh)
}
+ wantRevision := int64(1)
+ if wantForceFresh {
+ wantRevision = 2
+ }
+ if contextRevision != wantRevision {
+ t.Fatalf("queued task %s: channel_context_revision = %d, want %d", taskID, contextRevision, wantRevision)
+ }
var pendingFresh bool
if err := testPool.QueryRow(ctx, `SELECT pending_fresh FROM channel_chat_session_binding WHERE chat_session_id = $1`, sessionID).Scan(&pendingFresh); err != nil {
t.Fatalf("load pending fresh after task enqueue: %v", err)
@@ -267,17 +289,21 @@ func runChannelNewCommandE2E(t *testing.T, channelType channel.Type, text, comma
}
var storedText string
+ var storedRevision int64
if err := testPool.QueryRow(ctx, `
- SELECT content FROM chat_message
+ SELECT content, channel_context_revision FROM chat_message
WHERE chat_session_id = $1 AND role = 'user'
ORDER BY created_at DESC, id DESC
LIMIT 1
- `, sessionID).Scan(&storedText); err != nil {
+ `, sessionID).Scan(&storedText, &storedRevision); err != nil {
t.Fatalf("load persisted chat message: %v", err)
}
if storedText != wantStoredText {
t.Fatalf("persisted message = %q, want %q", storedText, wantStoredText)
}
+ if storedRevision != wantRevision {
+ t.Fatalf("persisted message context revision = %d, want %d", storedRevision, wantRevision)
+ }
claimed := claimTaskForRuntimeGuard(t, runtimeID, daemonID)
if claimed.ChatMessage != wantStoredText {
@@ -355,8 +381,8 @@ func (b *channelNewE2ESessionBinder) EnsureSession(ctx context.Context, p engine
})
}
-func (b *channelNewE2ESessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) error {
- return b.session.MarkPendingFresh(ctx, sessionID)
+func (b *channelNewE2ESessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error {
+ return b.session.MarkPendingFresh(ctx, sessionID, messageID)
}
func (b *channelNewE2ESessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {
diff --git a/server/internal/handler/chat_history.go b/server/internal/handler/chat_history.go
index 25facd8e16..80a808e7e8 100644
--- a/server/internal/handler/chat_history.go
+++ b/server/internal/handler/chat_history.go
@@ -55,7 +55,7 @@ type ChatChannelHistoryResponse struct {
// reconstruct the conversation after a lost resume instead of being told nothing
// is readable (see the continuity-notice split in execenv).
func (h *Handler) GetChatChannelHistory(w http.ResponseWriter, r *http.Request) {
- sessionID, ok := h.chatHistorySession(w, r)
+ scope, ok := h.chatHistorySession(w, r)
if !ok {
return
}
@@ -66,15 +66,15 @@ func (h *Handler) GetChatChannelHistory(w http.ResponseWriter, r *http.Request)
// serve the stored transcript directly. Without this a no-Slack deployment
// — the exact one this feature targets — would dead-end on a "no channel
// integration" note and never reach the transcript.
- page, err = h.chatMessageHistory(r, sessionID)
+ page, err = h.chatMessageHistory(r, scope)
} else {
- page, err = h.SlackHistory.ChannelOverview(r.Context(), sessionID, historyOptionsFrom(r))
+ page, err = h.SlackHistory.ChannelOverview(r.Context(), scope.sessionID, scope.historyOptions(r))
if errors.Is(err, slack.ErrNoSlackSession) {
// Not Slack-backed: read the session's own stored transcript instead.
- page, err = h.chatMessageHistory(r, sessionID)
+ page, err = h.chatMessageHistory(r, scope)
}
}
- h.respondChatHistory(w, r, sessionID, page, err)
+ h.respondChatHistory(w, r, scope.sessionID, page, err)
}
// chatMessageHistory reads a chat session's own stored transcript (chat_message)
@@ -84,15 +84,22 @@ func (h *Handler) GetChatChannelHistory(w http.ResponseWriter, r *http.Request)
// Multica — there is no platform to read back. It pages through the same
// (created_at, id) cursor the frontend's message list uses, so an agent can walk
// a long session back without re-reading the recent window each time.
-func (h *Handler) chatMessageHistory(r *http.Request, sessionID pgtype.UUID) (channel.HistoryPage, error) {
+func (h *Handler) chatMessageHistory(r *http.Request, scope chatHistoryScope) (channel.HistoryPage, error) {
limit := clampTranscriptLimit(parseHistoryLimit(r.URL.Query().Get("limit")))
beforeCreatedAt, beforeID := parseTranscriptCursor(r.URL.Query().Get("before"))
- messages, err := h.Queries.ListChatMessagesPage(r.Context(), db.ListChatMessagesPageParams{
- ChatSessionID: sessionID,
- Limit: int32(limit),
- BeforeCreatedAt: beforeCreatedAt,
- BeforeID: beforeID,
- })
+ var messages []db.ChatMessage
+ var err error
+ if scope.contextRevision.Valid {
+ messages, err = h.Queries.ListChatMessagesPageForChannelContext(r.Context(), db.ListChatMessagesPageForChannelContextParams{
+ ChatSessionID: scope.sessionID, ChannelContextRevision: scope.contextRevision,
+ PageLimit: int32(limit), BeforeCreatedAt: beforeCreatedAt, BeforeID: beforeID,
+ })
+ } else {
+ messages, err = h.Queries.ListChatMessagesPage(r.Context(), db.ListChatMessagesPageParams{
+ ChatSessionID: scope.sessionID, Limit: int32(limit),
+ BeforeCreatedAt: beforeCreatedAt, BeforeID: beforeID,
+ })
+ }
if err != nil {
return channel.HistoryPage{}, err
}
@@ -118,7 +125,7 @@ func (h *Handler) chatMessageHistory(r *http.Request, sessionID pgtype.UUID) (ch
// unset here would tell a Feishu/WeCom/DingTalk agent it is in a web-only
// chat — and would disagree with the empty-read path below, which already
// reports the bound platform for the very same session.
- channelType, err := h.sessionChannelType(r.Context(), sessionID)
+ channelType, err := h.sessionChannelType(r.Context(), scope.sessionID)
if err != nil {
return channel.HistoryPage{}, fmt.Errorf("%w: %w", errChannelBindingRead, err)
}
@@ -193,7 +200,7 @@ func transcriptAuthor(role channel.HistoryRole) string {
// channel stays server-pinned to the session, so the id is only a within-channel
// locator.
func (h *Handler) GetChatThread(w http.ResponseWriter, r *http.Request) {
- sessionID, ok := h.chatHistorySession(w, r)
+ scope, ok := h.chatHistorySession(w, r)
if !ok {
return
}
@@ -202,8 +209,8 @@ func (h *Handler) GetChatThread(w http.ResponseWriter, r *http.Request) {
return
}
threadID := r.URL.Query().Get("id")
- page, err := h.SlackHistory.Thread(r.Context(), sessionID, threadID, historyOptionsFrom(r))
- h.respondChatHistory(w, r, sessionID, page, err)
+ page, err := h.SlackHistory.Thread(r.Context(), scope.sessionID, threadID, scope.historyOptions(r))
+ h.respondChatHistory(w, r, scope.sessionID, page, err)
}
// chatHistorySession authorizes the request and returns the caller's own chat
@@ -212,29 +219,48 @@ func (h *Handler) GetChatThread(w http.ResponseWriter, r *http.Request) {
// mul_ PAT leaves X-Actor-Source empty and does NOT strip a client-forged
// X-Task-ID), so requiring the task-token actor is load-bearing — without it a
// member could forge X-Task-ID and read another session's history.
-func (h *Handler) chatHistorySession(w http.ResponseWriter, r *http.Request) (pgtype.UUID, bool) {
+type chatHistoryScope struct {
+ sessionID pgtype.UUID
+ contextRevision pgtype.Int8
+ historyStart string
+ historyEnd string
+ boundaryPending bool
+}
+
+func (s chatHistoryScope) historyOptions(r *http.Request) channel.HistoryOptions {
+ opts := historyOptionsFrom(r)
+ opts.BoundaryPending = s.boundaryPending
+ opts.After = s.historyStart
+ opts.Until = s.historyEnd
+ if s.contextRevision.Valid {
+ opts.ContextRevision = s.contextRevision.Int64
+ }
+ return opts
+}
+
+func (h *Handler) chatHistorySession(w http.ResponseWriter, r *http.Request) (chatHistoryScope, bool) {
if r.Header.Get("X-Actor-Source") != "task_token" {
writeError(w, http.StatusForbidden, "chat history is only available from within an agent task")
- return pgtype.UUID{}, false
+ return chatHistoryScope{}, false
}
taskIDHeader := r.Header.Get("X-Task-ID")
if taskIDHeader == "" {
writeError(w, http.StatusBadRequest, "missing task context")
- return pgtype.UUID{}, false
+ return chatHistoryScope{}, false
}
taskUUID, err := util.ParseUUID(taskIDHeader)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid task id")
- return pgtype.UUID{}, false
+ return chatHistoryScope{}, false
}
task, err := h.Queries.GetAgentTask(r.Context(), taskUUID)
if err != nil {
writeError(w, http.StatusNotFound, "task not found")
- return pgtype.UUID{}, false
+ return chatHistoryScope{}, false
}
if !task.ChatSessionID.Valid {
writeError(w, http.StatusBadRequest, "this task is not a chat task")
- return pgtype.UUID{}, false
+ return chatHistoryScope{}, false
}
// Defense in depth: load the session and confirm it lives in the token's
// stamped workspace. The token→task binding already guarantees the agent can
@@ -242,13 +268,26 @@ func (h *Handler) chatHistorySession(w http.ResponseWriter, r *http.Request) (pg
session, err := h.Queries.GetChatSession(r.Context(), task.ChatSessionID)
if err != nil {
writeError(w, http.StatusNotFound, "chat session not found")
- return pgtype.UUID{}, false
+ return chatHistoryScope{}, false
}
if ws := ctxWorkspaceID(r.Context()); ws != "" && uuidToString(session.WorkspaceID) != ws {
writeError(w, http.StatusForbidden, "chat session does not belong to this workspace")
- return pgtype.UUID{}, false
+ return chatHistoryScope{}, false
+ }
+ scope := chatHistoryScope{sessionID: task.ChatSessionID, contextRevision: task.ChannelContextRevision}
+ if task.ChannelContextRevision.Valid {
+ generation, err := h.Queries.GetChannelChatContextGeneration(r.Context(), db.GetChannelChatContextGenerationParams{
+ ChatSessionID: task.ChatSessionID, Revision: task.ChannelContextRevision.Int64,
+ })
+ if err != nil {
+ writeError(w, http.StatusNotFound, "chat context generation not found")
+ return chatHistoryScope{}, false
+ }
+ scope.historyStart = generation.HistoryStartMessageID.String
+ scope.historyEnd = generation.HistoryEndMessageID.String
+ scope.boundaryPending = generation.HistoryBoundaryPending
}
- return task.ChatSessionID, true
+ return scope, true
}
// respondChatHistory writes the shared response: a note (200) when the session
diff --git a/server/internal/handler/chat_history_test.go b/server/internal/handler/chat_history_test.go
index f25d83a099..5e6d7c31ef 100644
--- a/server/internal/handler/chat_history_test.go
+++ b/server/internal/handler/chat_history_test.go
@@ -11,10 +11,12 @@ import (
"testing"
"time"
+ "github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/integrations/channel"
"github.com/multica-ai/multica/server/internal/integrations/slack"
+ "github.com/multica-ai/multica/server/internal/util"
)
type fakeChatHistoryReader struct {
@@ -27,6 +29,22 @@ type fakeChatHistoryReader struct {
gotOpts channel.HistoryOptions
}
+func TestChatHistoryScopePassesImmutableContextGeneration(t *testing.T) {
+ scope := chatHistoryScope{
+ contextRevision: pgtype.Int8{Int64: 3, Valid: true},
+ historyStart: "100.000000",
+ historyEnd: "200.000000",
+ boundaryPending: true,
+ }
+ opts := scope.historyOptions(newRequest("GET", "/api/chat/history?limit=7&before=150.000000", nil))
+ if opts.ContextRevision != 3 || opts.After != "100.000000" || opts.Until != "200.000000" || !opts.BoundaryPending {
+ t.Fatalf("generation options = %+v", opts)
+ }
+ if opts.Limit != 7 || opts.Before != "150.000000" {
+ t.Fatalf("paging options = %+v", opts)
+ }
+}
+
func (f *fakeChatHistoryReader) ChannelOverview(_ context.Context, sid pgtype.UUID, opts channel.HistoryOptions) (channel.HistoryPage, error) {
f.overviewCalls++
f.gotSession = sid
@@ -70,7 +88,7 @@ func newChatHistoryTask(t *testing.T, chatSession bool) string {
// session and returns the task id.
func newChatHistoryTaskForSession(t *testing.T, sessionID string) string {
t.Helper()
- agentID := createHandlerTestAgent(t, "ChatHistorySessionAgent", []byte("[]"))
+ agentID := createHandlerTestAgent(t, "ChatHistorySessionAgent-"+uuid.NewString(), []byte("[]"))
runtimeID := handlerTestRuntimeID(t)
var taskID string
if err := testPool.QueryRow(context.Background(), `
@@ -403,6 +421,97 @@ func TestGetChatHistory_WebOnlyTranscriptHasNoChannelType(t *testing.T) {
}
}
+func TestGetChatHistory_ChannelTaskCannotReadEarlierContextGeneration(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("requires test database")
+ }
+ ctx := context.Background()
+ agentID := createHandlerTestAgent(t, "ChatHistoryFreshBoundaryAgent", []byte("[]"))
+ sessionID := createHandlerTestChatSession(t, agentID)
+ legacyTaskID := newChatHistoryTaskForSession(t, sessionID)
+ taskID := newChatHistoryTaskForSession(t, sessionID)
+ withSlackHistory(t, nil)
+
+ var installationID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO channel_installation (workspace_id, agent_id, channel_type, config, status, installer_user_id)
+ VALUES ($1, $2, 'wecom', '{"app_id":"history-context-boundary"}'::jsonb, 'active', $3)
+ RETURNING id
+ `, testWorkspaceID, agentID, testUserID).Scan(&installationID); err != nil {
+ t.Fatalf("create installation: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM channel_chat_context_generation WHERE chat_session_id = $1`, sessionID)
+ testPool.Exec(context.Background(), `DELETE FROM channel_chat_session_binding WHERE chat_session_id = $1`, sessionID)
+ testPool.Exec(context.Background(), `DELETE FROM channel_installation WHERE id = $1`, installationID)
+ })
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO channel_chat_session_binding
+ (chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, context_revision)
+ VALUES ($1, $2, 'wecom', 'CONTEXT_BOUNDARY', 'group', 2)
+ `, sessionID, installationID); err != nil {
+ t.Fatalf("seed context binding: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO channel_chat_context_generation (chat_session_id, revision)
+ VALUES ($1, 1), ($1, 2)
+ `, sessionID); err != nil {
+ t.Fatalf("seed context generations: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET channel_context_revision = 2 WHERE id = $1`, taskID); err != nil {
+ t.Fatalf("stamp task context generation: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `UPDATE agent_task_queue SET channel_context_revision = 1 WHERE id = $1`, legacyTaskID); err != nil {
+ t.Fatalf("stamp legacy task context generation: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO chat_message (chat_session_id, role, content, task_id, channel_ingested, channel_context_revision)
+ VALUES
+ ($1, 'user', 'old secret', NULL, TRUE, 1),
+ ($1, 'user', 'rolling legacy message', NULL, TRUE, NULL),
+ ($1, 'assistant', 'rolling legacy answer', $2, FALSE, NULL),
+ ($1, 'user', 'fresh question', NULL, TRUE, 2)
+ `, sessionID, legacyTaskID); err != nil {
+ t.Fatalf("seed context messages: %v", err)
+ }
+ visible, err := testHandler.Queries.ListChatMessages(ctx, util.MustParseUUID(sessionID))
+ if err != nil {
+ t.Fatalf("list UI transcript: %v", err)
+ }
+ if len(visible) != 4 {
+ t.Fatalf("UI transcript contains %d messages, want both generations", len(visible))
+ }
+
+ w := httptest.NewRecorder()
+ testHandler.GetChatChannelHistory(w, taskActorReq("/api/chat/history", taskID))
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())
+ }
+ var resp ChatChannelHistoryResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if len(resp.Messages) != 1 || resp.Messages[0].Text != "fresh question" {
+ t.Fatalf("generation-scoped transcript = %+v", resp.Messages)
+ }
+
+ w = httptest.NewRecorder()
+ testHandler.GetChatChannelHistory(w, taskActorReq("/api/chat/history", legacyTaskID))
+ if w.Code != http.StatusOK {
+ t.Fatalf("legacy status = %d, want 200: %s", w.Code, w.Body.String())
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode legacy response: %v", err)
+ }
+ legacyTexts := make(map[string]bool, len(resp.Messages))
+ for _, message := range resp.Messages {
+ legacyTexts[message.Text] = true
+ }
+ if len(resp.Messages) != 3 || !legacyTexts["old secret"] || !legacyTexts["rolling legacy message"] || !legacyTexts["rolling legacy answer"] {
+ t.Fatalf("first-generation rolling transcript = %+v", resp.Messages)
+ }
+}
+
// TestGetChatHistory_TranscriptPagesWithoutDuplicatesOrGaps: the transcript
// honors the ?limit / ?before paging contract — walking back page by page with
// next_cursor yields every stored message exactly once, and a full page
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 370955153f..7b0a7cacda 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -2657,7 +2657,7 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
}
}
projectCtx.applyTo(&resp)
- if !task.ForceFreshSession {
+ if !task.ForceFreshSession && !task.ChannelContextRevision.Valid {
// Resume chat sessions only when the stored pointer was produced
// by the same runtime as the claiming task. When the chat_session
// pointer is missing (legacy NULL runtime_id), stale (last task
@@ -2716,13 +2716,23 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
// reads belong after it: a task that cannot load its input is preserved
// for redelivery and must not spend two more queries before returning.
if !task.ForceFreshSession {
+ contextRevision := pgtype.Int8{}
+ if task.ChannelContextRevision.Valid {
+ contextRevision = task.ChannelContextRevision
+ }
// GetLastChatTaskSession currently has exactly two consumers: the
// prior session and prior workdir fields. Keep this guard coupled to
// both so adding a third consumer cannot silently skip its fallback.
- if chatSessionResumeFallbackNeeded(resp.PriorSessionID, resp.PriorWorkDir) {
+ // Context-scoped channel tasks always resolve both fields from task
+ // rows in their own generation; the Chat-wide pointer may belong to a
+ // different generation when independent debounce timers race.
+ if task.ChannelContextRevision.Valid || chatSessionResumeFallbackNeeded(resp.PriorSessionID, resp.PriorWorkDir) {
h.Metrics.RecordChatClaimSessionFallbackNeeded()
started := time.Now()
- prior, err := h.Queries.GetLastChatTaskSession(r.Context(), cs.ID)
+ prior, err := h.Queries.GetLastChatTaskSession(r.Context(), db.GetLastChatTaskSessionParams{
+ ChatSessionID: cs.ID,
+ ChannelContextRevision: contextRevision,
+ })
h.Metrics.ObserveChatClaimLastSessionQuery(time.Since(started).Seconds())
switch {
case err == nil && prior.SessionID.Valid:
@@ -2748,7 +2758,10 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
// either pointer field needed fallback, so this query stays
// unconditional for non-force-fresh chat claims.
started := time.Now()
- missing, err := h.Queries.GetLatestChatTaskRolloutMissing(r.Context(), cs.ID)
+ missing, err := h.Queries.GetLatestChatTaskRolloutMissing(r.Context(), db.GetLatestChatTaskRolloutMissingParams{
+ ChatSessionID: cs.ID,
+ ChannelContextRevision: contextRevision,
+ })
h.Metrics.ObserveChatClaimRolloutMissingQuery(time.Since(started).Seconds())
if err == nil && missing {
resp.PriorSessionResumeUnavailable = true
diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.go
index ac777300b9..8fa7bc8ec2 100644
--- a/server/internal/handler/daemon_test.go
+++ b/server/internal/handler/daemon_test.go
@@ -3192,6 +3192,68 @@ func TestClaimTask_ChatPriorSessionRuntimeGuard(t *testing.T) {
}
}
+// Different channel context generations have independent debounce timers. If
+// the newer generation finishes first, its Chat-wide pointer must not become
+// the resume source for a delayed task from the older generation.
+func TestClaimTask_ChannelContextRevisionScopesProviderResume(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)
+ chatSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{
+ "title": "channel generation resume scope",
+ "session_id": "new-generation-session",
+ "work_dir": "/tmp/new-generation-workdir",
+ "runtime_id": runtimeID,
+ })
+
+ dbfx.Exec(t, `
+ INSERT INTO agent_task_queue (
+ agent_id, runtime_id, chat_session_id, status, priority,
+ started_at, completed_at, session_id, work_dir,
+ channel_context_revision
+ )
+ VALUES
+ ($1, $2, $3, 'completed', 0, now() - interval '2 minutes', now() - interval '2 minutes',
+ 'old-generation-session', '/tmp/old-generation-workdir', 1),
+ ($1, $2, $3, 'completed', 0, now() - interval '1 minute', now() - interval '1 minute',
+ 'new-generation-session', '/tmp/new-generation-workdir', 2)
+ `, agentID, runtimeID, chatSessionID)
+ dbfx.Exec(t, `
+ UPDATE agent_task_queue
+ SET session_rollout_missing = TRUE
+ WHERE chat_session_id = $1 AND channel_context_revision = 2
+ `, chatSessionID)
+
+ taskID := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": runtimeID,
+ "chat_session_id": chatSessionID,
+ "priority": 1000,
+ "channel_context_revision": int64(1),
+ })
+ dbfx.Exec(t, `UPDATE agent_task_queue SET chat_input_task_id = id WHERE id = $1`, taskID)
+ dbfx.Insert(t, "chat_message", testutil.Cols{
+ "chat_session_id": chatSessionID,
+ "role": "user",
+ "content": "delayed old-generation message",
+ "task_id": taskID,
+ "channel_context_revision": int64(1),
+ })
+
+ task := claimTaskForRuntimeGuard(t, runtimeID, daemonID)
+ if task.PriorSessionID != "old-generation-session" {
+ t.Fatalf("prior session = %q, want old-generation-session", task.PriorSessionID)
+ }
+ if task.PriorWorkDir != "/tmp/old-generation-workdir" {
+ t.Fatalf("prior workdir = %q, want /tmp/old-generation-workdir", task.PriorWorkDir)
+ }
+ if task.PriorSessionResumeUnavailable {
+ t.Fatal("new-generation continuity gap leaked into old-generation claim")
+ }
+}
+
// TestClaimTask_ChatDeliversAllUnansweredUserMessages pins the fix for the
// regression the MUL-2968 debounce exposed: when several user messages are
// debounced into a single run, the agent must receive ALL of them, not just
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index 683c8c451a..a0e02060e1 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -37,6 +37,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"autopilot_subscriber": workspaceDelete,
"autopilot_trigger": workspaceDelete,
"channel_binding_token": workspaceDelete,
+ "channel_chat_context_generation": workspaceDelete,
"channel_chat_session_binding": workspaceDelete,
"channel_inbound_audit": workspaceDelete,
"channel_inbound_message_dedup": workspaceDelete,
diff --git a/server/internal/integrations/channel/engine/batcher.go b/server/internal/integrations/channel/engine/batcher.go
index 6cdb156de5..3706e820c2 100644
--- a/server/internal/integrations/channel/engine/batcher.go
+++ b/server/internal/integrations/channel/engine/batcher.go
@@ -17,20 +17,21 @@ type stoppableTimer interface {
Stop() bool
}
-// pendingBatcher debounces the per-chat_session run trigger. Each inbound
-// message that lands in a session calls Schedule, which (re)arms a single
-// timer for that session; when the session goes quiet for the window the
-// latest flush runs exactly once. This collapses a burst into ONE agent run —
-// safe because the chat task reads the WHOLE session at run time. Only the run
-// TRIGGER is debounced; the chat_message rows, dedup, and frame ACK already
-// happened synchronously upstream.
+// pendingBatcher debounces a per-(chat_session, context generation) run trigger.
+// Each inbound message calls Schedule, which (re)arms one timer for that
+// generation; when it goes quiet the latest flush runs exactly once. This
+// collapses an in-generation burst into one agent run while preserving /new as
+// a hard batch boundary. Only the run trigger is debounced; chat_message rows,
+// dedup, and frame ACK already happened synchronously upstream.
//
-// State is in-process, keyed by chat_session_id (a globally-unique UUID). The
+// State is in-process, keyed by chat_session_id plus context revision. The
// WS lease guarantees a single active owner per installation, so a session is
// debounced by one process. A hard crash inside the window drops the pending
// trigger (messages are durable; they just do not fire a run until the next
-// message). Graceful shutdown calls FlushAll so that boundary is not hit on a
-// normal restart. Goroutine-safe; one instance is shared across supervisors.
+// message). Callers include the durable context revision in the key, so a
+// /new boundary can never replace the pending flush for the preceding context.
+// Graceful shutdown calls FlushAll so that boundary is not hit on a normal
+// restart. Goroutine-safe; one instance is shared across supervisors.
type pendingBatcher struct {
window time.Duration
@@ -78,6 +79,19 @@ func realAfterFunc(d time.Duration, fn func()) stoppableTimer {
// Calling Schedule after FlushAll runs the flush inline rather than dropping it
// (the shutdown race where a message arrives after the drain has begun).
func (b *pendingBatcher) Schedule(key string, flush func()) {
+ b.schedule(key, flush, true)
+}
+
+// ScheduleIfAbsent arms key only when this process has no live window for it.
+// Crash recovery uses this for older durable context generations: a missing
+// timer must be restored, but a message on a newer generation must not reset an
+// older generation's already-running silence window or replace its sender
+// metadata.
+func (b *pendingBatcher) ScheduleIfAbsent(key string, flush func()) {
+ b.schedule(key, flush, false)
+}
+
+func (b *pendingBatcher) schedule(key string, flush func(), replace bool) {
b.mu.Lock()
if b.stopped {
b.mu.Unlock()
@@ -88,6 +102,10 @@ func (b *pendingBatcher) Schedule(key string, flush func()) {
gen := b.seq
fire := func() { b.onFire(key, gen) }
if e, ok := b.pending[key]; ok {
+ if !replace {
+ b.mu.Unlock()
+ return
+ }
e.timer.Stop()
e.flush = flush
e.gen = gen
diff --git a/server/internal/integrations/channel/engine/batcher_test.go b/server/internal/integrations/channel/engine/batcher_test.go
index ff0d0b8e91..e6045e774a 100644
--- a/server/internal/integrations/channel/engine/batcher_test.go
+++ b/server/internal/integrations/channel/engine/batcher_test.go
@@ -64,6 +64,12 @@ func (f *fakeTimerFactory) armedCount() int {
return n
}
+func (f *fakeTimerFactory) createdCount() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return len(f.all)
+}
+
// newTestBatcher builds a batcher whose timers are driven by f. Shared with
// router_test.go (same package) to drive the debounce coalescing test.
func newTestBatcher(f *fakeTimerFactory) *pendingBatcher {
@@ -138,6 +144,23 @@ func TestPendingBatcher_StaleTimerFireIsNoop(t *testing.T) {
}
}
+func TestPendingBatcher_ScheduleIfAbsentPreservesExistingWindow(t *testing.T) {
+ f := &fakeTimerFactory{}
+ b := newTestBatcher(f)
+ firstCalls, recoveryCalls := 0, 0
+
+ b.Schedule("s", func() { firstCalls++ })
+ b.ScheduleIfAbsent("s", func() { recoveryCalls++ })
+
+ if got := f.createdCount(); got != 1 {
+ t.Fatalf("recovery replaced a live timer: created=%d, want 1", got)
+ }
+ f.fireArmed()
+ if firstCalls != 1 || recoveryCalls != 0 {
+ t.Fatalf("live/recovery flushes = %d/%d, want 1/0", firstCalls, recoveryCalls)
+ }
+}
+
func TestPendingBatcher_FlushAllDrainsPending(t *testing.T) {
f := &fakeTimerFactory{}
b := newTestBatcher(f)
diff --git a/server/internal/integrations/channel/engine/resolvers.go b/server/internal/integrations/channel/engine/resolvers.go
index e2bade266c..9c0998bcec 100644
--- a/server/internal/integrations/channel/engine/resolvers.go
+++ b/server/internal/integrations/channel/engine/resolvers.go
@@ -126,6 +126,21 @@ type AppendResult struct {
// DedupMarked is true when AppendMessage finalized the dedup claim in its
// own tx; the Router then skips the post-pipeline finalize.
DedupMarked bool
+ // ContextRevision is the durable agent-visible context generation assigned
+ // to this message. The batcher keys and task snapshot use it as a boundary.
+ ContextRevision int64
+ // PendingContexts includes every generation with durable unowned input and
+ // its authenticated sender snapshot. It re-arms debounce windows lost on
+ // process crash without borrowing the sender of a later generation.
+ PendingContexts []PendingContext
+}
+
+// PendingContext identifies durable unowned input that needs a run timer. The
+// initiator can be absent only for legacy or corrupt data; recovery fails
+// closed for such older generations rather than impersonating a new sender.
+type PendingContext struct {
+ Revision int64
+ InitiatorUserID pgtype.UUID
}
// BindMediaParams carries stored media references to the post-append
@@ -201,7 +216,7 @@ type Deduper interface {
// rotated mid-flight.
type SessionBinder interface {
EnsureSession(ctx context.Context, p EnsureSessionParams) (pgtype.UUID, error)
- MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) error
+ MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error
AppendMessage(ctx context.Context, p AppendParams) (AppendResult, error)
BindMedia(ctx context.Context, p BindMediaParams) error
}
@@ -334,7 +349,7 @@ type IssueCreator interface {
// TaskEnqueuer is the narrow subset of service.TaskService the Router needs to
// trigger a chat run. Shared across platforms.
type TaskEnqueuer interface {
- EnqueueChatTask(ctx context.Context, session db.ChatSession, initiatorUserID pgtype.UUID, forceFreshSession bool) (db.AgentTaskQueue, error)
+ EnqueueChannelChatTask(ctx context.Context, session db.ChatSession, initiatorUserID pgtype.UUID, forceFreshSession bool, contextRevision int64) (db.AgentTaskQueue, error)
PromoteChannelChatTasksIfMediaReady(ctx context.Context, sessionID pgtype.UUID) error
PromoteDeferredChannelIssueTask(ctx context.Context, taskID pgtype.UUID) error
}
diff --git a/server/internal/integrations/channel/engine/router.go b/server/internal/integrations/channel/engine/router.go
index ffddc34199..0ac99ed2c3 100644
--- a/server/internal/integrations/channel/engine/router.go
+++ b/server/internal/integrations/channel/engine/router.go
@@ -350,7 +350,7 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe
// ForceFresh is a task-dispatch property. A bare command has no useful
// task to dispatch, so remember the intent and apply it to the next real
// message instead of writing or running an empty turn.
- if err := set.Session.MarkPendingFresh(ctx, sessionID); err != nil {
+ if err := set.Session.MarkPendingFresh(ctx, sessionID, msg.MessageID); err != nil {
return Result{}, finalizeRelease, fmt.Errorf("persist fresh command: %w", err)
}
return Result{
@@ -502,7 +502,28 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe
// and the OutboundReplier still fires — only the debounced run trigger
// (and therefore the typing indicator) is suppressed.
if !msg.SkipAgentRun {
- r.scheduleRun(set, inst, msg, sessionID, identity.UserID)
+ pendingContexts := appendRes.PendingContexts
+ if len(pendingContexts) == 0 {
+ // Test and third-party SessionBinder implementations created before the
+ // crash-recovery field still schedule the appended generation normally.
+ pendingContexts = []PendingContext{{
+ Revision: appendRes.ContextRevision, InitiatorUserID: identity.UserID,
+ }}
+ }
+ for _, pending := range pendingContexts {
+ revision := pending.Revision
+ forceFresh := revision == appendRes.ContextRevision && msg.ForceFresh
+ if revision == appendRes.ContextRevision {
+ r.scheduleRunWithFresh(set, inst, msg, sessionID, identity.UserID, forceFresh, revision)
+ } else if pending.InitiatorUserID.Valid {
+ r.scheduleRecoveredRun(set, inst, msg, sessionID, pending.InitiatorUserID, revision)
+ } else {
+ slog.Warn("skipping recovered channel context without initiator snapshot",
+ "chat_session_id", util.UUIDToString(sessionID),
+ "context_revision", revision,
+ )
+ }
+ }
res.runScheduled = true
}
if resolveMedia {
@@ -685,21 +706,35 @@ func (r *Router) finishMediaQueue(key string, done chan struct{}) {
// scheduleRun hands the per-session run trigger to the debouncer (or fires it
// inline when batching is disabled).
-func (r *Router) scheduleRun(set ResolverSet, inst ResolvedInstallation, msg channel.InboundMessage, sessionID, initiatorUserID pgtype.UUID) {
- fresh := msg.ForceFresh
+func (r *Router) scheduleRun(set ResolverSet, inst ResolvedInstallation, msg channel.InboundMessage, sessionID, initiatorUserID pgtype.UUID, contextRevision int64) {
+ r.scheduleRunWithFresh(set, inst, msg, sessionID, initiatorUserID, msg.ForceFresh, contextRevision)
+}
+
+func (r *Router) scheduleRunWithFresh(set ResolverSet, inst ResolvedInstallation, msg channel.InboundMessage, sessionID, initiatorUserID pgtype.UUID, fresh bool, contextRevision int64) {
+ r.scheduleRunMode(set, inst, msg, sessionID, initiatorUserID, fresh, contextRevision, true)
+}
+
+func (r *Router) scheduleRecoveredRun(set ResolverSet, inst ResolvedInstallation, msg channel.InboundMessage, sessionID, initiatorUserID pgtype.UUID, contextRevision int64) {
+ r.scheduleRunMode(set, inst, msg, sessionID, initiatorUserID, false, contextRevision, false)
+}
+
+func (r *Router) scheduleRunMode(set ResolverSet, inst ResolvedInstallation, msg channel.InboundMessage, sessionID, initiatorUserID pgtype.UUID, fresh bool, contextRevision int64, replace bool) {
if r.batcher == nil {
- r.flushChatRun(set, inst, msg, sessionID, initiatorUserID, fresh)
+ r.flushChatRun(set, inst, msg, sessionID, initiatorUserID, fresh, contextRevision)
return
}
- key := keyForSession(sessionID)
+ key := keyForSessionContext(sessionID, contextRevision)
flush := func() {
- // A later message may replace this closure inside the debounce window.
- // AppendMessage persists ForceFresh on the channel binding, and
- // EnqueueChatTask consumes it transactionally, so correctness does not
- // depend on which message's in-memory closure wins.
- r.flushChatRun(set, inst, msg, sessionID, initiatorUserID, fresh)
+ // A later message in this same durable context generation may replace
+ // the closure. /new advances the generation and therefore uses a distinct
+ // batch key; the pre-boundary flush remains armed independently.
+ r.flushChatRun(set, inst, msg, sessionID, initiatorUserID, fresh, contextRevision)
+ }
+ if replace {
+ r.batcher.Schedule(key, flush)
+ } else {
+ r.batcher.ScheduleIfAbsent(key, flush)
}
- r.batcher.Schedule(key, flush)
}
// chatRunFlushTimeout bounds the detached flush (session reload + enqueue +
@@ -709,7 +744,7 @@ const chatRunFlushTimeout = 10 * time.Second
// flushChatRun is the debounced run-trigger: reload session, enqueue exactly
// one chat task for the window, and emit the offline/archived notice (only
// known here now) via the replier. Errors are logged, not returned.
-func (r *Router) flushChatRun(set ResolverSet, inst ResolvedInstallation, msg channel.InboundMessage, sessionID, initiatorUserID pgtype.UUID, forceFresh bool) {
+func (r *Router) flushChatRun(set ResolverSet, inst ResolvedInstallation, msg channel.InboundMessage, sessionID, initiatorUserID pgtype.UUID, forceFresh bool, contextRevision int64) {
ctx, cancel := context.WithTimeout(context.Background(), chatRunFlushTimeout)
defer cancel()
@@ -720,7 +755,7 @@ func (r *Router) flushChatRun(set ResolverSet, inst ResolvedInstallation, msg ch
r.clearTyping(ctx, set, sessionID)
return
}
- if _, err := r.tasks.EnqueueChatTask(ctx, session, initiatorUserID, forceFresh); err != nil {
+ if _, err := r.tasks.EnqueueChannelChatTask(ctx, session, initiatorUserID, forceFresh, contextRevision); err != nil {
// No task was enqueued, so no task lifecycle event will ever publish and
// the platform's bus-driven typing clear can never fire. Clear the
// indicator here (before any notice) so the "processing" reaction does
@@ -787,6 +822,10 @@ func keyForSession(sessionID pgtype.UUID) string {
return string(sessionID.Bytes[:])
}
+func keyForSessionContext(sessionID pgtype.UUID, contextRevision int64) string {
+ return fmt.Sprintf("%s:%d", keyForSession(sessionID), contextRevision)
+}
+
// applyFinalize flips the in-flight claim row to its terminal state,
// token-fenced. Best-effort: a transport failure cannot abort the outcome.
func (r *Router) applyFinalize(ctx context.Context, set ResolverSet, instID pgtype.UUID, messageID string, claimToken pgtype.UUID, action dedupFinalize) {
diff --git a/server/internal/integrations/channel/engine/router_test.go b/server/internal/integrations/channel/engine/router_test.go
index a83c22c6a1..ee62b15059 100644
--- a/server/internal/integrations/channel/engine/router_test.go
+++ b/server/internal/integrations/channel/engine/router_test.go
@@ -105,7 +105,7 @@ func (f *fakeBinder) EnsureSession(_ context.Context, p EnsureSessionParams) (pg
}
return f.ensureID, f.ensureErr
}
-func (f *fakeBinder) MarkPendingFresh(_ context.Context, _ pgtype.UUID) error {
+func (f *fakeBinder) MarkPendingFresh(_ context.Context, _ pgtype.UUID, _ string) error {
f.mu.Lock()
defer f.mu.Unlock()
f.pendingFresh++
@@ -299,7 +299,10 @@ type fakeTasks struct {
promotions int
issueTaskPromotions []pgtype.UUID
forceFresh bool
+ forceFreshArgs []bool
initiator pgtype.UUID
+ initiators []pgtype.UUID
+ contextRevisions []int64
err error
}
@@ -317,18 +320,31 @@ func (f *fakeTasks) PromoteDeferredChannelIssueTask(_ context.Context, taskID pg
return nil
}
-func (f *fakeTasks) EnqueueChatTask(_ context.Context, _ db.ChatSession, initiator pgtype.UUID, forceFresh bool) (db.AgentTaskQueue, error) {
+func (f *fakeTasks) EnqueueChannelChatTask(_ context.Context, _ db.ChatSession, initiator pgtype.UUID, forceFresh bool, contextRevision int64) (db.AgentTaskQueue, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.called = true
f.callCount++
f.forceFresh = forceFresh
+ f.forceFreshArgs = append(f.forceFreshArgs, forceFresh)
f.initiator = initiator
+ f.initiators = append(f.initiators, initiator)
+ f.contextRevisions = append(f.contextRevisions, contextRevision)
return db.AgentTaskQueue{}, f.err
}
func (f *fakeTasks) wasCalled() bool { f.mu.Lock(); defer f.mu.Unlock(); return f.called }
func (f *fakeTasks) freshArg() bool { f.mu.Lock(); defer f.mu.Unlock(); return f.forceFresh }
func (f *fakeTasks) calls() int { f.mu.Lock(); defer f.mu.Unlock(); return f.callCount }
+func (f *fakeTasks) revisions() []int64 {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]int64(nil), f.contextRevisions...)
+}
+func (f *fakeTasks) freshArgs() []bool {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]bool(nil), f.forceFreshArgs...)
+}
func (f *fakeTasks) promotionCalls() int {
f.mu.Lock()
defer f.mu.Unlock()
@@ -339,6 +355,11 @@ func (f *fakeTasks) initiatorArg() pgtype.UUID {
defer f.mu.Unlock()
return f.initiator
}
+func (f *fakeTasks) initiatorArgs() []pgtype.UUID {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]pgtype.UUID(nil), f.initiators...)
+}
type fakeReader struct {
session db.ChatSession
@@ -823,6 +844,118 @@ func TestRouter_MediaQueuePreservesSessionOrderWithoutCancellingRunBoundary(t *t
}
}
+func TestRouter_ContextGenerationsUseIndependentBatchWindows(t *testing.T) {
+ h := newHarness(t)
+ timers := &fakeTimerFactory{}
+ h.router.batcher = newTestBatcher(timers)
+ msg := p2pMessage(t)
+ sessionID := h.binder.ensureID
+ initiator := h.ident.id.UserID
+
+ h.router.scheduleRun(h.router.sets[channel.TypeFeishu], h.inst.inst, msg, sessionID, initiator, 1)
+ h.router.scheduleRun(h.router.sets[channel.TypeFeishu], h.inst.inst, msg, sessionID, initiator, 2)
+ if got := h.router.batcher.pendingCount(); got != 2 {
+ t.Fatalf("pending generation windows = %d, want 2", got)
+ }
+ timers.fireArmed()
+ if !waitFor(time.Second, func() bool { return h.tasks.calls() == 2 }) {
+ t.Fatalf("generation flushes = %d, want 2", h.tasks.calls())
+ }
+ revisions := h.tasks.revisions()
+ if len(revisions) != 2 || revisions[0] != 1 || revisions[1] != 2 {
+ t.Fatalf("enqueued context revisions = %v, want [1 2]", revisions)
+ }
+}
+
+func TestRouter_RearmsUnownedContextGenerationsAfterBatcherRestart(t *testing.T) {
+ h := newHarness(t)
+ timers := &fakeTimerFactory{}
+ h.router.batcher = newTestBatcher(timers)
+ h.binder.appendResult.ContextRevision = 2
+ alice := uuidFromString(t, "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")
+ bob := h.ident.id.UserID
+ h.binder.appendResult.PendingContexts = []PendingContext{
+ {Revision: 1, InitiatorUserID: alice},
+ {Revision: 2, InitiatorUserID: bob},
+ }
+ msg := p2pMessage(t)
+ msg.ForceFresh = true
+
+ if err := h.router.Handle(context.Background(), msg); err != nil {
+ t.Fatalf("Handle: %v", err)
+ }
+ if got := h.router.batcher.pendingCount(); got != 2 {
+ t.Fatalf("rearmed generation windows = %d, want 2", got)
+ }
+ timers.fireArmed()
+ if !waitFor(time.Second, func() bool { return h.tasks.calls() == 2 }) {
+ t.Fatalf("generation recovery flushes = %d, want 2", h.tasks.calls())
+ }
+ if got := h.tasks.revisions(); len(got) != 2 || got[0] != 1 || got[1] != 2 {
+ t.Fatalf("recovered context revisions = %v, want [1 2]", got)
+ }
+ if got := h.tasks.freshArgs(); len(got) != 2 || got[0] || !got[1] {
+ t.Fatalf("recovered force-fresh flags = %v, want [false true]", got)
+ }
+ if got := h.tasks.initiatorArgs(); len(got) != 2 || got[0] != alice || got[1] != bob {
+ t.Fatalf("recovered initiators = %v, want [%v %v]", got, alice, bob)
+ }
+}
+
+func TestRouter_RecoveryWithoutInitiatorFailsClosed(t *testing.T) {
+ h := newHarness(t)
+ timers := &fakeTimerFactory{}
+ h.router.batcher = newTestBatcher(timers)
+ h.binder.appendResult.ContextRevision = 2
+ h.binder.appendResult.PendingContexts = []PendingContext{
+ {Revision: 1},
+ {Revision: 2, InitiatorUserID: h.ident.id.UserID},
+ }
+
+ msg := p2pMessage(t)
+ msg.ForceFresh = true
+ if err := h.router.Handle(context.Background(), msg); err != nil {
+ t.Fatalf("Handle: %v", err)
+ }
+ if got := h.router.batcher.pendingCount(); got != 1 {
+ t.Fatalf("scheduled generation windows = %d, want 1", got)
+ }
+ timers.fireArmed()
+ if !waitFor(time.Second, func() bool { return h.tasks.calls() == 1 }) {
+ t.Fatalf("generation flushes = %d, want 1", h.tasks.calls())
+ }
+ if got := h.tasks.revisions(); len(got) != 1 || got[0] != 2 {
+ t.Fatalf("enqueued context revisions = %v, want [2]", got)
+ }
+}
+
+func TestRouter_RecoveryDoesNotDelayLiveOlderGeneration(t *testing.T) {
+ h := newHarness(t)
+ timers := &fakeTimerFactory{}
+ h.router.batcher = newTestBatcher(timers)
+ msg := p2pMessage(t)
+ h.router.scheduleRun(h.router.sets[channel.TypeFeishu], h.inst.inst, msg,
+ h.binder.ensureID, h.ident.id.UserID, 1)
+
+ h.binder.appendResult.ContextRevision = 2
+ h.binder.appendResult.PendingContexts = []PendingContext{
+ {Revision: 1, InitiatorUserID: h.ident.id.UserID},
+ {Revision: 2, InitiatorUserID: h.ident.id.UserID},
+ }
+ msg.ForceFresh = true
+ if err := h.router.Handle(context.Background(), msg); err != nil {
+ t.Fatalf("Handle: %v", err)
+ }
+ if got := timers.createdCount(); got != 2 {
+ t.Fatalf("timers created = %d, want 2; recovery reset the live revision-1 window", got)
+ }
+
+ timers.fireArmed()
+ if !waitFor(time.Second, func() bool { return h.tasks.calls() == 2 }) {
+ t.Fatalf("generation flushes = %d, want 2", h.tasks.calls())
+ }
+}
+
func TestRouter_ClaimLost_Drops(t *testing.T) {
h := newHarness(t)
h.binder.appendErr = ErrClaimLost
diff --git a/server/internal/integrations/channel/engine/session.go b/server/internal/integrations/channel/engine/session.go
index 815157fd18..0e61c9fe2d 100644
--- a/server/internal/integrations/channel/engine/session.go
+++ b/server/internal/integrations/channel/engine/session.go
@@ -47,7 +47,9 @@ type SessionQueries interface {
LockWorkspaceForChatSessionCreate(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error)
CreateChatSession(ctx context.Context, arg db.CreateChatSessionParams) (db.ChatSession, error)
CreateChannelChatSessionBinding(ctx context.Context, arg db.CreateChannelChatSessionBindingParams) (db.ChannelChatSessionBinding, error)
+ LockChatSessionForAppend(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error)
CreateChatMessage(ctx context.Context, arg db.CreateChatMessageParams) (db.ChatMessage, error)
+ ListUnownedChannelChatContextRevisions(ctx context.Context, chatSessionID pgtype.UUID) ([]PendingContext, error)
ClearChatMessageChannelMediaPending(ctx context.Context, arg db.ClearChatMessageChannelMediaPendingParams) error
LockIssueForChannelMediaBind(ctx context.Context, arg db.LockIssueForChannelMediaBindParams) (pgtype.UUID, error)
UpdateChatMessageContentForChannelMedia(ctx context.Context, arg db.UpdateChatMessageContentForChannelMediaParams) (int64, error)
@@ -56,7 +58,12 @@ type SessionQueries interface {
LinkAttachmentsToChatMessage(ctx context.Context, arg db.LinkAttachmentsToChatMessageParams) ([]pgtype.UUID, error)
ClaimChannelMediaPendingObjectsForBind(ctx context.Context, arg db.ClaimChannelMediaPendingObjectsForBindParams) ([]string, error)
TouchChatSession(ctx context.Context, id pgtype.UUID) error
- MarkChannelChatSessionPendingFresh(ctx context.Context, chatSessionID pgtype.UUID) (bool, error)
+ LockChannelChatSessionBindingForContext(ctx context.Context, chatSessionID pgtype.UUID) (db.ChannelChatSessionBinding, error)
+ LockChannelChatContextGenerationByRevision(ctx context.Context, arg db.LockChannelChatContextGenerationByRevisionParams) (db.ChannelChatContextGeneration, error)
+ EnsureChannelChatContextGeneration(ctx context.Context, chatSessionID pgtype.UUID) error
+ AdvanceChannelChatContextGeneration(ctx context.Context, arg db.AdvanceChannelChatContextGenerationParams) (db.AdvanceChannelChatContextGenerationRow, error)
+ ResolveChannelChatContextHistoryStart(ctx context.Context, arg db.ResolveChannelChatContextHistoryStartParams) error
+ SetChannelChatContextInitiator(ctx context.Context, arg db.SetChannelChatContextInitiatorParams) (pgtype.UUID, error)
UpdateChannelChatSessionBindingReplyTarget(ctx context.Context, arg db.UpdateChannelChatSessionBindingReplyTargetParams) error
MarkChannelInboundDedupProcessed(ctx context.Context, arg db.MarkChannelInboundDedupProcessedParams) (int64, error)
}
@@ -79,11 +86,34 @@ func (a dbSessionQueries) CreateChatSession(ctx context.Context, arg db.CreateCh
return a.q.CreateChatSession(ctx, arg)
}
func (a dbSessionQueries) CreateChannelChatSessionBinding(ctx context.Context, arg db.CreateChannelChatSessionBindingParams) (db.ChannelChatSessionBinding, error) {
- return a.q.CreateChannelChatSessionBinding(ctx, arg)
+ row, err := a.q.CreateChannelChatSessionBinding(ctx, arg)
+ return db.ChannelChatSessionBinding{
+ ID: row.ID, ChatSessionID: row.ChatSessionID, InstallationID: row.InstallationID,
+ ChannelType: row.ChannelType, ChannelChatID: row.ChannelChatID, ChatType: row.ChatType,
+ LastMessageID: row.LastMessageID, LastThreadID: row.LastThreadID, Config: row.Config,
+ CreatedAt: row.CreatedAt, PendingFresh: row.PendingFresh, ContextRevision: row.ContextRevision,
+ }, err
+}
+func (a dbSessionQueries) LockChatSessionForAppend(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error) {
+ return a.q.LockChatSessionForAppend(ctx, id)
}
func (a dbSessionQueries) CreateChatMessage(ctx context.Context, arg db.CreateChatMessageParams) (db.ChatMessage, error) {
return a.q.CreateChatMessage(ctx, arg)
}
+func (a dbSessionQueries) ListUnownedChannelChatContextRevisions(ctx context.Context, chatSessionID pgtype.UUID) ([]PendingContext, error) {
+ rows, err := a.q.ListUnownedChannelChatContextRevisions(ctx, chatSessionID)
+ if err != nil {
+ return nil, err
+ }
+ contexts := make([]PendingContext, 0, len(rows))
+ for _, row := range rows {
+ contexts = append(contexts, PendingContext{
+ Revision: row.ContextRevision,
+ InitiatorUserID: row.InitiatorUserID,
+ })
+ }
+ return contexts, nil
+}
func (a dbSessionQueries) ClearChatMessageChannelMediaPending(ctx context.Context, arg db.ClearChatMessageChannelMediaPendingParams) error {
return a.q.ClearChatMessageChannelMediaPending(ctx, arg)
}
@@ -109,8 +139,23 @@ func (a dbSessionQueries) ClaimChannelMediaPendingObjectsForBind(ctx context.Con
func (a dbSessionQueries) TouchChatSession(ctx context.Context, id pgtype.UUID) error {
return a.q.TouchChatSession(ctx, id)
}
-func (a dbSessionQueries) MarkChannelChatSessionPendingFresh(ctx context.Context, chatSessionID pgtype.UUID) (bool, error) {
- return a.q.MarkChannelChatSessionPendingFresh(ctx, chatSessionID)
+func (a dbSessionQueries) LockChannelChatSessionBindingForContext(ctx context.Context, chatSessionID pgtype.UUID) (db.ChannelChatSessionBinding, error) {
+ return a.q.LockChannelChatSessionBindingForContext(ctx, chatSessionID)
+}
+func (a dbSessionQueries) LockChannelChatContextGenerationByRevision(ctx context.Context, arg db.LockChannelChatContextGenerationByRevisionParams) (db.ChannelChatContextGeneration, error) {
+ return a.q.LockChannelChatContextGenerationByRevision(ctx, arg)
+}
+func (a dbSessionQueries) EnsureChannelChatContextGeneration(ctx context.Context, chatSessionID pgtype.UUID) error {
+ return a.q.EnsureChannelChatContextGeneration(ctx, chatSessionID)
+}
+func (a dbSessionQueries) AdvanceChannelChatContextGeneration(ctx context.Context, arg db.AdvanceChannelChatContextGenerationParams) (db.AdvanceChannelChatContextGenerationRow, error) {
+ return a.q.AdvanceChannelChatContextGeneration(ctx, arg)
+}
+func (a dbSessionQueries) ResolveChannelChatContextHistoryStart(ctx context.Context, arg db.ResolveChannelChatContextHistoryStartParams) error {
+ return a.q.ResolveChannelChatContextHistoryStart(ctx, arg)
+}
+func (a dbSessionQueries) SetChannelChatContextInitiator(ctx context.Context, arg db.SetChannelChatContextInitiatorParams) (pgtype.UUID, error) {
+ return a.q.SetChannelChatContextInitiator(ctx, arg)
}
func (a dbSessionQueries) UpdateChannelChatSessionBindingReplyTarget(ctx context.Context, arg db.UpdateChannelChatSessionBindingReplyTargetParams) error {
return a.q.UpdateChannelChatSessionBindingReplyTarget(ctx, arg)
@@ -325,13 +370,57 @@ func (s *ChatSession) AppendUserMessage(ctx context.Context, in AppendInput) (Ap
}
defer tx.Rollback(ctx)
qtx := s.q.WithTx(tx)
-
commandSource := in.CommandText
if commandSource == "" {
commandSource = in.Body
}
cmd, _ := ParseIssueCommand(commandSource)
+ // Context paths acquire chat_session before binding and generation. This
+ // also keeps the later TouchChatSession update from introducing the reverse
+ // binding -> chat_session edge against task enqueue.
+ if _, err := qtx.LockChatSessionForAppend(ctx, in.SessionID); err != nil {
+ return AppendResult{}, fmt.Errorf("lock chat session for append: %w", err)
+ }
+ binding, err := qtx.LockChannelChatSessionBindingForContext(ctx, in.SessionID)
+ if err != nil {
+ return AppendResult{}, fmt.Errorf("lock channel chat binding: %w", err)
+ }
+ if err := qtx.EnsureChannelChatContextGeneration(ctx, in.SessionID); err != nil {
+ return AppendResult{}, fmt.Errorf("ensure channel chat context: %w", err)
+ }
+ contextState, err := qtx.LockChannelChatContextGenerationByRevision(ctx, db.LockChannelChatContextGenerationByRevisionParams{
+ ChatSessionID: in.SessionID, Revision: binding.ContextRevision,
+ })
+ if err != nil {
+ return AppendResult{}, fmt.Errorf("lock channel chat context: %w", err)
+ }
+ contextRevision := binding.ContextRevision
+ if in.ForceFresh || (binding.PendingFresh && !contextState.PendingFresh) {
+ advanced, err := qtx.AdvanceChannelChatContextGeneration(ctx, db.AdvanceChannelChatContextGenerationParams{
+ ChatSessionID: in.SessionID, CurrentRevision: contextRevision,
+ HistoryBoundaryMessageID: textOrNull(in.MessageID), HasMessageBody: true,
+ })
+ if err != nil {
+ return AppendResult{}, fmt.Errorf("advance channel chat context: %w", err)
+ }
+ contextRevision = advanced.Revision
+ } else if contextState.HistoryBoundaryPending && in.MessageID != "" {
+ if err := qtx.ResolveChannelChatContextHistoryStart(ctx, db.ResolveChannelChatContextHistoryStartParams{
+ HistoryStartMessageID: textOrNull(in.MessageID), ChatSessionID: in.SessionID, Revision: contextRevision,
+ }); err != nil {
+ return AppendResult{}, fmt.Errorf("resolve channel chat history boundary: %w", err)
+ }
+ }
+ // A channel command is excluded from agent input, so it must not replace
+ // the principal used to recover earlier unowned agent-visible messages.
+ if contextRevision > 0 && cmd == nil {
+ if _, err := qtx.SetChannelChatContextInitiator(ctx, db.SetChannelChatContextInitiatorParams{
+ ChatSessionID: in.SessionID, Revision: contextRevision, InitiatorUserID: in.Sender,
+ }); err != nil {
+ return AppendResult{}, fmt.Errorf("snapshot channel context initiator: %w", err)
+ }
+ }
// channel_ingested is the immutable provenance the cancel path gates on:
// it must be stamped in the same transaction as the message so no later
// binding deletion (archive, installation rebind) can strip it.
@@ -343,18 +432,18 @@ func (s *ChatSession) AppendUserMessage(ctx context.Context, in AppendInput) (Ap
MessageKind: textOrNullIf(cmd != nil, channelCommandMessageKind),
ChannelMediaPendingSecs: pgtype.Float8{Float64: in.MediaPendingSeconds, Valid: in.MediaPendingSeconds > 0},
ChannelIngested: pgtype.Bool{Bool: true, Valid: true},
+ ChannelContextRevision: pgtype.Int8{Int64: contextRevision, Valid: contextRevision > 0},
})
if err != nil {
return AppendResult{}, fmt.Errorf("create chat message: %w", err)
}
+ pendingContexts, err := qtx.ListUnownedChannelChatContextRevisions(ctx, in.SessionID)
+ if err != nil {
+ return AppendResult{}, fmt.Errorf("list pending channel contexts: %w", err)
+ }
if err := qtx.TouchChatSession(ctx, in.SessionID); err != nil {
return AppendResult{}, fmt.Errorf("touch chat session: %w", err)
}
- if in.ForceFresh {
- if _, err := qtx.MarkChannelChatSessionPendingFresh(ctx, in.SessionID); err != nil {
- return AppendResult{}, fmt.Errorf("mark pending fresh: %w", err)
- }
- }
// Record the latest trigger so the decoupled outbound patcher can thread
// its reply back into the originating topic.
@@ -389,14 +478,48 @@ func (s *ChatSession) AppendUserMessage(ctx context.Context, in AppendInput) (Ap
if err := tx.Commit(ctx); err != nil {
return AppendResult{}, fmt.Errorf("commit: %w", err)
}
- return AppendResult{MessageID: msg.ID, IssueCommand: cmd, DedupMarked: markedInTx}, nil
+ return AppendResult{
+ MessageID: msg.ID,
+ IssueCommand: cmd,
+ DedupMarked: markedInTx,
+ ContextRevision: contextRevision,
+ PendingContexts: pendingContexts,
+ }, nil
}
// MarkPendingFresh persists a bare `/new` command. Non-bare `/new` messages
// mark the same flag inside AppendUserMessage's transaction instead.
-func (s *ChatSession) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) error {
- if _, err := s.q.MarkChannelChatSessionPendingFresh(ctx, sessionID); err != nil {
- return fmt.Errorf("mark pending fresh: %w", err)
+func (s *ChatSession) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error {
+ tx, err := s.tx.Begin(ctx)
+ if err != nil {
+ return fmt.Errorf("begin fresh context tx: %w", err)
+ }
+ defer tx.Rollback(ctx)
+ qtx := s.q.WithTx(tx)
+ if _, err := qtx.LockChatSessionForAppend(ctx, sessionID); err != nil {
+ return fmt.Errorf("lock chat session for fresh context: %w", err)
+ }
+ binding, err := qtx.LockChannelChatSessionBindingForContext(ctx, sessionID)
+ if err != nil {
+ return fmt.Errorf("lock channel chat binding: %w", err)
+ }
+ if err := qtx.EnsureChannelChatContextGeneration(ctx, sessionID); err != nil {
+ return fmt.Errorf("ensure channel chat context: %w", err)
+ }
+ _, err = qtx.LockChannelChatContextGenerationByRevision(ctx, db.LockChannelChatContextGenerationByRevisionParams{
+ ChatSessionID: sessionID, Revision: binding.ContextRevision,
+ })
+ if err != nil {
+ return fmt.Errorf("lock channel chat context: %w", err)
+ }
+ if _, err := qtx.AdvanceChannelChatContextGeneration(ctx, db.AdvanceChannelChatContextGenerationParams{
+ ChatSessionID: sessionID, CurrentRevision: binding.ContextRevision,
+ HistoryBoundaryMessageID: textOrNull(messageID), HasMessageBody: false,
+ }); err != nil {
+ return fmt.Errorf("advance channel chat context: %w", err)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return fmt.Errorf("commit fresh context: %w", err)
}
return nil
}
diff --git a/server/internal/integrations/channel/engine/session_db_test.go b/server/internal/integrations/channel/engine/session_db_test.go
index 680555baf9..dc57f33f29 100644
--- a/server/internal/integrations/channel/engine/session_db_test.go
+++ b/server/internal/integrations/channel/engine/session_db_test.go
@@ -45,15 +45,42 @@ func sessionPersistenceTestDB(t *testing.T) *pgxpool.Pool {
type sessionPersistenceFixture struct {
workspaceID pgtype.UUID
userID pgtype.UUID
+ agentID pgtype.UUID
sessionID pgtype.UUID
}
func seedSessionPersistenceFixture(t *testing.T, pool *pgxpool.Pool) sessionPersistenceFixture {
+ f := seedSessionPersistenceFixtureWithoutChannel(t, pool)
+ ctx := context.Background()
+ var installationID pgtype.UUID
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO channel_installation (
+ workspace_id, agent_id, channel_type, config, status, installer_user_id
+ ) VALUES ($1, $2, 'lark', '{}'::jsonb, 'active', $3)
+ RETURNING id
+ `, f.workspaceID, f.agentID, f.userID).Scan(&installationID); err != nil {
+ t.Fatalf("create channel installation: %v", err)
+ }
+ if _, err := db.New(pool).CreateChannelChatSessionBinding(ctx, db.CreateChannelChatSessionBindingParams{
+ ChatSessionID: f.sessionID, InstallationID: installationID, ChannelType: "lark",
+ ChannelChatID: "channel-media-" + fmt.Sprint(time.Now().UnixNano()), ChatType: "p2p", Config: []byte("{}"),
+ }); err != nil {
+ t.Fatalf("create channel binding: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_chat_context_generation WHERE chat_session_id = $1`, f.sessionID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_chat_session_binding WHERE chat_session_id = $1`, f.sessionID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_installation WHERE id = $1`, installationID)
+ })
+ return f
+}
+
+func seedSessionPersistenceFixtureWithoutChannel(t *testing.T, pool *pgxpool.Pool) sessionPersistenceFixture {
t.Helper()
ctx := context.Background()
suffix := time.Now().UnixNano()
var f sessionPersistenceFixture
- var runtimeID, agentID pgtype.UUID
+ var runtimeID pgtype.UUID
if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id`,
"Channel media test", fmt.Sprintf("channel-media-%[email protected]", suffix)).Scan(&f.userID); err != nil {
@@ -85,19 +112,119 @@ func seedSessionPersistenceFixture(t *testing.T, pool *pgxpool.Pool) sessionPers
if err := pool.QueryRow(ctx, `
INSERT INTO agent (workspace_id, name, runtime_mode, runtime_id, owner_id)
VALUES ($1, $2, 'local', $3, $4)
- RETURNING id`, f.workspaceID, fmt.Sprintf("channel-media-agent-%d", suffix), runtimeID, f.userID).Scan(&agentID); err != nil {
+ RETURNING id`, f.workspaceID, fmt.Sprintf("channel-media-agent-%d", suffix), runtimeID, f.userID).Scan(&f.agentID); err != nil {
t.Fatalf("create agent: %v", err)
}
if err := pool.QueryRow(ctx, `
INSERT INTO chat_session (workspace_id, agent_id, creator_id, title)
VALUES ($1, $2, $3, 'Channel media test')
- RETURNING id`, f.workspaceID, agentID, f.userID).Scan(&f.sessionID); err != nil {
+ RETURNING id`, f.workspaceID, f.agentID, f.userID).Scan(&f.sessionID); err != nil {
t.Fatalf("create chat session: %v", err)
}
return f
}
+func TestAppendUserMessage_AdvancesPendingFreshForBindingCreatedByLegacyServer(t *testing.T) {
+ pool := sessionPersistenceTestDB(t)
+ fixture := seedSessionPersistenceFixtureWithoutChannel(t, pool)
+ ctx := context.Background()
+ queries := db.New(pool)
+ session := NewChatSession(queries, pool, channel.TypeFeishu, SessionTitles{})
+
+ var installationID pgtype.UUID
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO channel_installation (
+ workspace_id, agent_id, channel_type, config, status, installer_user_id
+ )
+ VALUES ($1, $2, 'lark', '{}'::jsonb, 'active', $3)
+ RETURNING id
+ `, fixture.workspaceID, fixture.agentID, fixture.userID).Scan(&installationID); err != nil {
+ t.Fatalf("create legacy installation: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_chat_context_generation WHERE chat_session_id = $1`, fixture.sessionID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_chat_session_binding WHERE chat_session_id = $1`, fixture.sessionID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_installation WHERE id = $1`, installationID)
+ })
+
+ // Simulate an old server running after the schema migration: it creates the
+ // legacy binding shape, writes a normal turn, then records a bare /new only
+ // on channel_chat_session_binding. No generation row exists yet.
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO channel_chat_session_binding (
+ chat_session_id, installation_id, channel_type, channel_chat_id, chat_type
+ )
+ VALUES ($1, $2, 'lark', 'legacy-created-binding', 'p2p')
+ `, fixture.sessionID, installationID); err != nil {
+ t.Fatalf("create legacy binding: %v", err)
+ }
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO chat_message (chat_session_id, role, content, channel_ingested)
+ VALUES ($1, 'user', 'old context', TRUE)
+ `, fixture.sessionID); err != nil {
+ t.Fatalf("create legacy context message: %v", err)
+ }
+ if _, err := pool.Exec(ctx, `
+ UPDATE channel_chat_session_binding SET pending_fresh = TRUE
+ WHERE chat_session_id = $1
+ `, fixture.sessionID); err != nil {
+ t.Fatalf("mark legacy pending fresh: %v", err)
+ }
+
+ result, err := session.AppendUserMessage(ctx, AppendInput{
+ SessionID: fixture.sessionID,
+ Sender: fixture.userID,
+ Body: "new context",
+ MessageID: "new-context-message",
+ })
+ if err != nil {
+ t.Fatalf("append through new server: %v", err)
+ }
+ if result.ContextRevision != 2 {
+ t.Fatalf("new message revision = %d, want 2", result.ContextRevision)
+ }
+ if len(result.PendingContexts) != 2 || result.PendingContexts[0].Revision != 1 || result.PendingContexts[1].Revision != 2 {
+ t.Fatalf("pending contexts = %v, want revisions [1 2]", result.PendingContexts)
+ }
+ if result.PendingContexts[0].InitiatorUserID.Valid {
+ t.Fatalf("legacy context initiator = %v, want missing fail-closed snapshot", result.PendingContexts[0].InitiatorUserID)
+ }
+ if result.PendingContexts[1].InitiatorUserID != fixture.userID {
+ t.Fatalf("new context initiator = %v, want %v", result.PendingContexts[1].InitiatorUserID, fixture.userID)
+ }
+
+ var bindingRevision int64
+ var revisions []int64
+ if err := pool.QueryRow(ctx, `
+ SELECT context_revision FROM channel_chat_session_binding
+ WHERE chat_session_id = $1
+ `, fixture.sessionID).Scan(&bindingRevision); err != nil {
+ t.Fatalf("load repaired binding revision: %v", err)
+ }
+ rows, err := pool.Query(ctx, `
+ SELECT revision FROM channel_chat_context_generation
+ WHERE chat_session_id = $1 ORDER BY revision
+ `, fixture.sessionID)
+ if err != nil {
+ t.Fatalf("list repaired generations: %v", err)
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var revision int64
+ if err := rows.Scan(&revision); err != nil {
+ t.Fatalf("scan repaired generation: %v", err)
+ }
+ revisions = append(revisions, revision)
+ }
+ if err := rows.Err(); err != nil {
+ t.Fatalf("iterate repaired generations: %v", err)
+ }
+ if bindingRevision != 2 || len(revisions) != 2 || revisions[0] != 1 || revisions[1] != 2 {
+ t.Fatalf("repaired context = binding:%d generations:%v, want 2/[1 2]", bindingRevision, revisions)
+ }
+}
+
func TestChannelIssueCommandIsExcludedFromLaterChatTaskBatch(t *testing.T) {
pool := sessionPersistenceTestDB(t)
fixture := seedSessionPersistenceFixture(t, pool)
diff --git a/server/internal/integrations/channel/engine/session_test.go b/server/internal/integrations/channel/engine/session_test.go
index 1cb0dbca66..4e575ff68a 100644
--- a/server/internal/integrations/channel/engine/session_test.go
+++ b/server/internal/integrations/channel/engine/session_test.go
@@ -26,14 +26,36 @@ func uid(b byte) pgtype.UUID {
// fakeTx satisfies pgx.Tx by embedding the (nil) interface; the ChatSession
// service only calls Commit/Rollback, which we override as no-ops.
-type fakeTx struct{ pgx.Tx }
+type fakeTx struct {
+ pgx.Tx
+ commitErr error
+ committed bool
+ rolledBack bool
+}
-func (fakeTx) Commit(context.Context) error { return nil }
-func (fakeTx) Rollback(context.Context) error { return nil }
+func (tx *fakeTx) Commit(context.Context) error {
+ tx.committed = true
+ return tx.commitErr
+}
+func (tx *fakeTx) Rollback(context.Context) error {
+ tx.rolledBack = true
+ return nil
+}
-type fakeTxStarter struct{}
+type fakeTxStarter struct {
+ tx *fakeTx
+ beginErr error
+}
-func (fakeTxStarter) Begin(context.Context) (pgx.Tx, error) { return fakeTx{}, nil }
+func (s fakeTxStarter) Begin(context.Context) (pgx.Tx, error) {
+ if s.beginErr != nil {
+ return nil, s.beginErr
+ }
+ if s.tx != nil {
+ return s.tx, nil
+ }
+ return &fakeTx{}, nil
+}
// fakeSessionQueries is an in-memory SessionQueries for unit tests.
type fakeSessionQueries struct {
@@ -58,14 +80,24 @@ type fakeSessionQueries struct {
reconcilerOwnedKeys map[string]bool
issueLookupErr error
- markRows int64 // MarkChannelInboundDedupProcessed result
- pendingFresh bool
- createBindingErr error // simulate a unique violation on create
- raceWinner pgtype.UUID
+ markRows int64 // MarkChannelInboundDedupProcessed result
+ pendingFresh bool
+ legacyPendingFresh bool
+ contextRevision int64
+ contextInitiator pgtype.UUID
+ boundaryPending bool
+ ensureContextErr error
+ lockContextErr error
+ advanceContextErr error
+ resolveContextErr error
+ setInitiatorErr error
+ pendingContextsErr error
+ createBindingErr error // simulate a unique violation on create
+ raceWinner pgtype.UUID
}
func newFake() *fakeSessionQueries {
- return &fakeSessionQueries{bindings: map[string]pgtype.UUID{}, markRows: 1, messageID: uid(42), updateMediaRows: 1}
+ return &fakeSessionQueries{bindings: map[string]pgtype.UUID{}, markRows: 1, messageID: uid(42), updateMediaRows: 1, contextRevision: 1}
}
func bindKey(inst pgtype.UUID, chat string) string { return fmt.Sprintf("%x|%s", inst.Bytes, chat) }
@@ -101,12 +133,23 @@ func (f *fakeSessionQueries) CreateChannelChatSessionBinding(_ context.Context,
return db.ChannelChatSessionBinding{ChatSessionID: arg.ChatSessionID}, nil
}
+func (f *fakeSessionQueries) LockChatSessionForAppend(_ context.Context, id pgtype.UUID) (pgtype.UUID, error) {
+ return id, nil
+}
+
func (f *fakeSessionQueries) CreateChatMessage(_ context.Context, arg db.CreateChatMessageParams) (db.ChatMessage, error) {
f.messages = append(f.messages, arg.Content)
f.lastCreate = arg
return db.ChatMessage{ID: f.messageID}, nil
}
+func (f *fakeSessionQueries) ListUnownedChannelChatContextRevisions(context.Context, pgtype.UUID) ([]PendingContext, error) {
+ if f.pendingContextsErr != nil {
+ return nil, f.pendingContextsErr
+ }
+ return []PendingContext{{Revision: f.contextRevision, InitiatorUserID: f.contextInitiator}}, nil
+}
+
func (f *fakeSessionQueries) ClearChatMessageChannelMediaPending(context.Context, db.ClearChatMessageChannelMediaPendingParams) error {
f.mediaCleared++
return nil
@@ -159,9 +202,53 @@ func (f *fakeSessionQueries) TouchChatSession(context.Context, pgtype.UUID) erro
return nil
}
-func (f *fakeSessionQueries) MarkChannelChatSessionPendingFresh(context.Context, pgtype.UUID) (bool, error) {
+func (f *fakeSessionQueries) LockChannelChatSessionBindingForContext(context.Context, pgtype.UUID) (db.ChannelChatSessionBinding, error) {
+ if f.lockContextErr != nil {
+ return db.ChannelChatSessionBinding{}, f.lockContextErr
+ }
+ return db.ChannelChatSessionBinding{
+ ContextRevision: f.contextRevision, PendingFresh: f.legacyPendingFresh,
+ }, nil
+}
+
+func (f *fakeSessionQueries) LockChannelChatContextGenerationByRevision(context.Context, db.LockChannelChatContextGenerationByRevisionParams) (db.ChannelChatContextGeneration, error) {
+ if f.lockContextErr != nil {
+ return db.ChannelChatContextGeneration{}, f.lockContextErr
+ }
+ return db.ChannelChatContextGeneration{
+ Revision: f.contextRevision, PendingFresh: f.pendingFresh,
+ HistoryBoundaryPending: f.boundaryPending,
+ }, nil
+}
+
+func (f *fakeSessionQueries) EnsureChannelChatContextGeneration(context.Context, pgtype.UUID) error {
+ return f.ensureContextErr
+}
+
+func (f *fakeSessionQueries) AdvanceChannelChatContextGeneration(_ context.Context, arg db.AdvanceChannelChatContextGenerationParams) (db.AdvanceChannelChatContextGenerationRow, error) {
+ if f.advanceContextErr != nil {
+ return db.AdvanceChannelChatContextGenerationRow{}, f.advanceContextErr
+ }
+ f.contextRevision = arg.CurrentRevision + 1
f.pendingFresh = true
- return true, nil
+ f.boundaryPending = !arg.HasMessageBody
+ return db.AdvanceChannelChatContextGenerationRow{Revision: f.contextRevision, PendingFresh: true, HistoryBoundaryPending: f.boundaryPending}, nil
+}
+
+func (f *fakeSessionQueries) ResolveChannelChatContextHistoryStart(context.Context, db.ResolveChannelChatContextHistoryStartParams) error {
+ if f.resolveContextErr != nil {
+ return f.resolveContextErr
+ }
+ f.boundaryPending = false
+ return nil
+}
+
+func (f *fakeSessionQueries) SetChannelChatContextInitiator(_ context.Context, arg db.SetChannelChatContextInitiatorParams) (pgtype.UUID, error) {
+ if f.setInitiatorErr != nil {
+ return pgtype.UUID{}, f.setInitiatorErr
+ }
+ f.contextInitiator = arg.InitiatorUserID
+ return arg.InitiatorUserID, nil
}
func (f *fakeSessionQueries) UpdateChannelChatSessionBindingReplyTarget(context.Context, db.UpdateChannelChatSessionBindingReplyTargetParams) error {
@@ -323,6 +410,20 @@ func TestAppendUserMessage_IssueCommand(t *testing.T) {
}
}
+func TestAppendUserMessage_ChannelCommandDoesNotReplaceContextInitiator(t *testing.T) {
+ f := newFake()
+ f.contextInitiator = uid(7)
+ s := newTestSession(f)
+ if _, err := s.AppendUserMessage(context.Background(), AppendInput{
+ SessionID: uid(1), Sender: uid(8), Body: "/issue Fix bug", MessageID: "m1",
+ }); err != nil {
+ t.Fatalf("AppendUserMessage: %v", err)
+ }
+ if f.contextInitiator != uid(7) {
+ t.Fatalf("context initiator = %v, want prior agent-input sender %v", f.contextInitiator, uid(7))
+ }
+}
+
func TestAppendUserMessage_CommandTextOverridesEnrichedBody(t *testing.T) {
f := newFake()
s := newTestSession(f)
@@ -682,17 +783,148 @@ func TestAppendUserMessage_FreshMessagePersistsPendingIntent(t *testing.T) {
if !f.pendingFresh {
t.Fatal("fresh message did not persist pending intent in the append transaction")
}
+ if f.contextRevision != 2 || !f.lastCreate.ChannelContextRevision.Valid || f.lastCreate.ChannelContextRevision.Int64 != 2 {
+ t.Fatalf("fresh message context = generation %d / row %+v, want 2", f.contextRevision, f.lastCreate.ChannelContextRevision)
+ }
}
func TestMarkPendingFresh_BareCommandPersistsIntent(t *testing.T) {
f := newFake()
s := newTestSession(f)
- if err := s.MarkPendingFresh(context.Background(), uid(1)); err != nil {
+ if err := s.MarkPendingFresh(context.Background(), uid(1), "m1"); err != nil {
t.Fatalf("MarkPendingFresh: %v", err)
}
if !f.pendingFresh {
t.Fatal("bare fresh command did not persist pending intent")
}
+ if f.contextRevision != 2 || !f.boundaryPending {
+ t.Fatalf("bare fresh context = generation %d pending=%t, want 2/true", f.contextRevision, f.boundaryPending)
+ }
+}
+
+func TestAppendUserMessage_ResolvesBareFreshBoundaryOnNextMessage(t *testing.T) {
+ f := newFake()
+ s := newTestSession(f)
+ if err := s.MarkPendingFresh(context.Background(), uid(1), "command-ts"); err != nil {
+ t.Fatalf("MarkPendingFresh: %v", err)
+ }
+ res, err := s.AppendUserMessage(context.Background(), AppendInput{SessionID: uid(1), Body: "next", MessageID: "next-ts"})
+ if err != nil {
+ t.Fatalf("AppendUserMessage: %v", err)
+ }
+ if f.boundaryPending || res.ContextRevision != 2 || f.lastCreate.ChannelContextRevision.Int64 != 2 {
+ t.Fatalf("resolved context: pending=%t result=%d row=%d", f.boundaryPending, res.ContextRevision, f.lastCreate.ChannelContextRevision.Int64)
+ }
+}
+
+func TestAppendUserMessage_AdvancesLegacyPendingFreshFromRollingDeploy(t *testing.T) {
+ f := newFake()
+ f.legacyPendingFresh = true
+ s := newTestSession(f)
+ res, err := s.AppendUserMessage(context.Background(), AppendInput{
+ SessionID: uid(1), Body: "next", MessageID: "next-ts",
+ })
+ if err != nil {
+ t.Fatalf("AppendUserMessage: %v", err)
+ }
+ if f.contextRevision != 2 || res.ContextRevision != 2 || f.lastCreate.ChannelContextRevision.Int64 != 2 {
+ t.Fatalf("legacy pending fresh context = generation:%d result:%d row:%d, want 2", f.contextRevision, res.ContextRevision, f.lastCreate.ChannelContextRevision.Int64)
+ }
+}
+
+func TestAppendUserMessage_ContextGenerationFailuresDoNotWriteMessage(t *testing.T) {
+ testErr := errors.New("context generation failed")
+ tests := []struct {
+ name string
+ setup func(*fakeSessionQueries)
+ input AppendInput
+ }{
+ {name: "ensure", setup: func(f *fakeSessionQueries) { f.ensureContextErr = testErr }},
+ {name: "lock", setup: func(f *fakeSessionQueries) { f.lockContextErr = testErr }},
+ {name: "advance", setup: func(f *fakeSessionQueries) { f.advanceContextErr = testErr }, input: AppendInput{ForceFresh: true}},
+ {name: "resolve", setup: func(f *fakeSessionQueries) {
+ f.boundaryPending = true
+ f.resolveContextErr = testErr
+ }, input: AppendInput{MessageID: "boundary"}},
+ {name: "snapshot initiator", setup: func(f *fakeSessionQueries) { f.setInitiatorErr = testErr }},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ f := newFake()
+ tt.setup(f)
+ input := tt.input
+ input.SessionID = uid(1)
+ input.Body = "must not persist"
+ _, err := newTestSession(f).AppendUserMessage(context.Background(), input)
+ if !errors.Is(err, testErr) {
+ t.Fatalf("AppendUserMessage error = %v, want injected failure", err)
+ }
+ if len(f.messages) != 0 || f.touched != 0 || f.replyTargets != 0 {
+ t.Fatalf("failed append wrote message/touch/reply = %d/%d/%d", len(f.messages), f.touched, f.replyTargets)
+ }
+ })
+ }
+}
+
+func TestAppendUserMessage_PendingContextLookupFailureRollsBack(t *testing.T) {
+ testErr := errors.New("pending context lookup failed")
+ f := newFake()
+ f.pendingContextsErr = testErr
+ tx := &fakeTx{}
+ s := newChatSessionWith(f, fakeTxStarter{tx: tx}, channel.TypeFeishu, SessionTitles{})
+
+ _, err := s.AppendUserMessage(context.Background(), AppendInput{
+ SessionID: uid(1), Body: "must roll back", MessageID: "m1",
+ })
+ if !errors.Is(err, testErr) {
+ t.Fatalf("AppendUserMessage error = %v, want injected failure", err)
+ }
+ if tx.committed || !tx.rolledBack {
+ t.Fatalf("transaction committed/rolled back = %t/%t, want false/true", tx.committed, tx.rolledBack)
+ }
+ if f.touched != 0 || f.replyTargets != 0 {
+ t.Fatalf("failed append touched session/reply target = %d/%d, want 0/0", f.touched, f.replyTargets)
+ }
+}
+
+func TestMarkPendingFresh_ContextGenerationFailuresRollBack(t *testing.T) {
+ testErr := errors.New("context generation failed")
+ tests := []struct {
+ name string
+ setup func(*fakeSessionQueries)
+ }{
+ {name: "ensure", setup: func(f *fakeSessionQueries) { f.ensureContextErr = testErr }},
+ {name: "lock", setup: func(f *fakeSessionQueries) { f.lockContextErr = testErr }},
+ {name: "advance", setup: func(f *fakeSessionQueries) { f.advanceContextErr = testErr }},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ f := newFake()
+ tt.setup(f)
+ tx := &fakeTx{}
+ s := newChatSessionWith(f, fakeTxStarter{tx: tx}, channel.TypeFeishu, SessionTitles{})
+ err := s.MarkPendingFresh(context.Background(), uid(1), "command")
+ if !errors.Is(err, testErr) {
+ t.Fatalf("MarkPendingFresh error = %v, want injected failure", err)
+ }
+ if tx.committed || !tx.rolledBack {
+ t.Fatalf("transaction committed/rolledBack = %t/%t, want false/true", tx.committed, tx.rolledBack)
+ }
+ })
+ }
+}
+
+func TestMarkPendingFresh_CommitFailureRollsBack(t *testing.T) {
+ commitErr := errors.New("commit failed")
+ tx := &fakeTx{commitErr: commitErr}
+ s := newChatSessionWith(newFake(), fakeTxStarter{tx: tx}, channel.TypeFeishu, SessionTitles{})
+ err := s.MarkPendingFresh(context.Background(), uid(1), "command")
+ if !errors.Is(err, commitErr) {
+ t.Fatalf("MarkPendingFresh error = %v, want commit failure", err)
+ }
+ if !tx.committed || !tx.rolledBack {
+ t.Fatalf("transaction committed/rolledBack = %t/%t, want true/true", tx.committed, tx.rolledBack)
+ }
}
func TestAppendUserMessage_DedupMark(t *testing.T) {
diff --git a/server/internal/integrations/channel/history.go b/server/internal/integrations/channel/history.go
index c1fa08fd38..7ae88daa2e 100644
--- a/server/internal/integrations/channel/history.go
+++ b/server/internal/integrations/channel/history.go
@@ -81,4 +81,12 @@ type HistoryOptions struct {
// returns only messages strictly older than it. Empty starts at the most
// recent messages.
Before string
+ // After and Until are server-authoritative generation boundaries. Readers
+ // must treat the window as [After, Until); callers cannot set them via URL.
+ After string
+ Until string
+ BoundaryPending bool
+ // ContextRevision is the task's immutable channel context generation. Zero
+ // means this is a legacy or direct-chat read with no generation boundary.
+ ContextRevision int64
}
diff --git a/server/internal/integrations/channel/message.go b/server/internal/integrations/channel/message.go
index 830ccc886c..6d5f5ab06b 100644
--- a/server/internal/integrations/channel/message.go
+++ b/server/internal/integrations/channel/message.go
@@ -209,4 +209,8 @@ type OutboundMessage struct {
type SendResult struct {
// MessageID is the platform's identifier for the delivered message.
MessageID string
+ // MessageIDs contains every delivered platform message identifier when one
+ // logical reply is split into multiple messages. Adapters that never chunk
+ // may leave it empty and return only MessageID for compatibility.
+ MessageIDs []string
}
diff --git a/server/internal/integrations/dingtalk/byo_install_db_test.go b/server/internal/integrations/dingtalk/byo_install_db_test.go
index db8a40bb71..e74694cadf 100644
--- a/server/internal/integrations/dingtalk/byo_install_db_test.go
+++ b/server/internal/integrations/dingtalk/byo_install_db_test.go
@@ -68,6 +68,7 @@ func TestRegisterBYO_DifferentAppKey_IsolatesIdentityStateDB(t *testing.T) {
clean := func() {
_, _ = pool.Exec(context.Background(), `DELETE FROM channel_outbound_card_message WHERE chat_session_id = $1`, chatSessionID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_chat_context_generation WHERE chat_session_id = $1`, chatSessionID)
_, _ = pool.Exec(context.Background(), `DELETE FROM channel_chat_session_binding WHERE chat_session_id = $1`, chatSessionID)
_, _ = pool.Exec(context.Background(), `DELETE FROM channel_binding_token WHERE token_hash = $1`, tokenHash)
_, _ = pool.Exec(context.Background(), `DELETE FROM channel_user_binding WHERE workspace_id = $1 AND channel_user_id = $2`, workspaceID, staffID)
@@ -98,6 +99,10 @@ INSERT INTO channel_chat_session_binding (chat_session_id, installation_id, chan
VALUES ($1, $2, 'dingtalk', $3, 'p2p')
`, chatSessionID, oldInstallID, chatID)
exec(`
+INSERT INTO channel_chat_context_generation (chat_session_id, revision)
+VALUES ($1, 1)
+`, chatSessionID)
+ exec(`
INSERT INTO channel_binding_token (token_hash, workspace_id, installation_id, channel_type, channel_user_id, expires_at)
VALUES ($1, $2, $3, 'dingtalk', $4, now() + interval '10 minutes')
`, tokenHash, workspaceID, oldInstallID, staffID)
@@ -166,6 +171,7 @@ VALUES ($1, $2, $3, 'https://storage.example.test/old-image', $4)
assertCount("old installation", `SELECT count(*) FROM channel_installation WHERE id = $1`, 0, oldInstallID)
assertCount("old user binding", `SELECT count(*) FROM channel_user_binding WHERE installation_id = $1`, 0, oldInstallID)
assertCount("old chat binding", `SELECT count(*) FROM channel_chat_session_binding WHERE installation_id = $1`, 0, oldInstallID)
+ assertCount("old chat context", `SELECT count(*) FROM channel_chat_context_generation WHERE chat_session_id = $1`, 1, chatSessionID)
assertCount("old binding token", `SELECT count(*) FROM channel_binding_token WHERE installation_id = $1`, 0, oldInstallID)
assertCount("old outbound state", `SELECT count(*) FROM channel_outbound_card_message WHERE chat_session_id = $1`, 0, chatSessionID)
assertCount("old dedup state", `SELECT count(*) FROM channel_inbound_message_dedup WHERE installation_id = $1`, 0, oldInstallID)
diff --git a/server/internal/integrations/dingtalk/channel_context_cleanup_db_test.go b/server/internal/integrations/dingtalk/channel_context_cleanup_db_test.go
new file mode 100644
index 0000000000..83d0668c5d
--- /dev/null
+++ b/server/internal/integrations/dingtalk/channel_context_cleanup_db_test.go
@@ -0,0 +1,118 @@
+package dingtalk
+
+import (
+ "context"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+type dingtalkContextCleanupOwner struct {
+ creatorID string
+ workspaceID string
+ runtimeID string
+ agentID string
+ installationID string
+ chatSessionID string
+}
+
+func seedDingTalkContextCleanupOwner(
+ t *testing.T,
+ ctx context.Context,
+ pool *pgxpool.Pool,
+ kind string,
+) dingtalkContextCleanupOwner {
+ t.Helper()
+ owner := dingtalkContextCleanupOwner{
+ creatorID: uuid.NewString(),
+ workspaceID: uuid.NewString(),
+ runtimeID: uuid.NewString(),
+ agentID: uuid.NewString(),
+ installationID: uuid.NewString(),
+ chatSessionID: uuid.NewString(),
+ }
+ slug := "dingtalk-context-cleanup-" + uuid.NewString()
+ systemKey := ""
+ if kind == "system" {
+ systemKey = "dingtalk_context_cleanup_" + uuid.NewString()
+ }
+ exec := func(query string, args ...any) {
+ t.Helper()
+ if _, err := pool.Exec(ctx, query, args...); err != nil {
+ t.Fatalf("seed DingTalk context cleanup fixture: %v", err)
+ }
+ }
+ exec(`INSERT INTO "user" (id, name, email) VALUES ($1, 'DingTalk context cleanup creator', $2)`, owner.creatorID, slug+"@multica.test")
+ exec(`INSERT INTO workspace (id, name, slug, description) VALUES ($1, 'DingTalk context cleanup', $2, '')`, owner.workspaceID, slug)
+ exec(`INSERT INTO agent_runtime (id, workspace_id, name, runtime_mode, provider) VALUES ($1, $2, 'DingTalk cleanup runtime', 'local', 'multica_daemon')`, owner.runtimeID, owner.workspaceID)
+ exec(`
+ INSERT INTO agent (id, workspace_id, name, runtime_mode, runtime_id, kind, system_key)
+ VALUES ($1, $2, 'DingTalk cleanup agent', 'local', $3, $4, NULLIF($5, ''))
+ `, owner.agentID, owner.workspaceID, owner.runtimeID, kind, systemKey)
+ exec(`
+ INSERT INTO channel_installation (
+ id, workspace_id, agent_id, channel_type, config, installer_user_id, status
+ ) VALUES ($1, $2, $3, 'dingtalk', '{}'::jsonb, $4, 'active')
+ `, owner.installationID, owner.workspaceID, owner.agentID, owner.creatorID)
+ exec(`
+ INSERT INTO chat_session (id, workspace_id, agent_id, creator_id, title)
+ VALUES ($1, $2, $3, $4, 'retired channel chat')
+ `, owner.chatSessionID, owner.workspaceID, owner.agentID, owner.creatorID)
+ exec(`INSERT INTO channel_chat_context_generation (chat_session_id, revision) VALUES ($1, 1)`, owner.chatSessionID)
+
+ t.Cleanup(func() {
+ cleanupCtx := context.Background()
+ _, _ = pool.Exec(cleanupCtx, `DELETE FROM channel_chat_context_generation WHERE chat_session_id = $1`, owner.chatSessionID)
+ _, _ = pool.Exec(cleanupCtx, `DELETE FROM channel_chat_session_binding WHERE chat_session_id = $1`, owner.chatSessionID)
+ _, _ = pool.Exec(cleanupCtx, `DELETE FROM chat_session WHERE id = $1`, owner.chatSessionID)
+ _, _ = pool.Exec(cleanupCtx, `DELETE FROM channel_installation WHERE id = $1`, owner.installationID)
+ _, _ = pool.Exec(cleanupCtx, `DELETE FROM agent WHERE id = $1`, owner.agentID)
+ _, _ = pool.Exec(cleanupCtx, `DELETE FROM agent_runtime WHERE id = $1`, owner.runtimeID)
+ _, _ = pool.Exec(cleanupCtx, `DELETE FROM workspace WHERE id = $1`, owner.workspaceID)
+ _, _ = pool.Exec(cleanupCtx, `DELETE FROM "user" WHERE id = $1`, owner.creatorID)
+ })
+ return owner
+}
+
+func assertDingTalkContextCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, owner dingtalkContextCleanupOwner, want int) {
+ t.Helper()
+ var got int
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM channel_chat_context_generation WHERE chat_session_id = $1`, owner.chatSessionID).Scan(&got); err != nil {
+ t.Fatalf("count channel contexts: %v", err)
+ }
+ if got != want {
+ t.Fatalf("channel contexts for %s = %d, want %d", owner.chatSessionID, got, want)
+ }
+}
+
+func TestDeleteChannelInstallationsBySystemRuntimeAgentsCleansRetiredChatContexts(t *testing.T) {
+ pool := dingtalkInstallTestDB(t)
+ ctx := context.Background()
+ systemOwner := seedDingTalkContextCleanupOwner(t, ctx, pool, "system")
+ userOwner := seedDingTalkContextCleanupOwner(t, ctx, pool, "user")
+
+ if err := db.New(pool).DeleteChannelInstallationsBySystemRuntimeAgents(ctx, util.MustParseUUID(systemOwner.runtimeID)); err != nil {
+ t.Fatalf("DeleteChannelInstallationsBySystemRuntimeAgents: %v", err)
+ }
+
+ assertDingTalkContextCount(t, ctx, pool, systemOwner, 0)
+ assertDingTalkContextCount(t, ctx, pool, userOwner, 1)
+}
+
+func TestDeleteWorkspaceCleansRetiredChatContexts(t *testing.T) {
+ pool := dingtalkInstallTestDB(t)
+ ctx := context.Background()
+ target := seedDingTalkContextCleanupOwner(t, ctx, pool, "user")
+ unrelated := seedDingTalkContextCleanupOwner(t, ctx, pool, "user")
+
+ if err := db.New(pool).DeleteWorkspace(ctx, util.MustParseUUID(target.workspaceID)); err != nil {
+ t.Fatalf("DeleteWorkspace: %v", err)
+ }
+
+ assertDingTalkContextCount(t, ctx, pool, target, 0)
+ assertDingTalkContextCount(t, ctx, pool, unrelated, 1)
+}
diff --git a/server/internal/integrations/dingtalk/resolvers.go b/server/internal/integrations/dingtalk/resolvers.go
index 2bee130169..b5eb111e79 100644
--- a/server/internal/integrations/dingtalk/resolvers.go
+++ b/server/internal/integrations/dingtalk/resolvers.go
@@ -238,7 +238,7 @@ func (r *deduper) Release(ctx context.Context, installationID pgtype.UUID, messa
type chatSession interface {
EnsureSession(ctx context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error)
- MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) error
+ MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error
AppendUserMessage(ctx context.Context, in engine.AppendInput) (engine.AppendResult, error)
BindMediaRefs(ctx context.Context, in engine.BindMediaInput) error
}
@@ -354,8 +354,8 @@ func (r *sessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessio
return sessionID, nil
}
-func (r *sessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) error {
- return r.session.MarkPendingFresh(ctx, sessionID)
+func (r *sessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error {
+ return r.session.MarkPendingFresh(ctx, sessionID, messageID)
}
func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {
diff --git a/server/internal/integrations/dingtalk/resolvers_test.go b/server/internal/integrations/dingtalk/resolvers_test.go
index ccc55dd955..db04548360 100644
--- a/server/internal/integrations/dingtalk/resolvers_test.go
+++ b/server/internal/integrations/dingtalk/resolvers_test.go
@@ -59,7 +59,7 @@ func (c *captureChatSession) EnsureSession(_ context.Context, in engine.EnsureSe
c.ensureCalls++
return pgtype.UUID{}, c.ensureErr
}
-func (c *captureChatSession) MarkPendingFresh(context.Context, pgtype.UUID) error { return nil }
+func (c *captureChatSession) MarkPendingFresh(context.Context, pgtype.UUID, string) error { return nil }
func (c *captureChatSession) AppendUserMessage(_ context.Context, in engine.AppendInput) (engine.AppendResult, error) {
c.append = in
return engine.AppendResult{}, c.appendErr
diff --git a/server/internal/integrations/lark/feishu_resolvers.go b/server/internal/integrations/lark/feishu_resolvers.go
index 59e5ee4145..774228d0f1 100644
--- a/server/internal/integrations/lark/feishu_resolvers.go
+++ b/server/internal/integrations/lark/feishu_resolvers.go
@@ -159,7 +159,7 @@ func (r *feishuDeduper) Release(ctx context.Context, installationID pgtype.UUID,
// unit-tested with a fake; *engine.ChatSession is the production value.
type chatSession interface {
EnsureSession(ctx context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error)
- MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) error
+ MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error
AppendUserMessage(ctx context.Context, in engine.AppendInput) (engine.AppendResult, error)
BindMediaRefs(ctx context.Context, in engine.BindMediaInput) error
}
@@ -203,8 +203,8 @@ func (r *feishuSessionBinder) EnsureSession(ctx context.Context, p engine.Ensure
})
}
-func (r *feishuSessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) error {
- return r.session.MarkPendingFresh(ctx, sessionID)
+func (r *feishuSessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error {
+ return r.session.MarkPendingFresh(ctx, sessionID, messageID)
}
func (r *feishuSessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {
diff --git a/server/internal/integrations/lark/feishu_resolvers_test.go b/server/internal/integrations/lark/feishu_resolvers_test.go
index 50407c55ef..3aa131ac1b 100644
--- a/server/internal/integrations/lark/feishu_resolvers_test.go
+++ b/server/internal/integrations/lark/feishu_resolvers_test.go
@@ -31,7 +31,7 @@ func (f *fakeChatSession) EnsureSession(_ context.Context, in engine.EnsureSessi
return binderUUID(42), nil
}
-func (f *fakeChatSession) MarkPendingFresh(context.Context, pgtype.UUID) error { return nil }
+func (f *fakeChatSession) MarkPendingFresh(context.Context, pgtype.UUID, string) error { return nil }
func (f *fakeChatSession) AppendUserMessage(_ context.Context, in engine.AppendInput) (engine.AppendResult, error) {
f.appendIn = in
diff --git a/server/internal/integrations/slack/channel.go b/server/internal/integrations/slack/channel.go
index 0d199538ed..cd314670ee 100644
--- a/server/internal/integrations/slack/channel.go
+++ b/server/internal/integrations/slack/channel.go
@@ -34,13 +34,15 @@ type slackSender struct {
// Send delivers a minimal text reply via chat.postMessage, threading into
// out.ThreadID when set so a decoupled reply lands back in the originating
// thread. Long bodies are chunked under Slack's per-message cap; the returned
-// SendResult carries the timestamp of the LAST posted chunk.
+// SendResult carries every posted chunk timestamp and keeps MessageID as the
+// timestamp of the last chunk for existing callers.
func (c *slackSender) Send(ctx context.Context, out channel.OutboundMessage) (channel.SendResult, error) {
if c.api == nil {
return channel.SendResult{}, errors.New("slack: api client not configured")
}
threadTS := outboundThreadTS(out)
var lastTS string
+ var messageIDs []string
// Convert the agent's standard Markdown to Slack mrkdwn before posting so
// bold/headers/links render instead of showing literal markup.
for _, chunk := range chunkMessage(formatMrkdwn(out.Text), maxMessageRunes) {
@@ -56,8 +58,9 @@ func (c *slackSender) Send(ctx context.Context, out channel.OutboundMessage) (ch
return channel.SendResult{}, fmt.Errorf("slack: chat.postMessage: %w", err)
}
lastTS = ts
+ messageIDs = append(messageIDs, ts)
}
- return channel.SendResult{MessageID: lastTS}, nil
+ return channel.SendResult{MessageID: lastTS, MessageIDs: messageIDs}, nil
}
// newSlackSender builds a Send-only client from decoded credentials and a
diff --git a/server/internal/integrations/slack/channel_test.go b/server/internal/integrations/slack/channel_test.go
index 3447644ea8..10ff4f3995 100644
--- a/server/internal/integrations/slack/channel_test.go
+++ b/server/internal/integrations/slack/channel_test.go
@@ -53,6 +53,9 @@ func TestSend(t *testing.T) {
if res.MessageID != "1700000000.111111" {
t.Errorf("MessageID = %q", res.MessageID)
}
+ if len(res.MessageIDs) != 1 || res.MessageIDs[0] != "1700000000.111111" {
+ t.Errorf("MessageIDs = %v", res.MessageIDs)
+ }
if gotForm.Get("channel") != "C123" || gotForm.Get("text") != "reply body" {
t.Errorf("posted channel/text = %q / %q", gotForm.Get("channel"), gotForm.Get("text"))
}
diff --git a/server/internal/integrations/slack/history.go b/server/internal/integrations/slack/history.go
index 6e8373f133..c13664155e 100644
--- a/server/internal/integrations/slack/history.go
+++ b/server/internal/integrations/slack/history.go
@@ -15,6 +15,7 @@ import (
"github.com/slack-go/slack"
"github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -36,6 +37,7 @@ const (
type historyQueries interface {
GetChannelChatSessionBindingBySession(ctx context.Context, arg db.GetChannelChatSessionBindingBySessionParams) (db.ChannelChatSessionBinding, error)
GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error)
+ ListChannelOutboundMessageIDsForContext(ctx context.Context, arg db.ListChannelOutboundMessageIDsForContextParams) ([]string, error)
}
// historyClient is the slice of the slack-go Web API the reader calls. The real
@@ -77,10 +79,11 @@ func NewHistory(q historyQueries, decrypt Decrypter, logger *slog.Logger) *Histo
// slackTarget is the resolved per-session read context: a bot-token client plus
// the session's pinned channel and its own thread root.
type slackTarget struct {
- client historyClient
- channelID string
- threadRoot string // the session's own thread (empty for a DM)
- botUserID string
+ client historyClient
+ installationID pgtype.UUID
+ channelID string
+ threadRoot string // the session's own thread (empty for a DM)
+ botUserID string
}
// resolve maps a chat_session to its Slack channel + bot client. The channel is
@@ -114,10 +117,11 @@ func (h *History) resolve(ctx context.Context, chatSessionID pgtype.UUID) (slack
}
channelID, threadRoot := historyTarget(binding)
return slackTarget{
- client: h.newClient(creds.BotToken),
- channelID: channelID,
- threadRoot: threadRoot,
- botUserID: creds.BotUserID,
+ client: h.newClient(creds.BotToken),
+ installationID: binding.InstallationID,
+ channelID: channelID,
+ threadRoot: threadRoot,
+ botUserID: creds.BotUserID,
}, nil
}
@@ -130,17 +134,29 @@ func (h *History) ChannelOverview(ctx context.Context, chatSessionID pgtype.UUID
if err != nil {
return channel.HistoryPage{}, err
}
+ if opts.BoundaryPending || historyCursorReachedStart(opts.Before, opts.After) {
+ return channel.HistoryPage{ChannelType: string(TypeSlack)}, nil
+ }
limit := clampHistoryLimit(opts.Limit)
+ latest, oldest, inclusive := historyWindow(opts)
resp, err := t.client.GetConversationHistoryContext(ctx, &slack.GetConversationHistoryParameters{
ChannelID: t.channelID,
- Latest: opts.Before,
- Inclusive: false,
+ Latest: latest,
+ Oldest: oldest,
+ Inclusive: inclusive,
Limit: limit,
})
if err != nil {
return channel.HistoryPage{}, fmt.Errorf("read slack channel: %w", err)
}
- page := normalizePage(ctx, t.client, h.logger, resp.Messages, t.botUserID, limit, true)
+ nextCursor := historyNextCursor(resp.Messages, limit)
+ allowedBotMessages, err := h.allowedBotMessages(ctx, chatSessionID, t, opts, resp.Messages)
+ if err != nil {
+ return channel.HistoryPage{}, err
+ }
+ raw := filterHistoryWindow(resp.Messages, opts, t.botUserID, allowedBotMessages)
+ page := normalizePage(ctx, t.client, h.logger, raw, t.botUserID, limit, true)
+ page.NextCursor = nextCursor
page.ChannelType = string(TypeSlack)
return page, nil
}
@@ -159,15 +175,23 @@ func (h *History) Thread(ctx context.Context, chatSessionID pgtype.UUID, threadI
if ts == "" {
ts = t.threadRoot // the session's own thread
}
+ if opts.BoundaryPending {
+ return channel.HistoryPage{ChannelType: string(TypeSlack), ThreadID: ts}, nil
+ }
var raw []slack.Message
if ts == "" {
// No thread to read (a DM, or a group whose root could not be recovered):
// fall back to the channel's linear conversation.
+ if historyCursorReachedStart(opts.Before, opts.After) {
+ return channel.HistoryPage{ChannelType: string(TypeSlack), ThreadID: ts}, nil
+ }
+ latest, oldest, inclusive := historyWindow(opts)
resp, herr := t.client.GetConversationHistoryContext(ctx, &slack.GetConversationHistoryParameters{
ChannelID: t.channelID,
- Latest: opts.Before,
- Inclusive: false,
+ Latest: latest,
+ Oldest: oldest,
+ Inclusive: inclusive,
Limit: limit,
})
if herr != nil {
@@ -175,11 +199,16 @@ func (h *History) Thread(ctx context.Context, chatSessionID pgtype.UUID, threadI
}
raw = resp.Messages
} else {
+ if historyCursorReachedStart(opts.Before, opts.After) {
+ return channel.HistoryPage{ChannelType: string(TypeSlack), ThreadID: ts}, nil
+ }
+ latest, oldest, inclusive := historyWindow(opts)
msgs, _, _, rerr := t.client.GetConversationRepliesContext(ctx, &slack.GetConversationRepliesParameters{
ChannelID: t.channelID,
Timestamp: ts,
- Latest: opts.Before,
- Inclusive: false,
+ Latest: latest,
+ Oldest: oldest,
+ Inclusive: inclusive,
Limit: limit,
})
if rerr != nil {
@@ -187,12 +216,112 @@ func (h *History) Thread(ctx context.Context, chatSessionID pgtype.UUID, threadI
}
raw = msgs
}
+ nextCursor := historyNextCursor(raw, limit)
+ allowedBotMessages, err := h.allowedBotMessages(ctx, chatSessionID, t, opts, raw)
+ if err != nil {
+ return channel.HistoryPage{}, err
+ }
+ raw = filterHistoryWindow(raw, opts, t.botUserID, allowedBotMessages)
page := normalizePage(ctx, t.client, h.logger, raw, t.botUserID, limit, false)
+ page.NextCursor = nextCursor
page.ChannelType = string(TypeSlack)
page.ThreadID = ts
return page, nil
}
+func historyWindow(opts channel.HistoryOptions) (latest, oldest string, inclusive bool) {
+ latest = opts.Before
+ if opts.Until != "" && (latest == "" || slackTSLess(opts.Until, latest)) {
+ latest = opts.Until
+ }
+ if opts.Before == "" {
+ return latest, opts.After, opts.After != "" || opts.Until != ""
+ }
+ return latest, "", false
+}
+
+func historyCursorReachedStart(before, start string) bool {
+ return before != "" && start != "" && !slackTSLess(start, before)
+}
+
+func historyNextCursor(raw []slack.Message, limit int) string {
+ if len(raw) < limit || len(raw) == 0 {
+ return ""
+ }
+ oldest := raw[0].Timestamp
+ for i := 1; i < len(raw); i++ {
+ if slackTSLess(raw[i].Timestamp, oldest) {
+ oldest = raw[i].Timestamp
+ }
+ }
+ return oldest
+}
+
+func (h *History) allowedBotMessages(ctx context.Context, chatSessionID pgtype.UUID, target slackTarget, opts channel.HistoryOptions, raw []slack.Message) (map[string]struct{}, error) {
+ if opts.ContextRevision <= 1 {
+ return nil, nil
+ }
+ candidates := make([]string, 0, len(raw))
+ for _, message := range raw {
+ if message.User == target.botUserID {
+ candidates = append(candidates, message.Timestamp)
+ }
+ }
+ if len(candidates) == 0 {
+ return map[string]struct{}{}, nil
+ }
+ ids, err := h.q.ListChannelOutboundMessageIDsForContext(ctx, db.ListChannelOutboundMessageIDsForContextParams{
+ ChatSessionID: chatSessionID,
+ ChannelType: pgtype.Text{String: string(TypeSlack), Valid: true},
+ InstallationID: target.installationID,
+ ChannelChatID: pgtype.Text{String: target.channelID, Valid: true},
+ ChannelContextRevision: pgtype.Int8{Int64: opts.ContextRevision, Valid: true},
+ CandidateMessageIds: candidates,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("load slack reply provenance: %w", err)
+ }
+ allowed := make(map[string]struct{}, len(ids))
+ for _, id := range ids {
+ allowed[id] = struct{}{}
+ }
+ return allowed, nil
+}
+
+func filterHistoryWindow(raw []slack.Message, opts channel.HistoryOptions, botUserID string, allowedBotMessages map[string]struct{}) []slack.Message {
+ out := raw[:0]
+ for _, message := range raw {
+ if opts.After != "" && slackTSLess(message.Timestamp, opts.After) {
+ continue
+ }
+ if opts.Until != "" && !slackTSLess(message.Timestamp, opts.Until) {
+ continue
+ }
+ // Slack timestamps alone are not a causal boundary: a reply from an old
+ // task may be posted after /new. From generation 2 onward, trust an
+ // assistant message only when its provider id was persisted on a task in
+ // this exact generation. Human and third-party bot messages still follow
+ // the provider time window. Unknown own-bot output fails closed for agent
+ // context but remains visible to people in Slack.
+ if opts.ContextRevision > 1 && message.User == botUserID {
+ if _, ok := allowedBotMessages[message.Timestamp]; !ok {
+ continue
+ }
+ }
+ if message.Timestamp == opts.After {
+ text := strings.TrimSpace(strings.ReplaceAll(message.Text, "<@"+botUserID+">", ""))
+ if body, ok := engine.ParseFreshSessionCommand(text); ok {
+ if body == "" {
+ continue
+ }
+ message.Text = body
+ }
+ }
+ out = append(out, message)
+ }
+ return out
+}
+
func clampHistoryLimit(n int) int {
if n <= 0 {
return defaultHistoryLimit
@@ -263,13 +392,7 @@ func normalizePage(ctx context.Context, client historyClient, logger *slog.Logge
out = append(out, hm)
}
- page := channel.HistoryPage{Messages: out}
- // Advertise a cursor only when the platform returned a full page (more may
- // exist older than the oldest message we just returned).
- if len(raw) >= limit && len(out) > 0 {
- page.NextCursor = out[0].TS
- }
- return page
+ return channel.HistoryPage{Messages: out}
}
// maxDerivedTextLen caps text recovered from attachments/blocks so a verbose
diff --git a/server/internal/integrations/slack/history_test.go b/server/internal/integrations/slack/history_test.go
index 571cb0f6e4..6d447ecfaa 100644
--- a/server/internal/integrations/slack/history_test.go
+++ b/server/internal/integrations/slack/history_test.go
@@ -14,10 +14,12 @@ import (
)
type fakeHistoryQueries struct {
- binding db.ChannelChatSessionBinding
- bindingErr error
- inst db.ChannelInstallation
- instErr error
+ binding db.ChannelChatSessionBinding
+ bindingErr error
+ inst db.ChannelInstallation
+ instErr error
+ messageIDs []string
+ messageIDsErr error
}
func (f *fakeHistoryQueries) GetChannelChatSessionBindingBySession(context.Context, db.GetChannelChatSessionBindingBySessionParams) (db.ChannelChatSessionBinding, error) {
@@ -28,6 +30,10 @@ func (f *fakeHistoryQueries) GetChannelInstallation(context.Context, db.GetChann
return f.inst, f.instErr
}
+func (f *fakeHistoryQueries) ListChannelOutboundMessageIDsForContext(context.Context, db.ListChannelOutboundMessageIDsForContextParams) ([]string, error) {
+ return f.messageIDs, f.messageIDsErr
+}
+
type fakeHistoryClient struct {
historyMsgs []slack.Message
repliesMsgs []slack.Message
@@ -149,6 +155,115 @@ func TestChannelOverview(t *testing.T) {
}
}
+func TestChannelOverviewScopesAndSanitizesFreshGeneration(t *testing.T) {
+ q := &fakeHistoryQueries{binding: groupBinding("100.000000"), inst: activeSlackInstall()}
+ fc := &fakeHistoryClient{historyMsgs: []slack.Message{
+ msg("U1", "new reply", "104.000000"),
+ msg("U1", "/new current question", "103.000000"),
+ msg("U1", "old context", "102.000000"),
+ }}
+ h := newTestHistory(q, fc)
+ page, err := h.ChannelOverview(context.Background(), uid(9), channel.HistoryOptions{
+ After: "103.000000", Until: "105.000000",
+ })
+ if err != nil {
+ t.Fatalf("ChannelOverview: %v", err)
+ }
+ if fc.lastHistory.Oldest != "103.000000" || fc.lastHistory.Latest != "105.000000" || !fc.lastHistory.Inclusive {
+ t.Fatalf("Slack bounds = oldest %q latest %q inclusive %t", fc.lastHistory.Oldest, fc.lastHistory.Latest, fc.lastHistory.Inclusive)
+ }
+ if len(page.Messages) != 2 || page.Messages[0].Text != "current question" || page.Messages[1].Text != "new reply" {
+ t.Fatalf("scoped messages = %+v", page.Messages)
+ }
+}
+
+func TestChannelOverviewExcludesLateReplyFromPreviousGeneration(t *testing.T) {
+ q := &fakeHistoryQueries{
+ binding: groupBinding("100.000000"), inst: activeSlackInstall(),
+ messageIDs: []string{"104.000000"},
+ }
+ fc := &fakeHistoryClient{historyMsgs: []slack.Message{
+ msg("UBOT", "current generation answer", "104.000000"),
+ msg("UBOT", "late previous generation answer", "103.500000"),
+ msg("U1", "/new current question", "103.000000"),
+ }}
+ h := newTestHistory(q, fc)
+ page, err := h.ChannelOverview(context.Background(), uid(9), channel.HistoryOptions{
+ After: "103.000000", ContextRevision: 2,
+ })
+ if err != nil {
+ t.Fatalf("ChannelOverview: %v", err)
+ }
+ if len(page.Messages) != 2 || page.Messages[0].Text != "current question" || page.Messages[1].Text != "current generation answer" {
+ t.Fatalf("causally scoped messages = %+v", page.Messages)
+ }
+}
+
+func TestChannelOverviewFailsClosedForUnknownOwnBotReply(t *testing.T) {
+ q := &fakeHistoryQueries{binding: groupBinding("100.000000"), inst: activeSlackInstall()}
+ fc := &fakeHistoryClient{historyMsgs: []slack.Message{
+ msg("UBOT", "unattributed answer", "104.000000"),
+ msg("U1", "/new current question", "103.000000"),
+ }}
+ h := newTestHistory(q, fc)
+ page, err := h.ChannelOverview(context.Background(), uid(9), channel.HistoryOptions{
+ After: "103.000000", ContextRevision: 2,
+ })
+ if err != nil {
+ t.Fatalf("ChannelOverview: %v", err)
+ }
+ if len(page.Messages) != 1 || page.Messages[0].Text != "current question" {
+ t.Fatalf("fail-closed messages = %+v", page.Messages)
+ }
+}
+
+func TestChannelOverviewKeepsPagingCursorWhenLateRepliesFillPage(t *testing.T) {
+ q := &fakeHistoryQueries{binding: groupBinding("100.000000"), inst: activeSlackInstall()}
+ fc := &fakeHistoryClient{historyMsgs: []slack.Message{
+ msg("UBOT", "late old answer 2", "105.000000"),
+ msg("UBOT", "late old answer 1", "104.000000"),
+ }}
+ h := newTestHistory(q, fc)
+ page, err := h.ChannelOverview(context.Background(), uid(9), channel.HistoryOptions{
+ Limit: 2, After: "103.000000", ContextRevision: 2,
+ })
+ if err != nil {
+ t.Fatalf("ChannelOverview: %v", err)
+ }
+ if len(page.Messages) != 0 || page.NextCursor != "104.000000" {
+ t.Fatalf("filtered full page = messages:%+v cursor:%q", page.Messages, page.NextCursor)
+ }
+}
+
+func TestChannelOverviewPendingFreshBoundaryReturnsEmpty(t *testing.T) {
+ q := &fakeHistoryQueries{binding: groupBinding("100.000000"), inst: activeSlackInstall()}
+ fc := &fakeHistoryClient{historyMsgs: []slack.Message{msg("U1", "old context", "102.000000")}}
+ h := newTestHistory(q, fc)
+ page, err := h.ChannelOverview(context.Background(), uid(9), channel.HistoryOptions{BoundaryPending: true})
+ if err != nil {
+ t.Fatalf("ChannelOverview: %v", err)
+ }
+ if fc.historyCalls != 0 || len(page.Messages) != 0 {
+ t.Fatalf("pending boundary read calls=%d messages=%+v", fc.historyCalls, page.Messages)
+ }
+}
+
+func TestThreadPendingFreshBoundaryReturnsEmptyWithThreadID(t *testing.T) {
+ q := &fakeHistoryQueries{binding: groupBinding("50.000000"), inst: activeSlackInstall()}
+ fc := &fakeHistoryClient{repliesMsgs: []slack.Message{msg("U1", "old context", "52.000000")}}
+ h := newTestHistory(q, fc)
+ page, err := h.Thread(context.Background(), uid(9), "", channel.HistoryOptions{BoundaryPending: true})
+ if err != nil {
+ t.Fatalf("Thread: %v", err)
+ }
+ if fc.repliesCalls != 0 || fc.historyCalls != 0 || len(page.Messages) != 0 {
+ t.Fatalf("pending boundary read calls=%d/%d messages=%+v", fc.repliesCalls, fc.historyCalls, page.Messages)
+ }
+ if page.ChannelType != "slack" || page.ThreadID != "50.000000" {
+ t.Fatalf("pending boundary target = %q/%q, want slack/50.000000", page.ChannelType, page.ThreadID)
+ }
+}
+
// TestThreadCurrent reads the session's own thread via conversations.replies.
func TestThreadCurrent(t *testing.T) {
q := &fakeHistoryQueries{binding: groupBinding("50.000000"), inst: activeSlackInstall()}
diff --git a/server/internal/integrations/slack/outbound.go b/server/internal/integrations/slack/outbound.go
index e68cb69040..13c6c31983 100644
--- a/server/internal/integrations/slack/outbound.go
+++ b/server/internal/integrations/slack/outbound.go
@@ -27,6 +27,7 @@ type outboundQueries interface {
TaskHasChannelIngestedMessages(ctx context.Context, taskID pgtype.UUID) (bool, error)
GetChannelChatSessionBindingBySession(ctx context.Context, arg db.GetChannelChatSessionBindingBySessionParams) (db.ChannelChatSessionBinding, error)
GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error)
+ SetChatMessageChannelOutboundProvenanceByTask(ctx context.Context, arg db.SetChatMessageChannelOutboundProvenanceByTaskParams) (int64, error)
}
// replySender posts one reply. Satisfied by *slackSender, so the outbound path
@@ -137,13 +138,34 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {
return fmt.Errorf("decode slack credentials: %w", err)
}
channelID, threadTS := outboundTarget(binding)
- if _, err := o.newSender(creds).Send(ctx, channel.OutboundMessage{
+ result, err := o.newSender(creds).Send(ctx, channel.OutboundMessage{
ChatID: channelID,
Text: content,
ThreadID: threadTS,
- }); err != nil {
+ })
+ if err != nil {
return fmt.Errorf("post slack reply: %w", err)
}
+ messageIDs := result.MessageIDs
+ if len(messageIDs) == 0 && result.MessageID != "" {
+ messageIDs = []string{result.MessageID}
+ }
+ if len(messageIDs) == 0 {
+ return errors.New("post slack reply: provider returned no message id")
+ }
+ rows, err := o.q.SetChatMessageChannelOutboundProvenanceByTask(ctx, db.SetChatMessageChannelOutboundProvenanceByTaskParams{
+ ChannelType: pgtype.Text{String: string(TypeSlack), Valid: true},
+ InstallationID: binding.InstallationID,
+ ChannelChatID: pgtype.Text{String: channelID, Valid: true},
+ MessageIds: messageIDs,
+ TaskID: taskID,
+ })
+ if err != nil {
+ return fmt.Errorf("record slack reply provenance: %w", err)
+ }
+ if rows != 1 {
+ return fmt.Errorf("record slack reply provenance: updated %d assistant rows, want 1", rows)
+ }
return nil
}
diff --git a/server/internal/integrations/slack/outbound_test.go b/server/internal/integrations/slack/outbound_test.go
index 5faa7f6f11..1d9bf082d3 100644
--- a/server/internal/integrations/slack/outbound_test.go
+++ b/server/internal/integrations/slack/outbound_test.go
@@ -30,6 +30,9 @@ type fakeOutboundQueries struct {
task db.AgentTaskQueue
taskErr error
taskChannelIngested bool
+ provenanceRows int64
+ provenanceErr error
+ gotProvenance db.SetChatMessageChannelOutboundProvenanceByTaskParams
}
func (f *fakeOutboundQueries) GetAgentTask(context.Context, pgtype.UUID) (db.AgentTaskQueue, error) {
@@ -48,14 +51,26 @@ func (f *fakeOutboundQueries) GetChannelInstallation(context.Context, db.GetChan
return f.inst, f.instErr
}
+func (f *fakeOutboundQueries) SetChatMessageChannelOutboundProvenanceByTask(_ context.Context, arg db.SetChatMessageChannelOutboundProvenanceByTaskParams) (int64, error) {
+ f.gotProvenance = arg
+ if f.provenanceRows == 0 && f.provenanceErr == nil {
+ return 1, nil
+ }
+ return f.provenanceRows, f.provenanceErr
+}
+
type fakeSender struct {
called int
got channel.OutboundMessage
+ result channel.SendResult
}
func (f *fakeSender) Send(_ context.Context, out channel.OutboundMessage) (channel.SendResult, error) {
f.called++
f.got = out
+ if len(f.result.MessageIDs) > 0 || f.result.MessageID != "" {
+ return f.result, nil
+ }
return channel.SendResult{MessageID: "1.1"}, nil
}
@@ -121,13 +136,22 @@ func TestOutbound_PostsSealedChannelTaskReply(t *testing.T) {
},
inst: db.ChannelInstallation{ID: uid(1), Status: "active", Config: slackInstallConfigJSON()},
}
- fs := &fakeSender{}
+ fs := &fakeSender{result: channel.SendResult{MessageID: "1.2", MessageIDs: []string{"1.1", "1.2"}}}
newTestOutbound(q, fs).handleEvent(chatDoneEvent("00000000-0000-0000-0000-000000000001", "channel answer"))
if fs.called != 1 {
t.Fatalf("sender called %d times, want 1 for a sealed channel task", fs.called)
}
+ if len(q.gotProvenance.MessageIds) != 2 || q.gotProvenance.MessageIds[0] != "1.1" || q.gotProvenance.MessageIds[1] != "1.2" {
+ t.Fatalf("recorded message ids = %v, want [1.1 1.2]", q.gotProvenance.MessageIds)
+ }
+ if !q.gotProvenance.ChannelType.Valid || q.gotProvenance.ChannelType.String != "slack" {
+ t.Fatalf("recorded channel type = %+v, want slack", q.gotProvenance.ChannelType)
+ }
+ if q.gotProvenance.InstallationID != uid(1) || !q.gotProvenance.ChannelChatID.Valid || q.gotProvenance.ChannelChatID.String != "C123" {
+ t.Fatalf("recorded target = installation:%+v chat:%+v", q.gotProvenance.InstallationID, q.gotProvenance.ChannelChatID)
+ }
}
func TestOutbound_PostsReplyToBoundSlackChannel(t *testing.T) {
diff --git a/server/internal/integrations/slack/resolvers.go b/server/internal/integrations/slack/resolvers.go
index 6d9d362322..6a612253ac 100644
--- a/server/internal/integrations/slack/resolvers.go
+++ b/server/internal/integrations/slack/resolvers.go
@@ -331,8 +331,8 @@ func (r *sessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessio
})
}
-func (r *sessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) error {
- return r.session.MarkPendingFresh(ctx, sessionID)
+func (r *sessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error {
+ return r.session.MarkPendingFresh(ctx, sessionID, messageID)
}
func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {
diff --git a/server/internal/integrations/telegram/resolvers.go b/server/internal/integrations/telegram/resolvers.go
index da7cca7bbd..d76c864300 100644
--- a/server/internal/integrations/telegram/resolvers.go
+++ b/server/internal/integrations/telegram/resolvers.go
@@ -192,7 +192,17 @@ func (r *deduper) Release(ctx context.Context, installationID pgtype.UUID, messa
// ---- session bind / append ----
-type sessionBinder struct{ session *engine.ChatSession }
+// chatSession is the shared engine session surface used by the Telegram
+// adapter. Keeping the adapter behind this narrow seam makes its parameter
+// mapping testable without a database.
+type chatSession interface {
+ EnsureSession(ctx context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error)
+ MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error
+ AppendUserMessage(ctx context.Context, in engine.AppendInput) (engine.AppendResult, error)
+ BindMediaRefs(ctx context.Context, in engine.BindMediaInput) error
+}
+
+type sessionBinder struct{ session chatSession }
func (r *sessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessionParams) (pgtype.UUID, error) {
bindingKey, config, _ := telegramSessionRouting(p.Message)
@@ -207,8 +217,8 @@ func (r *sessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessio
})
}
-func (r *sessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) error {
- return r.session.MarkPendingFresh(ctx, sessionID)
+func (r *sessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error {
+ return r.session.MarkPendingFresh(ctx, sessionID, messageID)
}
func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {
@@ -227,6 +237,7 @@ func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams
ThreadID: replyThread,
ClaimToken: p.ClaimToken,
MediaPendingSeconds: p.MediaPendingSeconds,
+ ForceFresh: p.Message.ForceFresh,
})
}
diff --git a/server/internal/integrations/telegram/resolvers_test.go b/server/internal/integrations/telegram/resolvers_test.go
new file mode 100644
index 0000000000..98e1be16e3
--- /dev/null
+++ b/server/internal/integrations/telegram/resolvers_test.go
@@ -0,0 +1,56 @@
+package telegram
+
+import (
+ "context"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+)
+
+type captureChatSession struct {
+ appendIn engine.AppendInput
+}
+
+func (f *captureChatSession) EnsureSession(context.Context, engine.EnsureSessionInput) (pgtype.UUID, error) {
+ return pgtype.UUID{}, nil
+}
+
+func (f *captureChatSession) MarkPendingFresh(context.Context, pgtype.UUID, string) error {
+ return nil
+}
+
+func (f *captureChatSession) AppendUserMessage(_ context.Context, in engine.AppendInput) (engine.AppendResult, error) {
+ f.appendIn = in
+ return engine.AppendResult{}, nil
+}
+
+func (f *captureChatSession) BindMediaRefs(context.Context, engine.BindMediaInput) error {
+ return nil
+}
+
+func TestTelegramSessionBinder_AppendPreservesFreshContextIntent(t *testing.T) {
+ session := &captureChatSession{}
+ binder := &sessionBinder{session: session}
+
+ if _, err := binder.AppendMessage(context.Background(), engine.AppendParams{
+ Message: channel.InboundMessage{
+ MessageID: "-100200:10",
+ Text: "summarize this",
+ ForceFresh: true,
+ Source: channel.Source{
+ ChatID: "-100200",
+ ChatType: channel.ChatTypeGroup,
+ ThreadID: "42",
+ },
+ },
+ }); err != nil {
+ t.Fatalf("AppendMessage: %v", err)
+ }
+
+ if !session.appendIn.ForceFresh {
+ t.Fatal("AppendUserMessage lost ForceFresh; /new <message> would remain in the previous context generation")
+ }
+}
diff --git a/server/internal/integrations/wecom/inbound_media_bind_db_test.go b/server/internal/integrations/wecom/inbound_media_bind_db_test.go
index 0cfda32e5b..70f902729e 100644
--- a/server/internal/integrations/wecom/inbound_media_bind_db_test.go
+++ b/server/internal/integrations/wecom/inbound_media_bind_db_test.go
@@ -166,7 +166,7 @@ type bindTestTasks struct {
promoted int
}
-func (*bindTestTasks) EnqueueChatTask(context.Context, db.ChatSession, pgtype.UUID, bool) (db.AgentTaskQueue, error) {
+func (*bindTestTasks) EnqueueChannelChatTask(context.Context, db.ChatSession, pgtype.UUID, bool, int64) (db.AgentTaskQueue, error) {
return db.AgentTaskQueue{}, nil
}
func (b *bindTestTasks) PromoteChannelChatTasksIfMediaReady(context.Context, pgtype.UUID) error {
diff --git a/server/internal/integrations/wecom/resolvers_test.go b/server/internal/integrations/wecom/resolvers_test.go
index 7f4df8eefa..5d02b31981 100644
--- a/server/internal/integrations/wecom/resolvers_test.go
+++ b/server/internal/integrations/wecom/resolvers_test.go
@@ -42,7 +42,7 @@ func (f *fakeSessionBinder) EnsureSession(_ context.Context, in engine.EnsureSes
f.ensureIn = in
return f.sessID, nil
}
-func (f *fakeSessionBinder) MarkPendingFresh(context.Context, pgtype.UUID) error { return nil }
+func (f *fakeSessionBinder) MarkPendingFresh(context.Context, pgtype.UUID, string) error { return nil }
func (f *fakeSessionBinder) AppendUserMessage(_ context.Context, in engine.AppendInput) (engine.AppendResult, error) {
f.appendIn = in
return engine.AppendResult{}, nil
diff --git a/server/internal/integrations/wecom/wecom_resolvers.go b/server/internal/integrations/wecom/wecom_resolvers.go
index 64932337cb..77207fbbbf 100644
--- a/server/internal/integrations/wecom/wecom_resolvers.go
+++ b/server/internal/integrations/wecom/wecom_resolvers.go
@@ -84,7 +84,7 @@ func NewResolverSet(
// production value.
type engineSessionBinder interface {
EnsureSession(ctx context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error)
- MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) error
+ MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error
AppendUserMessage(ctx context.Context, in engine.AppendInput) (engine.AppendResult, error)
BindMediaRefs(ctx context.Context, in engine.BindMediaInput) error
}
@@ -227,8 +227,8 @@ func (r *sessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessio
})
}
-func (r *sessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID) error {
- return r.session.MarkPendingFresh(ctx, sessionID)
+func (r *sessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error {
+ return r.session.MarkPendingFresh(ctx, sessionID, messageID)
}
func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {
diff --git a/server/internal/migrations/channel_chat_context_generation_migration_test.go b/server/internal/migrations/channel_chat_context_generation_migration_test.go
new file mode 100644
index 0000000000..5645a51318
--- /dev/null
+++ b/server/internal/migrations/channel_chat_context_generation_migration_test.go
@@ -0,0 +1,334 @@
+package migrations
+
+import (
+ "context"
+ "os"
+ "testing"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+const channelContextMigrationTestSchema = "channel_context_migration_test"
+
+func TestChannelChatContextGenerationMigrationsUpDownAndLegacyRows(t *testing.T) {
+ dbURL := os.Getenv("DATABASE_URL")
+ if dbURL == "" {
+ t.Skip("integration test requires Postgres at DATABASE_URL")
+ }
+
+ ctx := context.Background()
+ pool, err := pgxpool.New(ctx, dbURL)
+ if err != nil {
+ t.Fatalf("connect to Postgres: %v", err)
+ }
+ defer pool.Close()
+
+ conn, err := pool.Acquire(ctx)
+ if err != nil {
+ t.Fatalf("acquire Postgres connection: %v", err)
+ }
+ defer conn.Release()
+
+ cleanup := func() {
+ _, _ = pool.Exec(context.Background(), "DROP SCHEMA IF EXISTS "+channelContextMigrationTestSchema+" CASCADE")
+ }
+ cleanup()
+ t.Cleanup(cleanup)
+ if _, err := conn.Exec(ctx, "CREATE SCHEMA "+channelContextMigrationTestSchema); err != nil {
+ t.Fatalf("create isolated migration schema: %v", err)
+ }
+ if _, err := conn.Exec(ctx, `SELECT set_config('search_path', $1, false)`, channelContextMigrationTestSchema); err != nil {
+ t.Fatalf("set isolated migration search path: %v", err)
+ }
+
+ if _, err := conn.Exec(ctx, `
+ CREATE TABLE channel_chat_session_binding (
+ chat_session_id UUID NOT NULL,
+ pending_fresh BOOLEAN NOT NULL DEFAULT FALSE
+ );
+ CREATE TABLE chat_message (
+ id UUID NOT NULL,
+ chat_session_id UUID NOT NULL,
+ role TEXT NOT NULL,
+ channel_ingested BOOLEAN NOT NULL DEFAULT FALSE,
+ task_id UUID
+ );
+ CREATE TABLE agent_task_queue (
+ id UUID NOT NULL,
+ chat_session_id UUID,
+ status TEXT NOT NULL DEFAULT 'queued',
+ parent_task_id UUID,
+ chat_input_task_id UUID,
+ retry_of_task_id UUID,
+ rerun_of_task_id UUID
+ );
+ `); err != nil {
+ t.Fatalf("create pre-migration tables: %v", err)
+ }
+
+ const sessionID = "c3440000-0000-4000-8000-000000000001"
+ const directSessionID = "c3440000-0000-4000-8000-000000000009"
+ const directTaskID = "c3440000-0000-4000-8000-000000000010"
+ const terminalTaskID = "c3440000-0000-4000-8000-000000000011"
+ if _, err := conn.Exec(ctx, `INSERT INTO channel_chat_session_binding (chat_session_id) VALUES ($1)`, sessionID); err != nil {
+ t.Fatalf("seed pre-migration binding: %v", err)
+ }
+ if _, err := conn.Exec(ctx, `
+ INSERT INTO chat_message (id, chat_session_id, role) VALUES
+ ('c3440000-0000-4000-8000-000000000002', $1, 'user'),
+ ('c3440000-0000-4000-8000-000000000003', $1, 'assistant')
+ `, sessionID); err != nil {
+ t.Fatalf("seed pre-migration messages: %v", err)
+ }
+ if _, err := conn.Exec(ctx, `
+ INSERT INTO agent_task_queue (id, chat_session_id, status)
+ VALUES ('c3440000-0000-4000-8000-000000000004', $1, 'queued'),
+ ($2, $3, 'queued'),
+ ($4, $1, 'completed'),
+ ('c3440000-0000-4000-8000-000000000020', $1, 'dispatched'),
+ ('c3440000-0000-4000-8000-000000000021', $1, 'running'),
+ ('c3440000-0000-4000-8000-000000000022', $1, 'waiting_local_directory'),
+ ('c3440000-0000-4000-8000-000000000023', $1, 'deferred')
+ `, sessionID, directTaskID, directSessionID, terminalTaskID); err != nil {
+ t.Fatalf("seed pre-migration task: %v", err)
+ }
+
+ applyMigrationFile(t, ctx, conn.Conn(), "377_channel_chat_context_generation.up.sql")
+ // The migration runner records each version after executing its SQL. If the
+ // ledger write fails, the next startup executes the same file again.
+ applyMigrationFile(t, ctx, conn.Conn(), "377_channel_chat_context_generation.up.sql")
+ applyMigrationFile(t, ctx, conn.Conn(), "378_channel_chat_context_generation_key.up.sql")
+ applyMigrationFile(t, ctx, conn.Conn(), "378_channel_chat_context_generation_key.up.sql")
+ applyMigrationFile(t, ctx, conn.Conn(), "379_channel_context_mixed_version_guard.up.sql")
+ applyMigrationFile(t, ctx, conn.Conn(), "379_channel_context_mixed_version_guard.up.sql")
+
+ var bindingRevision, generationRevision int64
+ if err := conn.QueryRow(ctx, `
+ SELECT binding.context_revision, generation.revision
+ FROM channel_chat_session_binding AS binding
+ JOIN channel_chat_context_generation AS generation
+ ON generation.chat_session_id = binding.chat_session_id
+ WHERE binding.chat_session_id = $1
+ `, sessionID).Scan(&bindingRevision, &generationRevision); err != nil {
+ t.Fatalf("read backfilled generation: %v", err)
+ }
+ if bindingRevision != 1 || generationRevision != 1 {
+ t.Fatalf("backfilled revisions = binding:%d generation:%d, want 1/1", bindingRevision, generationRevision)
+ }
+
+ var userRevision, assistantRevision *int64
+ if err := conn.QueryRow(ctx, `
+ SELECT
+ MAX(channel_context_revision) FILTER (WHERE role = 'user'),
+ MAX(channel_context_revision) FILTER (WHERE role = 'assistant')
+ FROM chat_message
+ WHERE chat_session_id = $1
+ `, sessionID).Scan(&userRevision, &assistantRevision); err != nil {
+ t.Fatalf("read message backfill: %v", err)
+ }
+ if userRevision != nil {
+ t.Fatalf("legacy user message revision = %v, want NULL (readers treat it as revision 1)", *userRevision)
+ }
+ if assistantRevision != nil {
+ t.Fatalf("assistant message revision = %v, want NULL (derived from its task)", *assistantRevision)
+ }
+
+ var backfilled int
+ if err := conn.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE chat_session_id = $1 AND channel_context_revision = 1`, sessionID).Scan(&backfilled); err != nil {
+ t.Fatalf("read task backfill: %v", err)
+ }
+ if backfilled != 5 {
+ t.Fatalf("backfilled in-flight channel tasks = %d, want 5", backfilled)
+ }
+ var terminalTaskRevision *int64
+ if err := conn.QueryRow(ctx, `SELECT channel_context_revision FROM agent_task_queue WHERE id = $1`, terminalTaskID).Scan(&terminalTaskRevision); err != nil {
+ t.Fatalf("read terminal task backfill: %v", err)
+ }
+ if terminalTaskRevision != nil {
+ t.Fatalf("terminal channel task revision = %v, want NULL", *terminalTaskRevision)
+ }
+ var directTaskRevision *int64
+ if err := conn.QueryRow(ctx, `SELECT channel_context_revision FROM agent_task_queue WHERE id = $1`, directTaskID).Scan(&directTaskRevision); err != nil {
+ t.Fatalf("read direct task backfill: %v", err)
+ }
+ if directTaskRevision != nil {
+ t.Fatalf("legacy direct task revision = %v, want NULL", *directTaskRevision)
+ }
+
+ assertChannelContextOwnershipGuard(t, ctx, conn.Conn(), sessionID, directSessionID, directTaskID)
+
+ assertChannelContextIndex(t, ctx, conn.Conn())
+ if _, err := conn.Exec(ctx, `
+ INSERT INTO channel_chat_context_generation (chat_session_id, revision)
+ VALUES ($1, 1)
+ `, sessionID); !isUniqueViolationMigration(err) {
+ t.Fatalf("duplicate generation error = %v, want unique violation", err)
+ }
+
+ applyMigrationFile(t, ctx, conn.Conn(), "379_channel_context_mixed_version_guard.down.sql")
+ applyMigrationFile(t, ctx, conn.Conn(), "378_channel_chat_context_generation_key.down.sql")
+ applyMigrationFile(t, ctx, conn.Conn(), "377_channel_chat_context_generation.down.sql")
+
+ var generationExists bool
+ if err := conn.QueryRow(ctx, `SELECT to_regclass($1) IS NOT NULL`, channelContextMigrationTestSchema+".channel_chat_context_generation").Scan(&generationExists); err != nil {
+ t.Fatalf("inspect rolled-back generation table: %v", err)
+ }
+ if generationExists {
+ t.Fatal("channel_chat_context_generation still exists after down migrations")
+ }
+ for _, column := range []string{
+ "channel_chat_session_binding.context_revision",
+ "chat_message.channel_context_revision",
+ "chat_message.channel_outbound_type",
+ "chat_message.channel_outbound_installation_id",
+ "chat_message.channel_outbound_chat_id",
+ "chat_message.channel_outbound_message_ids",
+ "agent_task_queue.channel_context_revision",
+ } {
+ var exists bool
+ if err := conn.QueryRow(ctx, `
+ SELECT EXISTS (
+ SELECT 1
+ FROM information_schema.columns
+ WHERE table_schema = $1
+ AND table_name = split_part($2, '.', 1)
+ AND column_name = split_part($2, '.', 2)
+ )
+ `, channelContextMigrationTestSchema, column).Scan(&exists); err != nil {
+ t.Fatalf("inspect rolled-back column %s: %v", column, err)
+ }
+ if exists {
+ t.Fatalf("column %s still exists after down migrations", column)
+ }
+ }
+}
+
+func assertChannelContextOwnershipGuard(t *testing.T, ctx context.Context, conn *pgx.Conn, sessionID, directSessionID, directTaskID string) {
+ t.Helper()
+ const newMessageID = "c3440000-0000-4000-8000-000000000006"
+ const taskID = "c3440000-0000-4000-8000-000000000007"
+ const retryTaskID = "c3440000-0000-4000-8000-000000000008"
+ const rerunTaskID = "c3440000-0000-4000-8000-000000000009"
+
+ statements := []struct {
+ sql string
+ args []any
+ }{
+ {`UPDATE channel_chat_session_binding SET context_revision = 2, pending_fresh = TRUE WHERE chat_session_id = $1`, []any{sessionID}},
+ {`INSERT INTO channel_chat_context_generation (chat_session_id, revision, pending_fresh) VALUES ($1, 2, TRUE)`, []any{sessionID}},
+ {`INSERT INTO chat_message (id, chat_session_id, role, channel_context_revision) VALUES ($2, $1, 'user', 2)`, []any{sessionID, newMessageID}},
+ {`INSERT INTO agent_task_queue (id, chat_session_id, channel_context_revision) VALUES ($2, $1, 2)`, []any{sessionID, taskID}},
+ {`INSERT INTO agent_task_queue (id, chat_session_id, retry_of_task_id) VALUES ($2, $1, $3)`, []any{directSessionID, retryTaskID, directTaskID}},
+ {`INSERT INTO agent_task_queue (id, chat_session_id, rerun_of_task_id) VALUES ($2, $1, $3)`, []any{directSessionID, rerunTaskID, directTaskID}},
+ }
+ for _, statement := range statements {
+ if _, err := conn.Exec(ctx, statement.sql, statement.args...); err != nil {
+ t.Fatalf("seed ownership guard fixture: %v", err)
+ }
+ }
+
+ for _, id := range []string{retryTaskID, rerunTaskID} {
+ var revision *int64
+ if err := conn.QueryRow(ctx, `SELECT channel_context_revision FROM agent_task_queue WHERE id = $1`, id).Scan(&revision); err != nil {
+ t.Fatalf("read direct retry/rerun revision: %v", err)
+ }
+ if revision != nil {
+ t.Fatalf("direct retry/rerun %s revision = %v, want NULL", id, *revision)
+ }
+ }
+
+ if _, err := conn.Exec(ctx, `
+ UPDATE chat_message SET task_id = $1
+ WHERE chat_session_id = $2 AND role = 'user' AND task_id IS NULL
+ `, taskID, sessionID); err != nil {
+ t.Fatalf("seal generation-2 batch: %v", err)
+ }
+
+ var newOwner *string
+ if err := conn.QueryRow(ctx, `
+ SELECT task_id::text
+ FROM chat_message
+ WHERE id = $1
+ `, newMessageID).Scan(&newOwner); err != nil {
+ t.Fatalf("read generation-2 batch ownership: %v", err)
+ }
+ var legacyOwner *string
+ if err := conn.QueryRow(ctx, `SELECT task_id::text FROM chat_message WHERE id = $1`, "c3440000-0000-4000-8000-000000000002").Scan(&legacyOwner); err != nil {
+ t.Fatalf("read legacy message owner: %v", err)
+ }
+ if legacyOwner != nil {
+ t.Fatalf("revision-1 legacy message crossed into revision-2 task: owner=%s", *legacyOwner)
+ }
+ if newOwner == nil || *newOwner != taskID {
+ t.Fatalf("revision-2 message owner = %v, want %s", newOwner, taskID)
+ }
+
+ if _, err := conn.Exec(ctx, `
+ INSERT INTO chat_message (id, chat_session_id, role, task_id)
+ VALUES ('c3440000-0000-4000-8000-000000000030', $1, 'assistant', $2)
+ `, sessionID, taskID); err != nil {
+ t.Fatalf("seed assistant outbound row: %v", err)
+ }
+ q := db.New(conn)
+ rows, err := q.SetChatMessageChannelOutboundProvenanceByTask(ctx, db.SetChatMessageChannelOutboundProvenanceByTaskParams{
+ ChannelType: pgtype.Text{String: "slack", Valid: true},
+ InstallationID: util.MustParseUUID("c3440000-0000-4000-8000-000000000040"),
+ ChannelChatID: pgtype.Text{String: "C123", Valid: true},
+ MessageIds: []string{"104.000000", "105.000000"},
+ TaskID: util.MustParseUUID(taskID),
+ })
+ if err != nil || rows != 1 {
+ t.Fatalf("record outbound provenance: rows=%d err=%v", rows, err)
+ }
+ ids, err := q.ListChannelOutboundMessageIDsForContext(ctx, db.ListChannelOutboundMessageIDsForContextParams{
+ ChatSessionID: util.MustParseUUID(sessionID),
+ ChannelType: pgtype.Text{String: "slack", Valid: true},
+ InstallationID: util.MustParseUUID("c3440000-0000-4000-8000-000000000040"),
+ ChannelChatID: pgtype.Text{String: "C123", Valid: true},
+ ChannelContextRevision: pgtype.Int8{Int64: 2, Valid: true},
+ CandidateMessageIds: []string{"103.000000", "104.000000", "105.000000"},
+ })
+ if err != nil {
+ t.Fatalf("list outbound provenance: %v", err)
+ }
+ if len(ids) != 2 || ids[0] != "104.000000" || ids[1] != "105.000000" {
+ t.Fatalf("outbound provenance ids = %v", ids)
+ }
+ otherTargetIDs, err := q.ListChannelOutboundMessageIDsForContext(ctx, db.ListChannelOutboundMessageIDsForContextParams{
+ ChatSessionID: util.MustParseUUID(sessionID),
+ ChannelType: pgtype.Text{String: "slack", Valid: true},
+ InstallationID: util.MustParseUUID("c3440000-0000-4000-8000-000000000041"),
+ ChannelChatID: pgtype.Text{String: "C123", Valid: true},
+ ChannelContextRevision: pgtype.Int8{Int64: 2, Valid: true},
+ CandidateMessageIds: []string{"104.000000"},
+ })
+ if err != nil {
+ t.Fatalf("list outbound provenance for other installation: %v", err)
+ }
+ if len(otherTargetIDs) != 0 {
+ t.Fatalf("other installation reused outbound ids = %v", otherTargetIDs)
+ }
+}
+
+func assertChannelContextIndex(t *testing.T, ctx context.Context, conn *pgx.Conn) {
+ t.Helper()
+ var unique, valid, ready bool
+ err := conn.QueryRow(ctx, `
+ SELECT index.indisunique, index.indisvalid, index.indisready
+ FROM pg_index AS index
+ JOIN pg_class AS relation ON relation.oid = index.indexrelid
+ JOIN pg_namespace AS namespace ON namespace.oid = relation.relnamespace
+ WHERE namespace.nspname = $1
+ AND relation.relname = 'channel_chat_context_generation_session_revision_idx'
+ `, channelContextMigrationTestSchema).Scan(&unique, &valid, &ready)
+ if err != nil {
+ t.Fatalf("inspect generation index: %v", err)
+ }
+ if !unique || !valid || !ready {
+ t.Fatalf("generation index flags = unique:%t valid:%t ready:%t, want all true", unique, valid, ready)
+ }
+}
diff --git a/server/internal/service/retry_deferred_test.go b/server/internal/service/retry_deferred_test.go
index 97f94bf5b2..9be369d27e 100644
--- a/server/internal/service/retry_deferred_test.go
+++ b/server/internal/service/retry_deferred_test.go
@@ -33,8 +33,8 @@ func TestCreateRetryTaskFireAtControlsDeferral(t *testing.T) {
// which the schedule wants the next (final) retry deferred.
var parentID pgtype.UUID
if err := pool.QueryRow(ctx, `
- INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, attempt, max_attempts, failure_reason, session_id, work_dir)
- VALUES ($1, $2, $3, 'failed', 0, 2, 2, 'agent_error.provider_network', 'src-session', '/tmp/src-workdir')
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, attempt, max_attempts, failure_reason, session_id, work_dir, channel_context_revision)
+ VALUES ($1, $2, $3, 'failed', 0, 2, 2, 'agent_error.provider_network', 'src-session', '/tmp/src-workdir', 7)
RETURNING id
`, agentID, runtimeID, issueID).Scan(&parentID); err != nil {
t.Fatalf("insert parent task: %v", err)
@@ -81,6 +81,9 @@ func TestCreateRetryTaskFireAtControlsDeferral(t *testing.T) {
if child.ForceFreshSession {
t.Errorf("force_fresh_session = true, want false (provider_network resumes) for %s", util.UUIDToString(child.ID))
}
+ if !child.ChannelContextRevision.Valid || child.ChannelContextRevision.Int64 != 7 {
+ t.Errorf("channel_context_revision = %+v, want 7", child.ChannelContextRevision)
+ }
})
}
}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 8ae772e06e..c63a759ee0 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -1665,10 +1665,20 @@ var ErrChatSessionArchived = errors.New("chat task: session archived")
// latest message in the silence window. Stored on the task so the daemon brief
// can attribute the run to the right person. See MUL-2645.
//
-// forceFreshSession applies only to the task created by this call. The daemon
-// uses it to skip prior chat-session resume for this dispatch without clearing
-// the chat session's stored resume pointer for future normal messages.
+// forceFreshSession applies only to the task created by this call. Channel
+// callers additionally use EnqueueChannelChatTask to snapshot the durable
+// context revision; its batch seal and history reads cannot cross that boundary.
+// The daemon skips prior provider-session resume for a fresh dispatch without
+// clearing the Chat's stored resume pointer for later generations.
func (s *TaskService) EnqueueChatTask(ctx context.Context, chatSession db.ChatSession, initiatorUserID pgtype.UUID, forceFreshSession bool) (db.AgentTaskQueue, error) {
+ return s.enqueueChatTask(ctx, chatSession, initiatorUserID, forceFreshSession, 0)
+}
+
+func (s *TaskService) EnqueueChannelChatTask(ctx context.Context, chatSession db.ChatSession, initiatorUserID pgtype.UUID, forceFreshSession bool, contextRevision int64) (db.AgentTaskQueue, error) {
+ return s.enqueueChatTask(ctx, chatSession, initiatorUserID, forceFreshSession, contextRevision)
+}
+
+func (s *TaskService) enqueueChatTask(ctx context.Context, chatSession db.ChatSession, initiatorUserID pgtype.UUID, forceFreshSession bool, contextRevision int64) (db.AgentTaskQueue, error) {
agent, err := s.Queries.GetAgent(ctx, chatSession.AgentID)
if err != nil {
slog.Error("chat task enqueue failed", "chat_session_id", util.UUIDToString(chatSession.ID), "error", err)
@@ -1736,14 +1746,36 @@ func (s *TaskService) EnqueueChatTask(ctx context.Context, chatSession db.ChatSe
// Lock the channel binding only after the chat_session lock above. The
// append path touches chat_session before binding as well, so this order
// avoids an ABBA edge while keeping pending fresh in the enqueue transaction.
- pendingFresh, err := qtx.LockChannelChatSessionPendingFresh(ctx, chatSession.ID)
+ binding, err := qtx.LockChannelChatSessionBindingForContext(ctx, chatSession.ID)
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
- return db.AgentTaskQueue{}, fmt.Errorf("lock channel pending fresh: %w", err)
+ return db.AgentTaskQueue{}, fmt.Errorf("lock channel chat binding: %w", err)
+ }
+ if errors.Is(err, pgx.ErrNoRows) && contextRevision > 0 {
+ return db.AgentTaskQueue{}, fmt.Errorf("lock channel chat binding: %w", err)
+ }
+ pendingFresh := false
+ if err == nil {
+ if err := qtx.EnsureChannelChatContextGeneration(ctx, chatSession.ID); err != nil {
+ return db.AgentTaskQueue{}, fmt.Errorf("ensure channel context generation: %w", err)
+ }
+ if contextRevision <= 0 {
+ contextRevision = binding.ContextRevision
+ }
+ generation, err := qtx.LockChannelChatContextGenerationByRevision(ctx, db.LockChannelChatContextGenerationByRevisionParams{
+ ChatSessionID: chatSession.ID, Revision: contextRevision,
+ })
+ if err != nil {
+ return db.AgentTaskQueue{}, fmt.Errorf("lock channel context generation: %w", err)
+ }
+ pendingFresh = generation.PendingFresh || (contextRevision == binding.ContextRevision && binding.PendingFresh)
}
- if err == nil && pendingFresh {
+ if pendingFresh {
forceFreshSession = true
}
- mediaPendingUntil, err := qtx.GetChannelMediaPendingUntil(ctx, chatSession.ID)
+ mediaPendingUntil, err := qtx.GetChannelMediaPendingUntil(ctx, db.GetChannelMediaPendingUntilParams{
+ ChatSessionID: chatSession.ID,
+ ChannelContextRevision: pgtype.Int8{Int64: contextRevision, Valid: contextRevision > 0},
+ })
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
slog.Error("chat task enqueue failed", "chat_session_id", util.UUIDToString(chatSession.ID), "error", err)
return db.AgentTaskQueue{}, fmt.Errorf("load channel media pending deadline: %w", err)
@@ -1765,11 +1797,12 @@ func (s *TaskService) EnqueueChatTask(ctx context.Context, chatSession db.ChatSe
Bool: forceFreshSession,
Valid: true,
},
- RuntimeMcpOverlay: runtimeMCPOverlay.Overlay,
- RuntimeConnectedApps: runtimeMCPOverlay.ConnectedApps,
- OriginatorSource: attrSource,
- TriggerEvidenceKind: attrEvidenceKind,
- TriggerEvidenceRefID: attrEvidenceRef,
+ RuntimeMcpOverlay: runtimeMCPOverlay.Overlay,
+ RuntimeConnectedApps: runtimeMCPOverlay.ConnectedApps,
+ OriginatorSource: attrSource,
+ TriggerEvidenceKind: attrEvidenceKind,
+ TriggerEvidenceRefID: attrEvidenceRef,
+ ChannelContextRevision: pgtype.Int8{Int64: contextRevision, Valid: contextRevision > 0},
})
if err != nil {
slog.Error("chat task enqueue failed", "chat_session_id", util.UUIDToString(chatSession.ID), "error", err)
@@ -1796,7 +1829,14 @@ func (s *TaskService) EnqueueChatTask(ctx context.Context, chatSession db.ChatSe
return db.AgentTaskQueue{}, fmt.Errorf("defer chat task for sealed pending media: %w", err)
}
if pendingFresh {
- if err := qtx.ClearChannelChatSessionPendingFresh(ctx, chatSession.ID); err != nil {
+ if err := qtx.ClearChannelChatContextPendingFresh(ctx, db.ClearChannelChatContextPendingFreshParams{
+ ChatSessionID: chatSession.ID, Revision: contextRevision,
+ }); err != nil {
+ return db.AgentTaskQueue{}, fmt.Errorf("clear channel context pending fresh: %w", err)
+ }
+ if err := qtx.ClearChannelChatSessionPendingFreshForRevision(ctx, db.ClearChannelChatSessionPendingFreshForRevisionParams{
+ ChatSessionID: chatSession.ID, Revision: contextRevision,
+ }); err != nil {
return db.AgentTaskQueue{}, fmt.Errorf("clear channel pending fresh: %w", err)
}
}
diff --git a/server/internal/service/task_channel_media_race_test.go b/server/internal/service/task_channel_media_race_test.go
index 8f832ae5ae..f3b59d8486 100644
--- a/server/internal/service/task_channel_media_race_test.go
+++ b/server/internal/service/task_channel_media_race_test.go
@@ -42,6 +42,33 @@ type raceInjectTx struct {
inject func()
}
+type failNamedExecTxStarter struct {
+ pool *pgxpool.Pool
+ queryName string
+ err error
+}
+
+func (s *failNamedExecTxStarter) Begin(ctx context.Context) (pgx.Tx, error) {
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return &failNamedExecTx{Tx: tx, queryName: s.queryName, err: s.err}, nil
+}
+
+type failNamedExecTx struct {
+ pgx.Tx
+ queryName string
+ err error
+}
+
+func (t *failNamedExecTx) Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) {
+ if strings.Contains(sql, t.queryName) {
+ return pgconn.CommandTag{}, t.err
+ }
+ return t.Tx.Exec(ctx, sql, args...)
+}
+
func (t *raceInjectTx) Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) {
if strings.Contains(sql, "LinkUnownedChannelChatMessagesToTask") && t.inject != nil {
t.inject()
@@ -50,6 +77,123 @@ func (t *raceInjectTx) Exec(ctx context.Context, sql string, args ...any) (pgcon
return t.Tx.Exec(ctx, sql, args...)
}
+func TestEnqueueChannelChatTask_ContextClearFailureRollsBackTaskAndSeal(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)
+
+ var chatSessionID, installationID, messageID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id)
+ VALUES ($1, $2, $3) RETURNING id
+ `, workspaceID, agentID, userID).Scan(&chatSessionID); err != nil {
+ t.Fatalf("seed chat session: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO channel_installation (
+ workspace_id, agent_id, channel_type, config, installer_user_id, status
+ ) VALUES ($1, $2, 'slack', '{}'::jsonb, $3, 'active')
+ RETURNING id
+ `, workspaceID, agentID, userID).Scan(&installationID); err != nil {
+ t.Fatalf("seed channel installation: %v", err)
+ }
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO channel_chat_session_binding (
+ chat_session_id, installation_id, channel_type, channel_chat_id,
+ chat_type, pending_fresh, context_revision
+ ) VALUES ($1, $2, 'slack', $3, 'p2p', TRUE, 1)
+ `, chatSessionID, installationID, "rollback-"+chatSessionID); err != nil {
+ t.Fatalf("seed channel binding: %v", err)
+ }
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO channel_chat_context_generation (
+ chat_session_id, revision, pending_fresh
+ ) VALUES ($1, 1, TRUE)
+ `, chatSessionID); err != nil {
+ t.Fatalf("seed channel context: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO chat_message (
+ chat_session_id, role, content, channel_ingested, channel_context_revision
+ ) VALUES ($1, 'user', 'keep me unowned', TRUE, 1)
+ RETURNING id
+ `, chatSessionID).Scan(&messageID); err != nil {
+ t.Fatalf("seed channel message: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_chat_context_generation WHERE chat_session_id = $1`, chatSessionID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_chat_session_binding WHERE chat_session_id = $1`, chatSessionID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_installation WHERE id = $1`, installationID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, chatSessionID)
+ })
+
+ for _, queryName := range []string{
+ "ClearChannelChatContextPendingFresh",
+ "ClearChannelChatSessionPendingFreshForRevision",
+ } {
+ t.Run(queryName, func(t *testing.T) {
+ injectedErr := errors.New("injected context clear failure")
+ svc := &TaskService{
+ Queries: q,
+ TxStarter: &failNamedExecTxStarter{
+ pool: pool, queryName: queryName, err: injectedErr,
+ },
+ Bus: events.New(),
+ }
+ _, err := svc.EnqueueChannelChatTask(ctx, db.ChatSession{
+ ID: util.MustParseUUID(chatSessionID), AgentID: util.MustParseUUID(agentID),
+ }, util.MustParseUUID(userID), false, 1)
+ if !errors.Is(err, injectedErr) {
+ t.Fatalf("EnqueueChannelChatTask error = %v, want injected clear failure", err)
+ }
+
+ var taskCount int
+ var owner pgtype.UUID
+ var generationPending, bindingPending bool
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE chat_session_id = $1`, chatSessionID).Scan(&taskCount); err != nil {
+ t.Fatalf("count rolled-back task: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `SELECT task_id FROM chat_message WHERE id = $1`, messageID).Scan(&owner); err != nil {
+ t.Fatalf("read rolled-back message owner: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `SELECT pending_fresh FROM channel_chat_context_generation WHERE chat_session_id = $1 AND revision = 1`, chatSessionID).Scan(&generationPending); err != nil {
+ t.Fatalf("read generation pending state: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `SELECT pending_fresh FROM channel_chat_session_binding WHERE chat_session_id = $1`, chatSessionID).Scan(&bindingPending); err != nil {
+ t.Fatalf("read binding pending state: %v", err)
+ }
+ if taskCount != 0 || owner.Valid || !generationPending || !bindingPending {
+ t.Fatalf("rollback state task/owner/generation/binding = %d/%v/%t/%t, want 0/NULL/true/true", taskCount, owner, generationPending, bindingPending)
+ }
+ })
+ }
+}
+
+func TestEnqueueChannelChatTask_RejectsRetiredBinding(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)
+ chatSessionID := seedChannelChatSession(t, ctx, pool, workspaceID, agentID, userID)
+
+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
+ _, err := svc.EnqueueChannelChatTask(ctx, db.ChatSession{
+ ID: util.MustParseUUID(chatSessionID), AgentID: util.MustParseUUID(agentID),
+ }, util.MustParseUUID(userID), false, 1)
+ if !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("EnqueueChannelChatTask error = %v, want missing binding", err)
+ }
+
+ var taskCount int
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE chat_session_id = $1`, chatSessionID).Scan(&taskCount); err != nil {
+ t.Fatalf("count channel tasks: %v", err)
+ }
+ if taskCount != 0 {
+ t.Fatalf("tasks created after binding retirement = %d, want 0", taskCount)
+ }
+}
+
// TestEnqueueChatTaskDefersWhenMediaMessageCommitsDuringEnqueue pins the fix
// for the enqueue-vs-append race: a media-pending message sealed into the task
// after the deadline read must still leave the task deferred (not claimable)
diff --git a/server/migrations/377_channel_chat_context_generation.down.sql b/server/migrations/377_channel_chat_context_generation.down.sql
new file mode 100644
index 0000000000..b18422c477
--- /dev/null
+++ b/server/migrations/377_channel_chat_context_generation.down.sql
@@ -0,0 +1,22 @@
+DROP TABLE IF EXISTS channel_chat_context_generation;
+
+ALTER TABLE agent_task_queue
+ DROP COLUMN IF EXISTS channel_context_revision;
+
+ALTER TABLE chat_message
+ DROP COLUMN IF EXISTS channel_outbound_message_ids;
+
+ALTER TABLE chat_message
+ DROP COLUMN IF EXISTS channel_outbound_chat_id;
+
+ALTER TABLE chat_message
+ DROP COLUMN IF EXISTS channel_outbound_installation_id;
+
+ALTER TABLE chat_message
+ DROP COLUMN IF EXISTS channel_outbound_type;
+
+ALTER TABLE chat_message
+ DROP COLUMN IF EXISTS channel_context_revision;
+
+ALTER TABLE channel_chat_session_binding
+ DROP COLUMN IF EXISTS context_revision;
diff --git a/server/migrations/377_channel_chat_context_generation.up.sql b/server/migrations/377_channel_chat_context_generation.up.sql
new file mode 100644
index 0000000000..4b1e0557d6
--- /dev/null
+++ b/server/migrations/377_channel_chat_context_generation.up.sql
@@ -0,0 +1,41 @@
+ALTER TABLE channel_chat_session_binding
+ ADD COLUMN IF NOT EXISTS context_revision BIGINT NOT NULL DEFAULT 1;
+
+ALTER TABLE chat_message
+ ADD COLUMN IF NOT EXISTS channel_context_revision BIGINT;
+
+ALTER TABLE chat_message
+ ADD COLUMN IF NOT EXISTS channel_outbound_type TEXT;
+
+ALTER TABLE chat_message
+ ADD COLUMN IF NOT EXISTS channel_outbound_installation_id UUID;
+
+ALTER TABLE chat_message
+ ADD COLUMN IF NOT EXISTS channel_outbound_chat_id TEXT;
+
+ALTER TABLE chat_message
+ ADD COLUMN IF NOT EXISTS channel_outbound_message_ids TEXT[];
+
+ALTER TABLE agent_task_queue
+ ADD COLUMN IF NOT EXISTS channel_context_revision BIGINT;
+
+CREATE TABLE IF NOT EXISTS channel_chat_context_generation (
+ chat_session_id UUID NOT NULL,
+ revision BIGINT NOT NULL,
+ history_start_message_id TEXT,
+ history_end_message_id TEXT,
+ history_boundary_pending BOOLEAN NOT NULL DEFAULT FALSE,
+ pending_fresh BOOLEAN NOT NULL DEFAULT FALSE,
+ initiator_user_id UUID,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+INSERT INTO channel_chat_context_generation (chat_session_id, revision)
+SELECT chat_session_id, context_revision
+FROM channel_chat_session_binding AS binding
+WHERE NOT EXISTS (
+ SELECT 1
+ FROM channel_chat_context_generation AS generation
+ WHERE generation.chat_session_id = binding.chat_session_id
+ AND generation.revision = binding.context_revision
+);
diff --git a/server/migrations/378_channel_chat_context_generation_key.down.sql b/server/migrations/378_channel_chat_context_generation_key.down.sql
new file mode 100644
index 0000000000..b3f9fc1d6d
--- /dev/null
+++ b/server/migrations/378_channel_chat_context_generation_key.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS channel_chat_context_generation_session_revision_idx;
diff --git a/server/migrations/378_channel_chat_context_generation_key.up.sql b/server/migrations/378_channel_chat_context_generation_key.up.sql
new file mode 100644
index 0000000000..9c594c55e3
--- /dev/null
+++ b/server/migrations/378_channel_chat_context_generation_key.up.sql
@@ -0,0 +1,2 @@
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS channel_chat_context_generation_session_revision_idx
+ ON channel_chat_context_generation (chat_session_id, revision);
diff --git a/server/migrations/379_channel_context_mixed_version_guard.down.sql b/server/migrations/379_channel_context_mixed_version_guard.down.sql
new file mode 100644
index 0000000000..b6305f05fb
--- /dev/null
+++ b/server/migrations/379_channel_context_mixed_version_guard.down.sql
@@ -0,0 +1,2 @@
+DROP TRIGGER IF EXISTS trg_enforce_channel_message_task_context_revision ON chat_message;
+DROP FUNCTION IF EXISTS enforce_channel_message_task_context_revision();
diff --git a/server/migrations/379_channel_context_mixed_version_guard.up.sql b/server/migrations/379_channel_context_mixed_version_guard.up.sql
new file mode 100644
index 0000000000..0bb449a6c7
--- /dev/null
+++ b/server/migrations/379_channel_context_mixed_version_guard.up.sql
@@ -0,0 +1,58 @@
+-- Snapshot only channel tasks that may still execute after this migration.
+-- Terminal historical rows remain NULL and use the generation-1 read fallback;
+-- rewriting them would create unnecessary table churn during deployment.
+UPDATE agent_task_queue AS task
+SET channel_context_revision = 1
+WHERE task.channel_context_revision IS NULL
+ AND task.chat_session_id IS NOT NULL
+ AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+ AND (
+ EXISTS (
+ SELECT 1
+ FROM channel_chat_session_binding AS binding
+ WHERE binding.chat_session_id = task.chat_session_id
+ )
+ OR EXISTS (
+ SELECT 1
+ FROM chat_message AS message
+ WHERE message.task_id = task.id
+ AND message.channel_ingested
+ )
+ );
+
+-- A channel message can only become input to a task from the same context
+-- generation. This is a durable data invariant, not an old-writer shim: the
+-- supported deployment strategy stops the previous server before starting the
+-- new one, while adjacent-release rollback relies on nullable columns and the
+-- generation-1 fallback.
+CREATE OR REPLACE FUNCTION enforce_channel_message_task_context_revision()
+RETURNS trigger
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ task_revision BIGINT;
+BEGIN
+ IF OLD.task_id IS NOT NULL
+ OR NEW.task_id IS NULL
+ OR NEW.role <> 'user' THEN
+ RETURN NEW;
+ END IF;
+
+ SELECT COALESCE(task.channel_context_revision, 1)
+ INTO task_revision
+ FROM agent_task_queue AS task
+ WHERE task.id = NEW.task_id;
+
+ IF task_revision IS NOT NULL
+ AND COALESCE(NEW.channel_context_revision, 1) <> task_revision THEN
+ RETURN OLD;
+ END IF;
+ RETURN NEW;
+END;
+$$;
+
+CREATE OR REPLACE TRIGGER trg_enforce_channel_message_task_context_revision
+BEFORE UPDATE OF task_id ON chat_message
+FOR EACH ROW
+WHEN (OLD.task_id IS NULL AND NEW.task_id IS NOT NULL AND NEW.role = 'user')
+EXECUTE FUNCTION enforce_channel_message_task_context_revision();
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 3904ebff27..1289a6ae63 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -32,7 +32,7 @@ WHERE acknowledged.id = (
WHERE attempt_count.trigger_evidence_kind = 'delegated_failure'
AND attempt_count.trigger_evidence_ref_id = $2
) >= $3::int
-RETURNING acknowledged.id, acknowledged.agent_id, acknowledged.issue_id, acknowledged.status, acknowledged.priority, acknowledged.dispatched_at, acknowledged.started_at, acknowledged.completed_at, acknowledged.result, acknowledged.error, acknowledged.created_at, acknowledged.context, acknowledged.runtime_id, acknowledged.session_id, acknowledged.work_dir, acknowledged.trigger_comment_id, acknowledged.chat_session_id, acknowledged.autopilot_run_id, acknowledged.attempt, acknowledged.max_attempts, acknowledged.parent_task_id, acknowledged.failure_reason, acknowledged.trigger_summary, acknowledged.force_fresh_session, acknowledged.is_leader_task, acknowledged.wait_reason, acknowledged.initiator_user_id, acknowledged.handoff_note, acknowledged.prepare_lease_expires_at, acknowledged.squad_id, acknowledged.runtime_mcp_overlay, acknowledged.escalation_for_task_id, acknowledged.fire_at, acknowledged.originator_user_id, acknowledged.runtime_connected_apps, acknowledged.coalesced_comment_ids, acknowledged.delivered_comment_ids, acknowledged.chat_input_task_id, acknowledged.chat_finalize_deferred_at, acknowledged.originator_source, acknowledged.delegated_from_task_id, acknowledged.retry_of_task_id, acknowledged.rerun_of_task_id, acknowledged.rule_version_id, acknowledged.trigger_evidence_kind, acknowledged.trigger_evidence_ref_id, acknowledged.accountable_user_id, acknowledged.session_rollout_missing, acknowledged.retired_session_id, acknowledged.quick_actions_disabled, acknowledged.regenerate_quick_actions_for, acknowledged.branch_name, acknowledged.durable_work_dir
+RETURNING acknowledged.id, acknowledged.agent_id, acknowledged.issue_id, acknowledged.status, acknowledged.priority, acknowledged.dispatched_at, acknowledged.started_at, acknowledged.completed_at, acknowledged.result, acknowledged.error, acknowledged.created_at, acknowledged.context, acknowledged.runtime_id, acknowledged.session_id, acknowledged.work_dir, acknowledged.trigger_comment_id, acknowledged.chat_session_id, acknowledged.autopilot_run_id, acknowledged.attempt, acknowledged.max_attempts, acknowledged.parent_task_id, acknowledged.failure_reason, acknowledged.trigger_summary, acknowledged.force_fresh_session, acknowledged.is_leader_task, acknowledged.wait_reason, acknowledged.initiator_user_id, acknowledged.handoff_note, acknowledged.prepare_lease_expires_at, acknowledged.squad_id, acknowledged.runtime_mcp_overlay, acknowledged.escalation_for_task_id, acknowledged.fire_at, acknowledged.originator_user_id, acknowledged.runtime_connected_apps, acknowledged.coalesced_comment_ids, acknowledged.delivered_comment_ids, acknowledged.chat_input_task_id, acknowledged.chat_finalize_deferred_at, acknowledged.originator_source, acknowledged.delegated_from_task_id, acknowledged.retry_of_task_id, acknowledged.rerun_of_task_id, acknowledged.rule_version_id, acknowledged.trigger_evidence_kind, acknowledged.trigger_evidence_ref_id, acknowledged.accountable_user_id, acknowledged.session_rollout_missing, acknowledged.retired_session_id, acknowledged.quick_actions_disabled, acknowledged.regenerate_quick_actions_for, acknowledged.branch_name, acknowledged.durable_work_dir, acknowledged.channel_context_revision
`
type AcknowledgeExhaustedDelegatedFailureRecoveryParams struct {
@@ -102,6 +102,7 @@ func (q *Queries) AcknowledgeExhaustedDelegatedFailureRecovery(ctx context.Conte
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -299,7 +300,7 @@ const cancelAgentTask = `-- name: CancelAgentTask :one
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
// Automatic cancellation without an explicit persisted failure reason. Unlike
@@ -361,6 +362,7 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -419,7 +421,7 @@ SET status = 'cancelled',
END
WHERE task.id = $1
AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision
`
// An explicit user cancellation is a terminal acknowledgement for any
@@ -483,6 +485,7 @@ func (q *Queries) CancelAgentTaskByUser(ctx context.Context, id pgtype.UUID) (Ag
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -495,7 +498,7 @@ SET status = 'cancelled',
failure_reason = $2,
prepare_lease_expires_at = NULL
WHERE id = $3 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
type CancelAgentTaskWithReasonParams struct {
@@ -568,6 +571,7 @@ func (q *Queries) CancelAgentTaskWithReason(ctx context.Context, arg CancelAgent
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -576,7 +580,7 @@ const cancelAgentTasksByAgent = `-- name: CancelAgentTasksByAgent :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
// Bulk-cancel every active (queued/dispatched/running) task for an agent.
@@ -647,6 +651,7 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -662,7 +667,7 @@ const cancelAgentTasksByChatSession = `-- name: CancelAgentTasksByChatSession :m
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
// Cancels active tasks belonging to a chat session. Called from
@@ -733,6 +738,7 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -748,7 +754,7 @@ const cancelAgentTasksByIssue = `-- name: CancelAgentTasksByIssue :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
// Cancels every active task on the issue and returns the affected rows so the
@@ -819,6 +825,7 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -835,7 +842,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE (trigger_comment_id = $1 OR $1 = ANY(coalesced_comment_ids))
AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
// Cancels active tasks whose planned batch contains the edited/deleted comment.
@@ -905,6 +912,7 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerC
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -925,9 +933,9 @@ WITH cancelled AS (
AND fallback.status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')
AND primary_task.issue_id = $1
AND primary_task.agent_id = $2
- RETURNING fallback.id, fallback.agent_id, fallback.issue_id, fallback.status, fallback.priority, fallback.dispatched_at, fallback.started_at, fallback.completed_at, fallback.result, fallback.error, fallback.created_at, fallback.context, fallback.runtime_id, fallback.session_id, fallback.work_dir, fallback.trigger_comment_id, fallback.chat_session_id, fallback.autopilot_run_id, fallback.attempt, fallback.max_attempts, fallback.parent_task_id, fallback.failure_reason, fallback.trigger_summary, fallback.force_fresh_session, fallback.is_leader_task, fallback.wait_reason, fallback.initiator_user_id, fallback.handoff_note, fallback.prepare_lease_expires_at, fallback.squad_id, fallback.runtime_mcp_overlay, fallback.escalation_for_task_id, fallback.fire_at, fallback.originator_user_id, fallback.runtime_connected_apps, fallback.coalesced_comment_ids, fallback.delivered_comment_ids, fallback.chat_input_task_id, fallback.chat_finalize_deferred_at, fallback.originator_source, fallback.delegated_from_task_id, fallback.retry_of_task_id, fallback.rerun_of_task_id, fallback.rule_version_id, fallback.trigger_evidence_kind, fallback.trigger_evidence_ref_id, fallback.accountable_user_id, fallback.session_rollout_missing, fallback.retired_session_id, fallback.quick_actions_disabled, fallback.regenerate_quick_actions_for, fallback.branch_name, fallback.durable_work_dir
+ RETURNING fallback.id, fallback.agent_id, fallback.issue_id, fallback.status, fallback.priority, fallback.dispatched_at, fallback.started_at, fallback.completed_at, fallback.result, fallback.error, fallback.created_at, fallback.context, fallback.runtime_id, fallback.session_id, fallback.work_dir, fallback.trigger_comment_id, fallback.chat_session_id, fallback.autopilot_run_id, fallback.attempt, fallback.max_attempts, fallback.parent_task_id, fallback.failure_reason, fallback.trigger_summary, fallback.force_fresh_session, fallback.is_leader_task, fallback.wait_reason, fallback.initiator_user_id, fallback.handoff_note, fallback.prepare_lease_expires_at, fallback.squad_id, fallback.runtime_mcp_overlay, fallback.escalation_for_task_id, fallback.fire_at, fallback.originator_user_id, fallback.runtime_connected_apps, fallback.coalesced_comment_ids, fallback.delivered_comment_ids, fallback.chat_input_task_id, fallback.chat_finalize_deferred_at, fallback.originator_source, fallback.delegated_from_task_id, fallback.retry_of_task_id, fallback.rerun_of_task_id, fallback.rule_version_id, fallback.trigger_evidence_kind, fallback.trigger_evidence_ref_id, fallback.accountable_user_id, fallback.session_rollout_missing, fallback.retired_session_id, fallback.quick_actions_disabled, fallback.regenerate_quick_actions_for, fallback.branch_name, fallback.durable_work_dir, fallback.channel_context_revision
)
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir FROM cancelled
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision FROM cancelled
`
type CancelDeferredEscalationsForIssueAgentParams struct {
@@ -989,6 +997,7 @@ type CancelDeferredEscalationsForIssueAgentRow struct {
RegenerateQuickActionsFor pgtype.UUID `json:"regenerate_quick_actions_for"`
BranchName pgtype.Text `json:"branch_name"`
DurableWorkDir pgtype.Text `json:"durable_work_dir"`
+ ChannelContextRevision pgtype.Int8 `json:"channel_context_revision"`
}
func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, arg CancelDeferredEscalationsForIssueAgentParams) ([]CancelDeferredEscalationsForIssueAgentRow, error) {
@@ -1054,6 +1063,7 @@ func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, ar
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -1070,7 +1080,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE escalation_for_task_id = $1
AND status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalationForTaskID pgtype.UUID) ([]AgentTaskQueue, error) {
@@ -1136,6 +1146,7 @@ func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalati
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -1152,7 +1163,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND agent_id = $2
AND status IN ('queued', 'dispatched', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
type CancelPendingTasksByIssueAndAgentParams struct {
@@ -1239,6 +1250,7 @@ func (q *Queries) CancelPendingTasksByIssueAndAgent(ctx context.Context, arg Can
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -1256,7 +1268,7 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE id = $1
AND chat_session_id = $2
AND status = 'queued'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
type CancelQueuedAgentTaskParams struct {
@@ -1323,6 +1335,7 @@ func (q *Queries) CancelQueuedAgentTask(ctx context.Context, arg CancelQueuedAge
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -1350,7 +1363,7 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE queued.chat_session_id = $1
AND queued.status = 'queued'
AND queued.id IS DISTINCT FROM (SELECT id FROM head)
-RETURNING queued.id, queued.agent_id, queued.issue_id, queued.status, queued.priority, queued.dispatched_at, queued.started_at, queued.completed_at, queued.result, queued.error, queued.created_at, queued.context, queued.runtime_id, queued.session_id, queued.work_dir, queued.trigger_comment_id, queued.chat_session_id, queued.autopilot_run_id, queued.attempt, queued.max_attempts, queued.parent_task_id, queued.failure_reason, queued.trigger_summary, queued.force_fresh_session, queued.is_leader_task, queued.wait_reason, queued.initiator_user_id, queued.handoff_note, queued.prepare_lease_expires_at, queued.squad_id, queued.runtime_mcp_overlay, queued.escalation_for_task_id, queued.fire_at, queued.originator_user_id, queued.runtime_connected_apps, queued.coalesced_comment_ids, queued.delivered_comment_ids, queued.chat_input_task_id, queued.chat_finalize_deferred_at, queued.originator_source, queued.delegated_from_task_id, queued.retry_of_task_id, queued.rerun_of_task_id, queued.rule_version_id, queued.trigger_evidence_kind, queued.trigger_evidence_ref_id, queued.accountable_user_id, queued.session_rollout_missing, queued.retired_session_id, queued.quick_actions_disabled, queued.regenerate_quick_actions_for, queued.branch_name, queued.durable_work_dir
+RETURNING queued.id, queued.agent_id, queued.issue_id, queued.status, queued.priority, queued.dispatched_at, queued.started_at, queued.completed_at, queued.result, queued.error, queued.created_at, queued.context, queued.runtime_id, queued.session_id, queued.work_dir, queued.trigger_comment_id, queued.chat_session_id, queued.autopilot_run_id, queued.attempt, queued.max_attempts, queued.parent_task_id, queued.failure_reason, queued.trigger_summary, queued.force_fresh_session, queued.is_leader_task, queued.wait_reason, queued.initiator_user_id, queued.handoff_note, queued.prepare_lease_expires_at, queued.squad_id, queued.runtime_mcp_overlay, queued.escalation_for_task_id, queued.fire_at, queued.originator_user_id, queued.runtime_connected_apps, queued.coalesced_comment_ids, queued.delivered_comment_ids, queued.chat_input_task_id, queued.chat_finalize_deferred_at, queued.originator_source, queued.delegated_from_task_id, queued.retry_of_task_id, queued.rerun_of_task_id, queued.rule_version_id, queued.trigger_evidence_kind, queued.trigger_evidence_ref_id, queued.accountable_user_id, queued.session_rollout_missing, queued.retired_session_id, queued.quick_actions_disabled, queued.regenerate_quick_actions_for, queued.branch_name, queued.durable_work_dir, queued.channel_context_revision
`
// Clear only positional follow-ups. The first visible task is current even
@@ -1420,6 +1433,7 @@ func (q *Queries) CancelQueuedAgentTasksForSession(ctx context.Context, chatSess
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -1447,7 +1461,7 @@ WHERE r.runtime_id = ANY($1::uuid[])
AND successor.id <> r.id
AND successor.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
// Cancels deferred auto-retry rows that a newer active task has already
@@ -1537,6 +1551,7 @@ func (q *Queries) CancelSupersededDeferredRetriesForRuntimes(ctx context.Context
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -1586,7 +1601,7 @@ WHERE id = (
LIMIT 1
FOR UPDATE SKIP LOCKED
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
type ClaimAgentTaskParams struct {
@@ -1668,6 +1683,7 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, arg ClaimAgentTaskParams)
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -1676,7 +1692,7 @@ const claimChatFinalizeDeferred = `-- name: ClaimChatFinalizeDeferred :one
UPDATE agent_task_queue
SET chat_finalize_deferred_at = NULL
WHERE id = $1 AND chat_finalize_deferred_at IS NOT NULL
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
// Atomically claims the deferred marker so the daemon ack and the sweeper
@@ -1738,6 +1754,7 @@ func (q *Queries) ClaimChatFinalizeDeferred(ctx context.Context, id pgtype.UUID)
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -1932,7 +1949,7 @@ SET status = 'completed', completed_at = now(), result = $2,
retired_session_id = COALESCE($8, retired_session_id),
prepare_lease_expires_at = NULL
WHERE id = $1 AND status = 'running'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
type CompleteAgentTaskParams struct {
@@ -2023,6 +2040,7 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -2262,7 +2280,7 @@ SELECT
$22,
COALESCE($23::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, $3, $2)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
type CreateAgentTaskParams struct {
@@ -2390,6 +2408,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -2418,7 +2437,7 @@ SELECT
$19,
COALESCE($20::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, $3, $2)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
type CreateDeferredAgentTaskParams struct {
@@ -2533,6 +2552,7 @@ func (q *Queries) CreateDeferredAgentTask(ctx context.Context, arg CreateDeferre
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -2571,7 +2591,7 @@ SELECT
$23,
COALESCE($24::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, $3, $2)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
type CreateDeferredChannelIssueTaskParams struct {
@@ -2690,6 +2710,7 @@ func (q *Queries) CreateDeferredChannelIssueTask(ctx context.Context, arg Create
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -2712,7 +2733,7 @@ SELECT
$11,
COALESCE($12::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, NULL, $2)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
type CreateQuickCreateTaskParams struct {
@@ -2810,6 +2831,7 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -2824,7 +2846,7 @@ INSERT INTO agent_task_queue (
originator_source, delegated_from_task_id, rule_version_id,
trigger_evidence_kind, trigger_evidence_ref_id, retry_of_task_id,
chat_input_task_id, fire_at,
- id
+ channel_context_revision, id
)
SELECT
p.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,
@@ -2844,6 +2866,7 @@ SELECT
p.originator_source, p.delegated_from_task_id, p.rule_version_id,
p.trigger_evidence_kind, p.trigger_evidence_ref_id, p.id,
p.chat_input_task_id, $2,
+ p.channel_context_revision,
-- Named new_task_id, not id: $1 above is the PARENT task's id.
COALESCE($6::uuid, gen_random_uuid())
FROM agent_task_queue p
@@ -2852,7 +2875,7 @@ WHERE p.id = $1
ON CONFLICT (issue_id, agent_id) WHERE status IN ('queued', 'dispatched')
OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')
DO NOTHING
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
type CreateRetryTaskParams struct {
@@ -3001,6 +3024,7 @@ func (q *Queries) CreateRetryTask(ctx context.Context, arg CreateRetryTaskParams
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -3136,7 +3160,7 @@ WHERE t.id = v.id
WHERE retry_parent.id = t.parent_task_id
AND retry_parent.failure_reason = 'runtime_offline'
)
-RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.branch_name, t.durable_work_dir
+RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.branch_name, t.durable_work_dir, t.channel_context_revision
`
type ExpireStaleQueuedTasksParams struct {
@@ -3232,6 +3256,7 @@ func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQue
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -3250,7 +3275,7 @@ WHERE id = $1
AND runtime_id = $2
AND status IN ('dispatched', 'waiting_local_directory')
AND started_at IS NULL
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
type ExtendAgentTaskPrepareLeaseParams struct {
@@ -3320,6 +3345,7 @@ func (q *Queries) ExtendAgentTaskPrepareLease(ctx context.Context, arg ExtendAge
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -3338,7 +3364,7 @@ SET status = 'failed',
retired_session_id = COALESCE($9, retired_session_id),
prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
type FailAgentTaskParams struct {
@@ -3435,6 +3461,7 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -3481,7 +3508,7 @@ WHERE retry.id = victims.id
AND COALESCE(runtime.last_seen_at, runtime.updated_at) >=
now() - make_interval(secs => $2::double precision)
)
-RETURNING retry.id, retry.agent_id, retry.issue_id, retry.status, retry.priority, retry.dispatched_at, retry.started_at, retry.completed_at, retry.result, retry.error, retry.created_at, retry.context, retry.runtime_id, retry.session_id, retry.work_dir, retry.trigger_comment_id, retry.chat_session_id, retry.autopilot_run_id, retry.attempt, retry.max_attempts, retry.parent_task_id, retry.failure_reason, retry.trigger_summary, retry.force_fresh_session, retry.is_leader_task, retry.wait_reason, retry.initiator_user_id, retry.handoff_note, retry.prepare_lease_expires_at, retry.squad_id, retry.runtime_mcp_overlay, retry.escalation_for_task_id, retry.fire_at, retry.originator_user_id, retry.runtime_connected_apps, retry.coalesced_comment_ids, retry.delivered_comment_ids, retry.chat_input_task_id, retry.chat_finalize_deferred_at, retry.originator_source, retry.delegated_from_task_id, retry.retry_of_task_id, retry.rerun_of_task_id, retry.rule_version_id, retry.trigger_evidence_kind, retry.trigger_evidence_ref_id, retry.accountable_user_id, retry.session_rollout_missing, retry.retired_session_id, retry.quick_actions_disabled, retry.regenerate_quick_actions_for, retry.branch_name, retry.durable_work_dir
+RETURNING retry.id, retry.agent_id, retry.issue_id, retry.status, retry.priority, retry.dispatched_at, retry.started_at, retry.completed_at, retry.result, retry.error, retry.created_at, retry.context, retry.runtime_id, retry.session_id, retry.work_dir, retry.trigger_comment_id, retry.chat_session_id, retry.autopilot_run_id, retry.attempt, retry.max_attempts, retry.parent_task_id, retry.failure_reason, retry.trigger_summary, retry.force_fresh_session, retry.is_leader_task, retry.wait_reason, retry.initiator_user_id, retry.handoff_note, retry.prepare_lease_expires_at, retry.squad_id, retry.runtime_mcp_overlay, retry.escalation_for_task_id, retry.fire_at, retry.originator_user_id, retry.runtime_connected_apps, retry.coalesced_comment_ids, retry.delivered_comment_ids, retry.chat_input_task_id, retry.chat_finalize_deferred_at, retry.originator_source, retry.delegated_from_task_id, retry.retry_of_task_id, retry.rerun_of_task_id, retry.rule_version_id, retry.trigger_evidence_kind, retry.trigger_evidence_ref_id, retry.accountable_user_id, retry.session_rollout_missing, retry.retired_session_id, retry.quick_actions_disabled, retry.regenerate_quick_actions_for, retry.branch_name, retry.durable_work_dir, retry.channel_context_revision
`
type FailExpiredRuntimeReconnectRetriesParams struct {
@@ -3560,6 +3587,7 @@ func (q *Queries) FailExpiredRuntimeReconnectRetries(ctx context.Context, arg Fa
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -3614,7 +3642,7 @@ WHERE (
)
)
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
type FailStaleTasksParams struct {
@@ -3724,6 +3752,7 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -3960,7 +3989,7 @@ func (q *Queries) GetAgentInWorkspace(ctx context.Context, arg GetAgentInWorkspa
}
const getAgentTask = `-- name: GetAgentTask :one
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision FROM agent_task_queue
WHERE id = $1
`
@@ -4021,12 +4050,13 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
const getAgentTaskForDelegatedFailureUpdate = `-- name: GetAgentTaskForDelegatedFailureUpdate :one
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision FROM agent_task_queue
WHERE id = $1
FOR UPDATE
`
@@ -4091,12 +4121,13 @@ func (q *Queries) GetAgentTaskForDelegatedFailureUpdate(ctx context.Context, id
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
const getAgentTaskInWorkspace = `-- name: GetAgentTaskInWorkspace :one
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE atq.id = $1 AND a.workspace_id = $2
`
@@ -4170,6 +4201,7 @@ func (q *Queries) GetAgentTaskInWorkspace(ctx context.Context, arg GetAgentTaskI
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -4386,18 +4418,27 @@ func (q *Queries) GetLastTaskStartedAtForIssueAndAgent(ctx context.Context, arg
const getLatestChatTaskRolloutMissing = `-- name: GetLatestChatTaskRolloutMissing :one
SELECT COALESCE(session_rollout_missing, FALSE) FROM agent_task_queue
WHERE chat_session_id = $1
+ AND (
+ $2::bigint IS NULL
+ OR COALESCE(channel_context_revision, 1) = $2::bigint
+ )
AND status IN ('completed', 'failed')
AND started_at IS NOT NULL
ORDER BY COALESCE(completed_at, started_at, dispatched_at, created_at) DESC
LIMIT 1
`
+type GetLatestChatTaskRolloutMissingParams struct {
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ ChannelContextRevision pgtype.Int8 `json:"channel_context_revision"`
+}
+
// Chat-session counterpart of GetLatestTaskRolloutMissing (MUL-5305): reports
// whether the most recent terminal task on this chat session withheld its Codex
// session because the rollout was missing. When true the next chat claim resumed
// an older session (or none), so it must disclose the continuity gap.
-func (q *Queries) GetLatestChatTaskRolloutMissing(ctx context.Context, chatSessionID pgtype.UUID) (bool, error) {
- row := q.db.QueryRow(ctx, getLatestChatTaskRolloutMissing, chatSessionID)
+func (q *Queries) GetLatestChatTaskRolloutMissing(ctx context.Context, arg GetLatestChatTaskRolloutMissingParams) (bool, error) {
+ row := q.db.QueryRow(ctx, getLatestChatTaskRolloutMissing, arg.ChatSessionID, arg.ChannelContextRevision)
var session_rollout_missing bool
err := row.Scan(&session_rollout_missing)
return session_rollout_missing, err
@@ -4983,7 +5024,7 @@ func (q *Queries) ListActiveSiblingIssueTasks(ctx context.Context, arg ListActiv
}
const listActiveTasksByIssue = `-- name: ListActiveTasksByIssue :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision FROM agent_task_queue
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
ORDER BY created_at DESC
`
@@ -5056,6 +5097,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -5068,7 +5110,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
}
const listAgentTasks = `-- name: ListAgentTasks :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision FROM agent_task_queue
WHERE agent_id = $1
ORDER BY created_at DESC
`
@@ -5136,6 +5178,7 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -5323,7 +5366,7 @@ func (q *Queries) ListAllAgentsAnyKind(ctx context.Context, workspaceID pgtype.U
}
const listChatFinalizeDeferredExpired = `-- name: ListChatFinalizeDeferredExpired :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision FROM agent_task_queue
WHERE chat_finalize_deferred_at IS NOT NULL
AND chat_finalize_deferred_at < now() - make_interval(secs => $1::double precision)
ORDER BY chat_finalize_deferred_at
@@ -5401,6 +5444,7 @@ func (q *Queries) ListChatFinalizeDeferredExpired(ctx context.Context, arg ListC
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -5511,7 +5555,7 @@ func (q *Queries) ListPendingDelegatedFailureRecoveries(ctx context.Context, max
}
const listPendingTasksByRuntime = `-- name: ListPendingTasksByRuntime :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision FROM agent_task_queue
WHERE runtime_id = $1 AND status IN ('queued', 'dispatched')
ORDER BY priority DESC, created_at ASC
`
@@ -5579,6 +5623,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -5591,7 +5636,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
}
const listQueuedClaimCandidatesByRuntime = `-- name: ListQueuedClaimCandidatesByRuntime :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision FROM agent_task_queue
WHERE runtime_id = $1 AND status = 'queued'
ORDER BY priority DESC, created_at ASC
`
@@ -5667,6 +5712,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -5679,7 +5725,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
}
const listQueuedClaimCandidatesByRuntimes = `-- name: ListQueuedClaimCandidatesByRuntimes :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision FROM agent_task_queue
WHERE runtime_id = ANY($1::uuid[]) AND status = 'queued'
ORDER BY priority DESC, created_at ASC
`
@@ -5757,6 +5803,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntimes(ctx context.Context, runti
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -5769,7 +5816,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntimes(ctx context.Context, runti
}
const listTasksByIssue = `-- name: ListTasksByIssue :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision FROM agent_task_queue
WHERE issue_id = $1
ORDER BY created_at DESC
`
@@ -5837,6 +5884,7 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -5910,16 +5958,16 @@ func (q *Queries) ListUserAgentsByRuntimeForUpdate(ctx context.Context, runtimeI
}
const listWorkspaceAgentTaskSnapshot = `-- name: ListWorkspaceAgentTaskSnapshot :many
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE a.workspace_id = $1
AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
UNION ALL
-SELECT latest.id, latest.agent_id, latest.issue_id, latest.status, latest.priority, latest.dispatched_at, latest.started_at, latest.completed_at, latest.result, latest.error, latest.created_at, latest.context, latest.runtime_id, latest.session_id, latest.work_dir, latest.trigger_comment_id, latest.chat_session_id, latest.autopilot_run_id, latest.attempt, latest.max_attempts, latest.parent_task_id, latest.failure_reason, latest.trigger_summary, latest.force_fresh_session, latest.is_leader_task, latest.wait_reason, latest.initiator_user_id, latest.handoff_note, latest.prepare_lease_expires_at, latest.squad_id, latest.runtime_mcp_overlay, latest.escalation_for_task_id, latest.fire_at, latest.originator_user_id, latest.runtime_connected_apps, latest.coalesced_comment_ids, latest.delivered_comment_ids, latest.chat_input_task_id, latest.chat_finalize_deferred_at, latest.originator_source, latest.delegated_from_task_id, latest.retry_of_task_id, latest.rerun_of_task_id, latest.rule_version_id, latest.trigger_evidence_kind, latest.trigger_evidence_ref_id, latest.accountable_user_id, latest.session_rollout_missing, latest.retired_session_id, latest.quick_actions_disabled, latest.regenerate_quick_actions_for, latest.branch_name, latest.durable_work_dir FROM agent a
+SELECT latest.id, latest.agent_id, latest.issue_id, latest.status, latest.priority, latest.dispatched_at, latest.started_at, latest.completed_at, latest.result, latest.error, latest.created_at, latest.context, latest.runtime_id, latest.session_id, latest.work_dir, latest.trigger_comment_id, latest.chat_session_id, latest.autopilot_run_id, latest.attempt, latest.max_attempts, latest.parent_task_id, latest.failure_reason, latest.trigger_summary, latest.force_fresh_session, latest.is_leader_task, latest.wait_reason, latest.initiator_user_id, latest.handoff_note, latest.prepare_lease_expires_at, latest.squad_id, latest.runtime_mcp_overlay, latest.escalation_for_task_id, latest.fire_at, latest.originator_user_id, latest.runtime_connected_apps, latest.coalesced_comment_ids, latest.delivered_comment_ids, latest.chat_input_task_id, latest.chat_finalize_deferred_at, latest.originator_source, latest.delegated_from_task_id, latest.retry_of_task_id, latest.rerun_of_task_id, latest.rule_version_id, latest.trigger_evidence_kind, latest.trigger_evidence_ref_id, latest.accountable_user_id, latest.session_rollout_missing, latest.retired_session_id, latest.quick_actions_disabled, latest.regenerate_quick_actions_for, latest.branch_name, latest.durable_work_dir, latest.channel_context_revision FROM agent a
JOIN LATERAL (
- SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir
+ SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.branch_name, atq.durable_work_dir, atq.channel_context_revision
FROM agent_task_queue atq
WHERE atq.agent_id = a.id
AND atq.status IN ('completed', 'failed')
@@ -6017,6 +6065,7 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceI
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -6266,7 +6315,7 @@ SET status = 'waiting_local_directory',
wait_reason = $2,
prepare_lease_expires_at = now() + make_interval(secs => $3::double precision)
WHERE id = $1 AND status = 'dispatched'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
type MarkAgentTaskWaitingLocalDirectoryParams struct {
@@ -6341,6 +6390,7 @@ func (q *Queries) MarkAgentTaskWaitingLocalDirectory(ctx context.Context, arg Ma
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -6349,7 +6399,7 @@ const markChatFinalizeDeferred = `-- name: MarkChatFinalizeDeferred :one
UPDATE agent_task_queue
SET chat_finalize_deferred_at = now()
WHERE id = $1
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
// Arms the deferred chat-finalize marker for a cancelled chat task whose
@@ -6411,6 +6461,7 @@ func (q *Queries) MarkChatFinalizeDeferred(ctx context.Context, id pgtype.UUID)
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -6571,7 +6622,7 @@ WHERE id = (
ORDER BY t.created_at DESC
LIMIT 1
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
type MergeDelegatedFailureCommentIntoPendingTaskParams struct {
@@ -6649,6 +6700,7 @@ func (q *Queries) MergeDelegatedFailureCommentIntoPendingTask(ctx context.Contex
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -6657,7 +6709,7 @@ const promoteDeferredChannelIssueTask = `-- name: PromoteDeferredChannelIssueTas
UPDATE agent_task_queue
SET status = 'queued', fire_at = NULL
WHERE id = $1 AND issue_id IS NOT NULL AND status = 'deferred'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
// Early promotion is idempotent at the service layer: a task already promoted
@@ -6719,6 +6771,7 @@ func (q *Queries) PromoteDeferredChannelIssueTask(ctx context.Context, id pgtype
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -6756,7 +6809,7 @@ WITH due AS (
UPDATE agent_task_queue
SET status = 'queued'
WHERE id IN (SELECT id FROM due WHERE issue_id IS NULL OR rn = 1)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
type PromoteDueDeferredTasksForRuntimeParams struct {
@@ -6842,6 +6895,7 @@ func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, arg Pro
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -6886,7 +6940,7 @@ WITH due AS (
UPDATE agent_task_queue
SET status = 'queued'
WHERE id IN (SELECT id FROM due WHERE issue_id IS NULL OR rn = 1)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
type PromoteDueDeferredTasksForRuntimesParams struct {
@@ -6960,6 +7014,7 @@ func (q *Queries) PromoteDueDeferredTasksForRuntimes(ctx context.Context, arg Pr
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -7067,7 +7122,7 @@ WHERE id = (
LIMIT 1
FOR UPDATE SKIP LOCKED
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
type ReclaimStaleDispatchedTaskForRuntimeParams struct {
@@ -7144,6 +7199,7 @@ func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, arg
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -7170,7 +7226,7 @@ WHERE id IN (
LIMIT $5::int
FOR UPDATE SKIP LOCKED
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
type ReclaimStaleDispatchedTasksForRuntimesParams struct {
@@ -7257,6 +7313,7 @@ func (q *Queries) ReclaimStaleDispatchedTasksForRuntimes(ctx context.Context, ar
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -7277,7 +7334,7 @@ SET status = 'failed',
wait_reason = NULL,
prepare_lease_expires_at = NULL
WHERE runtime_id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
// Called by the daemon at startup. Atomically fails any dispatched/running/
@@ -7349,6 +7406,7 @@ func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -7496,7 +7554,7 @@ WHERE id = $1
AND status = 'dispatched'
AND started_at IS NULL
AND dispatched_at = $3
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
type RequeueAgentTaskAfterClaimFailureParams struct {
@@ -7567,6 +7625,7 @@ func (q *Queries) RequeueAgentTaskAfterClaimFailure(ctx context.Context, arg Req
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -7775,7 +7834,7 @@ SET status = 'running',
wait_reason = NULL,
prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('dispatched', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
// Transitions a task to running. Accepts either 'dispatched' (the normal
@@ -7841,6 +7900,7 @@ func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTask
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index aae27ba5ac..e176917103 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -300,7 +300,7 @@ SELECT
$11,
COALESCE($12::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, NULL, $2)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
type CreateAutopilotTaskParams struct {
@@ -407,6 +407,7 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -902,7 +903,7 @@ func (q *Queries) GetAutopilotRunByWebhookDelivery(ctx context.Context, webhookD
}
const getAutopilotTaskByRun = `-- name: GetAutopilotTaskByRun :one
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision FROM agent_task_queue
WHERE autopilot_run_id = $1
ORDER BY created_at
LIMIT 1
@@ -967,6 +968,7 @@ func (q *Queries) GetAutopilotTaskByRun(ctx context.Context, autopilotRunID pgty
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
diff --git a/server/pkg/db/generated/channel.sql.go b/server/pkg/db/generated/channel.sql.go
index f142116188..029bc134dc 100644
--- a/server/pkg/db/generated/channel.sql.go
+++ b/server/pkg/db/generated/channel.sql.go
@@ -54,6 +54,76 @@ func (q *Queries) AcquireChannelWSLease(ctx context.Context, arg AcquireChannelW
return i, err
}
+const advanceChannelChatContextGeneration = `-- name: AdvanceChannelChatContextGeneration :one
+WITH closed AS (
+ UPDATE channel_chat_context_generation AS generation
+ SET history_end_message_id = $1
+ WHERE generation.chat_session_id = $2
+ AND generation.revision = $3
+), advanced AS (
+ UPDATE channel_chat_session_binding AS binding
+ SET context_revision = binding.context_revision + 1,
+ pending_fresh = TRUE
+ WHERE binding.chat_session_id = $2
+ AND binding.context_revision = $3
+ RETURNING binding.id, binding.chat_session_id, binding.installation_id, binding.channel_type, binding.channel_chat_id, binding.chat_type, binding.last_message_id, binding.last_thread_id, binding.config, binding.created_at, binding.pending_fresh, binding.context_revision
+), opened AS (
+ INSERT INTO channel_chat_context_generation (
+ chat_session_id, revision, history_start_message_id,
+ history_boundary_pending, pending_fresh
+ )
+ SELECT chat_session_id, context_revision,
+ CASE WHEN $4::boolean THEN $1 END,
+ NOT $4::boolean,
+ TRUE
+ FROM advanced
+ RETURNING chat_session_id, revision, history_start_message_id, history_end_message_id, history_boundary_pending, pending_fresh, initiator_user_id, created_at
+)
+SELECT chat_session_id, revision, history_start_message_id, history_end_message_id, history_boundary_pending, pending_fresh, initiator_user_id, created_at FROM opened
+`
+
+type AdvanceChannelChatContextGenerationParams struct {
+ HistoryBoundaryMessageID pgtype.Text `json:"history_boundary_message_id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ CurrentRevision int64 `json:"current_revision"`
+ HasMessageBody bool `json:"has_message_body"`
+}
+
+type AdvanceChannelChatContextGenerationRow struct {
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ Revision int64 `json:"revision"`
+ HistoryStartMessageID pgtype.Text `json:"history_start_message_id"`
+ HistoryEndMessageID pgtype.Text `json:"history_end_message_id"`
+ HistoryBoundaryPending bool `json:"history_boundary_pending"`
+ PendingFresh bool `json:"pending_fresh"`
+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
+// Opens a new agent-visible context while retaining the same Multica Chat.
+// The triggering platform message is the exclusive end of the old generation
+// and, when it has a body, the inclusive start of the new one.
+func (q *Queries) AdvanceChannelChatContextGeneration(ctx context.Context, arg AdvanceChannelChatContextGenerationParams) (AdvanceChannelChatContextGenerationRow, error) {
+ row := q.db.QueryRow(ctx, advanceChannelChatContextGeneration,
+ arg.HistoryBoundaryMessageID,
+ arg.ChatSessionID,
+ arg.CurrentRevision,
+ arg.HasMessageBody,
+ )
+ var i AdvanceChannelChatContextGenerationRow
+ err := row.Scan(
+ &i.ChatSessionID,
+ &i.Revision,
+ &i.HistoryStartMessageID,
+ &i.HistoryEndMessageID,
+ &i.HistoryBoundaryPending,
+ &i.PendingFresh,
+ &i.InitiatorUserID,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
const backfillChannelInstallationRegionToFeishuLark = `-- name: BackfillChannelInstallationRegionToFeishuLark :execrows
UPDATE channel_installation
SET config = jsonb_set(config, '{region}', '"lark"'),
@@ -243,6 +313,23 @@ func (q *Queries) ClaimNextChannelMediaPendingObjectForReconcile(ctx context.Con
return i, err
}
+const clearChannelChatContextPendingFresh = `-- name: ClearChannelChatContextPendingFresh :exec
+UPDATE channel_chat_context_generation
+SET pending_fresh = FALSE
+WHERE chat_session_id = $1
+ AND revision = $2
+`
+
+type ClearChannelChatContextPendingFreshParams struct {
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ Revision int64 `json:"revision"`
+}
+
+func (q *Queries) ClearChannelChatContextPendingFresh(ctx context.Context, arg ClearChannelChatContextPendingFreshParams) error {
+ _, err := q.db.Exec(ctx, clearChannelChatContextPendingFresh, arg.ChatSessionID, arg.Revision)
+ return err
+}
+
const clearChannelChatSessionPendingFresh = `-- name: ClearChannelChatSessionPendingFresh :exec
UPDATE channel_chat_session_binding
SET pending_fresh = FALSE
@@ -254,6 +341,23 @@ func (q *Queries) ClearChannelChatSessionPendingFresh(ctx context.Context, chatS
return err
}
+const clearChannelChatSessionPendingFreshForRevision = `-- name: ClearChannelChatSessionPendingFreshForRevision :exec
+UPDATE channel_chat_session_binding
+SET pending_fresh = FALSE
+WHERE chat_session_id = $1
+ AND context_revision = $2
+`
+
+type ClearChannelChatSessionPendingFreshForRevisionParams struct {
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ Revision int64 `json:"revision"`
+}
+
+func (q *Queries) ClearChannelChatSessionPendingFreshForRevision(ctx context.Context, arg ClearChannelChatSessionPendingFreshForRevisionParams) error {
+ _, err := q.db.Exec(ctx, clearChannelChatSessionPendingFreshForRevision, arg.ChatSessionID, arg.Revision)
+ return err
+}
+
const consumeChannelBindingToken = `-- name: ConsumeChannelBindingToken :one
UPDATE channel_binding_token
SET consumed_at = now()
@@ -357,12 +461,18 @@ func (q *Queries) CreateChannelBindingToken(ctx context.Context, arg CreateChann
const createChannelChatSessionBinding = `-- name: CreateChannelChatSessionBinding :one
+WITH binding AS (
INSERT INTO channel_chat_session_binding (
chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, config
) VALUES (
$1, $2, $3, $4, $5, $6
)
-RETURNING id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh
+RETURNING id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision
+), generation AS (
+ INSERT INTO channel_chat_context_generation (chat_session_id, revision)
+ SELECT chat_session_id, context_revision FROM binding
+)
+SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision FROM binding
`
type CreateChannelChatSessionBindingParams struct {
@@ -374,6 +484,21 @@ type CreateChannelChatSessionBindingParams struct {
Config []byte `json:"config"`
}
+type CreateChannelChatSessionBindingRow struct {
+ ID pgtype.UUID `json:"id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ChannelType string `json:"channel_type"`
+ ChannelChatID string `json:"channel_chat_id"`
+ ChatType string `json:"chat_type"`
+ LastMessageID pgtype.Text `json:"last_message_id"`
+ LastThreadID pgtype.Text `json:"last_thread_id"`
+ Config []byte `json:"config"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ PendingFresh bool `json:"pending_fresh"`
+ ContextRevision int64 `json:"context_revision"`
+}
+
// =====================
// channel_chat_session_binding
// =====================
@@ -383,7 +508,7 @@ type CreateChannelChatSessionBindingParams struct {
// is its own session. config carries any platform-specific outbound routing the
// key alone does not (e.g. Slack's real channel_id when the key is composite);
// it is opaque to the shared session service.
-func (q *Queries) CreateChannelChatSessionBinding(ctx context.Context, arg CreateChannelChatSessionBindingParams) (ChannelChatSessionBinding, error) {
+func (q *Queries) CreateChannelChatSessionBinding(ctx context.Context, arg CreateChannelChatSessionBindingParams) (CreateChannelChatSessionBindingRow, error) {
row := q.db.QueryRow(ctx, createChannelChatSessionBinding,
arg.ChatSessionID,
arg.InstallationID,
@@ -392,7 +517,7 @@ func (q *Queries) CreateChannelChatSessionBinding(ctx context.Context, arg Creat
arg.ChatType,
arg.Config,
)
- var i ChannelChatSessionBinding
+ var i CreateChannelChatSessionBindingRow
err := row.Scan(
&i.ID,
&i.ChatSessionID,
@@ -405,6 +530,7 @@ func (q *Queries) CreateChannelChatSessionBinding(ctx context.Context, arg Creat
&i.Config,
&i.CreatedAt,
&i.PendingFresh,
+ &i.ContextRevision,
)
return i, err
}
@@ -535,8 +661,12 @@ func (q *Queries) DeleteChannelBindingTokensByInstallation(ctx context.Context,
}
const deleteChannelChatSessionBindingBySession = `-- name: DeleteChannelChatSessionBindingBySession :exec
-DELETE FROM channel_chat_session_binding
-WHERE chat_session_id = $1
+WITH deleted_binding AS (
+ DELETE FROM channel_chat_session_binding AS binding
+ WHERE binding.chat_session_id = $1
+)
+DELETE FROM channel_chat_context_generation AS generation
+WHERE generation.chat_session_id = $1
`
// Application-layer integrity (replaces the old chat_session-FK ON DELETE
@@ -547,8 +677,9 @@ func (q *Queries) DeleteChannelChatSessionBindingBySession(ctx context.Context,
}
const deleteChannelChatSessionBindingsByInstallation = `-- name: DeleteChannelChatSessionBindingsByInstallation :exec
-DELETE FROM channel_chat_session_binding
-WHERE installation_id = $1 AND channel_type = $2
+DELETE FROM channel_chat_session_binding AS binding
+WHERE binding.installation_id = $1
+ AND binding.channel_type = $2
`
type DeleteChannelChatSessionBindingsByInstallationParams struct {
@@ -562,18 +693,26 @@ type DeleteChannelChatSessionBindingsByInstallationParams struct {
// so reusing it would keep routing the conversation to the OLD agent. Dropping
// the bindings forces the next inbound message to create a fresh session under
// the new agent. The chat_session rows are preserved for history; only the
-// channel binding is removed.
+// channel binding is removed. Context generations belong to the preserved Chat,
+// not to the retired binding: in-flight task history snapshots may still read
+// them after this statement commits.
func (q *Queries) DeleteChannelChatSessionBindingsByInstallation(ctx context.Context, arg DeleteChannelChatSessionBindingsByInstallationParams) error {
_, err := q.db.Exec(ctx, deleteChannelChatSessionBindingsByInstallation, arg.InstallationID, arg.ChannelType)
return err
}
const deleteChannelInstallationsBySystemRuntimeAgents = `-- name: DeleteChannelInstallationsBySystemRuntimeAgents :exec
-WITH doomed AS (
+WITH system_agents AS (
+ SELECT system_agent.id FROM agent AS system_agent
+ WHERE system_agent.runtime_id = $1 AND system_agent.kind = 'system'
+),
+doomed_sessions AS (
+ SELECT id FROM chat_session
+ WHERE agent_id IN (SELECT id FROM system_agents)
+),
+doomed AS (
SELECT id FROM channel_installation
- WHERE agent_id IN (
- SELECT id FROM agent WHERE runtime_id = $1 AND kind = 'system'
- )
+ WHERE agent_id IN (SELECT id FROM system_agents)
),
cleared_dingtalk_group_presence AS (
DELETE FROM dingtalk_group_presence WHERE installation_id IN (SELECT id FROM doomed)
@@ -588,6 +727,11 @@ cleared_chat_sessions AS (
DELETE FROM channel_chat_session_binding WHERE installation_id IN (SELECT id FROM doomed)
RETURNING chat_session_id
),
+cleared_chat_contexts AS (
+ DELETE FROM channel_chat_context_generation
+ WHERE chat_session_id IN (SELECT chat_session_id FROM cleared_chat_sessions)
+ OR chat_session_id IN (SELECT id FROM doomed_sessions)
+),
cleared_outbound_cards AS (
-- Reach channel_outbound_card_message (keyed by chat_session_id, no FK)
-- through the just-removed chat-session bindings, same as the reclaim path.
@@ -705,6 +849,24 @@ func (q *Queries) DeleteChannelUserBindingsByWorkspaceMember(ctx context.Context
return err
}
+const ensureChannelChatContextGeneration = `-- name: EnsureChannelChatContextGeneration :exec
+INSERT INTO channel_chat_context_generation (
+ chat_session_id, revision
+)
+SELECT binding.chat_session_id, binding.context_revision
+FROM channel_chat_session_binding AS binding
+WHERE binding.chat_session_id = $1
+ON CONFLICT (chat_session_id, revision) DO NOTHING
+`
+
+// Rolling-deploy repair: an older server can create a binding after the schema
+// migration but before every process is upgraded. Materialize its generation
+// lazily before a new server attempts to lock it.
+func (q *Queries) EnsureChannelChatContextGeneration(ctx context.Context, chatSessionID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, ensureChannelChatContextGeneration, chatSessionID)
+ return err
+}
+
const findChannelBindingForMember = `-- name: FindChannelBindingForMember :one
SELECT b.id, b.workspace_id, b.multica_user_id, b.installation_id, b.channel_type, b.channel_user_id, b.config, b.bound_at FROM channel_user_binding b
JOIN channel_installation ci ON ci.id = b.installation_id
@@ -860,8 +1022,35 @@ func (q *Queries) FindReusableChannelUserBinding(ctx context.Context, arg FindRe
return i, err
}
+const getChannelChatContextGeneration = `-- name: GetChannelChatContextGeneration :one
+SELECT chat_session_id, revision, history_start_message_id, history_end_message_id, history_boundary_pending, pending_fresh, initiator_user_id, created_at FROM channel_chat_context_generation
+WHERE chat_session_id = $1
+ AND revision = $2
+`
+
+type GetChannelChatContextGenerationParams struct {
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ Revision int64 `json:"revision"`
+}
+
+func (q *Queries) GetChannelChatContextGeneration(ctx context.Context, arg GetChannelChatContextGenerationParams) (ChannelChatContextGeneration, error) {
+ row := q.db.QueryRow(ctx, getChannelChatContextGeneration, arg.ChatSessionID, arg.Revision)
+ var i ChannelChatContextGeneration
+ err := row.Scan(
+ &i.ChatSessionID,
+ &i.Revision,
+ &i.HistoryStartMessageID,
+ &i.HistoryEndMessageID,
+ &i.HistoryBoundaryPending,
+ &i.PendingFresh,
+ &i.InitiatorUserID,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
const getChannelChatSessionBinding = `-- name: GetChannelChatSessionBinding :one
-SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh FROM channel_chat_session_binding
+SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision FROM channel_chat_session_binding
WHERE installation_id = $1 AND channel_chat_id = $2
`
@@ -887,12 +1076,13 @@ func (q *Queries) GetChannelChatSessionBinding(ctx context.Context, arg GetChann
&i.Config,
&i.CreatedAt,
&i.PendingFresh,
+ &i.ContextRevision,
)
return i, err
}
const getChannelChatSessionBindingBySession = `-- name: GetChannelChatSessionBindingBySession :one
-SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh FROM channel_chat_session_binding
+SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision FROM channel_chat_session_binding
WHERE chat_session_id = $1
AND channel_type = $2
`
@@ -921,12 +1111,13 @@ func (q *Queries) GetChannelChatSessionBindingBySession(ctx context.Context, arg
&i.Config,
&i.CreatedAt,
&i.PendingFresh,
+ &i.ContextRevision,
)
return i, err
}
const getChannelChatSessionBindingBySessionAny = `-- name: GetChannelChatSessionBindingBySessionAny :one
-SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh FROM channel_chat_session_binding
+SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision FROM channel_chat_session_binding
WHERE chat_session_id = $1
`
@@ -951,6 +1142,7 @@ func (q *Queries) GetChannelChatSessionBindingBySessionAny(ctx context.Context,
&i.Config,
&i.CreatedAt,
&i.PendingFresh,
+ &i.ContextRevision,
)
return i, err
}
@@ -1404,6 +1596,63 @@ func (q *Queries) ListChannelInstallationsByWorkspace(ctx context.Context, arg L
return items, nil
}
+const lockChannelChatContextGenerationByRevision = `-- name: LockChannelChatContextGenerationByRevision :one
+SELECT chat_session_id, revision, history_start_message_id, history_end_message_id, history_boundary_pending, pending_fresh, initiator_user_id, created_at FROM channel_chat_context_generation
+WHERE chat_session_id = $1
+ AND revision = $2
+FOR UPDATE
+`
+
+type LockChannelChatContextGenerationByRevisionParams struct {
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ Revision int64 `json:"revision"`
+}
+
+func (q *Queries) LockChannelChatContextGenerationByRevision(ctx context.Context, arg LockChannelChatContextGenerationByRevisionParams) (ChannelChatContextGeneration, error) {
+ row := q.db.QueryRow(ctx, lockChannelChatContextGenerationByRevision, arg.ChatSessionID, arg.Revision)
+ var i ChannelChatContextGeneration
+ err := row.Scan(
+ &i.ChatSessionID,
+ &i.Revision,
+ &i.HistoryStartMessageID,
+ &i.HistoryEndMessageID,
+ &i.HistoryBoundaryPending,
+ &i.PendingFresh,
+ &i.InitiatorUserID,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
+const lockChannelChatSessionBindingForContext = `-- name: LockChannelChatSessionBindingForContext :one
+SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision FROM channel_chat_session_binding
+WHERE chat_session_id = $1
+FOR UPDATE
+`
+
+// Context mutations acquire this row after chat_session and before any
+// channel_chat_context_generation row. Keeping the statements separate makes
+// the lock order explicit and identical for append, /new, and task enqueue.
+func (q *Queries) LockChannelChatSessionBindingForContext(ctx context.Context, chatSessionID pgtype.UUID) (ChannelChatSessionBinding, error) {
+ row := q.db.QueryRow(ctx, lockChannelChatSessionBindingForContext, chatSessionID)
+ var i ChannelChatSessionBinding
+ err := row.Scan(
+ &i.ID,
+ &i.ChatSessionID,
+ &i.InstallationID,
+ &i.ChannelType,
+ &i.ChannelChatID,
+ &i.ChatType,
+ &i.LastMessageID,
+ &i.LastThreadID,
+ &i.Config,
+ &i.CreatedAt,
+ &i.PendingFresh,
+ &i.ContextRevision,
+ )
+ return i, err
+}
+
const lockChannelChatSessionPendingFresh = `-- name: LockChannelChatSessionPendingFresh :one
SELECT pending_fresh FROM channel_chat_session_binding
WHERE chat_session_id = $1
@@ -1559,6 +1808,17 @@ cleared_chat_sessions AS (
WHERE installation_id IN (SELECT id FROM dead)
RETURNING chat_session_id
),
+cleared_chat_contexts AS (
+ -- A revoked installation can still own preserved Chat history and an
+ -- in-flight task snapshot. Remove only generations whose Chat was already
+ -- cascade-deleted by an earlier orphan teardown.
+ DELETE FROM channel_chat_context_generation AS generation
+ WHERE generation.chat_session_id IN (SELECT chat_session_id FROM cleared_chat_sessions)
+ AND NOT EXISTS (
+ SELECT 1 FROM chat_session AS session
+ WHERE session.id = generation.chat_session_id
+ )
+),
cleared_outbound_cards AS (
-- channel_outbound_card_message is keyed by chat_session_id (no installation_id,
-- no FK), so it is reached through the just-removed chat-session bindings. On an
@@ -1814,6 +2074,50 @@ func (q *Queries) ReleaseChannelWSLease(ctx context.Context, arg ReleaseChannelW
return err
}
+const resolveChannelChatContextHistoryStart = `-- name: ResolveChannelChatContextHistoryStart :exec
+UPDATE channel_chat_context_generation
+SET history_start_message_id = $1,
+ history_boundary_pending = FALSE
+WHERE chat_session_id = $2
+ AND revision = $3
+ AND history_boundary_pending
+`
+
+type ResolveChannelChatContextHistoryStartParams struct {
+ HistoryStartMessageID pgtype.Text `json:"history_start_message_id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ Revision int64 `json:"revision"`
+}
+
+func (q *Queries) ResolveChannelChatContextHistoryStart(ctx context.Context, arg ResolveChannelChatContextHistoryStartParams) error {
+ _, err := q.db.Exec(ctx, resolveChannelChatContextHistoryStart, arg.HistoryStartMessageID, arg.ChatSessionID, arg.Revision)
+ return err
+}
+
+const setChannelChatContextInitiator = `-- name: SetChannelChatContextInitiator :one
+UPDATE channel_chat_context_generation
+SET initiator_user_id = $1
+WHERE chat_session_id = $2
+ AND revision = $3
+RETURNING initiator_user_id
+`
+
+type SetChannelChatContextInitiatorParams struct {
+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ Revision int64 `json:"revision"`
+}
+
+// Snapshots the latest authenticated sender whose durable input belongs to a
+// generation. Crash recovery must use this identity rather than the sender of
+// a later generation that happened to re-arm the lost debounce timer.
+func (q *Queries) SetChannelChatContextInitiator(ctx context.Context, arg SetChannelChatContextInitiatorParams) (pgtype.UUID, error) {
+ row := q.db.QueryRow(ctx, setChannelChatContextInitiator, arg.InitiatorUserID, arg.ChatSessionID, arg.Revision)
+ var initiator_user_id pgtype.UUID
+ err := row.Scan(&initiator_user_id)
+ return initiator_user_id, err
+}
+
const setChannelInstallationConfig = `-- name: SetChannelInstallationConfig :exec
UPDATE channel_installation
SET config = $2, updated_at = now()
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 34cab339cc..881e9ecd67 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -221,7 +221,8 @@ func (q *Queries) CreateChatDraftRestore(ctx context.Context, arg CreateChatDraf
const createChatMessage = `-- name: CreateChatMessage :one
INSERT INTO chat_message (
chat_session_id, role, content, task_id, failure_reason, elapsed_ms,
- message_kind, quick_actions, channel_media_pending_until, channel_ingested, id
+ message_kind, quick_actions, channel_media_pending_until, channel_ingested,
+ channel_context_revision, id
)
VALUES (
$1, $2, $3, $4, $5, $6,
@@ -236,9 +237,10 @@ VALUES (
CASE WHEN $9::float8 IS NULL THEN NULL
ELSE now() + make_interval(secs => $9::float8) END,
COALESCE($10::boolean, FALSE),
- COALESCE($11::uuid, gen_random_uuid())
+ $11,
+ COALESCE($12::uuid, gen_random_uuid())
)
-RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions
+RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids
`
type CreateChatMessageParams struct {
@@ -252,6 +254,7 @@ type CreateChatMessageParams struct {
QuickActions []byte `json:"quick_actions"`
ChannelMediaPendingSecs pgtype.Float8 `json:"channel_media_pending_secs"`
ChannelIngested pgtype.Bool `json:"channel_ingested"`
+ ChannelContextRevision pgtype.Int8 `json:"channel_context_revision"`
ID pgtype.UUID `json:"id"`
}
@@ -270,6 +273,7 @@ func (q *Queries) CreateChatMessage(ctx context.Context, arg CreateChatMessagePa
arg.QuickActions,
arg.ChannelMediaPendingSecs,
arg.ChannelIngested,
+ arg.ChannelContextRevision,
arg.ID,
)
var i ChatMessage
@@ -286,6 +290,11 @@ func (q *Queries) CreateChatMessage(ctx context.Context, arg CreateChatMessagePa
&i.ChannelMediaPendingUntil,
&i.ChannelIngested,
&i.QuickActions,
+ &i.ChannelContextRevision,
+ &i.ChannelOutboundType,
+ &i.ChannelOutboundInstallationID,
+ &i.ChannelOutboundChatID,
+ &i.ChannelOutboundMessageIds,
)
return i, err
}
@@ -343,7 +352,7 @@ INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, chat_session_id,
initiator_user_id, originator_user_id, accountable_user_id, force_fresh_session, runtime_mcp_overlay,
runtime_connected_apps, originator_source, trigger_evidence_kind, trigger_evidence_ref_id,
- fire_at, id
+ fire_at, channel_context_revision, id
)
SELECT
$1, $2, NULL,
@@ -358,27 +367,29 @@ SELECT
$13,
$14,
$6::timestamptz,
- COALESCE($15::uuid, gen_random_uuid())
+ $15::bigint,
+ COALESCE($16::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, NULL, $2)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
type CreateChatTaskParams struct {
- AgentID pgtype.UUID `json:"agent_id"`
- RuntimeID pgtype.UUID `json:"runtime_id"`
- Priority int32 `json:"priority"`
- ChatSessionID pgtype.UUID `json:"chat_session_id"`
- InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
- FireAt pgtype.Timestamptz `json:"fire_at"`
- OriginatorUserID pgtype.UUID `json:"originator_user_id"`
- AccountableUserID pgtype.UUID `json:"accountable_user_id"`
- ForceFreshSession pgtype.Bool `json:"force_fresh_session"`
- RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`
- RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
- OriginatorSource pgtype.Text `json:"originator_source"`
- TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`
- TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
- ID pgtype.UUID `json:"id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ Priority int32 `json:"priority"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
+ FireAt pgtype.Timestamptz `json:"fire_at"`
+ OriginatorUserID pgtype.UUID `json:"originator_user_id"`
+ AccountableUserID pgtype.UUID `json:"accountable_user_id"`
+ ForceFreshSession pgtype.Bool `json:"force_fresh_session"`
+ RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`
+ RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
+ OriginatorSource pgtype.Text `json:"originator_source"`
+ TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`
+ TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
+ ChannelContextRevision pgtype.Int8 `json:"channel_context_revision"`
+ ID pgtype.UUID `json:"id"`
}
// Fenced against workspace teardown: lock_task_owner_rows (migration 284)
@@ -404,6 +415,7 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
arg.OriginatorSource,
arg.TriggerEvidenceKind,
arg.TriggerEvidenceRefID,
+ arg.ChannelContextRevision,
arg.ID,
)
var i AgentTaskQueue
@@ -461,6 +473,7 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -475,7 +488,7 @@ VALUES (
$3::timestamptz + interval '1 microsecond',
COALESCE($4::uuid, gen_random_uuid())
)
-RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions
+RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids
`
type CreateMikaOnboardingOpeningParams struct {
@@ -518,6 +531,11 @@ func (q *Queries) CreateMikaOnboardingOpening(ctx context.Context, arg CreateMik
&i.ChannelMediaPendingUntil,
&i.ChannelIngested,
&i.QuickActions,
+ &i.ChannelContextRevision,
+ &i.ChannelOutboundType,
+ &i.ChannelOutboundInstallationID,
+ &i.ChannelOutboundChatID,
+ &i.ChannelOutboundMessageIds,
)
return i, err
}
@@ -535,7 +553,7 @@ FROM (
WHERE task.id = $1
AND pending.max_until IS NOT NULL
AND (task.fire_at IS NULL OR task.fire_at < pending.max_until)
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision
`
// Closes the enqueue-vs-append race: under READ COMMITTED a media message can
@@ -601,6 +619,7 @@ func (q *Queries) DeferChatTaskForSealedPendingMedia(ctx context.Context, taskID
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
@@ -685,7 +704,7 @@ DELETE FROM chat_message
WHERE task_id = $1
AND role = 'user'
AND message_kind <> 'onboarding_kickoff'
-RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions
+RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids
`
// Deletes the MEMBER-TYPED input of a cancelled/edited turn.
@@ -715,6 +734,11 @@ func (q *Queries) DeleteUserChatMessageByTask(ctx context.Context, taskID pgtype
&i.ChannelMediaPendingUntil,
&i.ChannelIngested,
&i.QuickActions,
+ &i.ChannelContextRevision,
+ &i.ChannelOutboundType,
+ &i.ChannelOutboundInstallationID,
+ &i.ChannelOutboundChatID,
+ &i.ChannelOutboundMessageIds,
)
return i, err
}
@@ -725,26 +749,39 @@ FROM chat_message
WHERE chat_session_id = $1
AND role = 'user'
AND message_kind != 'channel_command'
+ AND (
+ $2::bigint IS NULL
+ OR channel_context_revision = $2::bigint
+ OR (
+ $2::bigint = 1
+ AND channel_context_revision IS NULL
+ )
+ )
AND channel_media_pending_until > now()
ORDER BY channel_media_pending_until DESC
LIMIT 1
`
+type GetChannelMediaPendingUntilParams struct {
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ ChannelContextRevision pgtype.Int8 `json:"channel_context_revision"`
+}
+
// The latest unexpired media deadline gates a channel task. Using a durable
// task fire_at means a process restart still produces the placeholder fallback.
// Only a turn that can join a task's input batch may gate one: channel_command
// turns are excluded from the seal below, so an unrelated later message would
// otherwise wait out a command's media (or its whole fallback budget, since a
// command whose create failed never runs the binder that clears the marker).
-func (q *Queries) GetChannelMediaPendingUntil(ctx context.Context, chatSessionID pgtype.UUID) (pgtype.Timestamptz, error) {
- row := q.db.QueryRow(ctx, getChannelMediaPendingUntil, chatSessionID)
+func (q *Queries) GetChannelMediaPendingUntil(ctx context.Context, arg GetChannelMediaPendingUntilParams) (pgtype.Timestamptz, error) {
+ row := q.db.QueryRow(ctx, getChannelMediaPendingUntil, arg.ChatSessionID, arg.ChannelContextRevision)
var channel_media_pending_until pgtype.Timestamptz
err := row.Scan(&channel_media_pending_until)
return channel_media_pending_until, err
}
const getChatMessage = `-- name: GetChatMessage :one
-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions FROM chat_message
+SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids FROM chat_message
WHERE id = $1
`
@@ -764,12 +801,17 @@ func (q *Queries) GetChatMessage(ctx context.Context, id pgtype.UUID) (ChatMessa
&i.ChannelMediaPendingUntil,
&i.ChannelIngested,
&i.QuickActions,
+ &i.ChannelContextRevision,
+ &i.ChannelOutboundType,
+ &i.ChannelOutboundInstallationID,
+ &i.ChannelOutboundChatID,
+ &i.ChannelOutboundMessageIds,
)
return i, err
}
const getChatMessageByTaskAssistant = `-- name: GetChatMessageByTaskAssistant :one
-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions FROM chat_message
+SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids FROM chat_message
WHERE task_id = $1 AND role = 'assistant'
ORDER BY created_at DESC
LIMIT 1
@@ -793,6 +835,11 @@ func (q *Queries) GetChatMessageByTaskAssistant(ctx context.Context, taskID pgty
&i.ChannelMediaPendingUntil,
&i.ChannelIngested,
&i.QuickActions,
+ &i.ChannelContextRevision,
+ &i.ChannelOutboundType,
+ &i.ChannelOutboundInstallationID,
+ &i.ChannelOutboundChatID,
+ &i.ChannelOutboundMessageIds,
)
return i, err
}
@@ -865,6 +912,10 @@ WITH retired_sessions AS (
SELECT DISTINCT r.retired_session_id AS session_id
FROM agent_task_queue r
WHERE r.chat_session_id = $1
+ AND (
+ $2::bigint IS NULL
+ OR COALESCE(r.channel_context_revision, 1) = $2::bigint
+ )
AND r.retired_session_id IS NOT NULL
), resume_overflow_at AS (
-- completed_at alone, where the issue-side twin coalesces four columns:
@@ -874,6 +925,10 @@ WITH retired_sessions AS (
SELECT MAX(t.completed_at) AS at
FROM agent_task_queue t
WHERE t.chat_session_id = $1
+ AND (
+ $2::bigint IS NULL
+ OR COALESCE(t.channel_context_revision, 1) = $2::bigint
+ )
AND t.status = 'failed'
AND (
COALESCE(t.failure_reason, '') = 'codex_resume_oversized'
@@ -884,6 +939,10 @@ WITH retired_sessions AS (
t.session_id, t.work_dir, t.runtime_id, t.status, t.failure_reason, t.error, t.completed_at
FROM agent_task_queue t
WHERE t.chat_session_id = $1
+ AND (
+ $2::bigint IS NULL
+ OR COALESCE(t.channel_context_revision, 1) = $2::bigint
+ )
AND t.session_id IS NOT NULL
AND t.status IN ('completed', 'failed', 'cancelled')
ORDER BY t.session_id, t.completed_at DESC
@@ -912,9 +971,10 @@ WHERE session_id NOT IN (SELECT session_id FROM retired_sessions)
)
-- MUL-5722, mirroring GetLastTaskSession: an overflowed resume records no
-- session, so exclude by time instead of by matching the failed row. Note
- -- this only guards the FALLBACK — the claim handler reads
- -- chat_session.session_id first, so a pointer still naming the oversized
- -- thread has to be cleared at fail time (see FailTask) to be covered.
+ -- this only guards the FALLBACK for legacy tasks — the claim handler reads
+ -- chat_session.session_id first for them, so a pointer still naming the
+ -- oversized thread has to be cleared at fail time (see FailTask) to be
+ -- covered. Context-scoped channel tasks resolve directly from this query.
AND (
(SELECT at FROM resume_overflow_at) IS NULL
OR completed_at > (SELECT at FROM resume_overflow_at)
@@ -923,6 +983,11 @@ ORDER BY completed_at DESC
LIMIT 1
`
+type GetLastChatTaskSessionParams struct {
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ ChannelContextRevision pgtype.Int8 `json:"channel_context_revision"`
+}
+
type GetLastChatTaskSessionRow struct {
SessionID pgtype.Text `json:"session_id"`
WorkDir pgtype.Text `json:"work_dir"`
@@ -933,7 +998,8 @@ type GetLastChatTaskSessionRow struct {
// session_id. Includes completed, failed AND cancelled tasks: each of them may
// have established a real agent session, and we'd rather resume there than
// start over and lose conversation memory. Used as a fallback when
-// chat_session.session_id is NULL. Resume-unsafe failures are excluded because
+// chat_session.session_id is NULL, and as the authoritative generation-scoped
+// source for channel tasks. Resume-unsafe failures are excluded because
// replaying those sessions deterministically reproduces the same terminal
// state. Keep this list in sync with resumeUnsafeFailureReason and
// GetLastTaskSession.
@@ -968,15 +1034,15 @@ type GetLastChatTaskSessionRow struct {
// session_id. Judging each session by its LATEST terminal state means a newer
// poisoned row invalidates the whole session, while a genuinely different
// healthy session stays eligible.
-func (q *Queries) GetLastChatTaskSession(ctx context.Context, chatSessionID pgtype.UUID) (GetLastChatTaskSessionRow, error) {
- row := q.db.QueryRow(ctx, getLastChatTaskSession, chatSessionID)
+func (q *Queries) GetLastChatTaskSession(ctx context.Context, arg GetLastChatTaskSessionParams) (GetLastChatTaskSessionRow, error) {
+ row := q.db.QueryRow(ctx, getLastChatTaskSession, arg.ChatSessionID, arg.ChannelContextRevision)
var i GetLastChatTaskSessionRow
err := row.Scan(&i.SessionID, &i.WorkDir, &i.RuntimeID)
return i, err
}
const getLatestAssistantChatMessageForSession = `-- name: GetLatestAssistantChatMessageForSession :one
-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions FROM chat_message
+SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids FROM chat_message
WHERE chat_session_id = $1 AND role = 'assistant' AND task_id IS NOT NULL
ORDER BY created_at DESC
LIMIT 1
@@ -1002,6 +1068,11 @@ func (q *Queries) GetLatestAssistantChatMessageForSession(ctx context.Context, c
&i.ChannelMediaPendingUntil,
&i.ChannelIngested,
&i.QuickActions,
+ &i.ChannelContextRevision,
+ &i.ChannelOutboundType,
+ &i.ChannelOutboundInstallationID,
+ &i.ChannelOutboundChatID,
+ &i.ChannelOutboundMessageIds,
)
return i, err
}
@@ -1246,10 +1317,20 @@ func (q *Queries) LinkChatMessageToTask(ctx context.Context, arg LinkChatMessage
const linkUnownedChannelChatMessagesToTask = `-- name: LinkUnownedChannelChatMessagesToTask :exec
UPDATE chat_message AS message
SET task_id = $1
+FROM agent_task_queue AS task
WHERE message.chat_session_id = $2
+ AND task.id = $1
AND message.role = 'user'
AND message.task_id IS NULL
AND message.message_kind != 'channel_command'
+ AND (
+ task.channel_context_revision IS NULL
+ OR message.channel_context_revision = task.channel_context_revision
+ OR (
+ task.channel_context_revision = 1
+ AND message.channel_context_revision IS NULL
+ )
+ )
AND NOT EXISTS (
SELECT 1
FROM chat_message AS prior
@@ -1525,6 +1606,63 @@ func (q *Queries) ListAllChatSessionsByCreator(ctx context.Context, arg ListAllC
return items, nil
}
+const listChannelOutboundMessageIDsForContext = `-- name: ListChannelOutboundMessageIDsForContext :many
+SELECT external.message_id::text
+FROM chat_message AS message
+JOIN agent_task_queue AS owner ON owner.id = message.task_id
+CROSS JOIN LATERAL unnest(message.channel_outbound_message_ids) AS external(message_id)
+WHERE message.chat_session_id = $1
+ AND message.role = 'assistant'
+ AND message.channel_outbound_type = $2
+ AND message.channel_outbound_installation_id = $3
+ AND message.channel_outbound_chat_id = $4
+ AND message.channel_outbound_message_ids IS NOT NULL
+ AND external.message_id = ANY($5::text[])
+ AND (
+ owner.channel_context_revision = $6
+ OR ($6 = 1 AND owner.channel_context_revision IS NULL)
+ )
+`
+
+type ListChannelOutboundMessageIDsForContextParams struct {
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ ChannelType pgtype.Text `json:"channel_type"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ChannelChatID pgtype.Text `json:"channel_chat_id"`
+ CandidateMessageIds []string `json:"candidate_message_ids"`
+ ChannelContextRevision pgtype.Int8 `json:"channel_context_revision"`
+}
+
+// Assistant generation is inherited from its owning task, matching
+// ListChatMessagesPageForChannelContext. Provider IDs are scoped by session,
+// adapter, and immutable generation before being trusted as agent context.
+func (q *Queries) ListChannelOutboundMessageIDsForContext(ctx context.Context, arg ListChannelOutboundMessageIDsForContextParams) ([]string, error) {
+ rows, err := q.db.Query(ctx, listChannelOutboundMessageIDsForContext,
+ arg.ChatSessionID,
+ arg.ChannelType,
+ arg.InstallationID,
+ arg.ChannelChatID,
+ arg.CandidateMessageIds,
+ arg.ChannelContextRevision,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []string{}
+ for rows.Next() {
+ var external_message_id string
+ if err := rows.Scan(&external_message_id); err != nil {
+ return nil, err
+ }
+ items = append(items, external_message_id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listChatDraftRestoresBySession = `-- name: ListChatDraftRestoresBySession :many
SELECT id, chat_session_id, task_id, content, attachment_ids, created_at FROM chat_draft_restore
WHERE chat_session_id = $1
@@ -1559,7 +1697,7 @@ func (q *Queries) ListChatDraftRestoresBySession(ctx context.Context, chatSessio
}
const listChatInputMessages = `-- name: ListChatInputMessages :many
-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions FROM chat_message
+SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids FROM chat_message
WHERE task_id = $1 AND role = 'user'
ORDER BY created_at ASC, id ASC
`
@@ -1593,6 +1731,11 @@ func (q *Queries) ListChatInputMessages(ctx context.Context, taskID pgtype.UUID)
&i.ChannelMediaPendingUntil,
&i.ChannelIngested,
&i.QuickActions,
+ &i.ChannelContextRevision,
+ &i.ChannelOutboundType,
+ &i.ChannelOutboundInstallationID,
+ &i.ChannelOutboundChatID,
+ &i.ChannelOutboundMessageIds,
); err != nil {
return nil, err
}
@@ -1605,7 +1748,7 @@ func (q *Queries) ListChatInputMessages(ctx context.Context, taskID pgtype.UUID)
}
const listChatMessages = `-- name: ListChatMessages :many
-SELECT message.id, message.chat_session_id, message.role, message.content, message.task_id, message.created_at, message.failure_reason, message.elapsed_ms, message.message_kind, message.channel_media_pending_until, message.channel_ingested, message.quick_actions FROM chat_message AS message
+SELECT message.id, message.chat_session_id, message.role, message.content, message.task_id, message.created_at, message.failure_reason, message.elapsed_ms, message.message_kind, message.channel_media_pending_until, message.channel_ingested, message.quick_actions, message.channel_context_revision, message.channel_outbound_type, message.channel_outbound_installation_id, message.channel_outbound_chat_id, message.channel_outbound_message_ids FROM chat_message AS message
WHERE message.chat_session_id = $1
AND message.message_kind != 'channel_command'
AND NOT (
@@ -1672,6 +1815,11 @@ func (q *Queries) ListChatMessages(ctx context.Context, chatSessionID pgtype.UUI
&i.ChannelMediaPendingUntil,
&i.ChannelIngested,
&i.QuickActions,
+ &i.ChannelContextRevision,
+ &i.ChannelOutboundType,
+ &i.ChannelOutboundInstallationID,
+ &i.ChannelOutboundChatID,
+ &i.ChannelOutboundMessageIds,
); err != nil {
return nil, err
}
@@ -1684,7 +1832,7 @@ func (q *Queries) ListChatMessages(ctx context.Context, chatSessionID pgtype.UUI
}
const listChatMessagesForLegacyTask = `-- name: ListChatMessagesForLegacyTask :many
-SELECT message.id, message.chat_session_id, message.role, message.content, message.task_id, message.created_at, message.failure_reason, message.elapsed_ms, message.message_kind, message.channel_media_pending_until, message.channel_ingested, message.quick_actions FROM chat_message AS message
+SELECT message.id, message.chat_session_id, message.role, message.content, message.task_id, message.created_at, message.failure_reason, message.elapsed_ms, message.message_kind, message.channel_media_pending_until, message.channel_ingested, message.quick_actions, message.channel_context_revision, message.channel_outbound_type, message.channel_outbound_installation_id, message.channel_outbound_chat_id, message.channel_outbound_message_ids FROM chat_message AS message
WHERE message.chat_session_id = $1
AND NOT (
message.role = 'user'
@@ -1740,6 +1888,11 @@ func (q *Queries) ListChatMessagesForLegacyTask(ctx context.Context, chatSession
&i.ChannelMediaPendingUntil,
&i.ChannelIngested,
&i.QuickActions,
+ &i.ChannelContextRevision,
+ &i.ChannelOutboundType,
+ &i.ChannelOutboundInstallationID,
+ &i.ChannelOutboundChatID,
+ &i.ChannelOutboundMessageIds,
); err != nil {
return nil, err
}
@@ -1752,7 +1905,7 @@ func (q *Queries) ListChatMessagesForLegacyTask(ctx context.Context, chatSession
}
const listChatMessagesPage = `-- name: ListChatMessagesPage :many
-SELECT message.id, message.chat_session_id, message.role, message.content, message.task_id, message.created_at, message.failure_reason, message.elapsed_ms, message.message_kind, message.channel_media_pending_until, message.channel_ingested, message.quick_actions FROM chat_message AS message
+SELECT message.id, message.chat_session_id, message.role, message.content, message.task_id, message.created_at, message.failure_reason, message.elapsed_ms, message.message_kind, message.channel_media_pending_until, message.channel_ingested, message.quick_actions, message.channel_context_revision, message.channel_outbound_type, message.channel_outbound_installation_id, message.channel_outbound_chat_id, message.channel_outbound_message_ids FROM chat_message AS message
WHERE message.chat_session_id = $1
AND message.message_kind != 'channel_command'
AND NOT (
@@ -1824,6 +1977,98 @@ func (q *Queries) ListChatMessagesPage(ctx context.Context, arg ListChatMessages
&i.ChannelMediaPendingUntil,
&i.ChannelIngested,
&i.QuickActions,
+ &i.ChannelContextRevision,
+ &i.ChannelOutboundType,
+ &i.ChannelOutboundInstallationID,
+ &i.ChannelOutboundChatID,
+ &i.ChannelOutboundMessageIds,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listChatMessagesPageForChannelContext = `-- name: ListChatMessagesPageForChannelContext :many
+SELECT message.id, message.chat_session_id, message.role, message.content, message.task_id, message.created_at, message.failure_reason, message.elapsed_ms, message.message_kind, message.channel_media_pending_until, message.channel_ingested, message.quick_actions, message.channel_context_revision, message.channel_outbound_type, message.channel_outbound_installation_id, message.channel_outbound_chat_id, message.channel_outbound_message_ids
+FROM chat_message AS message
+LEFT JOIN agent_task_queue AS owner ON owner.id = message.task_id
+WHERE message.chat_session_id = $1
+ AND message.message_kind != 'channel_command'
+ AND (
+ (
+ message.role = 'user'
+ AND (
+ message.channel_context_revision = $2
+ OR ($2 = 1 AND message.channel_context_revision IS NULL)
+ )
+ )
+ OR
+ (
+ message.role != 'user'
+ AND (
+ owner.channel_context_revision = $2
+ OR ($2 = 1 AND owner.channel_context_revision IS NULL)
+ )
+ )
+ )
+ AND (
+ $3::timestamptz IS NULL
+ OR (message.created_at, message.id) < ($3::timestamptz, $4::uuid)
+ )
+ORDER BY message.created_at DESC, message.id DESC
+LIMIT $5
+`
+
+type ListChatMessagesPageForChannelContextParams struct {
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ ChannelContextRevision pgtype.Int8 `json:"channel_context_revision"`
+ BeforeCreatedAt pgtype.Timestamptz `json:"before_created_at"`
+ BeforeID pgtype.UUID `json:"before_id"`
+ PageLimit int32 `json:"page_limit"`
+}
+
+// Agent-only transcript projection. UI readers continue using the unfiltered
+// ListChatMessagesPage query, while a channel task can see only the context
+// generation snapshotted on that task. Assistant rows inherit their generation
+// from their owning task, so retries and late completions stay in their turn.
+func (q *Queries) ListChatMessagesPageForChannelContext(ctx context.Context, arg ListChatMessagesPageForChannelContextParams) ([]ChatMessage, error) {
+ rows, err := q.db.Query(ctx, listChatMessagesPageForChannelContext,
+ arg.ChatSessionID,
+ arg.ChannelContextRevision,
+ arg.BeforeCreatedAt,
+ arg.BeforeID,
+ arg.PageLimit,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ChatMessage{}
+ for rows.Next() {
+ var i ChatMessage
+ if err := rows.Scan(
+ &i.ID,
+ &i.ChatSessionID,
+ &i.Role,
+ &i.Content,
+ &i.TaskID,
+ &i.CreatedAt,
+ &i.FailureReason,
+ &i.ElapsedMs,
+ &i.MessageKind,
+ &i.ChannelMediaPendingUntil,
+ &i.ChannelIngested,
+ &i.QuickActions,
+ &i.ChannelContextRevision,
+ &i.ChannelOutboundType,
+ &i.ChannelOutboundInstallationID,
+ &i.ChannelOutboundChatID,
+ &i.ChannelOutboundMessageIds,
); err != nil {
return nil, err
}
@@ -2090,6 +2335,68 @@ func (q *Queries) ListPendingChatTasksForSession(ctx context.Context, chatSessio
return items, nil
}
+const listUnownedChannelChatContextRevisions = `-- name: ListUnownedChannelChatContextRevisions :many
+WITH pending AS (
+ SELECT DISTINCT COALESCE(channel_context_revision, 1)::bigint AS context_revision
+ FROM chat_message
+ WHERE chat_session_id = $1
+ AND role = 'user'
+ AND task_id IS NULL
+ AND message_kind != 'channel_command'
+)
+SELECT pending.context_revision, generation.initiator_user_id
+FROM pending
+LEFT JOIN channel_chat_context_generation AS generation
+ ON generation.chat_session_id = $1
+ AND generation.revision = pending.context_revision
+ORDER BY pending.context_revision
+`
+
+type ListUnownedChannelChatContextRevisionsRow struct {
+ ContextRevision int64 `json:"context_revision"`
+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
+}
+
+// Returns every durable context generation that still has channel input without
+// a task owner. A process crash drops in-memory debounce timers; the next normal
+// inbound message uses this list to re-arm older generations instead of only
+// recovering the current one. Legacy NULL revisions are generation 1.
+func (q *Queries) ListUnownedChannelChatContextRevisions(ctx context.Context, chatSessionID pgtype.UUID) ([]ListUnownedChannelChatContextRevisionsRow, error) {
+ rows, err := q.db.Query(ctx, listUnownedChannelChatContextRevisions, chatSessionID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListUnownedChannelChatContextRevisionsRow{}
+ for rows.Next() {
+ var i ListUnownedChannelChatContextRevisionsRow
+ if err := rows.Scan(&i.ContextRevision, &i.InitiatorUserID); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const lockChatSessionForAppend = `-- name: LockChatSessionForAppend :one
+SELECT id FROM chat_session
+WHERE id = $1
+FOR KEY SHARE
+`
+
+// The append transaction's first lock. FOR KEY SHARE remains compatible with
+// task enqueue's FOR NO KEY UPDATE while establishing chat_session -> binding
+// -> generation order before the later TouchChatSession update.
+func (q *Queries) LockChatSessionForAppend(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error) {
+ row := q.db.QueryRow(ctx, lockChatSessionForAppend, id)
+ var id_2 pgtype.UUID
+ err := row.Scan(&id_2)
+ return id_2, err
+}
+
const lockChatSessionForDelete = `-- name: LockChatSessionForDelete :one
SELECT id FROM chat_session
WHERE id = $1
@@ -2440,12 +2747,11 @@ WHERE task.chat_session_id = $1
AND NOT EXISTS (
SELECT 1
FROM chat_message AS message
- WHERE message.chat_session_id = $1
+ WHERE message.task_id = task.id
AND message.role = 'user'
- AND message.message_kind != 'channel_command'
AND message.channel_media_pending_until > now()
)
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision
`
// Media completion may race with the 3s run batcher. Promote every original
@@ -2517,6 +2823,7 @@ func (q *Queries) PromoteChannelChatTasksIfMediaReady(ctx context.Context, chatS
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -2732,6 +3039,43 @@ func (q *Queries) ReleaseOnboardingKickoffFromTask(ctx context.Context, id pgtyp
return err
}
+const setChatMessageChannelOutboundProvenanceByTask = `-- name: SetChatMessageChannelOutboundProvenanceByTask :execrows
+UPDATE chat_message
+SET channel_outbound_type = $1,
+ channel_outbound_installation_id = $2,
+ channel_outbound_chat_id = $3,
+ channel_outbound_message_ids = $4::text[]
+WHERE task_id = $5
+ AND role = 'assistant'
+`
+
+type SetChatMessageChannelOutboundProvenanceByTaskParams struct {
+ ChannelType pgtype.Text `json:"channel_type"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ChannelChatID pgtype.Text `json:"channel_chat_id"`
+ MessageIds []string `json:"message_ids"`
+ TaskID pgtype.UUID `json:"task_id"`
+}
+
+// The assistant row is committed before EventChatDone is published. Attach the
+// external identifiers produced by the adapter to that durable turn so a live
+// provider-history reader can apply the same context-generation boundary as
+// the stored transcript. A send that succeeds but cannot record provenance is
+// deliberately treated as unknown (and therefore excluded from generation >1).
+func (q *Queries) SetChatMessageChannelOutboundProvenanceByTask(ctx context.Context, arg SetChatMessageChannelOutboundProvenanceByTaskParams) (int64, error) {
+ result, err := q.db.Exec(ctx, setChatMessageChannelOutboundProvenanceByTask,
+ arg.ChannelType,
+ arg.InstallationID,
+ arg.ChannelChatID,
+ arg.MessageIds,
+ arg.TaskID,
+ )
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
const setChatMessageQuickActionsByTask = `-- name: SetChatMessageQuickActionsByTask :one
UPDATE chat_message
SET quick_actions = $2
@@ -2741,7 +3085,7 @@ WHERE id = (
ORDER BY inner_msg.created_at DESC
LIMIT 1
)
-RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions
+RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids
`
type SetChatMessageQuickActionsByTaskParams struct {
@@ -2765,6 +3109,11 @@ func (q *Queries) SetChatMessageQuickActionsByTask(ctx context.Context, arg SetC
&i.ChannelMediaPendingUntil,
&i.ChannelIngested,
&i.QuickActions,
+ &i.ChannelContextRevision,
+ &i.ChannelOutboundType,
+ &i.ChannelOutboundInstallationID,
+ &i.ChannelOutboundChatID,
+ &i.ChannelOutboundMessageIds,
)
return i, err
}
@@ -2855,7 +3204,7 @@ const setChatTaskInputOwnerSelf = `-- name: SetChatTaskInputOwnerSelf :one
UPDATE agent_task_queue
SET chat_input_task_id = id
WHERE id = $1
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
// Stamps a freshly-created direct-chat task as the owner of its own input batch
@@ -2922,6 +3271,7 @@ func (q *Queries) SetChatTaskInputOwnerSelf(ctx context.Context, id pgtype.UUID)
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 6fa1d209ac..be5748aaba 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -170,6 +170,7 @@ type AgentTaskQueue struct {
RegenerateQuickActionsFor pgtype.UUID `json:"regenerate_quick_actions_for"`
BranchName pgtype.Text `json:"branch_name"`
DurableWorkDir pgtype.Text `json:"durable_work_dir"`
+ ChannelContextRevision pgtype.Int8 `json:"channel_context_revision"`
}
type AgentToLabel struct {
@@ -319,18 +320,30 @@ type ChannelBindingToken struct {
CreatedAt pgtype.Timestamptz `json:"created_at"`
}
+type ChannelChatContextGeneration struct {
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ Revision int64 `json:"revision"`
+ HistoryStartMessageID pgtype.Text `json:"history_start_message_id"`
+ HistoryEndMessageID pgtype.Text `json:"history_end_message_id"`
+ HistoryBoundaryPending bool `json:"history_boundary_pending"`
+ PendingFresh bool `json:"pending_fresh"`
+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
type ChannelChatSessionBinding struct {
- ID pgtype.UUID `json:"id"`
- ChatSessionID pgtype.UUID `json:"chat_session_id"`
- InstallationID pgtype.UUID `json:"installation_id"`
- ChannelType string `json:"channel_type"`
- ChannelChatID string `json:"channel_chat_id"`
- ChatType string `json:"chat_type"`
- LastMessageID pgtype.Text `json:"last_message_id"`
- LastThreadID pgtype.Text `json:"last_thread_id"`
- Config []byte `json:"config"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- PendingFresh bool `json:"pending_fresh"`
+ ID pgtype.UUID `json:"id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ChannelType string `json:"channel_type"`
+ ChannelChatID string `json:"channel_chat_id"`
+ ChatType string `json:"chat_type"`
+ LastMessageID pgtype.Text `json:"last_message_id"`
+ LastThreadID pgtype.Text `json:"last_thread_id"`
+ Config []byte `json:"config"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ PendingFresh bool `json:"pending_fresh"`
+ ContextRevision int64 `json:"context_revision"`
}
type ChannelInboundAudit struct {
@@ -417,18 +430,23 @@ type ChatDraftRestore struct {
}
type ChatMessage struct {
- ID pgtype.UUID `json:"id"`
- ChatSessionID pgtype.UUID `json:"chat_session_id"`
- Role string `json:"role"`
- Content string `json:"content"`
- TaskID pgtype.UUID `json:"task_id"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- FailureReason pgtype.Text `json:"failure_reason"`
- ElapsedMs pgtype.Int8 `json:"elapsed_ms"`
- MessageKind string `json:"message_kind"`
- ChannelMediaPendingUntil pgtype.Timestamptz `json:"channel_media_pending_until"`
- ChannelIngested bool `json:"channel_ingested"`
- QuickActions []byte `json:"quick_actions"`
+ ID pgtype.UUID `json:"id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ Role string `json:"role"`
+ Content string `json:"content"`
+ TaskID pgtype.UUID `json:"task_id"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ FailureReason pgtype.Text `json:"failure_reason"`
+ ElapsedMs pgtype.Int8 `json:"elapsed_ms"`
+ MessageKind string `json:"message_kind"`
+ ChannelMediaPendingUntil pgtype.Timestamptz `json:"channel_media_pending_until"`
+ ChannelIngested bool `json:"channel_ingested"`
+ QuickActions []byte `json:"quick_actions"`
+ ChannelContextRevision pgtype.Int8 `json:"channel_context_revision"`
+ ChannelOutboundType pgtype.Text `json:"channel_outbound_type"`
+ ChannelOutboundInstallationID pgtype.UUID `json:"channel_outbound_installation_id"`
+ ChannelOutboundChatID pgtype.Text `json:"channel_outbound_chat_id"`
+ ChannelOutboundMessageIds []string `json:"channel_outbound_message_ids"`
}
type ChatPinnedAgent struct {
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index 033044741b..004789f85a 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -16,7 +16,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE (runtime_id = ANY($1::uuid[]) OR agent_id = ANY($2::uuid[]))
AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision
`
type CancelAgentTasksByRuntimeOrAgentParams struct {
@@ -109,6 +109,7 @@ func (q *Queries) CancelAgentTasksByRuntimeOrAgent(ctx context.Context, arg Canc
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
@@ -248,7 +249,7 @@ SET status = 'failed', completed_at = now(), error = 'runtime went offline',
FROM victims
WHERE task.id = victims.id
AND task.status IN ('dispatched', 'running', 'waiting_local_directory')
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.branch_name, task.durable_work_dir, task.channel_context_revision
`
type FailTasksForOfflineRuntimesParams struct {
@@ -327,6 +328,7 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context, arg FailTasks
&i.RegenerateQuickActionsFor,
&i.BranchName,
&i.DurableWorkDir,
+ &i.ChannelContextRevision,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/generated/workspace.sql.go b/server/pkg/db/generated/workspace.sql.go
index ecdb8474e3..4ff55f680c 100644
--- a/server/pkg/db/generated/workspace.sql.go
+++ b/server/pkg/db/generated/workspace.sql.go
@@ -56,6 +56,9 @@ const deleteWorkspace = `-- name: DeleteWorkspace :exec
WITH ws_installations AS (
SELECT id FROM channel_installation WHERE workspace_id = $1
),
+ws_sessions AS (
+ SELECT id FROM chat_session WHERE workspace_id = $1
+),
ws_agents AS (
SELECT id FROM agent WHERE workspace_id = $1
),
@@ -72,6 +75,11 @@ cleared_chat_sessions AS (
DELETE FROM channel_chat_session_binding WHERE installation_id IN (SELECT id FROM ws_installations)
RETURNING chat_session_id
),
+cleared_chat_contexts AS (
+ DELETE FROM channel_chat_context_generation
+ WHERE chat_session_id IN (SELECT chat_session_id FROM cleared_chat_sessions)
+ OR chat_session_id IN (SELECT id FROM ws_sessions)
+),
cleared_outbound_cards AS (
-- channel_outbound_card_message is keyed by chat_session_id (no FK); its own
-- chat_session rows cascade away with the workspace, so reach the cards through
diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.go
index 3d06b1bfd7..f751062773 100644
--- a/server/pkg/db/generated/workspace_delete.sql.go
+++ b/server/pkg/db/generated/workspace_delete.sql.go
@@ -407,6 +407,10 @@ deleted_github_check_suites AS (
deleted_pending_github_suites AS (
DELETE FROM github_pending_check_suite WHERE workspace_id = $1
),
+deleted_channel_chat_contexts AS (
+ DELETE FROM channel_chat_context_generation
+ WHERE chat_session_id IN (SELECT id FROM ws_sessions)
+),
deleted_vcs_commit_statuses AS (
DELETE FROM vcs_commit_status
WHERE connection_id IN (SELECT id FROM ws_vcs_connections)
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index dc0d29e3de..4335a13f08 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -590,7 +590,7 @@ INSERT INTO agent_task_queue (
originator_source, delegated_from_task_id, rule_version_id,
trigger_evidence_kind, trigger_evidence_ref_id, retry_of_task_id,
chat_input_task_id, fire_at,
- id
+ channel_context_revision, id
)
SELECT
p.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,
@@ -610,6 +610,7 @@ SELECT
p.originator_source, p.delegated_from_task_id, p.rule_version_id,
p.trigger_evidence_kind, p.trigger_evidence_ref_id, p.id,
p.chat_input_task_id, sqlc.narg(fire_at),
+ p.channel_context_revision,
-- Named new_task_id, not id: $1 above is the PARENT task's id.
COALESCE(sqlc.narg('new_task_id')::uuid, gen_random_uuid())
FROM agent_task_queue p
@@ -1126,7 +1127,11 @@ LIMIT 1;
-- session because the rollout was missing. When true the next chat claim resumed
-- an older session (or none), so it must disclose the continuity gap.
SELECT COALESCE(session_rollout_missing, FALSE) FROM agent_task_queue
-WHERE chat_session_id = $1
+WHERE chat_session_id = sqlc.arg('chat_session_id')
+ AND (
+ sqlc.narg('channel_context_revision')::bigint IS NULL
+ OR COALESCE(channel_context_revision, 1) = sqlc.narg('channel_context_revision')::bigint
+ )
AND status IN ('completed', 'failed')
AND started_at IS NOT NULL
ORDER BY COALESCE(completed_at, started_at, dispatched_at, created_at) DESC
diff --git a/server/pkg/db/queries/channel.sql b/server/pkg/db/queries/channel.sql
index 2e9da7293b..f85a827106 100644
--- a/server/pkg/db/queries/channel.sql
+++ b/server/pkg/db/queries/channel.sql
@@ -218,6 +218,17 @@ cleared_chat_sessions AS (
WHERE installation_id IN (SELECT id FROM dead)
RETURNING chat_session_id
),
+cleared_chat_contexts AS (
+ -- A revoked installation can still own preserved Chat history and an
+ -- in-flight task snapshot. Remove only generations whose Chat was already
+ -- cascade-deleted by an earlier orphan teardown.
+ DELETE FROM channel_chat_context_generation AS generation
+ WHERE generation.chat_session_id IN (SELECT chat_session_id FROM cleared_chat_sessions)
+ AND NOT EXISTS (
+ SELECT 1 FROM chat_session AS session
+ WHERE session.id = generation.chat_session_id
+ )
+),
cleared_outbound_cards AS (
-- channel_outbound_card_message is keyed by chat_session_id (no installation_id,
-- no FK), so it is reached through the just-removed chat-session bindings. On an
@@ -259,11 +270,17 @@ SELECT id FROM dead;
-- Scoped to kind = 'system' since MUL-5559: a user agent now survives its
-- runtime's deletion as an unbound agent, so tearing down its installations
-- here would take a working bot away from an agent that is still there.
-WITH doomed AS (
+WITH system_agents AS (
+ SELECT system_agent.id FROM agent AS system_agent
+ WHERE system_agent.runtime_id = sqlc.arg('runtime_id') AND system_agent.kind = 'system'
+),
+doomed_sessions AS (
+ SELECT id FROM chat_session
+ WHERE agent_id IN (SELECT id FROM system_agents)
+),
+doomed AS (
SELECT id FROM channel_installation
- WHERE agent_id IN (
- SELECT id FROM agent WHERE runtime_id = sqlc.arg('runtime_id') AND kind = 'system'
- )
+ WHERE agent_id IN (SELECT id FROM system_agents)
),
cleared_dingtalk_group_presence AS (
DELETE FROM dingtalk_group_presence WHERE installation_id IN (SELECT id FROM doomed)
@@ -278,6 +295,11 @@ cleared_chat_sessions AS (
DELETE FROM channel_chat_session_binding WHERE installation_id IN (SELECT id FROM doomed)
RETURNING chat_session_id
),
+cleared_chat_contexts AS (
+ DELETE FROM channel_chat_context_generation
+ WHERE chat_session_id IN (SELECT chat_session_id FROM cleared_chat_sessions)
+ OR chat_session_id IN (SELECT id FROM doomed_sessions)
+),
cleared_outbound_cards AS (
-- Reach channel_outbound_card_message (keyed by chat_session_id, no FK)
-- through the just-removed chat-session bindings, same as the reclaim path.
@@ -502,12 +524,18 @@ WHERE installation_id = $1;
-- is its own session. config carries any platform-specific outbound routing the
-- key alone does not (e.g. Slack's real channel_id when the key is composite);
-- it is opaque to the shared session service.
+WITH binding AS (
INSERT INTO channel_chat_session_binding (
chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, config
) VALUES (
$1, $2, $3, $4, $5, $6
)
-RETURNING *;
+RETURNING *
+), generation AS (
+ INSERT INTO channel_chat_context_generation (chat_session_id, revision)
+ SELECT chat_session_id, context_revision FROM binding
+)
+SELECT * FROM binding;
-- name: GetChannelChatSessionBinding :one
-- Lookup-by-channel-chat: the inbound dispatcher finds the existing
@@ -559,16 +587,111 @@ SELECT pending_fresh FROM channel_chat_session_binding
WHERE chat_session_id = $1
FOR UPDATE;
+-- name: LockChannelChatSessionBindingForContext :one
+-- Context mutations acquire this row after chat_session and before any
+-- channel_chat_context_generation row. Keeping the statements separate makes
+-- the lock order explicit and identical for append, /new, and task enqueue.
+SELECT * FROM channel_chat_session_binding
+WHERE chat_session_id = $1
+FOR UPDATE;
+
-- name: ClearChannelChatSessionPendingFresh :exec
UPDATE channel_chat_session_binding
SET pending_fresh = FALSE
WHERE chat_session_id = $1;
+-- name: ClearChannelChatSessionPendingFreshForRevision :exec
+UPDATE channel_chat_session_binding
+SET pending_fresh = FALSE
+WHERE chat_session_id = @chat_session_id
+ AND context_revision = @revision;
+
+-- name: EnsureChannelChatContextGeneration :exec
+-- Rolling-deploy repair: an older server can create a binding after the schema
+-- migration but before every process is upgraded. Materialize its generation
+-- lazily before a new server attempts to lock it.
+INSERT INTO channel_chat_context_generation (
+ chat_session_id, revision
+)
+SELECT binding.chat_session_id, binding.context_revision
+FROM channel_chat_session_binding AS binding
+WHERE binding.chat_session_id = $1
+ON CONFLICT (chat_session_id, revision) DO NOTHING;
+
+-- name: AdvanceChannelChatContextGeneration :one
+-- Opens a new agent-visible context while retaining the same Multica Chat.
+-- The triggering platform message is the exclusive end of the old generation
+-- and, when it has a body, the inclusive start of the new one.
+WITH closed AS (
+ UPDATE channel_chat_context_generation AS generation
+ SET history_end_message_id = sqlc.narg('history_boundary_message_id')
+ WHERE generation.chat_session_id = @chat_session_id
+ AND generation.revision = @current_revision
+), advanced AS (
+ UPDATE channel_chat_session_binding AS binding
+ SET context_revision = binding.context_revision + 1,
+ pending_fresh = TRUE
+ WHERE binding.chat_session_id = @chat_session_id
+ AND binding.context_revision = @current_revision
+ RETURNING binding.*
+), opened AS (
+ INSERT INTO channel_chat_context_generation (
+ chat_session_id, revision, history_start_message_id,
+ history_boundary_pending, pending_fresh
+ )
+ SELECT chat_session_id, context_revision,
+ CASE WHEN @has_message_body::boolean THEN sqlc.narg('history_boundary_message_id') END,
+ NOT @has_message_body::boolean,
+ TRUE
+ FROM advanced
+ RETURNING *
+)
+SELECT * FROM opened;
+
+-- name: LockChannelChatContextGenerationByRevision :one
+SELECT * FROM channel_chat_context_generation
+WHERE chat_session_id = @chat_session_id
+ AND revision = @revision
+FOR UPDATE;
+
+-- name: ResolveChannelChatContextHistoryStart :exec
+UPDATE channel_chat_context_generation
+SET history_start_message_id = @history_start_message_id,
+ history_boundary_pending = FALSE
+WHERE chat_session_id = @chat_session_id
+ AND revision = @revision
+ AND history_boundary_pending;
+
+-- name: SetChannelChatContextInitiator :one
+-- Snapshots the latest authenticated sender whose durable input belongs to a
+-- generation. Crash recovery must use this identity rather than the sender of
+-- a later generation that happened to re-arm the lost debounce timer.
+UPDATE channel_chat_context_generation
+SET initiator_user_id = @initiator_user_id
+WHERE chat_session_id = @chat_session_id
+ AND revision = @revision
+RETURNING initiator_user_id;
+
+-- name: ClearChannelChatContextPendingFresh :exec
+UPDATE channel_chat_context_generation
+SET pending_fresh = FALSE
+WHERE chat_session_id = @chat_session_id
+ AND revision = @revision;
+
+-- name: GetChannelChatContextGeneration :one
+SELECT * FROM channel_chat_context_generation
+WHERE chat_session_id = @chat_session_id
+ AND revision = @revision;
+
-- name: DeleteChannelChatSessionBindingBySession :exec
-- Application-layer integrity (replaces the old chat_session-FK ON DELETE
-- CASCADE): drop the binding when its chat_session is deleted.
-DELETE FROM channel_chat_session_binding
-WHERE chat_session_id = $1;
+WITH deleted_binding AS (
+ DELETE FROM channel_chat_session_binding AS binding
+ WHERE binding.chat_session_id = sqlc.arg('chat_session_id')
+)
+DELETE FROM channel_chat_context_generation AS generation
+WHERE generation.chat_session_id = sqlc.arg('chat_session_id');
-- name: DeleteChannelChatSessionBindingsByInstallation :exec
-- Retire every chat-session binding for an installation. Used when an
@@ -577,9 +700,12 @@ WHERE chat_session_id = $1;
-- so reusing it would keep routing the conversation to the OLD agent. Dropping
-- the bindings forces the next inbound message to create a fresh session under
-- the new agent. The chat_session rows are preserved for history; only the
--- channel binding is removed.
-DELETE FROM channel_chat_session_binding
-WHERE installation_id = $1 AND channel_type = $2;
+-- channel binding is removed. Context generations belong to the preserved Chat,
+-- not to the retired binding: in-flight task history snapshots may still read
+-- them after this statement commits.
+DELETE FROM channel_chat_session_binding AS binding
+WHERE binding.installation_id = sqlc.arg('installation_id')
+ AND binding.channel_type = sqlc.arg('channel_type');
-- =====================
-- channel_inbound_message_dedup
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index 8870c8c589..231d0b6fa6 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -332,6 +332,14 @@ SELECT id FROM chat_session
WHERE id = $1
FOR UPDATE;
+-- name: LockChatSessionForAppend :one
+-- The append transaction's first lock. FOR KEY SHARE remains compatible with
+-- task enqueue's FOR NO KEY UPDATE while establishing chat_session -> binding
+-- -> generation order before the later TouchChatSession update.
+SELECT id FROM chat_session
+WHERE id = $1
+FOR KEY SHARE;
+
-- name: LockChatSessionForRuntimeBind :one
-- Acquires an exclusive (FOR UPDATE) row lock on chat_session(id), serialising
-- "which runtime does this session execute on" against "enqueue the next task".
@@ -440,7 +448,8 @@ WHERE id = $1;
-- 'no_response' to mark a visible turn with no text output (MUL-4351).
INSERT INTO chat_message (
chat_session_id, role, content, task_id, failure_reason, elapsed_ms,
- message_kind, quick_actions, channel_media_pending_until, channel_ingested, id
+ message_kind, quick_actions, channel_media_pending_until, channel_ingested,
+ channel_context_revision, id
)
VALUES (
$1, $2, $3, sqlc.narg(task_id), sqlc.narg(failure_reason), sqlc.narg(elapsed_ms),
@@ -455,6 +464,7 @@ VALUES (
CASE WHEN sqlc.narg(channel_media_pending_secs)::float8 IS NULL THEN NULL
ELSE now() + make_interval(secs => sqlc.narg(channel_media_pending_secs)::float8) END,
COALESCE(sqlc.narg(channel_ingested)::boolean, FALSE),
+ sqlc.narg(channel_context_revision),
COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
)
RETURNING *;
@@ -476,6 +486,40 @@ SELECT EXISTS (
AND channel_ingested
) AS channel_ingested;
+-- name: SetChatMessageChannelOutboundProvenanceByTask :execrows
+-- The assistant row is committed before EventChatDone is published. Attach the
+-- external identifiers produced by the adapter to that durable turn so a live
+-- provider-history reader can apply the same context-generation boundary as
+-- the stored transcript. A send that succeeds but cannot record provenance is
+-- deliberately treated as unknown (and therefore excluded from generation >1).
+UPDATE chat_message
+SET channel_outbound_type = @channel_type,
+ channel_outbound_installation_id = @installation_id,
+ channel_outbound_chat_id = @channel_chat_id,
+ channel_outbound_message_ids = @message_ids::text[]
+WHERE task_id = @task_id
+ AND role = 'assistant';
+
+-- name: ListChannelOutboundMessageIDsForContext :many
+-- Assistant generation is inherited from its owning task, matching
+-- ListChatMessagesPageForChannelContext. Provider IDs are scoped by session,
+-- adapter, and immutable generation before being trusted as agent context.
+SELECT external.message_id::text
+FROM chat_message AS message
+JOIN agent_task_queue AS owner ON owner.id = message.task_id
+CROSS JOIN LATERAL unnest(message.channel_outbound_message_ids) AS external(message_id)
+WHERE message.chat_session_id = @chat_session_id
+ AND message.role = 'assistant'
+ AND message.channel_outbound_type = @channel_type
+ AND message.channel_outbound_installation_id = @installation_id
+ AND message.channel_outbound_chat_id = @channel_chat_id
+ AND message.channel_outbound_message_ids IS NOT NULL
+ AND external.message_id = ANY(@candidate_message_ids::text[])
+ AND (
+ owner.channel_context_revision = @channel_context_revision
+ OR (@channel_context_revision = 1 AND owner.channel_context_revision IS NULL)
+ );
+
-- name: GetChannelMediaPendingUntil :one
-- The latest unexpired media deadline gates a channel task. Using a durable
-- task fire_at means a process restart still produces the placeholder fallback.
@@ -488,6 +532,14 @@ FROM chat_message
WHERE chat_session_id = $1
AND role = 'user'
AND message_kind != 'channel_command'
+ AND (
+ sqlc.narg('channel_context_revision')::bigint IS NULL
+ OR channel_context_revision = sqlc.narg('channel_context_revision')::bigint
+ OR (
+ sqlc.narg('channel_context_revision')::bigint = 1
+ AND channel_context_revision IS NULL
+ )
+ )
AND channel_media_pending_until > now()
ORDER BY channel_media_pending_until DESC
LIMIT 1;
@@ -540,10 +592,20 @@ WHERE id = $1 AND role = 'user';
-- pre-ownership rows of a legacy session are never swept into a new batch.
UPDATE chat_message AS message
SET task_id = @task_id
+FROM agent_task_queue AS task
WHERE message.chat_session_id = @chat_session_id
+ AND task.id = @task_id
AND message.role = 'user'
AND message.task_id IS NULL
AND message.message_kind != 'channel_command'
+ AND (
+ task.channel_context_revision IS NULL
+ OR message.channel_context_revision = task.channel_context_revision
+ OR (
+ task.channel_context_revision = 1
+ AND message.channel_context_revision IS NULL
+ )
+ )
AND NOT EXISTS (
SELECT 1
FROM chat_message AS prior
@@ -557,6 +619,26 @@ WHERE message.chat_session_id = @chat_session_id
AND (prior_batch.id IS NULL OR prior_batch.created_at > message.created_at)
);
+-- name: ListUnownedChannelChatContextRevisions :many
+-- Returns every durable context generation that still has channel input without
+-- a task owner. A process crash drops in-memory debounce timers; the next normal
+-- inbound message uses this list to re-arm older generations instead of only
+-- recovering the current one. Legacy NULL revisions are generation 1.
+WITH pending AS (
+ SELECT DISTINCT COALESCE(channel_context_revision, 1)::bigint AS context_revision
+ FROM chat_message
+ WHERE chat_session_id = $1
+ AND role = 'user'
+ AND task_id IS NULL
+ AND message_kind != 'channel_command'
+)
+SELECT pending.context_revision, generation.initiator_user_id
+FROM pending
+LEFT JOIN channel_chat_context_generation AS generation
+ ON generation.chat_session_id = $1
+ AND generation.revision = pending.context_revision
+ORDER BY pending.context_revision;
+
-- name: DeferChatTaskForSealedPendingMedia :one
-- Closes the enqueue-vs-append race: under READ COMMITTED a media message can
-- commit between GetChannelMediaPendingUntil and the batch seal above, landing
@@ -729,6 +811,40 @@ SELECT * FROM chat_message
WHERE task_id = $1 AND role = 'user'
ORDER BY created_at ASC, id ASC;
+-- name: ListChatMessagesPageForChannelContext :many
+-- Agent-only transcript projection. UI readers continue using the unfiltered
+-- ListChatMessagesPage query, while a channel task can see only the context
+-- generation snapshotted on that task. Assistant rows inherit their generation
+-- from their owning task, so retries and late completions stay in their turn.
+SELECT message.*
+FROM chat_message AS message
+LEFT JOIN agent_task_queue AS owner ON owner.id = message.task_id
+WHERE message.chat_session_id = @chat_session_id
+ AND message.message_kind != 'channel_command'
+ AND (
+ (
+ message.role = 'user'
+ AND (
+ message.channel_context_revision = @channel_context_revision
+ OR (@channel_context_revision = 1 AND message.channel_context_revision IS NULL)
+ )
+ )
+ OR
+ (
+ message.role != 'user'
+ AND (
+ owner.channel_context_revision = @channel_context_revision
+ OR (@channel_context_revision = 1 AND owner.channel_context_revision IS NULL)
+ )
+ )
+ )
+ AND (
+ sqlc.narg('before_created_at')::timestamptz IS NULL
+ OR (message.created_at, message.id) < (sqlc.narg('before_created_at')::timestamptz, sqlc.narg('before_id')::uuid)
+ )
+ORDER BY message.created_at DESC, message.id DESC
+LIMIT @page_limit;
+
-- name: ReanchorClaimedDirectChatInput :exec
-- An idle direct send is visible while it is the positional queue head. A
-- older/pre-deploy follow-up whose enqueue timestamp puts it before a newer
@@ -917,7 +1033,7 @@ INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, chat_session_id,
initiator_user_id, originator_user_id, accountable_user_id, force_fresh_session, runtime_mcp_overlay,
runtime_connected_apps, originator_source, trigger_evidence_kind, trigger_evidence_ref_id,
- fire_at, id
+ fire_at, channel_context_revision, id
)
SELECT
$1, $2, NULL,
@@ -932,6 +1048,7 @@ SELECT
sqlc.narg(trigger_evidence_kind),
sqlc.narg(trigger_evidence_ref_id),
sqlc.narg('fire_at')::timestamptz,
+ sqlc.narg('channel_context_revision')::bigint,
COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
WHERE lock_task_owner_rows($1, NULL, $2)
RETURNING *;
@@ -953,9 +1070,8 @@ WHERE task.chat_session_id = @chat_session_id
AND NOT EXISTS (
SELECT 1
FROM chat_message AS message
- WHERE message.chat_session_id = @chat_session_id
+ WHERE message.task_id = task.id
AND message.role = 'user'
- AND message.message_kind != 'channel_command'
AND message.channel_media_pending_until > now()
)
RETURNING task.*;
@@ -978,7 +1094,8 @@ RETURNING *;
-- session_id. Includes completed, failed AND cancelled tasks: each of them may
-- have established a real agent session, and we'd rather resume there than
-- start over and lose conversation memory. Used as a fallback when
--- chat_session.session_id is NULL. Resume-unsafe failures are excluded because
+-- chat_session.session_id is NULL, and as the authoritative generation-scoped
+-- source for channel tasks. Resume-unsafe failures are excluded because
-- replaying those sessions deterministically reproduces the same terminal
-- state. Keep this list in sync with resumeUnsafeFailureReason and
-- GetLastTaskSession.
@@ -1016,7 +1133,11 @@ RETURNING *;
WITH retired_sessions AS (
SELECT DISTINCT r.retired_session_id AS session_id
FROM agent_task_queue r
- WHERE r.chat_session_id = $1
+ WHERE r.chat_session_id = sqlc.arg('chat_session_id')
+ AND (
+ sqlc.narg('channel_context_revision')::bigint IS NULL
+ OR COALESCE(r.channel_context_revision, 1) = sqlc.narg('channel_context_revision')::bigint
+ )
AND r.retired_session_id IS NOT NULL
), resume_overflow_at AS (
-- completed_at alone, where the issue-side twin coalesces four columns:
@@ -1025,7 +1146,11 @@ WITH retired_sessions AS (
-- compared against. Change both halves together if that ever moves.
SELECT MAX(t.completed_at) AS at
FROM agent_task_queue t
- WHERE t.chat_session_id = $1
+ WHERE t.chat_session_id = sqlc.arg('chat_session_id')
+ AND (
+ sqlc.narg('channel_context_revision')::bigint IS NULL
+ OR COALESCE(t.channel_context_revision, 1) = sqlc.narg('channel_context_revision')::bigint
+ )
AND t.status = 'failed'
AND (
COALESCE(t.failure_reason, '') = 'codex_resume_oversized'
@@ -1035,7 +1160,11 @@ WITH retired_sessions AS (
SELECT DISTINCT ON (t.session_id)
t.session_id, t.work_dir, t.runtime_id, t.status, t.failure_reason, t.error, t.completed_at
FROM agent_task_queue t
- WHERE t.chat_session_id = $1
+ WHERE t.chat_session_id = sqlc.arg('chat_session_id')
+ AND (
+ sqlc.narg('channel_context_revision')::bigint IS NULL
+ OR COALESCE(t.channel_context_revision, 1) = sqlc.narg('channel_context_revision')::bigint
+ )
AND t.session_id IS NOT NULL
AND t.status IN ('completed', 'failed', 'cancelled')
ORDER BY t.session_id, t.completed_at DESC
@@ -1064,9 +1193,10 @@ WHERE session_id NOT IN (SELECT session_id FROM retired_sessions)
)
-- MUL-5722, mirroring GetLastTaskSession: an overflowed resume records no
-- session, so exclude by time instead of by matching the failed row. Note
- -- this only guards the FALLBACK — the claim handler reads
- -- chat_session.session_id first, so a pointer still naming the oversized
- -- thread has to be cleared at fail time (see FailTask) to be covered.
+ -- this only guards the FALLBACK for legacy tasks — the claim handler reads
+ -- chat_session.session_id first for them, so a pointer still naming the
+ -- oversized thread has to be cleared at fail time (see FailTask) to be
+ -- covered. Context-scoped channel tasks resolve directly from this query.
AND (
(SELECT at FROM resume_overflow_at) IS NULL
OR completed_at > (SELECT at FROM resume_overflow_at)
diff --git a/server/pkg/db/queries/workspace.sql b/server/pkg/db/queries/workspace.sql
index de09ad197b..bbbac3b491 100644
--- a/server/pkg/db/queries/workspace.sql
+++ b/server/pkg/db/queries/workspace.sql
@@ -99,6 +99,9 @@ SELECT id FROM workspace WHERE id = $1 FOR KEY SHARE;
WITH ws_installations AS (
SELECT id FROM channel_installation WHERE workspace_id = $1
),
+ws_sessions AS (
+ SELECT id FROM chat_session WHERE workspace_id = $1
+),
ws_agents AS (
SELECT id FROM agent WHERE workspace_id = $1
),
@@ -115,6 +118,11 @@ cleared_chat_sessions AS (
DELETE FROM channel_chat_session_binding WHERE installation_id IN (SELECT id FROM ws_installations)
RETURNING chat_session_id
),
+cleared_chat_contexts AS (
+ DELETE FROM channel_chat_context_generation
+ WHERE chat_session_id IN (SELECT chat_session_id FROM cleared_chat_sessions)
+ OR chat_session_id IN (SELECT id FROM ws_sessions)
+),
cleared_outbound_cards AS (
-- channel_outbound_card_message is keyed by chat_session_id (no FK); its own
-- chat_session rows cascade away with the workspace, so reach the cards through
diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sql
index be3aa931a5..42006eacb8 100644
--- a/server/pkg/db/queries/workspace_delete.sql
+++ b/server/pkg/db/queries/workspace_delete.sql
@@ -427,6 +427,10 @@ deleted_github_check_suites AS (
deleted_pending_github_suites AS (
DELETE FROM github_pending_check_suite WHERE workspace_id = $1
),
+deleted_channel_chat_contexts AS (
+ DELETE FROM channel_chat_context_generation
+ WHERE chat_session_id IN (SELECT id FROM ws_sessions)
+),
deleted_vcs_commit_statuses AS (
DELETE FROM vcs_commit_status
WHERE connection_id IN (SELECT id FROM ws_vcs_connections)