fix(antigravity): give the follow-up after a swarm its result, and say each thing once in the thread (#22893)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A task thread shows an agent's runs, and each new run starts from
the task's saved context
> - A second hands-on check of Google Antigravity `/swarm` runs (after
#22886) still found gaps
> - The first ordinary follow-up after a swarm was slow: it spent
minutes searching the instance's run logs to learn what the swarm did
> - The thread also showed each file twice, lost the "Swarm" note after
a reload, and read "Swarm Swarm started…"
> - This pull request gives the next run the swarm's result in its
opening context and removes the prompt's pointer to run records, and it
fixes the four thread problems
> - The benefit is a faster follow-up after a swarm and a thread that
says each thing once

## Linked Issues or Issue Description

Refs #22886

**What happened?**
1. After a finished `/swarm`, the ordinary follow-up "append three to
v1.txt" took 4 min 6 s (an earlier one took 5.5 min). The agent read the
server's raw run log of the swarm run with about 20 shell commands,
searched the instance folder, and listed processes. Other follow-ups
took 41 s and 105 s.
2. Each file showed twice: the run's file card, and a second card under
the final reply (from the reply's "Download: v1.txt" link). This also
happened on the ordinary follow-up.
3. The "Swarm" note on the user's message showed while live, but not
after a page reload.
4. Swarm activity rows read "Swarm Swarm started in the task folder…",
with the word twice.

**Expected behavior**
1. The follow-up starts with what the swarm did, so it has no reason to
search for it.
2. Each file shows once per run, as the run's file card.
3. The "Swarm" note shows after a reload.
4. A swarm row reads its sentence once.

**Steps to reproduce**
1. Send `/swarm Create v1.txt containing "one" and v2.txt containing
"two", one helper per file, then verify both.` to a Google Antigravity
agent.
2. When it finishes, look at the files and the activity rows, then
reload the page.
3. Send the ordinary follow-up `append three to v1.txt` and time it.
4. Put another task in Plan mode and send `/swarm do something`.

## What Changed

- Follow-up context (cause of item 1). A swarm runs in the Antigravity
CLI, and an ordinary turn runs on the registry route. The ordinary route
cannot reopen the swarm's conversation, so the Runner refuses the saved
session and the server starts a fresh one. That fresh session gets the
same wake prompt as any other turn. Before this change, its only record
of the swarm was the task continuation summary, and that summary listed
no files ("No file or route paths were detected"; the path detector only
knows repository folders such as `server/`). It also gave three run ids
and said "Detailed shell/tool commands remain in the run log and
transcript." The agent followed that line: its first searches matched
the swarm's run id, and an earlier follow-up searched for
`transcript*.jsonl` files. An ordinary follow-up after an ordinary turn
gets the same prompt, but it resumes its own conversation, so it already
knows what it did.
- `issue-continuation-summary.ts` (shared by every harness): a new
"Files Delivered" section lists, by name, the files the run handed in as
deliverables (applied or duplicate receipts), newest first, and keeps
earlier runs' names. These names are kept apart from "Files / Routes
Touched", because a deliverable's name is not always its path. The run's
own checks are listed, read through the shared accepted-result reader.
The summary contains no run ids, adapter names or log locations. The
"Commands Run" section is removed: it held only the run id and the log
pointer. The summary reaches the next turn through the existing
mechanism (the wake prompt's "Issue continuation summary" and the
continuation evidence).
- Server: `GET /issues/:id/recent-comments` and both chat bootstrap
routes now add the swarm marker with the same shared rule
(`withAntigravitySwarmMarkers`) as the comment list, the single comment
and the POST response. A cold task page reads this recent window, so the
marker was missing after a reload.
- UI: a reply does not show a second card for a file that its own run
already shows as a file card. The reply text and its links do not
change. A later run's reply that links the same file still shows the
file.
- UI: a swarm progress row shows its sentence without the "Swarm" label.
A failed or stopped row keeps its label and marker. Live and settled
rows use the same rule.

Not changed, by investigation:
- "Check passed cat v1.txt one\nthree" and "verifier check on swarm
board #6": the model wrote both strings in its `paperclip_finish` call.
The Runner's first record of the result already holds the literal
backslash and the board number, so this is model text, not Paperclip's
presentation.
- The inline "Download: v1.txt" links in the reply are the model's own
words, so they stay.
- No read-confinement policy is added. The agent finds the instance
folder from its working directory, not from the prompt.
- A refused send still shows its reason twice (inline under the composer
and as a toast). Each attempt to remove the toast missed a send path,
which could leave a refusal with no visible reason. A repeated reason is
better than a missing one, so this PR does not change the toast.

## Verification

- Red/green `server/src/__tests__/issue-continuation-summary.test.ts`: a
swarm's accepted result (from a live run, with ids replaced) is built
into the summary and rendered into the follow-up's wake prompt. The
prompt contains the hand-in summary, `v1.txt` and `v2.txt` under "Files
Delivered" (one with a different content reference and a duplicate
receipt), and the verifier check. A later run lists its own delivered
file first. A full path list still takes the latest run's path first. It
contains no run id, "run log", "transcript", attachment path, digest or
adapter name. A later run keeps the files listed. This failed before the
change.
- Red/green `server/src/__tests__/issue-chat-bootstrap-routes.test.ts`
(embedded Postgres): for an ordinary task and a conversation, a recorded
`/swarm` request carries `nativeCommand: "swarm"` on `GET /comments`,
`GET /comments/:id`, `GET /recent-comments`, `GET
/issues/:ref/chat-bootstrap` and the batch chat bootstrap. It failed on
`recent-comments` before the change.
- Red/green `ui/src/components/TaskChatThread.test.tsx`: a reply that
links its run's file shows no second card; a later run's reply still
shows it. It failed before the change.
- Red/green `ui/src/components/task-chat/antigravity-thread.test.tsx`:
the live swarm fixture's rows read "Swarm started in the task folder…"
(no doubled word), and live rows equal settled rows.
- Focused suites: UI `TaskChatThread.test.tsx` and
`src/components/task-chat` (925 tests), server bootstrap routes (19
tests) and continuation summary (7 tests) pass. UI and server typechecks
pass.
- Not proved without a live run: that the next follow-up after a swarm
is faster. The tests prove the opening input; the agent's behavior with
that input needs a live Antigravity run.

## Risks

- The continuation summary wording changes for every harness that runs
on a task (every adapter whose finished run refreshes the summary, not
only Antigravity): no run ids, no adapter name, no "Commands Run"
section, and a new "Files Delivered" section when the run registered
deliverables. Nothing in the code parses those lines. Older saved
summaries keep their text until the next run refreshes them.
- One extra indexed activity-log query for each recent-comments or
chat-bootstrap read (the same query the comment list already runs). The
bootstrap budget test still passes.
- The second-card rule matches only a file whose card belongs to the
same run as the reply.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in 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-25 02:50:44 -06:00
1 parent 3fbf872d9e
commit 5347c01de5
16 files changed
+234 -44

No files matched your search

@@ -10,6 +10,7 @@ import { issueRoutes } from "../routes/issues.js";
import { activityRoutes } from "../routes/activity.js";
import { agentRoutes } from "../routes/agents.js";
import { errorHandler } from "../middleware/index.js";
import { recordAntigravitySwarmRequest } from "../services/antigravity-swarm.js";
import { describeEmbeddedPostgres, seedCompanyWithBoardAccess, useEmbeddedPostgres, type BoardActor } from "./helpers/route-test-harness.js";
describeEmbeddedPostgres("task chat bootstrap", () => {
@@ -140,6 +141,29 @@ describeEmbeddedPostgres("task chat bootstrap", () => {
expect(res.body.items[0].recentComments).not.toHaveProperty("oldestCommentId");
});
it("marks a recorded /swarm request on every path that returns comments to the thread", async () => {
const f = await seedCompanyWithBoardAccess(ctx.db, "Swarm marker");
const server = app(f.actor);
for (const conversation of [false, true]) {
const task = await seedTask(f.companyId, { userId: f.userId, conversation });
const requested = task.commentIds[6]!;
await recordAntigravitySwarmRequest(ctx.db, { companyId: f.companyId, issueId: task.issueId, commentId: requested, userId: f.userId });
const marks = (comments: Array<{ id: string; nativeCommand?: string }>) =>
comments.filter((comment) => comment.nativeCommand === "swarm").map((comment) => comment.id);
const list = await request(server).get(`/api/issues/${task.issueId}/comments`).expect(200);
expect(marks(list.body), "comments").toEqual([requested]);
const one = await request(server).get(`/api/issues/${task.issueId}/comments/${requested}`).expect(200);
expect(one.body.nativeCommand, "comment").toBe("swarm");
const recent = await request(server).get(`/api/issues/${task.issueId}/recent-comments`).expect(200);
expect(marks(recent.body.comments), "recent-comments").toEqual([requested]);
const single = await request(server).get(`/api/issues/${task.issueId}/chat-bootstrap`).expect(200);
expect(marks(single.body.recentComments.comments), "chat-bootstrap").toEqual([requested]);
const batch = await request(server).get(url(f.companyId)).query({ ids: task.issueId }).expect(200);
expect(marks(batch.body.items[0].recentComments.comments), "batch chat-bootstrap").toEqual([requested]);
}
});
it("follows request order with mixed UUIDs and identifiers, and reads a task named twice once per ref", async () => {
const f = await seedCompanyWithBoardAccess(ctx.db, "Order");
const a = await seedTask(f.companyId, { userId: f.userId });
@@ -5,6 +5,7 @@ import {
continuationSummaryParksExecutor,
extractContinuationSummaryNextAction,
} from "../services/issue-continuation-summary.js";
import { renderPaperclipWakePrompt } from "@paperclipai/adapter-utils/server-utils";
describe("issue continuation summaries", () => {
it("builds bounded issue-local handoff context with required sections", () => {
@@ -50,14 +51,74 @@ describe("issue continuation summaries", () => {
expect(body).toContain("## Acceptance Criteria");
expect(body).toContain("- Summary is issue-local");
expect(body).toContain("## Recent Concrete Actions");
expect(body).toContain("Run `run-1` finished with status `succeeded`");
expect(body).toContain("The latest run finished with status `succeeded`");
expect(body).toContain("`server/src/services/heartbeat.ts`");
expect(body).toContain("## Commands Run");
expect(body).toContain("## Blockers / Decisions");
expect(body).toContain("## Next Action");
expect(body.length).toBeLessThanOrEqual(ISSUE_CONTINUATION_SUMMARY_MAX_BODY_CHARS);
});
it("opens the next session after a swarm with what the swarm did, never with where Paperclip keeps its records", () => {
const swarmRunId = "6a1f0c2e-0000-4000-8000-00000000a001";
const deliverable = (filename: string, attachmentId: string, contentRef = filename, disposition = "applied") => ({
operationId: "register_deliverable",
input: { title: `${filename} deliverable`, filename, contentRef, contentType: "text/plain", byteSize: 3, sha256: "0".repeat(64) },
result: { disposition, attachmentId, contentPath: `/api/attachments/${attachmentId}/content` },
});
const body = buildContinuationSummaryMarkdown({
issue: { id: "issue-1", identifier: "ANT-1", title: "UI check", description: "Please wait for the request in a comment.",
status: "done", priority: "medium" },
run: {
id: swarmRunId, status: "succeeded", error: null, finishedAt: new Date("2026-11-25T07:49:36.000Z"),
resultJson: {
summary: "Successfully created v1.txt containing \"one\" and v2.txt containing \"two\" using dedicated swarm helpers per file, and verified both files.",
acceptedResult: { verification: [{ status: "passed", commandOrCheck: "verifier check",
detail: "Both files verified successfully: v1.txt exists and contains \"one\", and v2.txt exists and contains \"two\"." }] },
semanticToolReceipts: {
"register-v1-txt": deliverable("v1.txt", "6a1f0c2e-0000-4000-8000-00000000b001"),
"register-v2-txt": deliverable("v2.txt", "6a1f0c2e-0000-4000-8000-00000000b002", "out/v2.txt", "duplicate"),
},
},
},
agent: { id: "agent-1", name: "Swarm Agent", adapterType: "paperclip_runner" },
});
const prompt = renderPaperclipWakePrompt({
reason: "issue_reopened_via_comment",
issue: { id: "issue-1", identifier: "ANT-1", title: "UI check", status: "in_progress" },
comments: [{ id: "comment-1", body: "append three to v1.txt" }],
fallbackFetchNeeded: false,
continuationSummary: { key: "continuation-summary", body },
});
expect(prompt).toContain("Successfully created v1.txt containing \"one\" and v2.txt containing \"two\"");
expect(prompt).toContain("## Files Delivered\n\n- `v1.txt`\n- `v2.txt`");
expect(prompt).toContain("## Files / Routes Touched\n\n- No file or route paths were detected");
expect(prompt).toContain("Check verifier check: passed (Both files verified successfully");
expect(prompt).not.toContain(swarmRunId);
expect(prompt).not.toMatch(/run log|transcript|\/api\/attachments|[0-9a-f]{64}|paperclip_runner/);
const next = buildContinuationSummaryMarkdown({
issue: { id: "issue-1", identifier: "ANT-1", title: "UI check", description: null, status: "done", priority: "medium" },
run: { id: "run-next", status: "succeeded", error: null, resultJson: { summary: "Appended three.",
semanticToolReceipts: { "register-v3-txt": deliverable("v3.txt", "6a1f0c2e-0000-4000-8000-00000000b003") } } },
agent: { id: "agent-1", name: "Swarm Agent", adapterType: "paperclip_runner" },
previousSummaryBody: body,
});
expect(next).toContain("## Files Delivered\n\n- `v3.txt`\n- `v1.txt`\n- `v2.txt`");
});
it("lists the latest run's paths before older ones once the list is full", () => {
const older = Array.from({ length: 12 }, (_, index) => `- \`server/src/old-${index}.ts\``).join("\n");
const body = buildContinuationSummaryMarkdown({
issue: { id: "issue-1", identifier: "PAP-1", title: "Paths", description: null, status: "in_progress", priority: "medium" },
run: { id: "run-1", status: "succeeded", error: null, resultJson: { summary: "Updated server/src/new.ts." } },
agent: { id: "agent-1", name: "Agent", adapterType: "codex_local" },
previousSummaryBody: `# Continuation Summary\n\n## Files / Routes Touched\n\n${older}\n`,
});
expect(body).toContain("## Files / Routes Touched\n\n- `server/src/new.ts`\n- `server/src/old-0.ts`");
expect(body).not.toContain("old-11.ts");
});
it("uses failure state to point the next run at the error", () => {
const body = buildContinuationSummaryMarkdown({
issue: {
+3 -2
View File
@@ -17385,7 +17385,7 @@ export function issueRoutes(
}) {
if (issue.conversationAgentId) {
const recent = await svc.listComments(issue.id, { companyId: issue.companyId, order: "desc", limit: 21 });
const comments = recent.slice(0, 20);
const comments = await withAntigravitySwarmMarkers(db, issue.companyId, issue.id, recent.slice(0, 20));
return runRedactions.redactForIssue(issue.companyId, issue.id, {
comments,
latestCommentId: comments[0]?.id ?? null,
@@ -17400,7 +17400,8 @@ export function issueRoutes(
? Promise.resolve([])
: svc.listComments(issue.id, { companyId: issue.companyId, order: "asc", limit: 1, humanOnly: true }),
]);
const comments = [...new Map([...firstInstruction, ...human, ...recent.slice(0, 4)].map((comment) => [comment.id, comment])).values()];
const comments = await withAntigravitySwarmMarkers(db, issue.companyId, issue.id,
[...new Map([...firstInstruction, ...human, ...recent.slice(0, 4)].map((comment) => [comment.id, comment])).values()]);
const included = new Set(comments.map((comment) => comment.id));
return runRedactions.redactForIssue(issue.companyId, issue.id, {
comments,
+7 -2
View File
@@ -353,7 +353,12 @@ function readAcceptedSemanticSummary(resultJson: Record<string, unknown>) {
return null;
}
function semanticResultCandidates(resultJson: Record<string, unknown>) {
export function isCommittedToolReceiptResult(result: unknown): boolean {
const disposition = record(result).disposition;
return disposition === "applied" || disposition === "duplicate";
}
export function semanticResultCandidates(resultJson: Record<string, unknown>) {
return [
record(resultJson.nativeResult),
record(resultJson.acceptedResult),
@@ -782,7 +787,7 @@ export function findHeartbeatRunCompletionComment<T extends { id: string; presen
receiptRecord.operationId === "register_deliverable" &&
typeof receiptResult.attachmentId === "string" &&
receiptResult.commandId === `deliverable-prepared:${receiptResult.attachmentId}` &&
["applied", "duplicate"].includes(String(receiptResult.disposition)) &&
isCommittedToolReceiptResult(receiptResult) &&
Array.isArray(receiptResult.entityRefs)
) {
// File preparation binds an attachment to a generated comment. That
@@ -3,7 +3,7 @@ import type { Db } from "@paperclipai/db";
import { documents, issueDocuments, issues } from "@paperclipai/db";
import { ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY, readRunFailureCause, withoutSqlStatementText, type SourceTrustMetadata } from "@paperclipai/shared";
import { documentService } from "./documents.js";
import { summarizeRunErrorForModel } from "./heartbeat-run-summary.js";
import { isCommittedToolReceiptResult, semanticResultCandidates, summarizeRunErrorForModel } from "./heartbeat-run-summary.js";
export { ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY };
export const ISSUE_CONTINUATION_SUMMARY_TITLE = "Continuation Summary";
@@ -70,6 +70,38 @@ function readResultSummary(resultJson: Record<string, unknown> | null | undefine
);
}
function asRecord(value: unknown): Record<string, unknown> | null {
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : null;
}
function readDeliveredFiles(resultJson: Record<string, unknown> | null | undefined): string[] {
const receipts = asRecord(resultJson?.semanticToolReceipts);
if (!receipts) return [];
const files = new Set<string>();
for (const value of Object.values(receipts)) {
const receipt = asRecord(value);
if (receipt?.operationId !== "register_deliverable" || !isCommittedToolReceiptResult(receipt.result)) continue;
const filename = asNonEmptyString(asRecord(receipt.input)?.filename);
if (filename && filename.length <= 200 && !/[`\u0000-\u001f]/.test(filename)) files.add(filename);
if (files.size >= 12) break;
}
return [...files];
}
function readVerification(resultJson: Record<string, unknown> | null | undefined): string[] {
const checks = semanticResultCandidates(resultJson ?? {}).map((candidate) => candidate.verification).find(Array.isArray);
if (!checks) return [];
return checks.slice(0, 6).flatMap((value) => {
const check = asRecord(value);
const name = asNonEmptyString(check?.commandOrCheck);
const status = asNonEmptyString(check?.status);
if (!name || !status) return [];
const detail = asNonEmptyString(check?.detail);
const oneLine = (text: string, max: number) => truncateText(text.replace(/\s+/g, " "), max).replace(/\n/g, " ");
return [`Check ${oneLine(name, 160)}: ${status}${detail ? ` (${oneLine(detail, 240)})` : ""}.`];
});
}
function extractMarkdownSection(markdown: string | null | undefined, heading: string) {
if (!markdown) return null;
const escaped = heading.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -150,13 +182,17 @@ export function buildContinuationSummaryMarkdown(input: {
const modelError = summarizeRunErrorForModel(
run.error ? withoutSqlStatementText(run.error, readRunFailureCause(run.resultJson)) : run.error, terminalFailureCategory);
const recentActions = [
`Run \`${run.id}\` finished with status \`${run.status}\`${run.finishedAt ? ` at ${run.finishedAt.toISOString()}` : ""}.`,
`The latest run finished with status \`${run.status}\`${run.finishedAt ? ` at ${run.finishedAt.toISOString()}` : ""}.`,
resultSummary ? truncateText(resultSummary, SUMMARY_SECTION_MAX_CHARS) : "No adapter-provided result summary was captured for this run.",
...readVerification(run.resultJson),
];
if (modelError) {
recentActions.push(`Latest run error${run.errorCode ? ` (${run.errorCode})` : ""}: ${truncateText(modelError, 500)}`);
}
const previousDelivered = [...(extractMarkdownSection(input.previousSummaryBody, "Files Delivered") ?? "")
.matchAll(/^[-*]\s+`([^`\n]+)`\s*$/gm)].map((match) => match[1]!);
const delivered = [...new Set([...readDeliveredFiles(run.resultJson), ...previousDelivered])].slice(0, 12);
const paths = extractPathCandidates(resultSummary, run.stdoutExcerpt, run.stderrExcerpt, input.previousSummaryBody);
const objective = extractMarkdownSection(issue.description, "Objective") ?? issue.description?.trim() ?? "No objective captured.";
const acceptanceCriteria = extractMarkdownSection(issue.description, "Acceptance Criteria") ?? "No explicit acceptance criteria captured.";
@@ -170,8 +206,7 @@ export function buildContinuationSummaryMarkdown(input: {
`- Status: ${issue.status}`,
`- Priority: ${issue.priority}`,
`- Current mode: ${mode}`,
`- Last updated by run: ${run.id}`,
`- Agent: ${agent.name} (${agent.adapterType ?? "unknown"})`,
`- Agent: ${agent.name}`,
"",
"## Objective",
"",
@@ -189,16 +224,7 @@ export function buildContinuationSummaryMarkdown(input: {
"",
bulletList(paths.map((path) => `\`${path}\``), "No file or route paths were detected in the captured run summary."),
"",
"## Commands Run",
"",
bulletList(
[
`Heartbeat run \`${run.id}\` invoked adapter \`${agent.adapterType ?? "unknown"}\`.`,
"Detailed shell/tool commands remain in the run log and transcript.",
],
"No command metadata captured.",
),
"",
...(delivered.length > 0 ? ["## Files Delivered", "", bulletList(delivered.map((name) => `\`${name}\``), ""), ""] : []),
"## Blockers / Decisions",
"",
bulletList(
@@ -3,6 +3,7 @@ import { and, eq } from "drizzle-orm";
import { createHash } from "node:crypto";
import { assets, companies, completionContracts, documents, documentRevisions, heartbeatRuns, issueDocuments, issueAttachments, issues, issueThreadInteractions, issueWorkProducts, mcpAttachmentUploads, dotRunnerAssignments, type Db } from "@paperclipai/db";
import { projectHumanInteractionResponse } from "../execution-continuation.js";
import { isCommittedToolReceiptResult } from "../heartbeat-run-summary.js";
export class NativeDeliverableEvidenceError extends Error {}
@@ -42,7 +43,7 @@ async function hasCurrentPublicationReceipt(db: Db, companyId: string, receipts:
const receipt = record(value);
const input = record(receipt.input);
const result = record(receipt.result);
if ((result.disposition !== "applied" && result.disposition !== "duplicate") ||
if (!isCommittedToolReceiptResult(result) ||
!Array.isArray(result.entityRefs) || result.entityRefs[0] !== attachment.id) continue;
if (receipt.operationId === "publish_external_deliverable" && result.source === "authenticated_upload"
&& result.commandId === `deliverable-uploaded:${attachment.id}` && typeof input.uploadId === "string"
@@ -324,7 +325,7 @@ export async function publishedTaskDocuments(db: Db, binding: { companyId: strin
const saved = await (binding.lockSources ? query.for("share", { of: [issueDocuments, documents, documentRevisions, heartbeatRuns], noWait: true }) : query);
return saved.filter(document => Object.values(record(document.resultJson?.semanticToolReceipts)).some(value => {
const receipt = record(value), result = record(receipt.result), published = record(result.document);
return receipt.operationId === "write_document" && ["applied", "duplicate"].includes(String(result.disposition))
return receipt.operationId === "write_document" && isCommittedToolReceiptResult(result)
&& published.id === document.id && published.latestRevisionId === document.revisionId;
})).map(({ id, revisionId, key, issuePrefix, issueIdentifier }) => ({ id, revisionId, key,
href: `/${encodeURIComponent(issuePrefix)}/issues/${encodeURIComponent(issueIdentifier ?? binding.issueId)}#document-${encodeURIComponent(key)}` }));