fix: deliver saved answers to dependency-blocked tasks (#20363)

## Thinking Path

> - Paperclip lets people direct agent work through tasks and structured
answers.
> - Dependencies stop task execution until prerequisite work finishes.
> - A person must still be able to answer or redirect the assignee of a
blocked task.
> - Ordinary comments already get a bounded answer/triage turn. A saved
question response has no comment ID, so the same gates reject it.
> - Later dispatch also requires an active task and tries to check it
out. That conflicts with bounded interaction on a blocked task.
> - This pull request verifies the stored human response at each gate
and keeps the turn in bounded interaction mode.
> - The assignee can receive the answer without starting dependency work
or removing its blockers.

## Linked Issues or Issue Description

Refs #19923. That change covers dependency waits and comment retries.
This change covers stored interaction responses that have no comment ID.

**What happened?**

A parent task waits on a parked child. The assignee asked a setup
question. After a person answers, the response stays queued. Sending
that saved response is refused as `issue_dependencies_blocked`. Ordinary
new messages can reach the same assignee.

Passing admission alone is insufficient. The dispatch status check
rejects a blocked task, and automatic checkout then tries to start work
whose prerequisites are unfinished.

**Expected behavior**

Deliver the stored human answer or confirmation to its requesting
assignee as a bounded answer/triage turn. Keep the task blocked and keep
its dependency relationships. Preserve current-owner, pause, approval,
budget, recovery, and execution gates.

**Steps to reproduce**

1. Assign a parent task and make a backlog child block it.
2. Save a question on the parent and answer it as a person.
3. Dispatch its resolved-interaction wake, or send the saved answer from
the task queue.
4. Observe that the answer does not reach the provider while an ordinary
comment can run in answer/triage mode.

**Paperclip version or commit**

Reproduced on master at `653ab8b18f76`. This branch is rebased onto
master at `0e3fdebea8`.

## What Changed

- Verify the stored response by company, task, requesting agent, status,
kind, human resolver, and resolution time. A context flag alone is
insufficient.
- Allow a verified response through dependency admission and claim in
the existing bounded interaction mode.
- Recheck that response during scheduled retry promotion and final
provider dispatch.
- Keep bounded responses from checking out the blocked task or setting
it to `in_progress`, including when the last blocker finishes during
preparation.
- Preserve continuation classification through workspace and AI-account
resource waits, so the final response and owner checks still run.
- Correct the task-case API summary so the existing `case for task`
discovery regression passes on the first search page. This fixes a
pre-existing failure exposed by full CI, without changing search ranking
or assertions.
- Ignore obsolete Retry notices after newer conversation work, without
acknowledging saved input or changing execution authority.
- Document the response contract. Add real PostgreSQL and
assembled-heartbeat regressions.

## Verification

- Final commit `ba4b337cf1bb0236b7c0a742665b222ee894ff51`: [required CI
passed, attempt
2](https://github.com/paperclipai/paperclip/actions/runs/42706363120/attempts/2),
including typecheck, production build, server/chat tests, Runner checks,
and all 8 browser shards. PR status: 59 passing checks and 3 normal
skips.
- Red: answered questions and accepted/rejected confirmations return no
admitted run before the fix. All three new positive cases fail at the
dependency gate. A resource-wait retry also reproduces as refused before
its gate is fixed.
- Green: at delivery revision `9375a603e4`, focused heartbeat
integration and classification passed 14 tests; retry scheduling and
dispatch safety passed 241 tests. These use real PostgreSQL and
controlled adapter and resource-availability boundaries. The wider
initial dependency, native-continuation, and queue suites also passed
before the final refinements.
- Negative cases keep pending, missing, wrong-task, and agent-resolved
responses blocked. Changing the response proof immediately before
dispatch cancels the run without calling the provider. Policy controls
retain the current assignee, task status, and pending approval checks.
- Positive cases execute once, leave the parent blocked, preserve the
dependency edge, and leave the child in backlog with no child execution.
The same saved response survives a resource wait; removing its human
proof refuses promotion.
- The resource-wait provider-boundary and blocker-completion regressions
also failed before their fixes. All 14 focused integration and
classifier cases passed at delivery revision `9375a603e4`, including a
changed response during retry preparation.
- Red: a retained Retry for an older run makes a newer successful
conversation display as failed. Green: all 78 database-backed query and
interruption-presentation tests pass, including a later real failure and
independent queued input controls.
- Server layered typecheck and module-boundary checks passed at
`11992aad0c7fbaf13e7548d71ee633560bd8bb6f`, before the one-line API
summary correction. That CI passed build, typecheck and every browser
shard, but exposed the pre-existing case-search assertion and a
report-assets test timeout. Final-head CI passed as linked above.
- Fresh Greptile review is 5/5 on final commit
`ba4b337cf1bb0236b7c0a742665b222ee894ff51`, with no unresolved threads.
- The existing API discovery suite reproduced its first-page assertion
before the summary correction; all 3 cases pass afterward. The timed-out
report-assets privacy test passed locally in isolation and the full
support job passed on the final-head rerun. Runner shutdowns interrupted
the first attempt; affected jobs were rerun once without code changes. A
separate onboarding timeout also passed on that rerun.
- `pnpm verify --explain` requests broad CI because the execution
contract is a global input. The final CI run supplied that coverage.
- Separately recovered the reported staging conversation through an
ordinary message and the existing steering control. The agent
acknowledged the message and the saved-answer queue drained. The fresh
Notebook action subsequently succeeded. This was on the previously
deployed revision; it does not claim this code is deployed.

## Risks

- This changes admission and dispatch. Each gate checks the persisted
response; no caller-supplied marker grants the exception.
- The bounded turn does not check out the task, resolve a dependency, or
approve another action. Existing pause, ownership, budget, approval, and
stopped-execution controls still apply.
- Each additional lookup is one primary-key read and runs only for a
response on a dependency-blocked path. There is no new polling worker.
- No migration is required. Older queued contexts get the exception only
when their stored human response still verifies. No prior run or action
is replayed by this change.
- This PR does not roll out the code to staging.

## Model Used

OpenAI Codex, GPT-6 family, with repository tools, code execution, and
browser inspection. The runtime does not expose the exact model ID,
context-window limit, or reasoning-mode label; those values are not
asserted.

## 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:
DottaandPaperclip authored and GitHub committed 2026-11-09 16:27:34 -06:00
1 parent eebdfe71b1
commit 3cc1032f6a
12 files changed
+245 -7

No files matched your search

@@ -42,6 +42,7 @@ import { budgetService, budgetServiceInTransaction, recheckAdmittedRunBudgetRead
import { lockRunBudgetRecoveryOwnerInTransaction, recheckRunBudgetReservationInTransaction } from "../../../services/budget-reservations.js";
import { isCompletedOnboardingHandoffWake } from "../../../services/chat-completion-delivery.js";
import { isUnstartedTaskQuestionAnswer } from "../../../services/unstarted-task-question-answer.js";
import { isVerifiedDependencyInteractionResponse } from "../../../services/queued-interaction-response.js";
import { isHeartbeatWakeOnDemandEnabled } from "../../../services/heartbeat-policy.js";
import { notifyChatRunMilestones } from "../../../services/chat-run-milestone-notifications.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "../../../services/delivery-work-notifications.js";
@@ -488,8 +489,12 @@ export function createPostgresRunDispatchAdapter(
.from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, input.companyId),
eq(agentWakeupRequests.id, input.wakeupRequestId))).then(rows => rows[0]?.actor ?? null) : null })
: false;
const responseAdmitted = readiness && !readiness.isDependencyReady
&& input.contextSnapshot.dependencyBlockedInteraction === true
&& await isVerifiedDependencyInteractionResponse(dbOrTx, { companyId: input.companyId,
issueId, agentId: input.agentId, context: input.contextSnapshot });
facts.dependenciesBlocked =
readiness && !readiness.isDependencyReady && !stallAdmitted
readiness && !readiness.isDependencyReady && !stallAdmitted && !responseAdmitted
? {
unresolvedBlockerIssueIds: readiness.unresolvedBlockerIssueIds,
unresolvedBlockerCount: readiness.unresolvedBlockerCount,
@@ -680,6 +685,10 @@ export function createPostgresRunDispatchAdapter(
issueExecutionRunId: issue?.executionRunId ?? null,
issueCheckoutRunId: issue?.checkoutRunId ?? null,
isResolvedInteractionContinuation,
isDependencyBlockedInteractionResponse: Boolean(isResolvedInteractionContinuation && issue?.status === "blocked"
&& context.dependencyBlockedInteraction === true
&& await isVerifiedDependencyInteractionResponse(dbOrTx, { companyId: input.companyId, issueId,
agentId: input.agentId, context })),
isUnstartedTaskQuestionAnswer: Boolean(isResolvedInteractionContinuation && issue?.status === "todo" &&
await isUnstartedTaskQuestionAnswer(dbOrTx, { companyId: input.companyId, issueId, interactionId: context.interactionId })),
isConnectionContinuation: (isResolvedInteractionContinuation && context.interactionKind === "connection_intent")
@@ -267,6 +267,21 @@ describe("decideScheduledRetryGate", () => {
});
describe("decideQueuedRunStaleness", () => {
it("keeps a verified response bounded to a blocked task and its current assignee", () => {
const response = { ...baseStalenessFacts(), isResolvedInteractionContinuation: true,
issueStatus: "blocked", isDependencyBlockedInteractionResponse: true };
expect(decideQueuedRunStaleness(response, NOW)).toEqual({ stale: false });
expect(decideQueuedRunStaleness({ ...response, isDependencyBlockedInteractionResponse: false }, NOW))
.toMatchObject({ stale: true, errorCode: "issue_not_in_progress" });
expect(decideQueuedRunStaleness({ ...response, issueAssigneeAgentId: "other-agent" }, NOW))
.toMatchObject({ stale: true, errorCode: "issue_assignee_changed" });
for (const issueStatus of ["backlog", "todo", "done", "cancelled"]) {
expect(decideQueuedRunStaleness({ ...response, issueStatus }, NOW)).toMatchObject({ stale: true });
}
expect(decideQueuedRunStaleness({ ...response, pendingResponse: "approval" }, NOW))
.toMatchObject({ stale: true, errorCode: "issue_waiting_for_response" });
});
it("is not stale when every rule passes", () => {
expect(decideQueuedRunStaleness(baseStalenessFacts(), NOW)).toEqual({
stale: false,
@@ -147,6 +147,8 @@ export type QueuedRunFacts = {
isResolvedInteractionContinuation: boolean;
/** Verified under the issue lock: an answer to a question no run asked, on a todo task that has never started. */
isUnstartedTaskQuestionAnswer?: boolean;
/** The stored human response was verified again for bounded dependency interaction. */
isDependencyBlockedInteractionResponse?: boolean;
/** A connection resolution or tool refresh can resume an agent waiting in review. */
isConnectionContinuation?: boolean;
isInteractionWake: boolean;
@@ -514,9 +516,10 @@ export function decideQueuedRunStaleness(
if (facts.isResolvedInteractionContinuation || facts.isConnectionContinuation) {
// A todo task that has never started has no parked execution to protect.
const startsUnstartedTask = facts.issueStatus === "todo" && facts.isUnstartedTaskQuestionAnswer === true;
const answersBlockedTask = facts.issueStatus === "blocked" && facts.isDependencyBlockedInteractionResponse === true;
const earlyStatus = decideIssueStatus({
status: facts.issueStatus,
requiresInProgress: facts.issueStatus !== "in_review" && !startsUnstartedTask,
requiresInProgress: facts.issueStatus !== "in_review" && !startsUnstartedTask && !answersBlockedTask,
terminalBypass: true,
});
if (earlyStatus === "not_in_progress") {
@@ -9,6 +9,14 @@ import {
} from "./wake-context.js";
describe("wake context", () => {
it.each(["workspace_busy", "ai_connection_busy", "ai_connection_pool_wait"])(
"keeps a bounded response classified through a %s resource wait", retryReason => {
const context = { interactionId: "response", interactionStatus: "answered", mutation: "interaction",
dependencyBlockedInteraction: true, wakeReason: `${retryReason}_retry`, retryReason };
expect(isResolvedInteractionContinuationWakeContext(context)).toBe(true);
expect(isResolvedInteractionContinuationWakeContext({ ...context, dependencyBlockedInteraction: false })).toBe(false);
expect(isResolvedInteractionContinuationWakeContext({ ...context, mutation: undefined })).toBe(false);
});
it("recognizes a retired available connection without accepting ordinary expiry", () => {
const context = { interactionId: "connection", interactionStatus: "expired", interactionKind: "connection_intent",
connectionIntentResolution: "existing_connection", mutation: "interaction", wakeReason: "issue_commented" };
@@ -29,6 +29,9 @@ export const RESOLVED_INTERACTION_CONTINUATION_STATUSES = new Set([
"cancelled",
"rejected",
]);
const RESOLVED_INTERACTION_RESOURCE_WAIT_REASONS = new Set([
WORKSPACE_BUSY_RETRY_REASON, AI_CONNECTION_BUSY_RETRY_REASON, AI_CONNECTION_POOL_WAIT_RETRY_REASON,
]);
// A run silent for this long no longer counts as the shared-workspace holder
// it was waiting behind. Kept here so the deferral gate and the parked-wait
@@ -170,7 +173,7 @@ export function allowsIssueInteractionWake(
/**
* Whether a wake may run while its issue still has unresolved blockers: a
* verified comment interaction, or a stalled child or blocker
* verified comment or human-response interaction, or a stalled child or blocker
* (`issue_blocker_stalled`, once per stall), which the assignee must be able
* to re-delegate, escalate or block on while that dependency is stuck. The
* caller verifies the stall against server state (`verifyBlockerStallWake`);
@@ -181,8 +184,9 @@ export function allowsDependencyBlockedWake(
contextSnapshot: Record<string, unknown> | null | undefined,
interactionWakeReasons: ReadonlySet<string>,
verifiedBlockerStall: boolean,
verifiedInteractionResponse = false,
): boolean {
return allowsIssueInteractionWake(contextSnapshot, interactionWakeReasons) || verifiedBlockerStall;
return allowsIssueInteractionWake(contextSnapshot, interactionWakeReasons) || verifiedBlockerStall || verifiedInteractionResponse;
}
export function isResolvedInteractionContinuationWakeContext(contextSnapshot: unknown): boolean {
@@ -201,6 +205,8 @@ export function isResolvedInteractionContinuationWakeContext(contextSnapshot: un
return (
(mutation === "interaction" && wakeReason === "issue_commented") ||
(mutation === "interaction" && retryReason === RUNNER_REVISION_WAIT_RETRY_REASON) ||
(mutation === "interaction" && context.dependencyBlockedInteraction === true && retryReason !== null
&& RESOLVED_INTERACTION_RESOURCE_WAIT_REASONS.has(retryReason)) ||
wakeReason === INTERACTION_CONTINUATION_INFRA_WAKE_REASON ||
retryReason === INTERACTION_CONTINUATION_INFRA_RETRY_REASON
);