mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-22 20:29:18 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A parent task gets a wake when a child task completes. If the parent is running, that wake waits behind the run. > - At finalization, a parent's done claim stays open (`native_child_completion_pending`) while such a wake is still owed, so the parent never finishes without the child result. > - The server had no record of what a running parent actually read. A parent that read its finished children mid-turn and then finished the task still kept the wake owed. > - The task stayed `in_progress`, the wake started a second parent turn, and the agent wrote a second completion summary. > - This pull request records a run's read of a finished child and counts that read as delivery of the child result. > - The benefit is one completion turn when the parent already read its children, while unread child results still get a fresh turn. ## Linked Issues or Issue Description Refs #21189 (child results saved before the run started). Refs #21175 (the same pattern for comments: `task_history.read`). Refs #15372 (the pending child-completion guard). **What happened?** Restart-chaos wave `w-20261112T223803-s7101`, on a master build that includes #21189, task t006 (OpenCode, native runner, staging-mix parent with two subtasks): - Parent run `bfe9941c` started at 22:55:56. - Its children CHA-11 and CHA-12 finished at 23:07:53 and 23:11:38. - The child-completion intent and its deferred dispatch row were saved at 23:11:38, after the run started. So the #21189 rule counted them as new input. - At 23:26:41 the run's reasoning says "Both subtask ledgers exist … Both subtasks are done". The run then saved the CHILD hashes and posted DONE at 23:33:39. - At finalization, the done claim was committed as `native_child_completion_pending`. The deferred wake then started run `40928116`, which wrote a second completion summary. Root cause: `hasPendingNativeChildCompletion()` (`server/src/services/native-runtime/native-child-completion-delivery.ts`) proved delivery only by wake binding and timestamps. No durable record showed that the finishing run had read the completed child. **Expected behavior** A finishing run's recorded read of a completed child counts as that child result being delivered. A read while the child was open, a read by another run, or a failed event write does not count. An unread child result still keeps the task open and gets one fresh parent turn. **Steps to reproduce** 1. Start a native parent run. 2. Complete a child while the run is active. The child-completion wake waits behind the run. 3. Let the run read the child (`get_task_context`, or `GET /api/issues/:childId`), then claim `done`. 4. Finalize and release the run. On `master`, the decision is `native_child_completion_pending` and the wake becomes a second run. The same wave's t001 grade ("duplicate completion") is not this bug. That run only said it *will* post the DONE marker later, and the grader counts any mention. Its `subtasks_once` failure comes from the restart-recovery continuation. This PR does not change either one. ## What Changed - `native-child-completion-delivery.ts`: - New `recordChildTaskRead()` writes a `child_task.read` run-log event. The payload is `{ parentIssueId, children: { id: { status, updatedAt } } }`, and it lists only children in `done`. - `hasPendingNativeChildCompletion()` no longer counts a child-completion wake as pending when the finishing run recorded a read of that wake's completed child in `done` at or after the child's completion decision (`status_decisions.created_at`, or the wake's `createdAt` when the decision row is missing). - The #21189 start-time rule is unchanged. - `paperclip-runner-tool-authority.ts`: `get_task_context` records the finished child tasks it returns. A failed write is logged and leaves the result owed. - `routes/issues.ts`: `GET /issues/:id`, `GET /issues/:id/documents` and `GET /issues/:id/documents/:key` record the read when the request has all of these: - an agent actor with a run token - a child issue in `done` This runs after the existing access and company checks. So a board user, another company's agent, or a read of an open task writes nothing. A qualifying read adds one statement: the existing `appendHeartbeatRunEvent` fast path, a single `update … returning` / `insert` CTE bound to the run's id, company and agent. Every other read adds no query. - `doc/run-log-events.md`: documents `child_task.read` and how delivery uses it. - Tests: a finalization-to-release regression in `heartbeat-process-recovery.test.ts` and a new `native-child-task-read-routes.test.ts`. ## Verification - RED on `master`: in `heartbeat-process-recovery.test.ts` "counts a child result as read by the finishing parent run (saved after the run started, read: after the child finished)", the run reads the child through the real `get_task_context`, then finalization and the wake-queue release run. - On master: `native_child_completion_pending`, task `in_progress`, and the wake is promoted into a second run, the same as t006. - With this change: `done`, the wake is cancelled, and there is one run. - The other cases in the same test behave the same before and after this change: - saved before the run started: done - not read: pending, fresh turn with the child results - read while the child was open: pending - `native-child-task-read-routes.test.ts` (5 tests): - An agent read of a done child through each of the three routes records the read and clears the pending result. - An open child records nothing. - A board read records nothing. - Another company's agent gets no 200 and records nothing. - Neighbouring suites after merging `origin/master`: `heartbeat-process-recovery`, `muse-control`, `heartbeat-held-comment-wake`, `native-status-arbiter-corpus`, `heartbeat-dependency-scheduling`, `paperclip-runner-tool-authority`, `agent-task-hierarchy-depth-routes`, and the two new test files: 8 files, 982/982 tests pass. - `pnpm --filter @paperclipai/server typecheck` passes. **Not verified** - No chaos wave has run on this change yet. - In t006, the parent's tool calls fell in the 4,220 run events that the evidence omitted. Its reasoning text proves the read, but the exact tool (`get_task_context`, `get_task`, `read_task_document` or `call_api`) is not visible. - A read through `search_tasks`, or through a shell command that calls the API without the run token, is not recorded. Such a result stays owed and gets one fresh turn, which is the old behavior. ## Risks - A recorded read of a done child now lets the parent finish without another turn. If the agent read the child but ignored it, no second turn reminds it. A read while the child was still open never counts. - Each qualifying agent read of a done child appends one run-log row. Board reads and reads of open tasks write nothing. - No migration. Wakes saved by older builds work unchanged. Without a recorded read, the old behavior applies. - This is a run-log change only (instance database). It adds no Telemetry or OpenTelemetry export. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edits, test runs). ## 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 <noreply@anthropic.com>
63 lines
4.1 KiB
TypeScript
63 lines
4.1 KiB
TypeScript
import { and, eq, inArray, isNull, ne, or, sql } from "drizzle-orm";
|
|
import { agentWakeupRequests, heartbeatRunEvents, heartbeatRuns, statusDecisions, type Db } from "@paperclipai/db";
|
|
import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js";
|
|
|
|
export interface NativeChildCompletionRecipient {
|
|
companyId: string;
|
|
issueId: string;
|
|
agentId: string;
|
|
runId: string;
|
|
sourceIntentId: string | null;
|
|
}
|
|
|
|
export const CHILD_TASK_READ_EVENT = "child_task.read";
|
|
|
|
export async function recordChildTaskRead(db: Db, input: {
|
|
companyId: string; agentId: string; runId: string; parentIssueId: string;
|
|
children: ReadonlyArray<{ id: string; parentId: string | null; status: string; updatedAt: Date; lastStatusDecisionId?: string | null }>;
|
|
}): Promise<void> {
|
|
const completed = input.children.filter(child => child.parentId === input.parentIssueId && child.status === "done");
|
|
if (completed.length === 0) return;
|
|
await appendHeartbeatRunEvent(db, { companyId: input.companyId, runId: input.runId, agentId: input.agentId,
|
|
eventType: CHILD_TASK_READ_EVENT, stream: "system", level: "info",
|
|
payload: { parentIssueId: input.parentIssueId,
|
|
children: Object.fromEntries(completed.map(child => [child.id, { status: child.status, updatedAt: child.updatedAt.toISOString(),
|
|
statusDecisionId: child.lastStatusDecisionId ?? null }])) } });
|
|
}
|
|
|
|
/** New child results belong to a fresh parent turn, including across a Done claim. */
|
|
export async function hasPendingNativeChildCompletion(db: Db, input: NativeChildCompletionRecipient) {
|
|
const completedChildId = sql`coalesce(${agentWakeupRequests.payload}->>'completedChildIssueId',
|
|
${agentWakeupRequests.payload}->'_paperclipWakeContext'->>'completedChildIssueId')`;
|
|
const [pending] = await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and(
|
|
eq(agentWakeupRequests.companyId, input.companyId),
|
|
eq(agentWakeupRequests.agentId, input.agentId),
|
|
or(eq(agentWakeupRequests.reason, "issue_children_completed"),
|
|
and(eq(agentWakeupRequests.reason, "issue_execution_deferred"),
|
|
sql`${agentWakeupRequests.payload}->'_paperclipWakeContext'->>'wakeReason' = 'issue_children_completed'`)),
|
|
eq(agentWakeupRequests.requestedByActorType, "system"),
|
|
or(eq(agentWakeupRequests.requestedByActorId, "native-status-committer"),
|
|
sql`${agentWakeupRequests.requestedByActorId} like 'native-status-wake-dispatch:%'`),
|
|
inArray(agentWakeupRequests.status, ["queued", "claimed", "deferred_issue_execution"]),
|
|
sql`${agentWakeupRequests.payload}->>'issueId' = ${input.issueId}`,
|
|
sql`nullif(${agentWakeupRequests.payload}->'_paperclipWakeContext'->>'nativeChildCompletionDecisionId', '') is not null`,
|
|
or(isNull(agentWakeupRequests.runId), ne(agentWakeupRequests.runId, input.runId)),
|
|
sql`${agentWakeupRequests.createdAt} >= coalesce((select ${heartbeatRuns.startedAt} from ${heartbeatRuns}
|
|
where ${heartbeatRuns.id} = ${input.runId} and ${heartbeatRuns.companyId} = ${input.companyId}), '-infinity'::timestamptz)`,
|
|
sql`not exists (select 1 from ${heartbeatRunEvents} child_read
|
|
where child_read.company_id = ${input.companyId} and child_read.run_id = ${input.runId}
|
|
and child_read.event_type = ${CHILD_TASK_READ_EVENT}
|
|
and child_read.payload->>'parentIssueId' = ${input.issueId}
|
|
and child_read.payload->'children'->(${completedChildId})->>'status' = 'done'
|
|
and (child_read.payload->'children'->(${completedChildId})->>'statusDecisionId'
|
|
= ${agentWakeupRequests.payload}->'_paperclipWakeContext'->>'nativeChildCompletionDecisionId'
|
|
or (child_read.payload->'children'->(${completedChildId})->>'updatedAt')::timestamptz
|
|
>= date_trunc('milliseconds', coalesce((select ${statusDecisions.createdAt} from ${statusDecisions}
|
|
where ${statusDecisions.companyId} = ${input.companyId}
|
|
and ${statusDecisions.id}::text = ${agentWakeupRequests.payload}->'_paperclipWakeContext'->>'nativeChildCompletionDecisionId'),
|
|
${agentWakeupRequests.createdAt}))))`,
|
|
input.sourceIntentId ? ne(agentWakeupRequests.id, input.sourceIntentId) : undefined,
|
|
)).limit(1);
|
|
return Boolean(pending);
|
|
}
|