mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-19 16:29:42 +01:00
Add bulk keyed issue document reads for native helpers (#22105)
## Thinking Path
> - Paperclip manages work for AI agents.
> - Native helpers read task documents through authorized API tools.
> - A scan of 146 cases needs one saved response and one download per
case.
> - The document service can read the same key across authorized tasks
with bounded queries.
> - This pull request adds a bounded bulk read with the existing task
access policy.
> - Helpers can transfer one batch and check current revisions before
fetching changed bodies.
## Linked Issues or Issue Description
**Subsystem affected**
Task document REST API, shared query contracts, and native API
discovery.
**Problem or motivation**
Per-task document reads make native sync scans cost hundreds of tool
calls. Task list timestamps do not prove that document content is
unchanged.
**Proposed solution**
Add `GET
/api/companies/{companyId}/issue-documents?key=notes&issueIds=...`. Read
up to 200 task UUIDs under current company and task permissions. Return
current bodies and revision metadata, or metadata alone with
`includeBody=false`.
**Alternatives considered**
Generic request batching would add tool execution and partial failure
rules. One bulk resource read removes the per-case relay cost with the
existing tools. Do not skip documents based only on task-row timestamps.
Keep managed skill files immutable; cleanup of copied skill test
fixtures belongs to those tests.
**Roadmap alignment**
This improves existing task documents and native API access. It adds no
new workflow or UI. The roadmap has no duplicate bulk document read
work. No duplicate open pull request was found.
## What Changed
- Add a bulk keyed document route and a company-scoped document reader.
Reuse the current batched task-read policy and completed-task read
receipts.
- Preserve request order and deduplicate IDs. Return `document: null`
for readable tasks without the key. Omit unreadable, hidden, foreign and
missing tasks without revealing which exist.
- Bound requests to 200 IDs and responses to 8 MiB of JSON bytes. Check
encoded body sizes in SQL before fetching bodies in the same read
snapshot. Build JSON within the byte budget. Oversized responses fail
with 413 and are never saved as partial artifacts.
- Admit at most two active reads per actor and eight per server
instance. Extra requests receive 429 with Retry-After. Keep the slot
until both the database work and response settle.
- Batch completed-handoff lookups and group child receipts by parent.
Extend the existing event batch writer for ordinary non-waking receipts
with atomic sequence allocation. Stored receipt shapes stay unchanged
for existing consumers.
- Expose revision-only reads without selecting document bodies. Document
native discovery, one save plus one download, and complete-inventory
checks.
- Add real HTTP, database and artifact tests for 146 open and completed
cases, 200 maximum-size bodies, metadata overhead, access failures,
query limits and JSON expansion. Cover admission limits, failure
cleanup, and concurrent event writers. Refresh the shared SDK source
pins.
## Verification
Final revision: `93dc8b029600211d79a050650f3dff82e5dad52f`.
- [CI run 44212220917, attempt
3](https://github.com/paperclipai/paperclip/actions/runs/44212220917)
passed. This includes typecheck, build, general tests, Runner checks,
serialized server suites, all e2e shards, and the final verify gate.
-
[Build](https://github.com/paperclipai/paperclip/actions/runs/44212220917/job/134506305267),
[e2e](https://github.com/paperclipai/paperclip/actions/runs/44212220917/job/134506309117),
and
[verify](https://github.com/paperclipai/paperclip/actions/runs/44212220917/job/134510062263)
are green.
- [Linux CI job
134506309291](https://github.com/paperclipai/paperclip/actions/runs/44212220917/job/134506309291)
passed all 16 bulk document integration tests. This includes the native
transfer of all 146 documents with the saved size and hash,
completed-case receipt batching, and size-only rejection of 200
maximum-size documents.
- [Greptile
review](https://github.com/paperclipai/paperclip/pull/22105#issuecomment-6965449032)
is 5/5 on the final revision. All review threads are resolved. Security
checks pass. GitHub reports CLEAN and MERGEABLE.
- Local server typecheck passed on macOS with Node 25.6.1. The focused
run below passed 177 tests; the Linux-only transfer test was skipped
locally and then passed in CI.
```sh
pnpm --filter @paperclipai/server typecheck
cd server
pnpm exec vitest run \
src/routes/issue-document-batch.test.ts \
src/services/native-runtime/issue-document-batch.integration.test.ts \
src/__tests__/documents-service.test.ts \
src/__tests__/openapi-routes.test.ts \
src/__tests__/heartbeat-run-event-atomic-append.test.ts \
src/__tests__/chat-completion-delivery.test.ts \
src/__tests__/native-child-task-read-routes.test.ts
```
- Shared typecheck and build passed. From `packages/shared/`, `pnpm exec
vitest run src/validators/issue.test.ts` passed 61 tests before the
rebase; the batch query contract did not change in the rebase.
- `node tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --check`
passed. Runtime and lockfile pins are unchanged.
- `pnpm verify --explain` returned exit 2 because the API docs and
shared contracts require broader CI. The successful CI run above
supplies that coverage.
Failure and recovery record:
- Both performance findings reproduced before the fixes. Scale tests now
verify a size-only query for 200 large documents and one handoff lookup
plus two receipt-write statements for 146 completed cases. Concurrent
writers retain contiguous unique sequences and decoded payloads.
- Initial local runs found missing shared exports and OpenAPI route
coverage. These are fixed. Fixtures now respect Linux-only installation,
thrown cross-company denials, and the ES2022 TypeScript target. Rebase
conflicts preserved the onboarding coverage from master.
- CI attempt 1 interrupted Build, e2e shard 7 and six general-test
shards with runner shutdown signals. Attempt 2 recovered the tests but
its [Build
job](https://github.com/paperclipai/paperclip/actions/runs/44212220917/job/134499680425)
also received a shutdown signal and exited 143. No compiler or test
assertion failure was found in those interrupted job logs. The reason
the runners stopped remains unknown. Attempt 3 recovered Build and its
dependent verify gate on the same revision. Earlier interruptions are
not counted as passes.
## Risks
- Additive API only. No migration or existing endpoint response change.
- Helpers must adopt the batch response to gain the tool-call reduction.
They must verify that every requested task is present before treating
the scan as complete. Unreadable tasks are intentionally omitted.
- Split large document batches when the route returns 413. Metadata
remains available without bodies. Concurrency limits are per server
instance and can refuse simultaneous reads with 429; callers retry after
an active read finishes.
- This does not change company-owned helper inventory expiry or cleanup
tests, installed skill permissions, or generic tool batching. It does
not deploy to a tenant.
## Model Used
OpenAI `gpt-6.1-sol` through Codex in T3 Code, with xhigh reasoning,
tool use, and code execution. Context window size was not exposed.
## 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:
1 parent
bf55063567
commit
ea154ce55e
20 files changed
+634
-30
No files matched your search
@@ -0,0 +1,194 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { drizzle } from "drizzle-orm/postgres-js";
|
||||
import { agentApiKeys, assets, chatTaskHandoffs, documents, heartbeatRunEvents, issueDocuments, issues } from "@paperclipai/db";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { startRunnerApiTestServer } from "../../__tests__/helpers/runner-api-server.js";
|
||||
import { documentService } from "../documents.js";
|
||||
import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js";
|
||||
|
||||
const operationId = "GET /api/companies/{companyId}/issue-documents";
|
||||
|
||||
describe("bulk issue documents through native API tools", () => {
|
||||
let server: Awaited<ReturnType<typeof startRunnerApiTestServer>>;
|
||||
const oldSecret = process.env.PAPERCLIP_AGENT_JWT_SECRET;
|
||||
beforeAll(async () => {
|
||||
process.env.PAPERCLIP_AGENT_JWT_SECRET = randomUUID();
|
||||
server = await startRunnerApiTestServer();
|
||||
}, 60000);
|
||||
afterAll(async () => {
|
||||
await server?.close();
|
||||
if (oldSecret === undefined) delete process.env.PAPERCLIP_AGENT_JWT_SECRET;
|
||||
else process.env.PAPERCLIP_AGENT_JWT_SECRET = oldSecret;
|
||||
});
|
||||
|
||||
async function saveCases(completed = false) {
|
||||
const f = await server.fixture({ conversation: completed });
|
||||
const ids = Array.from({ length: 146 }, () => randomUUID());
|
||||
await server.db.insert(issues).values(ids.map(id => ({ id, companyId: f.companyId, title: "Sync case", status: completed ? "done" : "todo", ...(completed ? { parentId: f.issueId } : {}) })));
|
||||
if (completed) await server.db.insert(chatTaskHandoffs).values(ids.map(taskId => ({
|
||||
taskId, companyId: f.companyId, conversationId: f.issueId, agentId: f.agentId, sessionGeneration: 0,
|
||||
})));
|
||||
const rows = await server.db.insert(documents).values(ids.map((id, index) => ({
|
||||
companyId: f.companyId, format: "markdown", title: "Case", latestBody: `Case ${index}: é🧭\n\"quoted\" \\escaped`,
|
||||
}))).returning();
|
||||
await server.db.insert(issueDocuments).values(rows.map((row, index) => ({ companyId: f.companyId, issueId: ids[index], documentId: row.id, key: "sentry-case" })));
|
||||
const authority = new PaperclipRunnerToolAuthority(server.db, { ...f, workspaceRoot: f.workspace });
|
||||
const execute = (tool: string, args: object) => authority.execute({ tool, callId: randomUUID(), arguments: args }) as Promise<any>;
|
||||
const found = await execute("search_api", { query: "bulk issue documents by key", limit: 10 });
|
||||
expect(JSON.stringify(found)).toContain(operationId);
|
||||
const queries: string[] = [];
|
||||
const previousDebug = server.db.$client.options.debug;
|
||||
server.db.$client.options.debug = (_connection, query) => { queries.push(query); };
|
||||
let saved: any;
|
||||
try {
|
||||
saved = await execute("save_api_response", { operationId, pathParams: { companyId: f.companyId }, query: { key: "sentry-case", issueIds: ids.join(",") } });
|
||||
} finally { server.db.$client.options.debug = previousDebug; }
|
||||
expect(saved).toMatchObject({ ok: true, status: 200, artifact: { byteSize: expect.any(Number), sha256: expect.any(String) } });
|
||||
const [asset] = await server.db.select().from(assets).where(eq(assets.id, saved.artifact.artifactId));
|
||||
const object = await server.storage.getObject(f.companyId, asset.objectKey);
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of object.stream) chunks.push(Buffer.from(chunk));
|
||||
return { f, ids, rows, saved, execute, queries, bytes: Buffer.concat(chunks) };
|
||||
}
|
||||
|
||||
it("saves 146 complete documents in one lossless response artifact", async () => {
|
||||
const { ids, rows, saved, bytes } = await saveCases();
|
||||
expect(bytes.length).toBe(saved.artifact.byteSize);
|
||||
expect(createHash("sha256").update(bytes).digest("hex")).toBe(saved.artifact.sha256);
|
||||
const result = JSON.parse(bytes.toString());
|
||||
expect(result.key).toBe("sentry-case");
|
||||
expect(result.items.map((item: any) => item.issueId)).toEqual(ids);
|
||||
expect(result.items.map((item: any) => item.document.body)).toEqual(rows.map(row => row.latestBody));
|
||||
for (const item of result.items) expect(item.document).toMatchObject({ issueId: item.issueId, key: "sentry-case", latestRevisionNumber: expect.any(Number), updatedAt: expect.any(String) });
|
||||
});
|
||||
|
||||
it.skipIf(process.platform !== "linux")("downloads all 146 documents in one native transfer with the saved hash and size", async () => {
|
||||
const { f, saved, execute, bytes } = await saveCases();
|
||||
await execute("download_artifact", { artifactId: saved.artifact.artifactId, byteSize: saved.artifact.byteSize, sha256: saved.artifact.sha256, destination: "cases.json" });
|
||||
expect(await readFile(join(f.workspace, "cases.json"))).toEqual(bytes);
|
||||
});
|
||||
|
||||
it("reads 146 completed cases with one handoff lookup and batched receipt writes", async () => {
|
||||
const { f, ids, queries } = await saveCases(true);
|
||||
expect(queries.filter(query => /from "chat_task_handoffs"/.test(query))).toHaveLength(1);
|
||||
const writes = queries.filter(query => /insert into heartbeat_run_events/.test(query));
|
||||
expect(writes).toHaveLength(2);
|
||||
const events = await server.db.select().from(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, f.runId));
|
||||
const handoffs = events.filter(event => event.eventType === "chat_handoff.completed_read");
|
||||
expect(new Set(handoffs.map(event => event.payload!.taskId))).toEqual(new Set(ids));
|
||||
const children = events.filter(event => event.eventType === "child_task.read");
|
||||
expect(children).toHaveLength(1);
|
||||
expect(new Set(Object.keys(children[0].payload!.children as object))).toEqual(new Set(ids));
|
||||
expect(new Set(events.map(event => event.seq)).size).toBe(events.length);
|
||||
});
|
||||
|
||||
it("returns current revision metadata without bodies and identifies readable tasks with no document", async () => {
|
||||
const f = await server.fixture();
|
||||
const service = documentService(server.db);
|
||||
const first = await service.getIssueDocumentByKey(f.issueId, "notes");
|
||||
await service.upsertIssueDocument({ issueId: f.issueId, key: "notes", format: "markdown", body: "Updated content", baseRevisionId: first!.latestRevisionId });
|
||||
const current = await service.getIssueDocumentByKey(f.issueId, "notes");
|
||||
const receipt = await f.authority.execute({ tool: "call_api", callId: randomUUID(), arguments: {
|
||||
operationId, pathParams: { companyId: f.companyId }, query: { key: " NOTES ", issueIds: [f.blockerId, f.issueId, f.issueId].join(","), includeBody: false },
|
||||
} }) as any;
|
||||
expect(receipt).toMatchObject({ ok: true, data: { key: "notes", items: [
|
||||
{ issueId: f.blockerId, document: null },
|
||||
{ issueId: f.issueId, document: { latestRevisionId: current!.latestRevisionId, latestRevisionNumber: 2 } },
|
||||
] } });
|
||||
expect(receipt.data.items[1].document).not.toHaveProperty("body");
|
||||
});
|
||||
|
||||
it("omits private, hidden, foreign and missing tasks without disclosing which exist", async () => {
|
||||
const f = await server.fixture();
|
||||
const foreign = await server.fixture();
|
||||
const privateId = randomUUID(), hiddenId = randomUUID(), missingId = randomUUID();
|
||||
await server.db.insert(issues).values([
|
||||
{ id: privateId, companyId: f.companyId, title: "Private", visibility: "private", status: "todo" },
|
||||
{ id: hiddenId, companyId: f.companyId, title: "Hidden", hiddenAt: new Date(), status: "todo" },
|
||||
]);
|
||||
for (const id of [privateId, hiddenId]) await documentService(server.db).upsertIssueDocument({ issueId: id, key: "notes", format: "markdown", body: "Never leak" });
|
||||
const result = await f.authority.execute({ tool: "call_api", callId: randomUUID(), arguments: {
|
||||
operationId, pathParams: { companyId: f.companyId }, query: { key: "notes", issueIds: [f.issueId, privateId, hiddenId, foreign.issueId, missingId].join(",") },
|
||||
} }) as any;
|
||||
expect(result).toMatchObject({ ok: true, data: { items: [{ issueId: f.issueId, document: { body: "Document verification code: silver-wren." } }] } });
|
||||
expect(JSON.stringify(result)).not.toContain("Never leak");
|
||||
await expect(f.authority.execute({ tool: "save_api_response", callId: randomUUID(), arguments: {
|
||||
operationId, pathParams: { companyId: foreign.companyId }, query: { key: "notes", issueIds: foreign.issueId },
|
||||
} })).rejects.toMatchObject({ status: 403 });
|
||||
const anonymous = await fetch(`${server.apiUrl}/api/companies/${f.companyId}/issue-documents?key=notes&issueIds=${f.issueId}`);
|
||||
expect(anonymous.status).toBe(401);
|
||||
});
|
||||
|
||||
it("enforces company boundaries and denies task bridge keys on the HTTP route", async () => {
|
||||
const f = await server.fixture({ connectionScenario: "fresh", disableWakeOnDemand: true });
|
||||
const token = `pcp_fixture_${randomUUID()}`;
|
||||
const [key] = await server.db.insert(agentApiKeys).values({
|
||||
companyId: f.companyId, agentId: f.agentId, name: "Batch fixture",
|
||||
keyHash: createHash("sha256").update(token).digest("hex"), responsibleUserId: f.responsibleUserId,
|
||||
}).returning();
|
||||
const get = (companyId: string) => fetch(`${server.apiUrl}/api/companies/${companyId}/issue-documents?key=notes&issueIds=${f.issueId}`, { headers: { Authorization: `Bearer ${token}` } });
|
||||
expect((await get(f.companyId)).status).toBe(200);
|
||||
expect((await get(f.foreignCompanyId)).status).toBe(403);
|
||||
await server.db.update(agentApiKeys).set({ scopeConfig: { kind: "task_bridge", projectId: f.projectId } }).where(eq(agentApiKeys.id, key.id));
|
||||
expect((await get(f.companyId)).status).toBe(403);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{}, { key: "notes" }, { key: "notes", issueIds: "" }, { key: "notes", issueIds: "not-a-uuid" },
|
||||
{ key: "notes", issueIds: Array.from({ length: 201 }, () => randomUUID()).join(",") },
|
||||
{ key: "../notes", issueIds: randomUUID() }, { key: "notes", issueIds: randomUUID(), includeBody: "yes" },
|
||||
{ key: "notes", issueIds: randomUUID(), breakGlass: true },
|
||||
])("rejects invalid or unbounded query %#", async query => {
|
||||
const f = await server.fixture();
|
||||
const result = await f.authority.execute({ tool: "call_api", callId: randomUUID(), arguments: { operationId, pathParams: { companyId: f.companyId }, query } }) as any;
|
||||
expect(result).toMatchObject({ ok: false, status: 400 });
|
||||
});
|
||||
|
||||
it("rejects an oversized batch without saving a partial artifact, while metadata remains readable", async () => {
|
||||
const f = await server.fixture();
|
||||
const document = await documentService(server.db).getIssueDocumentByKey(f.issueId, "notes");
|
||||
// Escaping expands these bodies in JSON. The cap must use wire bytes.
|
||||
await server.db.update(documents).set({ latestBody: "\"".repeat(4 * 1024 * 1024) }).where(eq(documents.id, document!.id));
|
||||
const query = { key: "notes", issueIds: f.issueId };
|
||||
const result = await f.authority.execute({ tool: "save_api_response", callId: randomUUID(), arguments: { operationId, pathParams: { companyId: f.companyId }, query } }) as any;
|
||||
expect(result).toMatchObject({ ok: false, status: 413 });
|
||||
expect(result).not.toHaveProperty("artifact");
|
||||
const metadata = await f.authority.execute({ tool: "call_api", callId: randomUUID(), arguments: { operationId, pathParams: { companyId: f.companyId }, query: { ...query, includeBody: false } } }) as any;
|
||||
expect(metadata).toMatchObject({ ok: true, data: { items: [{ issueId: f.issueId, document: { latestRevisionId: document!.latestRevisionId } }] } });
|
||||
expect(metadata.data.items[0].document).not.toHaveProperty("body");
|
||||
});
|
||||
|
||||
it("rejects many large documents using a size-only query before loading any bodies", async () => {
|
||||
const f = await server.fixture();
|
||||
const ids = Array.from({ length: 200 }, () => randomUUID());
|
||||
await server.db.insert(issues).values(ids.map(id => ({ id, companyId: f.companyId, title: "Large case", status: "todo" })));
|
||||
const rows = await server.db.insert(documents).values(ids.map(() => ({ companyId: f.companyId, latestBody: sql<string>`repeat('x', 524288)` }))).returning({ id: documents.id });
|
||||
await server.db.insert(issueDocuments).values(rows.map((row, index) => ({ companyId: f.companyId, issueId: ids[index], documentId: row.id, key: "sentry-case" })));
|
||||
const queries: string[] = [];
|
||||
const measured = drizzle(server.db.$client, { schema: server.db._.fullSchema, logger: { logQuery: query => queries.push(query) } }) as typeof server.db;
|
||||
let status: number | undefined;
|
||||
try { await documentService(measured).getIssueDocumentsByKey(f.companyId, ids, "sentry-case"); }
|
||||
catch (error) { status = (error as { status: number }).status; }
|
||||
expect(status).toBe(413);
|
||||
const reads = queries.filter(query => /^select /i.test(query));
|
||||
expect(reads).toHaveLength(1);
|
||||
expect(reads[0]).toContain("octet_length");
|
||||
expect(reads[0].split(" from ")[0]).not.toContain('"documents"."id"');
|
||||
const result = await f.authority.execute({ tool: "save_api_response", callId: randomUUID(), arguments: {
|
||||
operationId, pathParams: { companyId: f.companyId }, query: { key: "sentry-case", issueIds: ids.join(",") },
|
||||
} }) as any;
|
||||
expect(result).toMatchObject({ ok: false, status: 413 });
|
||||
expect(result).not.toHaveProperty("artifact");
|
||||
// Bodies alone fit, but their metadata pushes the response over budget.
|
||||
// The incremental JSON builder must refuse this before joining a response.
|
||||
await server.db.update(documents).set({ latestBody: "x".repeat(524000) }).where(eq(documents.companyId, f.companyId));
|
||||
const nearLimit = await f.authority.execute({ tool: "save_api_response", callId: randomUUID(), arguments: {
|
||||
operationId, pathParams: { companyId: f.companyId }, query: { key: "sentry-case", issueIds: ids.slice(0, 16).join(",") },
|
||||
} }) as any;
|
||||
expect(nearLimit).toMatchObject({ ok: false, status: 413 });
|
||||
expect(nearLimit).not.toHaveProperty("artifact");
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
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";
|
||||
import { appendHeartbeatRunEventBatch } from "../heartbeat-run-events.js";
|
||||
|
||||
export interface NativeChildCompletionRecipient {
|
||||
companyId: string;
|
||||
@@ -17,12 +17,25 @@ export async function recordChildTaskRead(db: Db, input: {
|
||||
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 }])) } });
|
||||
await recordChildTaskReads(db, { ...input, children: completed });
|
||||
}
|
||||
|
||||
/** Group completed children by parent, then persist the existing receipt shape in one statement. */
|
||||
export async function recordChildTaskReads(db: Db, input: {
|
||||
companyId: string; agentId: string; runId: string;
|
||||
children: ReadonlyArray<{ id: string; parentId: string | null; status: string; updatedAt: Date; lastStatusDecisionId?: string | null }>;
|
||||
}): Promise<void> {
|
||||
const groups = new Map<string, Record<string, unknown>>();
|
||||
for (const child of input.children) {
|
||||
if (!child.parentId || child.status !== "done") continue;
|
||||
const children = groups.get(child.parentId) ?? {};
|
||||
children[child.id] = { status: child.status, updatedAt: child.updatedAt.toISOString(), statusDecisionId: child.lastStatusDecisionId ?? null };
|
||||
groups.set(child.parentId, children);
|
||||
}
|
||||
await appendHeartbeatRunEventBatch(db, [...groups].map(([parentIssueId, children]) => ({
|
||||
companyId: input.companyId, runId: input.runId, agentId: input.agentId,
|
||||
eventType: CHILD_TASK_READ_EVENT, stream: "system", level: "info", payload: { parentIssueId, children },
|
||||
})));
|
||||
}
|
||||
|
||||
/** New child results belong to a fresh parent turn, including across a Done claim. */
|
||||
|
||||
Reference in new issue
Block a user