Skip to content

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

Go

MUL-8218: fix(daemon): flag edited trigger comments on resumed runs (#9526)

Multica Eve4fa40c502eec
diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.go
index 403fece180..ae7ae4a019 100644
--- a/server/internal/daemon/prompt.go
+++ b/server/internal/daemon/prompt.go
@@ -452,6 +452,9 @@ func buildCommentPrompt(task Task, provider string) string {
var b strings.Builder
b.WriteString("You are running as a local coding agent for a Multica workspace.\n\n")
fmt.Fprintf(&b, "Your assigned issue ID is: %s\n\n", task.IssueID)
+ // A real resume: the latest turn's session comes back. Shared by the
+ // edited-comment notes (MUL-8218) and the reading pointers below.
+ resumed := task.PriorSessionID != "" && !task.PriorSessionResumeUnavailable
if task.TriggerCommentContent != "" {
authorLabel := "A user"
if task.TriggerAuthorType == "system" {
@@ -463,8 +466,20 @@ func buildCommentPrompt(task Task, provider string) string {
}
authorLabel = fmt.Sprintf("Another agent (%s)", name)
}
- fmt.Fprintf(&b, "[NEW COMMENT] %s just left a new comment. Focus on THIS comment — do not confuse it with previous ones:\n\n", authorLabel)
+ // MUL-8218: an edited trigger on a resumed session. The edit cancelled
+ // the run that read the old text and retriggered from the new one, but
+ // that run's transcript is what this session resumes. Say which version
+ // is current; the work already done is not undone by the edit.
+ editedSinceResume := resumed && task.TriggerCommentEditedAt != ""
+ if editedSinceResume {
+ fmt.Fprintf(&b, "[EDITED COMMENT] %s edited a comment after your previous run in this session started. Focus on THIS comment — do not confuse it with previous ones:\n\n", authorLabel)
+ } else {
+ fmt.Fprintf(&b, "[NEW COMMENT] %s just left a new comment. Focus on THIS comment — do not confuse it with previous ones:\n\n", authorLabel)
+ }
fmt.Fprintf(&b, "> %s\n\n", task.TriggerCommentContent)
+ if editedSinceResume {
+ b.WriteString(buildEditedTriggerNote(task))
+ }
// MUL-4195: comments that arrived before this run started were folded
// into it rather than dropped. The trigger above is the newest; the
// agent must ALSO address these earlier ones so no deliberate user
@@ -474,6 +489,7 @@ func buildCommentPrompt(task Task, provider string) string {
// a thread-agnostic issue-wide fetch hint for old servers that only send
// the ids.
if len(task.CoalescedComments) > 0 {
+ editedCoalesced := 0
fmt.Fprintf(&b, "This run also covers %d earlier comment(s) posted before it started — you must read and address them too, not just the one above. They may be in different threads, so each is reproduced here with its own thread:\n\n", len(task.CoalescedComments))
for _, cc := range task.CoalescedComments {
authorLabel := "A user"
@@ -497,9 +513,20 @@ func buildCommentPrompt(task Task, provider string) string {
if cc.ThreadID != "" {
fmt.Fprintf(&b, " [thread %s]", cc.ThreadID)
}
+ if resumed && cc.EditedAt != "" {
+ editedCoalesced++
+ fmt.Fprintf(&b, " [EDITED at %s", cc.EditedAt)
+ if cc.Revision > 0 {
+ fmt.Fprintf(&b, ", revision %d", cc.Revision)
+ }
+ b.WriteString(" — current version]")
+ }
b.WriteString(":\n")
fmt.Fprintf(&b, " > %s\n", strings.ReplaceAll(strings.TrimSpace(cc.Content), "\n", "\n > "))
}
+ if editedCoalesced > 0 {
+ fmt.Fprintf(&b, "\n%d comment(s) above marked EDITED changed after your previous run in this session started. Your session history may still contain earlier versions of them. %s\n", editedCoalesced, editedCommentGuidance)
+ }
fmt.Fprintf(&b, "\nIf you need the surrounding discussion for any of them, fetch its thread with `multica issue comment list %s --thread <thread-id> --tail 30 --compact --output json` using the thread id shown above.\n\n", task.IssueID)
} else if len(task.CoalescedCommentIDs) > 0 {
// MUL-5442: this fallback used to send the agent at `--recent 30`.
@@ -543,7 +570,6 @@ func buildCommentPrompt(task Task, provider string) string {
// session is warm enough to skip the issue read while treating it as cold
// for comments. On anything but a real resume with a server-computed
// comparison this renders the unconditional read, byte for byte.
- resumed := task.PriorSessionID != "" && !task.PriorSessionResumeUnavailable
b.WriteString(execenv.BuildIssueStateHint(
task.IssueID, task.IssueStatus, task.IssueAssigneeType, task.IssueAssigneeID,
task.IssueChangedFields, task.IssueStateDeltaKnown, resumed,
@@ -919,3 +945,26 @@ func taskIsSquadLeader(task Task) bool {
}
return task.IsLeaderTask || task.SquadID != ""
}
+
+// buildEditedTriggerNote explains an edited trigger comment to a resumed
+// session (MUL-8218). The session's history may quote the comment's earlier
+// text; only the version quoted in this prompt is an instruction. The note
+// deliberately does not call the previous run void: files it changed,
+// commands it ran and comments it posted still happened.
+func buildEditedTriggerNote(task Task) string {
+ var b strings.Builder
+ b.WriteString("This comment")
+ if task.TriggerCommentID != "" {
+ fmt.Fprintf(&b, " (%s", task.TriggerCommentID)
+ if task.TriggerCommentRevision > 0 {
+ fmt.Fprintf(&b, ", revision %d", task.TriggerCommentRevision)
+ }
+ b.WriteString(")")
+ }
+ fmt.Fprintf(&b, " was edited at %s. Your session history may still contain an earlier version of it. %s\n\n", task.TriggerCommentEditedAt, editedCommentGuidance)
+ return b.String()
+}
+
+// editedCommentGuidance is the shared instruction for any edited comment a
+// resumed session receives, trigger or folded-in (MUL-8218).
+const editedCommentGuidance = "The text quoted in this prompt is the current version and the only one to act on; treat any earlier wording, and plans that depended on it, as withdrawn. Work already done in this session (file changes, commands, posted comments) still happened and was not rolled back — re-evaluate what remains against the current text instead of repeating it or assuming it was undone."
diff --git a/server/internal/daemon/prompt_edited_trigger_test.go b/server/internal/daemon/prompt_edited_trigger_test.go
new file mode 100644
index 0000000000..5aed45379a
--- /dev/null
+++ b/server/internal/daemon/prompt_edited_trigger_test.go
@@ -0,0 +1,104 @@
+package daemon
+
+import (
+ "strings"
+ "testing"
+)
+
+// MUL-8218 / GH #9492: a resumed session may quote the pre-edit text of the
+// trigger comment. The prompt must say which version is current without
+// claiming the earlier run's work was undone.
+func TestBuildCommentPromptEditedTrigger(t *testing.T) {
+ base := Task{
+ IssueID: "issue-1",
+ TriggerCommentID: "comment-1",
+ TriggerCommentContent: "Now it connects over TLS",
+ PriorSessionID: "session-1",
+ TriggerCommentEditedAt: "2026-10-26T02:20:00Z",
+ TriggerCommentRevision: 3,
+ }
+
+ t.Run("edited on a resumed session", func(t *testing.T) {
+ out := buildCommentPrompt(base, "claude")
+ for _, want := range []string{
+ "[EDITED COMMENT] A user edited a comment after your previous run in this session started.",
+ "> Now it connects over TLS",
+ "This comment (comment-1, revision 3) was edited at 2026-10-26T02:20:00Z.",
+ "The text quoted in this prompt is the current version and the only one to act on",
+ "still happened and was not rolled back",
+ } {
+ if !strings.Contains(out, want) {
+ t.Errorf("prompt missing %q:\n%s", want, out)
+ }
+ }
+ if strings.Contains(out, "[NEW COMMENT]") {
+ t.Error("edited trigger must not be announced as a new comment")
+ }
+ })
+
+ t.Run("not edited", func(t *testing.T) {
+ task := base
+ task.TriggerCommentEditedAt = ""
+ task.TriggerCommentRevision = 0
+ out := buildCommentPrompt(task, "claude")
+ if !strings.Contains(out, "[NEW COMMENT] A user just left a new comment.") {
+ t.Errorf("unedited trigger must keep the new-comment header:\n%s", out)
+ }
+ if strings.Contains(out, "[EDITED COMMENT]") || strings.Contains(out, "was edited at") {
+ t.Error("unedited trigger must not carry the edit note")
+ }
+ })
+
+ // Without a resumed session there is no earlier version in history to
+ // warn about; the daemon clears PriorSessionID when it drops the session.
+ for name, mutate := range map[string]func(*Task){
+ "cold start": func(t *Task) { t.PriorSessionID = "" },
+ "resume unavailable": func(t *Task) { t.PriorSessionResumeUnavailable = true },
+ } {
+ t.Run(name, func(t *testing.T) {
+ task := base
+ mutate(&task)
+ out := buildCommentPrompt(task, "claude")
+ if strings.Contains(out, "[EDITED COMMENT]") || strings.Contains(out, "was edited at") {
+ t.Errorf("%s: edit note must only render on a resumed session:\n%s", name, out)
+ }
+ })
+ }
+}
+
+// An edited comment folded behind a newer, unchanged trigger must still be
+// marked as the current version (review of PR #9526).
+func TestBuildCommentPromptEditedCoalescedComment(t *testing.T) {
+ base := Task{
+ IssueID: "issue-1",
+ TriggerCommentID: "comment-2",
+ TriggerCommentContent: "Please continue",
+ PriorSessionID: "session-1",
+ CoalescedComments: []CoalescedCommentData{
+ {ID: "comment-1", ThreadID: "thread-1", Content: "edited instruction Y", EditedAt: "2026-10-26T02:20:00Z", Revision: 2},
+ {ID: "comment-0", ThreadID: "thread-1", Content: "unchanged instruction"},
+ },
+ }
+
+ out := buildCommentPrompt(base, "claude")
+ for _, want := range []string{
+ "[NEW COMMENT] A user just left a new comment.",
+ "- comment comment-1 (A user) [thread thread-1] [EDITED at 2026-10-26T02:20:00Z, revision 2 — current version]:",
+ "- comment comment-0 (A user) [thread thread-1]:",
+ "1 comment(s) above marked EDITED changed after your previous run in this session started.",
+ "still happened and was not rolled back",
+ } {
+ if !strings.Contains(out, want) {
+ t.Errorf("prompt missing %q:\n%s", want, out)
+ }
+ }
+ if strings.Contains(out, "[EDITED COMMENT]") {
+ t.Error("an unchanged trigger must keep the new-comment header")
+ }
+
+ cold := base
+ cold.PriorSessionID = ""
+ if out := buildCommentPrompt(cold, "claude"); strings.Contains(out, "EDITED") {
+ t.Errorf("cold start must not mark edits:\n%s", out)
+ }
+}
diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.go
index 09b671642b..511d72cdfb 100644
--- a/server/internal/daemon/types.go
+++ b/server/internal/daemon/types.go
@@ -126,6 +126,8 @@ type Task struct {
TriggerCommentContent string `json:"trigger_comment_content,omitempty"` // content of the triggering comment
TriggerAuthorType string `json:"trigger_author_type,omitempty"` // "agent" or "member" — author kind for the triggering comment
TriggerAuthorName string `json:"trigger_author_name,omitempty"` // display name of the triggering comment author
+ TriggerCommentEditedAt string `json:"trigger_comment_edited_at,omitempty"` // MUL-8218: set when the trigger comment was edited after the resumed session's run started, so the resumed history may quote an earlier version. Empty on old servers / unedited comments
+ TriggerCommentRevision int64 `json:"trigger_comment_revision,omitempty"` // MUL-8218: current revision of the trigger comment; sent alongside TriggerCommentEditedAt
NewCommentCount int `json:"new_comment_count,omitempty"` // issue-wide comments since this agent's last run (excludes its own and the injected trigger); 0/omitted for old daemons or cold start
NewCommentsSince string `json:"new_comments_since,omitempty"` // RFC3339 anchor (last run's started_at) the count is measured from; empty on cold start
NewCommentsDeltaKnown bool `json:"new_comments_delta_known,omitempty"` // the server actually computed the issue-wide delta this claim (both reads succeeded). A zero NewCommentCount means "nothing was said" only when this is true; otherwise the zero is a failed read, a cold start, or an old server, and the prompt must not present it as the comment scan's answer (MUL-6984)
@@ -210,6 +212,8 @@ type CoalescedCommentData struct {
AuthorName string `json:"author_name,omitempty"`
Content string `json:"content"`
CreatedAt string `json:"created_at,omitempty"`
+ EditedAt string `json:"edited_at,omitempty"` // MUL-8218: set when this comment was edited after the resumed session's run started; empty on old servers / unedited comments
+ Revision int64 `json:"revision,omitempty"` // MUL-8218: current revision, sent alongside EditedAt
}
// AgentData holds agent details returned by the claim endpoint.
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 3a604fd4a4..c04d20f892 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -482,6 +482,13 @@ type AgentTaskResponse struct {
TriggerAuthorName string `json:"trigger_author_name,omitempty"` // display name of the triggering comment author
NewCommentCount int `json:"new_comment_count,omitempty"` // ISSUE-WIDE comments since this agent's last run — every thread, not just the triggering one (CountNewCommentsSince); excludes the injected trigger and the agent's own comments; omitempty so old daemons ignore it
NewCommentsSince string `json:"new_comments_since,omitempty"` // RFC3339 anchor (last run's started_at) the count is measured from; omitempty so old daemons ignore it. Suppressed with the count when the delta is zero — NewCommentsDeltaKnown, not this field, is what says the server looked
+ // MUL-8218: set only when the trigger comment was edited AFTER the run
+ // whose session this claim resumes had started, so that session's history
+ // may still hold an earlier version of the text. EditedAt is RFC3339;
+ // Revision is the comment's current revision. omitempty so old daemons
+ // ignore both.
+ TriggerCommentEditedAt string `json:"trigger_comment_edited_at,omitempty"`
+ TriggerCommentRevision int64 `json:"trigger_comment_revision,omitempty"`
// NewCommentsDeltaKnown reports that the issue-wide delta above was
// actually COMPUTED this claim — both the anchor lookup and the count
// query succeeded. Without it, NewCommentCount == 0 is ambiguous: a true
@@ -744,6 +751,15 @@ type CoalescedCommentData struct {
AuthorName string `json:"author_name,omitempty"`
Content string `json:"content"`
CreatedAt string `json:"created_at,omitempty"`
+ // MUL-8218: set when this comment was edited after the run whose session
+ // this claim resumes had started (see triggerCommentEditedSince). omitempty
+ // so old daemons ignore both.
+ EditedAt string `json:"edited_at,omitempty"`
+ Revision int64 `json:"revision,omitempty"`
+
+ // source is the row this entry was read from, kept so the claim can run
+ // the edit check once the resumed session is known. Never serialized.
+ source db.Comment
}
// TaskUsageData is one (provider, model) slice of a single run's token usage.
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 5f6d2685b2..0205518964 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -3114,6 +3114,11 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
// claim actually hands back — see resumeAnchor there.
var commentDeltaScope *commentCountScope
var resumeAnchor *resumedRunAnchor
+ // started_at of the run whose session this claim resumes, whatever its
+ // status. Unlike resumeAnchor it is set for failed/cancelled sources
+ // too: a cancelled run's transcript is exactly where an edited comment's
+ // earlier text survives (MUL-8218).
+ var resumedRunStartedAt pgtype.Timestamptz
// Squad-leader briefing injection: keyed off the task being a
// leader-task (is_leader_task) carrying a squad_id — NOT off the
@@ -3280,6 +3285,9 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
// was triggered by a human or by another agent — a signal used by the
// harness instructions to avoid mention loops between agents.
effectiveTriggerUUID := task.TriggerCommentID
+ // The loaded trigger row, kept for the edit check that runs once the
+ // resumed session is known (MUL-8218).
+ var loadedTrigger *db.Comment
if effectiveTriggerUUID.Valid {
// Scope by the runtime's workspace so a task row carrying a foreign
// comment UUID can never pull another workspace's comment text into
@@ -3290,6 +3298,7 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
ID: effectiveTriggerUUID,
WorkspaceID: runtime.WorkspaceID,
}); err == nil && !comment.DeletedAt.Valid {
+ loadedTrigger = &comment
resp.TriggerCommentContent = comment.Content
resp.TriggerThreadID = uuidToString(comment.ID)
if comment.ParentID.Valid {
@@ -3402,6 +3411,7 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
if !service.ResumeUnsafeFailure(src.FailureReason.String, src.Error.String) &&
src.SessionID.Valid && src.RuntimeID == task.RuntimeID && !sourceSessionRetired {
resp.PriorSessionID = src.SessionID.String
+ resumedRunStartedAt = src.StartedAt
// The deltas date from the run we actually resume, which on
// this path is the operator-chosen source — routinely NOT
// the newest run on the issue. nil unless that run proved it
@@ -3437,6 +3447,7 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
}); err == nil && prior.SessionID.Valid {
if prior.RuntimeID == task.RuntimeID {
resp.PriorSessionID = prior.SessionID.String
+ resumedRunStartedAt = prior.StartedAt
// Same rule as the rerun path: date the deltas from the run
// this session belongs to. GetLastTaskSession skips poisoned
// and retired sessions, so `prior` can be an older run than
@@ -3468,6 +3479,26 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
applyFreshSessionRetryWorkdir(*task, &resp, requestHasClientCapability(r, protocol.DaemonCapabilityCheckoutKeepsWorkV1))
}
+ // MUL-8218: a comment edit cancels the affected run and retriggers from
+ // the edited comment, but the new run resumes that run's session, whose
+ // history still quotes the pre-edit text. Tell the agent which version
+ // is current so it does not keep reasoning from the withdrawn one.
+ // Every comment this run delivers is checked, not only the trigger: an
+ // edited comment can be folded behind a newer, unchanged one.
+ if resp.PriorSessionID != "" {
+ if loadedTrigger != nil && triggerCommentEditedSince(*loadedTrigger, resumedRunStartedAt) {
+ resp.TriggerCommentEditedAt = loadedTrigger.UpdatedAt.Time.UTC().Format(time.RFC3339)
+ resp.TriggerCommentRevision = loadedTrigger.Revision
+ }
+ for i := range resp.CoalescedComments {
+ src := resp.CoalescedComments[i].source
+ if triggerCommentEditedSince(src, resumedRunStartedAt) {
+ resp.CoalescedComments[i].EditedAt = src.UpdatedAt.Time.UTC().Format(time.RFC3339)
+ resp.CoalescedComments[i].Revision = src.Revision
+ }
+ }
+ }
+
// Both deltas, now that the resume source is known (MUL-7344).
//
// resumeAnchor is non-nil only where a session was actually ADOPTED
@@ -5116,6 +5147,7 @@ func (h *Handler) buildCoalescedCommentData(ctx context.Context, workspaceID pgt
AuthorType: comment.AuthorType,
Content: comment.Content,
CreatedAt: timestampToString(comment.CreatedAt),
+ source: comment,
}
if comment.ParentID.Valid {
root, err := h.Queries.GetCommentThreadRootID(ctx, comment.ID)
diff --git a/server/internal/handler/daemon_claim_edited_trigger_test.go b/server/internal/handler/daemon_claim_edited_trigger_test.go
new file mode 100644
index 0000000000..1a3ee9489a
--- /dev/null
+++ b/server/internal/handler/daemon_claim_edited_trigger_test.go
@@ -0,0 +1,316 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// MUL-8218 / GH #9492: the user writes X, the agent starts, the user edits the
+// comment to Y. The edit cancels that run and retriggers from Y, but the new
+// run resumes the cancelled run's session — whose history still quotes X. The
+// claim must tell the daemon the trigger was edited after that run started.
+
+func TestTriggerCommentEditedSince(t *testing.T) {
+ start := time.Date(2026, 10, 26, 10, 0, 0, 0, time.UTC)
+ ts := func(d time.Duration) pgtype.Timestamptz {
+ return pgtype.Timestamptz{Time: start.Add(d), Valid: true}
+ }
+ runStarted := ts(0)
+
+ cases := []struct {
+ name string
+ comment db.Comment
+ started pgtype.Timestamptz
+ want bool
+ }{
+ {
+ name: "edited after the run started",
+ comment: db.Comment{CreatedAt: ts(-time.Minute), UpdatedAt: ts(time.Minute), Revision: 2},
+ started: runStarted,
+ want: true,
+ },
+ {
+ name: "never edited",
+ comment: db.Comment{CreatedAt: ts(-time.Minute), UpdatedAt: ts(-time.Minute), Revision: 1},
+ started: runStarted,
+ },
+ {
+ name: "edited before the run started: the run already read the new text",
+ comment: db.Comment{CreatedAt: ts(-2 * time.Minute), UpdatedAt: ts(-time.Minute), Revision: 2},
+ started: runStarted,
+ },
+ {
+ name: "created after the run started: the session never saw any version",
+ comment: db.Comment{CreatedAt: ts(time.Minute), UpdatedAt: ts(2 * time.Minute), Revision: 2},
+ started: runStarted,
+ },
+ {
+ name: "only change is a single resolve",
+ comment: db.Comment{
+ CreatedAt: ts(-time.Minute), UpdatedAt: ts(time.Minute), Revision: 2,
+ ResolvedAt: ts(time.Minute),
+ },
+ started: runStarted,
+ },
+ {
+ name: "edit then resolve: the resolve must not hide the edit",
+ comment: db.Comment{
+ CreatedAt: ts(-time.Minute), UpdatedAt: ts(2 * time.Minute), Revision: 3,
+ ResolvedAt: ts(2 * time.Minute),
+ },
+ started: runStarted,
+ want: true,
+ },
+ {
+ name: "edited after an earlier resolve",
+ comment: db.Comment{
+ CreatedAt: ts(-time.Minute), UpdatedAt: ts(2 * time.Minute), Revision: 3,
+ ResolvedAt: ts(time.Minute),
+ },
+ started: runStarted,
+ want: true,
+ },
+ {
+ name: "resumed run never started",
+ comment: db.Comment{CreatedAt: ts(-time.Minute), UpdatedAt: ts(time.Minute), Revision: 2},
+ started: pgtype.Timestamptz{},
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := triggerCommentEditedSince(tc.comment, tc.started); got != tc.want {
+ t.Fatalf("triggerCommentEditedSince = %v, want %v", got, tc.want)
+ }
+ })
+ }
+}
+
+type claimEditedTriggerResp struct {
+ Task *struct {
+ PriorSessionID string `json:"prior_session_id"`
+ TriggerCommentID string `json:"trigger_comment_id"`
+ TriggerCommentContent string `json:"trigger_comment_content"`
+ TriggerCommentEditedAt string `json:"trigger_comment_edited_at"`
+ TriggerCommentRevision int64 `json:"trigger_comment_revision"`
+ } `json:"task"`
+}
+
+func claimEditedTriggerTask(t *testing.T, runtimeID string) claimEditedTriggerResp {
+ t.Helper()
+ req := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
+ req = withURLParam(req, "runtimeId", runtimeID)
+ w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
+ var resp claimEditedTriggerResp
+ w.JSON(&resp)
+ if resp.Task == nil {
+ t.Fatalf("expected a claimed task, got nil: %s", w.Body.String())
+ }
+ return resp
+}
+
+// TestClaimTask_FlagsTriggerEditedAfterResumedCancelledRun is the reported
+// scenario: the resumed session belongs to the CANCELLED run that read X.
+func TestClaimTask_FlagsTriggerEditedAfterResumedCancelledRun(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ runtimeID := createClaimReclaimRuntime(t, ctx, "Edited trigger runtime")
+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Edited trigger agent")
+
+ commentID := dbfx.Comment(t, issueID, "Now it connect", testutil.Cols{
+ "created_at": testutil.Raw("now() - interval '10 minutes'"),
+ "updated_at": testutil.Raw("now() - interval '10 minutes'"),
+ })
+ dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": runtimeID,
+ "issue_id": issueID,
+ "trigger_comment_id": commentID,
+ "status": "cancelled",
+ "session_id": "edited-trigger-cancelled-session",
+ "started_at": testutil.Raw("now() - interval '9 minutes'"),
+ "completed_at": testutil.Raw("now() - interval '5 minutes'"),
+ })
+ // The edit: new body, revision bump, updated_at after the run started.
+ dbfx.Exec(t, `UPDATE comment SET content = 'Now it connects over TLS', revision = revision + 1, updated_at = now() - interval '5 minutes' WHERE id = $1`, commentID)
+ dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": runtimeID,
+ "issue_id": issueID,
+ "trigger_comment_id": commentID,
+ })
+
+ resp := claimEditedTriggerTask(t, runtimeID)
+ if resp.Task.PriorSessionID != "edited-trigger-cancelled-session" {
+ t.Fatalf("PriorSessionID = %q, want the cancelled run's session", resp.Task.PriorSessionID)
+ }
+ if resp.Task.TriggerCommentContent != "Now it connects over TLS" {
+ t.Fatalf("TriggerCommentContent = %q, want the edited body", resp.Task.TriggerCommentContent)
+ }
+ if resp.Task.TriggerCommentEditedAt == "" {
+ t.Fatal("TriggerCommentEditedAt is empty, want the edit time: the resumed history quotes the old text")
+ }
+ if resp.Task.TriggerCommentRevision != 2 {
+ t.Fatalf("TriggerCommentRevision = %d, want 2", resp.Task.TriggerCommentRevision)
+ }
+}
+
+// TestClaimTask_NoEditFlagWhenTriggerUnchangedSinceResumedRun guards the
+// common follow-up: nothing was edited, so nothing is flagged.
+func TestClaimTask_NoEditFlagWhenTriggerUnchangedSinceResumedRun(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ runtimeID := createClaimReclaimRuntime(t, ctx, "Unedited trigger runtime")
+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Unedited trigger agent")
+
+ dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": runtimeID,
+ "issue_id": issueID,
+ "status": "completed",
+ "session_id": "unedited-trigger-session",
+ "started_at": testutil.Raw("now() - interval '1 hour'"),
+ "completed_at": testutil.Raw("now() - interval '50 minutes'"),
+ })
+ createCommentTriggeredClaimTask(t, ctx, agentID, runtimeID, issueID, nil)
+
+ resp := claimEditedTriggerTask(t, runtimeID)
+ if resp.Task.PriorSessionID != "unedited-trigger-session" {
+ t.Fatalf("PriorSessionID = %q, want unedited-trigger-session", resp.Task.PriorSessionID)
+ }
+ if resp.Task.TriggerCommentEditedAt != "" || resp.Task.TriggerCommentRevision != 0 {
+ t.Fatalf("edit fields = (%q, %d), want empty for a new, unedited comment",
+ resp.Task.TriggerCommentEditedAt, resp.Task.TriggerCommentRevision)
+ }
+}
+
+// TestUpdateComment_EditedTriggerReachesResumedRun drives the reported flow
+// through the real edit path, twice: claim X, run, edit to Y (the edit cancels
+// the run and retriggers), claim — then run, edit to Z, claim again. Each
+// follow-up must resume the cancelled run's session, carry the newest body,
+// and flag the edit with the matching revision.
+func TestUpdateComment_EditedTriggerReachesResumedRun(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ fixture := createCommentDeliveryFixture(t, "Edited trigger resumed run")
+ makeCommentDeliverySingleThread(t, fixture)
+ dbfx.Exec(t, `UPDATE issue SET assignee_type = 'agent', assignee_id = $2 WHERE id = $1`, fixture.issueID, fixture.agentID)
+ triggerID := fixture.commentID[2]
+
+ first := claimCommentDeliveryFixture(t, fixture, "")
+ if first.TriggerCommentEditedAt != "" {
+ t.Fatalf("first claim flagged an edit (%q) on a never-edited trigger", first.TriggerCommentEditedAt)
+ }
+
+ runningTaskID := first.ID
+ var revision int64 = 1
+ previous := "latest instruction"
+ for i, body := range []string{"edited instruction Y", "edited instruction Z"} {
+ session := "edited-trigger-session-" + string(rune('a'+i))
+ // The daemon started the run and pinned its session before the edit.
+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'running', started_at = now() - interval '30 seconds', session_id = $2 WHERE id = $1`, runningTaskID, session)
+
+ w := httptest.NewRecorder()
+ req := newRequest(http.MethodPut, "/api/comments/"+triggerID, map[string]any{"content": body})
+ req = withURLParam(req, "commentId", triggerID)
+ testHandler.UpdateComment(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("edit %d: UpdateComment got %d: %s", i, w.Code, w.Body.String())
+ }
+ revision++
+ if got := taskStatus(t, runningTaskID); got != "cancelled" {
+ t.Fatalf("edit %d: running task status = %q, want cancelled by the edit", i, got)
+ }
+
+ next := claimCommentDeliveryFixture(t, fixture, "")
+ if next.PriorSessionID != session {
+ t.Fatalf("edit %d: PriorSessionID = %q, want %q (the cancelled run's session)", i, next.PriorSessionID, session)
+ }
+ // The fixture's batch is folded into one legacy bundle here; the
+ // current body must be in it and the superseded one must not.
+ if !strings.Contains(next.TriggerCommentContent, body) || strings.Contains(next.TriggerCommentContent, previous) {
+ t.Fatalf("edit %d: TriggerCommentContent = %q, want the current body %q only", i, next.TriggerCommentContent, body)
+ }
+ if next.TriggerCommentEditedAt == "" {
+ t.Fatalf("edit %d: TriggerCommentEditedAt empty, want the edit flagged", i)
+ }
+ if next.TriggerCommentRevision != revision {
+ t.Fatalf("edit %d: TriggerCommentRevision = %d, want %d", i, next.TriggerCommentRevision, revision)
+ }
+ runningTaskID = next.ID
+ previous = body
+ }
+}
+
+// Review regressions for PR #9526 (supplied by the reviewer, adapted): a
+// resolve after the edit, and an edited comment folded behind a newer trigger.
+func TestClaimTask_EditThenResolveKeepsEditFlag(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database unavailable")
+ }
+ f := createCommentDeliveryFixture(t, "Review edit then resolve")
+ makeCommentDeliverySingleThread(t, f)
+ dbfx.Exec(t, `UPDATE issue SET assignee_type='agent', assignee_id=$2 WHERE id=$1`, f.issueID, f.agentID)
+ first := claimCommentDeliveryFixture(t, f, "")
+ dbfx.Exec(t, `UPDATE agent_task_queue SET status='running', started_at=now()-interval '30 seconds', session_id='review-edit-resolve-session' WHERE id=$1`, first.ID)
+ trigger := f.commentID[2]
+ req := withURLParam(newRequest(http.MethodPut, "/api/comments/"+trigger, map[string]any{"content": "edited instruction Y"}), "commentId", trigger)
+ testutil.Call(t, testHandler.UpdateComment, req).Want(http.StatusOK)
+ resolveCommentHTTP(t, trigger)
+ next := claimCommentDeliveryFixture(t, f, "")
+ if next.PriorSessionID != "review-edit-resolve-session" {
+ t.Fatal("unexpected resume session")
+ }
+ if next.TriggerCommentEditedAt == "" {
+ t.Fatal("edit warning lost after resolve although resumed history still holds X")
+ }
+}
+
+func TestClaimTask_FlagsEditedCoalescedComment(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database unavailable")
+ }
+ f := createCommentDeliveryFixture(t, "Review edit coalesced")
+ makeCommentDeliverySingleThread(t, f)
+ dbfx.Exec(t, `UPDATE issue SET assignee_type='agent', assignee_id=$2 WHERE id=$1`, f.issueID, f.agentID)
+ first := claimCommentDeliveryFixture(t, f, "coalesced-comments-v1")
+ dbfx.Exec(t, `UPDATE agent_task_queue SET status='running', started_at=now()-interval '30 seconds', session_id='review-edit-coalesced-session' WHERE id=$1`, first.ID)
+ editedID := f.commentID[0]
+ req := withURLParam(newRequest(http.MethodPut, "/api/comments/"+editedID, map[string]any{"content": "edited instruction Y"}), "commentId", editedID)
+ testutil.Call(t, testHandler.UpdateComment, req).Want(http.StatusOK)
+ newComment := withURLParam(newRequest(http.MethodPost, "/api/issues/"+f.issueID+"/comments", map[string]any{"content": "[@Review](mention://agent/" + f.agentID + ") Please continue with the current instructions.", "parent_id": editedID}), "id", f.issueID)
+ testutil.Call(t, testHandler.CreateComment, newComment).Want(http.StatusCreated)
+ next := claimCommentDeliveryFixture(t, f, "coalesced-comments-v1")
+ if next.PriorSessionID != "review-edit-coalesced-session" {
+ t.Fatal("unexpected resume session")
+ }
+ if next.TriggerCommentEditedAt != "" {
+ t.Fatalf("the new, unchanged trigger was flagged as edited (%q)", next.TriggerCommentEditedAt)
+ }
+ var found bool
+ for _, cc := range next.CoalescedComments {
+ if cc.ID != editedID {
+ if cc.EditedAt != "" {
+ t.Fatalf("unchanged coalesced comment %s flagged as edited", cc.ID)
+ }
+ continue
+ }
+ found = true
+ if cc.Content != "edited instruction Y" || cc.EditedAt == "" || cc.Revision != 2 {
+ t.Fatalf("edited coalesced comment = %+v, want current body, edit time and revision 2", cc)
+ }
+ }
+ if !found {
+ t.Fatalf("edited comment %s not delivered: %+v", editedID, next.CoalescedComments)
+ }
+}
diff --git a/server/internal/handler/issue_snapshot.go b/server/internal/handler/issue_snapshot.go
index 468049a51f..3566de0b09 100644
--- a/server/internal/handler/issue_snapshot.go
+++ b/server/internal/handler/issue_snapshot.go
@@ -193,3 +193,29 @@ type commentCountScope struct {
IssueID pgtype.UUID
WorkspaceID pgtype.UUID
}
+
+// triggerCommentEditedSince reports whether comment c may have been edited
+// after a resumed run started (MUL-8218), i.e. whether that run's session may
+// hold an earlier version of c's text.
+//
+// Time is the whole test: the comment must have existed before the run
+// started (otherwise the session never saw any version of it) and been
+// changed after. revision > 1 rules out a never-edited row.
+//
+// updated_at and revision also move on resolve/unresolve, and a later resolve
+// can hide an earlier body edit behind its own timestamp. The only change that
+// is provably resolve-only is a first-revision row resolved once: revision 2
+// with resolved_at == updated_at. Anything else errs toward the note, which is
+// harmless — it only says the quoted text is the current version.
+func triggerCommentEditedSince(c db.Comment, runStartedAt pgtype.Timestamptz) bool {
+ if !runStartedAt.Valid || !c.CreatedAt.Valid || !c.UpdatedAt.Valid || c.Revision <= 1 {
+ return false
+ }
+ if !c.CreatedAt.Time.Before(runStartedAt.Time) || !c.UpdatedAt.Time.After(runStartedAt.Time) {
+ return false
+ }
+ if c.Revision == 2 && c.ResolvedAt.Valid && c.ResolvedAt.Time.Equal(c.UpdatedAt.Time) {
+ return false
+ }
+ return true
+}