feat(connections): let users delete data read through a connection (#22010)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents call connected apps, such as Google Workspace, through
Paperclip's tool gateway
> - Paperclip saves part of each tool result, approval previews, app
views and the full run transcripts that contain tool output
> - No user action deleted this data. Removing the connection left it in
place
> - Google's restricted-scope review requires that users can delete the
data an app obtained, and that the privacy policy says how
> - This pull request adds "Delete data read through this connection"
for any connection, on the connection's page and as an option when you
remove it
> - The benefit is that the picker text ("They stay there until you
delete them") is now true, and the privacy policy can link to a help
page

## Linked Issues or Issue Description

**Subsystem affected**

Connections (tool gateway audit tables, run logs, run events) and the
Connectors UI.

**Problem or motivation**

Paperclip stores content from a connection's tool calls in several
places and gives users no way to delete it:

- `tool_invocations.arguments_summary/result_summary` and
`tool_call_events.arguments_summary/request_summary/result_summary` keep
the first ~4,000 characters of each redacted value
(`summarizeToolValue`, `tool-access-policy.ts` `redactArguments`). No
retention limit.
- `tool_action_requests` keeps `canonical_arguments_summary`,
`preview_markdown` and `signed_arguments`. The linked approval card
(`issue_thread_interactions`) keeps copies in `payload.detailsMarkdown`,
`payload.toolAction.previewMarkdown`,
`payload.toolAction.argumentsSummaryJson` and
`result.toolAction.resultSummary`.
- `tool_mcp_app_views` keeps `tool_input` and `tool_result` for MCP app
views.
- Run transcripts hold full tool output: the run log (`local_file` with
an optional S3 mirror, or `s3_segments`/`s3_archive` object journals),
`heartbeat_run_events.message/payload`, and
`heartbeat_runs.stdout_excerpt/stderr_excerpt`. Neither run-log store
had a delete path.
- Connection removal (`removal.ts`) archives the connection and revokes
credentials. It deletes no content.

**Proposed solution**

A durable, resumable, company-scoped deletion request per connection.
See "Design" below.

**Alternatives considered**

- Delete synchronously in the request. Rejected: an interrupted request
leaves partial state that needs a person to retry it.
- Delete only the run events that mention the connection. Rejected: tool
output also reaches the model's later messages, so the safe unit is the
whole run transcript.
- Delete the audit rows. Rejected: counts, outcomes and hashes feed the
activity history and usage counts.

## Design

**Rule.** The job never drops a reference to content it has not
confirmed deleted. It is marked complete, and writes the
`tool_connection.content_deleted` activity entry, only after every step
succeeded. A step that cannot confirm its work throws. The request then
stays pending, the UI says "Paperclip keeps trying until it finishes",
and the worker retries it.

**Store inventory.** Every place that stores tool arguments, results or
previews. I found them from `summarizeToolValue`, `redactArguments`,
`writeAudit`, and every column or JSON field named like summary,
preview, arguments, result, toolInput or toolResult.

| Store | Content | Cleared by this PR | Proof |
| --- | --- | --- | --- |
| `tool_invocations.arguments_summary`, `result_summary`, `progress` |
Redacted request/result preview, provider progress | Yes: `summary`
becomes `""` with `contentDeletedAt`; `progress` null; size and sha256
kept | content-deletion test 1 |
| `tool_call_events.arguments_summary`, `request_summary`,
`result_summary` | Same previews | Yes, same | test 1 |
| `tool_access_audit_events.details.argumentsSummary` (`writeAudit`) |
Argument preview | Yes, same; decision, ids, size, hash kept | test 1 |
| `tool_action_requests.canonical_arguments_summary`,
`preview_markdown`, `signed_arguments` | Approval preview and arguments
| Yes, for settled requests | test 1, card retry test |
| Approval card in `issue_thread_interactions`:
`payload.detailsMarkdown`, `payload.toolAction.previewMarkdown`,
`payload.toolAction.argumentsSummaryJson`,
`result.toolAction.resultSummary` | Approval preview, arguments,
executed result | Yes. Cards are found from every settled request of a
batch, in the same transaction | test 1, card retry test |
| `heartbeat_runs.context_snapshot` and `agent_wakeup_requests.payload`
(`toolAction(s)[].resultSummary`,
`paperclipAgentMessage.untrustedToolResults[].resultSummary`) | Approved
action result delivered to the agent | Yes, for settled runs and settled
wakes | test 1 |
| `tool_mcp_app_views.tool_input`, `tool_result`, `model_context` | App
view input, result, shared context | Yes: rows deleted | test 1 |
| Run log: object journal, archive journal, original `local_file` log
and its legacy S3 mirror | Full transcript | Yes, every copy, for each
settled run that called the connection or received an approved result |
run-log-store tests, test 1 |
| `heartbeat_run_events.message`, `payload` | Transcript events | Yes,
except structural events (lifecycle, terminal, presentation, usage,
compaction, session/turn start, `native.*`) | test 1 |
| `heartbeat_runs.stdout_excerpt`, `stderr_excerpt`, and every string
`summary`, `result`, `message`, `text`, `output`, `content` or `body` at
any depth of `result_json` (including `nativeResult`, `acceptedResult`,
`semanticResult` and their `continuation`) | Output excerpts and final
answer | Yes; schema and control fields kept | test 1, canary |
| `approvals.payload` (formal board approval) | Tool name, risk and
hashes only | Not needed: no content | — |
| `tool_mcp_tasks` | Request hash and sealed provider task id; no result
| Not needed: no content | — |
| `tool_mcp_elicitations.questions` and their question cards | Questions
the provider asked a person | No. These are provider prompts, not tool
results, and the answered question stays in the task. Follow-up if
wanted | — |
| `tool_mcp_skills`, `tool_mcp_skill_files`, `tool_catalog_entries` |
Skills and tool descriptions the provider publishes | No. These are
provider definitions, not data read through tool calls | — |
| Transcripts of later runs that read an app view's `model_context` |
Shared app context | No. Nothing records which runs read it. The help
page says so. Follow-up | — |
| `issue_comments.body`, issue documents (including continuation
summaries), files, chat messages | Task content written by agents or
Paperclip | No, by design. The user removes it by editing or deleting it
or the task. The confirmation says in bold that anything agents wrote
into tasks is not removed, and so does the help page. The canary
excludes `issue_comments.body` by name for this reason | canary asserts
it is kept |
| Raw provider traces | Full provider traffic | No. Admin opt-in,
encrypted, expire within 24 hours | — |
| Feedback exports already sent | Run logs the user chose to share | No.
Already outside Paperclip | — |
| Content of runs of a deleted task or company | Same stores | No.
Follow-up | — |

**Durable request (schema change).** I added one table,
`tool_connection_content_deletions`, and migration `0490`. I followed
`doc/DATABASE.md`: edited the schema, exported it from
`packages/db/src/schema/index.ts`, ran `pnpm db:generate`, and ran the
migration drift and compatibility tests. The classifier marks it
`online_compatible` (a new table and its indexes only). No existing
table can hold a durable per-connection request with a cutoff time,
cursor, counts and retry state. Without it, an interrupted deletion
could resume only when a person pressed the button again.

**Resume after restart.** The worker uses the shared
`registerDeadlineWork` lifecycle on a new
`tool-connection-content-deletion` queue. The request insert signals the
queue in the same transaction. At server start the worker runs once,
`next()` finds any pending row, and processing continues from the saved
phase and cursor. Nobody presses anything. `next()` returns a deadline
only while a pending row exists, so an idle instance sends no recurring
query. A failure records `attempts` and `last_error` and retries after
30 seconds.

**One run selection.** `runsWithStoredContentSql` selects the runs whose
transcripts are deleted: runs that made a tool call or tool-call event
through the connection, and runs whose context lists one of the
connection's approved action requests, limited to runs that still hold a
log, an excerpt, result text or a content event. The dialog count, its
in-progress warning and the job's `runs` phase all use this one
function.

**Phases.** `invocations`, `events`, `auditEvents`, `appViews`,
`deliveredResults` (50 action requests per page; matching runs and wakes
are locked with `FOR UPDATE` before their documents are rewritten),
`runs` (the shared selection, 50 run ids per page, then one run at a
time), `done`.

**Canary test.** `tool-connection-content-deletion-canary.test.ts` puts
a unique marker in a tool call's arguments and result, an approved
action with a preview, a result delivered to a later run and its wake, a
native run that quotes the marker in its answer and events, a run log
migrated from a local file with an S3 mirror to an object journal, an
MCP App view and the audit tables. It checks that the marker is first
present in the database, the object store, the legacy mirror and the log
files. After the deletion it scans every `text`, `varchar`, `json` and
`jsonb` column of every table found through `information_schema` (no
hand-written table list), every object in both stores and every file
under the log directory. Any hit fails with the table and column or the
key. It runs three times: a complete deletion, a deletion interrupted
twice by storage failures and resumed, and two deletions for different
connections on one task at the same time. The only exclusion is
`issue_comments.body`, named with its reason.

**Batching and time budget.** Tool rows are read in pages of 200 with
keyset pagination on the existing `(company_id, created_at)` indexes,
bounded by the request time. Each page's writes and the saved progress
commit in one transaction. Counts are therefore exact, and a crash
repeats at most one page, idempotently. Runs advance one at a time from
the shared selection. Each 1,000-event page is its own step. Log removal
is its own step and runs before its progress transaction, so object
storage calls never run inside a database transaction. The 10-second
budget is checked after every step. Nothing changes on the agent boot or
tool-call path.

**In-flight work.** A run counts as settled only when its status is
terminal, `finished_at` is set, cost accounting is done, and no native
finalization is open. Calls, approvals, events, app views, delivered
results and transcripts tied to other runs or wakes are skipped and
counted. The confirmation says "N runs are still working and will be
skipped. Delete again after they finish."

**Permissions.** Board users with configure access (connection manager
or creator) can delete, like `DELETE /tool-connections/:id`. Agents,
viewers and other companies are refused. The activity entries
`tool_connection.content_deletion_requested` and
`tool_connection.content_deleted` hold counts only.

**UI reads.** The dialog loads counts once when it opens. While a
deletion runs, it polls `GET
/tool-connections/:id/stored-content/deletion`, a single indexed row
read, every 2 seconds. Polling stops when the job completes or the
dialog closes. The Delete button is not gated on counts.

## What Changed

- `packages/db`: new `tool_connection_content_deletions` table and
migration `0490` (online compatible: new table and its indexes only).
- `packages/shared`: `ToolConnectionStoredContent`,
`ToolConnectionContentDeletion` and counts types; optional
`contentDeletedAt` on `ToolRedactedValueSummary`.
- `server`: `RunLogStore.remove`, which deletes every copy of a run's
log (`composeRunLogStore`); `content-deletion.ts` service; deadline
worker wired into startup and pre-drain; `GET
/tool-connections/:id/stored-content`, `POST` and `GET
/tool-connections/:id/stored-content/deletion`, and `DELETE
/tool-connections/:id?deleteStoredContent=true`; OpenAPI entries.
- `ui`: "Delete data" row on the connection's Permissions tab with a
confirmation that shows counts, skipped runs, and "This cannot be
undone"; "Also delete data read through this connection" checkbox in the
Connectors removal dialog.
- Docs: user help
`docs/guides/board-operator/deleting-connection-data.md` (for the
privacy policy link) and an API note in
`doc/connections/CONNECTOR-PLAYBOOK.md`.
- `tests/runner-e2e/source-sdk-public-inputs.json` refreshed for the
shared type change.

`server/src/routes/tool-access.ts` (3,010 lines) and
`ui/src/pages/apps/Browse.tsx` (1,722 lines) grow by about 40 and 20
lines. The routes reuse that file's connection access checks; the dialog
reuses the existing removal confirmation. The new logic lives in its own
files.

## Verification

- `server/src/__tests__/tool-connection-content-deletion.test.ts`
(embedded PostgreSQL): content is gone from every "Yes" store in the
inventory; rows, hashes and sizes stay; another connection and another
company are untouched; a running run is skipped and is deleted after it
settles; a storage failure leaves the request pending with `retrying`,
and the next pass completes it; an approval-card update that fails once
is cleared on the retry; an unrecognised log backend keeps the pointer,
keeps the job pending and writes no completion entry; a zero time budget
yields after every step and still finishes; a repeat request returns the
pending one; agents and outsiders are refused; removal with
`deleteStoredContent=true` queues the deletion.
- `run-log-store.test.ts` and `object-run-log-store.test.ts`: `remove`
deletes local and mirrored logs and object journals, removes a migrated
run's original local file and mirror with its journal, refuses an object
log when object storage is not configured, and is idempotent.
- `ui/.../StoredContentDeletion.test.tsx`: confirmation text, counts,
skipped-run warning, and the request.
- Red: these tests fail on `master` because `remove`, the service and
the routes do not exist. Green on this branch.
- Ran: the tests above, `openapi-routes`,
`server-startup-feedback-export`, `tool-connection-removal`,
`packages/db` migration drift and compatibility tests, all
`ui/src/pages/apps` tests (950), `pnpm check:token-gates`, server and UI
`tsc --noEmit`. `pnpm verify` exits 2 (global CI input changed), so
required CI supplies broad coverage.

## Risks

- Deleting is permanent by design. The confirmation says so.
- A `local_file` log written on another replica's local disk stays on
that pod's disk until the pod is replaced; its S3 mirror is deleted. New
logs on S3-configured instances use object journals, which are deleted.
- On versioned buckets, earlier object versions remain until the
bucket's lifecycle policy removes them (the existing journal delete path
does not remove versions).
- Not in this PR (follow-ups): the "No" rows of the inventory (except
agent-written task content, which is out of scope by design), mainly the
same deletion when a task or a company is deleted, and later runs that
read an app view's shared context.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with
tool use and code execution.

## 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-17 08:55:35 -06:00
1 parent 55b692d532
commit d1b5cfe038
30 files changed
+2752 -25

No files matched your search

@@ -79,6 +79,7 @@ export const DELIVERY_QUEUES = {
decisionArchiveDelivery: "decision-archive-delivery",
toolConnectionHealth: "tool-connection-health",
toolConnectionContentDeletion: "tool-connection-content-deletion",
toolReviewProjection: "tool-review-projection",
toolReviewInterruption: "tool-review-interruption",
toolReviewRecovery: "tool-review-recovery",
@@ -66,6 +66,18 @@ const event = (seq: number) => ({
});
describe("S3 run log store", () => {
it("removes every object of a finalized log and stays removable", async () => {
const m = memory(), store = createObjectRunLogStore({ provider: m.provider, keyPrefix: "logs",
assertWriterAuthority: async () => undefined });
const handle = await store.begin(input);
await store.append(handle, { ...event(1), chunk: "tool result content" });
await store.finalize(handle);
expect([...m.objects.keys()].some((key) => key.includes(handle.logRef))).toBe(true);
await store.remove!(handle);
await store.remove!(handle);
expect([...m.objects.keys()].filter((key) => key.includes(handle.logRef) && !key.endsWith("/head.json"))).toEqual([]);
await expect(store.read(handle)).rejects.toThrow("Run log not found");
});
it("awaits a successor flush started by another drain waiter before finalizing", async () => {
const m = memory(), store = createObjectRunLogStore({ provider: m.provider, keyPrefix: "logs", flushMs: 1000,
segmentBytes: 1024, assertWriterAuthority: async () => undefined });
@@ -399,6 +399,10 @@ export function createObjectRunLogStore(options: ObjectRunLogStoreOptions): RunL
nextOffset: nextOffset ?? offset + bytes.length,
};
},
async remove(handle, signal) {
if (handle.store !== "s3_segments" && handle.store !== "s3_archive") throw new Error("Invalid object run log backend");
await journal(handle.logRef, "background").remove(signal);
},
async flushInflightMirrors() {
await Promise.all([...writers.values()].map(flush));
},
+42 -1
View File
@@ -4,7 +4,8 @@ import path from "node:path";
import os from "node:os";
import { createHash } from "node:crypto";
import { Readable } from "node:stream";
import { createDurableRunLogStore } from "./run-log-store.js";
import { composeRunLogStore, createDurableRunLogStore } from "./run-log-store.js";
import { objectLogFixture } from "./heartbeat/__tests__/object-log-fixture.js";
import type { StorageProvider } from "../storage/types.js";
// In-memory StorageProvider stand-in: durable, survives the "pod roll" (local
@@ -68,6 +69,46 @@ afterEach(async () => {
const begin = { companyId: "co1", agentId: "ag1", runId: "run1" };
describe("createDurableRunLogStore", () => {
it("removes a migrated run's original local log and mirror along with its object journal", async () => {
const { provider, objects } = createMemoryProvider();
const local = createDurableRunLogStore({ basePath: baseDir, s3: { provider } });
const external = objectLogFixture();
const store = composeRunLogStore(local, external);
const original = await local.begin(begin);
await local.append(original, { stream: "stdout", chunk: "tool result content", ts: "t1" });
await local.finalize(original);
const migrated = await external.begin(begin);
await external.append(migrated, { stream: "stdout", chunk: "tool result content", ts: "t1", seq: 1 });
await external.finalize(migrated);
expect(objects.has(original.logRef)).toBe(true);
await store.remove!(migrated);
await store.remove!(migrated);
expect(objects.has(original.logRef)).toBe(false);
await expect(fs.stat(path.join(baseDir, original.logRef))).rejects.toMatchObject({ code: "ENOENT" });
await expect(external.read(migrated)).rejects.toThrow("Run log not found");
await expect(store.remove!({ store: "s3_segments", logRef: "../escape" })).rejects.toThrow("Invalid run log reference");
});
it("refuses to report an object log removed when object storage is not configured", async () => {
const local = createDurableRunLogStore({ basePath: baseDir });
const store = composeRunLogStore(local, null);
await expect(store.remove!({ store: "s3_segments", logRef: "co1/ag1/run1" })).rejects.toThrow("Object run log storage is not configured");
});
it("removes a finalized log from local disk and its object mirror", async () => {
const { provider, objects } = createMemoryProvider();
const store = createDurableRunLogStore({ basePath: baseDir, s3: { provider } });
const handle = await store.begin(begin);
await store.append(handle, { stream: "stdout", chunk: "tool result content", ts: "t1" });
await store.finalize(handle);
expect(objects.has(handle.logRef)).toBe(true);
await store.remove!(handle);
await store.remove!(handle);
expect(objects.has(handle.logRef)).toBe(false);
await expect(fs.stat(path.join(baseDir, handle.logRef))).rejects.toMatchObject({ code: "ENOENT" });
await expect(store.read(handle)).rejects.toThrow("Run log not found");
});
it.each([false, true])("reads a complete long final record from a compact tail (S3 fallback: %s)", async (remote) => {
const { provider, objects, calls } = createMemoryProvider();
const store = createDurableRunLogStore({ basePath: baseDir, s3: { provider } });
+44 -14
View File
@@ -85,6 +85,7 @@ export interface RunLogStore {
recordVerifiedSourcePrefix?(handle: RunLogHandle, sourceCursor: number): Promise<void>;
finalize(handle: RunLogHandle, options?: { computeDigest?: boolean }): Promise<RunLogFinalizeSummary>;
read(handle: RunLogHandle, opts?: RunLogReadOptions): Promise<RunLogReadResult>;
remove?(handle: RunLogHandle, signal?: AbortSignal): Promise<void>;
// Optional so existing fakes/fixtures keep compiling: uploads every dirty
// in-flight mirror immediately (graceful-shutdown path). No-op when the
// in-flight mirror is not enabled.
@@ -494,6 +495,14 @@ export function createDurableRunLogStore(options: DurableRunLogStoreOptions): Ru
};
},
async remove(handle, signal) {
if (handle.store !== "local_file") throw new Error("Invalid local run log backend");
signal?.throwIfAborted();
await retireInflightMirror(handle.logRef);
await fs.rm(resolveWithin(basePath, handle.logRef), { force: true });
if (s3) await s3.provider.deleteObject({ objectKey: s3Key(handle.logRef), signal });
},
async flushInflightMirrors() {
if (!s3 || inflightMirrorMs <= 0) return;
const flushEntry = async (logRef: string, entry: InflightMirrorEntry) => {
@@ -558,20 +567,13 @@ export function resolveRunLogS3(): DurableRunLogStoreOptions["s3"] {
};
}
let cachedStore: RunLogStore | null = null;
export function runLogBaseRef(handle: RunLogHandle): string {
const base = handle.store === "local_file" ? handle.logRef.replace(/\.ndjson$/, "") : handle.logRef.replace(/\.archive$/, "");
if (!/^[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/.test(base)) throw new Error("Invalid run log reference");
return base;
}
export function getRunLogStore() {
if (cachedStore) return cachedStore;
const basePath = process.env.RUN_LOG_BASE_PATH ?? path.resolve(resolvePaperclipInstanceRoot(), "data", "run-logs");
const local = createDurableRunLogStore({ basePath, s3: resolveRunLogS3() });
const s3 = resolveRunEvidenceStorage();
const external = s3 ? createObjectRunLogStore({
provider: s3.provider, keyPrefix: s3.keyPrefix || "run-logs",
assertWriterAuthority: async input => {
if (!input.assertWriterAuthority) throw new Error("Object run logs require admitted writer authority");
await input.assertWriterAuthority();
},
}) : null;
export function composeRunLogStore(local: RunLogStore, external: RunLogStore | null): RunLogStore {
const writer = external ?? local;
function writable(handle: RunLogHandle) {
if (handle.store === "s3_archive") throw new Error("Historical run log archives are read-only");
@@ -579,7 +581,7 @@ export function getRunLogStore() {
if (!external) throw new Error("Object run log storage is not configured");
return external;
}
cachedStore = {
return {
begin: input => {
if (input.previousStore === "s3_archive") throw new Error("Historical run log archives are read-only");
if (input.previousStore === "local_file") return local.begin(input);
@@ -603,8 +605,36 @@ export function getRunLogStore() {
}
return local.read(handle, opts);
},
remove: async (handle, signal) => {
if (!local.remove) throw new Error("Run log removal is unavailable");
const base = runLogBaseRef(handle);
if (external?.remove) {
await external.remove({ store: "s3_segments", logRef: base }, signal);
await external.remove({ store: "s3_archive", logRef: `${base}.archive` }, signal);
} else if (handle.store !== "local_file") {
throw new Error("Object run log storage is not configured");
}
await local.remove({ store: "local_file", logRef: `${base}.ndjson` }, signal);
},
flushInflightMirrors: async () => { await Promise.all([local.flushInflightMirrors?.(), external?.flushInflightMirrors?.()]); },
};
}
let cachedStore: RunLogStore | null = null;
export function getRunLogStore() {
if (cachedStore) return cachedStore;
const basePath = process.env.RUN_LOG_BASE_PATH ?? path.resolve(resolvePaperclipInstanceRoot(), "data", "run-logs");
const local = createDurableRunLogStore({ basePath, s3: resolveRunLogS3() });
const s3 = resolveRunEvidenceStorage();
const external = s3 ? createObjectRunLogStore({
provider: s3.provider, keyPrefix: s3.keyPrefix || "run-logs",
assertWriterAuthority: async input => {
if (!input.assertWriterAuthority) throw new Error("Object run logs require admitted writer authority");
await input.assertWriterAuthority();
},
}) : null;
cachedStore = composeRunLogStore(local, external);
return cachedStore;
}
@@ -0,0 +1,761 @@
import { and, asc, desc, eq, gt, inArray, lte, sql, type SQL } from "drizzle-orm";
import {
agentWakeupRequests,
heartbeatRunEvents,
heartbeatRuns,
issueThreadInteractions,
toolAccessAuditEvents,
toolActionRequests,
toolCallEvents,
toolConnectionContentDeletions,
toolInvocations,
toolMcpAppViews,
type Db,
} from "@paperclipai/db";
import type {
ToolConnectionContentDeletion,
ToolConnectionContentDeletionCounts,
ToolConnectionStoredContent,
} from "@paperclipai/shared";
import { isRunLogStoreType, type RunLogHandle, type RunLogStore } from "../../run-log-store.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "../../delivery-work-notifications.js";
import { logActivity } from "../../activity-log.js";
const BATCH_SIZE = 200;
const EVENT_BATCH_SIZE = 1000;
const STEP_BUDGET_MS = 10_000;
const SETTLED_RUN_STATUSES = ["succeeded", "failed", "cancelled", "timed_out", "interrupted"];
const UNSETTLED_INVOCATION_STATUSES = ["pending", "authorized", "awaiting_approval", "executing"];
const UNSETTLED_ACTION_REQUEST_STATUSES = ["pending", "approved", "executing"];
const UNSETTLED_WAKE_STATUSES = ["queued", "deferred_issue_execution", "claimed"];
const RESULT_TEXT_KEYS = ["summary", "result", "message", "text", "output", "content", "body"];
const STRUCTURAL_EVENT_TYPES = [
"lifecycle",
"run.terminal",
"run.presentation.resolved",
"adapter.invoke",
"usage.reported",
"context.compacted",
"session.started",
"session.resumed",
"turn.started",
"turn.accepted",
"harness.ready",
];
type Phase = "invocations" | "events" | "auditEvents" | "appViews" | "deliveredResults" | "runs" | "done";
const PHASES: Phase[] = ["invocations", "events", "auditEvents", "appViews", "deliveredResults", "runs", "done"];
const RUN_BATCH_SIZE = 50;
const DELIVERY_BATCH_SIZE = 50;
type RunInProgress = { id: string; eventAfterId: number; changed: boolean; stage?: "events" | "log" };
type Progress = {
phase: Phase;
cursor: { createdAt: string; id: string } | null;
runCursor: string | null;
currentRun: RunInProgress | null;
pendingRuns: string[];
counts: ToolConnectionContentDeletionCounts;
};
type DeletionRow = typeof toolConnectionContentDeletions.$inferSelect;
export type ContentDeletionActor = { actorType: "user" | "agent" | "system"; actorId: string | null };
class ProgressConflict extends Error {}
export function emptyContentDeletionCounts(): ToolConnectionContentDeletionCounts {
return { toolCalls: 0, approvals: 0, auditEvents: 0, appViews: 0, runs: 0, runsInProgress: 0, itemsInProgress: 0 };
}
function readProgress(row: DeletionRow): Progress {
const raw = row.progress as Partial<Progress>;
const counts = { ...emptyContentDeletionCounts(), ...(raw.counts ?? {}) };
const phase = PHASES.includes(raw.phase as Phase) ? raw.phase as Phase : "invocations";
return { phase, cursor: raw.cursor ?? null, runCursor: raw.runCursor ?? null, currentRun: raw.currentRun ?? null, pendingRuns: raw.pendingRuns ?? [], counts };
}
function nextPhase(phase: Phase): Phase {
return PHASES[Math.min(PHASES.indexOf(phase) + 1, PHASES.length - 1)]!;
}
function listSql(values: string[]): SQL {
return sql.join(values.map((value) => sql`${value}`), sql`, `);
}
export function settledRunSql(runId: SQL | typeof toolInvocations.runId): SQL {
return sql`exists (select 1 from ${heartbeatRuns} r where r.id = ${runId}
and r.status in (${listSql(SETTLED_RUN_STATUSES)})
and r.finished_at is not null
and r.cost_accounting_pending = false
and not exists (select 1 from native_run_finalizations f where f.run_id = r.id
and f.phase not in ('committed', 'terminal_failure', 'applied')))`;
}
export function runsWithStoredContentSql(scope: { companyId: string; connectionId: string; cutoff: Date }): SQL {
const calls = sql`${toolInvocations.companyId} = ${scope.companyId} and ${toolInvocations.connectionId} = ${scope.connectionId}
and ${toolInvocations.createdAt} <= ${scope.cutoff.toISOString()}::timestamptz`;
const resultText = sql.join(RESULT_TEXT_KEYS.map((key) =>
sql.raw(`jsonb_path_exists(coalesce("heartbeat_runs"."result_json", '{}'::jsonb), 'lax $.**.${key} ? (@.type() == "string" && @ != "")')`)), sql` or `);
return sql`${heartbeatRuns.companyId} = ${scope.companyId}
and (${heartbeatRuns.id} in (select ${toolInvocations.runId} from ${toolInvocations} where ${calls} and ${toolInvocations.runId} is not null)
or ${heartbeatRuns.id} in (select ${toolCallEvents.runId} from ${toolCallEvents} where ${toolCallEvents.companyId} = ${scope.companyId}
and ${toolCallEvents.connectionId} = ${scope.connectionId} and ${toolCallEvents.createdAt} <= ${scope.cutoff.toISOString()}::timestamptz
and ${toolCallEvents.runId} is not null)
or (${heartbeatRuns.issueId} in (select ${toolActionRequests.issueId} from ${toolActionRequests}
join ${toolInvocations} on ${toolInvocations.id} = ${toolActionRequests.invocationId} where ${calls})
and ${heartbeatRuns.contextSnapshot}->'toolActionRequestIds' ?| array(select ${toolActionRequests.id}::text from ${toolActionRequests}
join ${toolInvocations} on ${toolInvocations.id} = ${toolActionRequests.invocationId} where ${calls})))
and (${heartbeatRuns.logRef} is not null or ${heartbeatRuns.logStore} is not null
or ${heartbeatRuns.stdoutExcerpt} is not null or ${heartbeatRuns.stderrExcerpt} is not null
or ${resultText}
or exists (select 1 from ${heartbeatRunEvents} where ${heartbeatRunEvents.companyId} = ${heartbeatRuns.companyId}
and ${heartbeatRunEvents.runId} = ${heartbeatRuns.id} and ${contentEventSql()}))`;
}
function contentEventSql(): SQL {
return sql`${heartbeatRunEvents.eventType} not in (${listSql(STRUCTURAL_EVENT_TYPES)})
and ${heartbeatRunEvents.eventType} not like 'native.%'
and not (${heartbeatRunEvents.eventType} = 'item.completed' and (${heartbeatRunEvents.payload} -> 'prpEvent' -> 'payload' ->> 'kind') = 'usage')
and (${heartbeatRunEvents.message} is not null or ${heartbeatRunEvents.payload} is not null)`;
}
function clearedSummary(column: SQL, deletedAt: string): SQL {
return sql`case when ${column} is null then null
else ${column} || jsonb_build_object('summary', '', 'contentDeletedAt', ${deletedAt}::text) end`;
}
export function withoutActionResults(value: unknown, actionRequestIds: ReadonlySet<string>): { value: unknown; changed: boolean } {
let changed = false;
const walk = (node: unknown): unknown => {
if (Array.isArray(node)) return node.map(walk);
if (!node || typeof node !== "object") return node;
const record = node as Record<string, unknown>;
const next: Record<string, unknown> = {};
for (const [key, entry] of Object.entries(record)) next[key] = walk(entry);
if (typeof record.actionRequestId === "string" && actionRequestIds.has(record.actionRequestId)
&& typeof record.resultSummary === "string" && record.resultSummary !== "") {
next.resultSummary = "";
changed = true;
}
return next;
};
const result = walk(value);
return { value: changed ? result : value, changed };
}
export function withoutResultText(value: Record<string, unknown> | null): { value: Record<string, unknown> | null; changed: boolean } {
if (!value || typeof value !== "object") return { value, changed: false };
let changed = false;
const walk = (node: unknown, topLevel: boolean): unknown => {
if (Array.isArray(node)) return node.map((entry) => walk(entry, false));
if (!node || typeof node !== "object") return node;
const next: Record<string, unknown> = {};
for (const [key, entry] of Object.entries(node as Record<string, unknown>)) {
if (RESULT_TEXT_KEYS.includes(key) && typeof entry === "string") {
if (entry !== "") changed = true;
if (!topLevel) next[key] = "";
else if (entry === "") next[key] = entry;
continue;
}
next[key] = walk(entry, false);
}
return next;
};
const next = walk(value, true) as Record<string, unknown>;
return { value: changed ? next : value, changed };
}
function toDeletion(row: DeletionRow): ToolConnectionContentDeletion {
return {
id: row.id,
status: row.status,
requestedAt: row.requestedAt.toISOString(),
completedAt: row.completedAt?.toISOString() ?? null,
retrying: row.status === "pending" && row.lastError !== null,
counts: readProgress(row).counts,
};
}
export function createConnectionContentDeletion(db: Db, deps: { runLogStore: () => RunLogStore }) {
async function latestDeletion(connection: { id: string; companyId: string }) {
const [latest] = await db
.select()
.from(toolConnectionContentDeletions)
.where(and(
eq(toolConnectionContentDeletions.companyId, connection.companyId),
eq(toolConnectionContentDeletions.connectionId, connection.id),
))
.orderBy(desc(toolConnectionContentDeletions.createdAt))
.limit(1);
return latest ? toDeletion(latest) : null;
}
async function storedContent(connection: { id: string; companyId: string }): Promise<ToolConnectionStoredContent> {
const scope = and(eq(toolInvocations.companyId, connection.companyId), eq(toolInvocations.connectionId, connection.id));
const [calls] = await db
.select({ toolCalls: sql<number>`count(*)::int` })
.from(toolInvocations)
.where(and(
scope,
sql`coalesce(${toolInvocations.resultSummary}->>'contentDeletedAt', ${toolInvocations.argumentsSummary}->>'contentDeletedAt') is null`,
sql`(${toolInvocations.resultSummary} is not null or ${toolInvocations.argumentsSummary} is not null)`,
));
const [approvals] = await db
.select({ count: sql<number>`count(*)::int` })
.from(toolActionRequests)
.innerJoin(toolInvocations, eq(toolInvocations.id, toolActionRequests.invocationId))
.where(and(
scope,
eq(toolActionRequests.companyId, connection.companyId),
sql`(${toolActionRequests.canonicalArgumentsSummary}->>'contentDeletedAt' is null or ${toolActionRequests.previewMarkdown} is not null)`,
));
const [views] = await db
.select({ count: sql<number>`count(*)::int` })
.from(toolMcpAppViews)
.where(and(eq(toolMcpAppViews.connectionId, connection.id), eq(toolMcpAppViews.companyId, connection.companyId)));
const [runs] = await db
.select({
runs: sql<number>`count(*)::int`,
runsInProgress: sql<number>`count(*) filter (where not ${settledRunSql(sql`${heartbeatRuns.id}`)})::int`,
})
.from(heartbeatRuns)
.where(runsWithStoredContentSql({ companyId: connection.companyId, connectionId: connection.id, cutoff: new Date() }));
return {
stored: {
toolCalls: calls?.toolCalls ?? 0,
approvals: approvals?.count ?? 0,
appViews: views?.count ?? 0,
runs: runs?.runs ?? 0,
runsInProgress: runs?.runsInProgress ?? 0,
},
deletion: await latestDeletion(connection),
};
}
async function request(connection: { id: string; companyId: string }, actor: ContentDeletionActor) {
return db.transaction(async (tx) => {
const pendingFor = () => tx
.select()
.from(toolConnectionContentDeletions)
.where(and(
eq(toolConnectionContentDeletions.companyId, connection.companyId),
eq(toolConnectionContentDeletions.connectionId, connection.id),
eq(toolConnectionContentDeletions.status, "pending"),
))
.limit(1);
const [existing] = await pendingFor();
if (existing) return { deletion: toDeletion(existing), created: false };
await notifyDeliveryWork(tx, DELIVERY_QUEUES.toolConnectionContentDeletion);
const now = new Date();
const [created] = await tx
.insert(toolConnectionContentDeletions)
.values({
requestedAt: now,
createdAt: now,
updatedAt: now,
companyId: connection.companyId,
connectionId: connection.id,
requestedByActorType: actor.actorType,
requestedByActorId: actor.actorId,
progress: { phase: "invocations", cursor: null, runCursor: null, currentRun: null, pendingRuns: [], counts: emptyContentDeletionCounts() },
})
.onConflictDoNothing()
.returning();
if (created) return { deletion: toDeletion(created), created: true };
const [raced] = await pendingFor();
return { deletion: toDeletion(raced!), created: false };
});
}
async function settledRunIds(tx: Db, runIds: string[]) {
if (runIds.length === 0) return new Set<string>();
const rows = await tx
.select({ id: heartbeatRuns.id })
.from(heartbeatRuns)
.where(and(inArray(heartbeatRuns.id, runIds), settledRunSql(sql`${heartbeatRuns.id}`)));
return new Set(rows.map((row) => row.id));
}
async function clearDeliveredResults(tx: Db, job: DeletionRow, progress: Progress, requests: Array<{ id: string; issueId: string | null }>) {
const issueIds = [...new Set(requests.flatMap((row) => row.issueId ? [row.issueId] : []))];
if (issueIds.length === 0) return [];
const ids = new Set(requests.map((row) => row.id));
const idList = sql`array[${listSql([...ids])}]::text[]`;
const runs = await tx
.select({ id: heartbeatRuns.id, contextSnapshot: heartbeatRuns.contextSnapshot })
.from(heartbeatRuns)
.where(and(
eq(heartbeatRuns.companyId, job.companyId),
inArray(heartbeatRuns.issueId, issueIds),
sql`${heartbeatRuns.contextSnapshot}->'toolActionRequestIds' ?| ${idList}`,
))
.for("update");
const settled = await settledRunIds(tx, runs.map((row) => row.id));
for (const run of runs) {
if (!settled.has(run.id)) {
progress.counts.itemsInProgress += 1;
continue;
}
const cleaned = withoutActionResults(run.contextSnapshot, ids);
if (cleaned.changed) {
await tx.update(heartbeatRuns).set({ contextSnapshot: cleaned.value as Record<string, unknown> }).where(eq(heartbeatRuns.id, run.id));
}
}
const wakes = await tx
.select({ id: agentWakeupRequests.id, status: agentWakeupRequests.status, payload: agentWakeupRequests.payload })
.from(agentWakeupRequests)
.where(and(
eq(agentWakeupRequests.companyId, job.companyId),
inArray(sql<string>`${agentWakeupRequests.payload}->>'issueId'`, issueIds),
sql`(${agentWakeupRequests.payload}->'toolActionRequestIds' ?| ${idList}
or ${agentWakeupRequests.payload}->'_paperclipWakeContext'->'toolActionRequestIds' ?| ${idList})`,
))
.for("update");
for (const wake of wakes) {
const cleaned = withoutActionResults(wake.payload, ids);
if (!cleaned.changed) continue;
if (UNSETTLED_WAKE_STATUSES.includes(wake.status)) {
progress.counts.itemsInProgress += 1;
continue;
}
await tx.update(agentWakeupRequests).set({ payload: cleaned.value as Record<string, unknown> }).where(eq(agentWakeupRequests.id, wake.id));
}
return runs.filter((row) => settled.has(row.id)).map((row) => row.id);
}
async function invocationsStep(tx: Db, job: DeletionRow, progress: Progress, deletedAt: string) {
const cursor = progress.cursor;
const page = await tx
.select({ id: toolInvocations.id, createdAt: toolInvocations.createdAt, runId: toolInvocations.runId, status: toolInvocations.status })
.from(toolInvocations)
.where(and(
eq(toolInvocations.companyId, job.companyId),
lte(toolInvocations.createdAt, job.requestedAt),
cursor ? sql`(${toolInvocations.createdAt}, ${toolInvocations.id}) > (${cursor.createdAt}::timestamptz, ${cursor.id}::uuid)` : undefined,
eq(toolInvocations.connectionId, job.connectionId),
))
.orderBy(asc(toolInvocations.createdAt), asc(toolInvocations.id))
.limit(BATCH_SIZE);
if (page.length === 0) return true;
const settledRuns = await settledRunIds(tx, [...new Set(page.flatMap((row) => row.runId ? [row.runId] : []))]);
const eligible = page.filter((row) => !UNSETTLED_INVOCATION_STATUSES.includes(row.status) && (!row.runId || settledRuns.has(row.runId)));
progress.counts.itemsInProgress += page.length - eligible.length;
const ids = eligible.map((row) => row.id);
if (ids.length > 0) {
const cleared = await tx
.update(toolInvocations)
.set({
argumentsSummary: clearedSummary(sql`${toolInvocations.argumentsSummary}`, deletedAt) as never,
resultSummary: clearedSummary(sql`${toolInvocations.resultSummary}`, deletedAt) as never,
progress: null,
})
.where(and(
eq(toolInvocations.companyId, job.companyId),
inArray(toolInvocations.id, ids),
sql`coalesce(${toolInvocations.resultSummary}->>'contentDeletedAt', ${toolInvocations.argumentsSummary}->>'contentDeletedAt') is null`,
sql`(${toolInvocations.resultSummary} is not null or ${toolInvocations.argumentsSummary} is not null or ${toolInvocations.progress} is not null)`,
))
.returning({ id: toolInvocations.id });
progress.counts.toolCalls += cleared.length;
const requests = await tx
.select({ id: toolActionRequests.id, interactionId: toolActionRequests.interactionId, issueId: toolActionRequests.issueId, status: toolActionRequests.status })
.from(toolActionRequests)
.where(and(eq(toolActionRequests.companyId, job.companyId), inArray(toolActionRequests.invocationId, ids)));
const settledRequests = requests.filter((row) => !UNSETTLED_ACTION_REQUEST_STATUSES.includes(row.status));
progress.counts.itemsInProgress += requests.length - settledRequests.length;
if (settledRequests.length > 0) {
const requestIds = settledRequests.map((row) => row.id);
const clearedRequests = await tx
.update(toolActionRequests)
.set({
canonicalArgumentsSummary: clearedSummary(sql`${toolActionRequests.canonicalArgumentsSummary}`, deletedAt) as never,
previewMarkdown: null,
signedArguments: null,
})
.where(and(
eq(toolActionRequests.companyId, job.companyId),
inArray(toolActionRequests.id, requestIds),
sql`(${toolActionRequests.canonicalArgumentsSummary}->>'contentDeletedAt' is null or ${toolActionRequests.previewMarkdown} is not null or ${toolActionRequests.signedArguments} is not null)`,
))
.returning({ id: toolActionRequests.id });
progress.counts.approvals += clearedRequests.length;
const interactionIds = settledRequests.flatMap((row) => row.interactionId ? [row.interactionId] : []);
if (interactionIds.length > 0) {
await tx
.update(issueThreadInteractions)
.set({
payload: sql`case when jsonb_typeof(${issueThreadInteractions.payload}->'toolAction') = 'object'
then jsonb_set(jsonb_set(${issueThreadInteractions.payload} - 'detailsMarkdown', '{toolAction,previewMarkdown}', 'null'::jsonb), '{toolAction,argumentsSummaryJson}', 'null'::jsonb)
else ${issueThreadInteractions.payload} - 'detailsMarkdown' end` as never,
result: sql`case when jsonb_typeof(${issueThreadInteractions.result}->'toolAction') = 'object'
then jsonb_set(${issueThreadInteractions.result}, '{toolAction,resultSummary}', 'null'::jsonb)
else ${issueThreadInteractions.result} end` as never,
})
.where(and(
eq(issueThreadInteractions.companyId, job.companyId),
inArray(issueThreadInteractions.id, interactionIds),
sql`(${issueThreadInteractions.payload} ? 'detailsMarkdown'
or ${issueThreadInteractions.payload}->'toolAction'->>'previewMarkdown' is not null
or ${issueThreadInteractions.payload}->'toolAction'->>'argumentsSummaryJson' is not null
or ${issueThreadInteractions.result}->'toolAction'->>'resultSummary' is not null)`,
));
}
}
}
const last = page[page.length - 1]!;
progress.cursor = { createdAt: last.createdAt.toISOString(), id: last.id };
return page.length < BATCH_SIZE;
}
async function eventsStep(tx: Db, job: DeletionRow, progress: Progress, deletedAt: string) {
const cursor = progress.cursor;
const page = await tx
.select({ id: toolCallEvents.id, createdAt: toolCallEvents.createdAt, runId: toolCallEvents.runId })
.from(toolCallEvents)
.where(and(
eq(toolCallEvents.companyId, job.companyId),
lte(toolCallEvents.createdAt, job.requestedAt),
cursor ? sql`(${toolCallEvents.createdAt}, ${toolCallEvents.id}) > (${cursor.createdAt}::timestamptz, ${cursor.id}::uuid)` : undefined,
eq(toolCallEvents.connectionId, job.connectionId),
))
.orderBy(asc(toolCallEvents.createdAt), asc(toolCallEvents.id))
.limit(BATCH_SIZE);
if (page.length === 0) return true;
const settledRuns = await settledRunIds(tx, [...new Set(page.flatMap((row) => row.runId ? [row.runId] : []))]);
const ids = page.filter((row) => !row.runId || settledRuns.has(row.runId)).map((row) => row.id);
progress.counts.itemsInProgress += page.length - ids.length;
if (ids.length > 0) {
const cleared = await tx
.update(toolCallEvents)
.set({
argumentsSummary: clearedSummary(sql`${toolCallEvents.argumentsSummary}`, deletedAt) as never,
requestSummary: clearedSummary(sql`${toolCallEvents.requestSummary}`, deletedAt) as never,
resultSummary: clearedSummary(sql`${toolCallEvents.resultSummary}`, deletedAt) as never,
})
.where(and(
eq(toolCallEvents.companyId, job.companyId),
inArray(toolCallEvents.id, ids),
sql`coalesce(${toolCallEvents.resultSummary}->>'contentDeletedAt', ${toolCallEvents.requestSummary}->>'contentDeletedAt', ${toolCallEvents.argumentsSummary}->>'contentDeletedAt') is null`,
sql`(${toolCallEvents.resultSummary} is not null or ${toolCallEvents.requestSummary} is not null or ${toolCallEvents.argumentsSummary} is not null)`,
))
.returning({ id: toolCallEvents.id });
progress.counts.auditEvents += cleared.length;
}
const last = page[page.length - 1]!;
progress.cursor = { createdAt: last.createdAt.toISOString(), id: last.id };
return page.length < BATCH_SIZE;
}
async function auditEventsStep(tx: Db, job: DeletionRow, progress: Progress, deletedAt: string) {
const cursor = progress.cursor;
const page = await tx
.select({ id: toolAccessAuditEvents.id, createdAt: toolAccessAuditEvents.createdAt, runId: sql<string | null>`${toolAccessAuditEvents.details}->>'runId'` })
.from(toolAccessAuditEvents)
.where(and(
eq(toolAccessAuditEvents.companyId, job.companyId),
lte(toolAccessAuditEvents.createdAt, job.requestedAt),
cursor ? sql`(${toolAccessAuditEvents.createdAt}, ${toolAccessAuditEvents.id}) > (${cursor.createdAt}::timestamptz, ${cursor.id}::uuid)` : undefined,
eq(toolAccessAuditEvents.connectionId, job.connectionId),
))
.orderBy(asc(toolAccessAuditEvents.createdAt), asc(toolAccessAuditEvents.id))
.limit(BATCH_SIZE);
if (page.length === 0) return true;
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const runIds = [...new Set(page.flatMap((row) => row.runId && uuid.test(row.runId) ? [row.runId] : []))];
const settledRuns = await settledRunIds(tx, runIds);
const ids = page.filter((row) => !row.runId || !uuid.test(row.runId) || settledRuns.has(row.runId)).map((row) => row.id);
progress.counts.itemsInProgress += page.length - ids.length;
if (ids.length > 0) {
const cleared = await tx
.update(toolAccessAuditEvents)
.set({
details: sql`jsonb_set(${toolAccessAuditEvents.details}, '{argumentsSummary}',
${toolAccessAuditEvents.details}->'argumentsSummary' || jsonb_build_object('summary', '', 'contentDeletedAt', ${deletedAt}::text))` as never,
})
.where(and(
eq(toolAccessAuditEvents.companyId, job.companyId),
inArray(toolAccessAuditEvents.id, ids),
sql`jsonb_typeof(${toolAccessAuditEvents.details}->'argumentsSummary') = 'object'`,
sql`${toolAccessAuditEvents.details}->'argumentsSummary'->>'contentDeletedAt' is null`,
))
.returning({ id: toolAccessAuditEvents.id });
progress.counts.auditEvents += cleared.length;
}
const last = page[page.length - 1]!;
progress.cursor = { createdAt: last.createdAt.toISOString(), id: last.id };
return page.length < BATCH_SIZE;
}
async function appViewsStep(tx: Db, job: DeletionRow, progress: Progress) {
const page = await tx
.select({ id: toolMcpAppViews.id, runId: toolMcpAppViews.runId })
.from(toolMcpAppViews)
.where(and(
eq(toolMcpAppViews.connectionId, job.connectionId),
eq(toolMcpAppViews.companyId, job.companyId),
lte(toolMcpAppViews.createdAt, job.requestedAt),
progress.runCursor ? gt(toolMcpAppViews.id, progress.runCursor) : undefined,
))
.orderBy(asc(toolMcpAppViews.id))
.limit(BATCH_SIZE);
if (page.length === 0) return true;
const settledRuns = await settledRunIds(tx, [...new Set(page.flatMap((row) => row.runId ? [row.runId] : []))]);
const ids = page.filter((row) => !row.runId || settledRuns.has(row.runId)).map((row) => row.id);
progress.counts.itemsInProgress += page.length - ids.length;
if (ids.length > 0) {
const removed = await tx
.delete(toolMcpAppViews)
.where(and(eq(toolMcpAppViews.companyId, job.companyId), inArray(toolMcpAppViews.id, ids)))
.returning({ id: toolMcpAppViews.id });
progress.counts.appViews += removed.length;
}
progress.runCursor = page[page.length - 1]!.id;
return page.length < BATCH_SIZE;
}
async function runEventPage(tx: Db, companyId: string, run: RunInProgress) {
const batch = await tx
.select({ id: heartbeatRunEvents.id })
.from(heartbeatRunEvents)
.where(and(
eq(heartbeatRunEvents.companyId, companyId),
eq(heartbeatRunEvents.runId, run.id),
gt(heartbeatRunEvents.id, run.eventAfterId),
))
.orderBy(asc(heartbeatRunEvents.id))
.limit(EVENT_BATCH_SIZE);
if (batch.length === 0) return true;
const ids = batch.map((row) => row.id);
const cleared = await tx
.update(heartbeatRunEvents)
.set({ message: null, payload: null as never })
.where(and(
inArray(heartbeatRunEvents.id, ids),
contentEventSql(),
))
.returning({ id: heartbeatRunEvents.id });
if (cleared.length > 0) run.changed = true;
run.eventAfterId = ids[ids.length - 1]!;
return batch.length < EVENT_BATCH_SIZE;
}
async function removeRunLog(companyId: string, runId: string, signal: AbortSignal) {
let removedAny = false;
for (let attempt = 0; attempt < 3; attempt++) {
const [run] = await db
.select({ logStore: heartbeatRuns.logStore, logRef: heartbeatRuns.logRef })
.from(heartbeatRuns)
.where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId)));
if (!run?.logRef && !run?.logStore) return removedAny;
if (!run.logRef || !isRunLogStoreType(run.logStore)) throw new Error("run_log_store_unrecognised");
const handle: RunLogHandle = { store: run.logStore, logRef: run.logRef };
const store = deps.runLogStore();
if (!store.remove) throw new Error("run_log_removal_unavailable");
await store.remove(handle, signal);
const updated = await db
.update(heartbeatRuns)
.set({ logStore: null, logRef: null })
.where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.logStore, run.logStore), eq(heartbeatRuns.logRef, run.logRef)))
.returning({ id: heartbeatRuns.id });
removedAny = true;
if (updated.length > 0) return true;
}
throw new Error("run_log_reference_changed");
}
async function finishRun(tx: Db, companyId: string, run: RunInProgress) {
const [row] = await tx
.select({ stdoutExcerpt: heartbeatRuns.stdoutExcerpt, stderrExcerpt: heartbeatRuns.stderrExcerpt, resultJson: heartbeatRuns.resultJson })
.from(heartbeatRuns)
.where(and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, companyId)))
.for("update");
if (!row) return;
const result = withoutResultText(row.resultJson);
if (row.stdoutExcerpt === null && row.stderrExcerpt === null && !result.changed) return;
await tx
.update(heartbeatRuns)
.set({ stdoutExcerpt: null, stderrExcerpt: null, resultJson: result.value as Record<string, unknown> | null })
.where(and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, companyId)));
run.changed = true;
}
async function deliveredResultsStep(tx: Db, job: DeletionRow, progress: Progress) {
const requests = await tx
.select({ id: toolActionRequests.id, issueId: toolActionRequests.issueId })
.from(toolActionRequests)
.innerJoin(toolInvocations, eq(toolInvocations.id, toolActionRequests.invocationId))
.where(and(
eq(toolActionRequests.companyId, job.companyId),
eq(toolInvocations.companyId, job.companyId),
eq(toolInvocations.connectionId, job.connectionId),
lte(toolInvocations.createdAt, job.requestedAt),
progress.runCursor ? gt(toolActionRequests.id, progress.runCursor) : undefined,
))
.orderBy(asc(toolActionRequests.id))
.limit(DELIVERY_BATCH_SIZE);
if (requests.length === 0) return true;
progress.runCursor = requests[requests.length - 1]!.id;
await clearDeliveredResults(tx, job, progress, requests);
return requests.length < DELIVERY_BATCH_SIZE;
}
async function runsStep(tx: Db, job: DeletionRow, progress: Progress) {
if (!progress.currentRun) {
let runId = progress.pendingRuns.shift() ?? null;
if (!runId) {
const rows = await tx
.select({ id: heartbeatRuns.id })
.from(heartbeatRuns)
.where(and(
progress.runCursor ? gt(heartbeatRuns.id, progress.runCursor) : undefined,
runsWithStoredContentSql({ companyId: job.companyId, connectionId: job.connectionId, cutoff: job.requestedAt }),
))
.orderBy(asc(heartbeatRuns.id))
.limit(RUN_BATCH_SIZE);
if (rows.length === 0) return true;
progress.pendingRuns = rows.map((row) => row.id);
progress.runCursor = rows[rows.length - 1]!.id;
return false;
}
if (!(await settledRunIds(tx, [runId])).has(runId)) {
progress.counts.runsInProgress += 1;
return false;
}
progress.currentRun = { id: runId, eventAfterId: 0, changed: false, stage: "events" };
return false;
}
const run = progress.currentRun;
if (run.stage === "log") {
if (run.changed) progress.counts.runs += 1;
progress.currentRun = null;
return false;
}
if (!(await runEventPage(tx, job.companyId, run))) return false;
await finishRun(tx, job.companyId, run);
run.stage = "log";
return false;
}
async function step(job: DeletionRow, signal: AbortSignal) {
const progress = readProgress(job);
const deletedAt = job.requestedAt.toISOString();
if (progress.currentRun?.stage === "log" && await removeRunLog(job.companyId, progress.currentRun.id, signal)) {
progress.currentRun.changed = true;
}
return db.transaction(async (rawTx) => {
const tx = rawTx as unknown as Db;
const done = progress.phase === "invocations" ? await invocationsStep(tx, job, progress, deletedAt)
: progress.phase === "events" ? await eventsStep(tx, job, progress, deletedAt)
: progress.phase === "auditEvents" ? await auditEventsStep(tx, job, progress, deletedAt)
: progress.phase === "appViews" ? await appViewsStep(tx, job, progress)
: progress.phase === "deliveredResults" ? await deliveredResultsStep(tx, job, progress)
: await runsStep(tx, job, progress);
if (done) {
progress.phase = nextPhase(progress.phase);
progress.cursor = null;
progress.runCursor = null;
progress.currentRun = null;
progress.pendingRuns = [];
}
const [saved] = await tx
.update(toolConnectionContentDeletions)
.set({ progress: progress as unknown as Record<string, unknown>, updatedAt: new Date() })
.where(and(
eq(toolConnectionContentDeletions.id, job.id),
eq(toolConnectionContentDeletions.status, "pending"),
eq(toolConnectionContentDeletions.updatedAt, job.updatedAt),
))
.returning();
if (!saved) throw new ProgressConflict();
return saved;
});
}
async function complete(job: DeletionRow) {
const progress = readProgress(job);
const now = new Date();
return db.transaction(async (tx) => {
const [done] = await tx
.update(toolConnectionContentDeletions)
.set({ status: "completed", completedAt: now, updatedAt: now, lastError: null })
.where(and(
eq(toolConnectionContentDeletions.id, job.id),
eq(toolConnectionContentDeletions.status, "pending"),
eq(toolConnectionContentDeletions.updatedAt, job.updatedAt),
sql`${toolConnectionContentDeletions.progress}->>'phase' = 'done'`,
))
.returning();
if (!done) return null;
await logActivity(tx as unknown as Db, {
companyId: job.companyId,
actorType: job.requestedByActorType === "agent" ? "agent" : job.requestedByActorType === "user" ? "user" : "system",
actorId: job.requestedByActorId ?? "tool-connection-content-deletion",
action: "tool_connection.content_deleted",
entityType: "tool_connection",
entityId: job.connectionId,
details: { ...progress.counts },
});
return done;
});
}
async function process(jobId: string, signal: AbortSignal, budgetMs = STEP_BUDGET_MS) {
const startedAt = Date.now();
let [job] = await db.select().from(toolConnectionContentDeletions).where(eq(toolConnectionContentDeletions.id, jobId));
if (!job || job.status !== "pending") return job ?? null;
try {
while (!signal.aborted) {
if (readProgress(job).phase === "done") return await complete(job);
job = await step(job, signal);
if (Date.now() - startedAt >= budgetMs) return job;
}
return job;
} catch (error) {
if (error instanceof ProgressConflict) return null;
await db
.update(toolConnectionContentDeletions)
.set({
attempts: sql`${toolConnectionContentDeletions.attempts} + 1`,
lastError: error instanceof Error ? error.message.slice(0, 500) : "content deletion failed",
updatedAt: new Date(),
})
.where(and(eq(toolConnectionContentDeletions.id, job.id), eq(toolConnectionContentDeletions.status, "pending")));
throw error;
}
}
async function processPending(signal: AbortSignal) {
const rows = await db
.select({ id: toolConnectionContentDeletions.id })
.from(toolConnectionContentDeletions)
.where(eq(toolConnectionContentDeletions.status, "pending"))
.orderBy(asc(toolConnectionContentDeletions.updatedAt))
.limit(10);
let failure: unknown = null;
for (const { id } of rows) {
if (signal.aborted) break;
try {
await process(id, signal);
} catch (error) {
failure ??= error;
}
}
if (failure) throw failure;
}
async function nextDeadline() {
const [row] = await db
.select({ id: toolConnectionContentDeletions.id })
.from(toolConnectionContentDeletions)
.where(eq(toolConnectionContentDeletions.status, "pending"))
.limit(1);
return row ? Date.now() : null;
}
return { storedContent, latestDeletion, request, process, processPending, nextDeadline };
}
export type ConnectionContentDeletionService = ReturnType<typeof createConnectionContentDeletion>;
@@ -0,0 +1,40 @@
import type { Db } from "@paperclipai/db";
import { DELIVERY_QUEUES } from "./delivery-work-notifications.js";
import { registerDeadlineWork } from "./deadline-work.js";
import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js";
import { registerIdleLocalWorkProbe } from "./idle-local-work.js";
import { getRunLogStore } from "./run-log-store.js";
import { createConnectionContentDeletion } from "./tool-access/connections/content-deletion.js";
export function registerToolConnectionContentDeletionWork(
db: Db,
coordinator: ReturnType<typeof createDeliveryWorkCoordinator>,
canRun: () => boolean,
) {
const deletions = createConnectionContentDeletion(db, { runLogStore: getRunLogStore });
let deadline: number | null | undefined;
const unregister = registerIdleLocalWorkProbe(() => {
if (deadline === undefined) return "unknown";
return deadline === null ? "none" : "present";
});
const worker = registerDeadlineWork(coordinator, DELIVERY_QUEUES.toolConnectionContentDeletion, {
canRun,
retryMs: 30_000,
continuationMs: 250,
onSettled: () => {
deadline = undefined;
},
run: (signal) => signal.aborted ? Promise.resolve() : deletions.processPending(signal),
next: async () => {
deadline = await deletions.nextDeadline();
return deadline;
},
});
return {
...worker,
stop: async () => {
unregister();
await worker.stop();
},
};
}