mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 20:09:33 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - People talk to agents in agent chats. Each message starts a native run, a "turn", for the chat's agent > - When a turn ends with a committed reply but no posted comment, committed-reply recovery posts that reply later > - Recovery treats an unposted turn as the current turn when the task holds no execution run. A later turn holds that run only while it runs > - So when a later turn fails at setup, or finishes, an earlier turn's reply qualifies again. Recovery then posts it as a new message, days late > - This pull request makes recovery skip a turn when a later turn of the same agent on the task has started > - The benefit is that a person never sees an old reply as a new message ## Linked Issues or Issue Description No public issue exists. Bug description: **What happened?** On a hosted instance, old agent replies appeared in agent chats as new comments, 2 to 8 days after their runs ended. In each case, a new run of the same agent on the same task had just started or failed at setup. Each posted comment had the old run as `createdByRunId`, and its `presentationDecision` had `commentAction: create` and the reason code `committed_task_response_recovered`. Some of the old replies had been shown before by another run. Others had never been shown. Cause: `recoverCommittedNativeChatResponseInScope` in `native-run-finalizer.ts` and the pending-presentation query in `native-response-presentation-query.ts` accept an unposted conversation turn as current when `issues.executionRunId` is null or the run itself. A later turn releases `executionRunId` when it fails at setup or finishes. After that, every earlier unposted turn of the same conversation generation passes the check again. **Expected behavior** Recovery posts a turn's reply only while that turn is still the latest started turn of the conversation. An earlier turn's reply is never posted after a later turn started. **Steps to reproduce** 1. Commit a native conversation turn with a final reply and no posted comment. 2. Insert a later run of the same agent for the same task. Give it status `failed` (setup failure), `running`, or `succeeded`. 3. Set the task's `executionRunId` to null. 4. Call `recoverCommittedNativeChatResponse`. Before this change, it returns `true` and posts the earlier reply. **Paperclip version or commit** Reproduced in tests on `master` at `cec8c2b3f4`. Related: #18465 and #20204 added committed-reply recovery. This PR keeps their behavior for the current turn. ## What Changed - `native-run-finalizer.ts`: new `laterConversationTurnStarted`. Committed-reply recovery treats a conversation turn as current only when no later run of the same agent on the task has started. Three later runs do not count: a `queued` wake that has not started, a discarded queued message (`cancelled` with no `startedAt`), and a context compaction run (it keeps the same session). One shared condition, `laterConversationTurn`, is used by recovery and by the pending-presentation query. The query compares the stored `createdAt` values in SQL, because a JavaScript `Date` drops microseconds. - `native-response-presentation-query.ts`: the pending-presentation candidates query has the same `NOT EXISTS` condition. It uses the existing `heartbeat_runs_company_ctx_issue_created_idx` index. - `agent-chat-response-recovery.test.ts`: new tests for a later turn that failed at setup, is running, or finished, with `yielded`, `done`, and held (pending approval) turns. New tests show that the reply still posts when the only later run is a queued wake, a discarded queued message, or a context compaction run. ## Verification - Red before the fix, green after: `never posts an earlier turn's reply after a later turn of the conversation started (...)` in `server/src/services/native-runtime/agent-chat-response-recovery.test.ts`. - Without the source change: 5 failed, 65 passed (70). - With the source change: 70 passed (70). - Red before the review fix, green after: `still posts the reply when the only later run is a discarded queued message` and `... is a context compaction run`. On the first commit: 2 failed. Now: the file has 72 passed (72). - `pnpm verify` returned exit 2 (an opaque setup dependency), so CI supplies broad coverage. - Focused related suites (`committed-chat-response-authority`, `idle-native-finalization`, `chat-monitor-continuation`, `presentation-ownership-read`, `native-blocked-reply-recovery`, `native-response-publication-retry`, `paperclip-control-plane-port`, `native-workspace-queued-wake-recovery`, `native-run-finalizer-telemetry`): 340 passed (10 files, with the recovery test file). After that run, a type-only change moved the shared alias; the recovery test file passed again on the final revision (72 passed). - `pnpm --filter @paperclipai/server typecheck`: passed on the first commit. On the final revision, the local run was stopped by the shared memory limit of this machine. CI typecheck covers the final revision. - Not run locally: `chat-channels.integration.test.ts` (did not finish in 25 minutes on this machine). CI runs it. - Not run: a live chat on a hosted instance. ## Risks - Low risk. The change only removes cases where recovery posts a reply. The current turn still recovers its reply. - A turn whose reply did not post before a later turn started now never posts that reply by recovery. The later turn answers the conversation instead. - No migration and no API change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in a Claude Code agent session. ## 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: lucktastic <13757243+lucktastic@users.noreply.github.com> Co-authored-by: Paperclip <noreply@paperclip.ing> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com>
139 lines
11 KiB
TypeScript
139 lines
11 KiB
TypeScript
import { alias, QueryBuilder } from "drizzle-orm/pg-core";
|
|
import { nativeEffectiveRunTerminalStateSql } from "./native-accepted-outcome.js";
|
|
import { and, asc, eq, exists, gt, inArray, isNotNull, isNull, ne, notExists, or, sql, type SQL } from "drizzle-orm";
|
|
import { chatActions, heartbeatRunEvents, heartbeatRuns, issues, nativeRunFinalizations, nativeRunResults, statusDecisions, statusDecisionEffects } from "@paperclipai/db";
|
|
import type { NativeResponsePresentationScope } from "../native-response-presentation-notifications.js";
|
|
|
|
const laterDecisions = alias(statusDecisions, "later_status_decisions");
|
|
export const laterTurns = alias(heartbeatRuns, "later_conversation_turns");
|
|
|
|
/** A later run of the turn's agent on the task that started a new turn. A
|
|
* queued wake, a discarded queued message, and context compaction do not. */
|
|
export function laterConversationTurn(issueId: SQL | string) {
|
|
return and(
|
|
eq(laterTurns.companyId, heartbeatRuns.companyId),
|
|
sql`${laterTurns.contextSnapshot}->>'issueId' = ${issueId}`,
|
|
gt(laterTurns.createdAt, heartbeatRuns.createdAt),
|
|
eq(laterTurns.agentId, heartbeatRuns.agentId), ne(laterTurns.status, "queued"),
|
|
or(ne(laterTurns.status, "cancelled"), isNotNull(laterTurns.startedAt)),
|
|
sql`not coalesce(jsonb_typeof(${laterTurns.contextSnapshot}->'contextCompactionRequestId') = 'string'
|
|
and ${laterTurns.contextSnapshot}->>'contextCompactionRequestId' ~ '[^[:space:]]', false)`,
|
|
);
|
|
}
|
|
|
|
export function nativeResponsePresentationCandidates(scope?: NativeResponsePresentationScope, after?: string, runId?: string) {
|
|
const db = new QueryBuilder();
|
|
return db.select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId,
|
|
issueId: nativeRunFinalizations.issueId, agentId: heartbeatRuns.agentId, nextAttemptAt: nativeRunFinalizations.nextAttemptAt,
|
|
endpointId: chatActions.endpointId, principalId: chatActions.principalId,
|
|
// Durable publication retry schedule for an ordinary final task reply.
|
|
publicationNextAttemptAt: sql<string | null>`${heartbeatRuns.resultJson} #>> '{responsePublication,nextAttemptAt}'`.as("publication_next_attempt_at"),
|
|
// Agent Chat conversations keep their completion outbox as the bounded owner.
|
|
taskReply: sql<boolean>`coalesce(${nativeRunResults.resultJson} #>> '{result,reportedWorkDisposition}' in ('done', 'needs_review', 'blocked')
|
|
and (coalesce(${issues.conversationAgentId}::text, '') = '' or coalesce(${issues.conversationUserId}, '') = ''), false)`.as("task_reply"),
|
|
}).from(nativeRunFinalizations)
|
|
.innerJoin(heartbeatRuns, and(eq(heartbeatRuns.id, nativeRunFinalizations.runId),
|
|
eq(heartbeatRuns.companyId, nativeRunFinalizations.companyId), eq(heartbeatRuns.nativeIssueId, nativeRunFinalizations.issueId)))
|
|
.leftJoin(chatActions, and(eq(chatActions.id, heartbeatRuns.wakeupRequestId),
|
|
eq(chatActions.companyId, heartbeatRuns.companyId)))
|
|
.innerJoin(issues, and(eq(issues.id, nativeRunFinalizations.issueId), eq(issues.companyId, nativeRunFinalizations.companyId)))
|
|
.innerJoin(nativeRunResults, and(eq(nativeRunResults.id, nativeRunFinalizations.resultId),
|
|
eq(nativeRunResults.companyId, nativeRunFinalizations.companyId), eq(nativeRunResults.issueId, nativeRunFinalizations.issueId),
|
|
eq(nativeRunResults.runId, heartbeatRuns.id), eq(nativeRunResults.completionContractId, heartbeatRuns.completionContractId)))
|
|
.innerJoin(statusDecisions, and(eq(statusDecisions.id, nativeRunFinalizations.decisionId),
|
|
eq(statusDecisions.companyId, nativeRunFinalizations.companyId), eq(statusDecisions.issueId, nativeRunFinalizations.issueId),
|
|
eq(statusDecisions.runId, heartbeatRuns.id), eq(statusDecisions.assessmentId, nativeRunFinalizations.assessmentId)))
|
|
.where(and(
|
|
eq(heartbeatRuns.runtimeMode, "native"), inArray(heartbeatRuns.status, ["succeeded", "failed", "timed_out"]),
|
|
isNotNull(heartbeatRuns.finishedAt), eq(nativeRunFinalizations.phase, "committed"), isNull(nativeRunFinalizations.leaseOwner),
|
|
eq(nativeRunResults.schemaStatus, "accepted"),
|
|
sql`jsonb_typeof(${heartbeatRuns.resultJson} #> '{presentationDecision,commentId}') is distinct from 'string'`,
|
|
sql`coalesce(${heartbeatRuns.resultJson} #> '{presentationDecision,commentAction}', '"create"'::jsonb) = '"create"'::jsonb`,
|
|
// A reply whose bounded publication retries are exhausted stays visible
|
|
// as a named failure instead of being retried forever.
|
|
sql`${heartbeatRuns.resultJson} #>> '{responsePublication,state}' is distinct from 'failed'`,
|
|
sql`${heartbeatRuns.contextSnapshot}->'skipIssueComment' is distinct from 'true'::jsonb`,
|
|
sql`coalesce(${statusDecisions.decisionJson}->'externalChatReviewPresentation', 'null'::jsonb) in ('null'::jsonb, 'false'::jsonb, '0'::jsonb, '""'::jsonb)`,
|
|
sql`${nativeRunResults.resultJson} #>> '{result,schema}' = 'paperclip.run_result.v1'`,
|
|
sql`${nativeEffectiveRunTerminalStateSql(nativeRunResults.resultJson)} = 'succeeded'`,
|
|
sql`${nativeEffectiveRunTerminalStateSql(nativeRunResults.resultJson, "turnTerminalState")} = 'completed'`,
|
|
or(
|
|
and(eq(heartbeatRuns.status, "succeeded"),
|
|
or(sql`(coalesce(${issues.conversationAgentId}::text, '') = '' or coalesce(${issues.conversationUserId}, '') = '')`,
|
|
// An unsettled conversation turn. A held turn keeps the status its
|
|
// gate committed; recovery applies the live path's answered rule.
|
|
and(or(ne(statusDecisions.reasonCode, "conversation_turn_finished"), eq(issues.status, "in_progress")),
|
|
eq(issues.conversationAgentId, heartbeatRuns.agentId), eq(issues.conversationUserId, heartbeatRuns.responsibleUserId),
|
|
eq(issues.conversationState, "active"),
|
|
or(isNull(issues.executionRunId), eq(issues.executionRunId, heartbeatRuns.id)),
|
|
sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${issues.id}::text`,
|
|
sql`jsonb_typeof(${heartbeatRuns.contextSnapshot}->'conversationSessionGeneration') = 'number'`,
|
|
sql`${heartbeatRuns.contextSnapshot}->>'conversationSessionGeneration' = ${issues.conversationSessionGeneration}::text`,
|
|
// A later turn that started replaced this one, even after it
|
|
// released the execution run (for example, it failed at setup).
|
|
notExists(db.select({ id: laterTurns.id }).from(laterTurns)
|
|
.where(laterConversationTurn(sql`${issues.id}::text`))),
|
|
exists(db.select({ id: heartbeatRunEvents.id }).from(heartbeatRunEvents).where(and(
|
|
eq(heartbeatRunEvents.companyId, heartbeatRuns.companyId), eq(heartbeatRunEvents.runId, heartbeatRuns.id),
|
|
eq(heartbeatRunEvents.agentId, heartbeatRuns.agentId), eq(heartbeatRunEvents.eventType, "item.completed"),
|
|
sql`${heartbeatRunEvents.payload} #>> '{prpEvent,runId}' = ${heartbeatRuns.id}::text`,
|
|
sql`${heartbeatRunEvents.payload} #>> '{prpEvent,normalizedSessionId}' = ${heartbeatRuns.nativeSessionId}::text`,
|
|
sql`${heartbeatRunEvents.payload} #>> '{prpEvent,turnId}' = ${nativeRunResults.turnId}`,
|
|
sql`${heartbeatRunEvents.payload} #>> '{prpEvent,payload,kind}' = 'agentMessage'`,
|
|
sql`${heartbeatRunEvents.payload} #>> '{prpEvent,payload,channel}' = 'final'`,
|
|
sql`${heartbeatRunEvents.payload} #>> '{prpEvent,payload,text}' ~ '[^[:space:]]'`,
|
|
))))),
|
|
or(
|
|
and(sql`${nativeRunResults.resultJson} #>> '{result,reportedWorkDisposition}' = 'done'`,
|
|
sql`${nativeRunResults.resultJson} #>> '{terminal,reportedWorkDisposition}' = 'done'`),
|
|
and(sql`(coalesce(${issues.conversationAgentId}::text, '') = '' or coalesce(${issues.conversationUserId}, '') = '')`,
|
|
sql`${nativeRunResults.resultJson} #>> '{result,reportedWorkDisposition}' = 'needs_review'`,
|
|
sql`${nativeRunResults.resultJson} #>> '{terminal,reportedWorkDisposition}' = 'needs_review'`),
|
|
and(sql`(coalesce(${issues.conversationAgentId}::text, '') = '' or coalesce(${issues.conversationUserId}, '') = '')`,
|
|
sql`${nativeRunResults.resultJson} #>> '{result,reportedWorkDisposition}' = 'blocked'`,
|
|
sql`${nativeRunResults.resultJson} #>> '{terminal,reportedWorkDisposition}' = 'blocked'`,
|
|
eq(issues.status, "blocked"),
|
|
notExists(db.select({ id: laterDecisions.id }).from(laterDecisions).where(and(
|
|
eq(laterDecisions.companyId, statusDecisions.companyId), eq(laterDecisions.issueId, statusDecisions.issueId),
|
|
eq(laterDecisions.applicationState, "applied"),
|
|
gt(laterDecisions.decisionVersion, statusDecisions.decisionVersion))))),
|
|
and(sql`(coalesce(${issues.conversationAgentId}::text, '') <> '' and coalesce(${issues.conversationUserId}, '') <> '')`,
|
|
sql`${nativeRunResults.resultJson} #>> '{result,reportedWorkDisposition}' = 'yielded'`,
|
|
sql`${nativeRunResults.resultJson} #>> '{terminal,reportedWorkDisposition}' = 'yielded'`),
|
|
)),
|
|
and(sql`${nativeRunResults.resultJson} #>> '{result,reportedWorkDisposition}' = 'yielded'`,
|
|
sql`${nativeRunResults.resultJson} #>> '{terminal,reportedWorkDisposition}' = 'yielded'`,
|
|
sql`jsonb_typeof(${nativeRunResults.resultJson} #> '{result,summary}') = 'string'
|
|
and ${nativeRunResults.resultJson} #>> '{result,summary}' ~ '[^[:space:]]'`,
|
|
sql`jsonb_typeof(${nativeRunResults.resultJson} #> '{result,continuation,idempotencyKey}') = 'string'
|
|
and ${nativeRunResults.resultJson} #>> '{result,continuation,idempotencyKey}' ~ '[^[:space:]]'`,
|
|
or(
|
|
and(sql`${nativeRunResults.resultJson} #>> '{result,continuation,kind}' = 'response_wake'`,
|
|
sql`${nativeRunResults.resultJson} #> '{result,attentionRequests}' = '[]'::jsonb`,
|
|
sql`jsonb_typeof(${nativeRunResults.resultJson} #> '{result,continuation,summary}') = 'string'
|
|
and ${nativeRunResults.resultJson} #>> '{result,continuation,summary}' ~ '[^[:space:]]'`),
|
|
and(eq(heartbeatRuns.status, "succeeded"), or(
|
|
and(sql`${nativeRunResults.resultJson} #>> '{result,continuation,kind}' = 'same_agent'`,
|
|
eq(statusDecisions.reasonCode, "live_continuation_registered")),
|
|
and(sql`${nativeRunResults.resultJson} #>> '{result,continuation,kind}' = 'monitor'`,
|
|
inArray(statusDecisions.reasonCode, ["scheduled_monitor_waiting", "scheduled_monitor_dispatched", "scheduled_monitor_preserved"])),
|
|
)),
|
|
)),
|
|
),
|
|
notExists(db.select({ id: statusDecisionEffects.id }).from(statusDecisionEffects).where(and(
|
|
eq(statusDecisionEffects.companyId, nativeRunFinalizations.companyId),
|
|
eq(statusDecisionEffects.issueId, nativeRunFinalizations.issueId),
|
|
eq(statusDecisionEffects.decisionId, nativeRunFinalizations.decisionId),
|
|
inArray(statusDecisionEffects.deliveryState, ["pending", "failed"]),
|
|
))),
|
|
scope ? and(eq(heartbeatRuns.companyId, scope.companyId), scope.issueId ? eq(nativeRunFinalizations.issueId, scope.issueId) : undefined) : undefined,
|
|
scope?.runId ? eq(heartbeatRuns.id, scope.runId) : undefined,
|
|
scope?.agentId ? eq(heartbeatRuns.agentId, scope.agentId) : undefined,
|
|
after ? gt(heartbeatRuns.id, after) : undefined, runId ? eq(heartbeatRuns.id, runId) : undefined,
|
|
)).orderBy(asc(heartbeatRuns.id)).limit(100);
|
|
}
|
|
|
|
export function nativeResponsePresentationPendingQuery() {
|
|
return nativeResponsePresentationCandidates();
|
|
}
|