From de675d924a25feb8993e74c31c26cf7041901235 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:31:11 -0600 Subject: [PATCH] fix(heartbeat): stop a comment the closing run already read from reopening its finished task (#21175) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A person can add a comment to a task while the agent's run on that task is still working > - The comment must reach the agent once: in the running turn, or in one later turn > - In a restart-chaos wave, a comment that the running turn already read reopened the finished task, and the agent did the completion turn a second time 15 minutes later > - This pull request makes a read by the running turn count as delivery, and holds the comment behind the running run so the run's own release settles it > - The benefit is no reopened done task, no repeated completion turn, and an unread comment that is delivered when its run finishes, not after a slot wait and a stale cancellation ## Linked Issues or Issue Description **What happened?** Restart-chaos wave `w-20261112T181948-s7101`, task t005 (OpenCode, native Runner), during a two-server overlap deploy (K15). - 18:26:56 run A started on the old server. 18:26:55 traffic switched to the new server. - 18:27:03.953 a board user posted a follow-up comment. The new server handled it. Run A was not in that process's `activeRunExecutions`, so `filterZombieCoalesceTarget` treated it as a zombie. Admission returned `proceed`, and the comment got its own queued run B (18:27:04.252). The queued run is not part of the release drain. - 18:33:32 run A called `get_task_history`, received the comment, applied it, and finished the task (`done`, 18:34:20). - Run B waited for an agent slot until 18:41:49 and was cancelled as `continuation_task_ownership_changed`. - `deferUndeliveredCommentsOfStaleRun` then saved the comment again. Its "unread" test is only "a run started before the comment and finished after it". `deliveredQueuedCommentIds` had no record of run A's read. The release drain reopened the task (done to todo, 18:41:51), and run C (18:49:22) posted a second "Task complete" summary. The harness grade `done_comment_once` failed. **Expected behavior** - A comment that the running turn received is consumed. No queued work outlives that run, and the task stays done. - A comment that the running turn did not receive is delivered once, through the normal comment-on-done-task path, when that run finishes. - A stale continuation is never re-issued for a comment that a completed run already read. **Steps to reproduce** 1. Start a native run on a task. 2. Post a person's comment while another server instance executes the run (or seed a queued comment run behind it). 3. Let the run read `get_task_history`, then finish the task. 4. Before this change, the queued comment run is cancelled as stale, the task reopens, and the agent runs a second completion turn. **Paperclip version or commit** `master` at ef6d347f79. ## What Changed - `server/src/services/queued-comment-delivery.ts`: new run-log event `task_history.read` and `recordTaskHistoryRead`. `deliveredQueuedCommentIds` also counts a comment as delivered when a succeeded run of the assignee on that task read the comment's current revision (`historyReadDeliveredSql`). All existing consumers use this one check: the release drain liveness check, the stale-continuation save (`saveUndeliveredUserComments`), the ownership reconciler, and first-turn queued input. - `paperclip-runner-tool-authority.ts` and `runner-semantic-authority.ts`: `get_task_history` records the returned comment IDs and `updatedAt` values. The tool output does not change. A failed record is logged and leaves the comment owed, so it is delivered again. - `server/src/modules/wake-queue/application/use-cases.ts`: a comment follow-up for the same agent's `running` run is held as a deferred wake even when this process does not track that run. Before, a run executed by another server instance was treated as a zombie, and the comment got its own queued run that bypassed the release drain. Coalescing into an untracked run is still refused. - `doc/run-log-events.md`: documents `task_history.read`. - Regression tests in `server/src/__tests__/heartbeat-held-comment-wake.test.ts`. Intended behaviour chosen: in t005 run A received the comment mid-turn through its own `get_task_history` call (run events at 18:33:32 show the comment ID in the tool result, and the result says it added the follow-up line), so (a) applied. The fix makes that read the durable proof of delivery. A comment that no run read still follows the existing outbox: it is held behind the run and delivered once at the run's release, reopening the done task as a person's comment does. Envelope task history of another message's turn still does not count (unchanged doctrine and test). ## Verification - RED on master (`ef6d347f79`), `npx vitest run src/__tests__/heartbeat-held-comment-wake.test.ts -t "mid-turn|another server|held message"`: 3 failed, 1 passed. - "consumes a message the closing run read mid-turn, so its stale queued run reopens nothing": delivered 1, expected 0. - "holds a message behind a run another server is executing instead of queueing a run of its own": a queued run was created. - "settles a held message as soon as its run closes the task (read mid-turn: true)": delivered 1, expected 0. - The unread variant (delivered once, no cancelled stale run) passes on both, as intended. - GREEN with this change: all 4 pass. - Review follow-up (f43e79c3): a history read counts as delivery only for a succeeded run on the read revision. Tests cover an edit after the read (the stale queued run delivers the comment once) and reads by an edited or failed run (the comment stays owed). Full file: 37/37 pass. - Security-scan follow-up (239f0597): the delivery check probes each run binding (`native_issue_id`, `context_snapshot->>'issueId'`) through its own existing index with `offset 0`. It reads only the assignee's succeeded runs of the task with `finished_at >= ` the comment's current revision. It does not use `started_at`, because the t005 reader started before the comment. It stops at the first matching `task_history.read` event of each run through `heartbeat_run_events_company_run_idx`. No migration is needed. - Seeded plan (local PostgreSQL: 200 tasks, 4,000 runs, 1.2M run events, one comment read by one run), `EXPLAIN (ANALYZE, BUFFERS)`: - Before: 1.202 ms, 6,097 shared buffers. It scanned every event of all 21 runs of the task. - After: 0.030 ms, 23 shared buffers. It reads one index-matched run and one event. The full `deliveredQueuedCommentIds` call takes 1.55 ms. - New case: a succeeded run's read is not delivery when the comment was edited after that run finished. Full held-comment file: 38/38 pass. - `muse-control.test.ts` compared the whole run row after a `get_task_history` call. It now allows that read's own run-log append (`nextEventSeq` +1, `updatedAt`), and every other column must be unchanged. That CI failure (General tests server 2/12) came from this PR. "e2e shard (5/8)" failed because the self-hosted runner lost communication; that is not related to this PR. - Runner and Muse suites (`dot-runner`, `paperclip-control-plane-port`, `runner-prp-coordinator`, `historical-task-questions`, `paperclip-runner-tool-authority`, `muse-native-follow-up`, `muse-control`): 509/509 pass. Server `tsc` is clean. - Neighbouring suites: `heartbeat-held-comment-wake`, `src/modules/wake-queue/**`, `execution-continuation`, `paperclip-runner-tool-authority`, `first-turn-queued-input`, `heartbeat-comment-wake-batching`, `ownership-reconciliation-report`, `heartbeat-zombie-guard`: 555/556 passed in one loaded run. The 2 timeouts (one batching test, one reconciler `afterAll` hook) pass when run alone (1/1, 44/44). - `server` `tsc --noEmit`: clean. - The restart-chaos harness already grades this class (`done_comment_once` in staging-mix). No new cell is necessary. ## Risks - Product choice: a comment counts as delivered when a succeeded run read it through `get_task_history`, even if the model ignored it. This is the same trust that applies to a comment delivered as wake input. The alternative fails worse: it reopens a done task and repeats a completed turn. An edit after the read, or a reader run that fails, leaves it owed. - Legacy (non-native) adapters that read comments through the REST API do not write the record. Their behavior does not change. - A comment follow-up behind a truly dead running run now waits as a deferred wake until recovery releases that run. Before, its queued run also could not start until the lock was released. - Each `get_task_history` call appends one small run-log row. This is not in the path before `turn.start`. - Upgrade-safe: continuations queued by older builds still go through the dispatch stale check, and that path now reads the same delivery record. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edit, test execution). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- doc/run-log-events.md | 18 +++ .../heartbeat-held-comment-wake.test.ts | 134 ++++++++++++++++++ server/src/__tests__/muse-control.test.ts | 5 +- .../wake-queue/application/use-cases.ts | 3 +- .../paperclip-runner-tool-authority.ts | 8 +- .../runner-semantic-authority.ts | 8 +- .../src/services/queued-comment-delivery.ts | 32 ++++- 7 files changed, 202 insertions(+), 6 deletions(-) diff --git a/doc/run-log-events.md b/doc/run-log-events.md index 0e1f3a0f2a5..0c80422eff0 100644 --- a/doc/run-log-events.md +++ b/doc/run-log-events.md @@ -1002,6 +1002,24 @@ creates no Telemetry or OpenTelemetry export. Neither wait consumes the provider-failure retry allowance. Each stops after 30 deferrals, after which the run follows the normal failure path. +## Task history reads + +When a native run reads its task's comments through `get_task_history`, the +server writes one `task_history.read` event (`stream: "system"`, level `info`) +to that run's log. Its payload has one field, `comments`, which maps each +returned comment ID to that comment's `updatedAt` timestamp. It contains no comment bodies or +author identifiers. The event creates no Telemetry or OpenTelemetry export. + +Per-comment delivery (`deliveredQueuedCommentIds`) reads this event. A +person's comment counts as received when a run of the task's assignee succeeded +after reading the comment's current revision. The comment's queued +wake then neither reopens the finished task nor starts another turn. An edit +after the read, or a read by a run that did not succeed, leaves the comment +owed, so it is delivered once. The check reads only the assignee's succeeded +runs of that task that finished at or after the comment's current revision, +through the existing run-binding and `(company_id, run_id)` event indexes. A failure to write the event leaves the comment +owed in the same way. + ## Managed Agent File Save Receipts The server writes `instruction_save` after managed file collection or a warm diff --git a/server/src/__tests__/heartbeat-held-comment-wake.test.ts b/server/src/__tests__/heartbeat-held-comment-wake.test.ts index b80b100bb65..3affe892351 100644 --- a/server/src/__tests__/heartbeat-held-comment-wake.test.ts +++ b/server/src/__tests__/heartbeat-held-comment-wake.test.ts @@ -15,6 +15,8 @@ import { heartbeatService } from "../services/heartbeat.js"; import { createOwnershipReportState, runOwnershipReconciliationPass } from "../services/recovery/ownership-invariant-report.js"; import { applyOwnershipReportBackstops } from "../services/native-runtime/native-finalization-reconciler.js"; import { promoteDeferredWorkIntents, TEMPORARY_REFUSAL_TRIGGERS, WORK_INTENT_TERMINAL_OUTCOMES } from "../services/work-intent-outbox.js"; +import { deliveredQueuedCommentIds } from "../services/queued-comment-delivery.js"; +import { PaperclipRunnerToolAuthority } from "../services/native-runtime/paperclip-runner-tool-authority.js"; import { recoveryPostgresSupport, startRecoveryPostgres } from "./helpers/recovery-postgres.js"; const describePostgres = recoveryPostgresSupport.supported ? describe : describe.skip; @@ -32,6 +34,7 @@ describePostgres("saved intents while another run's accounting is pending", () = let heartbeat: ReturnType; const adapterType = "codex_local"; const dispatched: Array<{ runId: string; context: Record }> = []; + let duringTurn: ((runId: string) => Promise) | null = null; const oldHome = process.env.PAPERCLIP_HOME; let home: string; @@ -45,6 +48,7 @@ describePostgres("saved intents while another run's accounting is pending", () = type: adapterType, supportsLocalAgentJwt: false, execute: async input => { dispatched.push({ runId: input.runId, context: input.context as Record }); + await duringTurn?.(input.runId); // The agent finishes the task, so no disposition repair follows. await db.update(issues).set({ status: "done" }).where(eq(issues.id, String(input.context.issueId))); return { exitCode: 0, signal: null, timedOut: false, resultJson: {} }; @@ -732,6 +736,136 @@ describePostgres("saved intents while another run's accounting is pending", () = expect(deliveries(f.commentId)).toHaveLength(1); }, 180_000); + async function runningNativeSource(f: Awaited>) { + await db.update(heartbeatRuns).set({ costAccountingPending: false }).where(eq(heartbeatRuns.id, f.pendingRunId)); + await db.delete(agentWakeupRequests).where(eq(agentWakeupRequests.id, f.wakeId)); + await db.update(heartbeatRuns).set({ status: "running", runtimeMode: "native", nativeIssueId: f.issueId, finishedAt: null, + startedAt: new Date(Date.now() - 30_000) }).where(eq(heartbeatRuns.id, f.sourceRunId)); + await db.update(issues).set({ executionRunId: f.sourceRunId, executionLockedAt: new Date() }).where(eq(issues.id, f.issueId)); + } + + async function readHistoryDuringTurn(f: Awaited>) { + const reader = new PaperclipRunnerToolAuthority(db, { companyId: f.companyId, agentId: f.agentId, issueId: f.issueId, + runId: f.sourceRunId }); + try { + const history = await reader.execute({ tool: "get_task_history", callId: `history-${f.sourceRunId}`, arguments: {} }); + expect((history as { comments: Array<{ id: string }> }).comments.map(comment => comment.id)).toContain(f.commentId); + } finally { reader.close(); } + } + + async function closeSourceRun(f: Awaited>) { + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date(Date.now() + 1_000) }) + .where(eq(heartbeatRuns.id, f.sourceRunId)); + await db.update(issues).set({ status: "done", completedAt: new Date() }).where(eq(issues.id, f.issueId)); + await closeByAgent(f); + } + + const issueStatus = async (f: { issueId: string }) => + (await db.select({ status: issues.status }).from(issues).where(eq(issues.id, f.issueId)))[0]?.status; + + const postComment = (f: Awaited>) => heartbeat.wakeup(f.agentId, { + source: "automation", triggerDetail: "system", reason: "issue_commented", + payload: { issueId: f.issueId, commentId: f.commentId, mutation: "comment" }, + requestedByActorType: "user", requestedByActorId: f.userId, + contextSnapshot: { issueId: f.issueId, taskId: f.issueId, commentId: f.commentId, wakeCommentId: f.commentId, + source: "issue.comment", wakeReason: "issue_commented" }, + }); + + it.each([ + { shape: "read unchanged", edit: false, delivered: 0 }, + { shape: "edited after the read", edit: true, delivered: 1 }, + ])("settles a stale queued run of a message the closing run read mid-turn ($shape)", async ({ edit, delivered }) => { + const f = await seedHeldComment(); + await runningNativeSource(f); + const [wake] = await db.insert(agentWakeupRequests).values({ companyId: f.companyId, agentId: f.agentId, source: "automation", + triggerDetail: "system", reason: "issue_commented", status: "queued", requestedByActorType: "user", requestedByActorId: f.userId, + payload: { issueId: f.issueId, commentId: f.commentId, mutation: "comment" } }).returning(); + const [stale] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, invocationSource: "automation", + triggerDetail: "system", status: "queued", wakeupRequestId: wake!.id, + contextSnapshot: { issueId: f.issueId, taskId: f.issueId, commentId: f.commentId, wakeCommentId: f.commentId, + wakeCommentIds: [f.commentId], wakeReason: "issue_commented", source: "issue.comment" } }).returning(); + await db.update(agentWakeupRequests).set({ runId: stale!.id }).where(eq(agentWakeupRequests.id, wake!.id)); + await readHistoryDuringTurn(f); + if (edit) await db.update(issueComments).set({ body: "Edited: also include the FOLLOWUP line twice.", + updatedAt: new Date(Date.now() + 500) }).where(eq(issueComments.id, f.commentId)); + await closeSourceRun(f); + await db.update(issues).set({ executionRunId: null, executionLockedAt: null }).where(eq(issues.id, f.issueId)); + await settle(f); await settle(f); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, stale!.id)))[0]).toMatchObject({ + status: "cancelled", errorCode: "continuation_task_ownership_changed" }); + await db.update(agentWakeupRequests).set({ updatedAt: new Date(Date.now() - 60_000) }) + .where(and(eq(agentWakeupRequests.companyId, f.companyId), eq(agentWakeupRequests.status, "deferred_issue_execution"))); + await settle(f); await settle(f); + expect(deliveries(f.commentId)).toHaveLength(delivered); + await settle(f); + expect(deliveries(f.commentId)).toHaveLength(delivered); + expect(await issueStatus(f)).toBe("done"); + const report = await runOwnershipReconciliationPass(db, { state: createOwnershipReportState(), record: false }); + expect(report.violations.filter(row => row.recordId === f.commentId)).toEqual([]); + }, 180_000); + + it.each([ + { outcome: "succeeded", edit: "none", consumed: true }, + { outcome: "succeeded", edit: "during the run", consumed: false }, + { outcome: "succeeded", edit: "after the run finished", consumed: false }, + { outcome: "failed", edit: "none", consumed: false }, + ])("counts a mid-turn history read as delivery only for a run that $outcome on the current revision (edited: $edit)", async ({ outcome, edit, consumed }) => { + const f = await seedHeldComment(); + await runningNativeSource(f); + await readHistoryDuringTurn(f); + const editComment = (at: number) => db.update(issueComments).set({ body: "Edited after the read.", updatedAt: new Date(at) }) + .where(eq(issueComments.id, f.commentId)); + if (edit === "during the run") await editComment(Date.now() + 500); + await db.update(heartbeatRuns).set({ status: outcome, finishedAt: new Date(Date.now() + 1_000), + ...(outcome === "failed" ? { errorCode: "adapter_failed" } : {}) }).where(eq(heartbeatRuns.id, f.sourceRunId)); + if (edit === "after the run finished") await editComment(Date.now() + 60_000); + const delivered = await deliveredQueuedCommentIds(db, { companyId: f.companyId, issueId: f.issueId, agentId: f.agentId, + commentIds: [f.commentId] }); + expect(delivered.has(f.commentId)).toBe(consumed); + }, 180_000); + + it("holds a message behind a run another server is executing instead of queueing a run of its own", async () => { + const f = await seedHeldComment(); + await runningNativeSource(f); + await postComment(f); + const queued = (await issueRuns(f)).filter(run => run.id !== f.sourceRunId && run.status === "queued"); + expect(queued).toEqual([]); + const held = await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, f.companyId), + eq(agentWakeupRequests.status, "deferred_issue_execution"))); + expect(held.map(row => row.payload?.commentId)).toEqual([f.commentId]); + }, 180_000); + + it.each([ + { read: true, delivered: 0 }, + { read: false, delivered: 1 }, + ])("settles a held message as soon as its run closes the task (read mid-turn: $read)", async ({ read, delivered }) => { + const f = await seedHeldComment(); + await db.update(heartbeatRuns).set({ costAccountingPending: false }).where(eq(heartbeatRuns.id, f.pendingRunId)); + await db.delete(agentWakeupRequests).where(eq(agentWakeupRequests.id, f.wakeId)); + let closingRunId: string | null = null; + duringTurn = async runId => { + duringTurn = null; + closingRunId = runId; + await postComment(f); + if (!read) return; + await db.update(heartbeatRuns).set({ runtimeMode: "native", nativeIssueId: f.issueId }).where(eq(heartbeatRuns.id, runId)); + await readHistoryDuringTurn({ ...f, sourceRunId: runId }); + await db.update(heartbeatRuns).set({ runtimeMode: "legacy" }).where(eq(heartbeatRuns.id, runId)); + await closeByAgent(f); + }; + if (!read) await closeByAgent(f); + await heartbeat.wakeup(f.agentId, { source: "assignment", triggerDetail: "system", reason: "issue_assigned", + payload: { issueId: f.issueId }, contextSnapshot: { issueId: f.issueId, taskId: f.issueId, wakeReason: "issue_assigned" } }); + await heartbeat.drainActiveRunExecutions(); + await heartbeat.drainActiveRunExecutions(); + expect(closingRunId).not.toBeNull(); + expect(deliveries(f.commentId)).toHaveLength(delivered); + expect((await issueRuns(f)).filter(run => run.status === "cancelled")).toEqual([]); + await settle(f); await settle(f); + expect(deliveries(f.commentId)).toHaveLength(delivered); + expect(await issueStatus(f)).toBe("done"); + }, 180_000); + it("still refuses work at a reached hard stop, which the board owns", async () => { const f = await seedHeldComment({ hardStopReached: true }); await db.update(heartbeatRuns).set({ costAccountingPending: false }).where(eq(heartbeatRuns.id, f.pendingRunId)); diff --git a/server/src/__tests__/muse-control.test.ts b/server/src/__tests__/muse-control.test.ts index 1ba4423b844..81e2bc22dd0 100644 --- a/server/src/__tests__/muse-control.test.ts +++ b/server/src/__tests__/muse-control.test.ts @@ -425,7 +425,10 @@ describe("personal Muse control plane",()=>{ expect(read.comments.find(row=>row.id===standardId)).toMatchObject({body:"Ordinary coordination",sourceTrust:null}); expect(await db.select().from(issueComments).where(eq(issueComments.issueId,f.issue.id)).orderBy(issueComments.id)).toEqual(stored); } - expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id,f.runId)))[0]).toEqual(committed.run); + const {nextEventSeq:readEventSeq,updatedAt:_readAt,...readRun}=(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id,f.runId)))[0]!; + const {nextEventSeq:committedEventSeq,updatedAt:_committedAt,...committedRun}=committed.run; + expect(readRun).toEqual(committedRun); + expect(readEventSeq).toBe(committedEventSeq+1); expect(committed.run.contextSnapshot).toEqual(writerContext); expect(await db.select().from(externalAgentHolds).where(eq(externalAgentHolds.assignmentId,f.assignment.id))).toEqual(beforeHolds); expect((await db.select({status:assignments.status,acceptedResultAt:assignments.acceptedResultAt,finalizedAt:assignments.finalizedAt}).from(assignments).where(eq(assignments.id,f.assignment.id)))[0]).toEqual({status:"accepted",acceptedResultAt:null,finalizedAt:null}); diff --git a/server/src/modules/wake-queue/application/use-cases.ts b/server/src/modules/wake-queue/application/use-cases.ts index f8a939e13f5..7448b734e40 100644 --- a/server/src/modules/wake-queue/application/use-cases.ts +++ b/server/src/modules/wake-queue/application/use-cases.ts @@ -904,7 +904,8 @@ export function createAdmitWakeBehindIssueExecution(deps: { isSameExecutionAgent, shouldDeferFollowupWake, shouldQueueFollowupForRunningWake, - availableActiveExecutionRunPresent: availableActiveExecutionRun !== null, + availableActiveExecutionRunPresent: availableActiveExecutionRun !== null || (shouldDeferFollowupWake && + isSameExecutionAgent && input.activeExecutionRun.status === "running" && Boolean(input.wakeCommentId)), }); if (decision.kind === "proceed") return { kind: "proceed" }; diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts index af33f5154d9..96cbf77c25f 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts @@ -138,6 +138,8 @@ import { READ_CHAT_ATTACHMENT_TOOL_NAME, type NativeChatAttachmentReadScope, } from "./chat-attachment-read.js"; +import { recordTaskHistoryRead } from "../queued-comment-delivery.js"; +import { logger } from "../../middleware/logger.js"; const EXTERNAL_WORKSPACE_OPERATIONS = new Set(["get_workspace", "list_workspaces", "select_workspace", "prepare_repository", "register_deliverable"]); const IMPLEMENTED_OPERATIONS = new Set([ @@ -993,6 +995,7 @@ export class PaperclipRunnerToolAuthority { authorAgentId: issueComments.authorAgentId, authorUserId: issueComments.authorUserId, createdAt: issueComments.createdAt, + updatedAt: issueComments.updatedAt, }).from(issueComments) .where(and( eq(issueComments.companyId, this.binding.companyId), @@ -1001,7 +1004,10 @@ export class PaperclipRunnerToolAuthority { )) .orderBy(desc(issueComments.createdAt)) .limit(limit); - return { comments: comments.reverse().map(comment => { + await recordTaskHistoryRead(this.db, { companyId: this.binding.companyId, agentId: this.binding.agentId, + runId: this.binding.runId, comments }).catch(error => + logger.warn({ err: error, runId: this.binding.runId }, "could not record the task history a run read")); + return { comments: comments.reverse().map(({ updatedAt: _updatedAt, ...comment }) => { const visible = isLowTrustQuarantined(readerSourceTrust) ? comment : sanitizeQuarantinedCommentForHigherTrust(comment); return { ...visible, body: fastResponseHistoryBody(visible) }; }) }; diff --git a/server/src/services/native-runtime/runner-semantic-authority.ts b/server/src/services/native-runtime/runner-semantic-authority.ts index 0fb5f6f228a..529c1ef483b 100644 --- a/server/src/services/native-runtime/runner-semantic-authority.ts +++ b/server/src/services/native-runtime/runner-semantic-authority.ts @@ -7,6 +7,8 @@ import { sanitizeQuarantinedCommentForHigherTrust, } from "../source-trust.js"; import { and, desc, eq, isNull } from "drizzle-orm"; +import { recordTaskHistoryRead } from "../queued-comment-delivery.js"; +import { logger } from "../../middleware/logger.js"; import type { Db } from "@paperclipai/db"; import { @@ -166,6 +168,7 @@ export class PaperclipRunnerSemanticAuthority { authorAgentId: issueComments.authorAgentId, authorUserId: issueComments.authorUserId, createdAt: issueComments.createdAt, + updatedAt: issueComments.updatedAt, }) .from(issueComments) .where( @@ -182,7 +185,10 @@ export class PaperclipRunnerSemanticAuthority { issue: context.issue, actor: { actorType: "agent", actorId: context.agent.id, agentId: context.agent.id, runId: context.run.id }, }); - const comments = rows.reverse().map(row => { + await recordTaskHistoryRead(this.#db, { companyId: this.#binding.companyId, agentId: this.#binding.agentId, + runId: this.#binding.runId, comments: rows }).catch(error => + logger.warn({ err: error, runId: this.#binding.runId }, "could not record the task history a run read")); + const comments = rows.reverse().map(({ updatedAt: _updatedAt, ...row }) => { const comment = isLowTrustQuarantined(readerSourceTrust) ? row : sanitizeQuarantinedCommentForHigherTrust(row); diff --git a/server/src/services/queued-comment-delivery.ts b/server/src/services/queued-comment-delivery.ts index 9faf1b6a169..69d97ee4d41 100644 --- a/server/src/services/queued-comment-delivery.ts +++ b/server/src/services/queued-comment-delivery.ts @@ -1,5 +1,6 @@ -import { and, eq, inArray, sql } from "drizzle-orm"; +import { and, eq, inArray, sql, type SQL } from "drizzle-orm"; import { heartbeatRunEvents, heartbeatRuns, issueComments, type Db } from "@paperclipai/db"; +import { appendHeartbeatRunEvent } from "./heartbeat-run-events.js"; /** The wake reason an inbound chat message records (see chat inbound wakeups). */ export const EXTERNAL_CHAT_MESSAGE_WAKE_REASON = "External chat message received"; @@ -41,11 +42,38 @@ export async function deliveredQueuedCommentIds(tx: Pick, input: { jsonb_build_object('id', ${issueComments.id}::text)) or jsonb_path_exists(delivered_run.context_snapshot, '$.paperclipWake.messages[*] ? (@.id == $id)', jsonb_build_object('id', ${issueComments.id}::text))))) - or ${firstTurnDeliveredSql(companyId, issueId, input.agentId)})`, + or ${firstTurnDeliveredSql(companyId, issueId, input.agentId)} + or ${historyReadDeliveredSql(companyId, issueId, input.agentId)})`, )); return new Set(rows.map(row => row.id)); } +export const TASK_HISTORY_READ_EVENT = "task_history.read"; + +export async function recordTaskHistoryRead(db: Db, input: { + companyId: string; agentId: string; runId: string; comments: ReadonlyArray<{ id: string; updatedAt: Date }>; +}): Promise { + if (input.comments.length === 0) return; + await appendHeartbeatRunEvent(db, { companyId: input.companyId, runId: input.runId, agentId: input.agentId, + eventType: TASK_HISTORY_READ_EVENT, stream: "system", level: "info", + payload: { comments: Object.fromEntries(input.comments.map(comment => [comment.id, comment.updatedAt.toISOString()])) } }); +} + +function historyReadDeliveredSql(companyId: string, issueId: string, agentId: string) { + const readBy = (binding: SQL) => sql`exists (select 1 from ${heartbeatRuns} reading_run + cross join lateral (select 1 from ${heartbeatRunEvents} history_read + where history_read.company_id = ${companyId} and history_read.run_id = reading_run.id + and history_read.event_type = ${TASK_HISTORY_READ_EVENT} + and (history_read.payload->'comments'->>${issueComments.id}::text)::timestamptz + >= date_trunc('milliseconds', ${issueComments.updatedAt}) + limit 1) read_revision + where reading_run.company_id = ${companyId} and ${binding} + and reading_run.agent_id = ${agentId} and reading_run.status = 'succeeded' + and reading_run.finished_at >= date_trunc('milliseconds', ${issueComments.updatedAt}) offset 0)`; + return sql`(${readBy(sql`reading_run.native_issue_id = ${issueId}`)} + or ${readBy(sql`reading_run.context_snapshot->>'issueId' = ${issueId}`)})`; +} + /** * The comment row was taken into an accepted first provider turn of a run of * this agent on this task, and not edited after that run sealed its input.