Admit saved task comments with the fresh issue run (#22268)

## Thinking Path

> - Paperclip agents take work from assigned tasks and from user
comments.
> - A fresh task run can include saved comments when the current agent
or a confirmed former assignee owns them.
> - Connected chat messages and resolved interactions have separate
authority and session requirements.
> - Heartbeat previously decided which receipts to adopt between the
three calls that saved a new run.
> - One wake-queue use case now selects the receipts and commits the
same run and comment lineage.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

Assignment and comment continuation when a task needs a fresh run.

**Subsystem affected**

Server task admission.

**Current behavior**

Heartbeat chooses the comment receipts to consume, reads their source,
and builds the final run context.

**Proposed behavior**

One application operation admits the run. Its Postgres adapter loads
eligible company and agent receipts under the issue lock. The caller
supplies the responsible user and records the specialized continuation.

**Additional context**

Builds on #22266. The existing release and queued-comment boundaries are
in #13136 and #13145.

## What Changed

- Keep exact resumed receipts separate from ordinary board comments.
Adopt a prior assignee’s comments only when the interrupted run proves a
handoff.
- Use the same canonical comment ID codecs for admission and dispatch.
- Test the assignment path with one or two saved comments and
independent chat and interaction receipts.

## Verification

On c957f8529c, 260 tests passed across the four admission, liveness and
responsible-user suites. The saved Grok interrupt route passed its
exactly-once continuation test. A separate Postgres run passed the
ordered comment and rollback checks, both reassignment cases, and the
company isolation test. Server typecheck and module boundaries passed.

Check the fresh admission and handoff cases in
`server/src/services/heartbeat/queue.test.ts`. Run `pnpm exec vitest run
server/src/__tests__/heartbeat-comment-wake-batching.test.ts
server/src/services/issue-queued-comment-queue.test.ts`, `pnpm --filter
@paperclipai/server typecheck`, and `node
scripts/check-module-boundaries.mjs`.

## Risks

Receipt selection controls which user input reaches the next agent. The
store requires the same company, issue and executor or a verified
handoff. Chat and interaction receipts preserve their independent
delivery.

## Model Used

OpenAI GPT-6.2 Sol (`gpt-6.2-sol`) implemented the change. OpenAI Codex
directed the work, reviewed the diff, and ran qualification.

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Nicky LeachandPaperclip authored and GitHub committed 2026-11-18 19:24:39 -08:00
1 parent f324238f73
commit eca7f85778
12 files changed
+372 -283

No files matched your search

@@ -16,7 +16,7 @@ import { earlierDeclinedOutcomeReply } from "../../../services/chat-interaction-
import { currentConversationCommentCondition } from "../../../services/agent-conversations.js";
import { getExecutionBlocker, hasPendingRunCleanup } from "../../../services/execution-blocker.js";
import { nativeManualAdmissionHoldsExecution } from "../../../services/native-runtime/native-runner-ownership.js";
import { and, asc, eq, inArray, isNull, notInArray, or, sql } from "drizzle-orm";
import { and, asc, eq, inArray, isNull, ne, notInArray, or, sql } from "drizzle-orm";
import { readReleaseRun, type ReleaseRun } from "./release-run-read.js";
import { isGovernancePauseStop } from "../../../services/governance-pause-stop.js";
import { agentRunSupersededByFreshContinuation } from "../../../agent-run-cancellation.js";
@@ -53,13 +53,15 @@ import { executionRetryAccounting } from "../../../services/execution-recovery-a
import { issueService } from "../../../services/issues.js";
import { issueRecoveryActionService } from "../../../services/issue-recovery-actions.js";
import { readContinuationAttempt } from "../../../services/recovery/run-liveness-continuations.js";
import { undeliveredLegacyUserCommentIds } from "../../../services/explicit-native-continuation.js";
import { withRecoveryContext } from "../../../services/recovery/status-only-context.js";
import { parseIssueExecutionState } from "../../../services/issue-execution-policy.js";
import {
queuedCommentIdsFromWakePayload,
DEFERRED_WAKE_CONTEXT_KEY,
queuedCommentIdsFromRunContext,
queuedCommentIdsFromWakePayload,
withQueuedCommentIdsInWakePayload,
} from "../../../services/issue-queued-comment-queue.js";
} from "../../../lib/queued-comment-context.js";
import { CHAT_CONVERSATION_ID_KEY, extractWakeCommentIds, readWakeChatConversationId } from "../../run-dispatch/index.js";
import { deferredWakeHoldsNoOtherConversation, otherConversationCommentIds, splitOtherConversationMessages } from "./chat-conversation-batch.js";
import { hasInteractionContinuationWakeContext } from "../domain/context.js";
@@ -85,13 +87,12 @@ import type {
WakeQueueHost,
WakeQueueTransaction,
} from "../application/ports.js";
import type { FreshIssueRunWriter } from "../application/fresh-issue-run.js";
import type { FreshIssueRunStore } from "../application/fresh-issue-run.js";
import type { RunSummary } from "../application/types.js";
const DEFERRED_WAKE_STATUS = "deferred_issue_execution";
/** Wake outcome for a deferred chat wake whose news an earlier reply already gave. */
export const ALREADY_REPORTED_WAKE_REASON = "Already reported by an earlier reply in this conversation";
const DEFERRED_WAKE_CONTEXT_KEY = "_paperclipWakeContext";
const EXECUTION_PATH_HEARTBEAT_RUN_STATUSES = ["queued", "running", "scheduled_retry"] as const;
type HeartbeatRunRow = typeof heartbeatRuns.$inferSelect;
@@ -1537,10 +1538,10 @@ export function createPostgresWakeQueueAdapter(db: Db, deps: WakeQueuePostgresAd
};
}
export function createFreshIssueRunWriter(
export function createFreshIssueRunStore(
scope: TransactionScope,
companyId: string,
): FreshIssueRunWriter<HeartbeatRunRow> {
): FreshIssueRunStore<HeartbeatRunRow> {
const tx = requireAdmissionTx(scope, companyId);
return {
async saveReceipt(input) {
@@ -1561,6 +1562,36 @@ export function createFreshIssueRunWriter(
)).returning();
return receipt;
},
async readCommentCandidates({ issueId, agentId, handoffRunId, receiptScope, checkExecutionBlocker }) {
const [handoff] = handoffRunId ? await tx.select({ agentId: heartbeatRuns.agentId }).from(heartbeatRuns).where(and(
eq(heartbeatRuns.id, handoffRunId), eq(heartbeatRuns.companyId, companyId),
eq(heartbeatRuns.status, "cancelled"), eq(heartbeatRuns.errorCode, "issue_reassigned"),
ne(heartbeatRuns.agentId, agentId),
sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${issueId}`,
or(isNull(heartbeatRuns.nativeIssueId), eq(heartbeatRuns.nativeIssueId, issueId)),
)) : [];
const candidates = receiptScope && (!checkExecutionBlocker || !(await getExecutionBlocker(tx, companyId, issueId)))
? await tx.select({
id: agentWakeupRequests.id,
reason: agentWakeupRequests.reason,
idempotencyKey: agentWakeupRequests.idempotencyKey,
payload: agentWakeupRequests.payload,
}).from(agentWakeupRequests).where(and(
eq(agentWakeupRequests.companyId, companyId),
inArray(agentWakeupRequests.agentId, handoff ? [agentId, handoff.agentId] : [agentId]),
eq(agentWakeupRequests.status, "deferred_issue_execution"),
sql`${agentWakeupRequests.payload}->>'issueId' = ${issueId}`,
receiptScope.kind === "exact" ? eq(agentWakeupRequests.id, receiptScope.wakeId) : undefined,
)).orderBy(asc(agentWakeupRequests.requestedAt))
: [];
return { handoffAgentId: handoff?.agentId ?? null, candidates };
},
readUndeliveredLegacyCommentIds(issueId, agentId, commentIds) {
return undeliveredLegacyUserCommentIds(tx, companyId, issueId, agentId, commentIds);
},
notifyRunMilestones(issueId) {
return notifyChatRunMilestones(tx, { companyId, issueId });
},
async insertQueuedRun(seed) {
const [run] = await tx.insert(heartbeatRuns).values({
...seed, companyId, status: "queued",
@@ -1,5 +1,14 @@
import { isUuidLike } from "@paperclipai/shared";
import {
DEFERRED_WAKE_CONTEXT_KEY,
queuedCommentIdsFromRunContext,
queuedCommentIdsFromWakePayload,
withQueuedCommentIdsInRunContext,
withQueuedCommentIdsInWakePayload,
} from "../../../lib/queued-comment-context.js";
import { hasInteractionContinuationWakeContext, isInteractionResolutionWakePayload } from "../domain/context.js";
import { parseObject, readNonEmptyString } from "../domain/values.js";
import type { DurableWakeAdmissionReceipt } from "./ports.js";
import { readNonEmptyString } from "../domain/values.js";
type WakeReceiptSeed = {
agentId: string;
@@ -33,8 +42,24 @@ type SaveWakeReceipt =
| { kind: "insert"; seed: WakeReceiptSeed & Partial<DurableWakeAdmissionReceipt> }
| { kind: "promote"; wakeId: string; agentId: string; payload: WakeReceiptSeed["payload"] };
export type FreshIssueRunWriter<Run> = {
type DeferredCommentCandidate = {
id: string;
reason: string | null;
idempotencyKey: string | null;
payload: unknown;
};
export type FreshIssueRunStore<Run> = {
saveReceipt(input: SaveWakeReceipt): Promise<{ id: string } | undefined>;
readCommentCandidates(input: {
issueId: string;
agentId: string;
handoffRunId: string | null;
receiptScope: { kind: "all" } | { kind: "exact"; wakeId: string } | null;
checkExecutionBlocker: boolean;
}): Promise<{ handoffAgentId: string | null; candidates: DeferredCommentCandidate[] }>;
readUndeliveredLegacyCommentIds(issueId: string, agentId: string, commentIds: string[]): Promise<string[]>;
notifyRunMilestones(issueId: string): Promise<void>;
insertQueuedRun(seed: QueuedRunSeed): Promise<Run>;
bindReceipts(input: {
wakeId: string;
@@ -44,53 +69,115 @@ export type FreshIssueRunWriter<Run> = {
}): Promise<void>;
};
/**
* Runs under heartbeat's existing issue lock. The caller validates admission,
* selects saved comments and records specialized continuation delivery between
* run creation and receipt binding.
*/
export function createFreshIssueRunAdmission<Run>(writer: FreshIssueRunWriter<Run>) {
return {
createReceipt(input: WakeReceiptSeed & {
durableReceipt?: DurableWakeAdmissionReceipt;
deferredChatReceiptId?: string;
}) {
const { durableReceipt, deferredChatReceiptId, ...seed } = input;
// A deferred durable chat wake keeps its original identity and source.
return writer.saveReceipt(deferredChatReceiptId
? { kind: "promote", wakeId: deferredChatReceiptId, agentId: seed.agentId, payload: seed.payload }
: {
kind: "insert",
seed: durableReceipt
? { ...seed, id: durableReceipt.id, requestedAt: durableReceipt.requestedAt }
: seed,
});
},
createRun(input: Omit<QueuedRunSeed,
"id" | "scopeKind" | "issueId" | "scheduledRetryAttempt" | "scheduledRetryReason"
> & {
explicitContinuationRunId: string | null;
reconciledSourceRunId: string | null;
reconciledRestoreRetryCount: number | null;
issueId: unknown;
}) {
const {
explicitContinuationRunId, reconciledSourceRunId, reconciledRestoreRetryCount, issueId, ...seed
} = input;
const scopedIssueId = readNonEmptyString(issueId);
return writer.insertQueuedRun({
...seed,
...(explicitContinuationRunId ? { id: explicitContinuationRunId } : {}),
scopeKind: scopedIssueId ? "issue" : "company",
issueId: scopedIssueId,
retryOfRunId: reconciledSourceRunId || seed.retryOfRunId,
sessionIdBefore: explicitContinuationRunId ? null : seed.sessionIdBefore,
...(reconciledRestoreRetryCount !== null ? {
scheduledRetryAttempt: reconciledRestoreRetryCount,
scheduledRetryReason: "transient_failure",
} : {}),
});
},
bindReceipts: writer.bindReceipts,
type FreshIssueRunInput = {
receipt: WakeReceiptSeed;
issue: { id: string; assigneeAgentId: string | null; isConversation: boolean };
durableReceipt?: DurableWakeAdmissionReceipt;
durableChatReceiptId?: string;
allowRunCoalescing?: boolean;
executionWaitRequestId?: string;
queuedCommentInterruptId?: string;
queuedCommentRequestId?: string;
boardRetryReceiptId?: string;
failedChatRetryReceiptId?: string;
ownsReconstructionContinuation: boolean;
contextSnapshot: Record<string, unknown>;
sessionIdBefore: string | null;
continuationAttempt: number;
explicitContinuationRunId: string | null;
retryOfRunId: string | null;
reconciledSourceRunId: string | null;
reconciledRestoreRetryCount: number | null;
resolveResponsibleUserId(): Promise<string>;
recordContinuationDelivery(runId: string): Promise<void>;
};
function isOrdinaryBoardComment(wake: DeferredCommentCandidate): boolean {
const payload = parseObject(wake.payload);
const context = parseObject(payload[DEFERRED_WAKE_CONTEXT_KEY]);
// Durable chat and interaction wakes carry their own actor, source, and session.
return !wake.idempotencyKey?.startsWith("chat-inbound:") &&
!isInteractionResolutionWakePayload(payload) &&
!hasInteractionContinuationWakeContext(context) &&
["issue_commented", "issue_reopened_via_comment"].includes(String(context.wakeReason ?? wake.reason)) &&
queuedCommentIdsFromWakePayload(payload).length > 0;
}
/** Admit one new run and its saved inputs using the caller's existing issue lock. */
export function createFreshIssueRunAdmission<Run extends { id: string }>(store: FreshIssueRunStore<Run>) {
return async function admitFreshIssueRun(input: FreshIssueRunInput): Promise<Run | undefined> {
const { receipt, durableReceipt, durableChatReceiptId, executionWaitRequestId, issue, contextSnapshot } = input;
const { agentId, source, triggerDetail, reason, payload } = receipt;
// A deferred durable chat wake keeps its original identity and source.
const primary = await store.saveReceipt(durableChatReceiptId && durableChatReceiptId === executionWaitRequestId
? { kind: "promote", wakeId: durableChatReceiptId, agentId, payload }
: {
kind: "insert",
seed: durableReceipt ? { ...receipt, id: durableReceipt.id, requestedAt: durableReceipt.requestedAt } : receipt,
});
if (!primary) return undefined;
// Only a verified reassignment can bring a previous executor's saved comments.
const interruptedRunId = readNonEmptyString(contextSnapshot.interruptedRunId);
const handoffRunId = source === "assignment" && reason === "issue_assigned" &&
issue.assigneeAgentId === agentId && interruptedRunId && isUuidLike(interruptedRunId)
? interruptedRunId : null;
// Chat keeps separate batches, but an exact resumed receipt must be consumed with its successor.
const canCoalesceComments = !durableChatReceiptId && !issue.isConversation && input.allowRunCoalescing !== false;
const { handoffAgentId, candidates } = await store.readCommentCandidates({
issueId: issue.id,
agentId,
handoffRunId,
receiptScope: canCoalesceComments || (executionWaitRequestId && input.boardRetryReceiptId)
? { kind: "all" }
: executionWaitRequestId ? { kind: "exact", wakeId: executionWaitRequestId } : null,
checkExecutionBlocker: !input.ownsReconstructionContinuation,
});
const adopted = candidates.filter((wake) => wake.id === executionWaitRequestId ||
wake.id === input.queuedCommentInterruptId || wake.id === input.queuedCommentRequestId ||
isOrdinaryBoardComment(wake));
const adoptedWakeIds = adopted.map((wake) => wake.id);
let commentIds = [...new Set([
...adopted.flatMap((wake) => queuedCommentIdsFromWakePayload(wake.payload)),
...queuedCommentIdsFromRunContext(contextSnapshot),
])];
if (input.queuedCommentRequestId || input.boardRetryReceiptId || handoffAgentId) {
commentIds = await store.readUndeliveredLegacyCommentIds(issue.id, agentId, commentIds);
}
await store.notifyRunMilestones(issue.id);
const responsibleUserId = await input.resolveResponsibleUserId();
const scopedIssueId = readNonEmptyString(contextSnapshot.issueId);
const run = await store.insertQueuedRun({
...(input.explicitContinuationRunId ? { id: input.explicitContinuationRunId } : {}),
agentId,
scopeKind: scopedIssueId ? "issue" : "company",
issueId: scopedIssueId,
invocationSource: source,
triggerDetail,
responsibleUserId,
wakeupRequestId: primary.id,
retryOfRunId: input.reconciledSourceRunId || input.retryOfRunId,
contextSnapshot: adopted.length ? withQueuedCommentIdsInRunContext(contextSnapshot, commentIds, adoptedWakeIds) : contextSnapshot,
sessionIdBefore: input.explicitContinuationRunId ? null : input.sessionIdBefore,
continuationAttempt: input.continuationAttempt,
...(input.reconciledRestoreRetryCount !== null ? {
scheduledRetryAttempt: input.reconciledRestoreRetryCount,
scheduledRetryReason: "transient_failure",
} : {}),
});
await input.recordContinuationDelivery(run.id);
await store.bindReceipts({
wakeId: primary.id,
runId: run.id,
failedChatRetryReceiptId: input.failedChatRetryReceiptId,
adopted: adopted.length ? {
wakeIds: adoptedWakeIds,
payload: withQueuedCommentIdsInWakePayload(payload, commentIds),
} : undefined,
});
return run;
};
}
@@ -1,4 +1,5 @@
import { readWakeChatConversationId } from "../../run-dispatch/index.js";
import { DEFERRED_WAKE_CONTEXT_KEY } from "../../../lib/queued-comment-context.js";
import { enrichPromotedWakeContext, wakeMustNotJoinActiveRun, withMergedWakeReasons } from "../domain/context.js";
import { QUEUED_MESSAGES_DELIVERED_REASON } from "../domain/policy.js";
import {
@@ -36,8 +37,6 @@ import type {
import type { PostCommitEffect, ReleaseOutcome } from "./types.js";
import { WakeQueueApplicationError } from "./types.js";
const DEFERRED_WAKE_CONTEXT_KEY = "_paperclipWakeContext";
const ISSUE_DISPOSITION_REPAIR_RETRY_REASON = "issue_disposition_repair";
const EXECUTION_REVIEW_PARTICIPANT_RECOVERY_WAKE_REASONS = new Set([
"execution_review_requested",
@@ -114,7 +114,7 @@ export function hasRetainedExternalChatRetry(context: unknown): boolean {
(activeSource === "issue.interaction.respond" && active.externalChatContinuation === true));
}
function isInteractionResolutionWakePayload(payload: Record<string, unknown> | null | undefined): boolean {
export function isInteractionResolutionWakePayload(payload: Record<string, unknown> | null | undefined): boolean {
return readNonEmptyString(payload?.mutation) === "interaction";
}
+2 -2
View File
@@ -1,7 +1,7 @@
import type { Db } from "@paperclipai/db";
import {
createAdmissionTransactionScope as buildAdmissionTransactionScope,
createFreshIssueRunWriter,
createFreshIssueRunStore,
createPostgresWakeQueueAdapter,
createWakeAdmissionReader,
createWakeAdmissionWriter,
@@ -114,7 +114,7 @@ export type WakeQueue = ReturnType<typeof createWakeQueue>;
/** Uses the transaction that already owns the issue's admission lock. */
export function bindFreshIssueRunAdmission(companyId: string, tx: Db) {
return createFreshIssueRunAdmission(createFreshIssueRunWriter(buildAdmissionTransactionScope(companyId, tx), companyId));
return createFreshIssueRunAdmission(createFreshIssueRunStore(buildAdmissionTransactionScope(companyId, tx), companyId));
}
/**