fix(native): count a parent run's read of a finished child as delivery of its result (#21227)

## 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>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-12 19:07:31 -06:00
1 parent ad320aeb71
commit b0233b5b33
6 files changed
+219 -7

No files matched your search

+23
View File
@@ -1024,6 +1024,29 @@ comments one run read, with each read's time and the comment revision it saw,
whatever the run's outcome. A failure to write the event leaves the comment
owed in the same way.
When a run reads a finished child task, the server writes one
`child_task.read` event (`stream: "system"`, level `info`) to that run's log.
The reads that count are `get_task_context` on the parent task, and a
successful agent request with a run token for `GET /api/issues/:id`,
`GET /api/issues/:id/documents` or `GET /api/issues/:id/documents/:key` of a
child in `done`. The route writes the event only after the requested content
has loaded, so a 400 or 404 records nothing. The payload has `parentIssueId`
and `children`, which maps each finished child ID to the revision the run
received: its `status`, `updatedAt` and `statusDecisionId`. It contains no
titles, summaries or document bodies. The event creates no Telemetry or
OpenTelemetry export.
`hasPendingNativeChildCompletion` reads this event. A child-completion wake no
longer keeps the parent's done claim open when the finishing run received that
child in `done` at the completion the wake reports: the received
`statusDecisionId` is the wake's completion decision, or the received
`updatedAt` is at or after that decision was saved. The event's own write time
does not count, so a delayed write of an older revision cannot deliver a newer
completion. The wake is then cancelled at release instead of starting another
parent turn. A read while the child was still open, a read of an older
revision, a read by another run, or a failure to write the event leaves the
child result owed.
## Managed Agent File Save Receipts
The server writes `instruction_save` after managed file collection or a warm
@@ -265,6 +265,7 @@ import {
} from "../services/native-runtime/native-restart-recovery.ts";
import { claimNativeSessionResumptions } from "../services/native-runtime/native-finalization-reconciler.ts";
import { PaperclipControlPlanePort } from "../services/native-runtime/paperclip-control-plane-port.js";
import { PaperclipRunnerToolAuthority } from "../services/native-runtime/paperclip-runner-tool-authority.js";
import { finalizeNativeRun } from "../services/native-runtime/native-run-finalizer.js";
import { createWakeQueue } from "../modules/wake-queue/index.js";
import { recordNativeAttentionAssessment } from "../services/native-runtime/work-assessments.js";
@@ -15479,11 +15480,15 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
});
it.each([
["before", "done", "completion_claim_policy_accepted"],
["after", "in_progress", "native_child_completion_pending"],
] as const)("treats a child result saved %s the parent run started as read when the run finishes the task", async (
savedRelativeToStart, expectedStatus, expectedReason,
) => {
{ saved: "before", read: "none", delivered: true },
{ saved: "after", read: "none", delivered: false },
{ saved: "after", read: "after the child finished", delivered: true },
{ saved: "after", read: "while the child was open", delivered: false },
] as const)("counts a child result as read by the finishing parent run (saved $saved the run started, read: $read)", async ({
saved: savedRelativeToStart, read, delivered,
}) => {
const expectedStatus = delivered ? "done" : "in_progress";
const expectedReason = delivered ? "completion_claim_policy_accepted" : "native_child_completion_pending";
const fixture = await seedStrandedIssueFixture({ status: "in_progress", runStatus: "succeeded", livenessState: "advanced" });
const { companyId, agentId, issueId, runId } = fixture;
const childId = randomUUID();
@@ -15516,6 +15521,17 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
startedAt: runStartedAt, finishedAt: new Date(),
}).where(eq(heartbeatRuns.id, runId));
await db.update(issues).set({ executionRunId: runId, executionLockedAt: runStartedAt }).where(eq(issues.id, issueId));
if (read !== "none") {
if (read === "while the child was open") await db.update(issues).set({ status: "in_progress" }).where(eq(issues.id, childId));
await db.update(heartbeatRuns).set({ status: "running", finishedAt: null }).where(eq(heartbeatRuns.id, runId));
const reader = new PaperclipRunnerToolAuthority(db, { companyId, agentId, issueId, runId });
try {
const context = await reader.execute({ tool: "get_task_context", callId: `context-${runId}`, arguments: {} });
expect((context as { childTasks: Array<{ id: string }> }).childTasks.map(task => task.id)).toEqual([childId]);
} finally { reader.close(); }
await db.update(issues).set({ status: "done" }).where(eq(issues.id, childId));
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, runId));
}
await db.insert(issueComments).values({ companyId, issueId, authorType: "agent", authorAgentId: agentId,
createdByRunId: runId, body: "Both children are done; merged their ledgers. Task complete." });
await new PaperclipControlPlanePort(db, {
@@ -15550,7 +15566,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
.toEqual([expect.objectContaining({ status: expectedStatus })]);
const runs = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, companyId));
const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, childResult!.id));
if (savedRelativeToStart === "before") {
if (delivered) {
expect(wake).toMatchObject({ status: "cancelled", runId: null });
expect(runs).toHaveLength(1);
} else {
@@ -0,0 +1,127 @@
import { randomUUID } from "node:crypto";
import express from "express";
import request from "supertest";
import { and, eq } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { agentWakeupRequests, agents, companies, createDb, heartbeatRunEvents, heartbeatRuns, issues } from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { issueRoutes } from "../routes/issues.js";
import { errorHandler } from "../middleware/index.js";
import { documentService } from "../services/documents.js";
import { CHILD_TASK_READ_EVENT, hasPendingNativeChildCompletion } from "../services/native-runtime/native-child-completion-delivery.js";
const support = await getEmbeddedPostgresTestSupport();
const describePostgres = support.supported ? describe : describe.skip;
describePostgres("a parent run reading a finished child through the issue routes", () => {
let db: ReturnType<typeof createDb>;
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
const companyId = randomUUID();
const agentId = randomUUID();
const otherCompanyId = randomUUID();
const otherAgentId = randomUUID();
const otherRunId = randomUUID();
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("paperclip-native-child-read-routes-");
db = createDb(database.connectionString);
await db.insert(companies).values({ id: companyId, name: "Paperclip", issuePrefix: "CHR", defaultResponsibleUserId: "board-user",
requireBoardApprovalForNewAgents: false });
await db.insert(agents).values({ id: agentId, companyId, name: "Coder", role: "engineer", adapterType: "codex_local", status: "active" });
await db.insert(companies).values({ id: otherCompanyId, name: "Other", issuePrefix: "OTH", defaultResponsibleUserId: "board-user",
requireBoardApprovalForNewAgents: false });
await db.insert(agents).values({ id: otherAgentId, companyId: otherCompanyId, name: "Outsider", role: "engineer",
adapterType: "codex_local", status: "active" });
await db.insert(heartbeatRuns).values({ id: otherRunId, companyId: otherCompanyId, agentId: otherAgentId, status: "running",
runtimeMode: "native", startedAt: new Date(), contextSnapshot: {} });
}, 30_000);
afterAll(async () => { await database?.cleanup(); });
function app(actor: Express.Request["actor"]) {
const instance = express();
instance.use(express.json());
instance.use((req, _res, next) => { req.actor = actor; next(); });
instance.use("/api", issueRoutes(db, {} as never));
instance.use(errorHandler);
return instance;
}
const agentActor = (runId: string) => ({ type: "agent", companyId, agentId, runId, source: "agent_jwt",
onBehalfOfUserId: null, onBehalfOfMemberships: [] }) as Express.Request["actor"];
const boardActor = { type: "board", userId: "board-user", source: "local_implicit", isInstanceAdmin: true } as Express.Request["actor"];
async function seed(childStatus: "done" | "in_progress", issueNumber: number, options: { childRevisionAgeMs?: number; wakeAgeMs?: number } = {}) {
const runId = randomUUID();
const childId = randomUUID();
const parentId = randomUUID();
await db.insert(issues).values({ id: parentId, companyId, title: "Merge the ledgers", identifier: `CHR-${issueNumber + 100}`,
issueNumber: issueNumber + 100, status: "in_progress", assigneeAgentId: agentId });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", runtimeMode: "native",
nativeIssueId: parentId, startedAt: new Date(Date.now() - 60_000), contextSnapshot: { issueId: parentId } });
await db.insert(issues).values({ id: childId, companyId, parentId, title: "Child ledger", identifier: `CHR-${issueNumber}`,
issueNumber, status: childStatus, assigneeAgentId: agentId,
...(options.childRevisionAgeMs ? { updatedAt: new Date(Date.now() - options.childRevisionAgeMs) } : {}) });
await documentService(db).upsertIssueDocument({ issueId: childId, key: "ledger", format: "markdown", body: "ROUND 1" });
if (options.childRevisionAgeMs) await db.update(issues).set({ updatedAt: new Date(Date.now() - options.childRevisionAgeMs) })
.where(eq(issues.id, childId));
const [wake] = await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "automation", triggerDetail: "system",
reason: "issue_execution_deferred", requestedByActorType: "system", requestedByActorId: `native-status-wake-dispatch:${randomUUID()}`,
status: "deferred_issue_execution", createdAt: new Date(Date.now() - (options.wakeAgeMs ?? 30_000)),
payload: { issueId: parentId, _paperclipWakeContext: { issueId: parentId, wakeReason: "issue_children_completed",
nativeChildCompletionDecisionId: randomUUID(), completedChildIssueId: childId } } }).returning();
return { runId, childId, parentId, wakeId: wake!.id };
}
const reads = (runId: string) => db.select().from(heartbeatRunEvents)
.where(and(eq(heartbeatRunEvents.runId, runId), eq(heartbeatRunEvents.eventType, CHILD_TASK_READ_EVENT)));
const pending = (f: { runId: string; parentId: string }) =>
hasPendingNativeChildCompletion(db, { companyId, issueId: f.parentId, agentId, runId: f.runId, sourceIntentId: null });
it.each(["", "/documents", "/documents/ledger"])("records the parent run's read of a finished child (GET /issues/:id%s)", async (suffix) => {
const f = await seed("done", 10 + suffix.length);
expect(await pending(f)).toBe(true);
expect((await request(app(agentActor(f.runId))).get(`/api/issues/${f.childId}${suffix}`)).status).toBe(200);
expect(await reads(f.runId)).toEqual([expect.objectContaining({ payload: {
parentIssueId: f.parentId, children: { [f.childId]: { status: "done", updatedAt: expect.any(String), statusDecisionId: null } } } })]);
expect(await pending(f)).toBe(false);
});
it("does not count a read of a child that is still open, or a board read", async () => {
const open = await seed("in_progress", 40);
expect((await request(app(agentActor(open.runId))).get(`/api/issues/${open.childId}`)).status).toBe(200);
expect(await reads(open.runId)).toEqual([]);
expect(await pending(open)).toBe(true);
const board = await seed("done", 41);
expect((await request(app(boardActor)).get(`/api/issues/${board.childId}`)).status).toBe(200);
expect(await reads(board.runId)).toEqual([]);
expect(await pending(board)).toBe(true);
});
it("does not record a read by another company's agent", async () => {
const f = await seed("done", 42);
const outsider = { type: "agent", companyId: otherCompanyId, agentId: otherAgentId, runId: otherRunId, source: "agent_jwt",
onBehalfOfUserId: null, onBehalfOfMemberships: [] } as Express.Request["actor"];
for (const suffix of ["", "/documents", "/documents/ledger"]) {
expect((await request(app(outsider)).get(`/api/issues/${f.childId}${suffix}`)).status).not.toBe(200);
}
expect(await db.select().from(heartbeatRunEvents).where(eq(heartbeatRunEvents.eventType, CHILD_TASK_READ_EVENT))
.then(rows => rows.filter(row => row.runId === otherRunId || row.companyId === otherCompanyId))).toEqual([]);
expect(await pending(f)).toBe(true);
});
it.each([
["an invalid document key", "/documents/Not A Key!", 400],
["a missing document", "/documents/missing", 404],
])("does not count a failed request for %s as a read", async (_shape, suffix, status) => {
const f = await seed("done", 43 + suffix.length);
expect((await request(app(agentActor(f.runId))).get(`/api/issues/${f.childId}${encodeURI(suffix)}`)).status).toBe(status);
expect(await reads(f.runId)).toEqual([]);
expect(await pending(f)).toBe(true);
});
it("does not let a read of an older finished revision deliver a newer completion", async () => {
const f = await seed("done", 70, { childRevisionAgeMs: 60_000, wakeAgeMs: 10_000 });
expect((await request(app(agentActor(f.runId))).get(`/api/issues/${f.childId}`)).status).toBe(200);
expect(await reads(f.runId)).toHaveLength(1);
expect(await pending(f)).toBe(true);
});
});
+12
View File
@@ -24,6 +24,7 @@ import { listIssueStatusBlockerAttention } from "../services/issue-status-presen
import { assertNoCaseHandoffMutation } from "../services/heartbeat/case-handoff-lifecycle.js";
import { assertHandedOffRunTaskOwnership } from "../run-task-ownership.js";
import { recordNativeHumanSelfHandoff } from "../services/native-runtime/native-human-self-handoff.js";
import { recordChildTaskRead } from "../services/native-runtime/native-child-completion-delivery.js";
import { runRetainsIssueIdentity } from "../services/task-repository-acquisition.js";
import { withConversationReadState } from "../services/agent-chat-read-state.js";
import { markIssueReadSchema } from "@paperclipai/shared";
@@ -3611,6 +3612,13 @@ function logIssueListRequest(input: {
});
}
async function recordAgentChildTaskRead(db: Db, req: Request, issue: { id: string; companyId: string; parentId: string | null; status: string; updatedAt: Date; lastStatusDecisionId?: string | null }) {
if (req.actor.type !== "agent" || !req.actor.agentId || !req.actor.runId || !issue.parentId || issue.status !== "done") return;
await recordChildTaskRead(db, { companyId: issue.companyId, agentId: req.actor.agentId, runId: req.actor.runId,
parentIssueId: issue.parentId, children: [issue] })
.catch(error => logger.warn({ err: error, runId: req.actor.runId }, "could not record the child task a run read"));
}
export function issueRoutes(
db: Db,
storage: StorageService,
@@ -10079,6 +10087,7 @@ export function issueRoutes(
// and related-task enrichment. This never refreshes external providers.
if (req.query.view === "core") {
const core = await readIssueCore(issue, timing.time);
await recordAgentChildTaskRead(db, req, issue);
res.setHeader("Server-Timing", timing.header());
res.json(core);
return;
@@ -10160,6 +10169,7 @@ export function issueRoutes(
const visibleMentionedProjects = mentionedProjects.filter((_, index) => mentionedProjectVisibility[index]);
// Recovery revalidation may change the blocker; read it afterwards.
const executionBlocker = await timing.time("execution_blocker", () => getExecutionBlocker(db, issue.companyId, issue.id));
await recordAgentChildTaskRead(db, req, issue);
res.setHeader("Server-Timing", timing.header());
res.json({
...issue,
@@ -11366,6 +11376,7 @@ export function issueRoutes(
const docs = await documentsSvc.listIssueDocuments(issue.id, {
includeSystem: req.query.includeSystem === "true",
});
await recordAgentChildTaskRead(db, req, issue);
res.json(docs);
});
@@ -11399,6 +11410,7 @@ export function issueRoutes(
res.status(404).json({ error: "Document not found" });
return;
}
await recordAgentChildTaskRead(db, req, issue);
if (!shouldIncludeDocumentAnnotations(req)) {
res.json(doc);
return;
@@ -1,5 +1,6 @@
import { and, eq, inArray, isNull, ne, or, sql } from "drizzle-orm";
import { agentWakeupRequests, heartbeatRuns, type Db } from "@paperclipai/db";
import { agentWakeupRequests, heartbeatRunEvents, heartbeatRuns, statusDecisions, type Db } from "@paperclipai/db";
import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js";
export interface NativeChildCompletionRecipient {
companyId: string;
@@ -9,8 +10,25 @@ export interface NativeChildCompletionRecipient {
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),
@@ -26,6 +44,18 @@ export async function hasPendingNativeChildCompletion(db: Db, input: NativeChild
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);
@@ -139,6 +139,7 @@ import {
type NativeChatAttachmentReadScope,
} from "./chat-attachment-read.js";
import { recordTaskHistoryRead } from "../queued-comment-delivery.js";
import { recordChildTaskRead } from "./native-child-completion-delivery.js";
import { logger } from "../../middleware/logger.js";
const EXTERNAL_WORKSPACE_OPERATIONS = new Set(["get_workspace", "list_workspaces", "select_workspace", "prepare_repository", "register_deliverable"]);
@@ -947,6 +948,9 @@ export class PaperclipRunnerToolAuthority {
const readableChildren = this.binding.museRuntime
? await this.#readableMuseTaskIds(context.run, childTasks.map(task => task.id)) : null;
const visibleChildTasks = readableChildren ? childTasks.filter(task => readableChildren.has(task.id)) : childTasks;
await recordChildTaskRead(this.db, { companyId: this.binding.companyId, agentId: this.binding.agentId,
runId: this.binding.runId, parentIssueId: this.binding.issueId, children: visibleChildTasks.slice(0, 100) }).catch(error =>
logger.warn({ err: error, runId: this.binding.runId }, "could not record the child tasks a run read"));
return {
company: { id: this.binding.companyId },
actor: redactedActor(context.actor),