diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 24e06d59830..bf9f4a03333 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -49,6 +49,18 @@ and leaves all existing cases passive. Source identities are not grants. ### Task query performance +Native session resume selects its newest progress barrier within the existing +32-run task/session window in one SQL snapshot. Only the chosen checkpoint source +returns its saved native input, checkpoint, tool fingerprint, wake envelope, and +canonical task brief. Unused bootstrap candidates do not return full context or +profiles. Wrong runtime, nonterminal status, process identity, provider events, +invalid but non-null checkpoints, and future checkpoint barriers retain their +existing selection rules. Stored run payloads and history reads stay complete. +Run the synthetic PostgreSQL comparison with a pinned pre-change revision: +`pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-native-session-resume-reads.ts --baseline-ref=`. +An optional `PAPERCLIP_SESSION_RESUME_BENCHMARK_DATABASE_URL` must name a dedicated +test database ending in `_test`; otherwise the harness starts disposable PostgreSQL. + Agent request authentication uses a compact run-identity read. It omits saved execution payloads, results, and log excerpts from the query response. The read still locks the task before the run and reconciles pending steering from durable diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index 4853284df55..20f874a17ae 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -1888,6 +1888,17 @@ TLS and protocol metadata. To use an isolated external database, set `PAPERCLIP_CONTINUATION_BENCHMARK_DATABASE_URL` to a disposable database ending in `_test`. The harness applies migrations there and adds synthetic fixtures. +Continuation history reads select completed tool receipts and the typed +conversation/workspace recovery fields used to choose the prior terminal run. +Every completed receipt keeps its full result. Receipt order, company/agent/task +scope, and the complete retained history stay unchanged. Saved results remain +available to detail, recovery, and execution paths. +Use `pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-continuation-history.ts --baseline-ref=` +to compare generated SQL, complete continuation envelopes, and DataRow bytes. +The benchmark includes a large required-receipt control. Its external database +option is `PAPERCLIP_CONTINUATION_HISTORY_BENCHMARK_DATABASE_URL`, with the same +disposable `_test` database restriction. + Retry scheduling is in `server/src/services/heartbeat/retries.ts`. It owns bounded retry schedules, connection and workspace contention deferrals, shared-workspace holder checks, due retry promotion, and retry-now requests. `createHeartbeatRetries` @@ -3371,6 +3382,35 @@ pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-workspace-prepar It compares actual preparation guards with synthetic history. Local timings are separate from Git materialization, environment acquisition, and provider startup. +### Sidebar badge run-query benchmark + +The badge query keeps the newest 200 runs of nonterminated same-company agents. +It selects each agent's first observed run before status or Mine filters. An +observation ordinal preserves equal-time input order. Per-agent ranking orders +by full creation time first, then that ordinal for exact ties. SQL returns only failure +IDs, issue bindings, and creation times. Dismissals and fresh issue authorization +still run in the service. + +Run the synthetic PostgreSQL comparison with a pinned pre-change revision: + +```sh +PAPERCLIP_LOG_LEVEL=error SIDEBAR_REQUIRE_BYTE_REDUCTION=1 pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-sidebar-badges.ts --baseline-ref=bf3ef12f3a78d0b15a32ad57f7e16520fbf6cd5e +``` + +The harness starts disposable embedded PostgreSQL by default. To use an existing +isolated test database with current migrations, set +`PAPERCLIP_SIDEBAR_TEST_DATABASE_URL` to a dedicated database whose name ends in +`_test`. The harness removes only its own synthetic company fixtures. Do not use +a development or hosted company database. + +The report includes service-generated SQL, complete badge equality, candidate +bindings, alternating warm samples, plans, and UTF-8 response-value bytes before +Drizzle decoding. This byte count excludes protocol framing. The mixed fixture +covers shared agents, superseding successes, timestamp ties, Mine users, +dismissal equality, private and deleted issues, and more than 200 runs. The +all-failed, all-succeeded, and empty controls expose neutral or slower paths. +Timings describe local SQL work and do not establish hosted request latency. + ### Budget accounting performance Budget admission and settlement share the company accounting lock. They evaluate diff --git a/doc/plans/2026-10-24-recurring-server-sleep-stack.md b/doc/plans/2026-10-24-recurring-server-sleep-stack.md index b15de420078..3db8fa47099 100644 --- a/doc/plans/2026-10-24-recurring-server-sleep-stack.md +++ b/doc/plans/2026-10-24-recurring-server-sleep-stack.md @@ -18,7 +18,7 @@ Do not mark an item done from a timer removal or a green check alone. | 04 | Decision retention and notifications | Retention deadlines and notification delivery are separate reasons | Pending | | 05 | Decision expiry and interrupted effects | Expiry, effect recovery, continuation recovery | Pending | | 06 | Tool connection health | Configuration/use activation and defined proactive health deadlines | Pending | -| 07 | Secret proposals, tool reviews, gateway tokens | Separate expiry/scrub/recovery owners | Secret proposals: [#17446](https://github.com/paperclipai/paperclip/pull/17446), merged; gateway credentials: [#17450](https://github.com/paperclipai/paperclip/pull/17450), merged; pending tool-review expiry: [#17453](https://github.com/paperclipai/paperclip/pull/17453), merged; approved recovery: [#17454](https://github.com/paperclipai/paperclip/pull/17454), historical argument identity repair verified and awaiting fresh CI/review; other review duties pending | +| 07 | Secret proposals, tool reviews, gateway tokens | Separate expiry/scrub/recovery owners | Secret proposals: [#17446](https://github.com/paperclipai/paperclip/pull/17446), merged; gateway credentials: [#17450](https://github.com/paperclipai/paperclip/pull/17450), merged; pending tool-review expiry: [#17453](https://github.com/paperclipai/paperclip/pull/17453), merged; approved recovery: [#17454](https://github.com/paperclipai/paperclip/pull/17454), merged after current-head CI and both 5/5 reviews; interrupted claims: [#17458](https://github.com/paperclipai/paperclip/pull/17458), merged after current-head CI and both 5/5 reviews; projection: [#17468](https://github.com/paperclipai/paperclip/pull/17468), interaction-link index verified and awaiting fresh CI/review | | 08 | GitHub connection events and continuity | Event discovery/replay and credential continuity separately | Pending | | 09 | Merged-PR confirmations | Candidate writes, webhook activation where supported, outstanding-candidate fallback | Pending | | 10 | External-object refresh | Configuration changes, refresh deadlines, source events | Pending | diff --git a/doc/run-identity-reads.md b/doc/run-identity-reads.md new file mode 100644 index 00000000000..a41b252b411 --- /dev/null +++ b/doc/run-identity-reads.md @@ -0,0 +1,35 @@ +# Run identity reads + +`captureRunIdentity` locks the task before the run. It validates company, agent, +and active status. Pending steering still requires its durable acknowledgement. +The accepted requester is read for each operation. No scope adds a cache or skips +these checks. + +Callers choose a typed read scope: + +| Scope | Retained run data | Consumers | +| --- | --- | --- | +| `identity` | Run and accepted requester identifiers, status | Gateway, native connection tools, connection intents, project skill setup | +| `task_authorization` | Identity, task bindings, wake request, conversation generation, skill-test marker | Projects, workspace repositories, Slack, voice, connection management | +| `token_broker` | Identity, invocation source, task/project/routine and requester attribution | Connection token broker | +| `project_execution` | Task authorization plus runtime mode and the complete saved native execution input | Muse project admission | + +Narrow return types omit unselected columns. JSON projections preserve the types +of retained values. The default full read remains available for compatibility and +explicit inspection. Existing GitHub-credential and request-authentication scopes +keep their current contracts. Execution preparation and recovery retain their +separate complete-input reads. + +The synthetic real-PostgreSQL benchmark captures the actual locked query and +compares every retained column, context and identity result. It keeps the same +five-query reconciliation transaction, checks the unchanged stored run, records +plans and alternating timings, and measures raw PostgreSQL DataRow bytes: + +```sh +pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-run-identity-projections.ts --baseline-ref=623f1dc289a14a699ebbe3f09b94179d38fc2ae2 +``` + +The default uses disposable embedded PostgreSQL. `PAPERCLIP_TEST_DATABASE_URL` +can select a disposable local database whose name ends in `_test`. DataRow bytes +exclude response metadata, TLS and TCP. Byte reduction does not establish a +production latency or billing change. diff --git a/scripts/benchmark-chat-reply-lineage.ts b/scripts/benchmark-chat-reply-lineage.ts new file mode 100644 index 00000000000..353b92de5be --- /dev/null +++ b/scripts/benchmark-chat-reply-lineage.ts @@ -0,0 +1,110 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { promises as fs, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { applyPendingMigrations, createDb, startEmbeddedPostgresTestDatabase, type Db } from "../packages/db/src/index.js"; +import { resolveChatOriginPublicationBindings } from "../server/src/services/issues.js"; +import { captureLineageReads, chatReplyLineageFixture, cleanupChatReplyLineageFixture, expectedLineageContext, type LineageQuery, type LineageResolver } from "../server/src/__tests__/helpers/chat-reply-lineage.js"; +import { resolveExternalTestDatabaseUrl } from "../server/src/__tests__/helpers/external-test-database.js"; + +const repoRoot = fileURLToPath(new URL("../", import.meta.url)); +const ref = process.argv.find(arg => arg.startsWith("--baseline-ref="))?.slice(15); +assert.ok(ref, "Pass a pinned pre-fix --baseline-ref"); +const git = (args: string[]) => execFileSync("git", args, { cwd: repoRoot, encoding: "utf8" }).trim(); +const sourcePath = "server/src/services/issues.ts"; +const baselineRevision = git(["rev-parse", `${ref}^{commit}`]), treatmentRevision = git(["rev-parse", "HEAD"]); +const uncommittedChanges = git(["status", "--porcelain"]), treatmentDiff = git(["diff", "HEAD", "--", sourcePath]); +const sourceHash = () => createHash("sha256").update(readFileSync(path.join(repoRoot, sourcePath))).digest("hex"); +const treatmentSourceSha256 = sourceHash(); +const keepAlive = setInterval(() => {}, 1000); +let db: Db | undefined, temporary: Awaited> | undefined, baselineDirectory: string | undefined; +const companyIds: string[] = []; +let benchmarkFailure: { error: unknown } | undefined; +try { + const externalUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_CHAT_LINEAGE_BENCHMARK_DATABASE_URL"); + if (externalUrl) await applyPendingMigrations(externalUrl); + else temporary = await startEmbeddedPostgresTestDatabase("chat-lineage-benchmark-"); + db = createDb(externalUrl ?? temporary!.connectionString); + baselineDirectory = await fs.mkdtemp(path.join(repoRoot, "server/scripts/.chat-lineage-baseline-")); + const original = pathToFileURL(path.join(repoRoot, sourcePath)); + const baselineSource = execFileSync("git", ["show", `${baselineRevision}:${sourcePath}`], { cwd: repoRoot, encoding: "utf8" }); + await fs.writeFile(path.join(baselineDirectory, "issues.ts"), baselineSource.replace(/(from\s+|import\()(["'])(\.{1,2}\/[^"']+)\2/g, + (_match, prefix: string, quote: string, specifier: string) => `${prefix}${quote}${fileURLToPath(new URL(specifier, original))}${quote}`)); + const baseline = (await import(pathToFileURL(path.join(baselineDirectory, "issues.ts")).href)).resolveChatOriginPublicationBindings as LineageResolver; + const measurements = []; + for (const scenario of [{ name: "small", bytes: 16, hops: 0 }, { name: "wide", bytes: 192 * 1024, hops: 0 }, { name: "wide-24-continuations", bytes: 192 * 1024, hops: 24 }]) { + const f = await chatReplyLineageFixture(db, scenario.bytes); companyIds.push(f.companyId); + let runId = f.root.id; + for (let hop = 0; hop < scenario.hops; hop++) runId = (await f.continueFrom(runId)).run.id; + await db.$client.unsafe("ANALYZE"); + async function capture(resolver: LineageResolver) { + const reads: LineageQuery[] = []; + const result = await resolver(captureLineageReads(db!, reads), f.companyId, f.issueId, runId); + assert.deepEqual(result, f.expected); + assert.equal(reads.length, scenario.hops + 1); + return { result, reads }; + } + const before = await capture(baseline), after = await capture(resolveChatOriginPublicationBindings); + assert.deepEqual(after.result, before.result); + for (let index = 0; index < before.reads.length; index++) { + const row = before.reads[index].rows[0]; + assert.deepEqual(after.reads[index].rows, [{ ...row, contextSnapshot: expectedLineageContext(row.contextSnapshot) }]); + } + const variants = [before, after], samples: number[][] = [[], []], bytes: number[] = [0, 0]; + for (let iteration = 0; iteration < 9; iteration++) { + for (const variant of iteration % 2 ? [1, 0] : [0, 1]) { + const started = performance.now(); let returned = 0; + for (const query of variants[variant].reads) { + const rows = await db.$client.unsafe(query.sql, query.params as never[]).raw(); + returned += rows.reduce((sum, row) => sum + 7 + row.reduce((n: number, value: Buffer | null) => n + 4 + (value?.length ?? 0), 0), 0); + } + if (iteration >= 2) samples[variant].push(performance.now() - started); + bytes[variant] = returned; + } + } + const minimumSaving = Buffer.byteLength(f.context.prompt) * (scenario.hops + 1); + assert.ok(bytes[0] - bytes[1] >= minimumSaving, "All unrelated synthetic body bytes must be removed before transfer"); + const plans = []; + for (const variant of variants) { + const query = variant.reads[0]; + const [plan] = await db.$client.unsafe(`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${query.sql}`, query.params as never[]); + plans.push(plan["QUERY PLAN"]); + } + const timing = (values: number[]) => { const sorted = [...values].sort((a, b) => a - b); return { medianMs: sorted[3], minMs: sorted[0], maxMs: sorted[6], samplesMs: values }; }; + measurements.push({ scenario, bodyBytesPerRun: Buffer.byteLength(f.context.prompt), completeBindingsEqual: true, selectedColumnsEqual: true, + baselineDataRowBytes: bytes[0], treatmentDataRowBytes: bytes[1], minimumSaving, baselineTiming: timing(samples[0]), treatmentTiming: timing(samples[1]), + baselineQueries: before.reads.map(({ rows: _rows, ...query }) => query), treatmentQueries: after.reads.map(({ rows: _rows, ...query }) => query), plans }); + } + assert.equal(sourceHash(), treatmentSourceSha256, "Measured service source changed during the benchmark"); + console.log(JSON.stringify({ baselineRevision, treatmentRevision, sourcePath, treatmentSourceSha256, uncommittedChanges, treatmentDiff, + byteBoundary: "Exact text-format PostgreSQL DataRow frames; excludes row descriptions, command metadata, TLS and TCP. Timings cover captured lineage SQL only, not the complete authorization service.", + dependencyScope: "Only the pinned baseline issues.ts is loaded from history; imported helpers and synthetic fixtures are held identical.", + postgres: await db.$client.unsafe("select version()"), settings: await db.$client.unsafe("select name,setting,unit from pg_settings where name in ('shared_buffers','work_mem','jit') order by name"), + node: process.version, measurements }, null, 2)); +} catch (error) { + benchmarkFailure = { error }; + throw error; +} finally { + try { + try { + if (db) for (const companyId of companyIds) await cleanupChatReplyLineageFixture(db, companyId); + } finally { + try { + await db?.$client.end({ timeout: 0 }); + } finally { + try { + await temporary?.cleanup(); + } finally { + try { + if (baselineDirectory) await fs.rm(baselineDirectory, { recursive: true, force: true }); + } finally { clearInterval(keepAlive); } + } + } + } + } catch (error) { + if (benchmarkFailure) throw new AggregateError([benchmarkFailure.error, error], "Benchmark and cleanup failed"); + throw error; + } +} diff --git a/scripts/benchmark-continuation-history.ts b/scripts/benchmark-continuation-history.ts new file mode 100644 index 00000000000..c26a118c589 --- /dev/null +++ b/scripts/benchmark-continuation-history.ts @@ -0,0 +1,120 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { randomBytes, randomUUID } from "node:crypto"; +import { promises as fs } from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { agents, applyPendingMigrations, companies, createDb, heartbeatRuns, issues, startEmbeddedPostgresTestDatabase, type Db } from "../packages/db/src/index.js"; +import { buildExecutionContinuation } from "../server/src/services/execution-continuation.js"; +import { hasConversationContinuationPolicy } from "../server/src/services/conversation-continuation.js"; +import { resolveExternalTestDatabaseUrl } from "../server/src/__tests__/helpers/external-test-database.js"; + +const repoRoot = fileURLToPath(new URL("../", import.meta.url)); +const git = (...args: string[]) => execFileSync("git", args, { cwd: repoRoot, encoding: "utf8" }); +const baselineRef = process.argv.find(arg => arg.startsWith("--baseline-ref="))?.slice(15); +assert.ok(baselineRef, "Pass a pinned pre-fix --baseline-ref"); +const baselineRevision = git("rev-parse", "--verify", `${baselineRef}^{commit}`).trim(); +const baselineOnly = process.argv.includes("--baseline-only"); +const keepAlive = setInterval(() => {}, 1000); +let database: Awaited> | undefined; +let db: Db | undefined; +let baselineDir: string | undefined; +try { + const externalUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_CONTINUATION_HISTORY_BENCHMARK_DATABASE_URL"); + if (externalUrl) { + await applyPendingMigrations(externalUrl); + database = { connectionString: externalUrl, cleanup: async () => {} }; + } else database = await startEmbeddedPostgresTestDatabase("continuation-history-benchmark-"); + db = createDb(database.connectionString); + const original = new URL("../server/src/services/execution-continuation.ts", import.meta.url); + baselineDir = await fs.mkdtemp(path.join(repoRoot, "server/scripts/.history-baseline-")); + const source = git("show", `${baselineRevision}:server/src/services/execution-continuation.ts`); + const baselinePath = path.join(baselineDir, "continuation.ts"); + await fs.writeFile(baselinePath, source.replace(/(from |import\()"(\.{1,2}\/[^\"]+)"/g, + (_match, prefix: string, specifier: string) => `${prefix}${JSON.stringify(fileURLToPath(new URL(specifier, original)))}`)); + const baseline = await import(pathToFileURL(baselinePath).href) as { buildExecutionContinuation: typeof buildExecutionContinuation }; + const object = (value: unknown): Record => value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; + const receipts = (value: unknown) => Object.entries(object(object(value).apiToolReceipts)).flatMap(([id, entry]) => { + const receipt = object(entry); + return receipt.state === "completed" && typeof receipt.operationId === "string" ? [{ id, operationId: receipt.operationId, result: receipt.result }] : []; + }); + const results = []; + for (const receiptHeavy of [false, true]) { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Synthetic history", issuePrefix: `B${companyId.replaceAll("-", "")}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Fixture", adapterType: "paperclip_runner" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Continue", status: "in_progress", assigneeAgentId: agentId }); + const runCount = receiptHeavy ? 1 : 25; + const requiredResult = receiptHeavy ? randomBytes(1536 * 1024).toString("base64") : { receipt: "required output" }; + for (let index = 0; index < runCount; index++) await db.insert(heartbeatRuns).values({ companyId, agentId, + contextSnapshot: { issueId }, status: "failed", errorCode: "adapter_failed", runtimeMode: "legacy", + createdAt: new Date(Date.UTC(2020, 0, 1, 0, 0, index)), + resultJson: { nativeResult: { output: receiptHeavy ? "small" : randomBytes(144 * 1024).toString("base64") }, + conversationContinuation: "continue_conversation_v1", + apiToolReceipts: { saved: { state: "completed", operationId: "save_document", result: requiredResult, + request: receiptHeavy ? "small" : randomBytes(24 * 1024).toString("base64") }, pending: { state: "started", operationId: "unfinished", result: "not a completed action" } } }, + }); + await db.$client.unsafe("ANALYZE"); + async function capture(invoke: typeof buildExecutionContinuation) { + let query: { sql: string; params: unknown[] } | undefined; + let history: Array> | undefined; + const recorded = new Proxy(db!, { get(target, key) { + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const builder = target.select(...fields), from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const selection = from(...args), execute = selection.execute.bind(selection); + if (args[0] === heartbeatRuns) selection.execute = async (...executeArgs: Parameters) => { + const statement = selection.toSQL(), rows = await execute(...executeArgs); + if (statement.sql.includes('order by "heartbeat_runs"."created_at" asc')) { query = statement; history = rows; } + return rows; + }; + return selection; + }) as typeof builder.from; + return builder; + }; + }}); + const envelope = await invoke({ db: recorded, companyId, issueId, agentId, context: {}, summary: null, exposeLowTrustRaw: false }); + assert.ok(query); assert.ok(history); + return { query, history, envelope }; + } + const before = await capture(baseline.buildExecutionContinuation); + const after = await capture(baselineOnly ? baseline.buildExecutionContinuation : buildExecutionContinuation); + assert.deepEqual(after.envelope, before.envelope); + assert.equal(after.history.length, before.history.length); + for (let index = 0; index < before.history.length; index++) { + const oldRow = before.history[index], newRow = after.history[index]; + for (const [key, value] of Object.entries(oldRow)) if (key !== "result") assert.deepEqual(newRow[key], value); + assert.deepEqual(receipts(newRow.result), receipts(oldRow.result)); + assert.equal(hasConversationContinuationPolicy(newRow.result as Record), hasConversationContinuationPolicy(oldRow.result as Record)); + } + const queries = [before.query, after.query], bytes: number[] = [], samples: number[][] = [[], []]; + for (let iteration = 0; iteration < 9; iteration++) for (const variant of iteration % 2 ? [1, 0] : [0, 1]) { + const query = queries[variant], start = performance.now(); + const rows = await db.$client.unsafe(query.sql, query.params as never[]).raw(); + if (iteration >= 2) samples[variant].push(performance.now() - start); + bytes[variant] = rows.reduce((sum, row) => sum + 7 + row.reduce((n: number, value: Buffer | null) => n + 4 + (value?.length ?? 0), 0), 0); + } + if (!baselineOnly && !receiptHeavy) assert.ok(bytes[1] < bytes[0] / 10, "Wide unused-result fixture must remove more than 90% of DataRow bytes"); + if (receiptHeavy) { + assert.ok(after.envelope.completedActions); + assert.deepEqual(after.envelope.completedActions[0].result, requiredResult); + } + const plans = []; + for (const query of queries) { + const [plan] = await db.$client.unsafe(`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${query.sql}`, query.params as never[]); + plans.push(plan["QUERY PLAN"]); + } + const median = (values: number[]) => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)]; + results.push({ fixture: receiptHeavy ? "required-receipt-result" : "wide-unused-output", runCount, rows: after.history.length, + equalEnvelope: true, equalRetainedColumnsAndReceipts: true, baselineDataRowBytes: bytes[0], treatmentDataRowBytes: bytes[1], + reduction: 1 - bytes[1] / bytes[0], baselineMedianMs: median(samples[0]), treatmentMedianMs: median(samples[1]), samples, queries, plans }); + } + console.log(JSON.stringify({ baselineRevision, treatmentRevision: git("rev-parse", "HEAD").trim(), + treatmentDiff: git("diff", "HEAD", "--", "server/src/services/execution-continuation.ts"), baselineOnly, + byteBoundary: "Exact text-format PostgreSQL DataRow frames, excluding metadata, TLS and TCP", postgres: await db.$client.unsafe("select version()"), results }, null, 2)); +} finally { + try { await db?.$client.end({ timeout: 0 }); await database?.cleanup(); + if (baselineDir) await fs.rm(baselineDir, { recursive: true, force: true }); + } finally { clearInterval(keepAlive); } +} diff --git a/scripts/benchmark-native-session-resume-reads.ts b/scripts/benchmark-native-session-resume-reads.ts new file mode 100644 index 00000000000..df302f1ba71 --- /dev/null +++ b/scripts/benchmark-native-session-resume-reads.ts @@ -0,0 +1,127 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { randomBytes, randomUUID } from "node:crypto"; +import { promises as fs } from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { agents, applyPendingMigrations, companies, createDb, heartbeatRuns, issues, startEmbeddedPostgresTestDatabase, type Db } from "../packages/db/src/index.js"; +import { findNativeSessionResumeRun } from "../server/src/services/native-runtime/native-session-resume.js"; +import { resolveExternalTestDatabaseUrl } from "../server/src/__tests__/helpers/external-test-database.js"; + +type Query = { sql: string; params: unknown[] }; +const root = fileURLToPath(new URL("../", import.meta.url)); +const baselineRef = process.argv.find(arg => arg.startsWith("--baseline-ref="))?.slice(15); +assert.ok(baselineRef, "Pass a pinned pre-fix --baseline-ref"); +const baselineRevision = execFileSync("git", ["rev-parse", "--verify", `${baselineRef}^{commit}`], { cwd: root, encoding: "utf8" }).trim(); +const sourcePath = "server/src/services/native-runtime/native-session-resume.ts"; +const treatmentRevision = execFileSync("git", ["rev-parse", "HEAD"], { cwd: root, encoding: "utf8" }).trim(); +const treatmentDiff = execFileSync("git", ["diff", "HEAD", "--", sourcePath], { cwd: root, encoding: "utf8" }); +const externalUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_SESSION_RESUME_BENCHMARK_DATABASE_URL"); +const database = externalUrl ? { connectionString: externalUrl, cleanup: async () => {} } : await startEmbeddedPostgresTestDatabase("native-session-resume-benchmark-"); +const db = createDb(database.connectionString); +const baselineDir = await fs.mkdtemp(path.join(root, "server/scripts/.session-resume-baseline-")); +const companyIds: string[] = []; +try { + if (externalUrl) await applyPendingMigrations(externalUrl); + const moduleUrl = new URL(`../${sourcePath}`, import.meta.url); + const source = execFileSync("git", ["show", `${baselineRevision}:${sourcePath}`], { cwd: root, encoding: "utf8" }); + await fs.writeFile(path.join(baselineDir, "resume.ts"), source.replace(/from "(\.{1,2}\/[^\"]+)"/g, + (_match, specifier: string) => `from ${JSON.stringify(fileURLToPath(new URL(specifier, moduleUrl)))}`)); + const baseline = await import(pathToFileURL(path.join(baselineDir, "resume.ts")).href) as { findNativeSessionResumeRun: typeof findNativeSessionResumeRun }; + async function capture(invoke: typeof findNativeSessionResumeRun, input: Parameters[1]) { + const queries: Query[] = []; + const wrap = (target: Db): Db => new Proxy(target, { get(target, key) { + if (key === "with") return (...args: Parameters) => wrap(target.with(...args) as Db); + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const builder = target.select(...fields), from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const query = from(...args), execute = query.execute.bind(query); + query.execute = async (...executeArgs: Parameters) => { + queries.push(query.toSQL()); + return execute(...executeArgs); + }; + return query; + }) as typeof builder.from; + return builder; + }; + }}); + return { result: await invoke(wrap(db), input), queries }; + } + const median = (values: number[]) => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)]; + const measurements = []; + for (const scenario of ["wide_history", "unused_history", "small_selected"] as const) { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), normalizedSessionId = randomUUID(); + companyIds.push(companyId); + await db.insert(companies).values({ id: companyId, name: "Synthetic resume benchmark", issuePrefix: `B${companyId.replaceAll("-", "")}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Synthetic runner", adapterType: "paperclip_runner" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Retain canonical task" }); + const runCount = scenario === "small_selected" ? 1 : 15; + const prompt = randomBytes(scenario === "small_selected" ? 16 : 144 * 1024).toString("base64"); + const profilePadding = randomBytes(scenario === "small_selected" ? 16 : 72 * 1024).toString("base64"); + const neededInput = { task: { title: "Prior task", description: "Canonical description", prompt: profilePadding }, runtimeContext: { instructions: "Keep complete input" } }; + const checkpoint = { sessionId: normalizedSessionId, state: randomBytes(4096).toString("base64") }; + await db.insert(heartbeatRuns).values(Array.from({ length: runCount }, (_, n) => ({ + id: randomUUID(), companyId, agentId, nativeIssueId: issueId, nativeSessionId: normalizedSessionId, + runtimeMode: "native", status: "failed", createdAt: new Date(Date.UTC(2026, 8, 8, 0, 0, n)), + runnerProfileJson: { padding: "Unused profile metadata", nativeExecutionInput: neededInput, nativeToolContractFingerprint: "fixture", + ...(scenario !== "unused_history" && n === 0 ? { sessionCheckpoint: checkpoint } : {}) }, + contextSnapshot: { prompt, paperclipWake: { externalChatProvider: "slack", githubReviewConfigurations: [{ key: "review" }] }, + paperclipIssue: { id: issueId, title: "Prior canonical title", description: "Prior canonical description" } }, + }))); + await db.$client.unsafe("ANALYZE heartbeat_runs"); + const input = { companyId, agentId, issueId, normalizedSessionId, currentRunId: randomUUID(), beforeCreatedAt: new Date("2026-09-09T00:00:00Z") }; + const before = await capture(baseline.findNativeSessionResumeRun, input), after = await capture(findNativeSessionResumeRun, input); + const contract = (run: typeof after.result) => run && ({ ...run, + runnerProfileJson: { nativeExecutionInput: run.runnerProfileJson?.nativeExecutionInput ?? null, + nativeToolContractFingerprint: run.runnerProfileJson?.nativeToolContractFingerprint ?? null, + sessionCheckpoint: run.runnerProfileJson?.sessionCheckpoint ?? null }, + contextSnapshot: { paperclipWake: run.contextSnapshot?.paperclipWake ?? null, paperclipIssue: run.contextSnapshot?.paperclipIssue ?? null } }); + assert.deepEqual(contract(after.result), contract(before.result)); + const variants = [before.queries, after.queries], samples: number[][] = [[], []], dataRowBytes = [0, 0], resultRows = [0, 0]; + for (let iteration = 0; iteration < 9; iteration++) { + for (const variant of iteration % 2 ? [1, 0] : [0, 1]) { + const start = performance.now(); + let bytes = 0, count = 0; + for (const query of variants[variant]) { + const rows = await db.$client.unsafe(query.sql, query.params as never[]).raw(); + count += rows.length; + bytes += rows.reduce((total, row) => total + 7 + row.reduce((size: number, value: Buffer | null) => size + 4 + (value?.length ?? 0), 0), 0); + } + if (iteration >= 2) samples[variant].push(performance.now() - start); + dataRowBytes[variant] = bytes; resultRows[variant] = count; + } + } + const plans = []; + for (const queries of variants) { + const variantPlans = []; + for (const query of queries) { + const [plan] = await db.$client.unsafe(`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${query.sql}`, query.params as never[]); + variantPlans.push(plan["QUERY PLAN"]); + } + plans.push(variantPlans); + } + if (!process.argv.includes("--baseline-only") && scenario !== "small_selected") assert.ok(dataRowBytes[1] < dataRowBytes[0] / 10); + measurements.push({ scenario, runCount, equalConsumerFields: true, baselineQueryCount: before.queries.length, treatmentQueryCount: after.queries.length, + dataRowBytes, resultRows, baselineMedianMs: median(samples[0]), treatmentMedianMs: median(samples[1]), samples, queries: variants, plans }); + } + console.log(JSON.stringify({ baselineRevision, treatmentRevision, treatmentDiff, + acceptance: "Equal selected consumer fields; wide and unused histories remove at least 90% of DataRow bytes; no timing threshold", + byteBoundary: "Exact text-format PostgreSQL DataRow frames (7 bytes framing + 4 bytes length per column + raw field bytes); excludes RowDescription, command metadata, TLS and TCP", + postgres: await db.$client.unsafe("select version()"), measurements }, null, 2)); +} finally { + try { + for (const companyId of companyIds) { + await db.$client.unsafe("DELETE FROM heartbeat_runs WHERE company_id = $1::uuid", [companyId]); + await db.$client.unsafe("DELETE FROM issues WHERE company_id = $1::uuid", [companyId]); + await db.$client.unsafe("DELETE FROM agents WHERE company_id = $1::uuid", [companyId]); + await db.$client.unsafe("DELETE FROM companies WHERE id = $1::uuid", [companyId]); + } + } finally { + try { await db.$client.end({ timeout: 0 }); } + finally { + try { await database.cleanup(); } + finally { await fs.rm(baselineDir, { recursive: true, force: true }); } + } + } +} diff --git a/scripts/benchmark-run-identity-projections.ts b/scripts/benchmark-run-identity-projections.ts new file mode 100644 index 00000000000..4ddc589ef3b --- /dev/null +++ b/scripts/benchmark-run-identity-projections.ts @@ -0,0 +1,120 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { promises as fs } from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { applyPendingMigrations, createDb, startEmbeddedPostgresTestDatabase } from "../packages/db/src/index.js"; +import { captureRunIdentity } from "../server/src/services/run-identity.js"; +import { captureIdentityQueries, seedIdentityProjection, type IdentityQuery } from "../server/src/__tests__/helpers/run-identity-projection-fixture.js"; + +const root = fileURLToPath(new URL("../", import.meta.url)); +const git = (args: string[]) => execFileSync("git", args, { cwd: root, encoding: "utf8" }); +const baselineRef = process.argv.find(arg => arg.startsWith("--baseline-ref="))?.slice(15); +assert.ok(baselineRef, "Pass an explicit pre-fix --baseline-ref="); +const baselineRevision = git(["rev-parse", "--verify", `${baselineRef}^{commit}`]).trim(); +const modulePath = "server/src/services/run-identity.ts"; +const unchangedHelpers = ["run-task-binding.ts", "task-retry.ts", "issue-queued-comment-queue.ts"]; +for (const name of unchangedHelpers) { + const helper = `server/src/services/${name}`; + assert.equal(git(["show", `${baselineRevision}:${helper}`]), await fs.readFile(path.join(root, helper), "utf8"), + `Baseline helper ${name} changed; isolate it before benchmarking`); +} +const keepAlive = setInterval(() => {}, 1_000); +let temporary: Awaited> | undefined; +let db: ReturnType | undefined; +let baselineDir: string | undefined; +try { + const oldSource = git(["show", `${baselineRevision}:${modulePath}`]); + const moduleUrl = new URL(`../${modulePath}`, import.meta.url); + baselineDir = await fs.mkdtemp(path.join(root, "server/scripts/.identity-projection-baseline-")); + const baselineFile = path.join(baselineDir, "run-identity.ts"); + await fs.writeFile(baselineFile, oldSource.replace(/from "(\.{1,2}\/[^\"]+)"/g, + (_match, specifier: string) => `from ${JSON.stringify(fileURLToPath(new URL(specifier, moduleUrl)))}`)); + const baseline = await import(pathToFileURL(baselineFile).href) as typeof import("../server/src/services/run-identity.js"); + const externalUrl = process.env.PAPERCLIP_TEST_DATABASE_URL; + if (externalUrl) { + const parsed = new URL(externalUrl); + assert.ok(["127.0.0.1", "localhost"].includes(parsed.hostname) && /_test$/.test(parsed.pathname), + "External benchmark database must be a disposable local *_test database"); + await applyPendingMigrations(externalUrl); + db = createDb(externalUrl); + } else { + temporary = await startEmbeddedPostgresTestDatabase("identity-projection-benchmark-"); + db = createDb(temporary.connectionString); + } + const f = await seedIdentityProjection(db); + await db.$client.unsafe("ANALYZE"); + const beforeQueries: IdentityQuery[] = []; + const before = await baseline.captureRunIdentity(captureIdentityQueries(db, beforeQueries), f); + const findRunQuery = (queries: IdentityQuery[]) => { + const query = queries.find(query => query.sql.includes('from "heartbeat_runs"') && query.sql.includes("for no key update")); + assert.ok(query, "Capture the actual locked identity query"); + return query; + }; + const beforeQuery = findRunQuery(beforeQueries); + const dataRowBytes = async (query: IdentityQuery) => { + const rows = await db!.$client.unsafe(query.sql, query.params as never[]).raw(); + return rows.reduce((total, row) => total + 7 + 4 * row.length + row.reduce((bytes, value) => bytes + (value?.byteLength ?? 0), 0), 0); + }; + const baselineBytes = await dataRowBytes(beforeQuery); + async function plan(query: IdentityQuery) { + const [result] = await db!.$client.unsafe(`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${query.sql}`, query.params as never[]); + return result!["QUERY PLAN"]; + } + const results = []; + for (const readScope of ["identity", "task_authorization", "token_broker", "project_execution"] as const) { + const afterQueries: IdentityQuery[] = []; + const after = await captureRunIdentity(captureIdentityQueries(db, afterQueries), f, { readScope }); + assert.deepEqual(after.context, before.context); + for (const [key, value] of Object.entries(after.run)) { + if (key === "runnerProfileJson") assert.deepEqual(value, { nativeExecutionInput: before.run.runnerProfileJson?.nativeExecutionInput }); + else if (key !== "contextSnapshot") assert.deepEqual(value, before.run[key as keyof typeof before.run], `Retained ${key}`); + else { + const snapshot = value as Record; + for (const [name, selected] of Object.entries(snapshot)) { + if (name !== "paperclipIssue") assert.deepEqual(selected, before.run.contextSnapshot?.[name] ?? null, `Retained context ${name}`); + else for (const [nested, item] of Object.entries(selected as Record)) + assert.deepEqual(item, (before.run.contextSnapshot?.paperclipIssue as Record)?.[nested] ?? null, `Retained nested ${nested}`); + } + } + } + const afterQuery = findRunQuery(afterQueries), afterBytes = await dataRowBytes(afterQuery); + assert.ok(afterBytes < baselineBytes * (readScope === "project_execution" ? 0.5 : 0.05), + "Fixture acceptance: remove at least 95% of authority bytes or 50% while preserving complete execution input"); + assert.equal(afterQueries.length, beforeQueries.length, "No queries added or removed from identity reconciliation"); + const samples = { baseline: [] as number[], treatment: [] as number[] }; + for (let n = 0; n < 9; n++) { + for (const version of n % 2 ? ["treatment", "baseline"] as const : ["baseline", "treatment"] as const) { + const start = performance.now(); + if (version === "baseline") await baseline.captureRunIdentity(db, f); + else await captureRunIdentity(db, f, { readScope }); + if (n >= 2) samples[version].push(performance.now() - start); + } + } + const stats = (values: number[]) => { + const sorted = [...values].sort((a, b) => a - b); + return { samplesMs: values, medianMs: sorted[Math.floor(sorted.length / 2)], minMs: sorted[0], maxMs: sorted.at(-1) }; + }; + results.push({ readScope, baselineBytes, treatmentBytes: afterBytes, reductionPercent: 100 * (1 - afterBytes / baselineBytes), + retainedColumnsAndContextEqual: true, identityContextEqual: true, queryCount: afterQueries.length, + generatedSql: { baseline: beforeQuery, treatment: afterQuery }, + timings: { scope: "complete captureRunIdentity service transaction", warmups: 2, samples: 7, order: "alternating", + baseline: stats(samples.baseline), treatment: stats(samples.treatment) }, + plans: { baseline: await plan(beforeQuery), treatment: await plan(afterQuery) } }); + } + assert.deepEqual((await captureRunIdentity(db, f)).run, before.run, "Complete stored run unchanged"); + console.log(JSON.stringify({ baselineRevision, treatmentRevision: git(["rev-parse", "HEAD"]).trim(), + treatmentDiff: git(["diff", "HEAD", "--", "server/src"]), unchangedHelpers, + postgresVersion: (await db.$client.unsafe("SELECT version()"))[0]!.version, + settings: await db.$client.unsafe("SELECT name, setting FROM pg_settings WHERE name IN ('block_size','shared_buffers','work_mem','jit') ORDER BY name"), + fixture: { runs: 1, synthetic: true, contextBytes: Buffer.byteLength(JSON.stringify(f.payloads.contextSnapshot)), + profileBytes: Buffer.byteLength(JSON.stringify(f.payloads.runnerProfileJson)) }, + measurement: "PostgreSQL DataRow messages from raw text-format buffers; excludes metadata, TLS and TCP", results, + }, null, 2)); +} finally { + try { + await db?.$client.end({ timeout: 0 }); + await temporary?.cleanup(); + if (baselineDir) await fs.rm(baselineDir, { recursive: true, force: true }); + } finally { clearInterval(keepAlive); } +} diff --git a/scripts/benchmark-sidebar-badges.ts b/scripts/benchmark-sidebar-badges.ts new file mode 100644 index 00000000000..6e45bb45a65 --- /dev/null +++ b/scripts/benchmark-sidebar-badges.ts @@ -0,0 +1,104 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { promises as fs } from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { createDb, startEmbeddedPostgresTestDatabase, type Db } from "../packages/db/src/index.js"; +import { sidebarBadgeService } from "../server/src/services/sidebar-badges.js"; +import { captureSidebarQueries, cleanupSidebarFixture, observedSidebarFailures, seedSidebarFixture, type CapturedQuery } from "../server/src/__tests__/helpers/sidebar-badges-fixture.js"; + +const baselineRef = process.argv.find(arg => arg.startsWith("--baseline-ref="))?.slice(15); +assert.ok(baselineRef, "Pass --baseline-ref="); +const baselineRevision = execFileSync("git", ["rev-parse", "--verify", `${baselineRef}^{commit}`], { encoding: "utf8" }).trim(); +const treatmentRevision = execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim(); +const externalUrl = process.env.PAPERCLIP_SIDEBAR_TEST_DATABASE_URL; +assert.ok(!externalUrl || new URL(externalUrl).pathname.endsWith("_test"), "Use a dedicated synthetic *_test database"); +const keepAlive = setInterval(() => {}, 1000); +let database: Awaited> | undefined; +let baselineDir: string | undefined; +let db: Db | undefined; +const fixtures: Awaited>[] = []; +let failure: unknown; +try { + if (!externalUrl) database = await startEmbeddedPostgresTestDatabase("sidebar-benchmark-"); + db = createDb(externalUrl ?? database!.connectionString); + const modulePath = "server/src/services/sidebar-badges.ts"; + const moduleUrl = new URL(`../${modulePath}`, import.meta.url); + const source = execFileSync("git", ["show", `${baselineRevision}:${modulePath}`], { encoding: "utf8" }); + const rewritten = source.replace(/from "(\.{1,2}\/[^\"]+)"/g, + (_match, specifier: string) => `from ${JSON.stringify(fileURLToPath(new URL(specifier, moduleUrl)))}`); + baselineDir = await fs.mkdtemp(path.join(fileURLToPath(new URL("../server/scripts/", import.meta.url)), ".sidebar-baseline-")); + const baselineFile = path.join(baselineDir, "sidebar-badges.ts"); + await fs.writeFile(baselineFile, rewritten); + const baseline = await import(pathToFileURL(baselineFile).href) as typeof import("../server/src/services/sidebar-badges.js"); + const [{ version }] = await db.$client.unsafe("select version()"); + const settings = await db.$client.unsafe("select name, setting from pg_settings where name in ('work_mem', 'shared_buffers', 'jit', 'max_parallel_workers_per_gather')"); + const results = []; + for (const mode of ["mixed", "all-failed", "all-succeeded", "empty"] as const) { + const fixture = await seedSidebarFixture(db, mode); + fixtures.push(fixture); + await db.$client.unsafe("ANALYZE heartbeat_runs"); + await db.$client.unsafe("ANALYZE agents"); + const users = mode === "mixed" ? [undefined, null, "", "user-1", "user-2", "local-board", "nobody"] : [undefined]; + for (const currentUserId of users) { + const queries = { baseline: [] as CapturedQuery[], treatment: [] as CapturedQuery[] }; + const before = baseline.sidebarBadgeService(captureSidebarQueries(db, queries.baseline)); + const after = sidebarBadgeService(captureSidebarQueries(db, queries.treatment)); + const options = { ...fixture.options, currentUserId }; + const baselineResponse = await before.get(fixture.companyId, options); + const treatmentResponse = await after.get(fixture.companyId, options); + assert.deepEqual(treatmentResponse, baselineResponse); + assert.equal(queries.baseline.length, 1); + assert.equal(queries.treatment.length, 1); + const expected = await observedSidebarFailures(db, fixture.companyId, currentUserId); + const normalize = (rows: unknown[][]) => rows.map(row => JSON.stringify(row)).sort(); + const baselineQuery = queries.baseline[0]!, treatmentQuery = queries.treatment[0]!; + const treatmentRows = await db.$client.unsafe(treatmentQuery.sql, treatmentQuery.params as never[]).values(); + if (treatmentQuery.sql !== baselineQuery.sql) { + assert.deepEqual(normalize(treatmentRows.map(row => [...row.slice(0, 3), new Date(String(row[3])).toISOString()])), normalize(expected.map(row => [row.id, row.scopeKind, row.issueId, row.createdAt.toISOString()]))); + } + const samples = { baseline: [] as number[], treatment: [] as number[] }; + const rowsByVersion: Record = {}; + for (let iteration = 0; iteration < 9; iteration++) { + for (const label of iteration % 2 ? ["treatment", "baseline"] as const : ["baseline", "treatment"] as const) { + const query = label === "baseline" ? baselineQuery : treatmentQuery; + const start = performance.now(); + rowsByVersion[label] = await db.$client.unsafe(query.sql, query.params as never[]).values(); + if (iteration >= 2) samples[label].push(performance.now() - start); + } + } + const measurements = []; + for (const label of ["baseline", "treatment"] as const) { + const query = label === "baseline" ? baselineQuery : treatmentQuery; + const rows = rowsByVersion[label]!; + const responseValueBytes = rows.flat().reduce((sum, value) => sum + (value == null ? 0 : Buffer.byteLength(typeof value === "string" ? value : String(value))), 0); + const [plan] = await db.$client.unsafe(`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${query.sql}`, query.params as never[]); + const sorted = [...samples[label]].sort((a, b) => a - b); + measurements.push({ label, query, rows: rows.length, responseValueBytes, samplesMs: samples[label], medianMs: sorted[3], minMs: sorted[0], maxMs: sorted[6], plan: plan!["QUERY PLAN"] }); + } + if (process.env.SIDEBAR_REQUIRE_BYTE_REDUCTION === "1" && mode !== "empty") { + assert.ok(measurements[1]!.responseValueBytes < measurements[0]!.responseValueBytes); + } + results.push({ mode, currentUserId: currentUserId === undefined ? "" : currentUserId, equalBadgeResponse: treatmentResponse, equalCandidateRows: expected.length, measurements }); + } + } + console.log(JSON.stringify({ baselineRevision, treatmentRevision, + treatmentDiff: execFileSync("git", ["diff", "--", modulePath], { encoding: "utf8" }), + dependencyPolicy: "Baseline imports unchanged current authorization, privacy, and shared helpers", version, settings, + acceptance: "Identical complete badges and candidate bindings; fewer response-value bytes for nonempty fixtures. Timings are descriptive with no latency threshold.", + byteBoundary: "UTF-8 non-null cell values before Drizzle decoding, excluding PostgreSQL protocol framing; not wire bytes", + results }, null, 2)); +} catch (error) { + failure = error; +} finally { + const errors: unknown[] = failure === undefined ? [] : [failure]; + async function cleanup(action: () => Promise | undefined) { + try { await action(); } catch (error) { errors.push(error); } + } + if (db) for (const fixture of fixtures) await cleanup(() => cleanupSidebarFixture(db!, fixture)); + await cleanup(() => db?.$client.end({ timeout: 0 })); + await cleanup(() => database?.cleanup()); + await cleanup(() => baselineDir ? fs.rm(baselineDir, { recursive: true, force: true }) : undefined); + clearInterval(keepAlive); + if (errors.length) throw new AggregateError(errors, "Sidebar benchmark or cleanup failed"); +} diff --git a/server/src/__tests__/company-skills-routes.test.ts b/server/src/__tests__/company-skills-routes.test.ts index f40bfa0f8ce..11fe51213a7 100644 --- a/server/src/__tests__/company-skills-routes.test.ts +++ b/server/src/__tests__/company-skills-routes.test.ts @@ -1264,7 +1264,7 @@ describe("company skill mutation permissions", () => { const response = await request(createApp(agent)).post("/api/companies/company-1/skills/import") .send({ source: "https://github.com/acme/public-skills" }); expect(response.status, JSON.stringify(response.body)).toBe(201); - expect(mockCaptureRunIdentity).toHaveBeenCalledWith(expect.anything(), { companyId: "company-1", agentId: agent.agentId, runId: "run-1" }); + expect(mockCaptureRunIdentity).toHaveBeenCalledWith(expect.anything(), { companyId: "company-1", agentId: agent.agentId, runId: "run-1" }, { readScope: "identity" }); expect(mockSkillSourceService.importFromUrl).toHaveBeenCalledWith("company-1", expect.anything(), expect.objectContaining({ setup: { userId: "validated-owner", agentId: agent.agentId, localTrusted: false } })); }); diff --git a/server/src/__tests__/helpers/chat-reply-lineage.ts b/server/src/__tests__/helpers/chat-reply-lineage.ts new file mode 100644 index 00000000000..5a5b65baedc --- /dev/null +++ b/server/src/__tests__/helpers/chat-reply-lineage.ts @@ -0,0 +1,67 @@ +import { randomBytes, randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { agents, agentWakeupRequests, chatConversations, chatEndpoints, chatMessageLinks, companies, heartbeatRuns, issueComments, issues, issueThreadInteractions, toolApplications, toolConnections, toolActionRequests, toolActionDeliveries, toolInvocations, type Db } from "@paperclipai/db"; +import { resolveChatOriginPublicationBindings } from "../../services/issues.js"; + +export const lineageContextKeys = ["issueId", "taskId", "wakeCommentIds", "wakeCommentId", "commentId", "source", "sourceRunId", "interactionId", "endpointId"] as const; +export type LineageResolver = typeof resolveChatOriginPublicationBindings; +export type LineageQuery = { sql: string; params: unknown[]; rows: Array> }; + +export function captureLineageReads(db: Db, queries: LineageQuery[]): Db { + return new Proxy(db, { get(target, key) { + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const builder = target.select(...fields), from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const query = from(...args), execute = query.execute.bind(query); + if (args[0] === heartbeatRuns) query.execute = async (...executeArgs: Parameters) => { + const statement = query.toSQL(); + const rows = await execute(...executeArgs); + if (fields[0] && Object.keys(fields[0]).join(",") === "agentId,responsibleUserId,contextSnapshot") queries.push({ ...statement, rows }); + return rows; + }; + return query; + }) as typeof builder.from; + return builder; + }; + } }); +} + +export function expectedLineageContext(value: unknown): unknown { + if (value === null || typeof value !== "object" || Array.isArray(value)) return value; + return Object.fromEntries(lineageContextKeys.filter(key => Object.hasOwn(value, key)).map(key => [key, (value as Record)[key]])); +} + +export async function chatReplyLineageFixture(db: Db, bytes = 192 * 1024) { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Synthetic reply lineage", issuePrefix: `L${companyId.replaceAll("-", "").slice(0, 7)}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Synthetic worker", adapterType: "paperclip_runner" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Synthetic external reply", status: "in_progress", assigneeAgentId: agentId }); + const [application] = await db.insert(toolApplications).values({ companyId, name: "Synthetic chat", applicationKey: randomUUID(), type: "chat" }).returning(); + const [connection] = await db.insert(toolConnections).values({ companyId, applicationId: application.id, name: "Synthetic chat", uid: randomUUID(), transport: "chat_sdk", connectionPurpose: "channel" }).returning(); + const [endpoint] = await db.insert(chatEndpoints).values({ companyId, connectionId: connection.id, assignedAgentId: agentId, provider: "slack", publicId: randomUUID(), status: "active" }).returning(); + const [conversation] = await db.insert(chatConversations).values({ companyId, endpointId: endpoint.id, issueId, externalConversationId: randomUUID(), externalThreadId: randomUUID(), externalLabel: "Synthetic conversation" }).returning(); + const [comment] = await db.insert(issueComments).values({ companyId, issueId, authorType: "user", authorUserId: "synthetic-requester", body: "Please continue" }).returning(); + await db.insert(chatMessageLinks).values({ companyId, endpointId: endpoint.id, conversationId: conversation.id, commentId: comment.id, providerMessageId: randomUUID(), direction: "inbound" }); + const context = { source: "chat:slack", issueId, endpointId: endpoint.id, wakeCommentIds: [comment.id], prompt: randomBytes(bytes).toString("base64") }; + const insertRun = async (snapshot: unknown = context, overrides: Partial = {}) => { + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "succeeded", contextSnapshot: snapshot as never, ...overrides }).returning(); + return run; + }; + const root = await insertRun(); + async function continueFrom(sourceRunId: string) { + const [interaction] = await db.insert(issueThreadInteractions).values({ companyId, issueId, sourceRunId, kind: "request_confirmation", status: "accepted", payload: { version: 1 } as never }).returning(); + const run = await insertRun({ issueId, source: "issue.interaction.accept", sourceRunId, interactionId: interaction.id, prompt: context.prompt }); + const [wake] = await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "automation", reason: "issue_commented", status: "claimed", runId: run.id, idempotencyKey: `interaction:${interaction.id}:accepted` }).returning(); + return { run, interaction, wake }; + } + return { companyId, agentId, issueId, endpoint, conversation, comment, context, root, insertRun, continueFrom, + expected: [{ companyId, endpointId: endpoint.id, conversationId: conversation.id }] }; +} + +export async function cleanupChatReplyLineageFixture(db: Db, companyId: string) { + for (const table of [agentWakeupRequests, toolActionDeliveries, toolActionRequests, toolInvocations, issueThreadInteractions, chatMessageLinks, chatConversations, chatEndpoints, heartbeatRuns, issueComments, issues, toolConnections, toolApplications, agents]) { + await db.delete(table).where(eq(table.companyId, companyId)); + } + await db.delete(companies).where(eq(companies.id, companyId)); +} diff --git a/server/src/__tests__/helpers/run-identity-projection-fixture.ts b/server/src/__tests__/helpers/run-identity-projection-fixture.ts new file mode 100644 index 00000000000..5072e37060f --- /dev/null +++ b/server/src/__tests__/helpers/run-identity-projection-fixture.ts @@ -0,0 +1,41 @@ +import { randomBytes, randomUUID } from "node:crypto"; +import { agents, companies, heartbeatRuns, issueComments, issues, type Db } from "@paperclipai/db"; +import { initializeRunIdentity } from "../../services/run-identity.js"; + +export async function seedIdentityProjection(db: Db) { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID(), messageId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Synthetic identity", issuePrefix: companyId }); + await db.insert(agents).values({ id: agentId, companyId, name: "Identity reader", adapterType: "process" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Identity task", assigneeAgentId: agentId, + conversationAgentId: agentId, conversationUserId: "operator", conversationState: "active", conversationSessionGeneration: 3, workMode: "standard" }); + const payloads = { contextSnapshot: { issueId, conversationSessionGeneration: 3, paperclipSkillTest: false, + projectId: randomUUID(), routineId: randomUUID(), paperclipIssue: { id: issueId, projectId: randomUUID(), + responsibleUserId: "nested-user", document: randomBytes(8_192).toString("base64") }, + savedInput: randomBytes(96 * 1_024).toString("base64") }, + runnerProfileJson: { nativeExecutionInput: { savedInput: randomBytes(48 * 1_024).toString("base64") }, + unrelatedProfileDocument: randomBytes(8_192).toString("base64") }, + resultJson: { retained: randomBytes(4_096).toString("base64") }, stdoutExcerpt: "retained stdout", stderrExcerpt: "retained stderr" }; + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", nativeIssueId: issueId, + runtimeMode: "native", invocationSource: "automation", ...payloads }); + await db.insert(issueComments).values({ id: messageId, companyId, issueId, authorUserId: "next-user", body: "New request" }); + const context = await initializeRunIdentity(db, { companyId, runId, issueId, responsibleUserId: "operator", cause: "instruction" }); + return { companyId, agentId, issueId, runId, messageId, context, payloads }; +} + +export type IdentityQuery = { sql: string; params: unknown[] }; +export function captureIdentityQueries(db: Db, queries: IdentityQuery[]): Db { + return new Proxy(db, { get(target, key) { + if (key === "transaction") return (action: (tx: Db) => Promise) => + target.transaction(tx => action(captureIdentityQueries(tx as unknown as Db, queries))); + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const builder = target.select(...fields), from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const selection = from(...args), execute = selection.execute.bind(selection); + selection.execute = async () => { queries.push(selection.toSQL()); return execute(); }; + return selection; + }) as typeof builder.from; + return builder; + }; + }}); +} diff --git a/server/src/__tests__/helpers/sidebar-badges-fixture.ts b/server/src/__tests__/helpers/sidebar-badges-fixture.ts new file mode 100644 index 00000000000..7effeb74757 --- /dev/null +++ b/server/src/__tests__/helpers/sidebar-badges-fixture.ts @@ -0,0 +1,127 @@ +import { randomUUID } from "node:crypto"; +import { and, desc, eq, inArray, not, sql } from "drizzle-orm"; +import { agents, approvals, companies, heartbeatRuns, issues, type Db } from "@paperclipai/db"; +import { isHeartbeatRunVisibleInMine, latestFailedRunsByAgent } from "@paperclipai/shared"; +import type { sidebarBadgeService } from "../../services/sidebar-badges.js"; + +export type BadgeOptions = Parameters["get"]>[1]; +export type CapturedQuery = { sql: string; params: unknown[] }; + +export function captureSidebarQueries(db: Db, queries: CapturedQuery[]): Db { + return new Proxy(db, { get(target, key) { + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const builder = target.select(...fields), from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const selection = from(...args), execute = selection.execute.bind(selection); + selection.execute = async () => { + const query = selection.toSQL(); + if (query.sql.includes('"heartbeat_runs"')) queries.push(query); + return execute(); + }; + return selection; + }) as typeof builder.from; + return builder; + }; + }}); +} + +export async function observedSidebarFailures(db: Db, companyId: string, currentUserId?: string | null) { + const rows = await db.select({ + id: heartbeatRuns.id, agentId: heartbeatRuns.agentId, companyId: heartbeatRuns.companyId, + scopeKind: heartbeatRuns.scopeKind, issueId: heartbeatRuns.issueId, status: heartbeatRuns.status, + responsibleUserId: heartbeatRuns.responsibleUserId, createdAt: heartbeatRuns.createdAt, + }).from(heartbeatRuns).innerJoin(agents, eq(heartbeatRuns.agentId, agents.id)).where(and( + eq(heartbeatRuns.companyId, companyId), eq(agents.companyId, companyId), not(eq(agents.status, "terminated")), + )).orderBy(desc(heartbeatRuns.createdAt)).limit(200); + return latestFailedRunsByAgent(rows).filter(row => currentUserId === undefined || isHeartbeatRunVisibleInMine(row, currentUserId)); +} + +export async function seedSidebarFixture(db: Db, mode: "mixed" | "all-failed" | "all-succeeded" | "empty" = "mixed") { + return db.transaction(async tx => { + const companyId = randomUUID(), foreignCompanyId = randomUUID(); + await tx.insert(companies).values([ + { id: companyId, name: "Synthetic sidebar", issuePrefix: `B${companyId.slice(0, 7)}` }, + { id: foreignCompanyId, name: "Foreign sidebar", issuePrefix: `F${foreignCompanyId.slice(0, 7)}` }, + ]); + const actorId = randomUUID(); + await tx.insert(agents).values({ id: actorId, companyId, name: "Reader", role: "engineer" }); + const actor = { type: "agent" as const, agentId: actorId, companyId }; + const privateIssueId = randomUUID(), publicIssueId = randomUUID(), deletedIssueId = randomUUID(); + await tx.insert(issues).values([ + { id: privateIssueId, companyId, title: "Private", visibility: "private", privacyRootIssueId: privateIssueId, responsibleUserId: "other-user" }, + { id: publicIssueId, companyId, title: "Public" }, + { id: deletedIssueId, companyId, title: "Deleted" }, + ]); + const origin = Date.parse("2026-10-01T00:00:00.000Z"); + const agentIds = Array.from({ length: mode === "all-failed" ? 240 : 30 }, () => randomUUID()); + await tx.insert(agents).values(agentIds.map((id, index) => ({ id, companyId, name: `Agent ${index}`, role: "engineer" }))); + const runs: (typeof heartbeatRuns.$inferInsert)[] = []; + if (mode !== "empty") { + for (let index = 0; index < 420; index++) { + const agentIndex = index % agentIds.length; + runs.push({ id: randomUUID(), companyId, agentId: agentIds[agentIndex]!, + status: mode === "all-failed" ? "failed" : mode === "all-succeeded" ? "succeeded" : ["failed", "timed_out", "succeeded", "running", "queued", "cancelled"][agentIndex % 6], + responsibleUserId: ["user-1", "user-2", null, "", "local-board"][agentIndex % 5], + createdAt: new Date(origin + index), invocationSource: "manual" }); + } + } + const special: Record = {}; + if (mode === "mixed") { + async function add(name: string, values: Partial = {}) { + const agentId = randomUUID(), id = randomUUID(); + await tx.insert(agents).values({ id: agentId, companyId, name, role: "engineer" }); + runs.push({ id, companyId, agentId, status: "failed", responsibleUserId: "user-1", createdAt: new Date(origin + 1000 + runs.length), ...values }); + special[name] = id; + return agentId; + } + await add("outside-window", { createdAt: new Date(origin - 1000) }); + const shared = await add("superseded"); + runs.push({ companyId, agentId: shared, status: "succeeded", responsibleUserId: "user-2", createdAt: new Date(origin + 2000) }); + const foreignOwner = await add("other-user-latest"); + runs.push({ companyId, agentId: foreignOwner, status: "failed", responsibleUserId: "user-2", createdAt: new Date(origin + 2001) }); + await add("private", { scopeKind: "issue", issueId: privateIssueId }); + await add("public", { scopeKind: "issue", issueId: publicIssueId }); + await add("deleted", { scopeKind: "issue", issueId: deletedIssueId }); + await add("missing", { scopeKind: "issue", issueId: null }); + await add("dismissed"); + for (const [name, status] of [["tied-failure-first", "failed"], ["tied-success-first", "succeeded"]] as const) { + const agentId = await add(name, { status, createdAt: new Date(origin + 3000) }); + runs.push({ companyId, agentId, status: status === "failed" ? "succeeded" : "failed", responsibleUserId: "user-1", createdAt: new Date(origin + 3000) }); + } + const terminated = randomUUID(), crossCompanyAgent = randomUUID(); + await tx.insert(agents).values([ + { id: terminated, companyId, name: "Terminated", status: "terminated" }, + { id: crossCompanyAgent, companyId: foreignCompanyId, name: "Foreign" }, + ]); + for (let index = 0; index < 220; index++) runs.push({ companyId, agentId: index % 2 ? terminated : crossCompanyAgent, + status: "failed", responsibleUserId: "user-1", createdAt: new Date(origin + 10000 + index) }); + runs.push({ companyId: foreignCompanyId, agentId: crossCompanyAgent, status: "failed", createdAt: new Date(origin + 20000) }); + } + if (runs.length) await tx.insert(heartbeatRuns).values(runs); + if (mode === "mixed") { + await tx.delete(issues).where(eq(issues.id, deletedIssueId)); + const microAgent = randomUUID(); + await tx.insert(agents).values({ id: microAgent, companyId, name: "Submillisecond" }); + await tx.execute(sql`insert into heartbeat_runs (company_id, agent_id, status, responsible_user_id, created_at) values + (${companyId}, ${microAgent}, 'failed', 'user-1', '2026-10-01 00:00:04.000100+00'), + (${companyId}, ${microAgent}, 'succeeded', 'user-2', '2026-10-01 00:00:04.000900+00')`); + } + const approvalId = randomUUID(); + await tx.insert(approvals).values({ id: approvalId, companyId, type: "hire_agent", status: "pending", payload: {}, updatedAt: new Date(origin) }); + const dismissals = new Map([[`approval:${approvalId}`, origin]]); + const dismissed = runs.find(row => row.id === special.dismissed); + if (dismissed) dismissals.set(`run:${dismissed.id}`, (dismissed.createdAt as Date).getTime()); + return { companyId, foreignCompanyId, actor, actorId, privateIssueId, publicIssueId, special, dismissals, + options: { dismissals, joinRequests: [{ id: "join", createdAt: new Date(origin), updatedAt: null }], unreadTouchedIssues: 2, actor } satisfies BadgeOptions }; + }); +} + +export async function cleanupSidebarFixture(db: Db, fixture: Awaited>) { + const companyIds = [fixture.companyId, fixture.foreignCompanyId]; + await db.delete(heartbeatRuns).where(inArray(heartbeatRuns.companyId, companyIds)); + await db.delete(approvals).where(inArray(approvals.companyId, companyIds)); + await db.delete(issues).where(inArray(issues.companyId, companyIds)); + await db.delete(agents).where(inArray(agents.companyId, companyIds)); + await db.delete(companies).where(inArray(companies.id, companyIds)); +} diff --git a/server/src/__tests__/project-skill-setup-identity.test.ts b/server/src/__tests__/project-skill-setup-identity.test.ts index 844c4f7df71..d08cd9ec867 100644 --- a/server/src/__tests__/project-skill-setup-identity.test.ts +++ b/server/src/__tests__/project-skill-setup-identity.test.ts @@ -13,7 +13,7 @@ it('keeps responsibility without searching personal GitHub grants when the run h it('pins only the connection and grant already authorized for the active run', async () => { capture.mockResolvedValue({ run: { responsibleUserId: 'person' }, context: { github: { status: 'available', connectionId: 'selected', grantId: 'grant' } } }); expect(await projectSkillSetupIdentity(db, 'company', actor)).toMatchObject({ refreshUserId: 'person', connectionId: 'selected', refreshGrantId: 'grant' }); - expect(capture).toHaveBeenCalledWith(db, { companyId: 'company', agentId: 'agent', runId: 'run' }); + expect(capture).toHaveBeenCalledWith(db, { companyId: 'company', agentId: 'agent', runId: 'run' }, { readScope: 'identity' }); }); it('does not reuse an unavailable run credential', async () => { capture.mockResolvedValue({ run: { responsibleUserId: 'person' }, context: { github: { status: 'unavailable', connectionId: 'old', grantId: 'old' } } }); diff --git a/server/src/__tests__/run-identity-projections.test.ts b/server/src/__tests__/run-identity-projections.test.ts new file mode 100644 index 00000000000..1e7132029a2 --- /dev/null +++ b/server/src/__tests__/run-identity-projections.test.ts @@ -0,0 +1,116 @@ +import { randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { applyPendingMigrations, createDb, heartbeatRuns, issues, type Db } from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { captureIdentityQueries, seedIdentityProjection, type IdentityQuery } from "./helpers/run-identity-projection-fixture.js"; +import { captureRunIdentity } from "../services/run-identity.js"; +import { projectToolContext } from "../services/project-tool-context.js"; +import { boundRunIssueId } from "../services/run-task-binding.js"; + +const externalDatabaseUrl = process.env.PAPERCLIP_TEST_DATABASE_URL; +const support = externalDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); +const scopes = ["identity", "task_authorization", "token_broker"] as const; +(support.supported ? describe : describe.skip)("operation identity read projections", () => { + let temporary: Awaited> | undefined; + let db: Db; + beforeAll(async () => { + if (externalDatabaseUrl) { + await applyPendingMigrations(externalDatabaseUrl); + db = createDb(externalDatabaseUrl); + } else { + temporary = await startEmbeddedPostgresTestDatabase("identity-projection-"); + db = createDb(temporary.connectionString); + } + }, 90_000); + afterAll(async () => { await db?.$client.end({ timeout: 0 }); await temporary?.cleanup(); }); + + it.each(scopes)("bounds %s SQL results and preserves the stored execution", async readScope => { + const f = await seedIdentityProjection(db), queries: IdentityQuery[] = []; + const full = await captureRunIdentity(db, f); + const narrow = await captureRunIdentity(captureIdentityQueries(db, queries), f, { readScope }); + expect(narrow.context).toEqual(full.context); + expect(narrow.run).toMatchObject({ id: f.runId, companyId: f.companyId, agentId: f.agentId, + status: "running", responsibleUserId: "operator", activeIdentityContextId: full.run.activeIdentityContextId }); + expect(narrow.run).not.toHaveProperty("runnerProfileJson"); + expect(narrow.run).not.toHaveProperty("resultJson"); + const query = queries.find(query => query.sql.includes('from "heartbeat_runs"') && query.sql.includes("for no key update"))!; + const rows = await db.$client.unsafe(query.sql, query.params as never[]).raw(); + expect(rows).toHaveLength(1); + expect(rows[0]!.reduce((bytes, value) => bytes + (value?.byteLength ?? 0), 0)).toBeLessThan(2_048); + expect((await captureRunIdentity(db, f)).run).toEqual(full.run); + }); + + it("preserves task binding types and legacy non-object contexts", async () => { + const f = await seedIdentityProjection(db); + for (const snapshot of [null, false, 42, "text", [], ["value"], {}, ...[null, false, 42, " 3 ", [], {}, { nested: true }] + .map(value => ({ issueId: f.issueId, conversationSessionGeneration: value, paperclipSkillTest: value }))]) { + await db.$client.unsafe("UPDATE heartbeat_runs SET context_snapshot = $1::jsonb WHERE id = $2", [JSON.stringify(snapshot), f.runId]); + const full = await captureRunIdentity(db, f), narrow = await captureRunIdentity(db, f, { readScope: "task_authorization" }); + expect(boundRunIssueId(narrow.run)).toBe(boundRunIssueId(full.run)); + expect(Number(narrow.run.contextSnapshot?.conversationSessionGeneration ?? 0)).toBe(Number(full.run.contextSnapshot?.conversationSessionGeneration ?? 0)); + expect(Boolean(narrow.run.contextSnapshot?.paperclipSkillTest)).toBe(Boolean(full.run.contextSnapshot?.paperclipSkillTest)); + } + for (const issueId of [true, 123, [], {}, "malformed"]) { + await db.$client.unsafe("UPDATE heartbeat_runs SET context_snapshot = $1::jsonb WHERE id = $2", [JSON.stringify({ issueId }), f.runId]); + await expect(captureRunIdentity(db, f)).rejects.toThrow("task identity is invalid"); + await expect(captureRunIdentity(db, f, { readScope: "task_authorization" })).rejects.toThrow("task identity is invalid"); + } + }); + + it("retains broker fields and nested attribution without document payloads", async () => { + const f = await seedIdentityProjection(db); + for (const value of [null, true, 42, " padded ", [], {}, { retained: true }]) { + const snapshot = { issueId: f.issueId, projectId: value, routineId: value, responsibleUserId: value, + responsible_user_id: value, paperclipIssue: { id: value, projectId: value, responsibleUserId: value, + responsible_user_id: value, savedDocument: f.payloads.contextSnapshot.savedInput } }; + await db.update(heartbeatRuns).set({ contextSnapshot: snapshot }).where(eq(heartbeatRuns.id, f.runId)); + const narrow = await captureRunIdentity(db, f, { readScope: "token_broker" }); + expect(narrow.run.invocationSource).toBe("automation"); + expect(narrow.run.contextSnapshot).toEqual({ ...snapshot, paperclipIssue: { id: value, + projectId: value, responsibleUserId: value, responsible_user_id: value } }); + } + for (const paperclipIssue of [null, true, 42, "legacy", []]) { + await db.update(heartbeatRuns).set({ contextSnapshot: { paperclipIssue } }).where(eq(heartbeatRuns.id, f.runId)); + expect((await captureRunIdentity(db, f, { readScope: "token_broker" })).run.contextSnapshot?.paperclipIssue).toBeNull(); + } + }); + + it.each(scopes.flatMap(readScope => (["company", "agent", "run", "finished"] as const).map(fault => ({ readScope, fault }))))( + "denies $fault mismatches for $readScope", async ({ readScope, fault }) => { + const f = await seedIdentityProjection(db); + if (fault === "finished") await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, f.runId)); + await expect(captureRunIdentity(db, { ...f, ...(fault === "company" ? { companyId: randomUUID() } : + fault === "agent" ? { agentId: randomUUID() } : fault === "run" ? { runId: randomUUID() } : {}) }, { readScope })).rejects.toThrow("active run"); + }, + ); + + it("preserves every saved native input shape without unrelated profile fields", async () => { + const f = await seedIdentityProjection(db); + for (const nativeExecutionInput of [null, true, 42, "legacy", [], {}, { opaque: { retained: true } }]) { + await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeExecutionInput, unrelated: "drop" } }).where(eq(heartbeatRuns.id, f.runId)); + expect((await captureRunIdentity(db, f, { readScope: "project_execution" })).run.runnerProfileJson).toEqual({ nativeExecutionInput }); + } + await db.update(heartbeatRuns).set({ runnerProfileJson: { unrelated: "drop" } }).where(eq(heartbeatRuns.id, f.runId)); + expect((await captureRunIdentity(db, f, { readScope: "project_execution" })).run.runnerProfileJson).toEqual({}); + for (const profile of [null, true, 42, "legacy", []]) { + await db.$client.unsafe("UPDATE heartbeat_runs SET runner_profile_json = $1::jsonb WHERE id = $2", [JSON.stringify(profile), f.runId]); + expect((await captureRunIdentity(db, f, { readScope: "project_execution" })).run.runnerProfileJson).toBeNull(); + } + }); + + it("keeps the complete execution input for the project admission consumer", async () => { + const f = await seedIdentityProjection(db); + const actor = { type: "agent" as const, source: "agent_jwt" as const, companyId: f.companyId, agentId: f.agentId, runId: f.runId }; + const narrow = await projectToolContext(db, actor); + expect(narrow.run).not.toHaveProperty("runnerProfileJson"); + const full = await projectToolContext(db, actor, true, "Project", { includeExecutionInput: true }); + expect(full.run.runnerProfileJson).toEqual({ nativeExecutionInput: f.payloads.runnerProfileJson.nativeExecutionInput }); + expect(full.run.contextSnapshot).toEqual(narrow.run.contextSnapshot); + expect(full.run).not.toHaveProperty("resultJson"); + expect(full.run.contextSnapshot).not.toHaveProperty("savedInput"); + await db.update(issues).set({ conversationSessionGeneration: 4 }).where(eq(issues.id, f.issueId)); + await expect(projectToolContext(db, actor)).rejects.toThrow("session has changed"); + await expect(projectToolContext(db, actor, true, "Project", { includeExecutionInput: true })).rejects.toThrow("session has changed"); + }); +}); diff --git a/server/src/__tests__/run-identity.test.ts b/server/src/__tests__/run-identity.test.ts index 069139a8123..1cc8ed20f7a 100644 --- a/server/src/__tests__/run-identity.test.ts +++ b/server/src/__tests__/run-identity.test.ts @@ -1,19 +1,23 @@ import { randomUUID } from "node:crypto"; import { eq, sql } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { agentWakeupRequests, agents, companies, createDb, heartbeatRuns, heartbeatRunEvents, issueComments, issueThreadInteractions, issues, secretAccessEvents } from "@paperclipai/db"; +import { agentWakeupRequests, agents, companies, applyPendingMigrations, createDb, closeRegisteredClients, heartbeatRuns, heartbeatRunEvents, issueComments, issueThreadInteractions, issues, secretAccessEvents } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; import { acceptSteeredIdentity, captureRunIdentity, initializeRunIdentity, listRunIdentityContexts, rejectSteeredIdentity, reserveSteeredIdentity } from "../services/run-identity.js"; -const support = await getEmbeddedPostgresTestSupport(); +const externalDatabaseUrl = process.env.PAPERCLIP_TEST_DATABASE_URL; +const support = externalDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); (support.supported ? describe : describe.skip)("durable execution identity", () => { let database: Awaited>; let db: ReturnType; beforeAll(async () => { - database = await startEmbeddedPostgresTestDatabase("paperclip-run-identity-"); - db = createDb(database.connectionString); + if (externalDatabaseUrl) { await applyPendingMigrations(externalDatabaseUrl); db = createDb(externalDatabaseUrl); } + else { + database = await startEmbeddedPostgresTestDatabase("paperclip-run-identity-"); + db = createDb(database.connectionString); + } }, 30_000); - afterAll(async () => { await database?.cleanup(); }, 60_000); + afterAll(async () => { if (externalDatabaseUrl) await closeRegisteredClients(externalDatabaseUrl); await database?.cleanup(); }, 60_000); async function seed() { const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID(); @@ -123,7 +127,7 @@ const support = await getEmbeddedPostgresTestSupport(); }, ); - it.each([undefined, "github_credentials", "request_authentication"] as const)("holds acquisition during uncertain steering and never rewinds on replay with %s", async (readScope) => { + it.each([undefined, "github_credentials", "request_authentication", "identity", "task_authorization", "token_broker", "project_execution"] as const)("holds acquisition during uncertain steering and never rewinds on replay with %s", async (readScope) => { const options = readScope ? { readScope } : undefined; const input = await seed(); await initializeRunIdentity(db, { ...input, messageIds: [input.messageIds[0]], responsibleUserId: "A", cause: "instruction" }); @@ -176,7 +180,7 @@ const support = await getEmbeddedPostgresTestSupport(); expect(captured.run.responsibleUserId).toBeNull(); expect(captured.context?.parentContextId).toBe(origin.id); }); - it.each([undefined, "github_credentials", "request_authentication"] as const)("recovers an uncertain native acknowledgement with %s", async (readScope) => { + it.each([undefined, "github_credentials", "request_authentication", "identity", "task_authorization", "token_broker", "project_execution"] as const)("recovers an uncertain native acknowledgement with %s", async (readScope) => { const options = readScope ? { readScope } : undefined; const input = await seed(); await initializeRunIdentity(db, { ...input, messageIds: [], responsibleUserId: "A", cause: "instruction" }); @@ -260,9 +264,9 @@ const support = await getEmbeddedPostgresTestSupport(); await expect(initialization).resolves.toMatchObject({ responsibleUserId: "A" }); }); - it.each(["initialize", "capture"] as const)( - "can %s identity while an audit append holds foreign-key locks", - async (operation) => { + it.each((["initialize", "capture"] as const).flatMap(operation => [false, true].map(withQuery => ({ operation, withQuery }))))( + "can $operation identity while an audit append holds foreign-key locks (query: $withQuery)", + async ({ operation, withQuery }) => { const input = await seed(); if (operation === "capture") { await initializeRunIdentity(db, { ...input, messageIds: [], responsibleUserId: "A", cause: "instruction" }); @@ -270,11 +274,22 @@ const support = await getEmbeddedPostgresTestSupport(); // A real append holds KEY SHARE on both parent rows until it commits. // Bound the other connection's wait so a conflicting lock fails this // regression instead of leaving both transactions waiting for each other. - const identityDb = createDb(`${database.connectionString}?options=-c%20lock_timeout%3D1000`, { + const identityUrl = new URL(externalDatabaseUrl ?? database.connectionString); + if (withQuery) { + identityUrl.searchParams.set("application_name", "identity-query-test"); + identityUrl.searchParams.set("options", [identityUrl.searchParams.get("options"), "-c statement_timeout=5000"].filter(Boolean).join(" ")); + } + identityUrl.searchParams.set("options", [identityUrl.searchParams.get("options"), "-c lock_timeout=1000"].filter(Boolean).join(" ")); + const identityDb = createDb(identityUrl.toString(), { maxConnections: 1, }); const [settings] = await identityDb.execute(sql`show lock_timeout`); expect(settings?.lock_timeout).toBe("1s"); + if (withQuery) { + expect(identityUrl.searchParams.get("application_name")).toBe("identity-query-test"); + const [timeouts] = await identityDb.execute(sql`show statement_timeout`); + expect(timeouts?.statement_timeout).toBe("5s"); + } await db.transaction(async (audit) => { await audit.insert(secretAccessEvents).values({ companyId: input.companyId, diff --git a/server/src/__tests__/sidebar-badges.test.ts b/server/src/__tests__/sidebar-badges.test.ts new file mode 100644 index 00000000000..9830424dde9 --- /dev/null +++ b/server/src/__tests__/sidebar-badges.test.ts @@ -0,0 +1,139 @@ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { count, eq, inArray } from "drizzle-orm"; +import { agents, approvals, companies, createDb, getEmbeddedPostgresTestSupport, heartbeatRuns, issueAccessGrants, issues, startEmbeddedPostgresTestDatabase, type Db } from "@paperclipai/db"; +import { sidebarBadgeService } from "../services/sidebar-badges.js"; +import { authorizationService } from "../services/authorization.js"; +import { getHeartbeatRunReadDecisions } from "../services/heartbeat-run-privacy.js"; +import { captureSidebarQueries, cleanupSidebarFixture, observedSidebarFailures, seedSidebarFixture, type BadgeOptions, type CapturedQuery } from "./helpers/sidebar-badges-fixture.js"; + +const externalUrl = process.env.PAPERCLIP_SIDEBAR_TEST_DATABASE_URL; +const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); +const describePostgres = support.supported ? describe : describe.skip; +if (!support.supported) console.warn(`Skipping sidebar badge SQL tests: ${support.reason}`); + +describePostgres("sidebar badge failure candidates", () => { + let db: ReturnType; + let database: Awaited> | undefined; + const fixtures: Awaited>[] = []; + let fixture: Awaited>; + + beforeAll(async () => { + if (externalUrl && !new URL(externalUrl).pathname.endsWith("_test")) throw new Error("Use a dedicated synthetic *_test database"); + if (!externalUrl) database = await startEmbeddedPostgresTestDatabase("sidebar-badges-"); + db = createDb(externalUrl ?? database!.connectionString, { maxConnections: 1 }); + fixture = await seedSidebarFixture(db); + fixtures.push(fixture); + }, 90_000); + + afterAll(async () => { + const errors: unknown[] = []; + async function cleanup(action: () => Promise | undefined) { + try { await action(); } catch (error) { errors.push(error); } + } + for (const entry of fixtures) await cleanup(() => cleanupSidebarFixture(db, entry)); + await cleanup(() => db?.$client.end({ timeout: 0 })); + await cleanup(() => database?.cleanup()); + if (errors.length) throw new AggregateError(errors, "Sidebar test cleanup failed"); + }); + + async function verify(options?: BadgeOptions) { + const queries: CapturedQuery[] = []; + const actual = await sidebarBadgeService(captureSidebarQueries(db, queries)).get(fixture.companyId, options); + const expectedCandidates = await observedSidebarFailures(db, fixture.companyId, options?.currentUserId); + const candidates = await db.$client.unsafe(queries[0]!.sql, queries[0]!.params as never[]).values(); + const normalize = (rows: unknown[][]) => rows.map(row => JSON.stringify(row)).sort(); + expect(normalize(candidates.map(row => [...row.slice(0, 3), new Date(String(row[3])).toISOString()]))).toEqual(normalize( + expectedCandidates.map(row => [row.id, row.scopeKind, row.issueId, row.createdAt.toISOString()]), + )); + expect(expectedCandidates.map(row => row.id)).not.toContain(fixture.special.superseded); + expect(expectedCandidates.map(row => row.id)).not.toContain(fixture.special["outside-window"]); + const undismissed = expectedCandidates.filter(row => (options?.dismissals?.get(`run:${row.id}`) ?? -Infinity) < row.createdAt.getTime()); + const failedRuns = options?.actor + ? (await getHeartbeatRunReadDecisions(db, authorizationService(db), options.actor, undismissed)).filter(Boolean).length + : undismissed.length; + const approvals = options?.dismissals ? 0 : 1; + const joinRequests = options?.joinRequests?.length ?? 0; + expect(actual).toEqual({ inbox: approvals + failedRuns + joinRequests + (options?.unreadTouchedIssues ?? 0), approvals, failedRuns, joinRequests }); + return actual; + } + + it("rolls back all fixture rows when the final approval insert fails", async () => { + let companyIds: string[] = []; + let writtenRuns = 0; + function failLastInsert>(connection: T): T { + return new Proxy(connection, { get(target, key) { + if (key !== "insert") return Reflect.get(target, key); + return (table: Parameters[0]) => { + if (table === companies) return { values: (values: (typeof companies.$inferInsert)[]) => { + companyIds = values.map(row => row.id!); + fixtures.push({ ...fixture, companyId: companyIds[0]!, foreignCompanyId: companyIds[1]! }); + return target.insert(companies).values(values); + }}; + if (table === approvals) return { values: async (values: typeof approvals.$inferInsert) => { + const [row] = await target.select({ value: count() }).from(heartbeatRuns).where(inArray(heartbeatRuns.companyId, companyIds)); + writtenRuns = row!.value; + return target.insert(approvals).values({ ...values, payload: null as never }); + }}; + return target.insert(table); + }; + }}); + } + const failingDb = new Proxy(failLastInsert(db), { get(target, key) { + if (key !== "transaction") return Reflect.get(target, key); + return (callback: Parameters[0]) => db.transaction(tx => callback(failLastInsert(tx))); + }}); + await expect(seedSidebarFixture(failingDb)).rejects.toMatchObject({ cause: { code: "23502" } }); + expect(companyIds).toHaveLength(2); + expect(writtenRuns).toBeGreaterThan(600); + const rows = await Promise.all([ + db.select({ value: count() }).from(companies).where(inArray(companies.id, companyIds)), + db.select({ value: count() }).from(agents).where(inArray(agents.companyId, companyIds)), + db.select({ value: count() }).from(issues).where(inArray(issues.companyId, companyIds)), + db.select({ value: count() }).from(heartbeatRuns).where(inArray(heartbeatRuns.companyId, companyIds)), + db.select({ value: count() }).from(approvals).where(inArray(approvals.companyId, companyIds)), + ]); + expect(rows.map(([row]) => row!.value)).toEqual([0, 0, 0, 0, 0]); + }); + + it.each([undefined, null, "", "user-1", "user-2", "local-board", "nobody"])("keeps the bounded latest run before Mine filtering for %s", async currentUserId => { + await verify({ ...fixture.options, currentUserId }); + }); + + it("retains company-wide behavior without an actor or options", async () => { + await verify(); + await verify({ ...fixture.options, actor: undefined }); + await verify({ ...fixture.options, actor: { type: "none" } }); + }); + + it("rechecks private issue grants and deletion on every request", async () => { + const service = sidebarBadgeService(db); + const options = { ...fixture.options, currentUserId: "user-1" }; + const denied = await service.get(fixture.companyId, options); + const [grant] = await db.insert(issueAccessGrants).values({ issueId: fixture.privateIssueId, subjectType: "agent", subjectId: fixture.actorId, source: "explicit" }).returning(); + const allowed = await service.get(fixture.companyId, options); + expect(allowed.failedRuns).toBe(denied.failedRuns + 1); + await db.update(issueAccessGrants).set({ revokedAt: new Date() }).where(eq(issueAccessGrants.id, grant!.id)); + expect(await service.get(fixture.companyId, options)).toEqual(denied); + await db.delete(issues).where(eq(issues.id, fixture.publicIssueId)); + expect((await service.get(fixture.companyId, options)).failedRuns).toBe(denied.failedRuns - 1); + await verify(options); + }); + + it("preserves equal-time input order with index and sort plans", async () => { + await db.$client.unsafe("SET enable_indexscan = off"); + await db.$client.unsafe("SET enable_bitmapscan = off"); + try { await verify(fixture.options); } + finally { + await db.$client.unsafe("RESET enable_indexscan"); + await db.$client.unsafe("RESET enable_bitmapscan"); + } + }); + + it.each(["all-failed", "all-succeeded", "empty"] as const)("handles the %s control", async mode => { + const control = await seedSidebarFixture(db, mode); + fixtures.push(control); + const response = await sidebarBadgeService(db).get(control.companyId); + const failedRuns = mode === "all-failed" ? 200 : 0; + expect(response).toEqual({ inbox: failedRuns + 1, approvals: 1, failedRuns, joinRequests: 0 }); + }); +}); diff --git a/server/src/routes/projects.ts b/server/src/routes/projects.ts index c6479982335..272051bf521 100644 --- a/server/src/routes/projects.ts +++ b/server/src/routes/projects.ts @@ -423,7 +423,7 @@ export function projectRoutes(db: Db) { // The receipt lock can wait too. Keep current authority behind every // admission wait and ahead of both receipt replay and project creation. await withExternalExecutionAdmission(tx, actorCompanyId, agentId, runId, async () => { - const current = await projectToolContext(tx as unknown as Db, museActor, true); + const current = await projectToolContext(tx as unknown as Db, museActor, true, "Project", { includeExecutionInput: true }); try { const execution = parseNativeExecutionInput(current.run.runnerProfileJson?.nativeExecutionInput); const broker = museExternalAgents(db); diff --git a/server/src/services/chat-reply-lineage-context.test.ts b/server/src/services/chat-reply-lineage-context.test.ts new file mode 100644 index 00000000000..41ad66d3f3e --- /dev/null +++ b/server/src/services/chat-reply-lineage-context.test.ts @@ -0,0 +1,111 @@ +import { randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { applyPendingMigrations, createDb, heartbeatRuns, agentWakeupRequests, toolInvocations, toolActionRequests, toolActionDeliveries } from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; +import { resolveExternalTestDatabaseUrl } from "../__tests__/helpers/external-test-database.js"; +import { captureLineageReads, chatReplyLineageFixture, cleanupChatReplyLineageFixture, expectedLineageContext, type LineageQuery } from "../__tests__/helpers/chat-reply-lineage.js"; +import { resolveChatOriginPublicationBindings } from "./issues.js"; + +const externalUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_TEST_DATABASE_URL"); +const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); +describe.skipIf(!support.supported)("chat reply lineage context projection", () => { + let db: ReturnType; + let temporary: Awaited> | undefined; + const companyIds: string[] = []; + async function fixture(bytes?: number) { const f = await chatReplyLineageFixture(db, bytes); companyIds.push(f.companyId); return f; } + beforeAll(async () => { + if (externalUrl) await applyPendingMigrations(externalUrl); + else temporary = await startEmbeddedPostgresTestDatabase("chat-lineage-projection-"); + db = createDb(externalUrl ?? temporary!.connectionString); + }, 90_000); + afterAll(async () => { + try { + if (db) for (const companyId of companyIds) await cleanupChatReplyLineageFixture(db, companyId); + } finally { + try { await db?.$client.end({ timeout: 0 }); } + finally { await temporary?.cleanup(); } + } + }); + + it("projects the complete routing context before a wide body crosses PostgreSQL", async () => { + const f = await fixture(), reads: LineageQuery[] = []; + expect(await resolveChatOriginPublicationBindings(captureLineageReads(db, reads), f.companyId, f.issueId, f.root.id)).toEqual(f.expected); + expect(reads).toHaveLength(1); + const rows = await db.$client.unsafe(reads[0].sql, reads[0].params as never[]).raw(); + expect(rows.reduce((total, row) => total + row.reduce((n: number, value: Buffer | null) => n + (value?.length ?? 0), 0), 0)).toBeLessThan(1024); + expect(reads[0].rows).toEqual([{ agentId: f.agentId, responsibleUserId: null, contextSnapshot: expectedLineageContext(f.context) }]); + }); + + it.each([null, false, true, 0, 12, "", "malformed", [], ["source", { source: "chat:slack" }], {}, + { issueId: null, taskId: false, source: 3, interactionId: null, wakeCommentIds: { id: "not-array" } }, + ])("preserves malformed JSON and key absence for %j", async snapshot => { + const f = await fixture(1), run = await f.insertRun(snapshot), reads: LineageQuery[] = []; + expect(await resolveChatOriginPublicationBindings(captureLineageReads(db, reads), f.companyId, f.issueId, run.id)).toEqual([]); + expect(reads[0].rows[0].contextSnapshot).toEqual(expectedLineageContext(snapshot)); + }); + + it("keeps all nine keys and their JSON values, including explicit nulls and arrays", async () => { + const f = await fixture(1); + const snapshot = { issueId: null, taskId: f.issueId, wakeCommentIds: [f.comment.id, 1, null, f.comment.id], wakeCommentId: f.comment.id, commentId: f.comment.id, + source: "chat:slack", sourceRunId: { invalid: true }, interactionId: null, endpointId: f.endpoint.id, omitted: "wide unrelated value" }; + const run = await f.insertRun(snapshot), reads: LineageQuery[] = []; + expect(await resolveChatOriginPublicationBindings(captureLineageReads(db, reads), f.companyId, f.issueId, run.id)).toEqual(f.expected); + expect(reads[0].rows[0].contextSnapshot).toEqual(expectedLineageContext(snapshot)); + expect(Object.hasOwn(reads[0].rows[0].contextSnapshot as object, "interactionId")).toBe(true); + expect(Object.hasOwn(reads[0].rows[0].contextSnapshot as object, "omitted")).toBe(false); + }); + + it("preserves explicit JSON null as well as SQL null", async () => { + const f = await fixture(1), run = await f.insertRun(null), reads: LineageQuery[] = []; + await db.$client.unsafe("update heartbeat_runs set context_snapshot = 'null'::jsonb where id = $1::uuid", [run.id]); + expect(await resolveChatOriginPublicationBindings(captureLineageReads(db, reads), f.companyId, f.issueId, run.id)).toEqual([]); + expect(reads[0].rows[0].contextSnapshot).toBeNull(); + }); + + it.each([ + { name: "missing", snapshot: {}, wake: {}, allowed: true }, + { name: "explicit null", snapshot: { interactionId: null }, wake: { interactionId: null }, allowed: true }, + { name: "missing versus null", snapshot: { interactionId: null }, wake: {}, allowed: false }, + { name: "equal strings", snapshot: { interactionId: "synthetic-interaction" }, wake: { interactionId: "synthetic-interaction" }, allowed: true }, + { name: "number versus text", snapshot: { interactionId: 12 }, wake: { interactionId: "12" }, allowed: false }, + { name: "separate objects", snapshot: { interactionId: { id: "same" } }, wake: { interactionId: { id: "same" } }, allowed: false }, + ])("retains strict tool-action interaction semantics for $name and requires the durable receipt", async ({ snapshot, wake, allowed }) => { + const f = await fixture(1), continued = await f.continueFrom(f.root.id); + const [invocation] = await db.insert(toolInvocations).values({ companyId: f.companyId, issueId: f.issueId, agentId: f.agentId, runId: f.root.id, toolName: "synthetic-operation" }).returning(); + const [request] = await db.insert(toolActionRequests).values({ companyId: f.companyId, issueId: f.issueId, invocationId: invocation.id, + interactionId: continued.interaction.id, requestedByAgentId: f.agentId, status: "executed", canonicalArgumentsHash: "synthetic", canonicalArgumentsSummary: { summary: "Synthetic operation" } }).returning(); + await db.insert(toolActionDeliveries).values({ companyId: f.companyId, issueId: f.issueId, actionRequestId: request.id, interactionId: continued.interaction.id }); + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, source: "tool_action_review", sourceRunId: f.root.id, ...snapshot } }).where(eq(heartbeatRuns.id, continued.run.id)); + await db.insert(agentWakeupRequests).values({ companyId: f.companyId, agentId: f.agentId, source: "automation", reason: "issue_commented", status: "claimed", runId: continued.run.id, + idempotencyKey: `tool-action-response:${request.id}`, payload: { sourceRunId: f.root.id, toolActionRequestIds: [request.id], ...wake } }); + expect(await resolveChatOriginPublicationBindings(db, f.companyId, f.issueId, continued.run.id)).toEqual(allowed ? f.expected : []); + await db.delete(toolActionDeliveries).where(eq(toolActionDeliveries.actionRequestId, request.id)); + expect(await resolveChatOriginPublicationBindings(db, f.companyId, f.issueId, continued.run.id)).toEqual([]); + }); + + it("retains valid lineage beyond sixteen hops and rejects a durable cycle", async () => { + const f = await fixture(1); + let previous = f.root.id; + for (let index = 0; index < 24; index++) previous = (await f.continueFrom(previous)).run.id; + expect(await resolveChatOriginPublicationBindings(db, f.companyId, f.issueId, previous)).toEqual(f.expected); + const cycle = await f.continueFrom(previous); + await db.update(heartbeatRuns).set({ contextSnapshot: { source: "issue.interaction.accept", issueId: f.issueId, interactionId: cycle.interaction.id, sourceRunId: previous } }).where(eq(heartbeatRuns.id, f.root.id)); + await db.update(agentWakeupRequests).set({ runId: f.root.id }).where(eq(agentWakeupRequests.id, cycle.wake.id)); + const reads: LineageQuery[] = []; + expect(await resolveChatOriginPublicationBindings(captureLineageReads(db, reads), f.companyId, f.issueId, previous)).toEqual([]); + expect(reads).toHaveLength(25); + }); + + it("rejects mismatched company, task, agent, and endpoint bindings", async () => { + const f = await fixture(1), other = await fixture(1); + expect(await resolveChatOriginPublicationBindings(db, other.companyId, f.issueId, f.root.id)).toEqual([]); + for (const change of [{ issueId: other.issueId }, { endpointId: other.endpoint.id }, { source: false }, { wakeCommentIds: [randomUUID()], wakeCommentId: 12 }]) { + const run = await f.insertRun({ ...f.context, ...change }); + expect(await resolveChatOriginPublicationBindings(db, f.companyId, f.issueId, run.id)).toEqual([]); + } + const continued = await f.continueFrom(f.root.id); + await db.update(heartbeatRuns).set({ agentId: other.agentId }).where(eq(heartbeatRuns.id, continued.run.id)); + expect(await resolveChatOriginPublicationBindings(db, f.companyId, f.issueId, continued.run.id)).toEqual([]); + }); +}); diff --git a/server/src/services/connection-intents.ts b/server/src/services/connection-intents.ts index 1788c0ebd60..f0d143861e5 100644 --- a/server/src/services/connection-intents.ts +++ b/server/src/services/connection-intents.ts @@ -214,7 +214,7 @@ export function connectionIntentService(db: Db) { throw forbidden("Runtime tool token is no longer active"); } if (run.activeIdentityContextId && !failedAuthRun) { - const current = await captureRunIdentity(db, { companyId: run.companyId, agentId: run.agentId, runId: run.id }); + const current = await captureRunIdentity(db, { companyId: run.companyId, agentId: run.agentId, runId: run.id }, { readScope: "identity" }); run = { ...run, responsibleUserId: current.run.responsibleUserId }; } if (!run.responsibleUserId) throw forbidden("This task needs a responsible user to connect a service"); diff --git a/server/src/services/connection-management.ts b/server/src/services/connection-management.ts index fcc532476be..0c1740f04ba 100644 --- a/server/src/services/connection-management.ts +++ b/server/src/services/connection-management.ts @@ -3,7 +3,7 @@ import { isUuidLike } from "@paperclipai/shared"; import { agents, agentApiKeys, heartbeatRuns, runIdentityContexts, issues, projects, toolApplications, toolCatalogEntries, toolConnections, toolConnectionInstalls, toolProfiles, toolProfileEntries, toolProfileBindings, toolMcpGateways, aiConnectionPools, connectionGrants, routines, type Db } from "@paperclipai/db"; import { forbidden } from "../errors.js"; import { authorizationService, canActorReadIssuePrivacy, canActorReadProjectPrivacy, type AuthorizationActor, type AuthorizationDecision } from "./authorization.js"; -import { captureRunIdentity } from "./run-identity.js"; +import { captureRunIdentity, runIdentityTaskFields, type RunIdentityCapture } from "./run-identity.js"; import type { LogActivityInput } from "./activity-log.js"; import type { ConnectionManagementAction, ConnectionManagementResource } from "./connection-management-policy.js"; @@ -17,7 +17,7 @@ export type ConnectionManagementContext = { reauthorize: (continuation?: { afterHumanAction: true }) => Promise; }; -type CapturedConnectionRun = Omit>, "context"> & { context: Awaited>["context"] | null }; +type CapturedConnectionRun = RunIdentityCapture<"task_authorization">; const connectionReadRuns = new WeakMap(); export function responsibleConnectionUser(actor: AuthorizationActor): string | null { @@ -51,12 +51,12 @@ export function connectionManagementService(db: Db) { const reusable = options.capabilityProbe && !options.afterHumanAction && options.readContext?.actor === actor && options.readContext.resource.companyId === resource.companyId ? connectionReadRuns.get(options.readContext) : undefined; const captured = reusable ?? (options.afterHumanAction ? await (async () => { - const [run] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.id, actor.runId!), eq(heartbeatRuns.agentId, actor.agentId!), eq(heartbeatRuns.companyId, resource.companyId))); + const [run] = await db.select(runIdentityTaskFields).from(heartbeatRuns).where(and(eq(heartbeatRuns.id, actor.runId!), eq(heartbeatRuns.agentId, actor.agentId!), eq(heartbeatRuns.companyId, resource.companyId))); if (!run || !["running", "succeeded"].includes(run.status)) throw forbidden("The originating run cannot continue this authentication"); const [pending] = await db.select().from(runIdentityContexts).where(and(eq(runIdentityContexts.runId, run.id), eq(runIdentityContexts.status, "pending"))); if (pending) throw forbidden("Run identity is being reconciled"); return { run, context: null }; - })() : await captureRunIdentity(db, { companyId: resource.companyId, agentId: actor.agentId, runId: actor.runId })); + })() : await captureRunIdentity(db, { companyId: resource.companyId, agentId: actor.agentId, runId: actor.runId }, { readScope: "task_authorization" })); capturedRun = captured; const { run, context } = captured; if ((context?.responsibleUserId ?? run.responsibleUserId) !== responsibleUserId) throw forbidden("Run responsible-user authority has changed"); diff --git a/server/src/services/connectors/slack-authority.ts b/server/src/services/connectors/slack-authority.ts index 06da6455d35..ee19440f45e 100644 --- a/server/src/services/connectors/slack-authority.ts +++ b/server/src/services/connectors/slack-authority.ts @@ -8,7 +8,7 @@ import { type chatConversations, } from "@paperclipai/db"; import { and, eq, inArray } from "drizzle-orm"; -import { captureRunIdentity } from "../run-identity.js"; +import { captureRunIdentity, runIdentityTaskFields } from "../run-identity.js"; import { forbidden } from "../../errors.js"; import { boundRunIssueId } from "../run-task-binding.js"; import { chatRunSourceMessageId } from "../chat-channels/run-origin.js"; @@ -110,7 +110,7 @@ export async function slackRunOrigin(db: Db, binding: SlackTaskBinding) { if (!approved || !binding.identityContextId) throw forbidden("Slack approval is not executing for this task"); const [run] = await db - .select() + .select(runIdentityTaskFields) .from(heartbeatRuns) .where( and( @@ -141,7 +141,7 @@ export async function slackRunOrigin(db: Db, binding: SlackTaskBinding) { ); captured = { run, context }; } else { - captured = await captureRunIdentity(db, binding); + captured = await captureRunIdentity(db, binding, { readScope: "task_authorization" }); if ( binding.identityContextId && binding.identityContextId !== captured.context?.id diff --git a/server/src/services/execution-continuation-history-read.test.ts b/server/src/services/execution-continuation-history-read.test.ts new file mode 100644 index 00000000000..78b288849dc --- /dev/null +++ b/server/src/services/execution-continuation-history-read.test.ts @@ -0,0 +1,128 @@ +import assert from "node:assert/strict"; +import { randomBytes, randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { agents, applyPendingMigrations, companies, createDb, heartbeatRuns, issues, type Db } from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; +import { resolveExternalTestDatabaseUrl } from "../__tests__/helpers/external-test-database.js"; +import { buildExecutionContinuation } from "./execution-continuation.js"; + +const externalUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_EXECUTION_CONTINUATION_TEST_DATABASE_URL"); +const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); +describe.skipIf(!support.supported)("continuation history PostgreSQL projection", () => { + let database: Awaited>; + let db: Db; + beforeAll(async () => { + if (externalUrl) { + await applyPendingMigrations(externalUrl); + database = { connectionString: externalUrl, cleanup: async () => {} }; + } else database = await startEmbeddedPostgresTestDatabase("continuation-history-read-"); + db = createDb(database.connectionString); + }, 60_000); + afterAll(async () => { await db?.$client.end(); await database?.cleanup(); }); + + async function fixture(result: unknown) { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "History", issuePrefix: `H${companyId.replaceAll("-", "")}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Executor", adapterType: "paperclip_runner" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Continue", status: "in_progress", assigneeAgentId: agentId }); + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "failed", errorCode: "adapter_failed", + contextSnapshot: { issueId }, createdAt: new Date("2020-01-01T00:00:00Z"), resultJson: result as Record | null }).returning(); + return { companyId, agentId, issueId, run }; + } + + async function invoke(f: Awaited>, fullResult: boolean, context: Record = {}) { + const reads: Array>> = []; + const recorded = new Proxy(db, { get(target, key) { + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const historyRead = Object.hasOwn(fields[0] ?? {}, "retryOfRunId"); + const builder = historyRead && fullResult + ? target.select({ ...fields[0], result: heartbeatRuns.resultJson }) : target.select(...fields); + const from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const query = from(...args), execute = query.execute.bind(query); + if (historyRead) query.execute = async (...executeArgs: Parameters) => { + const rows = await execute(...executeArgs); reads.push(rows); return rows; + }; + return query; + }) as typeof builder.from; + return builder; + }; + }}); + const result = await buildExecutionContinuation({ db: recorded, companyId: f.companyId, agentId: f.agentId, + issueId: f.issueId, context, summary: null, exposeLowTrustRaw: false }); + return { result, reads }; + } + + async function compare(f: Awaited>, context: Record = {}) { + const before = await invoke(f, true, context), after = await invoke(f, false, context); + expect(after.result).toEqual(before.result); + expect(after.reads).toHaveLength(1); + expect(after.reads[0].map(({ result: _result, ...fields }) => fields)).toEqual(before.reads[0].map(({ result: _result, ...fields }) => fields)); + return { before, after }; + } + + it("keeps every completed receipt, its full result, missing values and receipt order", async () => { + const payload = randomBytes(128 * 1024).toString("base64"); + const result = { nativeResult: { output: payload }, conversationContinuation: "continue_conversation_v1", apiToolReceipts: { + "10": { state: "completed", operationId: "ten", result: null, unusedRequest: payload }, + "2": { state: "completed", operationId: "two", result: { nested: [payload, false, null] } }, + missing: { state: "completed", operationId: "" }, + pending: { state: "started", operationId: "pending", result: payload }, + invalid: { state: "completed", operationId: 42, result: payload }, + array: ["completed", "operation"], + scalar: "completed", number: 42, null: null, + } }; + const f = await fixture(result), { before, after } = await compare(f); + assert.ok(after.result.completedActions); + expect(after.result.completedActions.map(receipt => receipt.receiptId)).toEqual(["2", "10", "missing"]); + expect(after.result.completedActions[0].result).toEqual(result.apiToolReceipts["2"].result); + expect(after.result.completedActions[1].result).toBeNull(); + expect(after.result.completedActions[2].result).toBeUndefined(); + expect(Buffer.byteLength(JSON.stringify(after.reads))).toBeLessThan(Buffer.byteLength(JSON.stringify(before.reads)) / 2); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id)))[0].resultJson).toEqual(result); + }); + + const recovery = { schema: "paperclip.workspace-restore-recovery.v1" }; + it.each([ + { value: null, interrupted: false }, { value: [], interrupted: false }, { value: "scalar", interrupted: false }, { value: 42, interrupted: false }, + { value: {}, interrupted: false }, { value: { conversationContinuation: "continue_conversation_v1", apiToolReceipts: [1, 2] }, interrupted: true }, + { value: { conversationContinuation: 42, apiToolReceipts: "malformed" }, interrupted: false }, + ...["restore_permission_denied", "restore_lock_timeout", "restore_unsafe_archive", "restore_failed"].map(workspaceRestoreFailure => ({ + value: { conversationContinuation: "continue_conversation_v1", workspaceRestoreFailure, workspaceRestoreRecovery: recovery }, interrupted: false, + })), + { value: { conversationContinuation: "continue_conversation_v1", workspaceRestoreFailure: "restore_unsafe_archive" }, interrupted: false }, + { value: { conversationContinuation: "continue_conversation_v1", workspaceRestoreFailure: "custom", workspaceRestoreRecovery: recovery }, interrupted: true }, + ...[null, [], "schema", { schema: 42 }, { schema: "other" }].map(workspaceRestoreRecovery => ({ + value: { conversationContinuation: "continue_conversation_v1", workspaceRestoreFailure: "restore_failed", workspaceRestoreRecovery }, interrupted: true, + })), + ])("keeps continuation/recovery decisions for typed legacy JSON $value", async ({ value, interrupted }) => { + const f = await fixture(value), { after } = await compare(f); + expect(after.result.interruptedRunId).toBe(interrupted ? f.run.id : undefined); + expect(after.result.completedActions).toEqual([]); + }); + + it("keeps full ordered history and source-agent scope without cross-company or cross-task receipts", async () => { + const completed = (operationId: string) => ({ apiToolReceipts: { saved: { state: "completed", operationId, result: { operationId } } } }); + const f = await fixture({ ...completed("first"), conversationContinuation: "continue_conversation_v1" }); + const otherAgentId = randomUUID(); + await db.insert(agents).values({ id: otherAgentId, companyId: f.companyId, name: "Previous owner", adapterType: "paperclip_runner" }); + const [source] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: otherAgentId, status: "succeeded", + contextSnapshot: { issueId: f.issueId }, resultJson: completed("other-agent"), createdAt: new Date("2020-01-01T00:01:00Z") }).returning(); + await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "cancelled", errorCode: "execution_reconciliation_required", + contextSnapshot: { issueId: f.issueId }, resultJson: completed("cancelled"), createdAt: new Date("2020-01-01T00:02:00Z") }); + await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "failed", + contextSnapshot: { issueId: randomUUID() }, resultJson: completed("foreign-task") }); + const foreign = await fixture(completed("foreign-company")); + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId } }).where(eq(heartbeatRuns.id, foreign.run.id)); + const ordinary = await compare(f); + assert.ok(ordinary.after.result.completedActions); + expect(ordinary.after.result.completedActions.map(receipt => receipt.operationId)).toEqual(["first", "cancelled"]); + expect(ordinary.after.result.interruptedRunId).toBe(f.run.id); + const resumed = await compare(f, { previousRunId: source.id }); + assert.ok(resumed.after.result.completedActions); + expect(resumed.after.result.completedActions.map(receipt => receipt.operationId)).toEqual(["first", "other-agent", "cancelled"]); + expect(resumed.after.result.interruptedRunId).toBeUndefined(); + }); +}); diff --git a/server/src/services/execution-continuation.test.ts b/server/src/services/execution-continuation.test.ts index 834bf515ee7..fc9e88795ad 100644 --- a/server/src/services/execution-continuation.test.ts +++ b/server/src/services/execution-continuation.test.ts @@ -3,6 +3,7 @@ import { eq } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { agents, + applyPendingMigrations, companies, createDb, heartbeatRuns, @@ -15,6 +16,7 @@ import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase, } from "../__tests__/helpers/embedded-postgres.js"; +import { resolveExternalTestDatabaseUrl } from "../__tests__/helpers/external-test-database.js"; import { StaleExecutionContinuationError, buildExecutionContinuation, currentContinuationOrigins, projectHumanInteractionResponse } from "./execution-continuation.js"; const expectStaleContinuation = async ( @@ -29,7 +31,8 @@ const expectMissingContinuationContext = async (run: () => Promise) => await expect(result).rejects.toThrow("continuation_source_context_missing"); await expect(result).rejects.not.toBeInstanceOf(StaleExecutionContinuationError); }; -const support = await getEmbeddedPostgresTestSupport(); +const externalUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_EXECUTION_CONTINUATION_TEST_DATABASE_URL"); +const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); (support.supported ? describe : describe.skip)( "authorized continuation context", () => { @@ -44,13 +47,16 @@ const support = await getEmbeddedPostgresTestSupport(); laterId = randomUUID(), interactionId = randomUUID(); beforeAll(async () => { - database = await startEmbeddedPostgresTestDatabase( + if (externalUrl) { + await applyPendingMigrations(externalUrl); + database = { connectionString: externalUrl, cleanup: async () => {} }; + } else database = await startEmbeddedPostgresTestDatabase( "paperclip-continuation-context-", ); db = createDb(database.connectionString); await db .insert(companies) - .values({ id: companyId, name: "Continuation", issuePrefix: "CTX" }); + .values({ id: companyId, name: "Continuation", issuePrefix: `CTX${companyId.replaceAll("-", "")}` }); await db .insert(agents) .values({ diff --git a/server/src/services/execution-continuation.ts b/server/src/services/execution-continuation.ts index c44ce6ee325..378e7f1382c 100644 --- a/server/src/services/execution-continuation.ts +++ b/server/src/services/execution-continuation.ts @@ -31,6 +31,28 @@ const object = (v: unknown): Record => : {}; const string = (v: unknown) => typeof v === "string" && v.length > 0 ? v : null; +const historyResult = sql | null>`case + when jsonb_typeof(${heartbeatRuns.resultJson}) = 'object' then ( + select coalesce(jsonb_object_agg(field.key, case + when field.key = 'apiToolReceipts' and jsonb_typeof(field.value) = 'object' then ( + select coalesce(jsonb_object_agg(receipt.key, ( + select jsonb_object_agg(detail.key, detail.value) + from jsonb_each(receipt.value) as detail(key, value) + where detail.key in ('state', 'operationId', 'result') + )), '{}'::jsonb) + from jsonb_each(field.value) as receipt(key, value) + where receipt.value->'state' = '"completed"'::jsonb + and jsonb_typeof(receipt.value->'operationId') = 'string' + ) + when field.key = 'workspaceRestoreRecovery' and jsonb_typeof(field.value) = 'object' then ( + select coalesce(jsonb_object_agg(detail.key, detail.value), '{}'::jsonb) + from jsonb_each(field.value) as detail(key, value) + where detail.key = 'schema' + ) + else field.value end), '{}'::jsonb) + from jsonb_each(${heartbeatRuns.resultJson}) as field(key, value) + where field.key in ('apiToolReceipts', 'conversationContinuation', 'workspaceRestoreFailure', 'workspaceRestoreRecovery') + ) else ${heartbeatRuns.resultJson} end`; export function continuationOriginCommentIds(context: unknown): string[] { const c = object(context); const prior = object(c.executionContinuation); @@ -335,7 +357,7 @@ export async function buildExecutionContinuation(input: { ? { kind: "description" as const, id: issue.id, revision: hashObjectiveSource(issue.description) } : { kind: "title" as const, id: issue.id, revision: hashObjectiveSource(issue.title) }; const priorRuns = await db - .select({ id: heartbeatRuns.id, result: heartbeatRuns.resultJson, status: heartbeatRuns.status, errorCode: heartbeatRuns.errorCode, runtimeMode: heartbeatRuns.runtimeMode, retryOfRunId: heartbeatRuns.retryOfRunId }) + .select({ id: heartbeatRuns.id, result: historyResult, status: heartbeatRuns.status, errorCode: heartbeatRuns.errorCode, runtimeMode: heartbeatRuns.runtimeMode, retryOfRunId: heartbeatRuns.retryOfRunId }) .from(heartbeatRuns) .where( and( diff --git a/server/src/services/execution-workspace-repositories.ts b/server/src/services/execution-workspace-repositories.ts index fae172296ff..4d4cfe16b86 100644 --- a/server/src/services/execution-workspace-repositories.ts +++ b/server/src/services/execution-workspace-repositories.ts @@ -134,7 +134,7 @@ export function executionWorkspaceRepositoryService(db: Db) { let localTrusted = input.actor.source === "local_implicit"; if (input.actor.type === "agent") { if (input.actor.source !== "agent_jwt" || !input.actor.agentId || !input.actor.runId || input.actor.companyId !== input.companyId) throw forbidden("Repository preparation requires an authenticated task run"); - const identity = await captureRunIdentity(db, { companyId: input.companyId, agentId: input.actor.agentId, runId: input.actor.runId }); + const identity = await captureRunIdentity(db, { companyId: input.companyId, agentId: input.actor.agentId, runId: input.actor.runId }, { readScope: "task_authorization" }); const runIssueId = identity.run.nativeIssueId ?? identity.run.contextSnapshot?.issueId; if (runIssueId !== input.issueId) throw forbidden("Repository preparation is scoped to the current task"); userId = identity.run.responsibleUserId; diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index c6e54798555..391d08c660f 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -1170,7 +1170,13 @@ export async function resolveChatOriginPublicationBindings( .select({ agentId: heartbeatRuns.agentId, responsibleUserId: heartbeatRuns.responsibleUserId, - contextSnapshot: heartbeatRuns.contextSnapshot, + contextSnapshot: sql | null>` + case when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object' then + (select coalesce(jsonb_object_agg(entry.key, entry.value), '{}'::jsonb) + from jsonb_each(${heartbeatRuns.contextSnapshot}) as entry + where entry.key in ('issueId', 'taskId', 'wakeCommentIds', 'wakeCommentId', + 'commentId', 'source', 'sourceRunId', 'interactionId', 'endpointId')) + else ${heartbeatRuns.contextSnapshot} end`, }) .from(heartbeatRuns) .where( diff --git a/server/src/services/native-runtime/native-session-resume-projection.test.ts b/server/src/services/native-runtime/native-session-resume-projection.test.ts new file mode 100644 index 00000000000..08242f2a690 --- /dev/null +++ b/server/src/services/native-runtime/native-session-resume-projection.test.ts @@ -0,0 +1,203 @@ +import { randomUUID } from "node:crypto"; +import { and, eq, sql } from "drizzle-orm"; +import { agents, companies, createDb, heartbeatRunEvents, heartbeatRuns, issues, type Db } from "@paperclipai/db"; +import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; +import { resolveExternalTestDatabaseUrl } from "../../__tests__/helpers/external-test-database.js"; +import { findNativeSessionResumeRun } from "./native-session-resume.js"; + +const externalUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_TEST_DATABASE_URL"); +const supported = Boolean(externalUrl) || (await getEmbeddedPostgresTestSupport()).supported; + +(supported ? describe : describe.skip)("native session resume SQL projection", () => { + let database: Awaited>; + let db: Db; + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), normalizedSessionId = randomUUID(); + const currentRunId = randomUUID(); + const at = (second: number) => new Date(Date.UTC(2026, 8, 8, 0, 0, second)); + const input = { companyId, agentId, issueId, normalizedSessionId, currentRunId, beforeCreatedAt: at(30) }; + const checkpoint = { sessionId: "provider-session", identity: { runId: "prior" }, complete: [false, 0, "", null] }; + const nativeExecutionInput = { binding: { issueId }, task: { prompt: "Complete native input", description: "Description" }, runtimeContext: { nested: [1, 2] } }; + const paperclipWake = { externalChatProvider: "slack", githubReviewConfigurations: [{ key: "configuration", nested: { retained: true } }], other: ["preserved"] }; + const paperclipIssue = { id: issueId, title: "Saved canonical title", description: "Saved canonical description" }; + const profile = { nativeExecutionInput, sessionCheckpoint: checkpoint, nativeToolContractFingerprint: "fingerprint", unrelated: "Omit" }; + const run = (second: number, overrides: Partial = {}) => ({ + id: randomUUID(), companyId, agentId, nativeIssueId: issueId, nativeSessionId: normalizedSessionId, + runtimeMode: "native", status: "failed", createdAt: at(second), runnerProfileJson: {}, ...overrides, + }); + const select = () => findNativeSessionResumeRun(db, input); + const source = () => run(0, { runnerInstanceId: randomUUID(), processPid: 17, processGroupId: 19, processStartedAt: at(0), + runnerProfileJson: profile, contextSnapshot: { paperclipWake, paperclipIssue: { ...paperclipIssue, unrelated: "Omit" }, prompt: "Omit" } }); + const writeProfile = (id: string, value: unknown) => db.execute(sql`update ${heartbeatRuns} + set runner_profile_json = ${JSON.stringify(value)}::jsonb where ${heartbeatRuns.id} = ${id}`); + + beforeAll(async () => { + database = externalUrl ? { connectionString: externalUrl, cleanup: async () => {} } : await startEmbeddedPostgresTestDatabase("native-resume-projection-"); + db = createDb(database.connectionString); + await db.insert(companies).values({ id: companyId, name: "Resume projection", issuePrefix: `N${companyId.replaceAll("-", "")}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Runner" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Resume task" }); + }); + afterEach(async () => { + await db.delete(heartbeatRunEvents).where(eq(heartbeatRunEvents.companyId, companyId)); + await db.delete(heartbeatRuns).where(eq(heartbeatRuns.companyId, companyId)); + }); + afterAll(async () => { + if (!db) return; + try { + await db.delete(issues).where(eq(issues.companyId, companyId)); + await db.delete(agents).where(eq(agents.companyId, companyId)); + await db.delete(companies).where(eq(companies.id, companyId)); + } finally { + try { await db.$client.end({ timeout: 0 }); } + finally { await database.cleanup(); } + } + }); + + it("retains full required input, checkpoint, wake, canonical brief and process identity only for the selected source", async () => { + const saved = source(); + await db.insert(heartbeatRuns).values([saved, run(1), run(2)]); + const result = await select(); + expect(result).toEqual({ ...saved, runnerProfileJson: { nativeExecutionInput, sessionCheckpoint: checkpoint, nativeToolContractFingerprint: "fingerprint" }, + contextSnapshot: { paperclipWake, paperclipIssue } }); + const stored = await db.select({ profile: heartbeatRuns.runnerProfileJson, context: heartbeatRuns.contextSnapshot }).from(heartbeatRuns).where(eq(heartbeatRuns.id, saved.id)); + expect(stored[0].profile).toEqual(profile); + expect(stored[0].context).toEqual(saved.contextSnapshot); + for (const status of ["succeeded", "interrupted", "cancelled", "timed_out"]) { + await db.update(heartbeatRuns).set({ status }).where(eq(heartbeatRuns.id, saved.id)); + expect((await select())?.id).toBe(saved.id); + } + }); + + it("treats every non-null checkpoint as a barrier, including invalid false, zero, empty string, array and object values", async () => { + const saved = source(), newer = run(1); + await db.insert(heartbeatRuns).values([saved, newer]); + for (const value of [false, 0, "", "invalid", [], {}]) { + await writeProfile(newer.id, { sessionCheckpoint: value }); + const selected = await select(); + expect(selected?.id).toBe(newer.id); + expect(selected?.runnerProfileJson.sessionCheckpoint).toEqual(value); + } + }); + + it("skips only unused SQL-null, JSON-null, scalar, array and checkpoint-null profiles", async () => { + const saved = source(), newer = run(1, { runnerProfileJson: null }); + await db.insert(heartbeatRuns).values([saved, newer]); + expect((await select())?.id).toBe(saved.id); + for (const value of [null, false, 0, "sessionCheckpoint", [], ["sessionCheckpoint"], {}, { sessionCheckpoint: null }]) { + await writeProfile(newer.id, value); + expect((await select())?.id).toBe(saved.id); + } + }); + + it("preserves malformed selected context values and missing brief fields", async () => { + const saved = source(); + await db.insert(heartbeatRuns).values(saved); + for (const value of [null, false, 0, "invalid", [], {}, { paperclipWake: [], paperclipIssue: { id: issueId, title: false } }, + { paperclipIssue: { id: issueId, title: "Valid title without description" } }, + { paperclipIssue: { id: issueId, title: "Valid title", description: null } }]) { + await db.execute(sql`update ${heartbeatRuns} set context_snapshot = ${JSON.stringify(value)}::jsonb where ${heartbeatRuns.id} = ${saved.id}`); + const result = await select(); + const object = typeof value === "object" && value !== null && !Array.isArray(value) ? value : {}; + expect(result?.contextSnapshot.paperclipWake).toEqual("paperclipWake" in object ? object.paperclipWake : null); + expect(result?.contextSnapshot.paperclipIssue).toEqual("paperclipIssue" in object ? object.paperclipIssue : null); + } + }); + + it("stops at wrong runtime, nonterminal status and each process authority field", async () => { + await db.insert(heartbeatRuns).values(source()); + for (const override of [{ runtimeMode: "legacy" }, { status: "running" }, { processPid: 0 }, { processGroupId: 0 }, { processStartedAt: at(0) }]) { + const newer = run(1, override); + await db.insert(heartbeatRuns).values(newer); + expect(await select()).toBeNull(); + await db.delete(heartbeatRuns).where(eq(heartbeatRuns.id, newer.id)); + } + }); + + it("checks every provider evidence event and ignores unrelated event kinds", async () => { + const saved = source(), newer = run(1); + await db.insert(heartbeatRuns).values([saved, newer]); + for (const eventType of ["harness.ready", "session.started", "session.resumed", "session.updated", "turn.started", "provider.event", "provider.rpc_result", "log"]) { + await db.insert(heartbeatRunEvents).values({ companyId, agentId, runId: newer.id, seq: 1, eventType }); + if (eventType === "log") expect((await select())?.id).toBe(saved.id); + else expect(await select()).toBeNull(); + await db.delete(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, newer.id)); + } + }); + + it("excludes current and mismatched agent, company, task and session rows before applying barriers", async () => { + const saved = source(), otherCompany = randomUUID(), otherAgent = randomUUID(), otherIssue = randomUUID(); + await db.insert(companies).values({ id: otherCompany, name: "Other", issuePrefix: `D${otherCompany.replaceAll("-", "")}` }); + await db.insert(agents).values({ id: otherAgent, companyId: otherCompany, name: "Other" }); + await db.insert(issues).values({ id: otherIssue, companyId, title: "Other" }); + try { + await db.insert(heartbeatRuns).values([saved, run(1, { id: currentRunId, status: "running" }), + run(2, { companyId: otherCompany, status: "running" }), run(3, { agentId: otherAgent, status: "running" }), + run(4, { nativeIssueId: otherIssue, status: "running" }), run(5, { nativeSessionId: randomUUID(), status: "running" })]); + expect((await select())?.id).toBe(saved.id); + } finally { + await db.delete(heartbeatRuns).where(eq(heartbeatRuns.companyId, otherCompany)); + await db.delete(heartbeatRuns).where(eq(heartbeatRuns.agentId, otherAgent)); + await db.delete(issues).where(eq(issues.id, otherIssue)); + await db.delete(agents).where(eq(agents.id, otherAgent)); + await db.delete(companies).where(eq(companies.id, otherCompany)); + } + expect(await findNativeSessionResumeRun(db, { ...input, normalizedSessionId: "invalid" })).toBeNull(); + for (const key of ["companyId", "agentId", "issueId", "normalizedSessionId"] as const) { + expect(await findNativeSessionResumeRun(db, { ...input, [key]: input[key].toUpperCase() })).toBeNull(); + } + }); + + it("retains the 32-row bound and deterministic created-at/id ordering", async () => { + const saved = source(), unused = Array.from({ length: 32 }, () => run(1)); + await db.insert(heartbeatRuns).values([saved, ...unused]); + expect(await select()).toBeNull(); + await db.delete(heartbeatRuns).where(eq(heartbeatRuns.id, unused[0].id)); + expect((await select())?.id).toBe(saved.id); + const tied = [run(2, { runnerProfileJson: { sessionCheckpoint: false } }), run(2, { status: "running" })].sort((a, b) => b.id.localeCompare(a.id)); + await db.insert(heartbeatRuns).values(tied); + if (tied[0].status === "running") expect(await select()).toBeNull(); + else expect((await select())?.id).toBe(tied[0].id); + }); + + it("does not skip future checkpoint barriers and preserves Date millisecond comparison", async () => { + const saved = source(), future = run(31); + await db.insert(heartbeatRuns).values([saved, future]); + expect((await select())?.id).toBe(saved.id); + await writeProfile(future.id, { sessionCheckpoint: false }); + expect(await select()).toBeNull(); + await db.execute(sql`update ${heartbeatRuns} set created_at = '2026-09-08T00:00:30.000999Z'::timestamptz where ${heartbeatRuns.id} = ${future.id}`); + expect((await select())?.id).toBe(future.id); + }); + + it("sees a newly committed barrier and changed source binding in its single selection snapshot", async () => { + const saved = source(); + await db.insert(heartbeatRuns).values(saved); + let reads = 0; + const changing = new Proxy(db, { get(target, key) { + if (key !== "with") return Reflect.get(target, key); + return (...ctes: Parameters) => { + const builder = target.with(...ctes), original = builder.select.bind(builder); + builder.select = ((...fields: Parameters) => { + const selection = original(...fields), from = selection.from.bind(selection); + selection.from = ((...args: Parameters) => { + const query = from(...args), execute = query.execute.bind(query); + query.execute = async (...executeArgs: Parameters) => { + reads++; + await db.insert(heartbeatRuns).values(run(1, { runnerProfileJson: { sessionCheckpoint: 0 } })); + await db.update(heartbeatRuns).set({ nativeSessionId: randomUUID() }).where(and(eq(heartbeatRuns.id, saved.id), eq(heartbeatRuns.companyId, companyId))); + return execute(...executeArgs); + }; + return query; + }) as typeof selection.from; + return selection; + }) as typeof builder.select; + return builder; + }; + }}); + const selected = await findNativeSessionResumeRun(changing, input); + expect(reads).toBe(1); + expect(selected?.id).not.toBe(saved.id); + expect(selected?.runnerProfileJson.sessionCheckpoint).toBe(0); + }); +}); diff --git a/server/src/services/native-runtime/native-session-resume.ts b/server/src/services/native-runtime/native-session-resume.ts index a271601ce0b..25463b68c78 100644 --- a/server/src/services/native-runtime/native-session-resume.ts +++ b/server/src/services/native-runtime/native-session-resume.ts @@ -1,6 +1,6 @@ import { createHash, randomUUID } from "node:crypto"; import { isDeepStrictEqual } from "node:util"; -import { and, desc, eq, inArray, ne } from "drizzle-orm"; +import { and, desc, eq, exists, inArray, isNotNull, ne, not, or, sql } from "drizzle-orm"; import { heartbeatRunEvents, heartbeatRuns, type Db } from "@paperclipai/db"; import type { NativeExecutionInput, @@ -186,6 +186,16 @@ export function selectNativeSessionResumeRun< return null; } +const NATIVE_SESSION_PROVIDER_EVENT_TYPES = [ + "harness.ready", + "session.started", + "session.resumed", + "session.updated", + "turn.started", + "provider.event", + "provider.rpc_result", +]; + export async function nativeSessionProviderEvidence( db: Pick, runIds: string[], @@ -197,15 +207,7 @@ export async function nativeSessionProviderEvidence( .where( and( inArray(heartbeatRunEvents.runId, runIds), - inArray(heartbeatRunEvents.eventType, [ - "harness.ready", - "session.started", - "session.resumed", - "session.updated", - "turn.started", - "provider.event", - "provider.rpc_result", - ]), + inArray(heartbeatRunEvents.eventType, NATIVE_SESSION_PROVIDER_EVENT_TYPES), ), ) .groupBy(heartbeatRunEvents.runId); @@ -224,7 +226,50 @@ export async function findNativeSessionResumeRun( }, ) { if (!isNativeSessionId(input.normalizedSessionId)) return null; - const runs = await db + const candidates = db.$with("native_resume_candidates").as(db + .select({ + id: heartbeatRuns.id, + runtimeMode: heartbeatRuns.runtimeMode, + status: heartbeatRuns.status, + createdAt: heartbeatRuns.createdAt, + processPid: heartbeatRuns.processPid, + processGroupId: heartbeatRuns.processGroupId, + processStartedAt: heartbeatRuns.processStartedAt, + hasCheckpoint: sql`coalesce(${heartbeatRuns.runnerProfileJson}->'sessionCheckpoint' <> 'null'::jsonb, false)`.as("has_checkpoint"), + }) + .from(heartbeatRuns) + .where( + and( + ne(heartbeatRuns.id, input.currentRunId), + eq(heartbeatRuns.companyId, input.companyId), + eq(heartbeatRuns.agentId, input.agentId), + eq(heartbeatRuns.nativeIssueId, input.issueId), + eq(heartbeatRuns.nativeSessionId, input.normalizedSessionId), + ), + ) + .orderBy(desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id)) + .limit(32)); + const terminalStatuses = [...LEGACY_RETRY_SOURCE_TERMINAL_STATUSES]; + const barrier = db.$with("native_resume_barrier").as(db + .select() + .from(candidates) + .where(or( + ne(candidates.runtimeMode, "native"), + not(inArray(candidates.status, terminalStatuses)), + candidates.hasCheckpoint, + isNotNull(candidates.processPid), + isNotNull(candidates.processGroupId), + isNotNull(candidates.processStartedAt), + exists(db.select({ runId: heartbeatRunEvents.runId }) + .from(heartbeatRunEvents) + .where(and( + eq(heartbeatRunEvents.runId, candidates.id), + inArray(heartbeatRunEvents.eventType, NATIVE_SESSION_PROVIDER_EVENT_TYPES), + ))), + )) + .orderBy(desc(candidates.createdAt), desc(candidates.id)) + .limit(1)); + const [run] = await db.with(candidates, barrier) .select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, @@ -238,29 +283,39 @@ export async function findNativeSessionResumeRun( processPid: heartbeatRuns.processPid, processGroupId: heartbeatRuns.processGroupId, processStartedAt: heartbeatRuns.processStartedAt, - runnerProfileJson: heartbeatRuns.runnerProfileJson, - contextSnapshot: heartbeatRuns.contextSnapshot, + runnerProfileJson: sql<{ + nativeToolContractFingerprint: unknown; + nativeExecutionInput: unknown; + sessionCheckpoint: unknown; + }>`jsonb_build_object( + 'nativeToolContractFingerprint', ${heartbeatRuns.runnerProfileJson}->'nativeToolContractFingerprint', + 'nativeExecutionInput', ${heartbeatRuns.runnerProfileJson}->'nativeExecutionInput', + 'sessionCheckpoint', ${heartbeatRuns.runnerProfileJson}->'sessionCheckpoint' + )`, + contextSnapshot: sql<{ + paperclipWake: unknown; + paperclipIssue: unknown; + }>`jsonb_build_object( + 'paperclipWake', ${heartbeatRuns.contextSnapshot}->'paperclipWake', + 'paperclipIssue', case when jsonb_typeof(${heartbeatRuns.contextSnapshot}->'paperclipIssue') = 'object' + then (select coalesce(jsonb_object_agg(brief.key, brief.value), '{}'::jsonb) + from jsonb_each(${heartbeatRuns.contextSnapshot}->'paperclipIssue') as brief + where brief.key in ('id', 'title', 'description')) else ${heartbeatRuns.contextSnapshot}->'paperclipIssue' end + )`, }) .from(heartbeatRuns) - .where( - and( - ne(heartbeatRuns.id, input.currentRunId), - eq(heartbeatRuns.companyId, input.companyId), - eq(heartbeatRuns.agentId, input.agentId), - eq(heartbeatRuns.nativeIssueId, input.issueId), - eq(heartbeatRuns.nativeSessionId, input.normalizedSessionId), - ), - ) - .orderBy(desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id)) - .limit(32); - return selectNativeSessionResumeRun({ - ...input, - runs, - providerEvidenceRunIds: await nativeSessionProviderEvidence( - db, - runs.map((run) => run.id), - ), - }); + .innerJoin(barrier, eq(heartbeatRuns.id, barrier.id)) + .where(and( + eq(barrier.runtimeMode, "native"), + inArray(barrier.status, terminalStatuses), + eq(barrier.hasCheckpoint, true), + sql`${heartbeatRuns.companyId}::text = ${input.companyId}`, + sql`${heartbeatRuns.agentId}::text = ${input.agentId}`, + sql`${heartbeatRuns.nativeIssueId}::text = ${input.issueId}`, + sql`${heartbeatRuns.nativeSessionId}::text = ${input.normalizedSessionId}`, + sql`date_trunc('milliseconds', ${barrier.createdAt}) <= ${input.beforeCreatedAt.toISOString()}::timestamptz`, + )); + return run ?? null; } /** A preassigned session id may rotate only before immutable native admission. */ diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts index aa6863205fb..71f9e3ea02b 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts @@ -458,7 +458,7 @@ export class PaperclipRunnerToolAuthority { } if (RUNTIME_CONNECTION_TOOL_DEFINITIONS.some((tool) => tool.name === call.tool)) { await this.#boundContext(); - const { run } = await captureRunIdentity(this.db, this.binding); + const { run } = await captureRunIdentity(this.db, this.binding, { readScope: "identity" }); if (!run.responsibleUserId) throw forbidden("This task needs a responsible user before requesting a connection"); const claims = { sub: this.binding.agentId, company_id: this.binding.companyId, @@ -794,9 +794,9 @@ export class PaperclipRunnerToolAuthority { } case "report_progress": return this.#reportProgress(input); case "request_human_input": return this.#requestHumanInput(input, - (await captureRunIdentity(this.db, this.binding)).context?.id ?? null); + (await captureRunIdentity(this.db, this.binding, { readScope: "identity" })).context?.id ?? null); case "create_task": return this.#createTask(input, - (await captureRunIdentity(this.db, this.binding)).context?.id ?? null); + (await captureRunIdentity(this.db, this.binding, { readScope: "identity" })).context?.id ?? null); case "reassign_task": return this.#reassignTask(input); case "set_task_title": return this.#setTaskTitle(input); case "set_task_monitor": return this.#setTaskMonitor(input); diff --git a/server/src/services/project-skill-source-bindings.ts b/server/src/services/project-skill-source-bindings.ts index 29ff8bb1875..259e0dda705 100644 --- a/server/src/services/project-skill-source-bindings.ts +++ b/server/src/services/project-skill-source-bindings.ts @@ -12,7 +12,7 @@ export async function projectSkillSetupIdentity(db: Db, companyId: string, actor let connectionId: string | null = null, refreshGrantId: string | null = null; if (actor?.type === 'agent' && actor.source === 'agent_jwt') { if (!actor.runId || !actor.agentId || actor.companyId !== companyId) throw forbidden('Project skill setup requires an authenticated agent run.'); - const identity = await captureRunIdentity(db, { companyId, agentId: actor.agentId, runId: actor.runId }); + const identity = await captureRunIdentity(db, { companyId, agentId: actor.agentId, runId: actor.runId }, { readScope: 'identity' }); userId = identity.run.responsibleUserId; // Only reuse the connection already authorized by managed GitHub delivery // for this active run. Responsibility alone cannot discover another grant. diff --git a/server/src/services/project-tool-context.ts b/server/src/services/project-tool-context.ts index a0cc9468351..89be328b052 100644 --- a/server/src/services/project-tool-context.ts +++ b/server/src/services/project-tool-context.ts @@ -2,16 +2,21 @@ import type { Request } from "express"; import { and, eq } from "drizzle-orm"; import { issues, type Db } from "@paperclipai/db"; import { forbidden } from "../errors.js"; -import { captureRunIdentity } from "./run-identity.js"; +import { captureRunIdentity, type RunIdentityCapture } from "./run-identity.js"; +type ProjectToolResult = { run: Run; issue: typeof issues.$inferSelect; userId: string | null; localTrusted: boolean }; /** Resolve authority from the authenticated run, never caller-supplied user/task IDs. */ -export async function projectToolContext(db: Db, actor: Request["actor"], write = false, resource = "Project") { +export function projectToolContext(db: Db, actor: Request["actor"], write?: boolean, resource?: string): Promise["run"]>>; +export function projectToolContext(db: Db, actor: Request["actor"], write: boolean, resource: string, options: { includeExecutionInput: true }): Promise["run"]>>; +export async function projectToolContext(db: Db, actor: Request["actor"], write = false, resource = "Project", options?: { includeExecutionInput: true }) { if (actor.type !== "agent" || actor.source !== "agent_jwt" || !actor.runId || !actor.agentId || !actor.companyId) { throw forbidden(`${resource} tools require an authenticated agent run`); } // Acquire task/run locks before checking mode and session generation. A reset, // cancellation, or steering update cannot race a committing project mutation. - const identity = await captureRunIdentity(db, { companyId: actor.companyId, agentId: actor.agentId, runId: actor.runId }); + const binding = { companyId: actor.companyId, agentId: actor.agentId, runId: actor.runId }; + const identity = options?.includeExecutionInput ? await captureRunIdentity(db, binding, { readScope: "project_execution" }) : + await captureRunIdentity(db, binding, { readScope: "task_authorization" }); const run = identity.run; const snapshot = run.contextSnapshot ?? {}; const issueId = run.nativeIssueId ?? (typeof snapshot.issueId === "string" ? snapshot.issueId : null); diff --git a/server/src/services/run-identity.ts b/server/src/services/run-identity.ts index 166b1ae8cac..f72cc974ca7 100644 --- a/server/src/services/run-identity.ts +++ b/server/src/services/run-identity.ts @@ -465,16 +465,71 @@ export async function acceptSteeredIdentity( if (accepted) await activate(executor, accepted); } -export async function captureRunIdentity( +const runIdentityFields = { + id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId, + status: heartbeatRuns.status, responsibleUserId: heartbeatRuns.responsibleUserId, + activeIdentityContextId: heartbeatRuns.activeIdentityContextId, +}; + +export const runIdentityTaskFields = { + ...runIdentityFields, nativeIssueId: heartbeatRuns.nativeIssueId, issueId: heartbeatRuns.issueId, + wakeupRequestId: heartbeatRuns.wakeupRequestId, + contextSnapshot: sql | null>`case when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object' + then jsonb_build_object('issueId', ${heartbeatRuns.contextSnapshot}->'issueId', + 'taskId', ${heartbeatRuns.contextSnapshot}->'taskId', + 'conversationSessionGeneration', ${heartbeatRuns.contextSnapshot}->'conversationSessionGeneration', + 'paperclipSkillTest', ${heartbeatRuns.contextSnapshot}->'paperclipSkillTest') else null end`, +}; + +export const runIdentityBrokerFields = { + ...runIdentityFields, invocationSource: heartbeatRuns.invocationSource, + contextSnapshot: sql | null>`case when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object' + then jsonb_build_object('issueId', ${heartbeatRuns.contextSnapshot}->'issueId', + 'projectId', ${heartbeatRuns.contextSnapshot}->'projectId', 'routineId', ${heartbeatRuns.contextSnapshot}->'routineId', + 'responsibleUserId', ${heartbeatRuns.contextSnapshot}->'responsibleUserId', + 'responsible_user_id', ${heartbeatRuns.contextSnapshot}->'responsible_user_id', + 'paperclipIssue', case when jsonb_typeof(${heartbeatRuns.contextSnapshot}->'paperclipIssue') = 'object' + then jsonb_build_object('id', ${heartbeatRuns.contextSnapshot}->'paperclipIssue'->'id', + 'projectId', ${heartbeatRuns.contextSnapshot}->'paperclipIssue'->'projectId', + 'responsibleUserId', ${heartbeatRuns.contextSnapshot}->'paperclipIssue'->'responsibleUserId', + 'responsible_user_id', ${heartbeatRuns.contextSnapshot}->'paperclipIssue'->'responsible_user_id') else null end) + else null end`, +}; + +const runIdentityProjectFields = { + ...runIdentityTaskFields, runtimeMode: heartbeatRuns.runtimeMode, + runnerProfileJson: sql | null>`case when jsonb_typeof(${heartbeatRuns.runnerProfileJson}) = 'object' + then case when ${heartbeatRuns.runnerProfileJson} ? 'nativeExecutionInput' + then jsonb_build_object('nativeExecutionInput', ${heartbeatRuns.runnerProfileJson}->'nativeExecutionInput') + else '{}'::jsonb end else null end`, +}; + +type FullIdentityRun = typeof heartbeatRuns.$inferSelect; +type IdentityRun = Pick; +type TaskIdentityRun = Pick; +type BrokerIdentityRun = Pick; +type ProjectIdentityRun = Pick; +export type RunIdentityReadScope = "github_credentials" | "request_authentication" | "identity" | "task_authorization" | "token_broker" | "project_execution"; +export type RunIdentityCapture = { + run: Scope extends "identity" ? IdentityRun : Scope extends "task_authorization" ? TaskIdentityRun : + Scope extends "token_broker" ? BrokerIdentityRun : Scope extends "project_execution" ? ProjectIdentityRun : FullIdentityRun; + context: RunIdentityContext | null; +}; + +export async function captureRunIdentity( db: Db, input: { companyId: string; runId: string; agentId: string }, - options?: { readScope: "github_credentials" | "request_authentication" }, -) { + options?: { readScope: Scope }, +): Promise> { // Lock acquisition serializes with steering delivery and its durable acknowledgement. return db.transaction(async (tx) => { await lockIdentityTask(tx, input.companyId, input.runId); const [run] = await tx - .select(options?.readScope === "github_credentials" || options?.readScope === "request_authentication" ? { + .select(options?.readScope === "identity" ? runIdentityFields : + options?.readScope === "task_authorization" ? runIdentityTaskFields : + options?.readScope === "token_broker" ? runIdentityBrokerFields : + options?.readScope === "project_execution" ? runIdentityProjectFields : + options?.readScope === "github_credentials" || options?.readScope === "request_authentication" ? { ...getTableColumns(heartbeatRuns), contextSnapshot: sql | null>`case when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object' then jsonb_build_object('issueId', ${heartbeatRuns.contextSnapshot}->'issueId', @@ -528,7 +583,7 @@ export async function captureRunIdentity( ), ) : []; - return { run, context: context ?? null }; + return { run, context: context ?? null } as RunIdentityCapture; }); } diff --git a/server/src/services/sidebar-badges.ts b/server/src/services/sidebar-badges.ts index 4f0249043c2..80348af686a 100644 --- a/server/src/services/sidebar-badges.ts +++ b/server/src/services/sidebar-badges.ts @@ -1,7 +1,7 @@ -import { and, desc, eq, inArray, not, type SQL } from "drizzle-orm"; +import { and, desc, eq, inArray, isNull, not, or, sql, type SQL } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { agents, approvals, heartbeatRuns } from "@paperclipai/db"; -import { isHeartbeatRunVisibleInMine, latestFailedRunsByAgent, type SidebarBadges } from "@paperclipai/shared"; +import type { SidebarBadges } from "@paperclipai/shared"; import { authorizationService, type AuthorizationActor } from "./authorization.js"; import { getHeartbeatRunReadDecisions } from "./heartbeat-run-privacy.js"; @@ -51,11 +51,10 @@ export function sidebarBadgeService(db: Db) { rows.filter((row) => !isDismissed(extra?.dismissals ?? new Map(), `approval:${row.id}`, row.updatedAt)).length ); - const recentRuns = await db + const recentRuns = db .select({ id: heartbeatRuns.id, agentId: heartbeatRuns.agentId, - companyId: heartbeatRuns.companyId, scopeKind: heartbeatRuns.scopeKind, issueId: heartbeatRuns.issueId, status: heartbeatRuns.status, @@ -72,14 +71,50 @@ export function sidebarBadgeService(db: Db) { ), ) .orderBy(desc(heartbeatRuns.createdAt)) - .limit(200); + .limit(200) + .as("recent_runs"); - const failures = latestFailedRunsByAgent(recentRuns).filter((row) => - (extra?.currentUserId === undefined || isHeartbeatRunVisibleInMine(row, extra.currentUserId)) - && !isDismissed(extra?.dismissals ?? new Map(), `run:${row.id}`, row.createdAt), + const observedRuns = db.select({ + id: recentRuns.id, + agentId: recentRuns.agentId, + scopeKind: recentRuns.scopeKind, + issueId: recentRuns.issueId, + status: recentRuns.status, + responsibleUserId: recentRuns.responsibleUserId, + createdAt: recentRuns.createdAt, + observedOrder: sql`row_number() over ()`.as("observed_order"), + }).from(recentRuns).as("observed_runs"); + const rankedRuns = db.select({ + id: observedRuns.id, + scopeKind: observedRuns.scopeKind, + issueId: observedRuns.issueId, + status: observedRuns.status, + responsibleUserId: observedRuns.responsibleUserId, + createdAt: observedRuns.createdAt, + agentRunRank: sql`row_number() over (partition by ${observedRuns.agentId} order by ${observedRuns.createdAt} desc, ${observedRuns.observedOrder})`.as("agent_run_rank"), + }).from(observedRuns).as("ranked_runs"); + const mineCondition = extra?.currentUserId === undefined + ? undefined + : !extra.currentUserId + ? sql`false` + : extra.currentUserId === "local-board" + ? or(eq(rankedRuns.responsibleUserId, "local-board"), isNull(rankedRuns.responsibleUserId), eq(rankedRuns.responsibleUserId, "")) + : eq(rankedRuns.responsibleUserId, extra.currentUserId); + const candidates = await db.select({ + id: rankedRuns.id, + scopeKind: rankedRuns.scopeKind, + issueId: rankedRuns.issueId, + createdAt: rankedRuns.createdAt, + }).from(rankedRuns).where(and( + eq(rankedRuns.agentRunRank, 1), + inArray(rankedRuns.status, ["failed", "timed_out"]), + mineCondition, + )); + const failures = candidates.filter((row) => + !isDismissed(extra?.dismissals ?? new Map(), `run:${row.id}`, row.createdAt), ); const failedRuns = extra?.actor - ? (await getHeartbeatRunReadDecisions(db, authorization, extra.actor, failures)).filter(Boolean).length + ? (await getHeartbeatRunReadDecisions(db, authorization, extra.actor, failures.map((row) => ({ ...row, companyId })))).filter(Boolean).length : failures.length; const joinRequests = (extra?.joinRequests ?? []).filter((row) => diff --git a/server/src/services/tool-access/token-broker/admission.ts b/server/src/services/tool-access/token-broker/admission.ts index 5b30a3fd915..b4a98042001 100644 --- a/server/src/services/tool-access/token-broker/admission.ts +++ b/server/src/services/tool-access/token-broker/admission.ts @@ -1,5 +1,5 @@ import type { DbTransaction } from "../types.js"; -import { captureRunIdentity } from "../../run-identity.js"; +import { captureRunIdentity, runIdentityBrokerFields } from "../../run-identity.js"; import { and, eq, gte, inArray, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { connectionTokenIssuances, companyMemberships, heartbeatRuns, toolConnections, toolProfileBindings, toolProfileEntries, toolProfiles } from "@paperclipai/db"; @@ -75,11 +75,11 @@ export function createTokenBrokerAdmission(db: Db, now: () => Date) { runId: string; }) { const [initialRun] = await db - .select() + .select(runIdentityBrokerFields) .from(heartbeatRuns) .where(eq(heartbeatRuns.id, input.runId)); const run = initialRun?.activeIdentityContextId - ? (await captureRunIdentity(db, input)).run + ? (await captureRunIdentity(db, input, { readScope: "token_broker" })).run : initialRun; if ( !run || diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index 8eff3e7d0e2..4cacb30e47e 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -2200,7 +2200,7 @@ export function createToolGatewayService( companyId: session.companyId, agentId: session.agentId, runId: session.runId, - }); + }, { readScope: "identity" }); return { ...session, identityContextId: captured.context?.id, diff --git a/server/src/services/voice/speko-agent-tools.ts b/server/src/services/voice/speko-agent-tools.ts index 6332329fe35..7f0ce74b78f 100644 --- a/server/src/services/voice/speko-agent-tools.ts +++ b/server/src/services/voice/speko-agent-tools.ts @@ -19,7 +19,7 @@ export function registerSpekoVoiceRuntime(db: Db, start: (binding: Binding, invo async function resolveAuthority(db: Db, session: SpekoTaskSession, endpointId: string) { if (!(await instanceSettingsService(db).getExperimental()).enableChatConnectors) throw forbidden("Voice connections are disabled"); if (!runtimes.has(db) || !session.agentId || !session.runId || !session.issueId) throw forbidden("Speko tools require an active task run"); - const { run, context } = await captureRunIdentity(db, { companyId: session.companyId, agentId: session.agentId, runId: session.runId }); + const { run, context } = await captureRunIdentity(db, { companyId: session.companyId, agentId: session.agentId, runId: session.runId }, { readScope: "task_authorization" }); if (boundRunIssueId(run) !== session.issueId || !run.responsibleUserId || session.identityContextId && session.identityContextId !== context?.id) throw forbidden("The accepted requester or task changed"); const [endpoint] = await db.select().from(chatEndpoints).where(and(eq(chatEndpoints.companyId, session.companyId), eq(chatEndpoints.id, endpointId), eq(chatEndpoints.provider, "speko"), eq(chatEndpoints.assignedAgentId, session.agentId), eq(chatEndpoints.status, "active"))); if (!endpoint) throw forbidden("This agent has no active Speko connection");