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.