From 347d85fef3e55a82d10853a9849dec7a82e4090b Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:47:34 -0600 Subject: [PATCH 01/10] perf(chat): index GitHub review lookups and share review-wait reads (#20400) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - GitHub chat endpoints let agents review pull requests. The server reads review state when it lists issues and when it updates GitHub checks. > - On a hosted instance, two GitHub review queries used the most total database time. One query ran about 660,000 times at about 33 ms. The other query ran about 10,000 times at about 1 s. > - The first query finds a source comment's chat link. No index covers `chat_message_links.comment_id`, so each call reads the full table. Issue lists also read the same review waits two times per request. > - The second query joins deliveries, links and runs on a JSON key. The planner walks the agent's run history in creation order and reads each run's context. > - This pull request adds four concurrent indexes, splits the run lookup into two small reads, and shares review-wait reads in one issue-list request. > - The benefit is less background database load, so request reads wait less. The results stay the same. ## Linked Issues or Issue Description **What existing behavior does this improve?** GitHub review state reads. These are the inherited review-wait lookup by source comment, and the review-check lookup of the run that a delivery's comment woke. **Subsystem affected** Server chat channels (GitHub review waits and checks), issue list attention maps, and the database schema. **Current behavior** - `readInheritedGitHubReviewWait` filters `chat_message_links` by `company_id`, `comment_id` and `direction`. No index has `comment_id`, so PostgreSQL reads the full table on each call. The run-origin check does the same lookup first. - An issue list calls the external review-wait read from the review attention map and again from the blocked-inbox attention map. The two maps read the same in-review issues. - `githubReviewCheckState` joins deliveries, links and runs with `context_snapshot->>'wakeCommentId' = comment_id::text`, sorts by `created_at desc` and takes one row. The planner reads the agent's runs in creation order and reads each run context. If no run matches yet, it reads all of them. The delivery filter on `normalized_event` and the link join on `delivery_id` also have no index. **Proposed behavior** The same rows come back from small index reads. Each issue's review wait is read one time per issue-list request. **Reason and benefit** These two statement families used about 33,000 s of database time in one cumulative statistics window. The database had about 50 concurrent active queries, and request reads waited behind this background work. **Breaking changes** None. The migration adds indexes only. ## What Changed - Migration `0456_chat_review_lookup_indexes` builds four indexes with `CREATE INDEX CONCURRENTLY IF NOT EXISTS`. It runs through the existing top-level statement path, which repairs an invalid index on retry: - `chat_message_links_company_comment_idx` on `(company_id, comment_id)` where `comment_id is not null`. - `chat_message_links_delivery_idx` on `(delivery_id)` where `delivery_id is not null`. - `chat_deliveries_github_automatic_delivery_idx` on `(endpoint_id, normalized_event->'githubAutomatic'->'context'->>'deliveryId')` where that value is not null. - `heartbeat_runs_company_wake_comment_idx` on `(company_id, context_snapshot->>'wakeCommentId')`. This index is not partial. The planner does not use expression statistics from a partial index. Without these statistics, it estimates many matches and keeps the creation-order walk. - `githubReviewCheckState` reads the delivery's comment IDs first. If there is a comment, it reads the newest same-agent run with one of these `wakeCommentId` values. If there is no comment, it skips the run read. The comparison stays text equality on `comment_id::text`. - `createExternalReviewWaitReader` shares one read per issue between the review and blocked-inbox attention maps of one issue-list request. The reader exists only for that request. - `doc/DATABASE.md` describes the indexes and the new read order. - `scripts/benchmark-review-lookup-indexes.ts` compares the pre-fix and new code with and without the indexes. `scripts/benchmark-review-lookup-index-migration.ts` times the migration on a large synthetic database. ## Verification Local SQL measurements on a synthetic fixture. They are not production timings. Environment: embedded PostgreSQL 18.1, baseline revision `02bfe71a6b`. Fixture: 50,000 links, 5,000 deliveries with about 2 KiB events, and 4,000 runs with about 12 KiB incompressible contexts. The wake run is in the middle of the run history. Each value is the median server execution time from `EXPLAIN ANALYZE` (2 warmups, 9 samples). The order was: no indexes, indexes, then no indexes again. | Caller and statement | Before (no indexes, two passes) | After | Shared buffers before → after | | --- | --- | --- | --- | | Inherited review wait, link by source comment (same SQL) | 2.72 / 2.36 ms | 0.076 ms | 929 → 12 | | Review check, wake run found | 31.9 / 21.9 ms | 0.29 ms (two statements) | 25,776 → 62 | | Review check, no wake run yet | 71.0 / 47.5 ms | 0.06 ms (two statements) | 34,861 → 12 | - Indexes alone do not fix the review check. The old SQL with the new indexes took 8.6 ms (run found) and 29.7 ms (no run), because it still walked the run history. The new SQL without the new indexes was neutral (23.5 and 35.1 ms). - Service wall times on this shared machine were noisy, so the table reports server execution time. - Correctness: the benchmark fails unless the inherited statement returns the same positional rows in each index state. The check service result and the final wake-run rows of the new code must also match the pre-fix module for both cases. - Migration timing, normal migration runner, synthetic data: 200,000 runs (1.8 GB with 8 KiB incompressible contexts), 500,000 links and 100,000 deliveries. First run 4.2 s; rerun 0.38 s. Separate builds: links by comment 1.5 s, run wake comment 1.1 s, deliveries 0.7 s, links by delivery 0.3 s. All indexes were valid. The run index was 8.3 MB. - New tests: - `server/src/__tests__/github-review-check-state.test.ts` checks that the newest same-agent run is selected. It also checks that other agents, other companies, uppercase IDs, non-string values, list-only `wakeCommentIds`, comment-less links and unknown deliveries do not match. It checks that the generated statements can use the new indexes. - `server/src/services/native-runtime/external-review-wait.test.ts` checks that the reader reads each issue one time, keeps concurrent callers correct, and rejects all waiting callers when a read fails. - Red/green: with the pre-fix `review-check-state.ts`, the behavior test passes and the index test fails. With this change, both pass. - Focused runs pass: `issue-blocker-attention`, `heartbeat-issue-liveness-escalation`, review-wait, review-check-state, external-review-wait, review-repair (106 tests), and `external-chat-wait.integration` (285 tests). `pnpm --filter @paperclipai/server typecheck` and `pnpm --filter @paperclipai/db check:migrations` pass. Commands: ```sh pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-review-lookup-indexes.ts --baseline-ref=02bfe71a6b pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-review-lookup-index-migration.ts ``` ## Risks - The migration builds four indexes concurrently. It does not block writes. On a large database, the run index reads every run context one time. The local run took 1.1 s for 1.8 GB from a warm cache. Cold storage on smaller compute can be slower. - The run index adds one entry for each run insert and for each run update that is not a heap-only update. Many runs have no `wakeCommentId`, so these entries hold a null key. - The review check now sends two statements instead of one when a delivery has a comment. Each statement reads only a few index entries. - When two matching runs have the same `created_at`, either can be selected. The previous query had the same tie behavior. - This change does not change the number of in-review issues that one issue list reads. The blocked-inbox map still reads all in-review issues of the company. A smaller scope needs a separate change to the liveness classifier. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) by Anthropic, in Claude Code with tool use (shell, file edits, local PostgreSQL benchmarks). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- doc/DATABASE.md | 16 ++ packages/db/src/client.ts | 1 + .../0456_chat_review_lookup_indexes.sql | 4 + ...{0451_snapshot.json => 0456_snapshot.json} | 152 +++++++++++- packages/db/src/migrations/meta/_journal.json | 7 + packages/db/src/schema/chat_channels.ts | 15 ++ packages/db/src/schema/heartbeat_runs.ts | 6 + ...benchmark-review-lookup-index-migration.ts | 96 +++++++ scripts/benchmark-review-lookup-indexes.ts | 234 ++++++++++++++++++ .../github-review-check-state.test.ts | 93 +++++++ .../__tests__/helpers/github-review-wait.ts | 31 ++- .../github/review-check-state.ts | 37 +-- server/src/services/issues.ts | 20 +- .../external-review-wait.test.ts | 32 +++ .../native-runtime/external-review-wait.ts | 24 ++ 15 files changed, 741 insertions(+), 27 deletions(-) create mode 100644 packages/db/src/migrations/0456_chat_review_lookup_indexes.sql rename packages/db/src/migrations/meta/{0451_snapshot.json => 0456_snapshot.json} (99%) create mode 100644 scripts/benchmark-review-lookup-index-migration.ts create mode 100644 scripts/benchmark-review-lookup-indexes.ts create mode 100644 server/src/__tests__/github-review-check-state.test.ts create mode 100644 server/src/services/native-runtime/external-review-wait.test.ts diff --git a/doc/DATABASE.md b/doc/DATABASE.md index fb0e9198acc..8a0d3a50750 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -379,6 +379,22 @@ local fixture: pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-budget-cancellation-scan.ts --runs=20000 --payload-kib=16 ``` +GitHub review lookups use four indexes from migration 0456, which builds them +concurrently. `chat_message_links_company_comment_idx` finds a source comment's +link for inherited review waits and run-origin checks. +`chat_message_links_delivery_idx` finds a delivery's links. +`chat_deliveries_github_automatic_delivery_idx` finds a delivery by its GitHub +webhook delivery ID on one endpoint. These three are partial. +`heartbeat_runs_company_wake_comment_idx` keys runs by company and +`context_snapshot.wakeCommentId`. It is not partial, because the planner does not +use expression statistics from a partial index; without them it estimates many +matches and walks the run history by creation time instead. The review check +reads the delivery's comment IDs first and then the newest same-agent run woken +by one of them, so it no longer walks the agent's run history. The two link +indexes also serve the comment and delivery `on delete set null` actions. Issue +lists share one external review-wait read per issue between the review and +blocked-inbox attention maps. + The chat wake-notice sweep compares UUID columns directly against guarded, canonical lowercase UUID payload values. Malformed and noncanonical payloads still match nothing. The query can use existing primary keys without adding a diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index 10743acd93c..b6524aa1b51 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -618,6 +618,7 @@ const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set([ "0453_curious_ben_parker.sql", "0454_lumpy_ronan.sql", "0455_pending_budget_cancellation_index.sql", + "0456_chat_review_lookup_indexes.sql", "0384_funny_adam_warlock.sql", diff --git a/packages/db/src/migrations/0456_chat_review_lookup_indexes.sql b/packages/db/src/migrations/0456_chat_review_lookup_indexes.sql new file mode 100644 index 00000000000..4c37efeb656 --- /dev/null +++ b/packages/db/src/migrations/0456_chat_review_lookup_indexes.sql @@ -0,0 +1,4 @@ +CREATE INDEX CONCURRENTLY IF NOT EXISTS "chat_deliveries_github_automatic_delivery_idx" ON "chat_deliveries" USING btree ("endpoint_id",("normalized_event"->'githubAutomatic'->'context'->>'deliveryId')) WHERE ("chat_deliveries"."normalized_event"->'githubAutomatic'->'context'->>'deliveryId') is not null;--> statement-breakpoint +CREATE INDEX CONCURRENTLY IF NOT EXISTS "chat_message_links_company_comment_idx" ON "chat_message_links" USING btree ("company_id","comment_id") WHERE "chat_message_links"."comment_id" is not null;--> statement-breakpoint +CREATE INDEX CONCURRENTLY IF NOT EXISTS "chat_message_links_delivery_idx" ON "chat_message_links" USING btree ("delivery_id") WHERE "chat_message_links"."delivery_id" is not null;--> statement-breakpoint +CREATE INDEX CONCURRENTLY IF NOT EXISTS "heartbeat_runs_company_wake_comment_idx" ON "heartbeat_runs" USING btree ("company_id",("context_snapshot"->>'wakeCommentId')); \ No newline at end of file diff --git a/packages/db/src/migrations/meta/0451_snapshot.json b/packages/db/src/migrations/meta/0456_snapshot.json similarity index 99% rename from packages/db/src/migrations/meta/0451_snapshot.json rename to packages/db/src/migrations/meta/0456_snapshot.json index 371419bc95d..ea96ea87ab7 100644 --- a/packages/db/src/migrations/meta/0451_snapshot.json +++ b/packages/db/src/migrations/meta/0456_snapshot.json @@ -1,6 +1,6 @@ { - "id": "b5699366-77c2-48c8-b7dc-658a75de7658", - "prevId": "b8f43f1a-3230-4cda-991d-0e7b6323114b", + "id": "a2606b41-36c2-4eb5-a59d-28cc730bc455", + "prevId": "2be53987-902a-41b6-8cb4-6e89a768f8cf", "version": "7", "dialect": "postgresql", "tables": { @@ -10955,6 +10955,28 @@ "concurrently": false, "method": "btree", "with": {} + }, + "chat_deliveries_github_automatic_delivery_idx": { + "name": "chat_deliveries_github_automatic_delivery_idx", + "columns": [ + { + "expression": "endpoint_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "(\"normalized_event\"->'githubAutomatic'->'context'->>'deliveryId')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "(\"chat_deliveries\".\"normalized_event\"->'githubAutomatic'->'context'->>'deliveryId') is not null", + "concurrently": true, + "method": "btree", + "with": {} } }, "foreignKeys": { @@ -12393,6 +12415,44 @@ "concurrently": false, "method": "btree", "with": {} + }, + "chat_message_links_company_comment_idx": { + "name": "chat_message_links_company_comment_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "comment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"chat_message_links\".\"comment_id\" is not null", + "concurrently": true, + "method": "btree", + "with": {} + }, + "chat_message_links_delivery_idx": { + "name": "chat_message_links_delivery_idx", + "columns": [ + { + "expression": "delivery_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"chat_message_links\".\"delivery_id\" is not null", + "concurrently": true, + "method": "btree", + "with": {} } }, "foreignKeys": { @@ -17399,7 +17459,7 @@ "columnsTo": [ "id" ], - "onDelete": "set null", + "onDelete": "cascade", "onUpdate": "no action" }, "company_secret_proposals_secret_proposal_id_company_secret_proposals_id_fk": { @@ -34552,6 +34612,34 @@ "concurrently": false, "method": "btree", "with": {} + }, + "heartbeat_run_events_retry_exhausted_idx": { + "name": "heartbeat_run_events_retry_exhausted_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "run_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"heartbeat_run_events\".\"event_type\" = 'lifecycle' and \"heartbeat_run_events\".\"message\" like 'Bounded retry exhausted%'", + "concurrently": true, + "method": "btree", + "with": {} } }, "foreignKeys": { @@ -35393,6 +35481,22 @@ "method": "btree", "with": {} }, + "heartbeat_runs_pending_budget_cancellation_idx": { + "name": "heartbeat_runs_pending_budget_cancellation_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "jsonb_typeof(\"heartbeat_runs\".\"result_json\"->'startupCancellation'->'budgetEnforcement') = 'object'\n and \"heartbeat_runs\".\"result_json\"->'startupCancellation'->'budgetEnforcement'->>'deliveredAt' is null", + "concurrently": true, + "method": "btree", + "with": {} + }, "heartbeat_runs_tree_hold_suppression_idx": { "name": "heartbeat_runs_tree_hold_suppression_idx", "columns": [ @@ -35431,6 +35535,27 @@ "method": "btree", "with": {} }, + "heartbeat_runs_company_wake_comment_idx": { + "name": "heartbeat_runs_company_wake_comment_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "(\"context_snapshot\"->>'wakeCommentId')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, "heartbeat_runs_cost_accounting_pending_idx": { "name": "heartbeat_runs_cost_accounting_pending_idx", "columns": [ @@ -35562,6 +35687,27 @@ "method": "btree", "with": {} }, + "heartbeat_runs_company_native_workspace_idx": { + "name": "heartbeat_runs_company_native_workspace_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "(\"runner_profile_json\"->'nativeWorkspaceSync'->>'workspaceId')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, "heartbeat_runs_company_issue_created_idx": { "name": "heartbeat_runs_company_issue_created_idx", "columns": [ diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index f6f36f4fd59..6da1ec71b79 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -3179,6 +3179,13 @@ "when": 1794268118742, "tag": "0455_pending_budget_cancellation_index", "breakpoints": true + }, + { + "idx": 456, + "version": "7", + "when": 1794270045155, + "tag": "0456_chat_review_lookup_indexes", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/chat_channels.ts b/packages/db/src/schema/chat_channels.ts index 06bf31d12df..3a0a147d7b8 100644 --- a/packages/db/src/schema/chat_channels.ts +++ b/packages/db/src/schema/chat_channels.ts @@ -487,6 +487,11 @@ export const chatDeliveries = pgTable( table.endpointId, table.deduplicationKey, ), + // Review checks find their delivery by the GitHub webhook delivery id. + index("chat_deliveries_github_automatic_delivery_idx") + .on(table.endpointId, sql`(${table.normalizedEvent}->'githubAutomatic'->'context'->>'deliveryId')`) + .where(sql`(${table.normalizedEvent}->'githubAutomatic'->'context'->>'deliveryId') is not null`) + .concurrently(), foreignKey({ columns: [table.companyId, table.endpointId], foreignColumns: [chatEndpoints.companyId, chatEndpoints.id], @@ -638,6 +643,16 @@ export const chatMessageLinks = pgTable( table.conversationId, table.providerMessageId, ), + // Source-comment and delivery lookups (GitHub review waits and checks). + // These also serve the comment and delivery `on delete set null` actions. + index("chat_message_links_company_comment_idx") + .on(table.companyId, table.commentId) + .where(sql`${table.commentId} is not null`) + .concurrently(), + index("chat_message_links_delivery_idx") + .on(table.deliveryId) + .where(sql`${table.deliveryId} is not null`) + .concurrently(), foreignKey({ columns: [table.companyId, table.conversationId], foreignColumns: [chatConversations.companyId, chatConversations.id], diff --git a/packages/db/src/schema/heartbeat_runs.ts b/packages/db/src/schema/heartbeat_runs.ts index aaaf4fc2e74..819aaa20a0c 100644 --- a/packages/db/src/schema/heartbeat_runs.ts +++ b/packages/db/src/schema/heartbeat_runs.ts @@ -170,6 +170,12 @@ export const heartbeatRuns = pgTable( legacyControllerLeaseIdx: index("heartbeat_runs_legacy_controller_lease_idx") .on(table.controllerLeaseExpiresAt) .where(sql`${table.runtimeMode} = 'legacy' AND ${table.status} = 'running' AND ${table.controllerBootId} is not null`), + // Runs woken by one chat comment. Not partial: the planner ignores the + // expression statistics of a partial index and would then walk the run + // history by creation time to satisfy `order by created_at limit 1`. + companyWakeCommentIdx: index("heartbeat_runs_company_wake_comment_idx") + .on(table.companyId, sql`(${table.contextSnapshot}->>'wakeCommentId')`) + .concurrently(), costAccountingPendingIdx: index("heartbeat_runs_cost_accounting_pending_idx").on(table.updatedAt, table.id).where(sql`${table.costAccountingPending} = true`), costDataQualityIdx: index("heartbeat_runs_cost_data_quality_idx") .on(table.companyId, sql`coalesce(${table.finishedAt}, ${table.createdAt}) desc`, table.id) diff --git a/scripts/benchmark-review-lookup-index-migration.ts b/scripts/benchmark-review-lookup-index-migration.ts new file mode 100644 index 00000000000..5b689dce32f --- /dev/null +++ b/scripts/benchmark-review-lookup-index-migration.ts @@ -0,0 +1,96 @@ +/** + * Times migration 0456 through the normal migration runner on a large + * synthetic database, including a rerun after the history row is removed. + * + * pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-review-lookup-index-migration.ts + * + * Optional sizes: RUNS (default 200000), RUN_CONTEXT_KIB (8), LINKS (500000), + * DELIVERIES (100000). + */ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { applyPendingMigrations, createDb, startEmbeddedPostgresTestDatabase } from "../packages/db/src/index.js"; +import { seedGitHubReviewWait } from "../server/src/__tests__/helpers/github-review-wait.js"; + +const size = (name: string, fallback: number) => Number(process.env[name] ?? fallback); +const RUNS = size("RUNS", 200_000), RUN_CONTEXT_KIB = size("RUN_CONTEXT_KIB", 8); +const LINKS = size("LINKS", 500_000), DELIVERIES = size("DELIVERIES", 100_000); +const migrationName = "0456_chat_review_lookup_indexes"; +const migration = readFileSync(new URL(`../packages/db/src/migrations/${migrationName}.sql`, import.meta.url), "utf8"); +const indexNames = [...migration.matchAll(/IF NOT EXISTS "([a-z_]+)"/g)].map(match => match[1]!); + +const keepAlive = setInterval(() => {}, 1_000); +let temporary: Awaited> | undefined; +let db: ReturnType | undefined; +try { + temporary = await startEmbeddedPostgresTestDatabase("review-lookup-index-migration-"); + db = createDb(temporary.connectionString); + const sql = db.$client; + for (const name of indexNames) await sql.unsafe(`DROP INDEX IF EXISTS "${name}"`); + const { companyId, agentId, issueId, endpointId, conversationId } = await seedGitHubReviewWait(db); + await sql.unsafe("create extension if not exists pgcrypto"); + + const loadStart = performance.now(); + // Incompressible run contexts; half were woken by a comment. + await sql.unsafe(`insert into heartbeat_runs (company_id, agent_id, status, context_snapshot) + select $1::uuid, $2::uuid, 'succeeded', jsonb_build_object( + 'wakeCommentId', case when g % 2 = 0 then gen_random_uuid()::text end, 'issueId', $3::text, + 'prompt', (select string_agg(encode(gen_random_bytes(768), 'base64'), '') from generate_series(1, $4::int) s(i) where g > 0)) + from generate_series(1, $5::int) g`, [companyId, agentId, issueId, RUN_CONTEXT_KIB, RUNS]); + await sql.unsafe(`insert into issue_comments (company_id, issue_id, author_user_id, body) + select $1::uuid, $2::uuid, 'operator', 'load ' || g from generate_series(1, $3::int) g`, [companyId, issueId, LINKS]); + await sql.unsafe(`insert into chat_deliveries (company_id, endpoint_id, conversation_id, provider_event_id, + deduplication_key, event_kind, state, normalized_event) + select $1::uuid, $2::uuid, $3::uuid, 'load-' || g, 'load-' || g, 'message', 'processed', + jsonb_build_object('githubAutomatic', jsonb_build_object('context', jsonb_build_object( + 'deliveryId', gen_random_uuid()::text, 'body', (select string_agg(encode(gen_random_bytes(768), 'base64'), '') from generate_series(1, 2) s(i) where g > 0)))) + from generate_series(1, $4::int) g`, [companyId, endpointId, conversationId, DELIVERIES]); + await sql.unsafe(`with c as (select id, row_number() over (order by id) rn from issue_comments where company_id = $1::uuid), + d as (select id, row_number() over (order by id) rn from chat_deliveries where endpoint_id = $2::uuid) + insert into chat_message_links (company_id, endpoint_id, conversation_id, delivery_id, comment_id, + provider_message_id, direction) + select $1::uuid, $2::uuid, $3::uuid, d.id, c.id, 'load-' || c.rn, + case when c.rn % 2 = 0 then 'inbound' else 'outbound' end + from c left join d on d.rn = c.rn`, [companyId, endpointId, conversationId]); + await sql.unsafe("vacuum analyze"); + const loadMs = performance.now() - loadStart; + const tableSizes = await sql.unsafe(`select relname as table, n_live_tup::bigint::text as rows, + pg_size_pretty(pg_total_relation_size(relid)) as total_size from pg_stat_user_tables + where relname in ('chat_message_links', 'chat_deliveries', 'heartbeat_runs') order by relname`); + + async function migrate() { + await sql.unsafe(`delete from drizzle.__drizzle_migrations where hash in ( + select hash from drizzle.__drizzle_migrations order by created_at desc limit 1)`); + const start = performance.now(); + await applyPendingMigrations(temporary!.connectionString); + return performance.now() - start; + } + // First run builds every index; the rerun finds them valid and skips them. + const firstRunMs = await migrate(); + const valid = await sql.unsafe(`select c.relname, i.indisvalid, pg_size_pretty(pg_relation_size(c.oid)) as size + from pg_index i join pg_class c on c.oid = i.indexrelid where c.relname in (${indexNames.map((_, n) => `$${n + 1}`).join(", ")}) + order by c.relname`, indexNames); + assert.equal(valid.length, indexNames.length); + assert.ok(valid.every(row => row.indisvalid)); + const rerunMs = await migrate(); + // Per-index build time, measured separately with the same statements. + const builds: Array<{ index: string; ms: number }> = []; + for (const statement of migration.split("--> statement-breakpoint").map(part => part.trim()).filter(Boolean)) { + const name = statement.match(/IF NOT EXISTS "([a-z_]+)"/)![1]!; + await sql.unsafe(`DROP INDEX CONCURRENTLY "${name}"`); + const start = performance.now(); + await sql.unsafe(statement); + builds.push({ index: name, ms: Math.round(performance.now() - start) }); + } + console.log(JSON.stringify({ + postgresVersion: (await sql.unsafe("select version()"))[0]!.version, + fixture: { synthetic: true, runs: RUNS, runContextKiB: RUN_CONTEXT_KIB, links: LINKS, deliveries: DELIVERIES, + loadMs: Math.round(loadMs), tableSizes }, + migration: { firstRunMs: Math.round(firstRunMs), rerunMs: Math.round(rerunMs), indexes: valid, builds }, + }, null, 2)); +} finally { + try { + await db?.$client.end({ timeout: 0 }); + await temporary?.cleanup(); + } finally { clearInterval(keepAlive); } +} diff --git a/scripts/benchmark-review-lookup-indexes.ts b/scripts/benchmark-review-lookup-indexes.ts new file mode 100644 index 00000000000..1e3a3bd9a06 --- /dev/null +++ b/scripts/benchmark-review-lookup-indexes.ts @@ -0,0 +1,234 @@ +/** + * Local proof for the GitHub review lookups (migration 0456). + * + * Measures the SQL that the services generate: the inherited review-wait lookup + * by source comment (SQL unchanged; four new indexes) and the review-check + * fallback that finds the wake run from the delivery's inbound comments (SQL + * split into two statements). The pre-fix check module is loaded from + * --baseline-ref. Each version runs with and without the new indexes, and the + * script fails unless complete rows and service results match. + * + * pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-review-lookup-indexes.ts --baseline-ref= + * + * Optional sizes: LINKS (default 50000), DELIVERIES (5000), RUNS (4000), + * RUN_CONTEXT_KIB (12). + */ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { promises as fs, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { createDb, startEmbeddedPostgresTestDatabase } from "../packages/db/src/index.js"; +import { readInheritedGitHubReviewWait } from "../server/src/services/chat-channels/github/review-wait.js"; +import { githubReviewCheckState } from "../server/src/services/chat-channels/github/review-check-state.js"; +import { captureReviewWaitQueries, seedGitHubReviewCheck, seedGitHubReviewWait, + type CapturedReviewWaitQuery } from "../server/src/__tests__/helpers/github-review-wait.js"; + +const size = (name: string, fallback: number) => Number(process.env[name] ?? fallback); +const LINKS = size("LINKS", 50_000), DELIVERIES = size("DELIVERIES", 5_000); +const RUNS = size("RUNS", 4_000), RUN_CONTEXT_KIB = size("RUN_CONTEXT_KIB", 12); +const baselineRef = process.argv.find(arg => arg.startsWith("--baseline-ref="))?.slice(15); +assert.ok(baselineRef, "Pass an explicit pre-fix --baseline-ref="); +const git = (...args: string[]) => execFileSync("git", args, { encoding: "utf8" }); +const baselineRevision = git("rev-parse", "--verify", `${baselineRef}^{commit}`).trim(); +const root = fileURLToPath(new URL("../", import.meta.url)); +const checkModule = "server/src/services/chat-channels/github/review-check-state.ts"; +const waitModule = "server/src/services/chat-channels/github/review-wait.ts"; +assert.equal(git("show", `${baselineRevision}:${waitModule}`), readFileSync(path.join(root, waitModule), "utf8"), + "The review-wait module must be unchanged; only its indexes differ"); +const migration = readFileSync(path.join(root, "packages/db/src/migrations/0456_chat_review_lookup_indexes.sql"), "utf8"); +const indexStatements = migration.split("--> statement-breakpoint").map(statement => statement.trim()).filter(Boolean); +const indexNames = indexStatements.map(statement => statement.match(/IF NOT EXISTS "([a-z_]+)"/)![1]!); + +type CheckState = typeof githubReviewCheckState; +const keepAlive = setInterval(() => {}, 1_000); +let temporary: Awaited> | undefined; +let db: ReturnType | undefined; +let baselineDir: string | undefined; +try { + const moduleUrl = pathToFileURL(path.join(root, checkModule)); + baselineDir = await fs.mkdtemp(path.join(root, "server/scripts/.review-check-baseline-")); + const baselineFile = path.join(baselineDir, "review-check-state.ts"); + await fs.writeFile(baselineFile, git("show", `${baselineRevision}:${checkModule}`).replace(/from "(\.{1,2}\/[^"]+)"/g, + (_match, specifier: string) => `from ${JSON.stringify(fileURLToPath(new URL(specifier, moduleUrl)))}`)); + const baselineCheck = (await import(pathToFileURL(baselineFile).href) as { githubReviewCheckState: CheckState }).githubReviewCheckState; + + temporary = await startEmbeddedPostgresTestDatabase("review-lookups-benchmark-"); + db = createDb(temporary.connectionString); + const sql = db.$client; + const wait = await seedGitHubReviewWait(db); + const check = await seedGitHubReviewCheck(db); + + // Unrelated chat history: comments, deliveries and links on the same endpoint. + const loadStart = performance.now(); + await sql.unsafe(`insert into issue_comments (company_id, issue_id, author_user_id, body) + select $1::uuid, $2::uuid, 'operator', 'noise ' || g from generate_series(1, $3::int) g`, + [check.companyId, check.issueId, LINKS]); + await sql.unsafe(`insert into chat_deliveries (company_id, endpoint_id, conversation_id, provider_event_id, + deduplication_key, event_kind, state, normalized_event) + select $1::uuid, $2::uuid, $3::uuid, 'noise-' || g, 'noise-' || g, 'message', 'processed', + jsonb_build_object('githubAutomatic', jsonb_build_object('context', jsonb_build_object( + 'deliveryId', gen_random_uuid()::text, + 'body', (select string_agg(md5(random()::text || s.i || g), '') from generate_series(1, 64) s(i))))) + from generate_series(1, $4::int) g`, [check.companyId, check.endpointId, check.conversationId, DELIVERIES]); + await sql.unsafe(`with c as (select id, row_number() over (order by id) rn from issue_comments + where company_id = $1::uuid and body like 'noise %'), + d as (select id, row_number() over (order by id) rn from chat_deliveries + where endpoint_id = $2::uuid and provider_event_id like 'noise-%') + insert into chat_message_links (company_id, endpoint_id, conversation_id, delivery_id, comment_id, + provider_message_id, direction) + select $1::uuid, $2::uuid, $3::uuid, d.id, c.id, 'noise-' || c.rn, + case when c.rn % 2 = 0 then 'inbound' else 'outbound' end + from c left join d on d.rn = c.rn`, [check.companyId, check.endpointId, check.conversationId]); + // Runs of the same agent before and after the wake run; most were woken by + // some other comment. + await sql.unsafe(`insert into heartbeat_runs (company_id, agent_id, status, context_snapshot, created_at) + select $1::uuid, $2::uuid, 'succeeded', jsonb_build_object( + 'wakeCommentId', case when g % 5 <> 0 then gen_random_uuid()::text end, + 'issueId', $3::text, + 'prompt', (select string_agg(md5(random()::text || s.i || g), '') from generate_series(1, $4::int) s(i))), + now() + make_interval(secs => g - $5::int / 2) + from generate_series(1, $5::int) g`, [check.companyId, check.agentId, check.issueId, RUN_CONTEXT_KIB * 32, RUNS]); + const loadMs = performance.now() - loadStart; + const tableSizes = await sql.unsafe(`select relname as table, n_live_tup::int as rows, + pg_size_pretty(pg_total_relation_size(relid)) as total_size from pg_stat_user_tables + where relname in ('chat_message_links', 'chat_deliveries', 'heartbeat_runs', 'issue_comments') order by relname`); + // A delivery whose inbound comment has no wake run yet. + const [unmatched] = await sql.unsafe(`select d.normalized_event->'githubAutomatic'->'context'->>'deliveryId' as id + from chat_deliveries d join chat_message_links l on l.delivery_id = d.id and l.direction = 'inbound' + where d.endpoint_id = $1::uuid and d.provider_event_id like 'noise-%' order by d.provider_event_id limit 1`, [check.endpointId]); + assert.ok(unmatched?.id); + const unmatchedAction = { ...check.action, payload: { ...check.action.payload, + event: { ...check.event, deliveryId: unmatched.id as string } } }; + + const isWakeRead = (query: CapturedReviewWaitQuery) => query.sql.startsWith('select "chat_message_links"."comment_id"') || + query.sql.includes('from "chat_deliveries" inner join "chat_message_links"') || + (query.sql.startsWith('select "id", "status" from "heartbeat_runs"') && query.sql.includes("wakeCommentId")); + const rows = async (query: CapturedReviewWaitQuery) => + (await sql.unsafe(query.sql, query.params as never[]).values()).map(row => row.map(value => value?.toString() ?? null)); + async function captureCheck(reader: CheckState, action: typeof check.action) { + const queries: CapturedReviewWaitQuery[] = []; + const result = await reader(captureReviewWaitQueries(db!, queries), action); + return { result, wakeReads: queries.filter(isWakeRead) }; + } + async function captureWait() { + const queries: CapturedReviewWaitQuery[] = []; + const result = await readInheritedGitHubReviewWait(captureReviewWaitQueries(db!, queries), wait.run); + const inherited = queries.find(query => query.sql.includes('join "chat_github_reviews"')); + assert.ok(inherited); + return { result, inherited }; + } + const median = (values: number[]) => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)]!; + const round = (value: number) => Number(value.toFixed(3)); + async function sample(run: () => Promise) { + for (let n = 0; n < 2; n++) await run(); + const samples: number[] = []; + for (let n = 0; n < 9; n++) samples.push(await run()); + return { samplesMs: samples.map(round), medianMs: round(median(samples)), + minMs: round(Math.min(...samples)), maxMs: round(Math.max(...samples)) }; + } + // Server execution time from EXPLAIN ANALYZE, summed over a caller's statements. + async function explain(query: CapturedReviewWaitQuery) { + const [result] = await sql.unsafe(`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${query.sql}`, query.params as never[]); + return (result!["QUERY PLAN"] as Array<{ Plan: Record; "Execution Time": number }>)[0]!; + } + const executionMs = async (queries: CapturedReviewWaitQuery[]) => { + let total = 0; + for (const query of queries) total += (await explain(query))["Execution Time"]; + return total; + }; + const wall = (run: () => Promise) => async () => { + const start = performance.now(); + await run(); + return performance.now() - start; + }; + async function plans(queries: CapturedReviewWaitQuery[]) { + return Promise.all(queries.map(async query => { + const root = await explain(query), nodes: string[] = []; + const walk = (node: Record) => { + if (/Scan|Join|Loop/.test(String(node["Node Type"]))) nodes.push(`${node["Node Type"]}${node["Index Name"] ? ` using ${node["Index Name"]}` : ""}${node["Relation Name"] ? ` on ${node["Relation Name"]}` : ""}`); + for (const child of (node.Plans as Array> | undefined) ?? []) walk(child); + }; + walk(root.Plan); + return { executionMs: root["Execution Time"], sharedHitBlocks: root.Plan["Shared Hit Blocks"], + sharedReadBlocks: root.Plan["Shared Read Blocks"], nodes }; + })); + } + + async function measure(indexes: boolean) { + const builds: Array<{ index: string; ms: number }> = []; + if (!indexes) { + for (const name of indexNames) await sql.unsafe(`DROP INDEX CONCURRENTLY IF EXISTS "${name}"`); + } else { + for (const [n, statement] of indexStatements.entries()) { + const start = performance.now(); + await sql.unsafe(statement); + builds.push({ index: indexNames[n]!, ms: round(performance.now() - start) }); + } + } + await sql.unsafe("ANALYZE"); + const waitCapture = await captureWait(); + const versions = { baseline: baselineCheck, treatment: githubReviewCheckState }; + const checks: Record = {}; + const outputs: Record = {}; + for (const [version, reader] of Object.entries(versions)) { + for (const [name, action] of [["matched", check.action], ["noWakeRunYet", unmatchedAction]] as const) { + const captured = await captureCheck(reader, action); + const finalRows = captured.wakeReads.length ? await rows(captured.wakeReads.at(-1)!) : []; + outputs[`${version}.${name}`] = { result: captured.result, finalRows }; + checks[`${version}.${name}`] = { + statements: captured.wakeReads.length, + serverExecution: await sample(() => executionMs(captured.wakeReads)), + serviceWall: await sample(wall(() => reader(db!, action))), + plans: await plans(captured.wakeReads), + }; + } + } + return { + indexes, builds, waitCapture, outputs, + inheritedRows: await rows(waitCapture.inherited), + inherited: { + serverExecution: await sample(() => executionMs([waitCapture.inherited])), + serviceWall: await sample(wall(() => readInheritedGitHubReviewWait(db!, wait.run))), + plans: await plans([waitCapture.inherited]), + }, + checks, + }; + } + + // No indexes, indexes, then no indexes again to expose cache-order bias. + const runs = [await measure(false), await measure(true), await measure(false)]; + const reference = runs[0]!; + for (const run of runs) { + assert.equal(run.waitCapture.inherited.sql, reference.waitCapture.inherited.sql); + assert.deepEqual(run.inheritedRows, reference.inheritedRows, "Inherited review rows must match"); + assert.deepEqual(run.waitCapture.result, reference.waitCapture.result); + for (const name of ["matched", "noWakeRunYet"]) { + for (const version of ["baseline", "treatment"]) { + assert.deepEqual(run.outputs[`${version}.${name}`], reference.outputs[`baseline.${name}`], + `${version} ${name} result and final wake-run rows must match the pre-fix module`); + } + } + } + assert.equal(reference.waitCapture.result?.kind, "published"); + assert.deepEqual((reference.outputs["baseline.matched"] as { finalRows: unknown }).finalRows, [[check.wakeRunId, "running"]]); + assert.deepEqual((reference.outputs["baseline.noWakeRunYet"] as { finalRows: unknown }).finalRows, []); + + console.log(JSON.stringify({ + baselineRevision, treatmentRevision: git("rev-parse", "HEAD").trim(), + treatmentDiff: execFileSync("git", ["diff", "HEAD", "--", checkModule], { cwd: root, encoding: "utf8" }), + postgresVersion: (await sql.unsafe("select version()"))[0]!.version, + settings: await sql.unsafe("select name, setting from pg_settings where name in ('shared_buffers','work_mem','jit') order by name"), + fixture: { synthetic: true, links: LINKS, deliveries: DELIVERIES, runs: RUNS, runContextKiB: RUN_CONTEXT_KIB, + loadMs: Math.round(loadMs), tableSizes }, + correctness: { inheritedSqlUnchanged: true, inheritedRowsEqual: true, checkResultsEqual: true, finalWakeRunRowsEqual: true, + cases: ["matched", "noWakeRunYet"] }, + results: runs.map(({ waitCapture: _capture, outputs: _outputs, inheritedRows: _rows, ...run }) => run), + }, 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/server/src/__tests__/github-review-check-state.test.ts b/server/src/__tests__/github-review-check-state.test.ts new file mode 100644 index 00000000000..4950ecad9ce --- /dev/null +++ b/server/src/__tests__/github-review-check-state.test.ts @@ -0,0 +1,93 @@ +import { randomUUID } from "node:crypto"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { agents, chatMessageLinks, createDb, heartbeatRuns, type Db } from "@paperclipai/db"; +import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { captureReviewWaitQueries, seedGitHubReviewCheck, seedGitHubReviewWait, + type CapturedReviewWaitQuery } from "./helpers/github-review-wait.js"; +import { githubReviewCheckState } from "../services/chat-channels/github/review-check-state.js"; +import { readInheritedGitHubReviewWait } from "../services/chat-channels/github/review-wait.js"; + +describe("GitHub review lookups by source comment and delivery", () => { + let temporary: Awaited>; + let db: Db; + beforeAll(async () => { + if (process.env.PAPERCLIP_TEST_DATABASE_URL) { + db = createDb(process.env.PAPERCLIP_TEST_DATABASE_URL); + } else { + temporary = await startEmbeddedPostgresTestDatabase("github-review-check-state-"); + db = createDb(temporary.connectionString); + } + }, 30_000); + afterAll(async () => { await db?.$client.end({ timeout: 0 }); await temporary?.cleanup(); }); + + it("finds only the newest same-agent run woken by the delivery's comment", async () => { + const f = await seedGitHubReviewCheck(db); + const other = await seedGitHubReviewWait(db); + const otherAgentId = randomUUID(), at = (seconds: number) => new Date(Date.now() + seconds * 1_000); + await db.insert(agents).values({ id: otherAgentId, companyId: f.companyId, name: "Other", adapterType: "process" }); + // A delivery link without a comment cannot select a run. + await db.insert(chatMessageLinks).values({ companyId: f.companyId, endpointId: f.endpointId, + conversationId: f.conversationId, deliveryId: f.chatDeliveryId, providerMessageId: "outbound-reply", direction: "outbound" }); + await db.insert(heartbeatRuns).values([ + // Same comment, but another agent or company: never the review's run. + { companyId: f.companyId, agentId: otherAgentId, status: "succeeded", createdAt: at(60), + contextSnapshot: { wakeCommentId: f.commentId } }, + { companyId: other.companyId, agentId: other.agentId, status: "succeeded", createdAt: at(60), + contextSnapshot: { wakeCommentId: f.commentId } }, + // Text comparison: noncanonical, non-string and list-only values do not match. + { companyId: f.companyId, agentId: f.agentId, status: "failed", createdAt: at(60), + contextSnapshot: { wakeCommentId: f.commentId.toUpperCase() } }, + { companyId: f.companyId, agentId: f.agentId, status: "failed", createdAt: at(60), + contextSnapshot: { wakeCommentId: [f.commentId] } }, + { companyId: f.companyId, agentId: f.agentId, status: "failed", createdAt: at(60), + contextSnapshot: { wakeCommentIds: [f.commentId] } }, + { companyId: f.companyId, agentId: f.agentId, status: "failed", createdAt: at(60), contextSnapshot: null }, + { companyId: f.companyId, agentId: f.agentId, status: "succeeded", createdAt: at(-60), + contextSnapshot: { wakeCommentId: f.commentId } }, + ]); + expect(await githubReviewCheckState(db, f.action)).toMatchObject({ + disposition: "publish", run: { id: f.wakeRunId, status: "running" }, state: "running", status: "in_progress", + }); + + const [newest] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, + status: "succeeded", createdAt: at(120), contextSnapshot: { wakeCommentId: f.commentId } }).returning(); + expect(await githubReviewCheckState(db, f.action)).toMatchObject({ + run: { id: newest!.id, status: "succeeded" }, state: "incomplete", status: "completed", + }); + + // Another delivery id on the same endpoint selects no run. + const unmatched = { ...f.action, payload: { ...f.action.payload, + event: { ...f.event, deliveryId: randomUUID() } } }; + expect(await githubReviewCheckState(db, unmatched)).toMatchObject({ run: undefined, state: "queued" }); + }); + + it("reads source comments, deliveries and wake runs through their indexes", async () => { + const f = await seedGitHubReviewCheck(db); + const wait = await seedGitHubReviewWait(db); + // A run history in which each run was woken by another comment. With its + // statistics, the planner must prefer the wake-comment index to walking + // the history by creation time. + await db.$client.unsafe(`insert into heartbeat_runs (company_id, agent_id, status, context_snapshot, created_at) + select $1::uuid, $2::uuid, 'succeeded', jsonb_build_object('wakeCommentId', gen_random_uuid()::text), + now() + make_interval(secs => g) from generate_series(1, 2000) g`, [f.companyId, f.agentId]); + await db.$client.unsafe("analyze heartbeat_runs"); + const queries: CapturedReviewWaitQuery[] = []; + await githubReviewCheckState(captureReviewWaitQueries(db, queries), f.action); + await readInheritedGitHubReviewWait(captureReviewWaitQueries(db, queries), wait.run); + const comments = queries.find(query => query.sql.includes('from "chat_deliveries" inner join "chat_message_links"')); + const wakeRun = queries.find(query => query.sql.includes('from "heartbeat_runs"') && query.sql.includes("wakeCommentId")); + const inherited = queries.find(query => query.sql.includes('join "chat_github_reviews"')); + expect(comments && wakeRun && inherited).toBeTruthy(); + const plan = (query: CapturedReviewWaitQuery) => db.$client.begin(async sql => { + // Small test tables favour sequential scans; disable them to prove the + // generated predicates can use the partial indexes at all. + await sql.unsafe("set local enable_seqscan = off"); + return JSON.stringify(await sql.unsafe(`explain (format json) ${query.sql}`, query.params as never[])); + }); + const commentsPlan = await plan(comments!), wakeRunPlan = await plan(wakeRun!), inheritedPlan = await plan(inherited!); + expect(commentsPlan).toContain("chat_deliveries_github_automatic_delivery_idx"); + expect(commentsPlan).toContain("chat_message_links_delivery_idx"); + expect(wakeRunPlan).toContain("heartbeat_runs_company_wake_comment_idx"); + expect(inheritedPlan).toContain("chat_message_links_company_comment_idx"); + }); +}); diff --git a/server/src/__tests__/helpers/github-review-wait.ts b/server/src/__tests__/helpers/github-review-wait.ts index eb3bea3fcef..ecdcbe0075f 100644 --- a/server/src/__tests__/helpers/github-review-wait.ts +++ b/server/src/__tests__/helpers/github-review-wait.ts @@ -1,7 +1,7 @@ import { createHash, randomUUID } from "node:crypto"; import { and, eq, fillPlaceholders } from "drizzle-orm"; -import { agents, chatActions, chatConversations, chatEndpointResources, chatEndpoints, - chatGitHubReviews, chatMessageLinks, companies, heartbeatRuns, issueComments, issues, +import { agents, chatActions, chatConversations, chatDeliveries, chatEndpointResources, chatEndpoints, + chatGitHubConfigurations, chatGitHubReviews, chatMessageLinks, companies, heartbeatRuns, issueComments, issues, runIdentityContexts, toolApplications, toolConnections, type Db } from "@paperclipai/db"; import { defaultGitHubReviewPolicy } from "@paperclipai/shared"; @@ -79,6 +79,33 @@ export function captureReviewWaitQueries(db: Db, queries: CapturedReviewWaitQuer }}); } +/** Extend the review-wait fixture to a check action whose review has no run + * yet, so the check state must find the wake run from the inbound comment. */ +export async function seedGitHubReviewCheck(db: Db) { + const f = await seedGitHubReviewWait(db); + const githubDeliveryId = randomUUID(), chatDeliveryId = randomUUID(), wakeRunId = randomUUID(); + const event = { deliveryId: githubDeliveryId, repository: "synthetic/repository", repositoryId: "42", + pullNumber: 7, headSha: f.headSha }; + await db.update(chatEndpoints).set({ status: "active" }).where(eq(chatEndpoints.id, f.endpointId)); + await db.update(chatEndpointResources).set({ enabled: true, availability: "available" }) + .where(eq(chatEndpointResources.id, f.resourceId)); + await db.insert(chatGitHubConfigurations).values({ endpointId: f.endpointId, companyId: f.companyId, + configuration: { toolsEnabled: true } as never, updatedByUserId: "operator" }); + await db.insert(chatDeliveries).values({ id: chatDeliveryId, companyId: f.companyId, endpointId: f.endpointId, + conversationId: f.conversationId, providerEventId: githubDeliveryId, deduplicationKey: githubDeliveryId, + eventKind: "message", state: "processed", normalizedEvent: { githubAutomatic: { context: event } } }); + await db.update(chatMessageLinks).set({ deliveryId: chatDeliveryId }) + .where(and(eq(chatMessageLinks.companyId, f.companyId), eq(chatMessageLinks.commentId, f.commentId))); + await db.insert(heartbeatRuns).values({ id: wakeRunId, companyId: f.companyId, agentId: f.agentId, + nativeIssueId: f.issueId, status: "running", contextSnapshot: { wakeCommentId: f.commentId } }); + await db.update(chatGitHubReviews).set({ runId: null, assessment: null, state: "queued" }) + .where(eq(chatGitHubReviews.id, f.reviewId)); + const [action] = await db.insert(chatActions).values({ companyId: f.companyId, endpointId: f.endpointId, + kind: "github_review_check", providerActionId: `github_review_check:${githubDeliveryId}`, + payload: { event, admitted: true, runtimeGeneration: 0 } }).returning(); + return { ...f, action: action!, event, githubDeliveryId, chatDeliveryId, wakeRunId }; +} + export async function revokeReviewWaitConnection(db: Db, fixture: Awaited>) { await db.update(toolConnections).set({ enabled: false }).where(and( eq(toolConnections.id, fixture.connectionId), eq(toolConnections.companyId, fixture.companyId))); diff --git a/server/src/services/chat-channels/github/review-check-state.ts b/server/src/services/chat-channels/github/review-check-state.ts index 2254a82feb0..8c92c9ef421 100644 --- a/server/src/services/chat-channels/github/review-check-state.ts +++ b/server/src/services/chat-channels/github/review-check-state.ts @@ -1,4 +1,4 @@ -import { and, desc, eq, sql } from "drizzle-orm"; +import { and, desc, eq, inArray, isNotNull, sql } from "drizzle-orm"; import { chatActions, chatDeliveries, chatEndpoints, chatEndpointResources, chatGitHubConfigurations, chatGitHubReviews, chatMessageLinks, companies, heartbeatRuns, type Db } from "@paperclipai/db"; @@ -66,30 +66,37 @@ export async function githubReviewCheckState(db: Db, action: typeof chatActions. )[0] : undefined; if (review && !run) { - const [sourceRun] = await db - .select({ run: { id: heartbeatRuns.id, status: heartbeatRuns.status } }) + // Read the delivery's few comments first. A join lets the planner walk + // the agent's whole run history by creation time; a known comment list + // uses the wake-comment index, and no comment means no run to find. + const commentIds = [...new Set((await db + .select({ commentId: chatMessageLinks.commentId }) .from(chatDeliveries) .innerJoin( chatMessageLinks, eq(chatMessageLinks.deliveryId, chatDeliveries.id), ) - .innerJoin( - heartbeatRuns, - and( - eq(heartbeatRuns.companyId, action.companyId), - eq(heartbeatRuns.agentId, source.endpoint.assignedAgentId), - sql`${heartbeatRuns.contextSnapshot}->>'wakeCommentId' = ${chatMessageLinks.commentId}::text`, - ), - ) .where( and( eq(chatDeliveries.endpointId, action.endpointId), sql`${chatDeliveries.normalizedEvent}->'githubAutomatic'->'context'->>'deliveryId' = ${event.deliveryId}`, + isNotNull(chatMessageLinks.commentId), ), - ) - .orderBy(desc(heartbeatRuns.createdAt)) - .limit(1); - run = sourceRun?.run; + )).map(link => link.commentId!))]; + if (commentIds.length) { + [run] = await db + .select({ id: heartbeatRuns.id, status: heartbeatRuns.status }) + .from(heartbeatRuns) + .where( + and( + eq(heartbeatRuns.companyId, action.companyId), + eq(heartbeatRuns.agentId, source.endpoint.assignedAgentId), + inArray(sql`${heartbeatRuns.contextSnapshot}->>'wakeCommentId'`, commentIds), + ), + ) + .orderBy(desc(heartbeatRuns.createdAt)) + .limit(1); + } } const [delivery] = await db .select({ state: chatDeliveries.state }) diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index 3ad5ebad329..bf009635f5b 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -69,7 +69,7 @@ import { createHash, randomUUID } from "node:crypto"; import { isExplicitContinuationRetryClaim } from "./explicit-continuation-retry-claim.js"; import { nativeManualAdmissionHoldsExecution } from "./native-runtime/native-runner-ownership.js"; import { markdownToPlainText, parseMarkdown } from "chat"; -import { listExternalReviewWaits } from "./native-runtime/external-review-wait.js"; +import { createExternalReviewWaitReader, type ExternalReviewWaitReader } from "./native-runtime/external-review-wait.js"; import { and, asc, @@ -4686,6 +4686,7 @@ async function listIssueReviewAttentionMap( dbOrTx: any, companyId: string, issueRows: IssueReviewAttentionInput[], + readExternalReviewWaits: ExternalReviewWaitReader = createExternalReviewWaitReader(dbOrTx, companyId), ): Promise> { const result = new Map(); for (const row of issueRows) result.set(row.id, reviewAttentionNone()); @@ -4929,7 +4930,7 @@ async function listIssueReviewAttentionMap( queuedWakeRequests: wakeRows, pendingInteractions: interactionRows, pendingApprovals: approvalRows, - externalResponseWaits: await listExternalReviewWaits(dbOrTx, companyId, reviewIds), + externalResponseWaits: await readExternalReviewWaits(reviewIds), openRecoveryIssues: recoveryPaths, now: new Date(), }; @@ -5777,6 +5778,7 @@ async function listIssueBlockedInboxAttentionMap( dbOrTx: any, companyId: string, issueRows: BlockedInboxIssueRow[], + readExternalReviewWaits: ExternalReviewWaitReader = createExternalReviewWaitReader(dbOrTx, companyId), ): Promise> { const rowIssueIds = [...new Set(issueRows.map((row) => row.id))]; const result = new Map(); @@ -6036,7 +6038,7 @@ async function listIssueBlockedInboxAttentionMap( }); const findings = classifyIssueGraphLiveness({ - externalResponseWaits: await listExternalReviewWaits(dbOrTx, companyId, graphIssues.filter(issue => issue.status === "in_review").map(issue => issue.id)), + externalResponseWaits: await readExternalReviewWaits(graphIssues.filter(issue => issue.status === "in_review").map(issue => issue.id)), issues: graphIssues.map((issue) => ({ id: issue.id, companyId: issue.companyId, @@ -6637,6 +6639,8 @@ async function listBlockedInboxIssues( const issueIds = withRuns.map((row) => row.id); const includeLiveDescendantSummary = filters?.includeLiveDescendantSummary === true; + // Both attention maps read external review waits for overlapping issues. + const readExternalReviewWaits = createExternalReviewWaitReader(dbOrTx, companyId); const [ statsRows, readRows, @@ -6656,8 +6660,8 @@ async function listBlockedInboxIssues( lastActivityStatsForIssues(dbOrTx, companyId, issueIds), blockedByMapForIssues(dbOrTx, companyId, issueIds), listIssueBlockerAttentionMap(dbOrTx, companyId, withRuns), - listIssueReviewAttentionMap(dbOrTx, companyId, withRuns), - listIssueBlockedInboxAttentionMap(dbOrTx, companyId, withRuns), + listIssueReviewAttentionMap(dbOrTx, companyId, withRuns, readExternalReviewWaits), + listIssueBlockedInboxAttentionMap(dbOrTx, companyId, withRuns, readExternalReviewWaits), includeLiveDescendantSummary ? liveDescendantCountMapForIssues(dbOrTx, companyId, issueIds) : Promise.resolve(new Map()), @@ -8601,6 +8605,8 @@ export function issueService(db: Db) { const archiveByIssueId = new Map( archiveRows.map((row) => [row.issueId, row]), ); + // Both attention maps read external review waits for overlapping issues. + const readExternalReviewWaits = createExternalReviewWaitReader(db, companyId); const [ blockerAttentionByIssueId, reviewAttentionByIssueId, @@ -8609,9 +8615,9 @@ export function issueService(db: Db) { ? [new Map(), new Map(), new Map()] : await timePhase("attention", () => Promise.all([ filters?.listProjection === "index" ? Promise.resolve(new Map()) : listIssueBlockerAttentionMap(db, companyId, withRuns), - filters?.listProjection === "index" ? Promise.resolve(new Map()) : listIssueReviewAttentionMap(db, companyId, withRuns), + filters?.listProjection === "index" ? Promise.resolve(new Map()) : listIssueReviewAttentionMap(db, companyId, withRuns, readExternalReviewWaits), includeBlockedInboxAttention - ? listIssueBlockedInboxAttentionMap(db, companyId, withRuns) + ? listIssueBlockedInboxAttentionMap(db, companyId, withRuns, readExternalReviewWaits) : Promise.resolve(new Map()), ])); diff --git a/server/src/services/native-runtime/external-review-wait.test.ts b/server/src/services/native-runtime/external-review-wait.test.ts new file mode 100644 index 00000000000..ed1c65229db --- /dev/null +++ b/server/src/services/native-runtime/external-review-wait.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it, vi } from "vitest"; +import type { Db } from "@paperclipai/db"; +import { createExternalReviewWaitReader, type ExternalReviewWait } from "./external-review-wait.js"; + +const db = {} as Db; +const wait = (issueId: string) => ({ issueId, companyId: "company" }) as ExternalReviewWait; + +describe("createExternalReviewWaitReader", () => { + it("reads each issue once for callers that share one request", async () => { + const list = vi.fn(async (_db: Db, _companyId: string, issueIds: string[]) => + issueIds.filter(issueId => issueId !== "b").map(wait)); + const read = createExternalReviewWaitReader(db, "company", list); + // The review and blocked-inbox maps start their reads concurrently. + const [page, graph] = await Promise.all([read(["a", "b"]), read(["c", "a", "b", "c"])]); + expect(page).toEqual([wait("a")]); + expect(graph).toEqual([wait("c"), wait("a")]); + expect(await read(["a"])).toEqual([wait("a")]); + expect(await read([])).toEqual([]); + expect(list.mock.calls.map(([, companyId, issueIds]) => [companyId, issueIds])).toEqual([ + ["company", ["a", "b"]], ["company", ["c"]], + ]); + expect(list.mock.calls.every(([database]) => database === db)).toBe(true); + }); + + it("rejects every caller that waits on a failed read", async () => { + const failure = new Error("database unavailable"); + const list = vi.fn(async () => { throw failure; }); + const read = createExternalReviewWaitReader(db, "company", list); + await expect(Promise.all([read(["a"]), read(["a", "b"])])).rejects.toBe(failure); + expect(list).toHaveBeenCalledTimes(2); + }); +}); diff --git a/server/src/services/native-runtime/external-review-wait.ts b/server/src/services/native-runtime/external-review-wait.ts index b59aed390c3..054113ce9f1 100644 --- a/server/src/services/native-runtime/external-review-wait.ts +++ b/server/src/services/native-runtime/external-review-wait.ts @@ -78,3 +78,27 @@ export async function listExternalReviewWaits(db: Db, companyId: string, issueId })); return waits.filter((wait): wait is NonNullable => wait !== null); } + +export type ExternalReviewWait = Awaited>[number]; +export type ExternalReviewWaitReader = (issueIds: string[]) => Promise; + +/** Share one company's wait reads between callers that serve one request. + * Each issue's wait is independent of the other requested issues, so an issue + * is read at most once. Do not keep a reader beyond its request. */ +export function createExternalReviewWaitReader(db: Db, companyId: string, + list: typeof listExternalReviewWaits = listExternalReviewWaits): ExternalReviewWaitReader { + const byIssueId = new Map>(); + return async (issueIds) => { + const requested = [...new Set(issueIds)]; + const missing = requested.filter(issueId => !byIssueId.has(issueId)); + if (missing.length) { + const read = list(db, companyId, missing) + .then(waits => new Map(waits.map(wait => [wait.issueId, wait]))); + for (const issueId of missing) { + byIssueId.set(issueId, read.then(waits => waits.get(issueId) ?? null)); + } + } + const waits = await Promise.all(requested.map(issueId => byIssueId.get(issueId)!)); + return waits.filter((wait): wait is ExternalReviewWait => wait !== null); + }; +} From 3a5572c9e54dafdda658b45f970dfcbf441620ab Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Mon, 9 Nov 2026 16:50:58 -0800 Subject: [PATCH 02/10] Extend login PTY contracts for existing computers (#20410) ## Thinking Path > - Paperclip manages agent execution across environments. > - Environment providers own execution resources. > - Codex and Claude already share the login PTY transport. > - A login on an existing computer needs its own allocation and deadline. > - Input retries must retain their identity. > - Codex also needs a fixed credential-file read; Claude already returns its token through PTY output. > - This change extends the shared contract and keeps both existing provider parsers. ## Linked Issues or Issue Description **Problem** The existing login contract assumes a temporary sandbox. It cannot describe a login allocation on an existing computer or export its fixed credential result without generic execution. **Proposed solution** Add shared allocation purpose, command identity, PTY deadline, and input identity fields for both Codex and Claude. Add one optional credential-result hook for Codex's auth.json file. **Alternatives considered** A separate Claude login implementation would duplicate the current setup-token parser and owner-bound credential writer. Claude continues to use that existing path. The new artifact hook is Codex-specific because Claude's setup-token result comes through the existing shared PTY output stream. ## What Changed - Export the login contract types from the main SDK entry point. - Forward login purpose and command through plugin allocation and retain them in lease metadata. - Forward the PTY deadline and give each input write a stable identity. - End a login route when the worker cannot confirm input delivery. - Preserve the opening company scope for input, stop, and close callbacks. - Advertise and dispatch the optional fixed Codex credential-result hook. The allocation, deadline, input, output, and cleanup contracts serve both providers. This PR does not enable either provider on an existing computer. The dependent consumer PR connects admission, services, credential completion, and UI for both providers. ## Verification - Close-ordering regression: all 91 host worker-manager tests passed, including concurrent close callers waiting behind a held plugin acknowledgement after input failure. Server TypeScript check passed. All current CI gates, ordinary review, and the selected follow-up review pass on a39fb59bd1. - Shared and SDK TypeScript builds passed. - SDK worker dispatch: 31 tests passed. - Host worker-manager: 90 tests passed, including a nested worker-to-host scope guard. - Environment runtime with embedded PostgreSQL: 197 tests passed. - Added absent-hook, input-failure, and allocation-forwarding checks. - A running instance is not required to validate this SDK-only increment. Real provider acceptance follows after the dependent hooks are connected. ## Risks The hook and fields are optional. Existing sandbox providers keep their current path. Failed input delivery now ends its route instead of waiting for the deadline. There is no database migration. ## Model Used OpenAI Codex, GPT-6 family, with reasoning and code execution. The exact runtime model identifier and context size are not exposed to this agent. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- packages/plugins/sdk/README.md | 23 ++++++++ packages/plugins/sdk/src/define-plugin.ts | 5 ++ packages/plugins/sdk/src/index.ts | 9 +++ packages/plugins/sdk/src/protocol.ts | 32 ++++++++++ packages/plugins/sdk/src/worker-rpc-host.ts | 10 ++++ .../plugins/sdk/tests/worker-rpc-host.test.ts | 20 ++++++- .../src/__tests__/environment-runtime.test.ts | 4 ++ .../fixtures/plugin-worker-login-pty.cjs | 34 ++++++++++- .../__tests__/plugin-worker-manager.test.ts | 58 +++++++++++++++++++ server/src/services/environment-runtime.ts | 12 +++- server/src/services/plugin-worker-manager.ts | 47 +++++++++------ 11 files changed, 232 insertions(+), 22 deletions(-) diff --git a/packages/plugins/sdk/README.md b/packages/plugins/sdk/README.md index 29da17228ed..07bf77b16c5 100644 --- a/packages/plugins/sdk/README.md +++ b/packages/plugins/sdk/README.md @@ -1566,3 +1566,26 @@ The return value is transient raw credential material with the Connector's existing permissions. This capability is for trusted execution infrastructure, not agent-facing tools or UI. Never expose or persist it. See [GitHub identity](../../../doc/execution-github-identity.md#project-authorization-for-background-repository-work). + +## Login on an existing computer + +A driver can use the existing login PTY hooks for a login on a saved agent's +computer. Core sends `purpose: "login"`, a closed `loginCommandKey`, a stable +`creationOperationId`, and an absolute `requestedExpiresAt` to lease acquisition. +Release and destroy must retire only that login allocation and preserve the +computer. Omitted purpose retains the existing execution behavior. + +Core supplies `expiresAt` to the PTY open and an `inputId` for each input write. +Input, stop, and close retain the opening company context so provider callbacks +can use company-scoped host services during cleanup. +A provider that retries delivery must retain the input identity and bytes, and +reject reuse of the identity with different input. A failed input call ends the +Core login; Core does not silently replay an unconfirmed write. + +Providers can implement `onLoginPtyReadCredential` to export the fixed Codex +credential artifact for a bound login lease. The result is +`{ kind: "codex-auth-json", authJson }`; the request accepts no path or command. +The worker advertises this optional method only when the hook exists. The host +must check that method before using this read path, enforce a size limit, and +keep credential bytes out of logs and public session responses. Existing sandbox +providers can continue to use their descriptor-bound credential read. diff --git a/packages/plugins/sdk/src/define-plugin.ts b/packages/plugins/sdk/src/define-plugin.ts index 18edbc1db9d..eb6530c0067 100644 --- a/packages/plugins/sdk/src/define-plugin.ts +++ b/packages/plugins/sdk/src/define-plugin.ts @@ -94,6 +94,8 @@ import type { PluginLoginPtyOpenParams, PluginLoginPtyOpenResult, PluginLoginPtyInputParams, + PluginLoginPtyReadCredentialParams, + PluginLoginPtyReadCredentialResult, PluginLoginPtyStopParams, PluginLoginPtyCloseParams, PluginLoginPtyCloseResult, @@ -523,6 +525,9 @@ export interface PluginDefinition { /** Called to write delayed input to an open login pseudo-terminal, keyed by the worker session identifier. */ onLoginPtyInput?(params: PluginLoginPtyInputParams): Promise; + /** Optional fixed credential read, advertised through supported-method discovery. */ + onLoginPtyReadCredential?(params: PluginLoginPtyReadCredentialParams): Promise; + /** Called to stop an open login pseudo-terminal child, keyed by the worker session identifier. */ onLoginPtyStop?(params: PluginLoginPtyStopParams): Promise; diff --git a/packages/plugins/sdk/src/index.ts b/packages/plugins/sdk/src/index.ts index 1cf41d3241f..20e52d9e4ad 100644 --- a/packages/plugins/sdk/src/index.ts +++ b/packages/plugins/sdk/src/index.ts @@ -214,6 +214,15 @@ export type { PluginEnvironmentCancelInteractiveSetupResult, PluginEnvironmentDeleteTemplateParams, PluginEnvironmentDeleteTemplateResult, + PluginLoginCommandKey, + PluginLoginPtyOpenParams, + PluginLoginPtyOpenResult, + PluginLoginPtyInputParams, + PluginLoginPtyReadCredentialParams, + PluginLoginPtyReadCredentialResult, + PluginLoginPtyStopParams, + PluginLoginPtyCloseParams, + PluginLoginPtyCloseResult, PluginModalBoundsRequest, PluginRenderCloseEvent, PluginLauncherRenderContextSnapshot, diff --git a/packages/plugins/sdk/src/protocol.ts b/packages/plugins/sdk/src/protocol.ts index 0ad0814b2fd..ff3a43d51a8 100644 --- a/packages/plugins/sdk/src/protocol.ts +++ b/packages/plugins/sdk/src/protocol.ts @@ -646,6 +646,11 @@ export interface PluginEnvironmentRunnerIngressEndpointParams } export interface PluginEnvironmentAcquireLeaseParams extends PluginEnvironmentDriverBaseParams { + /** Omitted means ordinary execution. A login allocation targets a saved agent, + * requires requestedExpiresAt, and releases only that login, never its computer. */ + purpose?: "run" | "login"; + /** Host-resolved fixed command identity for a login allocation. */ + loginCommandKey?: PluginLoginCommandKey; runId: string; creationOperationId?: string; /** Explicit platform probes may request a provider-owned immutable snapshot @@ -1086,6 +1091,8 @@ export type PluginLoginCommandKey = "claude" | "codex" | "grok"; /** The open request for one live login pseudo-terminal. The worker registers the terminal by `hostRouteId`. */ export interface PluginLoginPtyOpenParams { + /** Independent absolute deadline, required by providers hosting login on an existing computer. */ + expiresAt?: string; /** The host-owned opaque route identifier. The worker registers the terminal by it. */ hostRouteId: string; /** The environment driver key, for the worker sandbox scope. It routes the worker; it confers no command authority. */ @@ -1117,20 +1124,42 @@ export interface PluginLoginPtyOpenResult { /** The input request. It carries the worker session identifier and the raw input bytes. */ export interface PluginLoginPtyInputParams { + /** Host-bound company context for provider callbacks during this lifecycle call. */ + companyId?: string; + /** Stable identity of this input write. Retries retain the identity and bytes. */ + inputId?: string; /** The worker session identifier that the open reply returned. */ workerSessionId: string; /** The raw input bytes to write to the terminal. */ data: string; } +/** Read the fixed Codex result of a bound login allocation; never an arbitrary path. */ +export interface PluginLoginPtyReadCredentialParams { + driverKey: string; + companyId: string; + environmentId: string; + providerLeaseId: string; + loginCommandKey: "codex"; +} + +export interface PluginLoginPtyReadCredentialResult { + kind: "codex-auth-json"; + authJson: string; +} + /** The stop request. It carries the worker session identifier. */ export interface PluginLoginPtyStopParams { + /** Host-bound company context for provider callbacks during this lifecycle call. */ + companyId?: string; /** The worker session identifier that the open reply returned. */ workerSessionId: string; } /** The close request. The host route identifier is the authoritative key. */ export interface PluginLoginPtyCloseParams { + /** Host-bound company context for provider callbacks during this lifecycle call. */ + companyId?: string; /** * The host-owned opaque route identifier. This is the authoritative close key, * so the host closes the terminal even when no worker session identifier @@ -1498,6 +1527,8 @@ export interface HostToWorkerMethods { ]; /** Write delayed input to a live login pseudo-terminal, keyed by the worker session identifier. */ loginPtyInput: [params: PluginLoginPtyInputParams, result: void]; + /** Read the fixed credential artifact after the bound login process succeeds. */ + loginPtyReadCredential: [params: PluginLoginPtyReadCredentialParams, result: PluginLoginPtyReadCredentialResult]; /** Stop a live login pseudo-terminal child, keyed by the worker session identifier. */ loginPtyStop: [params: PluginLoginPtyStopParams, result: void]; /** Close a live login pseudo-terminal by the host route identifier and return a bound acknowledgement. */ @@ -1572,6 +1603,7 @@ export const HOST_TO_WORKER_OPTIONAL_METHODS: readonly HostToWorkerMethodName[] "environmentDeleteTemplate", "loginPtyOpen", "loginPtyInput", + "loginPtyReadCredential", "loginPtyStop", "loginPtyClose", "duplexChannelOpen", diff --git a/packages/plugins/sdk/src/worker-rpc-host.ts b/packages/plugins/sdk/src/worker-rpc-host.ts index ec3f1ff2aa5..f6b801fc085 100644 --- a/packages/plugins/sdk/src/worker-rpc-host.ts +++ b/packages/plugins/sdk/src/worker-rpc-host.ts @@ -121,6 +121,7 @@ import type { PluginEnvironmentDeleteTemplateParams, PluginLoginPtyOpenParams, PluginLoginPtyInputParams, + PluginLoginPtyReadCredentialParams, PluginLoginPtyStopParams, PluginLoginPtyCloseParams, PluginDuplexChannelOpenParams, @@ -1807,6 +1808,9 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost case "loginPtyInput": return handleLoginPtyInput(params as PluginLoginPtyInputParams); + case "loginPtyReadCredential": + return handleLoginPtyReadCredential(params as PluginLoginPtyReadCredentialParams); + case "loginPtyStop": return handleLoginPtyStop(params as PluginLoginPtyStopParams); @@ -1892,6 +1896,7 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost if (plugin.definition.onEnvironmentDeleteTemplate) supportedMethods.push("environmentDeleteTemplate"); if (plugin.definition.onLoginPtyOpen) supportedMethods.push("loginPtyOpen"); if (plugin.definition.onLoginPtyInput) supportedMethods.push("loginPtyInput"); + if (plugin.definition.onLoginPtyReadCredential) supportedMethods.push("loginPtyReadCredential"); if (plugin.definition.onLoginPtyStop) supportedMethods.push("loginPtyStop"); if (plugin.definition.onLoginPtyClose) supportedMethods.push("loginPtyClose"); if (plugin.definition.onDuplexChannelOpen) supportedMethods.push("duplexChannelOpen"); @@ -2269,6 +2274,11 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost return plugin.definition.onLoginPtyInput(params); } + async function handleLoginPtyReadCredential(params: PluginLoginPtyReadCredentialParams) { + if (!plugin.definition.onLoginPtyReadCredential) throw methodNotImplemented("loginPtyReadCredential"); + return plugin.definition.onLoginPtyReadCredential(params); + } + async function handleLoginPtyStop(params: PluginLoginPtyStopParams) { if (!plugin.definition.onLoginPtyStop) { throw methodNotImplemented("loginPtyStop"); diff --git a/packages/plugins/sdk/tests/worker-rpc-host.test.ts b/packages/plugins/sdk/tests/worker-rpc-host.test.ts index 9aafcf5a26b..723020a812a 100644 --- a/packages/plugins/sdk/tests/worker-rpc-host.test.ts +++ b/packages/plugins/sdk/tests/worker-rpc-host.test.ts @@ -403,6 +403,23 @@ describe("worker configChanged cross-tenant guard", () => { return { callWorker, initialize, stop }; } + it.each([false, true])("advertises a fixed login credential read only with an explicit hook: %s", async supported => { + const params = { driverKey: "computer", companyId: "company", environmentId: "environment", providerLeaseId: "login", loginCommandKey: "codex" as const }; + const worker = makeWorker(definePlugin({ + async setup() {}, + ...(supported ? { async onLoginPtyReadCredential(input: typeof params) { + expect(input).toEqual(params); + return { kind: "codex-auth-json" as const, authJson: '{"fixture":true}' }; + } } : {}), + })); + try { + const initialized = await worker.initialize() as { supportedMethods: string[] }; + expect(initialized.supportedMethods.includes("loginPtyReadCredential")).toBe(supported); + if (supported) expect(await worker.callWorker("loginPtyReadCredential", params)).toEqual({ kind: "codex-auth-json", authJson: '{"fixture":true}' }); + else await expect(worker.callWorker("loginPtyReadCredential", params)).rejects.toMatchObject({ code: PLUGIN_RPC_ERROR_CODES.METHOD_NOT_IMPLEMENTED }); + } finally { worker.stop(); } + }); + it.each([false, true])("advertises and dispatches stop-only only with an explicit hook: %s", async supported => { let releases = 0, stops = 0; const worker = makeWorker(definePlugin({ async setup() {}, @@ -900,6 +917,7 @@ describe("worker setup-token pseudo-terminal dispatch", () => { return { workerSessionId: "ws-1" }; }, async onLoginPtyInput(params) { + expect(params.inputId).toBe("input-1"); inputs.push(params.data); }, async onLoginPtyStop() { @@ -986,7 +1004,7 @@ describe("worker setup-token pseudo-terminal dispatch", () => { // The worker streams output as a notification bound to the worker session id. emitOutput?.("prompt output"); - await callWorker("loginPtyInput", { workerSessionId: "ws-1", data: "browser-code" }); + await callWorker("loginPtyInput", { workerSessionId: "ws-1", data: "browser-code", inputId: "input-1" }); await callWorker("loginPtyStop", { workerSessionId: "ws-1" }); resolveWait?.({ exitCode: 0 }); await expect( diff --git a/server/src/__tests__/environment-runtime.test.ts b/server/src/__tests__/environment-runtime.test.ts index d2513eca283..99639d300a7 100644 --- a/server/src/__tests__/environment-runtime.test.ts +++ b/server/src/__tests__/environment-runtime.test.ts @@ -6288,11 +6288,13 @@ describeEmbeddedPostgres("environmentRuntimeService", () => { it("forwards a requested expiry to the acquire RPC and records only a provider-attested expiry", async () => { const pluginId = randomUUID(); let receivedRequestedExpiresAt: unknown; + let receivedPurpose: unknown, receivedCommand: unknown; const workerManager = { isRunning: vi.fn(() => true), call: vi.fn(async (_pluginId: string, method: string, params: Record) => { if (method === "environmentAcquireLease") { receivedRequestedExpiresAt = params.requestedExpiresAt; + receivedPurpose = params.purpose; receivedCommand = params.loginCommandKey; // The provider grants no expiry. return { providerLeaseId: "plugin-lease-no-expiry", metadata: { remoteCwd: "/workspace" } }; } @@ -6310,10 +6312,12 @@ describeEmbeddedPostgres("environmentRuntimeService", () => { heartbeatRunId: runId, persistedExecutionWorkspace: null, requestedExpiresAt, + purpose: "login", loginCommandKey: "codex", }); // The acquire RPC receives the requested expiry as an ISO 8601 string. expect(receivedRequestedExpiresAt).toBe(requestedExpiresAt.toISOString()); + expect(receivedPurpose).toBe("login"); expect(receivedCommand).toBe("codex"); // The provider gave no expiry, so the lease row records no expiry. The runtime // never synthesizes the requested deadline as evidence of provider enforcement. expect(acquired.lease.expiresAt ?? null).toBeNull(); diff --git a/server/src/__tests__/fixtures/plugin-worker-login-pty.cjs b/server/src/__tests__/fixtures/plugin-worker-login-pty.cjs index b8ffe6d0c1a..87383b2aefb 100644 --- a/server/src/__tests__/fixtures/plugin-worker-login-pty.cjs +++ b/server/src/__tests__/fixtures/plugin-worker-login-pty.cjs @@ -146,6 +146,16 @@ function scriptedOutputLines(directive, hostRouteId, workerSessionId) { // The registered terminals, keyed by the host route id. Each entry records the // bound worker session id and the close directive. const routes = new Map(); +const pendingHost = new Map(); +let nextHostCall = 0; +function probeCompanyScope(message, entry) { + const id = `scope-${++nextHostCall}`; + return new Promise((resolve, reject) => { + pendingHost.set(id, { resolve, reject }); + send({ jsonrpc: "2.0", id, method: "companies.get", params: { companyId: entry.companyId, stage: message.method }, + ...(message.paperclipInvocation ? { paperclipInvocationId: message.paperclipInvocation.id } : {}) }); + }); +} function parseDirective(raw) { try { @@ -158,12 +168,24 @@ function parseDirective(raw) { const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity }); -rl.on("line", (line) => { +rl.on("line", async (line) => { if (!line.trim()) return; const message = JSON.parse(line); + if (pendingHost.has(message.id)) { + const pending = pendingHost.get(message.id); pendingHost.delete(message.id); + if (message.error) pending.reject(new Error("Host company scope denied")); else pending.resolve(message.result); + return; + } const method = message && typeof message.method === "string" ? message.method : null; const params = message.params ?? {}; + if (["loginPtyInput", "loginPtyStop", "loginPtyClose"].includes(method)) { + const entry = method === "loginPtyClose" ? routes.get(params.hostRouteId) : [...routes.values()].find(value => value.workerSessionId === params.workerSessionId); + if (entry?.probeLifecycle) { + try { await probeCompanyScope(message, entry); } + catch { send({ jsonrpc: "2.0", id: message.id, error: { code: -32000, message: "Host company scope denied" } }); return; } + } + } if (method === "initialize") { send({ jsonrpc: "2.0", @@ -188,7 +210,9 @@ rl.on("line", (line) => { const closeMode = directive.closeMode ?? "ack"; routes.set(params.hostRouteId, { workerSessionId, + companyId: params.companyId, probeLifecycle: directive.probeLifecycle === true, closeMode, + rejectInput: directive.rejectInput === true, pendingOutput: directive.emitOnInput === true ? scriptedOutputLines(directive, params.hostRouteId, workerSessionId) : null, @@ -253,6 +277,14 @@ rl.on("line", (line) => { // test proves the input reaches the worker and the output routes back. for (const [hostRouteId, entry] of routes.entries()) { if (entry.workerSessionId === params.workerSessionId) { + if (entry.rejectInput) { + send({ jsonrpc: "2.0", id: message.id, error: { code: -32000, message: "input delivery unconfirmed" } }); + return; + } + if (typeof params.inputId !== "string" || params.inputId.length === 0) { + send({ jsonrpc: "2.0", id: message.id, error: { code: -32000, message: "input identity missing" } }); + return; + } if (entry.pendingOutput !== null) { process.stdout.write(entry.pendingOutput); entry.pendingOutput = null; diff --git a/server/src/__tests__/plugin-worker-manager.test.ts b/server/src/__tests__/plugin-worker-manager.test.ts index 5f8ee1d604c..fbc6bda25ec 100644 --- a/server/src/__tests__/plugin-worker-manager.test.ts +++ b/server/src/__tests__/plugin-worker-manager.test.ts @@ -1336,6 +1336,64 @@ describe("plugin worker manager setup-token pty route gate", () => { } }); + it("retains the opening company for scoped host calls during input, stop, and close", async () => { + const stages: string[] = []; + const handle = makeLoginPtyHandle({ hostHandlers: { "companies.get": async ( + params: { companyId: string; stage: string }, context?: { invocationScope?: { companyId?: string } }, + ) => { + if (context?.invocationScope?.companyId !== params.companyId || params.companyId !== "company-1") throw new Error("Host company scope denied"); + stages.push(params.stage); + return { id: params.companyId }; + } } }); + try { + await handle.start(); + const session = await handle.openLoginPtySession(ptyOpenInput({ probeLifecycle: true })); + session.write("browser-code"); + await vi.waitFor(() => expect(stages).toEqual(["loginPtyInput"])); + session.kill(); + await vi.waitFor(() => expect(stages).toEqual(["loginPtyInput", "loginPtyStop"])); + await session.close(); + expect(stages).toEqual(["loginPtyInput", "loginPtyStop", "loginPtyClose"]); + } finally { await handle.stop().catch(() => undefined); } + }); + + it("fails the login when input delivery is unconfirmed", async () => { + const handle = makeLoginPtyHandle(); + try { + await handle.start(); + const session = await handle.openLoginPtySession(ptyOpenInput({ rejectInput: true })); + session.write("browser-code"); + await expect(session.wait()).resolves.toEqual({ exitCode: null }); + await session.close(); + } finally { await handle.stop().catch(() => undefined); } + }); + + it("joins an in-flight close after input failure before releasing the login", async () => { + let releaseClose!: () => void; + const heldClose = new Promise(resolve => { releaseClose = resolve; }); + let closeCalls = 0; + const handle = makeLoginPtyHandle({ hostHandlers: { "companies.get": async (params: { stage: string }) => { + if (params.stage === "loginPtyClose") { closeCalls++; await heldClose; } + return { id: "company-1" }; + } } }); + try { + await handle.start(); + const session = await handle.openLoginPtySession(ptyOpenInput({ rejectInput: true, probeLifecycle: true })); + session.write("browser-code"); + await expect(session.wait()).resolves.toEqual({ exitCode: null }); + await vi.waitFor(() => expect(closeCalls).toBe(1)); + let completed = 0; + const first = session.close().then(() => { completed++; }); + const second = session.close().then(() => { completed++; }); + await new Promise(resolve => setImmediate(resolve)); + expect(completed).toBe(0); + releaseClose(); + await Promise.all([first, second]); + expect(completed).toBe(2); + expect(closeCalls).toBe(1); + } finally { releaseClose(); await handle.stop().catch(() => undefined); } + }); + it("terminalizes the route when the cumulative output passes the per-route bound", async () => { const handle = makeLoginPtyHandle({ loginPtyLimits: { maxTotalChars: 10 }, diff --git a/server/src/services/environment-runtime.ts b/server/src/services/environment-runtime.ts index 76b590c0d8f..2d5dd44d074 100644 --- a/server/src/services/environment-runtime.ts +++ b/server/src/services/environment-runtime.ts @@ -454,6 +454,8 @@ function stripSecretRefValuesFromPluginLeaseMetadata(input: { } export interface EnvironmentDriverAcquireInput { + purpose?: "run" | "login"; + loginCommandKey?: import("@paperclipai/plugin-sdk").PluginLoginCommandKey; companyId: string; environment: Environment; /** Saved environment before run-only lease retention settings. */ @@ -3364,7 +3366,7 @@ function createPluginEnvironmentDriver( driver.warmTaskVersion === 1 && !!input.issueId && !!input.agentId && !!input.heartbeatRunId && workerManager.getWorker(plugin.id)?.supportedMethods.includes("environmentResumeLease"); const lifecyclePolicy = warm ? { mode: "warm", idleTimeoutMs: parsed.config.runnerIdleTimeoutMs ?? 300_000 } : { mode: "per_turn", idleTimeoutMs: null }; - const fingerprint = createHash("sha256").update(JSON.stringify([parsed.config, input.agentId, input.runnerTaskProjectIds ?? []])).digest("hex"); + const fingerprint = createHash("sha256").update(JSON.stringify([parsed.config, input.agentId, input.runnerTaskProjectIds ?? [], ...(input.purpose ? [input.purpose, input.loginCommandKey] : [])])).digest("hex"); const candidates = warm ? await db.select().from(environmentLeases).where(and( eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.environmentId, input.environment.id), eq(environmentLeases.status, "retained"), eq(environmentLeases.issueId, input.issueId!), @@ -3405,6 +3407,7 @@ function createPluginEnvironmentDriver( config: parsed.config.driverConfig, runId: identity.runId, creationOperationId: identity.id, + ...(input.purpose ? { purpose: input.purpose, loginCommandKey: input.loginCommandKey } : {}), workspaceMode: input.executionWorkspaceMode ?? undefined, agentId: input.agentId ?? undefined, executionWorkspaceId: input.executionWorkspaceId ?? undefined, @@ -3436,8 +3439,9 @@ function createPluginEnvironmentDriver( ...(warm ? {runnerTaskProjectIds:[...input.runnerTaskProjectIds ?? []]} : {}),remoteCwd:".", ...(input.agentId ? { agentId: input.agentId } : {}), providerMetadata: providerLease.metadata ?? {}, + ...(input.purpose ? { purpose: input.purpose, loginCommandKey: input.loginCommandKey } : {}), environmentId: input.environment.id, - ...(input.adapterType === "paperclip_runner" && driver.supportsTasks === true ? { runnerTaskLease: true } : {}), + ...(input.purpose !== "login" && input.adapterType === "paperclip_runner" && driver.supportsTasks === true ? { runnerTaskLease: true } : {}), driver: input.environment.driver, executionWorkspaceMode: input.executionWorkspaceMode, pluginId: plugin.id, @@ -3845,6 +3849,8 @@ export function environmentRuntimeService( }, async acquireRunLease(input: { + purpose?: "run" | "login"; + loginCommandKey?: import("@paperclipai/plugin-sdk").PluginLoginCommandKey; companyId: string; environment: Environment; /** Saved environment before run-only lease retention settings. */ @@ -3901,6 +3907,8 @@ export function environmentRuntimeService( executionWorkspaceMode: leaseContext.executionWorkspaceMode, executionWorkspaceSettings: input.executionWorkspaceSettings ?? null, runnerTaskProjectIds: input.runnerTaskProjectIds, + purpose: input.purpose, + loginCommandKey: input.loginCommandKey, adapterType: input.adapterType ?? null, resolveSnapshotIdentity: input.resolveSnapshotIdentity, applyCustomImageTemplate: input.applyCustomImageTemplate ?? false, diff --git a/server/src/services/plugin-worker-manager.ts b/server/src/services/plugin-worker-manager.ts index 723eb327485..38ed65d8a53 100644 --- a/server/src/services/plugin-worker-manager.ts +++ b/server/src/services/plugin-worker-manager.ts @@ -590,6 +590,7 @@ export type ExecuteLogSink = ( * carries no command string, so a caller cannot select the command. */ export interface LoginPtyOpenInput { + expiresAt?: string; /** The environment driver key. It routes the worker; it confers no command authority. */ driverKey: string; companyId: string; @@ -1564,7 +1565,9 @@ export function createPluginWorkerHandle( type LoginPtyPreBindRecord = LoginPtyPreBindOutputRecord | LoginPtyPreBindExitRecord; interface LoginPtyRoute { + companyId: string; hostRouteId: string; + closePromise: Promise | null; state: LoginPtyRouteState; workerSessionId: string | null; listener: ((chunk: string) => void) | null; @@ -1626,11 +1629,11 @@ export function createPluginWorkerHandle( // that carries the exact host route identifier. An absent, malformed, // mismatched, or timed-out acknowledgement returns false, so the caller fails // closed. - async function closeLoginPtyTerminal(hostRouteId: string): Promise { + async function closeLoginPtyTerminal(hostRouteId: string, companyId: string): Promise { try { const ack = await callInternal( "loginPtyClose", - { hostRouteId }, + { hostRouteId, companyId }, loginPtyCloseTimeoutMs, ); return isRecord(ack) && readNonEmptyString(ack.hostRouteId) === hostRouteId; @@ -1647,6 +1650,9 @@ export function createPluginWorkerHandle( // every other route this worker still holds settles through the worker-exit // path that follows. async function terminalizeLoginPtyRoute(route: LoginPtyRoute): Promise { + // A notification may already have started close. Every later disposer must + // join that acknowledgement before its owner can release the allocation. + if (route.closePromise) return route.closePromise; if (route.terminalized) return; route.terminalized = true; route.state = "closed"; @@ -1660,20 +1666,22 @@ export function createPluginWorkerHandle( loginPtyRoutesByWorkerSessionId.delete(route.workerSessionId); } releaseLoginPtyRouteSlot(route); - // A terminalized route reports a null exit code, which the runner treats as a - // failure. + route.closePromise = (async () => { + const confirmed = await closeLoginPtyTerminal(route.hostRouteId, route.companyId); + if (!confirmed) { + // The worker did not acknowledge the close, so the host cannot prove the + // terminal is gone. Retire the worker before any reuse. + log.error( + { pluginId }, + "login pseudo-terminal close not acknowledged; retiring worker", + ); + retireWorkerProcess(); + } + })(); + // Report failure promptly, but retain the shared close barrier so the + // runner's following dispose waits for confirmed stop (or worker retirement). settleRouteWait(route, { exitCode: null }); - const confirmed = await closeLoginPtyTerminal(route.hostRouteId); - if (!confirmed) { - // The worker did not acknowledge the close, so the host cannot prove the - // terminal is gone. Fail closed: retire the worker before any reuse. This - // also settles and clears every other route the worker still holds. - log.error( - { pluginId }, - "login pseudo-terminal close not acknowledged; retiring worker", - ); - retireWorkerProcess(); - } + return route.closePromise; } // Resolve one login pseudo-terminal notification to its route. Return null @@ -1920,7 +1928,9 @@ export function createPluginWorkerHandle( settleWait = resolve; }); const route: LoginPtyRoute = { + companyId: input.companyId, hostRouteId, + closePromise: null, state: "reserved", workerSessionId: null, listener: null, @@ -1957,6 +1967,7 @@ export function createPluginWorkerHandle( providerLeaseId: input.providerLeaseId, loginCommandKey: input.loginCommandKey, sessionHome: input.sessionHome, + ...(input.expiresAt ? { expiresAt: input.expiresAt } : {}), }, loginPtyOpenTimeoutMs, ); @@ -2001,9 +2012,9 @@ export function createPluginWorkerHandle( if (route.state !== "open" || !sid) return; void callInternal( "loginPtyInput", - { workerSessionId: sid, data }, + { companyId: route.companyId, workerSessionId: sid, data, inputId: randomUUID() }, loginPtyOpenTimeoutMs, - ).catch(() => {}); + ).catch(() => terminalizeLoginPtyRoute(route)); }, wait(): Promise<{ exitCode: number | null }> { return waitPromise; @@ -2013,7 +2024,7 @@ export function createPluginWorkerHandle( if (!sid) return; void callInternal( "loginPtyStop", - { workerSessionId: sid }, + { companyId: route.companyId, workerSessionId: sid }, loginPtyOpenTimeoutMs, ).catch(() => {}); }, From 3040448da554922fd454e0d36e2934069ac02f4e Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 9 Nov 2026 19:16:34 -0600 Subject: [PATCH 03/10] fix(workspaces): refresh saved cohort source proofs on resume (#20429) ## Thinking Path > - Paperclip preserves agent work when a control-plane server is replaced. > - Online workspace imports save exact cohort, operation and snapshot identities for restart. > - A cohort proof also includes the complete current companion source scope. > - An independent companion import removes that companion from the local scope. > - The saved cohort then fails resume even when every saved member is unchanged. > - This pull request rechecks the current scope under fresh locks and refreshes its proof for all members in one transaction. > - The benefit is restartable online migration while independent work progresses. ## Linked Issues or Issue Description Refs: #19873, #20394, #20418. Related PR search found the original cohort owner, recovery-proof refresh and separate child-verification reuse. This fix addresses cohort scope freshness. **What happened?** An interrupted cohort rejects resume with `workspace_cohort_membership_changed` after a nonmember companion is migrated. The saved source proof includes companion workspace and task IDs. The exact saved members and their fingerprints can remain unchanged. **Expected behavior** The same saved cohort must resume after fresh admission. It must keep all member, operation and snapshot IDs. Changed members, active owners, changed journals and lost source locks must still refuse publication. **Steps to reproduce** 1. Start a two-member cohort and interrupt the second upload after the first archive is saved. 2. Import an archived nonmember companion through the existing canonical migration owner. 3. Resume the same two-member cohort. The original implementation refuses before it acquires the source fence. **Paperclip version or commit** Reproduced on master `3a5572c9e5`. **Deployment mode** Online administrative workspace migration with PostgreSQL and authenticated snapshot storage. ## What Changed - Admit a changed aggregate scope proof only when every saved member has a running journal and its current fingerprint matches both saved fingerprints. - Keep partial reservations on the original strict aggregate-proof path. Keep exact cohort and operation membership checks. - Run the existing source, lifecycle, recovery and finalizer admission before refresh. Lock member rows, inspect the current scope again, and compare every journal in one transaction. - Change only `cohortMigration.sourceProof`. Preserve all other metadata, identities, archive and recovery records. Abort the complete refresh on cancellation, a changed journal or a lost fence. - Extend the existing real PostgreSQL fixture with partial upload, canonical companion migration, refusal controls, transaction rollback, cold archive restore and replay. - Document the proof lifetime and resume boundary. ## Verification - Canonical Node24 worktree preflight passed. Plugin SDK build prerequisites passed. - Genuine RED on unchanged product: the real partial-upload and companion-import sequence fails with `workspace_cohort_membership_changed` (1 failed; 22 intentionally not selected; 10.44 seconds). - The identical positive passes after the fix (1 passed; 22 intentionally not selected; 9.87 seconds). - The complete focused cohort file passes: 23 tests in 33.33 seconds. Existing controls include changed member fingerprints, foreign and completed journals, active operations, peer cancellation, actual source-fence connection loss and outer-commit failure. - The new sequence also checks a held source lock, a held finalizer lock, cancellation before refresh, and an injected second-member update failure. The failed update rolls back every proof change. Both saved archives restore tracked and untracked work, and replay uses the same cohort. - After one final read-only preflight assertion, that complete new sequence passes again in 14.52 seconds with 22 existing cases intentionally not selected. Server TypeScript passes on the final files. Module boundaries and `git diff --check` pass. - Commands: `pnpm exec vitest run server/src/services/remote-workspace-cohort-migration.test.ts`; final case selection: `-t 'same uploaded cohort'`; `pnpm --filter @paperclipai/server exec tsc --noEmit`; `node scripts/check-module-boundaries.mjs`. - Initial local setup attempts remain nonpasses: sandbox PostgreSQL could not bind localhost, then the new archived companion fixture used a noncanonical repository folder. The corrected fixture uses the existing managed repository path. Neither setup failure is counted as the product RED. - Fresh [Greptile review](https://github.com/paperclipai/paperclip/pull/20429#issuecomment-6755862789) is 5/5 on exact head `6c640c4667b136e5416c1375f491729cf4bb9b49`, with zero inline threads. Required final-head CI is running. Hosted acceptance is not claimed by this PR. ## Risks - The old aggregate proof contains only a hash. Refresh therefore requires durable fingerprints for every saved member and repeats all current admission guards. A partially reserved cohort cannot use this path. - A stale proof must never hide a changed member or a new writer. Current source inspection, P/I/L/F locks, locked member rows, complete journal compare-and-swap and the existing capture and publication checks remain authoritative. - The all-member update must stay atomic. A database fault or cancellation rolls it back. The original cohort, operation and snapshot IDs remain fixed. - The change adds one bounded transaction only when a fully saved cohort's scope proof changes. It adds no recurring work, schema, provider, archive format, concurrency or deployment changes. ## Model Used OpenAI Codex, GPT-6 family, with repository tools and code execution. The runtime does not expose a more specific deployment identifier or context-window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes: #` / `Refs: #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip --- doc/DATABASE.md | 12 +++ .../remote-workspace-cohort-migration.test.ts | 90 ++++++++++++++++++- .../services/remote-workspace-migration.ts | 44 ++++++++- 3 files changed, 140 insertions(+), 6 deletions(-) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 8a0d3a50750..9b491cdf608 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -145,6 +145,18 @@ Receipt validation adds bounded per-scope database reads to startup eligibility. It does not add a recurring scan or network work. Qualification must measure the selected cohort's startup latency on the serving revision before enrollment. +### Workspace cohort admission proofs + +A saved cohort keeps its exact members, operations and snapshots on resume. +Independent companion imports can change the current source-scope proof without +changing those members. When every member has a running journal and its current +fingerprint matches both saved fingerprints, the importer can reprove the current +scope under fresh source, lifecycle and finalizer locks. After current source and +recovery checks, one transaction compares every journal and refreshes only the +cohort proof for all members. Cancellation or a changed journal rolls back the +whole refresh. Partial reservations still require the original aggregate proof. +Archives, recovery obligations and publication checks retain their existing owners. + ### Original local Git sources for archived workspaces When an archived runtime branch has an exact successful deletion receipt, its diff --git a/server/src/services/remote-workspace-cohort-migration.test.ts b/server/src/services/remote-workspace-cohort-migration.test.ts index 21cb2de46ba..92c353d2eee 100644 --- a/server/src/services/remote-workspace-cohort-migration.test.ts +++ b/server/src/services/remote-workspace-cohort-migration.test.ts @@ -6,7 +6,7 @@ import path from "node:path"; import { promisify } from "node:util"; import { eq, inArray, sql } from "drizzle-orm"; import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; -import { activityLog, agents, companies, createDb, environmentLeases, environments, heartbeatRuns, nativeRunFinalizations, executionWorkspaceSnapshots, executionWorkspaces, issues, projects, workspaceOperations, type Db } from "@paperclipai/db"; +import { activityLog, agents, companies, createDb, environmentLeases, environments, heartbeatRuns, nativeRunFinalizations, executionWorkspaceSnapshots, executionWorkspaces, issues, projects, projectWorkspaces, workspaceOperations, type Db } from "@paperclipai/db"; import { readRemoteWorkspaceAuthority } from "@paperclipai/shared"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; import { resolveManagedProjectWorkspaceDir } from "../home-paths.js"; @@ -46,11 +46,11 @@ describe.skipIf(!support.supported)("bounded workspace cohort migration", () => await db.execute(sql`drop trigger if exists cohort_commit_fault on workspace_operations`); await db.execute(sql`drop function if exists cohort_commit_fault()`); await db.execute(sql`drop trigger if exists cohort_reserve_fault on workspace_operations`); await db.execute(sql`drop function if exists cohort_reserve_fault()`); await db.delete(nativeRunFinalizations); await db.delete(environmentLeases); await db.delete(environments); await db.delete(heartbeatRuns); - await db.delete(issues); await db.delete(agents); await db.delete(executionWorkspaces); await db.delete(projects); await db.delete(companies); + await db.delete(issues); await db.delete(agents); await db.delete(executionWorkspaces); await db.delete(projectWorkspaces); await db.delete(projects); await db.delete(companies); vi.unstubAllEnvs(); await fs.rm(home, { recursive: true, force: true }); }); - async function fixture() { - const companyId = randomUUID(), projectId = randomUUID(), root = resolveManagedProjectWorkspaceDir({ companyId, projectId }); + async function fixture(repoName?: string) { + const companyId = randomUUID(), projectId = randomUUID(), root = resolveManagedProjectWorkspaceDir({ companyId, projectId, repoName }); await db.insert(companies).values({ id: companyId, name: "Cohort", issuePrefix: `C${companyId.slice(0, 6)}` }); await db.insert(projects).values({ id: projectId, companyId, name: "Shared Git" }); await fs.mkdir(root, { recursive: true }); await fs.writeFile(path.join(root, "saved.txt"), "committed base\n"); @@ -200,6 +200,88 @@ describe.skipIf(!support.supported)("bounded workspace cohort migration", () => await assertLocal(f); expect(await db.select().from(workspaceOperations)).toHaveLength(mode === "foreign" ? 3 : 2); }); + it("resumes the same uploaded cohort after an archived companion is independently migrated", async () => { + const f = await fixture("cohort"), held = await recoverable(f), cwd = path.join(f.root, ".paperclip", "worktrees", "retired"), closedAt = new Date(); + await git(f.root, "worktree", "add", "-qb", "retired", cwd); + await git(f.root, "worktree", "remove", cwd); + const receipt = await git(f.root, "branch", "-d", "retired"); + const [projectWorkspace] = await db.insert(projectWorkspaces).values({ companyId: f.companyId, projectId: f.projectId, + name: "Original repository", cwd: f.root, repoUrl: f.parent.repoUrl }).returning(); + const [issue] = await db.insert(issues).values({ companyId: f.companyId, projectId: f.projectId, title: "Retired companion" }).returning(); + const [companion] = await db.insert(executionWorkspaces).values({ companyId: f.companyId, projectId: f.projectId, + projectWorkspaceId: projectWorkspace.id, sourceIssueId: issue.id, name: "retired", mode: "isolated_workspace", + strategyType: "git_worktree", providerType: "git_worktree", cwd, providerRef: cwd, repoUrl: f.parent.repoUrl, + branchName: "retired", status: "archived", closedAt, metadata: { createdByRuntime: true, gitBranchOwnershipVersion: 1 } }).returning(); + await db.insert(workspaceOperations).values({ companyId: f.companyId, executionWorkspaceId: companion.id, + phase: "worktree_cleanup", status: "succeeded", command: "git branch -d retired", stdoutExcerpt: receipt, + startedAt: new Date(), finishedAt: new Date() }); + const put = storage.putFile.bind(storage); let uploads = 0; + const upload = vi.spyOn(storage, "putFile").mockImplementation(async input => { + if (++uploads === 2) throw new Error("interrupted_cohort_upload"); + return put(input); + }); + await expect(run(f, { concurrency: 1 })).rejects.toThrow("interrupted_cohort_upload"); + upload.mockRestore(); + const saved = (await db.select().from(workspaceOperations)).filter(row => row.phase === "remote_workspace_migration"); + expect(saved).toHaveLength(2); + const cohort = saved[0].metadata!.cohortMigration as { id: string; sourceProof: string; members: unknown[] }; + const snapshots = await db.select().from(executionWorkspaceSnapshots); + expect(snapshots.some(row => row.status === "uploaded")).toBe(true); + await migrateRemoteWorkspace({ db, storage, companyId: f.companyId, workspaceId: companion.id, apply: true, + signal: AbortSignal.timeout(50_000) }); + const noStorage = new Proxy(storage, { get() { throw new Error("unexpected_storage_operation"); } }); + await db.transaction(async tx => { + await expect(run(f, { db: tx as unknown as Db, storage: noStorage, apply: false })) + .resolves.toMatchObject({ applied: false, eligible: true, cohortId: cohort.id }); + }, { accessMode: "read only" }); + const other = createDb(database.connectionString, { maxConnections: 1 }); + try { + await withWorkspaceSourceLocks(other, { companyId: f.companyId, projectIds: [f.projectId] }, async () => { + await expect(run(f, { storage: noStorage })).rejects.toThrow("workspace_source_busy"); + }, true); + await other.transaction(async tx => { + expect(await tryLockNativeWorkspaceFinalization(tx as unknown as Db, { companyId: f.companyId, runId: held.runId })).toBe(true); + await expect(run(f, { storage: noStorage })).rejects.toThrow("remote_copyback_owned"); + }); + } finally { await other.$client.end({ timeout: 1 }); } + const inspect = onlineWorkspaceSource.inspectOnlineWorkspaceSource, cancelled = new AbortController(), calls = new Map(); + const probe = vi.spyOn(onlineWorkspaceSource, "inspectOnlineWorkspaceSource").mockImplementation(async (...args) => { + const result = await inspect(...args), count = (calls.get(args[1].id) ?? 0) + 1; calls.set(args[1].id, count); + if (count === 5) cancelled.abort(new Error("cancel_cohort_proof_refresh")); + return result; + }); + await expect(run(f, { storage: noStorage, signal: cancelled.signal })).rejects.toThrow("cancel_cohort_proof_refresh"); + probe.mockRestore(); + const last = [...saved].sort((a, b) => a.executionWorkspaceId!.localeCompare(b.executionWorkspaceId!)).at(-1)!; + await db.execute(sql.raw(`create function cohort_reserve_fault() returns trigger language plpgsql as $$ begin if new.id='${last.id}'::uuid then raise exception 'cohort_proof_refresh_fault'; end if; return new; end $$`)); + await db.execute(sql`create trigger cohort_reserve_fault before update on workspace_operations for each row execute function cohort_reserve_fault()`); + await expect(run(f, { storage: noStorage })).rejects.toThrow(); + await db.execute(sql`drop trigger cohort_reserve_fault on workspace_operations`); + await db.execute(sql`drop function cohort_reserve_fault()`); + expect((await db.select().from(workspaceOperations)).filter(row => saved.some(old => old.id === row.id))).toEqual(saved); + await assertLocal(f); + await expect(run(f)).resolves.toMatchObject({ applied: true, cohortId: cohort.id }); + const current = (await db.select().from(workspaceOperations)).filter(row => saved.some(old => old.id === row.id)); + expect(current).toHaveLength(2); + for (const operation of current) { + const refreshed = operation.metadata!.cohortMigration as typeof cohort; + expect(refreshed).toMatchObject({ id: cohort.id, members: cohort.members }); + expect(refreshed.sourceProof).not.toBe(cohort.sourceProof); + expect(operation.status).toBe("succeeded"); + } + expect((await db.select().from(executionWorkspaceSnapshots)).filter(row => snapshots.some(old => old.id === row.id))).toHaveLength(snapshots.length); + await expect(run(f)).resolves.toMatchObject({ applied: true, replayed: true, cohortId: cohort.id }); + for (const workspace of f.leaves) { + const [row] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, workspace.id)); + const ref = (await getWorkspaceSnapshot(db, { companyId: f.companyId, workspaceId: row.id, + snapshotId: readRemoteWorkspaceAuthority(row.metadata)!.snapshotId! }))!; + const archivePath = path.join(home, `${workspace.name}-resumed.pcws`), targetDir = path.join(home, `${workspace.name}-resumed`); + await loadWorkspaceSnapshotArchive({ storage, reference: ref, targetPath: archivePath }); + await restoreRemoteWorkspaceArchive({ archivePath, targetDir, expectedManifestDigest: ref.manifestDigest }); + expect(await fs.readFile(path.join(targetDir, "saved.txt"), "utf8")).toBe(`${workspace.name} dirty tracked work\n`); + expect(await fs.readFile(path.join(targetDir, "untracked.txt"), "utf8")).toBe(`${workspace.name} untracked work\n`); + } + }, 60_000); it("resumes the exact membership after reservation stops halfway", async () => { const f = await fixture(), second = [...f.leaves].sort((a, b) => a.id.localeCompare(b.id))[1]; await db.execute(sql.raw(`create function cohort_reserve_fault() returns trigger language plpgsql as $$ begin if new.execution_workspace_id='${second.id}'::uuid then raise exception 'cohort_reservation_fault'; end if; return new; end $$`)); diff --git a/server/src/services/remote-workspace-migration.ts b/server/src/services/remote-workspace-migration.ts index 0e657293ff7..6ccbfebd609 100644 --- a/server/src/services/remote-workspace-migration.ts +++ b/server/src/services/remote-workspace-migration.ts @@ -741,6 +741,7 @@ export async function migrateRemoteWorkspaceCohort(input: { const sourceProof = createHash("sha256").update(canonical({ scope: scopeIdentity(members[0].onlineSource), members: initial.map(workspace => ({ workspaceId: workspace.id, fingerprint: fingerprint(workspace) })) })).digest("hex"); const pending = []; + let unchangedMembers = true; for (const workspace of initial) { const marker = object(workspace.metadata?.remoteWorkspaceMigration); if (marker.schema !== SCHEMA || typeof marker.operationId !== "string") continue; @@ -749,11 +750,14 @@ export async function migrateRemoteWorkspaceCohort(input: { eq(workspaceOperations.id, marker.operationId), eq(workspaceOperations.phase, "remote_workspace_migration"))); if (!operation?.metadata?.cohortMigration) throw new Error("workspace_cohort_foreign_journal"); if (operation.status !== "running" || operation.finishedAt !== null) throw new Error("workspace_cohort_journal_changed"); + unchangedMembers &&= marker.sourceFingerprint === fingerprint(workspace) + && operation.metadata.sourceFingerprint === marker.sourceFingerprint; pending.push(cohortSchema.parse(operation.metadata.cohortMigration)); } - const cohort: WorkspaceMigrationCohort = pending[0] ?? { schema: "paperclip.remote-workspace-cohort.v1", id: randomUUID(), companyId, + let cohort: WorkspaceMigrationCohort = pending[0] ?? { schema: "paperclip.remote-workspace-cohort.v1", id: randomUUID(), companyId, sourceProof, members: workspaceIds.map(workspaceId => ({ workspaceId, operationId: randomUUID() })) }; - if (cohort.companyId !== companyId || cohort.sourceProof !== sourceProof + const refreshSourceProof = cohort.sourceProof !== sourceProof; + if (cohort.companyId !== companyId || refreshSourceProof && (pending.length !== workspaceIds.length || !unchangedMembers) || canonical(cohort.members.map(member => member.workspaceId)) !== canonical(workspaceIds) || new Set(cohort.members.map(member => member.operationId)).size !== workspaceIds.length || pending.some(marker => canonical(marker) !== canonical(cohort))) throw new Error("workspace_cohort_membership_changed"); @@ -785,6 +789,42 @@ export async function migrateRemoteWorkspaceCohort(input: { return reservation.value; }); await lockMigrationRecovery(lock, plans, cohort); + if (refreshSourceProof) { + const refreshedCohort = { ...cohort, sourceProof }; + const operations = await input.db.transaction(async tx => { + await lockMigrationParents(tx, companyId, null, plans.flatMap(plan => [plan.reserved.workspace.sourceIssueId!, + ...plan.reserved.legacyRecoverySources.map(source => source.issueId), + ...plan.onlineSource!.companions.flatMap(proof => proof.sources.map(source => source.issueId))])); + const locked = await tx.select().from(executionWorkspaces).where(and(eq(executionWorkspaces.companyId, companyId), + inArray(executionWorkspaces.id, workspaceIds))).orderBy(executionWorkspaces.id).for("update"); + if (locked.length !== plans.length || plans.some(plan => { + const workspace = locked.find(row => row.id === plan.input.workspaceId)!; + return fingerprint(workspace) !== plan.reserved.sourceFingerprint + || canonical(workspace.metadata?.remoteWorkspaceMigration) !== canonical(plan.reserved.workspace.metadata?.remoteWorkspaceMigration); + })) throw new Error("workspace_cohort_source_changed"); + await preflight(tx); + const updated = []; + for (const plan of plans) { + signal.throwIfAborted(); + const operation = plan.reserved.operation!; + const [current] = await tx.update(workspaceOperations).set({ metadata: { ...operation.metadata, + cohortMigration: refreshedCohort }, updatedAt: new Date() }).where(and( + eq(workspaceOperations.companyId, companyId), eq(workspaceOperations.executionWorkspaceId, plan.input.workspaceId), + eq(workspaceOperations.id, operation.id), eq(workspaceOperations.phase, "remote_workspace_migration"), + eq(workspaceOperations.status, "running"), sql`${workspaceOperations.finishedAt} is null`, + sql`${workspaceOperations.issueId} is not distinct from ${operation.issueId}::uuid`, + sql`${workspaceOperations.cwd} is not distinct from ${operation.cwd}`, + eq(workspaceOperations.metadata, operation.metadata!))).returning(); + if (!current) throw new Error("workspace_cohort_journal_changed"); + updated.push(current); + } + await lock.execute(sql`select 1`); + signal.throwIfAborted(); + return updated; + }); + for (const [index, plan] of plans.entries()) plan.reserved.operation = operations[index]; + cohort = refreshedCohort; + } const captures: Array = Array(plans.length); const childVerifier = createMigrationChildVerifier(plans[0].input, plans[0].onlineSource, lock); let next = 0, failure: unknown; From 915edcff49bb2cbacfbaee604b41e082e0397109 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 9 Nov 2026 19:23:31 -0600 Subject: [PATCH 04/10] fix(workspaces): preserve archived native recovery during migration (#20424) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Durable workspace migration must retain saved files and pending recovery work. > - An archived Git workspace can have an authenticated restore recipe and a terminal native run with pending remote files. > - Its task can select a different workspace. Reopening the archived workspace would change that task. > - The current migration owner refuses this source because it has no live local directory. > - This pull request uses the existing online recovery preservation owner for this exact archived recipe case. > - Migration retains the old task, provider allocation, recovery action, and native sync reference. ## Linked Issues or Issue Description Refs #20298, #20394, and #20418. Related cleanup work in #19812 does not cover this migration case. **What happened?** A historical archived Git workspace with a saved restore recipe and a terminal prepared native sync reference cannot migrate online. Admission reports `remote_copyback_unresolved` and `workspace_recovery_unresolved`. The old task can already select another workspace, so reopening it is not a safe migration path. **Expected behavior** Authenticate the archived files into private scratch. Preserve all typed native and provider recovery obligations in the existing migration journal and markers. Keep the original task selection, history, archive state, and restore flags unchanged. **Steps to reproduce** 1. Archive a Git worktree with staged, unstaged, and untracked files in a saved recipe. 2. Retain a terminal failed native run, its prepared sync reference, and its matching remote allocation and recovery action. 3. Remove the old local worktree and select a different workspace on the task. 4. Call `migrateRemoteWorkspace` without `writersStopped`. **Paperclip version or commit** Reproduced on `b2a7d322ed0bafda04a0b78ce14e4f25c8d5d170`. **Deployment mode** Self-hosted server with PostgreSQL and configured object storage. ## What Changed - Permit the existing online recovery owner to inspect recipe-backed archived Git sources. - Acquire the existing native finalization locks for those sources. Reinspect their exact proofs after lock acquisition and before publication. - Lock related source-task ancestry before publication. - Reuse the existing private Git restore, authenticated archive, journal, marker, and recovery-source contracts. Add no schema or provider calls. - Leave active sources and archived sources without a valid recipe on their existing refusal paths. - Include the shared UI correction from #20418. A nullable draft override follows fresh task data when the user has no local choice. Explicit choices increment a generation. Normal and recovered successful sends clear only their own choice; failed sends and newer choices remain intact. ## Verification - Unchanged master RED: the new historical-source fixture fails with `remote_workspace_migration_blocked:remote_copyback_unresolved,workspace_recovery_unresolved`. - Five focused real PostgreSQL, filesystem, Git, and encrypted-storage tests pass on Node 24.22.2. The success case loses an upload reply, resumes the same operation and snapshot, restores the staged/unstaged/untracked bytes, and verifies unchanged task history, lease, recovery action, finalizer, and recipe flags. - Recipe, prepared reference, and provider allocation changes during the actual upload each refuse publication. A competing native finalization owner refuses before capture. - Migration command: `pnpm exec vitest run server/src/services/remote-workspace-migration.test.ts -t 'unselected archived recipe|archived prepared source|competing native F owner'`. - All server typecheck layers, module boundary checks, and whitespace checks pass for the migration revision. The migration source bytes remain unchanged through the shared UI follow-ups. - Initial CI run 42727051535 exposed an existing planning-mode browser failure: shard 3/8 passed 33 cases but the refreshed task mode did not appear. The same issue occurred twice on #20418. A real local regression proved that initial cached data could leave the composer in its old mode. This path does not invoke migration. - Review then exposed genuine defects in the initial shared UI repair: an optimistic save rollback could reset a failed draft, and an earlier send could replace a newer draft choice. Recovered delivery also left a consumed choice pinned. All three have real RED→GREEN controls. The final shared fix uses an explicit nullable override, a choice generation, and one attempt-bound settlement owner for normal and recovered success, with no value-equality inference or durable payload changes. - Exact shared UI source now passes all 145 composer tests (2.88s), the original desktop/mobile planning browser case (15.5s; assertions and timeouts unchanged), token gates, and the canonical UI typecheck. The test harness uses the full persisted `IssueWorkMode` type, including `skill_test`, to fix the observed CI typing failure. - These UI results are reused from the identical shared source in #20418 through `ba1f85f18085dd0e84c594ed0cb68d5bf817c93c`. The unchanged planning browser pass is on the explicit-state model before the later settlement-helper extraction. The final receipt/resend controls, full composer suite, typecheck, and token gates include that extraction. They do not claim a local browser run on this entire combined branch. Fresh required CI and review qualify this PR head. - Previous-release state: existing recipe, v3 prepared reference, and journal shapes carry forward unchanged. A saved partial operation resumes with the same IDs. Migration does not certify remote file recovery or provider termination. Live provider recovery and hosted migration remain separate acceptance steps. ## Risks The change admits one more source class into an existing preservation path. An incorrect proof could publish incomplete file authority. The canonical recipe validation, full authenticated restore, native finalization locks, source reinspection, and publication checks remain mandatory. Pending remote data stays pending and retains its original allocation and reference. The shared UI repair updates only an unchanged draft mode; its regression checks preserve a local user choice. ## Model Used OpenAI Codex, GPT-6, with reasoning, repository tools, and code execution. The runtime does not expose a deployment suffix or context-window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- .../remote-workspace-migration.test.ts | 130 +++++++++++++++- .../services/remote-workspace-migration.ts | 14 +- .../task-chat/TaskChatComposer.test.tsx | 144 +++++++++++++++++- .../components/task-chat/TaskChatComposer.tsx | 24 ++- 4 files changed, 295 insertions(+), 17 deletions(-) diff --git a/server/src/services/remote-workspace-migration.test.ts b/server/src/services/remote-workspace-migration.test.ts index 32dd4fa4d6b..c31fad595eb 100644 --- a/server/src/services/remote-workspace-migration.test.ts +++ b/server/src/services/remote-workspace-migration.test.ts @@ -8,7 +8,7 @@ import { createServer, type Server } from "node:http"; import { pathToFileURL } from "node:url"; import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { and, eq, sql } from "drizzle-orm"; -import { activityLog, agents, environmentLeases, heartbeatRuns, nativeRunFinalizations, nativeRunResults, completionContracts, applyPendingMigrations, closeRegisteredClients, companies, createDb, executionWorkspaceSnapshots, +import { activityLog, agents, environments, environmentLeases, heartbeatRuns, nativeRunFinalizations, nativeRunResults, completionContracts, applyPendingMigrations, closeRegisteredClients, companies, createDb, executionWorkspaceSnapshots, executionWorkspaceRepositories, executionWorkspaceRuntimeLeases, executionWorkspaces, issueRecoveryActions, issues, projects, projectWorkspaces, workspaceOperations, workspaceRuntimeServices } from "@paperclipai/db"; import { readRemoteWorkspaceAuthority } from "@paperclipai/shared"; import { createLocalDiskStorageProvider } from "../storage/local-disk-provider.js"; @@ -37,6 +37,9 @@ import { isolatedRemoteSourcePath } from "./isolated-remote-workspace-source.js" import { verifiedGitCacheSource } from "./git-workspace-restoration.js"; import { withIndependentWorkspaceSourceLocks, withWorkspaceSourceLocks } from "./workspace-source-lock.js"; import { inspectOnlineWorkspaceSource } from "./online-workspace-source.js"; +import { tryLockNativeWorkspaceFinalization } from "./native-runtime/native-workspace-finalization-ownership.js"; +import { readMigratedLegacyWorkspaceSource } from "./legacy-workspace-recovery-migration.js"; +import { nativeSha256 } from "./native-runtime/canonical.js"; const execute = promisify(execFile); const git = async (cwd: string, ...args: string[]) => (await execute("git", ["-C", cwd, ...args], { env: { ...process.env, @@ -61,6 +64,7 @@ describe.skipIf(!support.supported)("remote workspace migration", () => { await Promise.all(servers.splice(0).map(server => new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())))); vi.unstubAllEnvs(); await db.delete(activityLog); await db.delete(workspaceOperations); await db.delete(executionWorkspaceSnapshots); await db.delete(workspaceRuntimeServices); await db.delete(executionWorkspaceRuntimeLeases); + await db.delete(environmentLeases); await db.delete(environments); await db.delete(nativeRunFinalizations); await db.delete(nativeRunResults); await db.delete(heartbeatRuns); await db.delete(completionContracts); await db.delete(issues); await db.delete(agents); await db.delete(executionWorkspaces); await db.delete(projectWorkspaces); await db.delete(projects); await db.delete(companies); await fs.rm(root, { recursive: true, force: true }); @@ -378,12 +382,12 @@ describe.skipIf(!support.supported)("remote workspace migration", () => { await restoreRemoteWorkspaceArchive({ archivePath, targetDir, expectedManifestDigest: reference!.manifestDigest }); expect(await fs.readFile(path.join(targetDir, ".paperclip/worktrees/child/child.txt"), "utf8")).toBe("saved child edits\n"); }); - async function failedCopybackFixture() { - const f = await seed(), runId = randomUUID(); + async function failedCopybackFixture(existing?: Awaited>) { + const f = existing ?? await seed(), runId = randomUUID(); const [agent] = await db.insert(agents).values({ companyId: f.companyId, name: "Historical agent", adapterType: "paperclip_runner" }).returning(); const reference = { schema: "paperclip.native-workspace-sync/v3", state: "prepared", workspaceId: f.workspaceId, leaseId: randomUUID(), providerLeaseId: randomUUID(), remoteCwd: "/workspaces/task", - descriptorSha256: "12".repeat(32), baselineSha256: "34".repeat(32), finalHostSha256: null, resourceDisposition: "stop_and_retain" }; + descriptorSha256: "12".repeat(32), baselineSha256: "34".repeat(32), finalHostSha256: null, resourceDisposition: "stop_and_retain" } as const; await db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: agent!.id, nativeIssueId: f.issueId, runtimeMode: "native", status: "failed", finishedAt: new Date(), runnerProfileJson: { nativeWorkspaceSync: reference } }); await db.insert(nativeRunFinalizations).values({ companyId: f.companyId, issueId: f.issueId, runId, phase: "terminal_failure" }); @@ -633,6 +637,122 @@ describe.skipIf(!support.supported)("remote workspace migration", () => { branchName, strategyType: "git_worktree", providerType: "git_worktree", metadata: { createdByRuntime: true, gitBranchOwnershipVersion: 1 } }).where(eq(executionWorkspaces.id, f.workspaceId)); return { ...f, cwd, base, upstream, commit, projectId, projectWorkspaceId, repoUrl, branchName }; } + async function archivedPreparedFixture() { + const base = await gitArchiveFixture(), f = { ...base, ...await failedCopybackFixture(base) }; + await fs.writeFile(path.join(f.cwd, "saved.txt"), "archived staged edit\n"); await git(f.cwd, "add", "saved.txt"); + await fs.writeFile(path.join(f.cwd, "saved.txt"), "archived unstaged edit\n"); + await fs.writeFile(path.join(f.cwd, "untracked.txt"), "archived private file\n"); + const captured = (await captureRestorePoint({ cwd: f.cwd, upstreamCommits: [f.upstream] }))!; + const id = randomUUID(), generation = 1, sealed = await sealRestorePoint(captured.payload, + { companyId: f.companyId, workspaceId: f.workspaceId, restorePointId: id, generation }); + const objectKey = `${f.companyId}/git-restore-points/${f.workspaceId}/${generation}/${id}.pcrp`; + await storage.putFile({ companyId: f.companyId, namespace: "git-restore-points", objectKey, + originalFilename: "saved.pcrp", contentType: "application/octet-stream", body: sealed.ciphertext }); + const restorePoint = { schema: "paperclip.git-restore-point.v1", id, generation, objectKey, byteSize: sealed.ciphertext.length, + sha256: sealed.sha256, key: sealed.key, head: captured.manifest.head, index: captured.manifest.index, + worktree: captured.manifest.worktree, ignored: captured.manifest.ignored, modes: captured.manifest.modes, headOnRemote: false }; + const contents = await captureGitWorkspaceContents(f.cwd, { companyId: f.companyId, workspaceId: f.workspaceId }, []); + await db.update(executionWorkspaces).set({ status: "archived", closedAt: new Date(), metadata: { + createdByRuntime: true, gitBranchOwnershipVersion: 1, gitCacheRestoration: { schema: "paperclip.git-cache-restoration.v2", + companyId: f.companyId, workspaceId: f.workspaceId, sourceIssueId: f.issueId, repoUrl: f.repoUrl, + commit: f.commit, branchName: f.branchName, sourceKind: "managed_project", projectId: f.projectId, + sourcePath: f.base, worktreePath: f.cwd, gitBranchOwnershipVersion: 1, verifiedAt: new Date().toISOString(), restorePoint, contents }, + } }).where(eq(executionWorkspaces.id, f.workspaceId)); + await git(f.base, "worktree", "remove", "--force", f.cwd); await git(f.base, "branch", "-D", f.branchName); + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + const [environment] = await db.insert(environments).values({ name: f.runId, driver: "daytona" }).returning(); + const [lease] = await db.insert(environmentLeases).values({ id: f.reference.leaseId, companyId: f.companyId, + environmentId: environment.id, heartbeatRunId: f.runId, issueId: f.issueId, executionWorkspaceId: f.workspaceId, + provider: "daytona", providerLeaseId: f.reference.providerLeaseId, status: "retained", leasePolicy: "retain_on_failure", + metadata: { remoteCwd: f.reference.remoteCwd } }).returning(); + const cause = "native_workspace_sync_out_unrecoverable"; + await db.update(nativeRunFinalizations).set({ failureCode: cause }).where(eq(nativeRunFinalizations.runId, f.runId)); + const [hold] = await db.insert(issueRecoveryActions).values({ companyId: f.companyId, sourceIssueId: f.issueId, + kind: "active_run_watchdog", cause, ownerType: "board", ownerAgentId: null, returnOwnerAgentId: run.agentId, + fingerprint: nativeSha256({ runId: f.runId, failureCode: cause }), nextAction: "Preserve retained remote files", evidence: { runId: f.runId } }).returning(); + const [selected] = await db.insert(executionWorkspaces).values({ companyId: f.companyId, sourceIssueId: f.issueId, + name: "Current task workspace", providerType: "local_fs", mode: "isolated_workspace", strategyType: "project_primary", cwd: path.join(root, "current-task") }).returning(); + await db.update(issues).set({ status: "cancelled", executionWorkspaceId: selected.id }).where(eq(issues.id, f.issueId)); + await db.insert(activityLog).values({ companyId: f.companyId, actorType: "user", actorId: "original owner", + action: "issue.updated", entityType: "issue", entityId: f.issueId, details: { retained: "original task history" } }); + const [task] = await db.select().from(issues).where(eq(issues.id, f.issueId)); + const [owner] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)); + const history = await db.select().from(activityLog).where(eq(activityLog.entityId, f.issueId)); + return { ...f, run, lease, hold, task, owner, history, before: await workspace(f.workspaceId) }; + } + it("preserves an unselected archived recipe and its pending native files without reopening the task", async () => { + const f = await archivedPreparedFixture(), put = storage.putFile.bind(storage); + let interrupt = true; + storage.putFile = async input => { const saved = await put(input); + if (interrupt) { interrupt = false; throw new Error("archived upload reply lost"); } return saved; }; + await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).rejects.toThrow("archived upload reply lost"); + const [interrupted] = await db.select().from(workspaceOperations).where(eq(workspaceOperations.phase, "remote_workspace_migration")); + const [pending] = await db.select().from(executionWorkspaceSnapshots); + expect(readRemoteWorkspaceAuthority((await workspace(f.workspaceId)).metadata)).toBeNull(); + expect(await migrateRemoteWorkspace({ db, storage, ...f, apply: true })).toMatchObject({ applied: true }); + const saved = await workspace(f.workspaceId), authority = readRemoteWorkspaceAuthority(saved.metadata)!; + expect(saved.status).toBe("archived"); expect(saved.closedAt).toEqual(f.before.closedAt); + expect(authority.snapshotId).toBe(pending.id); + expect((await db.select().from(workspaceOperations).where(eq(workspaceOperations.id, interrupted.id)))[0].status).toBe("succeeded"); + expect(saved.metadata?.gitCacheRestoration).toEqual(f.before.metadata?.gitCacheRestoration); + expect(saved.metadata?.remoteWorkspaceRecoverySourceRunIds).toEqual([f.runId]); + expect((await db.select().from(issues).where(eq(issues.id, f.issueId)))[0]).toEqual(f.task); + expect(await db.select().from(activityLog).where(eq(activityLog.entityId, f.issueId))).toEqual(f.history); + expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)))[0]).toEqual(f.owner); + expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.lease.id)))[0]).toEqual(f.lease); + expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.hold.id)))[0]).toEqual(f.hold); + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + const marker = { schema: "paperclip.legacy-workspace-recovery-migration.v1", operationId: expect.any(String), workspaceId: f.workspaceId }; + expect(run).toEqual({ ...f.run, updatedAt: expect.any(Date), runnerProfileJson: { ...f.run.runnerProfileJson, legacyWorkspaceRecoveryMigration: marker } }); + await expect(readMigratedLegacyWorkspaceSource(db, { companyId: f.companyId, runId: f.runId, + reference: f.reference })).resolves.toMatchObject({ runId: f.runId, reference: f.reference }); + await expect(fs.access(f.cwd)).rejects.toMatchObject({ code: "ENOENT" }); + const ref = (await getWorkspaceSnapshot(db, { ...f, snapshotId: authority.snapshotId! }))!; + const archivePath = path.join(root, "archived-native.pcws"), targetDir = path.join(root, "restored-native"); + await loadWorkspaceSnapshotArchive({ storage, reference: ref, targetPath: archivePath }); + await restoreRemoteWorkspaceArchive({ archivePath, targetDir, expectedManifestDigest: ref.manifestDigest }); + expect(await git(targetDir, "show", ":saved.txt")).toBe("archived staged edit"); + expect(await fs.readFile(path.join(targetDir, "saved.txt"), "utf8")).toBe("archived unstaged edit\n"); + expect(await fs.readFile(path.join(targetDir, "untracked.txt"), "utf8")).toBe("archived private file\n"); + await migrateRemoteWorkspace({ db, storage, ...f, apply: true }); + expect((await db.select().from(workspaceOperations).where(eq(workspaceOperations.phase, "remote_workspace_migration")))).toHaveLength(1); + }); + it.each(["recipe", "reference", "provider"])("refuses an archived prepared source changed during upload (%s)", async change => { + const f = await archivedPreparedFixture(), put = storage.putFile.bind(storage); + let uploaded = false; + storage.putFile = async input => { + const saved = await put(input); uploaded = true; + if (change === "recipe") await db.update(executionWorkspaces).set({ metadata: { ...f.before.metadata, + remoteWorkspaceMigration: (await workspace(f.workspaceId)).metadata?.remoteWorkspaceMigration, + gitCacheRestoration: { ...f.before.metadata!.gitCacheRestoration as object, commit: f.upstream } } }).where(eq(executionWorkspaces.id, f.workspaceId)); + else { + const reference = { ...f.reference, ...(change === "reference" ? { baselineSha256: "56".repeat(32) } : { providerLeaseId: randomUUID() }) }; + if (change === "provider") await db.update(environmentLeases).set({ providerLeaseId: reference.providerLeaseId }).where(eq(environmentLeases.id, f.lease.id)); + await db.update(heartbeatRuns).set({ runnerProfileJson: { ...f.run.runnerProfileJson, nativeWorkspaceSync: reference } }).where(eq(heartbeatRuns.id, f.runId)); + } + return saved; + }; + await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).rejects.toThrow(); + expect(uploaded).toBe(true); + expect(readRemoteWorkspaceAuthority((await workspace(f.workspaceId)).metadata)).toBeNull(); + expect((await db.select().from(issues).where(eq(issues.id, f.issueId)))[0]).toEqual(f.task); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)))[0].runnerProfileJson).not.toHaveProperty("legacyWorkspaceRecoveryMigration"); + await expect(fs.access(f.cwd)).rejects.toMatchObject({ code: "ENOENT" }); + }); + it("refuses a competing native F owner before capturing an archived prepared source", async () => { + const f = await archivedPreparedFixture(); + let release!: () => void, entered!: () => void; + const held = new Promise(done => { release = done; }), ready = new Promise(done => { entered = done; }); + const owner = db.transaction(async tx => { expect(await tryLockNativeWorkspaceFinalization(tx as unknown as typeof db, + { companyId: f.companyId, runId: f.runId })).toBe(true); entered(); await held; }); + await ready; + try { + await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).rejects.toThrow("remote_copyback_owned"); + expect(readRemoteWorkspaceAuthority((await workspace(f.workspaceId)).metadata)).toBeNull(); + expect(await db.select().from(executionWorkspaceSnapshots)).toHaveLength(0); + expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)))[0]).toEqual(f.owner); + } finally { release(); await owner; } + }); it.each(["legacy", "verified", "retry"])("recovers an archived Git workspace from its exact branch-deletion receipt (%s)", async receiptKind => { const f = await gitArchiveFixture(), closedAt = new Date(); await db.update(executionWorkspaces).set({ status: "archived", closedAt }).where(eq(executionWorkspaces.id, f.workspaceId)); @@ -1143,7 +1263,7 @@ describe.skipIf(!support.supported)("remote workspace migration", () => { const f = await seed(), closedAt = new Date("2026-10-20T12:00:00Z"); await db.update(executionWorkspaces).set({ status: "archived", closedAt }).where(eq(executionWorkspaces.id, f.workspaceId)); await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.issueId)); - await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).resolves.toMatchObject({ applied: true }); + expect(await migrateRemoteWorkspace({ db, storage, ...f, apply: true })).toMatchObject({ applied: true }); const saved = await workspace(f.workspaceId), authority = readRemoteWorkspaceAuthority(saved.metadata)!; expect(saved.status).toBe("archived"); expect(saved.closedAt).toEqual(closedAt); const [issue] = await db.select().from(issues).where(eq(issues.id, f.issueId)); diff --git a/server/src/services/remote-workspace-migration.ts b/server/src/services/remote-workspace-migration.ts index 6ccbfebd609..258724ccfff 100644 --- a/server/src/services/remote-workspace-migration.ts +++ b/server/src/services/remote-workspace-migration.ts @@ -160,7 +160,8 @@ async function inspect(db: ReadDb, input: { companyId: string; workspaceId: stri sql`${heartbeatRuns.runnerProfileJson}->'nativeWorkspaceSync'->>'state' in ('prepared', 'finalized')`, )); const legacyRecoverySources: LegacyWorkspaceRecoverySource[] = []; - const onlineRecoveryAllowed = Boolean(input.onlineSource) && !input.writersStopped; + const onlineRecoveryAllowed = !input.writersStopped + && Boolean(input.onlineSource || workspace.status === "archived" && archivedGitSource?.recipe); for (const run of referencedRuns.filter(run => object(run.reference).state === "prepared").sort((a, b) => a.id.localeCompare(b.id))) { if (onlineRecoveryAllowed) { const source = await inspectOnlineLegacyWorkspaceRecoverySource(db, { workspace, runId: run.id }); @@ -414,11 +415,12 @@ type ReservedMigration = Awaited>; type MigrationPlan = { input: MigrationInput; onlineSource?: OnlineWorkspaceSource; reserved: ReservedMigration }; async function lockMigrationRecovery(lock: MigrationTransaction, plans: MigrationPlan[], cohort?: WorkspaceMigrationCohort) { - const online = plans.filter(plan => plan.onlineSource); + const online = plans.filter(plan => !plan.input.writersStopped + && (plan.onlineSource || plan.reserved.workspace.status === "archived" && plan.reserved.archivedGitSource?.recipe)); if (!online.length) return; if (!await lockOnlineLegacyWorkspaceRecoverySources(lock as unknown as Db, { companyId: online[0].input.companyId, - sources: online.flatMap(({ reserved, onlineSource }) => [...reserved.legacyRecoverySources, ...onlineSource!.companions.flatMap(proof => proof.sources)]), - holds: online.flatMap(({ reserved, onlineSource }) => [...reserved.onlineRecoveryHolds, ...onlineSource!.companions.flatMap(proof => proof.holds)]) })) + sources: online.flatMap(({ reserved, onlineSource }) => [...reserved.legacyRecoverySources, ...(onlineSource?.companions.flatMap(proof => proof.sources) ?? [])]), + holds: online.flatMap(({ reserved, onlineSource }) => [...reserved.onlineRecoveryHolds, ...(onlineSource?.companions.flatMap(proof => proof.holds) ?? [])]) })) throw new Error("remote_workspace_migration_blocked:remote_copyback_owned"); const readers = await Promise.allSettled(online.map(async ({ input, onlineSource, reserved }) => { const current = await inspect(input.db, { ...input, onlineSource, operationId: reserved.operation!.id }, cohort); @@ -531,9 +533,9 @@ async function validateMigrationPublication(tx: MigrationTransaction, input: Mig || journal.issueId !== operation.issueId || journal.cwd !== operation.cwd || canonical(journal.metadata) !== canonical(operation.metadata)) throw new Error("workspace_cohort_journal_changed"); } - await lockMigrationParents(tx, input.companyId, reserved.workspace.sourceIssueId, onlineSource ? [ + await lockMigrationParents(tx, input.companyId, reserved.workspace.sourceIssueId, onlineSource || reserved.archivedGitSource?.recipe ? [ ...reserved.legacyRecoverySources.map(source => source.issueId), - ...onlineSource.companions.flatMap(proof => proof.sources.map(source => source.issueId)), + ...(onlineSource?.companions.flatMap(proof => proof.sources.map(source => source.issueId)) ?? []), ] : []); for (const actionId of [...new Set([...reserved.finalizedRecoveryHolds, ...reserved.onlineRecoveryHolds].map(held => held.actionId))].sort()) { await tx.select({ id: issueRecoveryActions.id }).from(issueRecoveryActions).where(and( diff --git a/ui/src/components/task-chat/TaskChatComposer.test.tsx b/ui/src/components/task-chat/TaskChatComposer.test.tsx index f02cf4b6d8d..c53445468e8 100644 --- a/ui/src/components/task-chat/TaskChatComposer.test.tsx +++ b/ui/src/components/task-chat/TaskChatComposer.test.tsx @@ -13,7 +13,7 @@ import { parseRunnerGoalCommand, TaskChatComposer } from "./TaskChatComposer"; import { ComposerAddMenu } from "./ComposerAddMenu"; import { QuestionForm } from "./QuestionForm"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import type { Agent, HeartbeatRun } from "@paperclipai/shared"; +import type { Agent, HeartbeatRun, IssueWorkMode } from "@paperclipai/shared"; import { agentsApi } from "@/api/agents"; import { instanceSettingsApi } from "@/api/instanceSettings"; import { CoordinatorPresentation } from "@/components/coordinator/CoordinatorPresentation"; @@ -1201,6 +1201,143 @@ describe("TaskChatComposer", () => { expect(onAdd).toHaveBeenCalledTimes(2); }); + it("reflects an externally updated task mode after mounting", async () => { + const onAdd = vi.fn(); + const onWorkModeChange = vi.fn(); + renderComposer({ onAdd, onWorkModeChange, workMode: "standard" }); + expect(container.querySelector('[data-testid="task-chat-composer-mode"]')).toBeNull(); + + renderComposer({ onAdd, onWorkModeChange, workMode: "planning" }); + await flushAsync(); + expect(container.querySelector('[data-testid="task-chat-composer-mode"]')?.getAttribute("data-pending-work-mode")) + .toBe("planning"); + }); + + it("keeps a local draft mode while persisted task data refreshes", async () => { + const onAdd = vi.fn(); + const onWorkModeChange = vi.fn(); + renderComposer({ onAdd, onWorkModeChange, workMode: "standard" }); + pressKey("Tab", { shiftKey: true }); + + renderComposer({ onAdd, onWorkModeChange, workMode: "ask" }); + await flushAsync(); + expect(container.querySelector('[data-testid="task-chat-composer-mode"]')?.getAttribute("data-pending-work-mode")) + .toBe("planning"); + expect(onWorkModeChange).not.toHaveBeenCalled(); + + // Matching task data does not acknowledge an unsent local choice. + renderComposer({ onAdd, onWorkModeChange, workMode: "planning" }); + renderComposer({ onAdd, onWorkModeChange, workMode: "standard" }); + await flushAsync(); + expect(container.querySelector('[data-testid="task-chat-composer-mode"]')?.getAttribute("data-pending-work-mode")) + .toBe("planning"); + }); + + it("keeps the chosen mode and message when an optimistic mode save rolls back", async () => { + const onAdd = vi.fn(); + let rejectSave!: () => void; + function OptimisticModeHarness() { + const [workMode, setWorkMode] = useState("standard"); + return { + setWorkMode(mode); + return new Promise((_resolve, reject) => { + rejectSave = () => { + setWorkMode("standard"); + reject(new Error("Mode save rejected")); + }; + }); + }} />; + } + render(); + pressKey("Tab", { shiftKey: true }); + typeText("Keep this planning message"); + pressKey("Enter"); + await flushAsync(); + await act(async () => rejectSave()); + await flushAsync(); + + expect(editable().textContent).toBe("Keep this planning message"); + expect(container.querySelector('[data-testid="task-chat-composer-mode"]')?.getAttribute("data-pending-work-mode")) + .toBe("planning"); + expect(onAdd).not.toHaveBeenCalled(); + }); + + it.each([ + ["standard", "planning", "standard"], + ["ask", "standard", "ask"], + ] as const)("keeps next draft mode %s → %s → %s through successful send", async (savedMode, sentMode, nextMode) => { + let resolveSend!: () => void; + const onAdd = vi.fn().mockReturnValue(new Promise((resolve) => { resolveSend = resolve; })); + function PendingSendHarness() { + const [workMode, setWorkMode] = useState(savedMode); + return { setWorkMode(mode); }} />; + } + const selectedMode = () => container.querySelector('[data-testid="task-chat-composer-mode"]') + ?.getAttribute("data-pending-work-mode") ?? "standard"; + render(); + pressKey("Tab", { shiftKey: true }); + expect(selectedMode()).toBe(sentMode); + typeText("First message"); + pressKey("Enter"); + await flushAsync(); + expect(onAdd).toHaveBeenCalledTimes(1); + + if (nextMode === "standard") { + flushSync(() => container.querySelector('[data-testid="task-chat-composer-mode"]')!.click()); + } else { + pressKey("Tab", { shiftKey: true }); + pressKey("Tab", { shiftKey: true }); + } + expect(selectedMode()).toBe(nextMode); + typeText("Next message"); + await act(async () => resolveSend()); + await flushAsync(); + expect(selectedMode()).toBe(nextMode); + expect(editable().textContent).toBe("Next message"); + }); + + it.each([ + ["receipt", false], ["receipt", true], + ["resend", false], ["resend", true], + ] as const)("settles the sent mode through %s without clearing a newer choice (%s)", async (method, newerChoice) => { + const key = `mode-settlement-${method}-${newerChoice}`; + const onAdd = vi.fn().mockRejectedValueOnce(new CommentSubmissionUnknownError()).mockResolvedValue(undefined); + const onWorkModeChange = vi.fn().mockResolvedValue(undefined); + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } }); + const show = (workMode: IssueWorkMode, confirmedSubmissionIds = new Set()) => render( + , + ); + show("standard"); + await flushAsync(); + pressKey("Tab", { shiftKey: true }); + typeText("First message"); + pressKey("Enter", { metaKey: true }); + await flushAsync(); + expect(onAdd).toHaveBeenCalledTimes(1); + const intent = loadDraftSubmission(key)!; + expect(intent).not.toBeNull(); + show("planning"); + if (newerChoice) pressKey("Tab", { shiftKey: true }); + + if (method === "receipt") show("planning", new Set([intent.attemptId])); + else { + const resend = Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Resend now")!; + flushSync(() => resend.click()); + } + await flushAsync(); + expect(loadDraftSubmission(key)).toBeNull(); + show("standard"); + await flushAsync(); + expect(container.querySelector('[data-testid="task-chat-composer-mode"]')?.getAttribute("data-pending-work-mode") ?? "standard") + .toBe(newerChoice ? "ask" : "standard"); + expect(onAdd).toHaveBeenCalledTimes(method === "receipt" ? 1 : 2); + if (method === "resend") expect(onAdd.mock.calls[1]?.[4]).toBe(intent.attemptId); + client.clear(); + }); + it("cycles the pending mode with Shift+Tab and applies it on submit", async () => { const onAdd = vi.fn().mockResolvedValue(undefined); const onWorkModeChange = vi.fn().mockResolvedValue(undefined); @@ -1226,6 +1363,11 @@ describe("TaskChatComposer", () => { expect(onWorkModeChange).toHaveBeenCalledWith("planning"); expect(onAdd).toHaveBeenCalledWith("do the plan", undefined, undefined, undefined, expect.any(String)); + + renderComposer({ onAdd, onWorkModeChange, workMode: "ask" }); + await flushAsync(); + expect(container.querySelector('[data-testid="task-chat-composer-mode"]')?.getAttribute("data-pending-work-mode")) + .toBe("ask"); }); it("cycles Auto, Plan, and Ask modes with Cmd+Period while focused", () => { diff --git a/ui/src/components/task-chat/TaskChatComposer.tsx b/ui/src/components/task-chat/TaskChatComposer.tsx index bf392b3d6d0..9e44a506187 100644 --- a/ui/src/components/task-chat/TaskChatComposer.tsx +++ b/ui/src/components/task-chat/TaskChatComposer.tsx @@ -354,7 +354,7 @@ type ComposerAttachment = { type QueuedEditBackup = { body: string; attachments: ComposerAttachment[]; - pendingMode: IssueWorkMode; + pendingMode: IssueWorkMode | null; pendingAssignee: string | null; }; @@ -451,8 +451,10 @@ export function TaskChatComposer({ useState(null); const [takeoverControlsSlot, setTakeoverControlsSlot] = useState(null); - const [localPendingMode, setPendingMode] = useState(workMode); - const pendingMode = creation ? workMode : localPendingMode; + const [pendingModeOverride, setPendingMode] = useState(null); + const modeChoiceGeneration = useRef(0); + const sentModeChoice = useRef<{ attemptId: string; generation: number } | null>(null); + const pendingMode = creation ? workMode : pendingModeOverride ?? workMode; const [pendingAssignee, setPendingAssignee] = useState(null); const coordinator = useCoordinatorPresentation(); const [localRunSettings, setLocalRunSettings] = useState(null); @@ -556,7 +558,7 @@ export function TaskChatComposer({ queuedEditBackupRef.current = { body: bodyRef.current, attachments: attachmentsRef.current, - pendingMode, + pendingMode: pendingModeOverride, pendingAssignee: pendingAssigneeRef.current, }; if (draftKey) saveDraft(draftKey, bodyRef.current); @@ -584,7 +586,7 @@ export function TaskChatComposer({ } previousQueuedEditIdRef.current = nextId; - }, [draftKey, pendingMode, queuedEdit]); + }, [draftKey, pendingModeOverride, queuedEdit]); useEffect(() => { if (!draftKey || queuedEdit) return; @@ -704,10 +706,18 @@ export function TaskChatComposer({ } function changeMode(mode: IssueWorkMode) { + modeChoiceGeneration.current += 1; setPendingMode(mode); if (creation) void onWorkModeChange?.(mode); } + function settleSentMode(attemptId: string) { + const choice = sentModeChoice.current; + if (choice?.attemptId !== attemptId) return; + if (modeChoiceGeneration.current === choice.generation) setPendingMode(null); + sentModeChoice.current = null; + } + async function uploadImage(file: File): Promise { const id = crypto.randomUUID(); setAttachments((prev) => [ @@ -926,6 +936,7 @@ export function TaskChatComposer({ const submittedBody = bodyRef.current; const submittedAttachments = attachmentsRef.current; const submittedAssignee = pendingAssigneeRef.current; + const submittedModeGeneration = modeChoiceGeneration.current; const trimmed = submittedBody.trim(); const goalCommand = queuedEdit ? ({ matched: false } as const) @@ -1088,6 +1099,7 @@ export function TaskChatComposer({ pendingDraftRef.current = { draftKey, attemptId, submittedBody, submittedAttachmentIds: attachmentIds, request, requestOwner }; changeBody(bodyRef.current); } + sentModeChoice.current = { attemptId, generation: submittedModeGeneration }; if (runSettings) { await onAdd(fullBody, reopen, reassignment, attachmentIds.length ? attachmentIds : undefined, attemptId, runSettings); } else { @@ -1098,6 +1110,7 @@ export function TaskChatComposer({ if (draftKey) settleDraftSubmission(draftKey, attemptId, mountedTaskKey.current === draftKey ? bodyRef.current : undefined); if (mountedTaskKey.current !== draftKey) return; + settleSentMode(attemptId); const submittedIds = new Set(submittedAttachments.map((item) => item.id)); setAttachments((current) => current.filter((item) => !submittedIds.has(item.id)), @@ -1149,6 +1162,7 @@ export function TaskChatComposer({ const settlementKey = JSON.stringify([draftKey, submission.attemptId]); if (settledSubmissionIds.current.has(settlementKey)) return; settledSubmissionIds.current.add(settlementKey); + settleSentMode(submission.attemptId); const nextDraft = submission.nextDraftOffset === undefined ? "" : bodyRef.current.slice(submission.nextDraftOffset); if (draftKey) settleDraftSubmission(draftKey, submission.attemptId, nextDraft); From 18697b8d21fbbe86bcf64621a86defe4c922baf5 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 9 Nov 2026 19:28:31 -0600 Subject: [PATCH 05/10] perf(workspaces): share cohort child-source verification (#20418) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip must preserve agent workspace bytes during online migration. > - A cohort can contain several aliases of the same physical source. > - The importer verifies imported children before capture and again before publication. > - The immutable-object cache avoids repeated downloads but still recaptures local child bytes for every alias. > - This pull request shares the initial proof within the held cohort fence and checks fresh bytes once more after every capture joins. > - The benefit is less repeated local archive work while child mutations still block the whole cohort. > - Required browser CI twice reproduced an independent stale composer-mode bug. A focused regression proves that refreshed persisted task mode was ignored after mount. The state repair follows task data when there is no local override. Explicit local mode choices retain their own generation so a completed send cannot clear the next draft’s choice. ## Linked Issues or Issue Description Refs: #20311, #20387, #20401, #20404. **Current behavior** Two aliases recapture the same imported child's local bytes four times, even with one immutable object read. A larger alias cohort repeats this multi-GB work for each member. **Proposed behavior** Share the successful initial verification for the same physical root, Git roots and exact recorded child set or discovery mode. After all captures join, run a separate fresh final verification for each root and recorded child set. Keep every member's database and publication checks. **Reason and benefit** The local PostgreSQL fixture proves that two aliases now perform two child recaptures instead of four. Hosted timing improvement has not been measured. ## What Changed - Add invocation-local initial and final proof maps to the existing cohort child verifier. - Retain the existing canonical source-owner check before and after shared results. - Defer cohort final nested checks until all captures finish, and join every final reader before publication or fence release. - Keep singleton verification, saved journal schemas, snapshot IDs, archive bytes and per-member publication checks unchanged. - Extend the existing real PostgreSQL alias fixture with a child mutation during the last parent upload. - Repair the required CI planning-mode race with a nullable local override: absent override follows task data; a user selection belongs to the draft. A successful send or confirmed resend/receipt clears it only if no newer choice exists. Failed saves preserve the mode and restored message. Queued-edit backup retains whether the mode was explicit. Leave the browser assertion and timeouts unchanged. ## Verification - Canonical Node24 worktree preflight and plugin SDK prerequisites passed. Server TypeScript passed. - Genuine unchanged-source PostgreSQL RED: two aliases performed four local child recaptures instead of two (one failed, 22 intentionally not selected). GREEN: five source-sharing, last-upload child mutation, capture/cancellation join and actual outer-commit rollback controls passed (18 intentionally not selected; 66.53s). The actual fence-loss control also passed (one passed, 22 intentionally not selected; 38.13s). Both wrappers completed cleanup. - Migration source and tree bytes remain identical to locally qualified `466837cfe997924c3794fd5d0e96134cab1cd04c`; later commits only repair the composer and its tests. - Required planning browser CI originally failed, then failed its one unchanged-head retry, because the planning chip remained absent after opening-question dismissal. Those failures remain recorded ([original](https://github.com/paperclipai/paperclip/actions/runs/42723622165/job/129523785985), [retry](https://github.com/paperclipai/paperclip/actions/runs/42723622165/job/129534415590)). The final-head identical case passes in 30.5s, with all 34 shard cases passing ([final CI](https://github.com/paperclipai/paperclip/actions/runs/42731309796/job/129550549775)). Assertions and timeouts were not relaxed. - Composer regressions reproduced stale loaded mode, optimistic-save rollback, overwritten next-draft choices, and stale mode after confirmed resend/receipt. All 145 composer tests now pass (2.88s). Canonical UI TypeScript and token gates pass. The original planning browser case also passed locally (15.5s; 26.9s including setup). - The first final-head serialized-suite attempt was automatically cancelled at its unchanged 20-minute job limit. Grouped Turbo output did not expose an individual failing assertion; cause remains unknown ([retained attempt](https://github.com/paperclipai/paperclip/actions/runs/42731309796/job/129550550373)). One same-head diagnostic retry was a cache miss and executed all 419 heartbeat recovery tests successfully in 376.94s on the identical CI checkout ([retry](https://github.com/paperclipai/paperclip/actions/runs/42731309796/job/129561196792)). It is not classified as infrastructure or a known flake. - Final exact head `ba1f85f18085dd0e84c594ed0cb68d5bf817c93c`: all 61 checks terminal (56 success, four skipped, one neutral); required CI is green ([workflow](https://github.com/paperclipai/paperclip/actions/runs/42731309796)). Fresh Greptile is 5/5 with every review thread resolved ([review](https://github.com/paperclipai/paperclip/pull/20418#issuecomment-6754705323)). Focused commands: ```sh node --import ./cli/node_modules/tsx/dist/loader.mjs packages/db/src/test-postgres-command.ts pnpm exec vitest run server/src/services/remote-workspace-cohort-migration.test.ts -t "shares the merged child verifier|joins active capture peers|keeps every authority and activity unpublished" pnpm exec vitest run ui/src/components/task-chat/TaskChatComposer.test.tsx pnpm --filter @paperclipai/server exec tsc --noEmit pnpm --filter @paperclipai/ui typecheck pnpm check:token-gates ``` ## Risks - Reuse is limited to one invocation under the same complete source and finalizer fences. Different physical roots, Git roots, recorded child sets and discovery mode have different keys. No local-byte proof is stored durably or reused after restart. - Initial and final maps are separate. A child change during any parent upload must fail the fresh final verification before the atomic publication transaction starts. - Final readers all finish before an error can release the source fence. Per-member database child rows, source fingerprints, journals, keys and publication locks retain their existing checks. - This reduces repeated verification for aliases. It does not change capture concurrency, upload policy or immutable checkpoint validation. Hosted speedup remains unverified. - The CI repair must distinguish task data from explicit draft intent. Only a successful send with the same choice generation clears its override; a later draft selection and failed-save rollback retain it. Regression tests cover these transitions. It adds no styling, request, or persistence changes. ## Model Used OpenAI GPT-6 (Codex), with tool use and code execution. The runtime does not expose a more specific model identifier or context-window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes: #` / `Refs: #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- .../2026-11-07-online-git-source-fence.md | 7 ++++ .../remote-workspace-cohort-migration.test.ts | 22 ++++++++-- .../remote-workspace-migration-tree.ts | 1 + .../services/remote-workspace-migration.ts | 40 +++++++++++++++---- 4 files changed, 58 insertions(+), 12 deletions(-) diff --git a/doc/plans/2026-11-07-online-git-source-fence.md b/doc/plans/2026-11-07-online-git-source-fence.md index e67165c3406..682725fcd97 100644 --- a/doc/plans/2026-11-07-online-git-source-fence.md +++ b/doc/plans/2026-11-07-online-git-source-fence.md @@ -105,6 +105,13 @@ original source, restore uncommitted/staged work, and run fsck. No hosted import hold, cancellation, provider call, or shared-cache Git command is part of these local tests. +A cohort shares its initial nested-source verification only within its held +source and finalizer fences, keyed by physical root, Git roots and the exact +recorded child set (or discovery). After every capture joins, a separate fresh +verification checks each physical root and child set before publication. A +changed child still rejects the whole cohort. Singleton imports keep their +per-import checks. No local-byte proof survives the invocation. + The online migration owner can checkpoint completed immutable nested-snapshot verification in the child snapshot ledger. This optional versioned proof binds the complete encrypted reference, child lineage, source operation and a known diff --git a/server/src/services/remote-workspace-cohort-migration.test.ts b/server/src/services/remote-workspace-cohort-migration.test.ts index 92c353d2eee..cc2c3ce9af4 100644 --- a/server/src/services/remote-workspace-cohort-migration.test.ts +++ b/server/src/services/remote-workspace-cohort-migration.test.ts @@ -139,7 +139,7 @@ describe.skipIf(!support.supported)("bounded workspace cohort migration", () => expect(await git(targetDir, "log", "-1", "--format=%s")).toBe("Original history"); } }, 60_000); - it("shares the merged child verifier across parallel aliases under the complete cohort fence", async () => { + it.each(["unchanged", "changed"] as const)("shares the merged child verifier across parallel aliases under the complete cohort fence (%s child bytes)", async mode => { const f = await fixture(), parent = f.leaves[0], cwd = path.join(parent.cwd!, ".paperclip", "worktrees", "nested"); await git(f.root, "worktree", "add", "-qb", "nested", cwd); const [childIssue, aliasIssue] = await db.insert(issues).values([ @@ -172,10 +172,24 @@ describe.skipIf(!support.supported)("bounded workspace cohort migration", () => return get(...args); }); const capture = vi.spyOn(workspaceArchive, "captureRemoteWorkspaceDirectory"); - await expect(run(f, { workspaceIds: [parent.id, alias.id] })).resolves.toMatchObject({ applied: true }); + const beforeActivity = await db.select().from(activityLog), put = storage.putFile.bind(storage); + let uploads = 0; + if (mode === "changed") vi.spyOn(storage, "putFile").mockImplementation(async input => { + const result = await put(input); + if (++uploads === 2) await fs.writeFile(path.join(cwd, "untracked.txt"), "changed during parent upload\n"); + return result; + }); + const pending = run(f, { workspaceIds: [parent.id, alias.id] }); + if (mode === "unchanged") await expect(pending).resolves.toMatchObject({ applied: true }); + else { + await expect(pending).rejects.toThrow("nested_workspace_source_changed"); + const selected = await db.select().from(executionWorkspaces).where(inArray(executionWorkspaces.id, [parent.id, alias.id])); + expect(selected.every(row => !readRemoteWorkspaceAuthority(row.metadata))).toBe(true); + expect(await db.select().from(activityLog)).toEqual(beforeActivity); + } expect(reads).toBe(1); - expect(capture.mock.calls.filter(([input]) => input.cwd === cwd && path.basename(input.archivePath) === "current.pcws")).toHaveLength(4); - expect(await fs.readFile(path.join(cwd, "untracked.txt"), "utf8")).toBe("nested dirty bytes\n"); + expect(capture.mock.calls.filter(([input]) => input.cwd === cwd && path.basename(input.archivePath) === "current.pcws")).toHaveLength(2); + expect(await fs.readFile(path.join(cwd, "untracked.txt"), "utf8")).toBe(mode === "unchanged" ? "nested dirty bytes\n" : "changed during parent upload\n"); }, 60_000); it.each(["foreign", "journal", "finished"])("refuses a changed %s operation before any authority write", async mode => { const f = await fixture(), put = storage.putFile.bind(storage); let uploaded = 0; diff --git a/server/src/services/remote-workspace-migration-tree.ts b/server/src/services/remote-workspace-migration-tree.ts index 34d88d67c1f..d7e3880c22a 100644 --- a/server/src/services/remote-workspace-migration-tree.ts +++ b/server/src/services/remote-workspace-migration-tree.ts @@ -361,6 +361,7 @@ export function createNestedWorkspaceImportVerifier(input: { }, }; return { + assertOwner, prepare(options: Omit): Promise { if (closed || current) return Promise.reject(new Error("nested_workspace_verifier_unavailable")); const work = (async () => { diff --git a/server/src/services/remote-workspace-migration.ts b/server/src/services/remote-workspace-migration.ts index 258724ccfff..cf068eebde6 100644 --- a/server/src/services/remote-workspace-migration.ts +++ b/server/src/services/remote-workspace-migration.ts @@ -431,17 +431,32 @@ async function lockMigrationRecovery(lock: MigrationTransaction, plans: Migratio for (const reader of readers) if (reader.status === "rejected") throw reader.reason; } -function createMigrationChildVerifier(input: MigrationInput, onlineSource: OnlineWorkspaceSource | undefined, sourceLock: MigrationTransaction) { +function createMigrationChildVerifier(input: MigrationInput, onlineSource: OnlineWorkspaceSource | undefined, sourceLock: MigrationTransaction, cohort = false) { if (onlineSource?.kind !== "git") return undefined; const verifier = createNestedWorkspaceImportVerifier({ db: input.db, storage: input.storage, companyId: input.companyId, sourceLock, projectIds: onlineSource.projectIds, issueIds: onlineSource.issueIds, signal: input.signal, persistVerification: true }); + type Options = Parameters[0]; + const initial = new Map>(), final = new Map>(); let pending = Promise.resolve(); + const prepare = (options: Options) => { + const work = pending.then(() => verifier.prepare(options)); + pending = work.then(() => undefined, () => undefined); + return work; + }; + const shared = async (options: Options, cache: typeof initial) => { + await verifier.assertOwner(); + const root = options.workspace.cwd ?? options.workspace.providerRef; + const key = canonical([root ? await fs.realpath(root) : null, [...(options.gitSourceRoots ?? [])].sort(), options.recordedChildren ?? null]); + let work = cache.get(key); + if (!work) { work = prepare(options); cache.set(key, work); } + const result = await work; + await verifier.assertOwner(); + return result; + }; return { - prepare(options: Parameters[0]) { - const work = pending.then(() => verifier.prepare(options)); - pending = work.then(() => undefined, () => undefined); - return work; - }, + prepare: (options: Options) => cohort ? shared(options, initial) : prepare(options), + finalize: (options: Options) => shared(options, final), + deferFinal: cohort, async close() { await pending; await verifier.close(); }, }; } @@ -511,7 +526,7 @@ async function captureMigration(input: MigrationInput, reserved: ReservedMigrati const current = await captureRemoteWorkspaceDirectory({ cwd: sourceRoot!, archivePath: currentArchive, exclude, requireNoGit: onlineSource?.kind === "ordinary", gitSourceRoots: onlineSource?.gitSourceRoots, signal: input.signal }); if (current.manifestDigest !== captured.manifestDigest) throw new Error("remote_workspace_migration_source_changed"); } - if (nested.length) { + if (nested.length && !childVerifier?.deferFinal) { const verifyScratch = path.join(scratch, "verify-nested"); await fs.mkdir(verifyScratch); const verified = await (childVerifier?.prepare ?? prepareNestedWorkspaceImports)({ ...input, workspace: reserved.workspace, scratch: verifyScratch, recordedChildren: nested, gitSourceRoots: onlineSource?.gitSourceRoots }); @@ -828,7 +843,7 @@ export async function migrateRemoteWorkspaceCohort(input: { cohort = refreshedCohort; } const captures: Array = Array(plans.length); - const childVerifier = createMigrationChildVerifier(plans[0].input, plans[0].onlineSource, lock); + const childVerifier = createMigrationChildVerifier(plans[0].input, plans[0].onlineSource, lock, true); let next = 0, failure: unknown; const worker = async () => { while (!signal.aborted && next < plans.length) { @@ -842,6 +857,15 @@ export async function migrateRemoteWorkspaceCohort(input: { for (const peer of peers) if (peer.status === "rejected") failure ??= peer.reason; if (failure) throw failure; signal.throwIfAborted(); + const nestedReaders = await Promise.allSettled(plans.map(async (plan, index) => { + const captured = captures[index]!; + if (!captured.nested.length) return; + const scratch = path.join(captured.scratch, "verify-nested"); await fs.mkdir(scratch); + const verified = await (childVerifier?.finalize ?? prepareNestedWorkspaceImports)({ ...plan.input, workspace: plan.reserved.workspace, + scratch, recordedChildren: captured.nested, gitSourceRoots: plan.onlineSource?.gitSourceRoots }); + if (canonical(verified) !== canonical(captured.nested)) throw new Error("nested_workspace_source_changed"); + })); + for (const reader of nestedReaders) if (reader.status === "rejected") throw reader.reason; await lock.execute(sql`select 1`); await lock.transaction(async tx => { await lockMigrationParents(tx, companyId, null, plans.flatMap(plan => [ From 5570debc5b94d19e5f499432356cb65a4019c8de Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Mon, 9 Nov 2026 17:43:34 -0800 Subject: [PATCH 06/10] fix(ui): stop reporting cancelled queries to Sentry (#20430) React Query's CancelledError keeps the default Error name, so the name-based abort check never matched it. A query cancelled with revert: false (for example by the persisted cache when an issue read is denied or the account changes) reached the query cache onError as an "unknown" error and was sent to Sentry. Recognize it by class. Co-Authored-By: Claude Opus 5.5 --- ui/src/api/errors.test.ts | 2 ++ ui/src/api/errors.ts | 7 +++++-- ui/src/lib/query-client.test.ts | 11 +++++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/ui/src/api/errors.test.ts b/ui/src/api/errors.test.ts index c3d6a0c196e..79ce5a6f006 100644 --- a/ui/src/api/errors.test.ts +++ b/ui/src/api/errors.test.ts @@ -1,3 +1,4 @@ +import { CancelledError } from "@tanstack/react-query"; import { describe, expect, it } from "vitest"; import { ApiError } from "./api-error"; import { @@ -37,6 +38,7 @@ describe("classifyError", () => { ["422", apiError(422), "invalid"], ["500", apiError(500, { error: "boom" }), "unknown"], ["an abort", new DOMException("Aborted", "AbortError"), "aborted"], + ["a React Query cancellation", new CancelledError({ revert: false }), "aborted"], ["a programming TypeError", new TypeError("Cannot read properties of undefined"), "unknown"], ["a plain Error", new Error("nope"), "unknown"], ["undefined", undefined, "unknown"], diff --git a/ui/src/api/errors.ts b/ui/src/api/errors.ts index e4ce2f2029f..677b2d965b4 100644 --- a/ui/src/api/errors.ts +++ b/ui/src/api/errors.ts @@ -12,6 +12,8 @@ * by hand-rolled fetches (health, uploads) classify the same way. */ +import { CancelledError } from "@tanstack/react-query"; + export type ErrorKind = | "transient" | "auth" @@ -181,8 +183,9 @@ function readableServerMessage(err: unknown): string | null { // --- Classification --------------------------------------------------------------- function isAbortError(err: unknown): boolean { - const name = record(err)?.name; - return name === "AbortError" || name === "CancelledError"; + // React Query's `CancelledError` keeps the default `name` ("Error"), so it + // can only be recognized by class. + return record(err)?.name === "AbortError" || err instanceof CancelledError; } function isNetworkTypeError(err: unknown): boolean { diff --git a/ui/src/lib/query-client.test.ts b/ui/src/lib/query-client.test.ts index 951aa1600f3..0c0c2cb4dd1 100644 --- a/ui/src/lib/query-client.test.ts +++ b/ui/src/lib/query-client.test.ts @@ -278,6 +278,17 @@ describe("createAppQueryClient", () => { unsubscribe(); }); + it("does not report a query that was cancelled without reverting", async () => { + const queryFn = vi.fn(() => new Promise(() => {})); + const observer = new QueryObserver(client, { queryKey: ["issues", "detail", "PAP-1"], queryFn }); + const unsubscribe = observer.subscribe(() => {}); + await vi.advanceTimersByTimeAsync(0); + await client.cancelQueries({ queryKey: ["issues", "detail"] }, { revert: false }); + expect(observer.getCurrentResult().error?.message).toBe("CancelledError"); + expect(reportError).not.toHaveBeenCalled(); + unsubscribe(); + }); + it("leaves a cache-only alias stale instead of refetching it without a queryFn", async () => { client.setQueryData(["issues", "detail", "issue-uuid"], { id: "issue-uuid", title: "Seeded" }); const queryFn = vi.fn(async () => "fetched"); From ff4ba7d3194d0fbef54ff88806593020ae377c66 Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Mon, 9 Nov 2026 17:46:33 -0800 Subject: [PATCH 07/10] perf(runner): run launch artifacts in place from a trusted read-only root (#20428) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The Rust Runner (`paperclip-runnerd`) starts provider sidecars and proxies from qualified launch artifacts: a Node runtime and the scripts it runs > - Since #12699, Runner copies each artifact into a sealed memfd and checks its SHA-256 on every verification. This defends against a path swap or an in-place rewrite between the check and the exec > - On a hosted agent computer (4 vCPU), the copy and digest of the 127 MB Node takes about 0.26–0.30 s warm and about 1.2 s right after a wake. This is on the path from `session.open` to the sidecar spawn, and again on every warm `run.attach`. Each Runner also holds about 125 MiB of shmem for the copy > - On that computer, the artifacts live on the Runner ROM: a read-only erofs image that the deploy pins by digest. The threat that the memfd defends against does not exist there. On local hosts the artifacts are writable, so the memfd must stay > - This pull request adds an explicit, path-scoped, default-off `--trusted-launch-root `. Runner runs an artifact in place only when its open descriptor proves that it is on an immutable mount under that root. Everything else keeps the sealed, hashed snapshot > - The benefit is a shorter `session.open` and `run.attach` on agent computers, and about 125 MiB less shmem per Runner, with no change where the flag is absent ## Linked Issues or Issue Description **What existing behavior does this improve?** Launch-artifact verification in `paperclip-runnerd` (`qualified_launch.rs`). Its callers are the ACPX `verified_transport` (every `session_config`, including the park rebind) and the OpenCode and Cursor Cloud proxy launches. **Subsystem affected** Rust Runner (`packages/paperclip-runner/runner/crates/runner-core`). **Current behavior** Every verification opens the artifact, copies all bytes into a sealed memfd, and hashes them. Node is 127 MB. The cost is described in the Thinking Path. **Proposed behavior** When the host passes `--trusted-launch-root /opt/paperclip/runner` and the root passes its checks, Runner holds each admitted artifact open in place and executes it through `/proc/self/fd/N`. It does not copy or re-hash it. Without the flag, nothing changes. **Reason and benefit** See the Thinking Path. Refs #12699 (introduced the sealed memfd). Refs #20423 (overlap, see below). ## What Changed - `qualified_launch.rs`: new `TrustedLaunchRoot` and `set_trusted_launch_root` (process-global, set once at startup, like `--task-memory-cgroup`). - **Root checks at startup.** The path must be absolute, already canonical (no symlink or `..`), a directory, and on a read-only, exec-permitted erofs or squashfs mount. If a check fails, runnerd logs a warning and keeps today's behavior. - **Per-artifact checks, on the open descriptor.** After today's checks (regular file, not a symlink, not group- or world-writable, open-time identity), the descriptor must be a regular file on the root's device. Its kernel path (`readlink /proc/self/fd/N`) must lie under the root by path components, so `/opt/paperclip/runner2` does not match. Its mount must pass `fstatvfs` (`ST_RDONLY` set, `ST_NOEXEC` clear) and `fstatfs` (erofs or squashfs magic). If any check fails, Runner logs the reason and uses the sealed snapshot. - **Admitted artifacts** become `VerifiedProcessArtifact::in_place_on_trusted_root` (crate-private). The held file goes through the existing `inherited_artifact` path, so the exec is `/proc/self/fd/N` and `PAPERCLIP_VERIFIED_RUNTIME_EXECUTABLE` still names a descriptor that nested launches can reopen. - New `verify_assigned_executable_launch_artifact` never uses the root. `stdio_mcp.rs` now calls it, so host-assigned stdio MCP binaries always keep the sealed snapshot. - `paperclip-runnerd.rs`: parse `--trusted-launch-root `. Older runnerd builds ignore unknown flags, so a host can pass it before every Runner understands it. - The trusted path is Linux-only. On macOS and Windows, `TrustedLaunchRoot::open` always refuses. - `tests/runner-e2e/SECURITY.md`: documents how the Kimi and Pi provider-death fixtures behave under a trusted root. ### Decision: the trusted path drops the digest The trusted path does not hash the artifact, not even once per process: - The ROM image is pinned by digest at deploy time. - On the agent computer, the Launcher computes the expected `--acpx-sidecar-command-sha256` and `--acpx-sidecar-script-sha256` from the same ROM files immediately before it starts Runner. A re-hash of an immutable file can only repeat that result. - One hash per process would not help `session.open`, because each task starts a new Runner process. - The mount check is the guard: erofs and squashfs have no write path, so the bytes cannot change while the descriptor is open. ### Fixtures that assert the sealed memfd - Untrusted-mode assertions are unchanged. The fixtures do not pass the flag. - Kimi (`kimi-provider-fault.py` `checked_parent_descriptor`): with a trusted root, the parent descriptor is the ROM's Node file (one link). The existing linked-descriptor branch handles it: same inode as `/proc//exe`, and the complete bytes hashed against `nodeSha256`. That branch never accepts the file as a memfd. The existing test `test_linked_descriptor_keeps_regular_single_link_checks_without_memfd_claim` covers it. - Pi provider-death admission binds `/proc/self/fd/3|7` to the native distribution snapshot's Node. The TypeScript ACPX closure copies that file whether or not a trusted root is set, so the flag does not affect it. ### Overlap with #20423 #20423 (draft) moves the same copy and hash to Runner boot and reuses the result. Where this flag is set (Cloud agent computers), there is nothing left to precompute, so #20423 is mostly redundant there. #20423 still helps hosts without a trusted root (local and sandbox Runners). This PR does not change #20423. ## Verification All runs are on Linux (aarch64, Rust 1.97.1, in a container): - `cargo fmt --manifest-path runner/Cargo.toml --all -- --check` - `cargo check --manifest-path runner/Cargo.toml --locked --workspace` - `cargo test -p paperclip-runner-core --lib -- qualified_launch trusted_root commonjs`: 12 passed. The new tests are: - `an_artifact_under_an_immutable_trusted_root_runs_in_place_without_a_digest`: trusted-root hit, with no memfd, the same inode as the source, and no re-hash. - `an_artifact_outside_the_trusted_root_keeps_the_sealed_snapshot`: a path outside the root is sealed, and a wrong digest still fails. - `a_sibling_with_the_root_as_a_name_prefix_is_outside_the_root`: `rom2/` does not match `rom`. - `a_root_that_is_not_read_only_falls_back_to_the_sealed_snapshot`: the real probe refuses a writable root at startup. A per-artifact mount failure falls back, and a wrong digest still fails. - `the_real_mount_probe_rejects_a_writable_filesystem` - `symlink_and_parent_escapes_from_the_root_fall_back`: a directory symlink out of the root, a `..` path out of the root, and a final-component symlink (still refused). - `a_root_must_be_absolute_canonical_and_a_directory` - `without_a_trusted_root_launch_artifacts_are_sealed_and_hashed`: flag absent, behavior unchanged. - `host_assigned_executables_ignore_the_trusted_root` - `trusted_root_artifacts_execute_the_held_file_and_reopen_it_for_nested_launches`: Runner execs from the held file, and a child re-execs `$PAPERCLIP_VERIFIED_RUNTIME_EXECUTABLE`. Both report the source file as `/proc/self/exe`. - `cargo test -p paperclip-runner-core --test stdio_mcp --test process_supervisor`: 4 and 8 passed. - Ad hoc, not committed: a privileged container with a real loop-mounted squashfs. The real `fstatvfs`/`fstatfs` probe admitted a `ro` mount and refused a `ro,noexec` mount. The unit tests replace only that mount probe, because CI cannot mount filesystems. - Not verified: a run on an agent computer with the real erofs ROM, and the latency and memory savings there. The Cloud Launcher change that passes the flag is a separate follow-up. ## Risks - **This change needs review from a security owner before merge.** It removes the sealed copy and the per-launch digest for admitted artifacts. That relies on the host's assertion that the root is a digest-pinned immutable image, plus the descriptor checks above. - **Misconfiguration fails closed.** A wrong, writable, `noexec`, non-canonical or missing root only loses the speedup, and runnerd logs a warning. There is no global "trust everything" switch, and Runner never selects a root from the filesystem it finds. - **Residual trust.** On an admitted file, Runner no longer detects a ROM image that differs from what the launch profile expected. On the agent computer, the Launcher derives the expected digests from the same ROM. Another host that passes the flag must pin its image the same way. An attacker with root in the guest (who could write the backing block device or remount) is out of scope; such an attacker can already control runnerd. - **Allowlist.** Only erofs and squashfs are accepted, because they cannot be written through any mount. A read-only bind mount of a writable filesystem is refused. A ROM that changes to another filesystem type will silently fall back to the sealed path (slower, still safe). - No migration. Behavior is unchanged when the flag is absent. Older runnerd builds ignore the flag. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edits, container builds). Extended reasoning was on. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../runner-core/src/bin/paperclip-runnerd.rs | 18 + .../runner-core/src/process_supervisor.rs | 66 +++ .../runner-core/src/qualified_launch.rs | 464 +++++++++++++++++- .../crates/runner-core/src/stdio_mcp.rs | 6 +- tests/runner-e2e/SECURITY.md | 10 + 5 files changed, 559 insertions(+), 5 deletions(-) diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/bin/paperclip-runnerd.rs b/packages/paperclip-runner/runner/crates/runner-core/src/bin/paperclip-runnerd.rs index 1241f1c5843..6d5ffa68fbf 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/bin/paperclip-runnerd.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/bin/paperclip-runnerd.rs @@ -559,6 +559,23 @@ fn apply_oom_score_adj(args: &[String]) -> Result<(), LocalRunnerError> { Ok(()) } +/// `--trusted-launch-root `: the host asserts that `` is an +/// immutable, digest-pinned image (the agent computer's Runner ROM). Launch +/// artifacts the root admits run in place instead of from a sealed copy. A root +/// that fails its startup checks only loses that speedup, never protection. +fn apply_trusted_launch_root(args: &[String]) -> Result<(), LocalRunnerError> { + let Some(path) = optional_value(args, "--trusted-launch-root")? else { + return Ok(()); + }; + match paperclip_runner_core::qualified_launch::TrustedLaunchRoot::open(Path::new(&path)) { + Ok(root) => paperclip_runner_core::qualified_launch::set_trusted_launch_root(root), + Err(reason) => eprintln!( + "paperclip-runnerd: ignoring --trusted-launch-root {path}: {reason}; launch artifacts keep sealed snapshots" + ), + } + Ok(()) +} + fn apply_task_memory_cgroup(args: &[String]) -> Result<(), LocalRunnerError> { if let Some(path) = optional_value(args, "--task-memory-cgroup")? { paperclip_runner_core::task_memory::set_task_cgroup(PathBuf::from(path)); @@ -640,6 +657,7 @@ fn run(args: &[String]) -> Result<(), LocalRunnerError> { } apply_oom_score_adj(args)?; apply_task_memory_cgroup(args)?; + apply_trusted_launch_root(args)?; if args.iter().any(|argument| argument == "--connect-url") || args.iter().any(|argument| argument == "--listen-address") || args.iter().any(|argument| argument == "--listen-port") diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/process_supervisor.rs b/packages/paperclip-runner/runner/crates/runner-core/src/process_supervisor.rs index 64d27043b29..e479e5247e9 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/process_supervisor.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/process_supervisor.rs @@ -102,6 +102,26 @@ impl VerifiedProcessArtifact { #[cfg(not(target_os = "macos"))] Self::snapshot_verified(display_path, file, expected_sha256) } + + /// Hold a launch artifact open in place instead of snapshotting it. + /// + /// Only `qualified_launch` calls this, and only after the trusted launch + /// root proved that this open descriptor itself lies on an immutable + /// mount under that root. The process then executes this descriptor + /// through `/proc/self/fd/N`, so a later path swap cannot change what + /// runs and nested launches reopen the same file. + #[cfg(target_os = "linux")] + pub(crate) fn in_place_on_trusted_root(display_path: PathBuf, file: File) -> Self { + Self { + display_path, + file: Arc::new(file), + } + } + + #[cfg(test)] + pub(crate) fn held_file(&self) -> &File { + &self.file + } } #[cfg(target_os = "macos")] @@ -2013,6 +2033,52 @@ mod tests { fs::remove_dir_all(directory).unwrap(); } + #[cfg(target_os = "linux")] + #[test] + fn trusted_root_artifacts_execute_the_held_file_and_reopen_it_for_nested_launches() { + let nonce = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + let directory = std::env::temp_dir().join(format!( + "paperclip-trusted-root-launch-{}-{nonce}", + std::process::id() + )); + fs::create_dir_all(&directory).unwrap(); + let shell = fs::canonicalize(directory.join(".")).unwrap().join("sh"); + fs::copy(fs::canonicalize("/bin/sh").unwrap(), &shell).unwrap(); + let program = VerifiedProcessArtifact::in_place_on_trusted_root( + shell.clone(), + File::open(&shell).unwrap(), + ); + let launch = VerifiedProcessLaunch::new( + program, + vec![ + VerifiedProcessArgument::Literal("-c".to_owned()), + VerifiedProcessArgument::Literal(format!( + "readlink /proc/$$/exe; \"${VERIFIED_RUNTIME_EXECUTABLE_ENV}\" -c 'readlink /proc/$$/exe'" + )), + ], + ); + + let inherited = launch.inherited_command().unwrap(); + assert!(inherited.program.starts_with("/proc/self/fd/")); + let output = Command::new(&inherited.program) + .args(&inherited.args) + .env(VERIFIED_RUNTIME_EXECUTABLE_ENV, &inherited.program) + .output() + .unwrap(); + drop(inherited); + + assert!(output.status.success(), "{output:?}"); + let expected = format!("{}\n", shell.display()); + assert_eq!( + String::from_utf8(output.stdout).unwrap(), + expected.repeat(2) + ); + fs::remove_dir_all(directory).unwrap(); + } + #[cfg(target_os = "macos")] #[test] fn executable_arguments_use_the_private_nested_launch_contract() { diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/qualified_launch.rs b/packages/paperclip-runner/runner/crates/runner-core/src/qualified_launch.rs index 570080ff877..c65f07b3379 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/qualified_launch.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/qualified_launch.rs @@ -1,4 +1,6 @@ use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; #[cfg(unix)] use std::os::unix::fs::{MetadataExt, PermissionsExt}; @@ -6,24 +8,210 @@ use std::os::unix::fs::{MetadataExt, PermissionsExt}; use crate::durable::{DurableRunnerError, QualifiedLaunchArtifact}; use crate::process_supervisor::VerifiedProcessArtifact; +static TRUSTED_LAUNCH_ROOT: OnceLock = OnceLock::new(); + +/// Set once at startup from `--trusted-launch-root`. Without it, every launch +/// artifact is copied into a sealed snapshot and hashed, as before. +pub fn set_trusted_launch_root(root: TrustedLaunchRoot) { + let _ = TRUSTED_LAUNCH_ROOT.set(root); +} + +/// A directory the host asserts is an immutable, digest-pinned image, such as +/// the agent computer's Runner ROM. Runner-owned launch artifacts whose open +/// descriptor lies on that image are executed in place: no sealed copy and no +/// per-launch digest. Anything the root does not admit keeps the sealed copy. +/// +/// The assertion is explicit and path-scoped. Admission still proves, from the +/// open descriptor, that the file is inside the root and on a read-only, +/// exec-permitted mount of a filesystem that cannot be written at all (erofs or +/// squashfs). A misconfigured root therefore only loses the speedup. +#[derive(Debug)] +pub struct TrustedLaunchRoot { + path: PathBuf, + #[cfg(target_os = "linux")] + device: u64, + #[cfg(target_os = "linux")] + immutable_mount: fn(&File) -> std::io::Result, +} + +impl TrustedLaunchRoot { + /// Accept a root only when it is absolute, already canonical (no symlink + /// or `..` component) and itself on an immutable mount. + pub fn open(path: &Path) -> Result { + #[cfg(target_os = "linux")] + { + Self::open_with_mount_check(path, immutable_exec_mount) + } + #[cfg(not(target_os = "linux"))] + { + let _ = path; + Err("trusted launch roots are supported only on Linux".to_owned()) + } + } + + #[cfg(target_os = "linux")] + fn open_with_mount_check( + path: &Path, + immutable_mount: fn(&File) -> std::io::Result, + ) -> Result { + if !path.is_absolute() { + return Err("trusted launch root must be an absolute path".to_owned()); + } + let canonical = fs::canonicalize(path) + .map_err(|error| format!("trusted launch root cannot be resolved: {error}"))?; + if canonical != path { + return Err("trusted launch root must not contain symlinks or `..`".to_owned()); + } + let directory = File::open(&canonical) + .map_err(|error| format!("trusted launch root cannot be opened: {error}"))?; + let metadata = directory + .metadata() + .map_err(|error| format!("trusted launch root cannot be inspected: {error}"))?; + if !metadata.is_dir() { + return Err("trusted launch root must be a directory".to_owned()); + } + if !immutable_mount(&directory).unwrap_or(false) { + return Err( + "trusted launch root is not on a read-only, exec-permitted erofs or squashfs mount" + .to_owned(), + ); + } + Ok(Self { + path: canonical, + device: metadata.dev(), + immutable_mount, + }) + } + + pub fn path(&self) -> &Path { + &self.path + } + + /// Decide from the open descriptor alone, never from the name it was + /// opened by: the kernel's path for the descriptor must lie under the + /// root, on the root's filesystem, and that mount must be immutable. + #[cfg(target_os = "linux")] + fn admits(&self, file: &File) -> Result<(), &'static str> { + use std::os::fd::AsRawFd; + + let metadata = file.metadata().map_err(|_| "cannot inspect descriptor")?; + if !metadata.is_file() { + return Err("not a regular file"); + } + if metadata.dev() != self.device { + return Err("not on the trusted root's filesystem"); + } + let held = fs::read_link(format!("/proc/self/fd/{}", file.as_raw_fd())) + .map_err(|_| "cannot resolve descriptor")?; + if !held.is_absolute() + || held + .components() + .any(|component| matches!(component, std::path::Component::ParentDir)) + || !held.starts_with(&self.path) + || held == self.path + { + return Err("outside the trusted root"); + } + if !(self.immutable_mount)(file).unwrap_or(false) { + return Err("not on a read-only, exec-permitted erofs or squashfs mount"); + } + Ok(()) + } +} + +/// erofs and squashfs have no write path at all, so a read-only mount of one +/// cannot change underneath an open descriptor, not even through another +/// mount of the same superblock. +#[cfg(target_os = "linux")] +fn immutable_exec_mount(file: &File) -> std::io::Result { + use rustix::fs::StatVfsMountFlags; + const EROFS_SUPER_MAGIC_V1: u32 = 0xE0F5_E1E2; + const SQUASHFS_MAGIC: u32 = 0x7371_7368; + + let mount = rustix::fs::fstatvfs(file)?; + if !mount.f_flag.contains(StatVfsMountFlags::RDONLY) + || mount.f_flag.contains(StatVfsMountFlags::NOEXEC) + { + return Ok(false); + } + // `f_type` is signed or unsigned, 32 or 64 bits, by architecture. The + // magic numbers are 32-bit, so compare the low word. + #[allow(clippy::unnecessary_cast)] + let filesystem = rustix::fs::fstatfs(file)?.f_type as u32; + Ok(matches!(filesystem, EROFS_SUPER_MAGIC_V1 | SQUASHFS_MAGIC)) +} + +/// Who chose an artifact. Only Runner-owned launch-profile artifacts may use +/// the trusted launch root. +#[derive(Clone, Copy)] +enum ArtifactOwner { + Runner, + HostAssigned, +} + +/// A Runner-owned artifact (provider runtime, sidecar or proxy) pinned by the +/// launch profile. It may run in place from the trusted launch root. pub fn verify_launch_artifact( artifact: &QualifiedLaunchArtifact, label: &str, ) -> Result { - verify_launch_artifact_with_role(artifact, label, false) + verify_owned( + artifact, + label, + false, + ArtifactOwner::Runner, + TRUSTED_LAUNCH_ROOT.get(), + ) } +/// The executable counterpart of [`verify_launch_artifact`]. pub fn verify_executable_launch_artifact( artifact: &QualifiedLaunchArtifact, label: &str, ) -> Result { - verify_launch_artifact_with_role(artifact, label, true) + verify_owned( + artifact, + label, + true, + ArtifactOwner::Runner, + TRUSTED_LAUNCH_ROOT.get(), + ) +} + +/// A host-assigned executable, such as a stdio MCP server. It is always +/// snapshotted and hashed, whatever the trusted launch root. +pub fn verify_assigned_executable_launch_artifact( + artifact: &QualifiedLaunchArtifact, + label: &str, +) -> Result { + verify_owned( + artifact, + label, + true, + ArtifactOwner::HostAssigned, + TRUSTED_LAUNCH_ROOT.get(), + ) +} + +fn verify_owned( + artifact: &QualifiedLaunchArtifact, + label: &str, + executable: bool, + owner: ArtifactOwner, + configured_root: Option<&TrustedLaunchRoot>, +) -> Result { + let trusted_root = match owner { + ArtifactOwner::Runner => configured_root, + ArtifactOwner::HostAssigned => None, + }; + verify_launch_artifact_with_role(artifact, label, executable, trusted_root) } fn verify_launch_artifact_with_role( artifact: &QualifiedLaunchArtifact, label: &str, executable: bool, + trusted_root: Option<&TrustedLaunchRoot>, ) -> Result { let source_metadata = fs::symlink_metadata(&artifact.path).map_err(|error| { DurableRunnerError::invalid(format!("failed to inspect qualified {label}: {error}")) @@ -64,6 +252,24 @@ fn verify_launch_artifact_with_role( "qualified {label} changed while it was opened" ))); } + #[cfg(target_os = "linux")] + if let Some(root) = trusted_root { + match root.admits(&file) { + // The image is immutable and pinned by digest where it is + // deployed, so re-hashing it here could only repeat that check. + Ok(()) => { + return Ok(VerifiedProcessArtifact::in_place_on_trusted_root( + canonical, file, + )) + } + Err(reason) => eprintln!( + "paperclip-runnerd: qualified {label} is not admitted by trusted launch root {} ({reason}); using a sealed snapshot", + root.path.display() + ), + } + } + #[cfg(not(target_os = "linux"))] + let _ = trusted_root; let snapshot = if executable { VerifiedProcessArtifact::snapshot_verified_executable(canonical, file, &artifact.sha256) } else { @@ -87,3 +293,257 @@ fn same_file(left: &fs::Metadata, right: &fs::Metadata) -> bool { && left.modified().ok() == right.modified().ok() && left.is_file() == right.is_file() } + +#[cfg(all(test, target_os = "linux"))] +mod tests { + use super::*; + use sha2::{Digest, Sha256}; + use std::time::{SystemTime, UNIX_EPOCH}; + + // A writable temporary directory stands in for the ROM. These checks + // replace only the mount-type probe; path, device and descriptor checks + // stay real. + fn immutable(_: &File) -> std::io::Result { + Ok(true) + } + + fn writable(_: &File) -> std::io::Result { + Ok(false) + } + + struct Fixture { + root: PathBuf, + } + + impl Fixture { + fn new(name: &str) -> Self { + let root = std::env::temp_dir().join(format!( + "paperclip-trusted-launch-root-{name}-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + fs::create_dir_all(root.join("rom/libexec")).unwrap(); + fs::create_dir_all(root.join("outside")).unwrap(); + Self { + root: fs::canonicalize(root).unwrap(), + } + } + + fn rom(&self) -> PathBuf { + self.root.join("rom") + } + + fn artifact(&self, path: PathBuf, bytes: &[u8]) -> QualifiedLaunchArtifact { + fs::write(&path, bytes).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap(); + QualifiedLaunchArtifact { + path, + sha256: format!("sha256:{:x}", Sha256::digest(bytes)), + } + } + } + + impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.root); + } + } + + fn sealed(artifact: &VerifiedProcessArtifact) -> bool { + let file = artifact.held_file(); + let link = fs::read_link(format!( + "/proc/self/fd/{}", + std::os::fd::AsRawFd::as_raw_fd(file) + )) + .unwrap(); + file.metadata().unwrap().nlink() == 0 + && link + .to_string_lossy() + .starts_with("/memfd:paperclip-verified-launch") + } + + fn same_inode(artifact: &VerifiedProcessArtifact, path: &Path) -> bool { + let held = artifact.held_file().metadata().unwrap(); + let named = fs::metadata(path).unwrap(); + held.dev() == named.dev() && held.ino() == named.ino() + } + + #[test] + fn an_artifact_under_an_immutable_trusted_root_runs_in_place_without_a_digest() { + let fixture = Fixture::new("hit"); + let root = TrustedLaunchRoot::open_with_mount_check(&fixture.rom(), immutable).unwrap(); + let mut artifact = fixture.artifact(fixture.rom().join("libexec/node"), b"node"); + // The trusted path does not re-hash: a wrong expected digest still + // admits, because the image itself is the pinned authority. + artifact.sha256 = "sha256:not-rehashed".to_owned(); + + let verified = + verify_launch_artifact_with_role(&artifact, "test", true, Some(&root)).unwrap(); + + assert!(!sealed(&verified)); + assert!(same_inode(&verified, &artifact.path)); + } + + #[test] + fn an_artifact_outside_the_trusted_root_keeps_the_sealed_snapshot() { + let fixture = Fixture::new("outside"); + let root = TrustedLaunchRoot::open_with_mount_check(&fixture.rom(), immutable).unwrap(); + let artifact = fixture.artifact(fixture.root.join("outside/node"), b"node"); + + let verified = + verify_launch_artifact_with_role(&artifact, "test", true, Some(&root)).unwrap(); + assert!(sealed(&verified)); + + let mut tampered = artifact.clone(); + tampered.sha256 = "sha256:wrong".to_owned(); + assert!(verify_launch_artifact_with_role(&tampered, "test", true, Some(&root)).is_err()); + } + + #[test] + fn a_sibling_with_the_root_as_a_name_prefix_is_outside_the_root() { + let fixture = Fixture::new("prefix"); + fs::create_dir_all(fixture.root.join("rom2")).unwrap(); + let root = TrustedLaunchRoot::open_with_mount_check(&fixture.rom(), immutable).unwrap(); + let artifact = fixture.artifact(fixture.root.join("rom2/node"), b"node"); + + let verified = + verify_launch_artifact_with_role(&artifact, "test", false, Some(&root)).unwrap(); + assert!(sealed(&verified)); + } + + #[test] + fn a_root_that_is_not_read_only_falls_back_to_the_sealed_snapshot() { + let fixture = Fixture::new("writable"); + // The real probe rejects a writable temporary directory at startup. + assert!(TrustedLaunchRoot::open(&fixture.rom()).is_err()); + + // A mount that stops being immutable after startup is rejected per + // artifact, from the open descriptor. + let mut root = TrustedLaunchRoot::open_with_mount_check(&fixture.rom(), immutable).unwrap(); + root.immutable_mount = writable; + let artifact = fixture.artifact(fixture.rom().join("libexec/node"), b"node"); + let verified = + verify_launch_artifact_with_role(&artifact, "test", true, Some(&root)).unwrap(); + assert!(sealed(&verified)); + + let mut tampered = artifact.clone(); + tampered.sha256 = "sha256:wrong".to_owned(); + assert!(verify_launch_artifact_with_role(&tampered, "test", true, Some(&root)).is_err()); + } + + #[test] + fn the_real_mount_probe_rejects_a_writable_filesystem() { + let fixture = Fixture::new("probe"); + let file = File::open(fixture.artifact(fixture.rom().join("node"), b"node").path).unwrap(); + assert!(!immutable_exec_mount(&file).unwrap()); + } + + #[test] + fn symlink_and_parent_escapes_from_the_root_fall_back() { + let fixture = Fixture::new("escape"); + let root = TrustedLaunchRoot::open_with_mount_check(&fixture.rom(), immutable).unwrap(); + let outside = fixture.artifact(fixture.root.join("outside/node"), b"node"); + + // A directory symlink inside the root that points outside it. + std::os::unix::fs::symlink(fixture.root.join("outside"), fixture.rom().join("escape")) + .unwrap(); + let through_link = QualifiedLaunchArtifact { + path: fixture.rom().join("escape/node"), + sha256: outside.sha256.clone(), + }; + let verified = + verify_launch_artifact_with_role(&through_link, "test", true, Some(&root)).unwrap(); + assert!(sealed(&verified)); + + // A `..` path that starts under the root and leaves it. + let dotted = QualifiedLaunchArtifact { + path: fixture.rom().join("libexec/../../outside/node"), + sha256: outside.sha256.clone(), + }; + let verified = + verify_launch_artifact_with_role(&dotted, "test", true, Some(&root)).unwrap(); + assert!(sealed(&verified)); + + // A final-component symlink is still refused outright. + std::os::unix::fs::symlink(&outside.path, fixture.rom().join("libexec/link")).unwrap(); + let linked = QualifiedLaunchArtifact { + path: fixture.rom().join("libexec/link"), + sha256: outside.sha256, + }; + assert!(verify_launch_artifact_with_role(&linked, "test", true, Some(&root)).is_err()); + } + + #[test] + fn a_root_must_be_absolute_canonical_and_a_directory() { + let fixture = Fixture::new("root-shape"); + std::os::unix::fs::symlink(fixture.rom(), fixture.root.join("alias")).unwrap(); + for candidate in [ + PathBuf::from("relative/rom"), + fixture.root.join("alias"), + fixture.rom().join("libexec/.."), + fixture.root.join("missing"), + ] { + assert!( + TrustedLaunchRoot::open_with_mount_check(&candidate, immutable).is_err(), + "{}", + candidate.display() + ); + } + let file = fixture + .artifact(fixture.rom().join("libexec/node"), b"node") + .path; + assert!(TrustedLaunchRoot::open_with_mount_check(&file, immutable).is_err()); + } + + #[test] + fn without_a_trusted_root_launch_artifacts_are_sealed_and_hashed() { + let fixture = Fixture::new("absent"); + let artifact = fixture.artifact(fixture.rom().join("libexec/node"), b"node"); + + assert!(TRUSTED_LAUNCH_ROOT.get().is_none()); + assert!(sealed(&verify_launch_artifact(&artifact, "test").unwrap())); + assert!(sealed( + &verify_executable_launch_artifact(&artifact, "test").unwrap() + )); + + let mut tampered = artifact; + tampered.sha256 = "sha256:wrong".to_owned(); + assert!(verify_launch_artifact(&tampered, "test").is_err()); + } + + #[test] + fn host_assigned_executables_ignore_the_trusted_root() { + let fixture = Fixture::new("assigned"); + let root = TrustedLaunchRoot::open_with_mount_check(&fixture.rom(), immutable).unwrap(); + let artifact = fixture.artifact(fixture.rom().join("libexec/mcp"), b"mcp"); + + // The same configured root admits this file for a Runner-owned launch. + let runner = + verify_owned(&artifact, "test", true, ArtifactOwner::Runner, Some(&root)).unwrap(); + assert!(!sealed(&runner)); + + // A host-assigned executable at the same path stays sealed and hashed. + let assigned = verify_owned( + &artifact, + "test", + true, + ArtifactOwner::HostAssigned, + Some(&root), + ) + .unwrap(); + assert!(sealed(&assigned)); + let mut tampered = artifact; + tampered.sha256 = "sha256:wrong".to_owned(); + assert!(verify_owned( + &tampered, + "test", + true, + ArtifactOwner::HostAssigned, + Some(&root), + ) + .is_err()); + } +} diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/stdio_mcp.rs b/packages/paperclip-runner/runner/crates/runner-core/src/stdio_mcp.rs index 7f580ea20a3..c530f6a82c8 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/stdio_mcp.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/stdio_mcp.rs @@ -15,7 +15,7 @@ use sha2::{Digest, Sha256}; use crate::durable::QualifiedLaunchArtifact; use crate::local_runner::LocalRunnerError; use crate::process_supervisor::{VerifiedProcessArgument, VerifiedProcessLaunch}; -use crate::qualified_launch::verify_executable_launch_artifact; +use crate::qualified_launch::verify_assigned_executable_launch_artifact; pub const BINDINGS_ENV: &str = "PAPERCLIP_NATIVE_MCP_STDIO"; pub const PROXY_ENV: &str = "PAPERCLIP_NATIVE_MCP_PROXY"; @@ -67,7 +67,7 @@ impl StdioMcpBinding { { return Err(invalid("invalid assigned stdio MCP binding")); } - verify_executable_launch_artifact( + verify_assigned_executable_launch_artifact( &QualifiedLaunchArtifact { path: self.command.clone(), sha256: self.sha256.clone(), @@ -271,7 +271,7 @@ pub fn run_proxy(path: &Path, content_images: bool) -> McpResult<()> { .map_err(|_| invalid("invalid stdio MCP configuration"))?; binding.validate()?; let (mut lock, resource_identity) = resource_lock(&binding.serial_resource)?; - let program = verify_executable_launch_artifact( + let program = verify_assigned_executable_launch_artifact( &QualifiedLaunchArtifact { path: binding.command.clone(), sha256: binding.sha256.clone(), diff --git a/tests/runner-e2e/SECURITY.md b/tests/runner-e2e/SECURITY.md index d186c8855de..709101ef64a 100644 --- a/tests/runner-e2e/SECURITY.md +++ b/tests/runner-e2e/SECURITY.md @@ -588,6 +588,16 @@ foreign inodes fail before any signal. Native Linux calibration exercises both descriptor launches with synthetic owned processes and no provider credentials; it does not qualify paid Pi behavior or change previous failed grades. +These fixtures run without `paperclip-runnerd --trusted-launch-root`, so the +Runner still hands providers a sealed memfd Node and the memfd assertions above +are unchanged. Under a trusted launch root (the agent computer's read-only Runner +ROM) the Runner instead holds the ROM's own Node file. Kimi admission then takes +its existing linked-descriptor branch: one link, the same inode as the parent's +`/proc//exe`, and the complete bytes hashed against `nodeSha256`. It never +accepts that file as a memfd. Pi admission binds to the native distribution +snapshot's Node, which the ACPX closure copies whether or not a trusted root is +set. + The private resource-admission marker and raw cleanup results control recovery-state retention independently of evidence packaging. A worker crash after admission keeps the owner-only recovery database; a confirmed pre-allocation bootstrap failure does not. Neither the marker nor the database enters published evidence. ## Task workspace fixture source From 4608744977cc64da1bd630c10557b96d6925fe4a Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 9 Nov 2026 19:49:00 -0600 Subject: [PATCH 08/10] fix(workspaces): preserve recovery for verified archived Git sources (#20436) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Durable workspace migration must retain saved Git files and pending native recovery. > - The archived-Git owner validates saved recipes, exact cleanup receipts, and surviving owned branches. > - Online recovery preservation currently accepts only the recipe variant. > - A valid cleanup receipt or owned branch therefore cannot migrate while an old native reference is still prepared. > - This pull request admits every verified archived-Git variant through the same recovery and finalization locks. > - Tasks stay done and keep their selected workspace, history, and pending provider obligations. ## Linked Issues or Issue Description Refs #20424, #20298, and #20418. The related cleanup work in #19812 does not cover this admission gap. **What happened?** Canonical inspection accepts the exact old commit of an archived Git workspace through a valid branch-deletion receipt or an owned surviving branch. Migration still reports `remote_copyback_unresolved` when a terminal native run retains a prepared reference. A read-only staging inventory reproduced this sole blocker for four such workspaces. Their original Git objects and canonical source proofs already exist. **Expected behavior** Preserve the verified Git baseline and every typed native/provider recovery obligation through the existing migration owner. Keep the task status, selection, history, archive state, and recovery records unchanged. Do not reopen the task or substitute the current default branch. **Steps to reproduce** 1. Save a clean archived Git workspace with an authentic cleanup receipt or a surviving owned branch, without a restore recipe. 2. Retain a terminal prepared native reference and its exact provider allocation and recovery action. 3. Remove the old task worktree. 4. Call `migrateRemoteWorkspace` online. **Paperclip version or commit** Reproduced on merged #20424, `915edcff49bb2cbacfbaee604b41e082e0397109`. **Deployment mode** Self-hosted server with PostgreSQL and configured object storage. ## What Changed - Change three conditions to accept a non-null canonical archived-Git source instead of requiring its recipe field. - Use the same typed recovery inspector, sorted native finalization locks, fresh reinspection, and source-task publication locks for all accepted variants. - Reuse the existing Git source validator, private scratch materializer, encrypted snapshot restore, journal, and recovery markers. No source-proof schema or provider protocol changes. - Extend the existing real fixture for cleanup receipts and retained branches. Verify exact old Git commits and unchanged task/recovery state. Refuse receipt revocation and branch movement during upload. ## Verification - Genuine RED on merged #20424: both new source-kind cases fail with `remote_workspace_migration_blocked:remote_copyback_unresolved,workspace_recovery_unresolved`. - GREEN: nine focused PostgreSQL/Git/encrypted-storage cases pass. They include both new variants, two actual upload-time source mutations, the existing recipe interrupted-journal resume, reference/provider mutations, and a competing native finalization owner. - Command: `pnpm exec vitest run server/src/services/remote-workspace-migration.test.ts -t 'no-recipe archived|unselected archived recipe|archived prepared source|competing native F owner'`. - All nine focused cases, server typecheck layers, module boundaries, and whitespace checks pass on exact published head `03065f97b31846a405a8911c30640ef62374e4a4`, after the clean rebase onto merged #20418. Required CI is now clean on this exact head:56 SUCCESS and4 expected SKIPPED checks, with no pending or failed checks. Fresh Greptile is5/5 with no actionable findings or unresolved threads. - Previous-release state: existing cleanup receipts, owned branches, prepared v3 references, and journal shapes carry forward unchanged. Saved snapshots and source identities retain their existing owners. Unrecognized or changed sources still refuse by the existing named errors. Migration does not declare remote files recovered or provider allocations stopped. - Hosted work in this PR was read-only source inspection and inventory. No staging import, source mutation, lifecycle reopen, or provider call was performed by this PR author. ## Risks The existing archived-Git validator now admits its other verified variants to recovery preservation. Incorrect source proof could publish incomplete authority. This PR keeps its exact commit/receipt/branch checks and full authenticated capture/readback. It also keeps all native ownership, reference, allocation, and publication checks. Missing or changed sources remain blocked, and pending remote data retains its original recovery obligation. ## Model Used OpenAI Codex, GPT-6, with reasoning, repository tools, and code execution. The runtime does not expose a deployment suffix or context-window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip --- .../remote-workspace-migration.test.ts | 103 +++++++++++++----- .../services/remote-workspace-migration.ts | 6 +- 2 files changed, 81 insertions(+), 28 deletions(-) diff --git a/server/src/services/remote-workspace-migration.test.ts b/server/src/services/remote-workspace-migration.test.ts index c31fad595eb..6ea398b49ae 100644 --- a/server/src/services/remote-workspace-migration.test.ts +++ b/server/src/services/remote-workspace-migration.test.ts @@ -637,28 +637,42 @@ describe.skipIf(!support.supported)("remote workspace migration", () => { branchName, strategyType: "git_worktree", providerType: "git_worktree", metadata: { createdByRuntime: true, gitBranchOwnershipVersion: 1 } }).where(eq(executionWorkspaces.id, f.workspaceId)); return { ...f, cwd, base, upstream, commit, projectId, projectWorkspaceId, repoUrl, branchName }; } - async function archivedPreparedFixture() { + async function archivedPreparedFixture(sourceKind: "recipe" | "cleanup" | "branch" = "recipe") { const base = await gitArchiveFixture(), f = { ...base, ...await failedCopybackFixture(base) }; - await fs.writeFile(path.join(f.cwd, "saved.txt"), "archived staged edit\n"); await git(f.cwd, "add", "saved.txt"); - await fs.writeFile(path.join(f.cwd, "saved.txt"), "archived unstaged edit\n"); - await fs.writeFile(path.join(f.cwd, "untracked.txt"), "archived private file\n"); - const captured = (await captureRestorePoint({ cwd: f.cwd, upstreamCommits: [f.upstream] }))!; - const id = randomUUID(), generation = 1, sealed = await sealRestorePoint(captured.payload, - { companyId: f.companyId, workspaceId: f.workspaceId, restorePointId: id, generation }); - const objectKey = `${f.companyId}/git-restore-points/${f.workspaceId}/${generation}/${id}.pcrp`; - await storage.putFile({ companyId: f.companyId, namespace: "git-restore-points", objectKey, - originalFilename: "saved.pcrp", contentType: "application/octet-stream", body: sealed.ciphertext }); - const restorePoint = { schema: "paperclip.git-restore-point.v1", id, generation, objectKey, byteSize: sealed.ciphertext.length, - sha256: sealed.sha256, key: sealed.key, head: captured.manifest.head, index: captured.manifest.index, - worktree: captured.manifest.worktree, ignored: captured.manifest.ignored, modes: captured.manifest.modes, headOnRemote: false }; - const contents = await captureGitWorkspaceContents(f.cwd, { companyId: f.companyId, workspaceId: f.workspaceId }, []); - await db.update(executionWorkspaces).set({ status: "archived", closedAt: new Date(), metadata: { - createdByRuntime: true, gitBranchOwnershipVersion: 1, gitCacheRestoration: { schema: "paperclip.git-cache-restoration.v2", - companyId: f.companyId, workspaceId: f.workspaceId, sourceIssueId: f.issueId, repoUrl: f.repoUrl, - commit: f.commit, branchName: f.branchName, sourceKind: "managed_project", projectId: f.projectId, - sourcePath: f.base, worktreePath: f.cwd, gitBranchOwnershipVersion: 1, verifiedAt: new Date().toISOString(), restorePoint, contents }, - } }).where(eq(executionWorkspaces.id, f.workspaceId)); - await git(f.base, "worktree", "remove", "--force", f.cwd); await git(f.base, "branch", "-D", f.branchName); + let cleanup: typeof workspaceOperations.$inferSelect | null = null; + if (sourceKind === "recipe") { + await fs.writeFile(path.join(f.cwd, "saved.txt"), "archived staged edit\n"); await git(f.cwd, "add", "saved.txt"); + await fs.writeFile(path.join(f.cwd, "saved.txt"), "archived unstaged edit\n"); + await fs.writeFile(path.join(f.cwd, "untracked.txt"), "archived private file\n"); + const captured = (await captureRestorePoint({ cwd: f.cwd, upstreamCommits: [f.upstream] }))!; + const id = randomUUID(), generation = 1, sealed = await sealRestorePoint(captured.payload, + { companyId: f.companyId, workspaceId: f.workspaceId, restorePointId: id, generation }); + const objectKey = `${f.companyId}/git-restore-points/${f.workspaceId}/${generation}/${id}.pcrp`; + await storage.putFile({ companyId: f.companyId, namespace: "git-restore-points", objectKey, + originalFilename: "saved.pcrp", contentType: "application/octet-stream", body: sealed.ciphertext }); + const restorePoint = { schema: "paperclip.git-restore-point.v1", id, generation, objectKey, byteSize: sealed.ciphertext.length, + sha256: sealed.sha256, key: sealed.key, head: captured.manifest.head, index: captured.manifest.index, + worktree: captured.manifest.worktree, ignored: captured.manifest.ignored, modes: captured.manifest.modes, headOnRemote: false }; + const contents = await captureGitWorkspaceContents(f.cwd, { companyId: f.companyId, workspaceId: f.workspaceId }, []); + await db.update(executionWorkspaces).set({ status: "archived", closedAt: new Date(), metadata: { + createdByRuntime: true, gitBranchOwnershipVersion: 1, gitCacheRestoration: { schema: "paperclip.git-cache-restoration.v2", + companyId: f.companyId, workspaceId: f.workspaceId, sourceIssueId: f.issueId, repoUrl: f.repoUrl, + commit: f.commit, branchName: f.branchName, sourceKind: "managed_project", projectId: f.projectId, + sourcePath: f.base, worktreePath: f.cwd, gitBranchOwnershipVersion: 1, verifiedAt: new Date().toISOString(), restorePoint, contents }, + } }).where(eq(executionWorkspaces.id, f.workspaceId)); + await git(f.base, "worktree", "remove", "--force", f.cwd); await git(f.base, "branch", "-D", f.branchName); + } else { + await db.update(executionWorkspaces).set({ status: "archived", closedAt: new Date() }).where(eq(executionWorkspaces.id, f.workspaceId)); + if (sourceKind === "cleanup") await git(f.base, "merge", "--ff-only", f.branchName); + await git(f.base, "worktree", "remove", f.cwd); + if (sourceKind === "cleanup") { + const receipt = await git(f.base, "branch", "-d", f.branchName); + [cleanup] = await db.insert(workspaceOperations).values({ companyId: f.companyId, executionWorkspaceId: f.workspaceId, + phase: "worktree_cleanup", status: "succeeded", exitCode: 0, command: `git branch -d ${f.branchName}`, + cwd: f.base, stdoutExcerpt: receipt, startedAt: new Date(), finishedAt: new Date(), + metadata: { cleanupAction: "branch_delete", workspaceId: f.workspaceId, workspacePath: f.cwd, branchName: f.branchName } }).returning(); + } + } const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); const [environment] = await db.insert(environments).values({ name: f.runId, driver: "daytona" }).returning(); const [lease] = await db.insert(environmentLeases).values({ id: f.reference.leaseId, companyId: f.companyId, @@ -670,16 +684,55 @@ describe.skipIf(!support.supported)("remote workspace migration", () => { const [hold] = await db.insert(issueRecoveryActions).values({ companyId: f.companyId, sourceIssueId: f.issueId, kind: "active_run_watchdog", cause, ownerType: "board", ownerAgentId: null, returnOwnerAgentId: run.agentId, fingerprint: nativeSha256({ runId: f.runId, failureCode: cause }), nextAction: "Preserve retained remote files", evidence: { runId: f.runId } }).returning(); - const [selected] = await db.insert(executionWorkspaces).values({ companyId: f.companyId, sourceIssueId: f.issueId, - name: "Current task workspace", providerType: "local_fs", mode: "isolated_workspace", strategyType: "project_primary", cwd: path.join(root, "current-task") }).returning(); - await db.update(issues).set({ status: "cancelled", executionWorkspaceId: selected.id }).where(eq(issues.id, f.issueId)); + if (sourceKind === "recipe") { + const [selected] = await db.insert(executionWorkspaces).values({ companyId: f.companyId, sourceIssueId: f.issueId, + name: "Current task workspace", providerType: "local_fs", mode: "isolated_workspace", strategyType: "project_primary", cwd: path.join(root, "current-task") }).returning(); + await db.update(issues).set({ status: "cancelled", executionWorkspaceId: selected.id }).where(eq(issues.id, f.issueId)); + } else await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.issueId)); await db.insert(activityLog).values({ companyId: f.companyId, actorType: "user", actorId: "original owner", action: "issue.updated", entityType: "issue", entityId: f.issueId, details: { retained: "original task history" } }); const [task] = await db.select().from(issues).where(eq(issues.id, f.issueId)); const [owner] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)); const history = await db.select().from(activityLog).where(eq(activityLog.entityId, f.issueId)); - return { ...f, run, lease, hold, task, owner, history, before: await workspace(f.workspaceId) }; + return { ...f, run, lease, hold, task, owner, history, cleanup, before: await workspace(f.workspaceId) }; } + it.each(["cleanup", "branch"] as const)("preserves a no-recipe archived %s source with prepared recovery", async kind => { + const f = await archivedPreparedFixture(kind); + expect(await migrateRemoteWorkspace({ db, storage, ...f, apply: true })).toMatchObject({ applied: true }); + const row = await workspace(f.workspaceId), authority = readRemoteWorkspaceAuthority(row.metadata)!; + expect(row.status).toBe("archived"); expect(row.closedAt).toEqual(f.before.closedAt); + expect(row.metadata).not.toHaveProperty("gitCacheRestoration"); + expect((await db.select().from(issues).where(eq(issues.id, f.issueId)))[0]).toEqual(f.task); + expect(await db.select().from(activityLog).where(eq(activityLog.entityId, f.issueId))).toEqual(f.history); + expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.lease.id)))[0]).toEqual(f.lease); + expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)))[0]).toEqual(f.owner); + expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.hold.id)))[0]).toEqual(f.hold); + await expect(readMigratedLegacyWorkspaceSource(db, { companyId: f.companyId, runId: f.runId, reference: f.reference })) + .resolves.toMatchObject({ runId: f.runId, reference: f.reference }); + if (f.cleanup) expect((await db.select().from(workspaceOperations).where(eq(workspaceOperations.id, f.cleanup.id)))[0]).toEqual(f.cleanup); + else expect(await git(f.base, "rev-parse", `refs/heads/${f.branchName}`)).toBe(f.commit); + await expect(fs.access(f.cwd)).rejects.toMatchObject({ code: "ENOENT" }); + const ref = (await getWorkspaceSnapshot(db, { ...f, snapshotId: authority.snapshotId! }))!; + const archivePath = path.join(root, "no-recipe.pcws"), targetDir = path.join(root, "restored-no-recipe"); + await loadWorkspaceSnapshotArchive({ storage, reference: ref, targetPath: archivePath }); + await restoreRemoteWorkspaceArchive({ archivePath, targetDir, expectedManifestDigest: ref.manifestDigest }); + expect(await git(targetDir, "rev-parse", "HEAD")).toBe(f.commit); + expect(await fs.readFile(path.join(targetDir, "saved.txt"), "utf8")).toBe("original saved work\n"); + }); + it.each(["cleanup", "branch"] as const)("refuses a no-recipe archived %s source changed during upload", async kind => { + const f = await archivedPreparedFixture(kind), put = storage.putFile.bind(storage); let uploaded = false; + storage.putFile = async input => { const saved = await put(input); uploaded = true; + if (f.cleanup) await db.update(workspaceOperations).set({ status: "failed" }).where(eq(workspaceOperations.id, f.cleanup.id)); + else await git(f.base, "update-ref", `refs/heads/${f.branchName}`, f.upstream); + return saved; }; + await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).rejects.toThrow(); + expect(uploaded).toBe(true); + expect(readRemoteWorkspaceAuthority((await workspace(f.workspaceId)).metadata)).toBeNull(); + expect((await db.select().from(issues).where(eq(issues.id, f.issueId)))[0]).toEqual(f.task); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)))[0]).toEqual(f.run); + expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.lease.id)))[0]).toEqual(f.lease); + await expect(fs.access(f.cwd)).rejects.toMatchObject({ code: "ENOENT" }); + }); it("preserves an unselected archived recipe and its pending native files without reopening the task", async () => { const f = await archivedPreparedFixture(), put = storage.putFile.bind(storage); let interrupt = true; diff --git a/server/src/services/remote-workspace-migration.ts b/server/src/services/remote-workspace-migration.ts index cf068eebde6..f512dc5552d 100644 --- a/server/src/services/remote-workspace-migration.ts +++ b/server/src/services/remote-workspace-migration.ts @@ -161,7 +161,7 @@ async function inspect(db: ReadDb, input: { companyId: string; workspaceId: stri )); const legacyRecoverySources: LegacyWorkspaceRecoverySource[] = []; const onlineRecoveryAllowed = !input.writersStopped - && Boolean(input.onlineSource || workspace.status === "archived" && archivedGitSource?.recipe); + && Boolean(input.onlineSource || workspace.status === "archived" && archivedGitSource); for (const run of referencedRuns.filter(run => object(run.reference).state === "prepared").sort((a, b) => a.id.localeCompare(b.id))) { if (onlineRecoveryAllowed) { const source = await inspectOnlineLegacyWorkspaceRecoverySource(db, { workspace, runId: run.id }); @@ -416,7 +416,7 @@ type MigrationPlan = { input: MigrationInput; onlineSource?: OnlineWorkspaceSour async function lockMigrationRecovery(lock: MigrationTransaction, plans: MigrationPlan[], cohort?: WorkspaceMigrationCohort) { const online = plans.filter(plan => !plan.input.writersStopped - && (plan.onlineSource || plan.reserved.workspace.status === "archived" && plan.reserved.archivedGitSource?.recipe)); + && (plan.onlineSource || plan.reserved.workspace.status === "archived" && plan.reserved.archivedGitSource)); if (!online.length) return; if (!await lockOnlineLegacyWorkspaceRecoverySources(lock as unknown as Db, { companyId: online[0].input.companyId, sources: online.flatMap(({ reserved, onlineSource }) => [...reserved.legacyRecoverySources, ...(onlineSource?.companions.flatMap(proof => proof.sources) ?? [])]), @@ -548,7 +548,7 @@ async function validateMigrationPublication(tx: MigrationTransaction, input: Mig || journal.issueId !== operation.issueId || journal.cwd !== operation.cwd || canonical(journal.metadata) !== canonical(operation.metadata)) throw new Error("workspace_cohort_journal_changed"); } - await lockMigrationParents(tx, input.companyId, reserved.workspace.sourceIssueId, onlineSource || reserved.archivedGitSource?.recipe ? [ + await lockMigrationParents(tx, input.companyId, reserved.workspace.sourceIssueId, onlineSource || reserved.archivedGitSource ? [ ...reserved.legacyRecoverySources.map(source => source.issueId), ...(onlineSource?.companions.flatMap(proof => proof.sources.map(source => source.issueId)) ?? []), ] : []); From 232480d18fe5756d3c49acd2600f6b434cc217e5 Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Mon, 9 Nov 2026 17:50:15 -0800 Subject: [PATCH 09/10] perf(runner): write preparation span rows to the run log in the background (#20426) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Before a native run starts its provider, the executor copies the preparation spans (queue, prepare phases, environment) into the run trace and the run log > - It records about 25 spans and waits for one run-log insert per span, one after another > - On a hosted test deployment, that step (`native.controller.span_persistence`, added in #20396) took a median of 0.28 s, and every task waited for it before the Runner started > - The run trace already has a way to write diagnostics without blocking the caller: `defer`, which `finish` drains before the root span closes > - This pull request writes those run-log rows through that path, in order, while the spans themselves are still recorded at once > - The benefit is about 0.25 s less before the provider starts, on every native run, cold or warm ## Linked Issues or Issue Description **What existing behavior does this improve?** The time between the end of heartbeat preparation and `native.session.execute` for native Runner tasks. **Subsystem affected** Server: native runtime tracing (`server/src/services/native-runtime/native-run-trace.ts`) and the native session executor. **Current behavior** `executeNativeSession` calls `trace.record` for each preparation span and awaits it. `trace.end` awaits `emitCompletedSpanEvent`, which inserts one `run.performance.span` row through `onEvent`. On a hosted test deployment, measured with the #20396 spans across 10 runs, `native.controller.span_persistence` took a median of 0.28 s: - 0.30 to 0.36 s for runs right after a computer wake - 0.17 to 0.25 s for runs on an awake computer It is the second largest step between preparation and the provider start (the median of that whole gap is 1.0 s). **Proposed behavior** The spans are still started and ended at once, with the same parents. The speed-budget bookkeeping still runs at once too. Only the run-log row is written later: one row at a time, in the order the spans ended, before the trace finishes. **Reason and benefit** The rows are diagnostics, and they already carry their own start time (`wallStartedAtMs`, `startOffsetMs`). Readers do not depend on the row order: the only reader in the repository, `summarizeStartupReuse`, looks for `runner.process.launch`, which this change does not defer. The provider can start without waiting for these inserts. **Breaking changes** None. ## What Changed - `native-run-trace.ts`: `end` and `record` take an optional `deferRunLog`. With it, `end` queues the run-log row on a per-trace chain registered with `defer`, so rows are written one at a time in order and `finish` waits for them. A row requested after the trace finished is dropped, as for other deferred diagnostics. - `native-session-executor.ts`: the preparation spans and the `environment.startup` scope use `deferRunLog: true`. - `doc/run-log-events.md`: note that native preparation span rows are written late, in order. - `native-run-trace.test.ts`: two tests. - Spans are recorded under their parent while every row write is blocked, and the rows are written in order before `task.provider_session.measured`. - A deferred row requested after `finish` is not written. ## Verification - `npx vitest run src/services/native-runtime/native-run-trace.test.ts src/services/native-runtime/native-run-trace-context.test.ts` (34 passed). Both new tests fail without the source change: the first times out waiting on the blocked write, and the second sees the row written. - `npx vitest run src/__tests__/heartbeat-preparation-gap-spans.test.ts src/services/native-runtime/native-session-executor.test.ts` (1321 passed) - `pnpm --filter @paperclipai/server typecheck` ## Risks - Low risk. The change is diagnostic only: OpenTelemetry spans and the speed-budget checks are unchanged. - The preparation rows can now land in the run log after the first Runner events. Readers already use the payload times, not the row order. - If the server process dies between the provider start and `finish`, the preparation rows of that run can be missing from the run log. The OpenTelemetry spans are not affected. - The deferred rows are written while the run continues, as budget-breach rows already are, so the sink sees concurrent writes from one run. This was already the case for deferred diagnostics. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, test runs, Honeycomb queries) and extended thinking. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- doc/run-log-events.md | 4 ++ .../native-runtime/native-run-trace.test.ts | 38 +++++++++++++++++++ .../native-runtime/native-run-trace.ts | 35 ++++++++++++----- ...unner-restart-recovery.integration.test.ts | 4 +- .../native-runtime/native-session-executor.ts | 6 ++- 5 files changed, 75 insertions(+), 12 deletions(-) diff --git a/doc/run-log-events.md b/doc/run-log-events.md index 161edb0bae5..217e785025a 100644 --- a/doc/run-log-events.md +++ b/doc/run-log-events.md @@ -68,6 +68,10 @@ Every `run.performance.span` payload also carries `wallStartedAtMs`, the span's start time in epoch milliseconds (since 2026-11-09). Span rows can be written late through deferred diagnostics, so readers take a span's start from this field (or from the trace start plus `startOffsetMs`), never from the row's write time. +The preparation spans of a native run (`heartbeat.queue`, `heartbeat.prepare_*`, +`environment.*`) are always written this way: in the order they ended, while the +provider starts, and before the run's trace finishes. They can appear after the +first Runner events of the run. `run.performance.span` also records `task.time_to_first_token` once per native dispatch at the first newly committed deliverable text: assistant or reasoning diff --git a/server/src/services/native-runtime/native-run-trace.test.ts b/server/src/services/native-runtime/native-run-trace.test.ts index 1cfb22cddcd..bd448269e37 100644 --- a/server/src/services/native-runtime/native-run-trace.test.ts +++ b/server/src/services/native-runtime/native-run-trace.test.ts @@ -595,6 +595,44 @@ describe("deferred diagnostics", () => { expect(names.indexOf("task.time_to_first_token")).toBeLessThan(names.indexOf("task.provider_session.measured")); }); + it("records spans without waiting on deferred run-log rows, then writes them in order before finish", async () => { + const { traceContext, spans } = createRecordingTraceContext(); + const written: unknown[] = []; + let release!: () => void; + const gate = new Promise((resolve) => { release = resolve; }); + const write = vi.fn(async (event: AdapterRuntimeEvent) => { + await gate; + written.push((event.payload as Record)?.span); + }); + const trace = createNativeRunTrace({ runId: "deferred-rows", startedAtMs: 1_000, traceContext, onEvent: write }); + trace.start("task.prepare", { parentName: "task.provider_session", startedAtMs: 1_000 }); + const names = ["heartbeat.queue", "heartbeat.prepare_before_environment", "heartbeat.prepare_after_environment"]; + for (const [index, name] of names.entries()) { + await trace.record({ name, parentName: "task.prepare", startedAtMs: 1_000 + index, endedAtMs: 1_100 + index }, { deferRunLog: true }); + } + // The spans exist under their parent while every row write is still blocked. + expect(spans.filter((span) => span.parentName === "task.prepare").map((span) => span.name)).toEqual(names); + expect(spans.filter((span) => names.includes(span.name)).every((span) => span.endedAtMs !== null)).toBe(true); + expect(written).toEqual([]); + expect(write.mock.calls.length).toBeLessThanOrEqual(1); + const finished = trace.finish("ok"); + release(); + await finished; + // Rows keep the order their spans ended in and land before the root span closes. + expect(written.slice(0, 3)).toEqual(names); + expect(written.indexOf("task.provider_session.measured")).toBeGreaterThan(2); + }); + + it("drops deferred run-log rows requested after the trace finished", async () => { + const write = vi.fn(async () => {}); + const trace = createNativeRunTrace({ runId: "deferred-rows-late", traceContext: createRecordingTraceContext().traceContext, onEvent: write }); + await trace.finish("ok"); + write.mockClear(); + await trace.record({ name: "heartbeat.queue", startedAtMs: 1_000, endedAtMs: 1_100 }, { deferRunLog: true }); + await new Promise((resolve) => setImmediate(resolve)); + expect(write).not.toHaveBeenCalled(); + }); + it("ignores a failed deferred diagnostic and work deferred after finish", async () => { const trace = createNativeRunTrace({ runId: "deferred-fail", traceContext: createRecordingTraceContext().traceContext }); trace.defer(async () => { throw new Error("diagnostic failed"); }); diff --git a/server/src/services/native-runtime/native-run-trace.ts b/server/src/services/native-runtime/native-run-trace.ts index 9224fd9dfee..6267e985f32 100644 --- a/server/src/services/native-runtime/native-run-trace.ts +++ b/server/src/services/native-runtime/native-run-trace.ts @@ -531,6 +531,8 @@ export function createNativeRunTrace(input: { endedAtMs?: number; outcome?: NativeRunSpanOutcome; attributes?: Record; + /** Write the run-log row after the caller continues; `finish` settles it. */ + deferRunLog?: boolean; } = {}, ): Promise => { const state = scopeState(scope); @@ -550,14 +552,18 @@ export function createNativeRunTrace(input: { }); if (outcome === "failed") { try { state.span.setStatus({ code: 2 }); } catch {} } try { state.span.end(endedAtMs); } catch {} - if (state.persistRunLog) await emitCompletedSpanEvent({ - name: state.name, - parentName: state.parentName, - startedAtMs: state.startedAtMs, - endedAtMs, - outcome, - attributes: state.attributes, - }); + if (state.persistRunLog) { + const completed: NativeRunHistoricalSpan = { + name: state.name, + parentName: state.parentName, + startedAtMs: state.startedAtMs, + endedAtMs, + outcome, + attributes: state.attributes, + }; + if (options.deferRunLog) deferRunLogRow(completed); + else await emitCompletedSpanEvent(completed); + } checkSpanBudget(state.name, state.startedAtMs, endedAtMs); }; @@ -596,7 +602,7 @@ export function createNativeRunTrace(input: { ); }; - const record = async (span: NativeRunHistoricalSpan, options: { persistRunLog?: boolean } = {}): Promise => { + const record = async (span: NativeRunHistoricalSpan, options: { persistRunLog?: boolean; deferRunLog?: boolean } = {}): Promise => { const scope = start(span.name, { parentName: span.parentName, startedAtMs: span.startedAtMs, @@ -606,6 +612,7 @@ export function createNativeRunTrace(input: { await end(scope, { endedAtMs: span.endedAtMs, outcome: span.outcome, + deferRunLog: options.deferRunLog, }); }; @@ -648,6 +655,16 @@ export function createNativeRunTrace(input: { pendingDiagnostics.add(pending); }; + // Deferred run-log rows are written one at a time, in the order their spans + // ended, so the sink sees the same sequence as the awaited path. + let runLogRows: Promise = Promise.resolve(); + const deferRunLogRow = (span: NativeRunHistoricalSpan): void => { + if (ended) return; + const written = runLogRows.then(() => emitCompletedSpanEvent(span)); + runLogRows = written; + defer(() => written); + }; + const finish = async (outcome: NativeRunSpanOutcome): Promise => { if (ended) return; try { input.onFinish?.(); } catch { /* Diagnostics cannot change runner control flow. */ } diff --git a/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts b/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts index 729845d8a14..b6af62a30fc 100644 --- a/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts +++ b/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts @@ -2510,7 +2510,9 @@ process.on("SIGTERM", () => child.kill("SIGTERM")); backend: { descriptor, openSession }, preparationSpans: [{ name: "heartbeat.prepare_after_environment", startedAtMs: Date.now(), endedAtMs: Date.now() }], onEvent: async event => { - if (event.payload?.span === "heartbeat.prepare_after_environment") { + // Preparation span rows are written in the background, so hold the + // controller on the awaited environment receipt that precedes them. + if (event.eventType === "run.startup.reuse" && event.payload?.layer === "environment") { prepared(); await continuePreparation; } diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index f0e9a0e335f..25eba55d801 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -9773,6 +9773,8 @@ async function executePaperclipNativeSessionAttempt( startedAtMs: environmentStartedAtMs, }) : null; + // The spans are recorded now; their run-log rows are written in the + // background so the provider start does not wait for one insert per span. await timeController("span_persistence", async () => { for (const span of preparationSpans) { const rootMilestone = isNativeRunRootHistoricalSpan(span.name); @@ -9783,10 +9785,10 @@ async function executePaperclipNativeSessionAttempt( : environmentSpans.includes(span) ? "environment.startup" : "task.prepare", - }); + }, { deferRunLog: true }); } if (environmentScope) { - await trace.end(environmentScope, { endedAtMs: environmentEndedAtMs }); + await trace.end(environmentScope, { endedAtMs: environmentEndedAtMs, deferRunLog: true }); } }); let retainedTransition: VerifiedWarmTransitionBinding | undefined; From 1ca3e8ea2a759e511ab2d2659339c6c770a7a2ba Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 9 Nov 2026 19:57:24 -0600 Subject: [PATCH 10/10] fix(native): let a resume claimed after a restart write the run's existing log (#20427) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - When a native run is interrupted, Paperclip can persist a same-run resume: a later attempt continues the same run from its exact checkpoint > - If the server restarts before that resume is dispatched, the new server process claims it. The resume then reopens the run's existing log, and only the current controller may write it > - The resume claim took the lease owner but left the dead process's controller identity on the lease. The log writer check compares the boot id, so it refused, and the exact checkpoint resume failed as `run_log_writer_authority_lost` > - This pull request stamps the claiming process's identity on the resume claim, as restart recovery's own claim already does > - The benefit is that a resume persisted before a restart continues after it, instead of failing and needing a manual Retry ## Linked Issues or Issue Description Refs #19831. Storage chaos wave `w-20261110T003423-s9903` (local ST2, seed 9903), task t01 (codex C1, K1). The wave went 7/8; t01 was the one task that needed a Retry. - Run 279772b3 was SIGKILLed during its first turn. The restarted server resumed it, and the Codex snapshot failed ("cannot safely recover an ambiguous Codex turn start"). A same-run resume was persisted. - A second SIGKILL hit (00:35:37), and the next process dispatched the scheduled resume at 00:35:56. - The resume's run-log claim failed in `createRunLogWriterAuthority`: the coordinator lease still carried the killed process's `controllerBootId`. The exact checkpoint resume was refused (`run_log_writer_authority_lost`), and the run ended `adapter_failed`, needing a Retry. The wave had S3 latency injected, but the failure does not depend on it. The new test reproduces it on master with no storage faults. ## What Changed - `server/src/services/native-runtime/native-finalization-reconciler.ts`: `dispatchNativeSessionResumptions` writes the claiming process's controller identity (boot id, pid, host hash, process start) along with its lease owner and expiry. This matches the restart-recovery claim, so ownership proofs and the run-log writer check see the process that actually owns the resume. - `server/src/__tests__/native-session-resumption.test.ts`: a regression test for this case. ## Verification - `native-session-resumption.test.ts`: - A coordinator persisted for resume by a previous process (stale boot id), on a run with an existing object-store log, is dispatched. - The run-log writer check accepts the new claim, and the lease carries this process's identity. - The test fails on master with `run_log_writer_authority_lost`. - Regression: the native resumption, binding, recovery-deadline, restart-recovery, scheduled-resume, owner-release, runner-ownership and recovery suites pass locally. `tsc --noEmit` passes for `server`. ## Risks - The resume claim now also refreshes the controller pid, host hash and process start on the coordinator row. These describe the process that owns the lease, exactly as after a restart-recovery claim. A claim by the same process writes the same values as before. - No schema migration. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edits). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- .../native-session-resumption.test.ts | 19 +++++++++++++++++++ .../native-finalization-reconciler.ts | 6 ++++++ 2 files changed, 25 insertions(+) diff --git a/server/src/__tests__/native-session-resumption.test.ts b/server/src/__tests__/native-session-resumption.test.ts index 2c6873dc213..db322b28ef5 100644 --- a/server/src/__tests__/native-session-resumption.test.ts +++ b/server/src/__tests__/native-session-resumption.test.ts @@ -1,4 +1,5 @@ import { readFile } from "node:fs/promises"; +import { createRunLogWriterAuthority } from "../services/heartbeat/run-log-authority.js"; import { enableRunFailureReporting } from "./helpers/run-failure-reporting.js"; import { EMBEDDED_POSTGRES_TEST_TIMEOUT_MS } from "@paperclipai/db"; import { spawn } from "node:child_process"; @@ -402,6 +403,24 @@ describe("P6-25 pre-result native session recovery", () => { await expect(db.select().from(nativeRunFinalizations)).resolves.toHaveLength(8); }); + it("lets a resume claimed by a restarted process write the run's existing log (storage chaos ST2 t01)", async () => { + await db.update(nativeRunFinalizations).set({ + phase: "retryable_failure", leaseOwner: null, leaseExpiresAt: null, nextAttemptAt: new Date(0), + controllerBootId: "previous-process-boot", + }).where(eq(nativeRunFinalizations.runId, runId)); + await db.update(heartbeatRuns).set({ status: "failed", logStore: "s3_segments", logRef: `${companyId}/run-log` }) + .where(eq(heartbeatRuns.id, runId)); + const dispatched: Array<{ runId: string; leaseOwner: string; attempt: number }> = []; + await dispatchNativeSessionResumptions({ db, runnerInstanceId: "heartbeat-restarted", runIds: [runId], + dispatch: (claim) => dispatched.push(claim) }); + expect(dispatched).toHaveLength(1); + const [resumed] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + await expect(createRunLogWriterAuthority(db, resumed!, dispatched[0]!.leaseOwner)()).resolves.toBeUndefined(); + const [owner] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId)); + expect(owner).toMatchObject({ controllerPid: process.pid, leaseOwner: dispatched[0]!.leaseOwner }); + expect(owner!.controllerBootId).not.toBe("previous-process-boot"); + }); + it("uses provider-neutral checkpoint-free bootstrap retry only when durable evidence proves no session existed", async () => { await expect(claimNativeSessionResumptions({ db, diff --git a/server/src/services/native-runtime/native-finalization-reconciler.ts b/server/src/services/native-runtime/native-finalization-reconciler.ts index d915c90cc55..97782172df6 100644 --- a/server/src/services/native-runtime/native-finalization-reconciler.ts +++ b/server/src/services/native-runtime/native-finalization-reconciler.ts @@ -1,4 +1,5 @@ import { notifyLiveRunRecovery } from "../live-run-recovery-notifications.js"; +import { currentControllerProcessStamp } from "../controller-process-identity.js"; import { NATIVE_SESSION_RESUMPTION_ISSUE_STATUSES } from "./native-session-resumption-statuses.js"; import { notifyExternalAgentSettlement } from "../../modules/external-agents/index.js"; import { pendingNativeRunProjectionCondition } from "./native-run-projection.js"; @@ -312,6 +313,11 @@ export async function claimNativeSessionResumptions(input: { phase: "observed", leaseOwner, leaseExpiresAt, + ...(() => { + const stamp = currentControllerProcessStamp(); + return { controllerBootId: stamp.bootId, controllerPid: stamp.pid, controllerHostHash: stamp.hostHash, + controllerProcessStartedAt: stamp.processStartedAt ? new Date(stamp.processStartedAt) : null }; + })(), failureCode: null, failureDetail: null, nextAttemptAt: null,