diff --git a/doc/DATABASE.md b/doc/DATABASE.md
index fb0e9198acc..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
@@ -379,6 +391,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/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/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/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/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/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/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__/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__/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/__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/__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/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/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/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