Merge branch 'master' of https://github.com/paperclipai/paperclip into codex/sleep-aware-chat-transports

* 'master' of https://github.com/paperclipai/paperclip:
  fix(native): let a resume claimed after a restart write the run's existing log (#20427)
  perf(runner): write preparation span rows to the run log in the background (#20426)
  fix(workspaces): preserve recovery for verified archived Git sources (#20436)
  perf(runner): run launch artifacts in place from a trusted read-only root (#20428)
  fix(ui): stop reporting cancelled queries to Sentry (#20430)
  perf(workspaces): share cohort child-source verification (#20418)
  fix(workspaces): preserve archived native recovery during migration (#20424)
  fix(workspaces): refresh saved cohort source proofs on resume (#20429)
  Extend login PTY contracts for existing computers (#20410)
  perf(chat): index GitHub review lookups and share review-wait reads (#20400)
This commit is contained in:
Dotta committed 2026-11-09 20:06:12 -06:00
commit a8bc837487
48 files changed
+2196 -103

No files matched your search

+28
View File
@@ -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
@@ -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
+4
View File
@@ -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
+1
View File
@@ -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",
@@ -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'));
@@ -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": [
+7
View File
@@ -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
}
]
}
+15
View File
@@ -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],
+6
View File
@@ -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)
@@ -559,6 +559,23 @@ fn apply_oom_score_adj(args: &[String]) -> Result<(), LocalRunnerError> {
Ok(())
}
/// `--trusted-launch-root <dir>`: the host asserts that `<dir>` 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")
@@ -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() {
@@ -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<TrustedLaunchRoot> = 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<bool>,
}
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<Self, String> {
#[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<bool>,
) -> Result<Self, String> {
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<bool> {
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<VerifiedProcessArtifact, DurableRunnerError> {
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<VerifiedProcessArtifact, DurableRunnerError> {
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<VerifiedProcessArtifact, DurableRunnerError> {
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<VerifiedProcessArtifact, DurableRunnerError> {
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<VerifiedProcessArtifact, DurableRunnerError> {
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<bool> {
Ok(true)
}
fn writable(_: &File) -> std::io::Result<bool> {
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());
}
}
@@ -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(),
+23
View File
@@ -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.
@@ -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<void>;
/** Optional fixed credential read, advertised through supported-method discovery. */
onLoginPtyReadCredential?(params: PluginLoginPtyReadCredentialParams): Promise<PluginLoginPtyReadCredentialResult>;
/** Called to stop an open login pseudo-terminal child, keyed by the worker session identifier. */
onLoginPtyStop?(params: PluginLoginPtyStopParams): Promise<void>;
+9
View File
@@ -214,6 +214,15 @@ export type {
PluginEnvironmentCancelInteractiveSetupResult,
PluginEnvironmentDeleteTemplateParams,
PluginEnvironmentDeleteTemplateResult,
PluginLoginCommandKey,
PluginLoginPtyOpenParams,
PluginLoginPtyOpenResult,
PluginLoginPtyInputParams,
PluginLoginPtyReadCredentialParams,
PluginLoginPtyReadCredentialResult,
PluginLoginPtyStopParams,
PluginLoginPtyCloseParams,
PluginLoginPtyCloseResult,
PluginModalBoundsRequest,
PluginRenderCloseEvent,
PluginLauncherRenderContextSnapshot,
+32
View File
@@ -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",
@@ -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");
@@ -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(
@@ -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<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
let db: ReturnType<typeof createDb> | 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); }
}
+234
View File
@@ -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=<pre-fix commit>
*
* 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=<commit>");
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<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
let db: ReturnType<typeof createDb> | 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<number>) {
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<string, unknown>; "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<unknown>) => 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<string, unknown>) => {
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<Record<string, unknown>> | 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<string, unknown> = {};
const outputs: Record<string, unknown> = {};
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); }
}
@@ -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<string, unknown>) => {
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();
@@ -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;
@@ -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<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
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");
});
});
@@ -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<ReturnType<typeof seedGitHubReviewWait>>) {
await db.update(toolConnections).set({ enabled: false }).where(and(
eq(toolConnections.id, fixture.connectionId), eq(toolConnections.companyId, fixture.companyId)));
@@ -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,
@@ -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<void>(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 },
@@ -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 })
+10 -2
View File
@@ -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,
+13 -7
View File
@@ -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<Map<string, IssueReviewAttention>> {
const result = new Map<string, IssueReviewAttention>();
for (const row of issueRows) result.set(row.id, reviewAttentionNone());
@@ -4929,7 +4930,7 @@ async function listIssueReviewAttentionMap(
queuedWakeRequests: wakeRows,
pendingInteractions: interactionRows,
pendingApprovals: approvalRows,
externalResponseWaits: await listExternalReviewWaits(dbOrTx, companyId, reviewIds),
externalResponseWaits: await readExternalReviewWaits(reviewIds),
openRecoveryIssues: recoveryPaths,
now: new Date(),
};
@@ -5777,6 +5778,7 @@ async function listIssueBlockedInboxAttentionMap(
dbOrTx: any,
companyId: string,
issueRows: BlockedInboxIssueRow[],
readExternalReviewWaits: ExternalReviewWaitReader = createExternalReviewWaitReader(dbOrTx, companyId),
): Promise<Map<string, IssueBlockedInboxAttention>> {
const rowIssueIds = [...new Set(issueRows.map((row) => row.id))];
const result = new Map<string, IssueBlockedInboxAttention>();
@@ -6036,7 +6038,7 @@ async function listIssueBlockedInboxAttentionMap(
});
const findings = classifyIssueGraphLiveness({
externalResponseWaits: await listExternalReviewWaits(dbOrTx, companyId, graphIssues.filter(issue => issue.status === "in_review").map(issue => issue.id)),
externalResponseWaits: await readExternalReviewWaits(graphIssues.filter(issue => issue.status === "in_review").map(issue => issue.id)),
issues: graphIssues.map((issue) => ({
id: issue.id,
companyId: issue.companyId,
@@ -6637,6 +6639,8 @@ async function listBlockedInboxIssues(
const issueIds = withRuns.map((row) => row.id);
const includeLiveDescendantSummary =
filters?.includeLiveDescendantSummary === true;
// Both attention maps read external review waits for overlapping issues.
const readExternalReviewWaits = createExternalReviewWaitReader(dbOrTx, companyId);
const [
statsRows,
readRows,
@@ -6656,8 +6660,8 @@ async function listBlockedInboxIssues(
lastActivityStatsForIssues(dbOrTx, companyId, issueIds),
blockedByMapForIssues(dbOrTx, companyId, issueIds),
listIssueBlockerAttentionMap(dbOrTx, companyId, withRuns),
listIssueReviewAttentionMap(dbOrTx, companyId, withRuns),
listIssueBlockedInboxAttentionMap(dbOrTx, companyId, withRuns),
listIssueReviewAttentionMap(dbOrTx, companyId, withRuns, readExternalReviewWaits),
listIssueBlockedInboxAttentionMap(dbOrTx, companyId, withRuns, readExternalReviewWaits),
includeLiveDescendantSummary
? liveDescendantCountMapForIssues(dbOrTx, companyId, issueIds)
: Promise.resolve(new Map<string, number>()),
@@ -8601,6 +8605,8 @@ export function issueService(db: Db) {
const archiveByIssueId = new Map(
archiveRows.map((row) => [row.issueId, row]),
);
// Both attention maps read external review waits for overlapping issues.
const readExternalReviewWaits = createExternalReviewWaitReader(db, companyId);
const [
blockerAttentionByIssueId,
reviewAttentionByIssueId,
@@ -8609,9 +8615,9 @@ export function issueService(db: Db) {
? [new Map<string, IssueBlockerAttention>(), new Map<string, IssueReviewAttention>(), new Map<string, IssueBlockedInboxAttention>()]
: await timePhase("attention", () => Promise.all([
filters?.listProjection === "index" ? Promise.resolve(new Map<string, IssueBlockerAttention>()) : listIssueBlockerAttentionMap(db, companyId, withRuns),
filters?.listProjection === "index" ? Promise.resolve(new Map<string, IssueReviewAttention>()) : listIssueReviewAttentionMap(db, companyId, withRuns),
filters?.listProjection === "index" ? Promise.resolve(new Map<string, IssueReviewAttention>()) : listIssueReviewAttentionMap(db, companyId, withRuns, readExternalReviewWaits),
includeBlockedInboxAttention
? listIssueBlockedInboxAttentionMap(db, companyId, withRuns)
? listIssueBlockedInboxAttentionMap(db, companyId, withRuns, readExternalReviewWaits)
: Promise.resolve(new Map<string, IssueBlockedInboxAttention>()),
]));
@@ -0,0 +1,32 @@
import { describe, expect, it, vi } from "vitest";
import type { Db } from "@paperclipai/db";
import { createExternalReviewWaitReader, type ExternalReviewWait } from "./external-review-wait.js";
const db = {} as Db;
const wait = (issueId: string) => ({ issueId, companyId: "company" }) as ExternalReviewWait;
describe("createExternalReviewWaitReader", () => {
it("reads each issue once for callers that share one request", async () => {
const list = vi.fn(async (_db: Db, _companyId: string, issueIds: string[]) =>
issueIds.filter(issueId => issueId !== "b").map(wait));
const read = createExternalReviewWaitReader(db, "company", list);
// The review and blocked-inbox maps start their reads concurrently.
const [page, graph] = await Promise.all([read(["a", "b"]), read(["c", "a", "b", "c"])]);
expect(page).toEqual([wait("a")]);
expect(graph).toEqual([wait("c"), wait("a")]);
expect(await read(["a"])).toEqual([wait("a")]);
expect(await read([])).toEqual([]);
expect(list.mock.calls.map(([, companyId, issueIds]) => [companyId, issueIds])).toEqual([
["company", ["a", "b"]], ["company", ["c"]],
]);
expect(list.mock.calls.every(([database]) => database === db)).toBe(true);
});
it("rejects every caller that waits on a failed read", async () => {
const failure = new Error("database unavailable");
const list = vi.fn(async () => { throw failure; });
const read = createExternalReviewWaitReader(db, "company", list);
await expect(Promise.all([read(["a"]), read(["a", "b"])])).rejects.toBe(failure);
expect(list).toHaveBeenCalledTimes(2);
});
});
@@ -78,3 +78,27 @@ export async function listExternalReviewWaits(db: Db, companyId: string, issueId
}));
return waits.filter((wait): wait is NonNullable<typeof wait> => wait !== null);
}
export type ExternalReviewWait = Awaited<ReturnType<typeof listExternalReviewWaits>>[number];
export type ExternalReviewWaitReader = (issueIds: string[]) => Promise<ExternalReviewWait[]>;
/** Share one company's wait reads between callers that serve one request.
* Each issue's wait is independent of the other requested issues, so an issue
* is read at most once. Do not keep a reader beyond its request. */
export function createExternalReviewWaitReader(db: Db, companyId: string,
list: typeof listExternalReviewWaits = listExternalReviewWaits): ExternalReviewWaitReader {
const byIssueId = new Map<string, Promise<ExternalReviewWait | null>>();
return async (issueIds) => {
const requested = [...new Set(issueIds)];
const missing = requested.filter(issueId => !byIssueId.has(issueId));
if (missing.length) {
const read = list(db, companyId, missing)
.then(waits => new Map(waits.map(wait => [wait.issueId, wait])));
for (const issueId of missing) {
byIssueId.set(issueId, read.then(waits => waits.get(issueId) ?? null));
}
}
const waits = await Promise.all(requested.map(issueId => byIssueId.get(issueId)!));
return waits.filter((wait): wait is ExternalReviewWait => wait !== null);
};
}
@@ -1,4 +1,5 @@
import { notifyLiveRunRecovery } from "../live-run-recovery-notifications.js";
import { currentControllerProcessStamp } from "../controller-process-identity.js";
import { NATIVE_SESSION_RESUMPTION_ISSUE_STATUSES } from "./native-session-resumption-statuses.js";
import { notifyExternalAgentSettlement } from "../../modules/external-agents/index.js";
import { pendingNativeRunProjectionCondition } from "./native-run-projection.js";
@@ -312,6 +313,11 @@ export async function claimNativeSessionResumptions(input: {
phase: "observed",
leaseOwner,
leaseExpiresAt,
...(() => {
const stamp = currentControllerProcessStamp();
return { controllerBootId: stamp.bootId, controllerPid: stamp.pid, controllerHostHash: stamp.hostHash,
controllerProcessStartedAt: stamp.processStartedAt ? new Date(stamp.processStartedAt) : null };
})(),
failureCode: null,
failureDetail: null,
nextAttemptAt: null,
@@ -595,6 +595,44 @@ describe("deferred diagnostics", () => {
expect(names.indexOf("task.time_to_first_token")).toBeLessThan(names.indexOf("task.provider_session.measured"));
});
it("records spans without waiting on deferred run-log rows, then writes them in order before finish", async () => {
const { traceContext, spans } = createRecordingTraceContext();
const written: unknown[] = [];
let release!: () => void;
const gate = new Promise<void>((resolve) => { release = resolve; });
const write = vi.fn(async (event: AdapterRuntimeEvent) => {
await gate;
written.push((event.payload as Record<string, unknown>)?.span);
});
const trace = createNativeRunTrace({ runId: "deferred-rows", startedAtMs: 1_000, traceContext, onEvent: write });
trace.start("task.prepare", { parentName: "task.provider_session", startedAtMs: 1_000 });
const names = ["heartbeat.queue", "heartbeat.prepare_before_environment", "heartbeat.prepare_after_environment"];
for (const [index, name] of names.entries()) {
await trace.record({ name, parentName: "task.prepare", startedAtMs: 1_000 + index, endedAtMs: 1_100 + index }, { deferRunLog: true });
}
// The spans exist under their parent while every row write is still blocked.
expect(spans.filter((span) => span.parentName === "task.prepare").map((span) => span.name)).toEqual(names);
expect(spans.filter((span) => names.includes(span.name)).every((span) => span.endedAtMs !== null)).toBe(true);
expect(written).toEqual([]);
expect(write.mock.calls.length).toBeLessThanOrEqual(1);
const finished = trace.finish("ok");
release();
await finished;
// Rows keep the order their spans ended in and land before the root span closes.
expect(written.slice(0, 3)).toEqual(names);
expect(written.indexOf("task.provider_session.measured")).toBeGreaterThan(2);
});
it("drops deferred run-log rows requested after the trace finished", async () => {
const write = vi.fn(async () => {});
const trace = createNativeRunTrace({ runId: "deferred-rows-late", traceContext: createRecordingTraceContext().traceContext, onEvent: write });
await trace.finish("ok");
write.mockClear();
await trace.record({ name: "heartbeat.queue", startedAtMs: 1_000, endedAtMs: 1_100 }, { deferRunLog: true });
await new Promise<void>((resolve) => setImmediate(resolve));
expect(write).not.toHaveBeenCalled();
});
it("ignores a failed deferred diagnostic and work deferred after finish", async () => {
const trace = createNativeRunTrace({ runId: "deferred-fail", traceContext: createRecordingTraceContext().traceContext });
trace.defer(async () => { throw new Error("diagnostic failed"); });
@@ -531,6 +531,8 @@ export function createNativeRunTrace(input: {
endedAtMs?: number;
outcome?: NativeRunSpanOutcome;
attributes?: Record<string, string | number | boolean>;
/** Write the run-log row after the caller continues; `finish` settles it. */
deferRunLog?: boolean;
} = {},
): Promise<void> => {
const state = scopeState(scope);
@@ -550,14 +552,18 @@ export function createNativeRunTrace(input: {
});
if (outcome === "failed") { try { state.span.setStatus({ code: 2 }); } catch {} }
try { state.span.end(endedAtMs); } catch {}
if (state.persistRunLog) await emitCompletedSpanEvent({
name: state.name,
parentName: state.parentName,
startedAtMs: state.startedAtMs,
endedAtMs,
outcome,
attributes: state.attributes,
});
if (state.persistRunLog) {
const completed: NativeRunHistoricalSpan = {
name: state.name,
parentName: state.parentName,
startedAtMs: state.startedAtMs,
endedAtMs,
outcome,
attributes: state.attributes,
};
if (options.deferRunLog) deferRunLogRow(completed);
else await emitCompletedSpanEvent(completed);
}
checkSpanBudget(state.name, state.startedAtMs, endedAtMs);
};
@@ -596,7 +602,7 @@ export function createNativeRunTrace(input: {
);
};
const record = async (span: NativeRunHistoricalSpan, options: { persistRunLog?: boolean } = {}): Promise<void> => {
const record = async (span: NativeRunHistoricalSpan, options: { persistRunLog?: boolean; deferRunLog?: boolean } = {}): Promise<void> => {
const scope = start(span.name, {
parentName: span.parentName,
startedAtMs: span.startedAtMs,
@@ -606,6 +612,7 @@ export function createNativeRunTrace(input: {
await end(scope, {
endedAtMs: span.endedAtMs,
outcome: span.outcome,
deferRunLog: options.deferRunLog,
});
};
@@ -648,6 +655,16 @@ export function createNativeRunTrace(input: {
pendingDiagnostics.add(pending);
};
// Deferred run-log rows are written one at a time, in the order their spans
// ended, so the sink sees the same sequence as the awaited path.
let runLogRows: Promise<void> = Promise.resolve();
const deferRunLogRow = (span: NativeRunHistoricalSpan): void => {
if (ended) return;
const written = runLogRows.then(() => emitCompletedSpanEvent(span));
runLogRows = written;
defer(() => written);
};
const finish = async (outcome: NativeRunSpanOutcome): Promise<void> => {
if (ended) return;
try { input.onFinish?.(); } catch { /* Diagnostics cannot change runner control flow. */ }
@@ -2510,7 +2510,9 @@ process.on("SIGTERM", () => child.kill("SIGTERM"));
backend: { descriptor, openSession },
preparationSpans: [{ name: "heartbeat.prepare_after_environment", startedAtMs: Date.now(), endedAtMs: Date.now() }],
onEvent: async event => {
if (event.payload?.span === "heartbeat.prepare_after_environment") {
// Preparation span rows are written in the background, so hold the
// controller on the awaited environment receipt that precedes them.
if (event.eventType === "run.startup.reuse" && event.payload?.layer === "environment") {
prepared();
await continuePreparation;
}
@@ -9773,6 +9773,8 @@ async function executePaperclipNativeSessionAttempt(
startedAtMs: environmentStartedAtMs,
})
: null;
// The spans are recorded now; their run-log rows are written in the
// background so the provider start does not wait for one insert per span.
await timeController("span_persistence", async () => {
for (const span of preparationSpans) {
const rootMilestone = isNativeRunRootHistoricalSpan(span.name);
@@ -9783,10 +9785,10 @@ async function executePaperclipNativeSessionAttempt(
: environmentSpans.includes(span)
? "environment.startup"
: "task.prepare",
});
}, { deferRunLog: true });
}
if (environmentScope) {
await trace.end(environmentScope, { endedAtMs: environmentEndedAtMs });
await trace.end(environmentScope, { endedAtMs: environmentEndedAtMs, deferRunLog: true });
}
});
let retainedTransition: VerifiedWarmTransitionBinding | undefined;
+29 -18
View File
@@ -590,6 +590,7 @@ export type ExecuteLogSink = (
* carries no command string, so a caller cannot select the command.
*/
export interface LoginPtyOpenInput {
expiresAt?: string;
/** The environment driver key. It routes the worker; it confers no command authority. */
driverKey: string;
companyId: string;
@@ -1564,7 +1565,9 @@ export function createPluginWorkerHandle(
type LoginPtyPreBindRecord = LoginPtyPreBindOutputRecord | LoginPtyPreBindExitRecord;
interface LoginPtyRoute {
companyId: string;
hostRouteId: string;
closePromise: Promise<void> | null;
state: LoginPtyRouteState;
workerSessionId: string | null;
listener: ((chunk: string) => void) | null;
@@ -1626,11 +1629,11 @@ export function createPluginWorkerHandle(
// that carries the exact host route identifier. An absent, malformed,
// mismatched, or timed-out acknowledgement returns false, so the caller fails
// closed.
async function closeLoginPtyTerminal(hostRouteId: string): Promise<boolean> {
async function closeLoginPtyTerminal(hostRouteId: string, companyId: string): Promise<boolean> {
try {
const ack = await callInternal(
"loginPtyClose",
{ hostRouteId },
{ hostRouteId, companyId },
loginPtyCloseTimeoutMs,
);
return isRecord(ack) && readNonEmptyString(ack.hostRouteId) === hostRouteId;
@@ -1647,6 +1650,9 @@ export function createPluginWorkerHandle(
// every other route this worker still holds settles through the worker-exit
// path that follows.
async function terminalizeLoginPtyRoute(route: LoginPtyRoute): Promise<void> {
// A notification may already have started close. Every later disposer must
// join that acknowledgement before its owner can release the allocation.
if (route.closePromise) return route.closePromise;
if (route.terminalized) return;
route.terminalized = true;
route.state = "closed";
@@ -1660,20 +1666,22 @@ export function createPluginWorkerHandle(
loginPtyRoutesByWorkerSessionId.delete(route.workerSessionId);
}
releaseLoginPtyRouteSlot(route);
// A terminalized route reports a null exit code, which the runner treats as a
// failure.
route.closePromise = (async () => {
const confirmed = await closeLoginPtyTerminal(route.hostRouteId, route.companyId);
if (!confirmed) {
// The worker did not acknowledge the close, so the host cannot prove the
// terminal is gone. Retire the worker before any reuse.
log.error(
{ pluginId },
"login pseudo-terminal close not acknowledged; retiring worker",
);
retireWorkerProcess();
}
})();
// Report failure promptly, but retain the shared close barrier so the
// runner's following dispose waits for confirmed stop (or worker retirement).
settleRouteWait(route, { exitCode: null });
const confirmed = await closeLoginPtyTerminal(route.hostRouteId);
if (!confirmed) {
// The worker did not acknowledge the close, so the host cannot prove the
// terminal is gone. Fail closed: retire the worker before any reuse. This
// also settles and clears every other route the worker still holds.
log.error(
{ pluginId },
"login pseudo-terminal close not acknowledged; retiring worker",
);
retireWorkerProcess();
}
return route.closePromise;
}
// Resolve one login pseudo-terminal notification to its route. Return null
@@ -1920,7 +1928,9 @@ export function createPluginWorkerHandle(
settleWait = resolve;
});
const route: LoginPtyRoute = {
companyId: input.companyId,
hostRouteId,
closePromise: null,
state: "reserved",
workerSessionId: null,
listener: null,
@@ -1957,6 +1967,7 @@ export function createPluginWorkerHandle(
providerLeaseId: input.providerLeaseId,
loginCommandKey: input.loginCommandKey,
sessionHome: input.sessionHome,
...(input.expiresAt ? { expiresAt: input.expiresAt } : {}),
},
loginPtyOpenTimeoutMs,
);
@@ -2001,9 +2012,9 @@ export function createPluginWorkerHandle(
if (route.state !== "open" || !sid) return;
void callInternal(
"loginPtyInput",
{ workerSessionId: sid, data },
{ companyId: route.companyId, workerSessionId: sid, data, inputId: randomUUID() },
loginPtyOpenTimeoutMs,
).catch(() => {});
).catch(() => terminalizeLoginPtyRoute(route));
},
wait(): Promise<{ exitCode: number | null }> {
return waitPromise;
@@ -2013,7 +2024,7 @@ export function createPluginWorkerHandle(
if (!sid) return;
void callInternal(
"loginPtyStop",
{ workerSessionId: sid },
{ companyId: route.companyId, workerSessionId: sid },
loginPtyOpenTimeoutMs,
).catch(() => {});
},
@@ -6,7 +6,7 @@ import path from "node:path";
import { promisify } from "node:util";
import { eq, inArray, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { activityLog, agents, companies, createDb, environmentLeases, environments, heartbeatRuns, nativeRunFinalizations, executionWorkspaceSnapshots, executionWorkspaces, issues, projects, workspaceOperations, type Db } from "@paperclipai/db";
import { activityLog, agents, companies, createDb, environmentLeases, environments, heartbeatRuns, nativeRunFinalizations, executionWorkspaceSnapshots, executionWorkspaces, issues, projects, projectWorkspaces, workspaceOperations, type Db } from "@paperclipai/db";
import { readRemoteWorkspaceAuthority } from "@paperclipai/shared";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js";
import { resolveManagedProjectWorkspaceDir } from "../home-paths.js";
@@ -46,11 +46,11 @@ describe.skipIf(!support.supported)("bounded workspace cohort migration", () =>
await db.execute(sql`drop trigger if exists cohort_commit_fault on workspace_operations`); await db.execute(sql`drop function if exists cohort_commit_fault()`);
await db.execute(sql`drop trigger if exists cohort_reserve_fault on workspace_operations`); await db.execute(sql`drop function if exists cohort_reserve_fault()`);
await db.delete(nativeRunFinalizations); await db.delete(environmentLeases); await db.delete(environments); await db.delete(heartbeatRuns);
await db.delete(issues); await db.delete(agents); await db.delete(executionWorkspaces); await db.delete(projects); await db.delete(companies);
await db.delete(issues); await db.delete(agents); await db.delete(executionWorkspaces); await db.delete(projectWorkspaces); await db.delete(projects); await db.delete(companies);
vi.unstubAllEnvs(); await fs.rm(home, { recursive: true, force: true });
});
async function fixture() {
const companyId = randomUUID(), projectId = randomUUID(), root = resolveManagedProjectWorkspaceDir({ companyId, projectId });
async function fixture(repoName?: string) {
const companyId = randomUUID(), projectId = randomUUID(), root = resolveManagedProjectWorkspaceDir({ companyId, projectId, repoName });
await db.insert(companies).values({ id: companyId, name: "Cohort", issuePrefix: `C${companyId.slice(0, 6)}` });
await db.insert(projects).values({ id: projectId, companyId, name: "Shared Git" });
await fs.mkdir(root, { recursive: true }); await fs.writeFile(path.join(root, "saved.txt"), "committed base\n");
@@ -139,7 +139,7 @@ describe.skipIf(!support.supported)("bounded workspace cohort migration", () =>
expect(await git(targetDir, "log", "-1", "--format=%s")).toBe("Original history");
}
}, 60_000);
it("shares the merged child verifier across parallel aliases under the complete cohort fence", async () => {
it.each(["unchanged", "changed"] as const)("shares the merged child verifier across parallel aliases under the complete cohort fence (%s child bytes)", async mode => {
const f = await fixture(), parent = f.leaves[0], cwd = path.join(parent.cwd!, ".paperclip", "worktrees", "nested");
await git(f.root, "worktree", "add", "-qb", "nested", cwd);
const [childIssue, aliasIssue] = await db.insert(issues).values([
@@ -172,10 +172,24 @@ describe.skipIf(!support.supported)("bounded workspace cohort migration", () =>
return get(...args);
});
const capture = vi.spyOn(workspaceArchive, "captureRemoteWorkspaceDirectory");
await expect(run(f, { workspaceIds: [parent.id, alias.id] })).resolves.toMatchObject({ applied: true });
const beforeActivity = await db.select().from(activityLog), put = storage.putFile.bind(storage);
let uploads = 0;
if (mode === "changed") vi.spyOn(storage, "putFile").mockImplementation(async input => {
const result = await put(input);
if (++uploads === 2) await fs.writeFile(path.join(cwd, "untracked.txt"), "changed during parent upload\n");
return result;
});
const pending = run(f, { workspaceIds: [parent.id, alias.id] });
if (mode === "unchanged") await expect(pending).resolves.toMatchObject({ applied: true });
else {
await expect(pending).rejects.toThrow("nested_workspace_source_changed");
const selected = await db.select().from(executionWorkspaces).where(inArray(executionWorkspaces.id, [parent.id, alias.id]));
expect(selected.every(row => !readRemoteWorkspaceAuthority(row.metadata))).toBe(true);
expect(await db.select().from(activityLog)).toEqual(beforeActivity);
}
expect(reads).toBe(1);
expect(capture.mock.calls.filter(([input]) => input.cwd === cwd && path.basename(input.archivePath) === "current.pcws")).toHaveLength(4);
expect(await fs.readFile(path.join(cwd, "untracked.txt"), "utf8")).toBe("nested dirty bytes\n");
expect(capture.mock.calls.filter(([input]) => input.cwd === cwd && path.basename(input.archivePath) === "current.pcws")).toHaveLength(2);
expect(await fs.readFile(path.join(cwd, "untracked.txt"), "utf8")).toBe(mode === "unchanged" ? "nested dirty bytes\n" : "changed during parent upload\n");
}, 60_000);
it.each(["foreign", "journal", "finished"])("refuses a changed %s operation before any authority write", async mode => {
const f = await fixture(), put = storage.putFile.bind(storage); let uploaded = 0;
@@ -200,6 +214,88 @@ describe.skipIf(!support.supported)("bounded workspace cohort migration", () =>
await assertLocal(f);
expect(await db.select().from(workspaceOperations)).toHaveLength(mode === "foreign" ? 3 : 2);
});
it("resumes the same uploaded cohort after an archived companion is independently migrated", async () => {
const f = await fixture("cohort"), held = await recoverable(f), cwd = path.join(f.root, ".paperclip", "worktrees", "retired"), closedAt = new Date();
await git(f.root, "worktree", "add", "-qb", "retired", cwd);
await git(f.root, "worktree", "remove", cwd);
const receipt = await git(f.root, "branch", "-d", "retired");
const [projectWorkspace] = await db.insert(projectWorkspaces).values({ companyId: f.companyId, projectId: f.projectId,
name: "Original repository", cwd: f.root, repoUrl: f.parent.repoUrl }).returning();
const [issue] = await db.insert(issues).values({ companyId: f.companyId, projectId: f.projectId, title: "Retired companion" }).returning();
const [companion] = await db.insert(executionWorkspaces).values({ companyId: f.companyId, projectId: f.projectId,
projectWorkspaceId: projectWorkspace.id, sourceIssueId: issue.id, name: "retired", mode: "isolated_workspace",
strategyType: "git_worktree", providerType: "git_worktree", cwd, providerRef: cwd, repoUrl: f.parent.repoUrl,
branchName: "retired", status: "archived", closedAt, metadata: { createdByRuntime: true, gitBranchOwnershipVersion: 1 } }).returning();
await db.insert(workspaceOperations).values({ companyId: f.companyId, executionWorkspaceId: companion.id,
phase: "worktree_cleanup", status: "succeeded", command: "git branch -d retired", stdoutExcerpt: receipt,
startedAt: new Date(), finishedAt: new Date() });
const put = storage.putFile.bind(storage); let uploads = 0;
const upload = vi.spyOn(storage, "putFile").mockImplementation(async input => {
if (++uploads === 2) throw new Error("interrupted_cohort_upload");
return put(input);
});
await expect(run(f, { concurrency: 1 })).rejects.toThrow("interrupted_cohort_upload");
upload.mockRestore();
const saved = (await db.select().from(workspaceOperations)).filter(row => row.phase === "remote_workspace_migration");
expect(saved).toHaveLength(2);
const cohort = saved[0].metadata!.cohortMigration as { id: string; sourceProof: string; members: unknown[] };
const snapshots = await db.select().from(executionWorkspaceSnapshots);
expect(snapshots.some(row => row.status === "uploaded")).toBe(true);
await migrateRemoteWorkspace({ db, storage, companyId: f.companyId, workspaceId: companion.id, apply: true,
signal: AbortSignal.timeout(50_000) });
const noStorage = new Proxy(storage, { get() { throw new Error("unexpected_storage_operation"); } });
await db.transaction(async tx => {
await expect(run(f, { db: tx as unknown as Db, storage: noStorage, apply: false }))
.resolves.toMatchObject({ applied: false, eligible: true, cohortId: cohort.id });
}, { accessMode: "read only" });
const other = createDb(database.connectionString, { maxConnections: 1 });
try {
await withWorkspaceSourceLocks(other, { companyId: f.companyId, projectIds: [f.projectId] }, async () => {
await expect(run(f, { storage: noStorage })).rejects.toThrow("workspace_source_busy");
}, true);
await other.transaction(async tx => {
expect(await tryLockNativeWorkspaceFinalization(tx as unknown as Db, { companyId: f.companyId, runId: held.runId })).toBe(true);
await expect(run(f, { storage: noStorage })).rejects.toThrow("remote_copyback_owned");
});
} finally { await other.$client.end({ timeout: 1 }); }
const inspect = onlineWorkspaceSource.inspectOnlineWorkspaceSource, cancelled = new AbortController(), calls = new Map<string, number>();
const probe = vi.spyOn(onlineWorkspaceSource, "inspectOnlineWorkspaceSource").mockImplementation(async (...args) => {
const result = await inspect(...args), count = (calls.get(args[1].id) ?? 0) + 1; calls.set(args[1].id, count);
if (count === 5) cancelled.abort(new Error("cancel_cohort_proof_refresh"));
return result;
});
await expect(run(f, { storage: noStorage, signal: cancelled.signal })).rejects.toThrow("cancel_cohort_proof_refresh");
probe.mockRestore();
const last = [...saved].sort((a, b) => a.executionWorkspaceId!.localeCompare(b.executionWorkspaceId!)).at(-1)!;
await db.execute(sql.raw(`create function cohort_reserve_fault() returns trigger language plpgsql as $$ begin if new.id='${last.id}'::uuid then raise exception 'cohort_proof_refresh_fault'; end if; return new; end $$`));
await db.execute(sql`create trigger cohort_reserve_fault before update on workspace_operations for each row execute function cohort_reserve_fault()`);
await expect(run(f, { storage: noStorage })).rejects.toThrow();
await db.execute(sql`drop trigger cohort_reserve_fault on workspace_operations`);
await db.execute(sql`drop function cohort_reserve_fault()`);
expect((await db.select().from(workspaceOperations)).filter(row => saved.some(old => old.id === row.id))).toEqual(saved);
await assertLocal(f);
await expect(run(f)).resolves.toMatchObject({ applied: true, cohortId: cohort.id });
const current = (await db.select().from(workspaceOperations)).filter(row => saved.some(old => old.id === row.id));
expect(current).toHaveLength(2);
for (const operation of current) {
const refreshed = operation.metadata!.cohortMigration as typeof cohort;
expect(refreshed).toMatchObject({ id: cohort.id, members: cohort.members });
expect(refreshed.sourceProof).not.toBe(cohort.sourceProof);
expect(operation.status).toBe("succeeded");
}
expect((await db.select().from(executionWorkspaceSnapshots)).filter(row => snapshots.some(old => old.id === row.id))).toHaveLength(snapshots.length);
await expect(run(f)).resolves.toMatchObject({ applied: true, replayed: true, cohortId: cohort.id });
for (const workspace of f.leaves) {
const [row] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, workspace.id));
const ref = (await getWorkspaceSnapshot(db, { companyId: f.companyId, workspaceId: row.id,
snapshotId: readRemoteWorkspaceAuthority(row.metadata)!.snapshotId! }))!;
const archivePath = path.join(home, `${workspace.name}-resumed.pcws`), targetDir = path.join(home, `${workspace.name}-resumed`);
await loadWorkspaceSnapshotArchive({ storage, reference: ref, targetPath: archivePath });
await restoreRemoteWorkspaceArchive({ archivePath, targetDir, expectedManifestDigest: ref.manifestDigest });
expect(await fs.readFile(path.join(targetDir, "saved.txt"), "utf8")).toBe(`${workspace.name} dirty tracked work\n`);
expect(await fs.readFile(path.join(targetDir, "untracked.txt"), "utf8")).toBe(`${workspace.name} untracked work\n`);
}
}, 60_000);
it("resumes the exact membership after reservation stops halfway", async () => {
const f = await fixture(), second = [...f.leaves].sort((a, b) => a.id.localeCompare(b.id))[1];
await db.execute(sql.raw(`create function cohort_reserve_fault() returns trigger language plpgsql as $$ begin if new.execution_workspace_id='${second.id}'::uuid then raise exception 'cohort_reservation_fault'; end if; return new; end $$`));
@@ -361,6 +361,7 @@ export function createNestedWorkspaceImportVerifier(input: {
},
};
return {
assertOwner,
prepare(options: Omit<NestedVerificationInput, "db" | "storage" | "signal">): Promise<ImportedWorkspaceChild[]> {
if (closed || current) return Promise.reject(new Error("nested_workspace_verifier_unavailable"));
const work = (async () => {
@@ -8,7 +8,7 @@ import { createServer, type Server } from "node:http";
import { pathToFileURL } from "node:url";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { and, eq, sql } from "drizzle-orm";
import { activityLog, agents, environmentLeases, heartbeatRuns, nativeRunFinalizations, nativeRunResults, completionContracts, applyPendingMigrations, closeRegisteredClients, companies, createDb, executionWorkspaceSnapshots,
import { activityLog, agents, environments, environmentLeases, heartbeatRuns, nativeRunFinalizations, nativeRunResults, completionContracts, applyPendingMigrations, closeRegisteredClients, companies, createDb, executionWorkspaceSnapshots,
executionWorkspaceRepositories, executionWorkspaceRuntimeLeases, executionWorkspaces, issueRecoveryActions, issues, projects, projectWorkspaces, workspaceOperations, workspaceRuntimeServices } from "@paperclipai/db";
import { readRemoteWorkspaceAuthority } from "@paperclipai/shared";
import { createLocalDiskStorageProvider } from "../storage/local-disk-provider.js";
@@ -37,6 +37,9 @@ import { isolatedRemoteSourcePath } from "./isolated-remote-workspace-source.js"
import { verifiedGitCacheSource } from "./git-workspace-restoration.js";
import { withIndependentWorkspaceSourceLocks, withWorkspaceSourceLocks } from "./workspace-source-lock.js";
import { inspectOnlineWorkspaceSource } from "./online-workspace-source.js";
import { tryLockNativeWorkspaceFinalization } from "./native-runtime/native-workspace-finalization-ownership.js";
import { readMigratedLegacyWorkspaceSource } from "./legacy-workspace-recovery-migration.js";
import { nativeSha256 } from "./native-runtime/canonical.js";
const execute = promisify(execFile);
const git = async (cwd: string, ...args: string[]) => (await execute("git", ["-C", cwd, ...args], { env: { ...process.env,
@@ -61,6 +64,7 @@ describe.skipIf(!support.supported)("remote workspace migration", () => {
await Promise.all(servers.splice(0).map(server => new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()))));
vi.unstubAllEnvs(); await db.delete(activityLog); await db.delete(workspaceOperations); await db.delete(executionWorkspaceSnapshots);
await db.delete(workspaceRuntimeServices); await db.delete(executionWorkspaceRuntimeLeases);
await db.delete(environmentLeases); await db.delete(environments);
await db.delete(nativeRunFinalizations); await db.delete(nativeRunResults); await db.delete(heartbeatRuns); await db.delete(completionContracts);
await db.delete(issues); await db.delete(agents); await db.delete(executionWorkspaces); await db.delete(projectWorkspaces); await db.delete(projects);
await db.delete(companies); await fs.rm(root, { recursive: true, force: true });
@@ -378,12 +382,12 @@ describe.skipIf(!support.supported)("remote workspace migration", () => {
await restoreRemoteWorkspaceArchive({ archivePath, targetDir, expectedManifestDigest: reference!.manifestDigest });
expect(await fs.readFile(path.join(targetDir, ".paperclip/worktrees/child/child.txt"), "utf8")).toBe("saved child edits\n");
});
async function failedCopybackFixture() {
const f = await seed(), runId = randomUUID();
async function failedCopybackFixture(existing?: Awaited<ReturnType<typeof seed>>) {
const f = existing ?? await seed(), runId = randomUUID();
const [agent] = await db.insert(agents).values({ companyId: f.companyId, name: "Historical agent", adapterType: "paperclip_runner" }).returning();
const reference = { schema: "paperclip.native-workspace-sync/v3", state: "prepared", workspaceId: f.workspaceId,
leaseId: randomUUID(), providerLeaseId: randomUUID(), remoteCwd: "/workspaces/task",
descriptorSha256: "12".repeat(32), baselineSha256: "34".repeat(32), finalHostSha256: null, resourceDisposition: "stop_and_retain" };
descriptorSha256: "12".repeat(32), baselineSha256: "34".repeat(32), finalHostSha256: null, resourceDisposition: "stop_and_retain" } as const;
await db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: agent!.id, nativeIssueId: f.issueId,
runtimeMode: "native", status: "failed", finishedAt: new Date(), runnerProfileJson: { nativeWorkspaceSync: reference } });
await db.insert(nativeRunFinalizations).values({ companyId: f.companyId, issueId: f.issueId, runId, phase: "terminal_failure" });
@@ -633,6 +637,175 @@ describe.skipIf(!support.supported)("remote workspace migration", () => {
branchName, strategyType: "git_worktree", providerType: "git_worktree", metadata: { createdByRuntime: true, gitBranchOwnershipVersion: 1 } }).where(eq(executionWorkspaces.id, f.workspaceId));
return { ...f, cwd, base, upstream, commit, projectId, projectWorkspaceId, repoUrl, branchName };
}
async function archivedPreparedFixture(sourceKind: "recipe" | "cleanup" | "branch" = "recipe") {
const base = await gitArchiveFixture(), f = { ...base, ...await failedCopybackFixture(base) };
let cleanup: typeof workspaceOperations.$inferSelect | null = null;
if (sourceKind === "recipe") {
await fs.writeFile(path.join(f.cwd, "saved.txt"), "archived staged edit\n"); await git(f.cwd, "add", "saved.txt");
await fs.writeFile(path.join(f.cwd, "saved.txt"), "archived unstaged edit\n");
await fs.writeFile(path.join(f.cwd, "untracked.txt"), "archived private file\n");
const captured = (await captureRestorePoint({ cwd: f.cwd, upstreamCommits: [f.upstream] }))!;
const id = randomUUID(), generation = 1, sealed = await sealRestorePoint(captured.payload,
{ companyId: f.companyId, workspaceId: f.workspaceId, restorePointId: id, generation });
const objectKey = `${f.companyId}/git-restore-points/${f.workspaceId}/${generation}/${id}.pcrp`;
await storage.putFile({ companyId: f.companyId, namespace: "git-restore-points", objectKey,
originalFilename: "saved.pcrp", contentType: "application/octet-stream", body: sealed.ciphertext });
const restorePoint = { schema: "paperclip.git-restore-point.v1", id, generation, objectKey, byteSize: sealed.ciphertext.length,
sha256: sealed.sha256, key: sealed.key, head: captured.manifest.head, index: captured.manifest.index,
worktree: captured.manifest.worktree, ignored: captured.manifest.ignored, modes: captured.manifest.modes, headOnRemote: false };
const contents = await captureGitWorkspaceContents(f.cwd, { companyId: f.companyId, workspaceId: f.workspaceId }, []);
await db.update(executionWorkspaces).set({ status: "archived", closedAt: new Date(), metadata: {
createdByRuntime: true, gitBranchOwnershipVersion: 1, gitCacheRestoration: { schema: "paperclip.git-cache-restoration.v2",
companyId: f.companyId, workspaceId: f.workspaceId, sourceIssueId: f.issueId, repoUrl: f.repoUrl,
commit: f.commit, branchName: f.branchName, sourceKind: "managed_project", projectId: f.projectId,
sourcePath: f.base, worktreePath: f.cwd, gitBranchOwnershipVersion: 1, verifiedAt: new Date().toISOString(), restorePoint, contents },
} }).where(eq(executionWorkspaces.id, f.workspaceId));
await git(f.base, "worktree", "remove", "--force", f.cwd); await git(f.base, "branch", "-D", f.branchName);
} else {
await db.update(executionWorkspaces).set({ status: "archived", closedAt: new Date() }).where(eq(executionWorkspaces.id, f.workspaceId));
if (sourceKind === "cleanup") await git(f.base, "merge", "--ff-only", f.branchName);
await git(f.base, "worktree", "remove", f.cwd);
if (sourceKind === "cleanup") {
const receipt = await git(f.base, "branch", "-d", f.branchName);
[cleanup] = await db.insert(workspaceOperations).values({ companyId: f.companyId, executionWorkspaceId: f.workspaceId,
phase: "worktree_cleanup", status: "succeeded", exitCode: 0, command: `git branch -d ${f.branchName}`,
cwd: f.base, stdoutExcerpt: receipt, startedAt: new Date(), finishedAt: new Date(),
metadata: { cleanupAction: "branch_delete", workspaceId: f.workspaceId, workspacePath: f.cwd, branchName: f.branchName } }).returning();
}
}
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
const [environment] = await db.insert(environments).values({ name: f.runId, driver: "daytona" }).returning();
const [lease] = await db.insert(environmentLeases).values({ id: f.reference.leaseId, companyId: f.companyId,
environmentId: environment.id, heartbeatRunId: f.runId, issueId: f.issueId, executionWorkspaceId: f.workspaceId,
provider: "daytona", providerLeaseId: f.reference.providerLeaseId, status: "retained", leasePolicy: "retain_on_failure",
metadata: { remoteCwd: f.reference.remoteCwd } }).returning();
const cause = "native_workspace_sync_out_unrecoverable";
await db.update(nativeRunFinalizations).set({ failureCode: cause }).where(eq(nativeRunFinalizations.runId, f.runId));
const [hold] = await db.insert(issueRecoveryActions).values({ companyId: f.companyId, sourceIssueId: f.issueId,
kind: "active_run_watchdog", cause, ownerType: "board", ownerAgentId: null, returnOwnerAgentId: run.agentId,
fingerprint: nativeSha256({ runId: f.runId, failureCode: cause }), nextAction: "Preserve retained remote files", evidence: { runId: f.runId } }).returning();
if (sourceKind === "recipe") {
const [selected] = await db.insert(executionWorkspaces).values({ companyId: f.companyId, sourceIssueId: f.issueId,
name: "Current task workspace", providerType: "local_fs", mode: "isolated_workspace", strategyType: "project_primary", cwd: path.join(root, "current-task") }).returning();
await db.update(issues).set({ status: "cancelled", executionWorkspaceId: selected.id }).where(eq(issues.id, f.issueId));
} else await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.issueId));
await db.insert(activityLog).values({ companyId: f.companyId, actorType: "user", actorId: "original owner",
action: "issue.updated", entityType: "issue", entityId: f.issueId, details: { retained: "original task history" } });
const [task] = await db.select().from(issues).where(eq(issues.id, f.issueId));
const [owner] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId));
const history = await db.select().from(activityLog).where(eq(activityLog.entityId, f.issueId));
return { ...f, run, lease, hold, task, owner, history, cleanup, before: await workspace(f.workspaceId) };
}
it.each(["cleanup", "branch"] as const)("preserves a no-recipe archived %s source with prepared recovery", async kind => {
const f = await archivedPreparedFixture(kind);
expect(await migrateRemoteWorkspace({ db, storage, ...f, apply: true })).toMatchObject({ applied: true });
const row = await workspace(f.workspaceId), authority = readRemoteWorkspaceAuthority(row.metadata)!;
expect(row.status).toBe("archived"); expect(row.closedAt).toEqual(f.before.closedAt);
expect(row.metadata).not.toHaveProperty("gitCacheRestoration");
expect((await db.select().from(issues).where(eq(issues.id, f.issueId)))[0]).toEqual(f.task);
expect(await db.select().from(activityLog).where(eq(activityLog.entityId, f.issueId))).toEqual(f.history);
expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.lease.id)))[0]).toEqual(f.lease);
expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)))[0]).toEqual(f.owner);
expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.hold.id)))[0]).toEqual(f.hold);
await expect(readMigratedLegacyWorkspaceSource(db, { companyId: f.companyId, runId: f.runId, reference: f.reference }))
.resolves.toMatchObject({ runId: f.runId, reference: f.reference });
if (f.cleanup) expect((await db.select().from(workspaceOperations).where(eq(workspaceOperations.id, f.cleanup.id)))[0]).toEqual(f.cleanup);
else expect(await git(f.base, "rev-parse", `refs/heads/${f.branchName}`)).toBe(f.commit);
await expect(fs.access(f.cwd)).rejects.toMatchObject({ code: "ENOENT" });
const ref = (await getWorkspaceSnapshot(db, { ...f, snapshotId: authority.snapshotId! }))!;
const archivePath = path.join(root, "no-recipe.pcws"), targetDir = path.join(root, "restored-no-recipe");
await loadWorkspaceSnapshotArchive({ storage, reference: ref, targetPath: archivePath });
await restoreRemoteWorkspaceArchive({ archivePath, targetDir, expectedManifestDigest: ref.manifestDigest });
expect(await git(targetDir, "rev-parse", "HEAD")).toBe(f.commit);
expect(await fs.readFile(path.join(targetDir, "saved.txt"), "utf8")).toBe("original saved work\n");
});
it.each(["cleanup", "branch"] as const)("refuses a no-recipe archived %s source changed during upload", async kind => {
const f = await archivedPreparedFixture(kind), put = storage.putFile.bind(storage); let uploaded = false;
storage.putFile = async input => { const saved = await put(input); uploaded = true;
if (f.cleanup) await db.update(workspaceOperations).set({ status: "failed" }).where(eq(workspaceOperations.id, f.cleanup.id));
else await git(f.base, "update-ref", `refs/heads/${f.branchName}`, f.upstream);
return saved; };
await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).rejects.toThrow();
expect(uploaded).toBe(true);
expect(readRemoteWorkspaceAuthority((await workspace(f.workspaceId)).metadata)).toBeNull();
expect((await db.select().from(issues).where(eq(issues.id, f.issueId)))[0]).toEqual(f.task);
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)))[0]).toEqual(f.run);
expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.lease.id)))[0]).toEqual(f.lease);
await expect(fs.access(f.cwd)).rejects.toMatchObject({ code: "ENOENT" });
});
it("preserves an unselected archived recipe and its pending native files without reopening the task", async () => {
const f = await archivedPreparedFixture(), put = storage.putFile.bind(storage);
let interrupt = true;
storage.putFile = async input => { const saved = await put(input);
if (interrupt) { interrupt = false; throw new Error("archived upload reply lost"); } return saved; };
await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).rejects.toThrow("archived upload reply lost");
const [interrupted] = await db.select().from(workspaceOperations).where(eq(workspaceOperations.phase, "remote_workspace_migration"));
const [pending] = await db.select().from(executionWorkspaceSnapshots);
expect(readRemoteWorkspaceAuthority((await workspace(f.workspaceId)).metadata)).toBeNull();
expect(await migrateRemoteWorkspace({ db, storage, ...f, apply: true })).toMatchObject({ applied: true });
const saved = await workspace(f.workspaceId), authority = readRemoteWorkspaceAuthority(saved.metadata)!;
expect(saved.status).toBe("archived"); expect(saved.closedAt).toEqual(f.before.closedAt);
expect(authority.snapshotId).toBe(pending.id);
expect((await db.select().from(workspaceOperations).where(eq(workspaceOperations.id, interrupted.id)))[0].status).toBe("succeeded");
expect(saved.metadata?.gitCacheRestoration).toEqual(f.before.metadata?.gitCacheRestoration);
expect(saved.metadata?.remoteWorkspaceRecoverySourceRunIds).toEqual([f.runId]);
expect((await db.select().from(issues).where(eq(issues.id, f.issueId)))[0]).toEqual(f.task);
expect(await db.select().from(activityLog).where(eq(activityLog.entityId, f.issueId))).toEqual(f.history);
expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)))[0]).toEqual(f.owner);
expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.lease.id)))[0]).toEqual(f.lease);
expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.hold.id)))[0]).toEqual(f.hold);
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
const marker = { schema: "paperclip.legacy-workspace-recovery-migration.v1", operationId: expect.any(String), workspaceId: f.workspaceId };
expect(run).toEqual({ ...f.run, updatedAt: expect.any(Date), runnerProfileJson: { ...f.run.runnerProfileJson, legacyWorkspaceRecoveryMigration: marker } });
await expect(readMigratedLegacyWorkspaceSource(db, { companyId: f.companyId, runId: f.runId,
reference: f.reference })).resolves.toMatchObject({ runId: f.runId, reference: f.reference });
await expect(fs.access(f.cwd)).rejects.toMatchObject({ code: "ENOENT" });
const ref = (await getWorkspaceSnapshot(db, { ...f, snapshotId: authority.snapshotId! }))!;
const archivePath = path.join(root, "archived-native.pcws"), targetDir = path.join(root, "restored-native");
await loadWorkspaceSnapshotArchive({ storage, reference: ref, targetPath: archivePath });
await restoreRemoteWorkspaceArchive({ archivePath, targetDir, expectedManifestDigest: ref.manifestDigest });
expect(await git(targetDir, "show", ":saved.txt")).toBe("archived staged edit");
expect(await fs.readFile(path.join(targetDir, "saved.txt"), "utf8")).toBe("archived unstaged edit\n");
expect(await fs.readFile(path.join(targetDir, "untracked.txt"), "utf8")).toBe("archived private file\n");
await migrateRemoteWorkspace({ db, storage, ...f, apply: true });
expect((await db.select().from(workspaceOperations).where(eq(workspaceOperations.phase, "remote_workspace_migration")))).toHaveLength(1);
});
it.each(["recipe", "reference", "provider"])("refuses an archived prepared source changed during upload (%s)", async change => {
const f = await archivedPreparedFixture(), put = storage.putFile.bind(storage);
let uploaded = false;
storage.putFile = async input => {
const saved = await put(input); uploaded = true;
if (change === "recipe") await db.update(executionWorkspaces).set({ metadata: { ...f.before.metadata,
remoteWorkspaceMigration: (await workspace(f.workspaceId)).metadata?.remoteWorkspaceMigration,
gitCacheRestoration: { ...f.before.metadata!.gitCacheRestoration as object, commit: f.upstream } } }).where(eq(executionWorkspaces.id, f.workspaceId));
else {
const reference = { ...f.reference, ...(change === "reference" ? { baselineSha256: "56".repeat(32) } : { providerLeaseId: randomUUID() }) };
if (change === "provider") await db.update(environmentLeases).set({ providerLeaseId: reference.providerLeaseId }).where(eq(environmentLeases.id, f.lease.id));
await db.update(heartbeatRuns).set({ runnerProfileJson: { ...f.run.runnerProfileJson, nativeWorkspaceSync: reference } }).where(eq(heartbeatRuns.id, f.runId));
}
return saved;
};
await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).rejects.toThrow();
expect(uploaded).toBe(true);
expect(readRemoteWorkspaceAuthority((await workspace(f.workspaceId)).metadata)).toBeNull();
expect((await db.select().from(issues).where(eq(issues.id, f.issueId)))[0]).toEqual(f.task);
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)))[0].runnerProfileJson).not.toHaveProperty("legacyWorkspaceRecoveryMigration");
await expect(fs.access(f.cwd)).rejects.toMatchObject({ code: "ENOENT" });
});
it("refuses a competing native F owner before capturing an archived prepared source", async () => {
const f = await archivedPreparedFixture();
let release!: () => void, entered!: () => void;
const held = new Promise<void>(done => { release = done; }), ready = new Promise<void>(done => { entered = done; });
const owner = db.transaction(async tx => { expect(await tryLockNativeWorkspaceFinalization(tx as unknown as typeof db,
{ companyId: f.companyId, runId: f.runId })).toBe(true); entered(); await held; });
await ready;
try {
await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).rejects.toThrow("remote_copyback_owned");
expect(readRemoteWorkspaceAuthority((await workspace(f.workspaceId)).metadata)).toBeNull();
expect(await db.select().from(executionWorkspaceSnapshots)).toHaveLength(0);
expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)))[0]).toEqual(f.owner);
} finally { release(); await owner; }
});
it.each(["legacy", "verified", "retry"])("recovers an archived Git workspace from its exact branch-deletion receipt (%s)", async receiptKind => {
const f = await gitArchiveFixture(), closedAt = new Date();
await db.update(executionWorkspaces).set({ status: "archived", closedAt }).where(eq(executionWorkspaces.id, f.workspaceId));
@@ -1143,7 +1316,7 @@ describe.skipIf(!support.supported)("remote workspace migration", () => {
const f = await seed(), closedAt = new Date("2026-10-20T12:00:00Z");
await db.update(executionWorkspaces).set({ status: "archived", closedAt }).where(eq(executionWorkspaces.id, f.workspaceId));
await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.issueId));
await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).resolves.toMatchObject({ applied: true });
expect(await migrateRemoteWorkspace({ db, storage, ...f, apply: true })).toMatchObject({ applied: true });
const saved = await workspace(f.workspaceId), authority = readRemoteWorkspaceAuthority(saved.metadata)!;
expect(saved.status).toBe("archived"); expect(saved.closedAt).toEqual(closedAt);
const [issue] = await db.select().from(issues).where(eq(issues.id, f.issueId));
@@ -160,7 +160,8 @@ async function inspect(db: ReadDb, input: { companyId: string; workspaceId: stri
sql`${heartbeatRuns.runnerProfileJson}->'nativeWorkspaceSync'->>'state' in ('prepared', 'finalized')`,
));
const legacyRecoverySources: LegacyWorkspaceRecoverySource[] = [];
const onlineRecoveryAllowed = Boolean(input.onlineSource) && !input.writersStopped;
const onlineRecoveryAllowed = !input.writersStopped
&& Boolean(input.onlineSource || workspace.status === "archived" && archivedGitSource);
for (const run of referencedRuns.filter(run => object(run.reference).state === "prepared").sort((a, b) => a.id.localeCompare(b.id))) {
if (onlineRecoveryAllowed) {
const source = await inspectOnlineLegacyWorkspaceRecoverySource(db, { workspace, runId: run.id });
@@ -414,11 +415,12 @@ type ReservedMigration = Awaited<ReturnType<typeof reserveMigration>>;
type MigrationPlan = { input: MigrationInput; onlineSource?: OnlineWorkspaceSource; reserved: ReservedMigration };
async function lockMigrationRecovery(lock: MigrationTransaction, plans: MigrationPlan[], cohort?: WorkspaceMigrationCohort) {
const online = plans.filter(plan => plan.onlineSource);
const online = plans.filter(plan => !plan.input.writersStopped
&& (plan.onlineSource || plan.reserved.workspace.status === "archived" && plan.reserved.archivedGitSource));
if (!online.length) return;
if (!await lockOnlineLegacyWorkspaceRecoverySources(lock as unknown as Db, { companyId: online[0].input.companyId,
sources: online.flatMap(({ reserved, onlineSource }) => [...reserved.legacyRecoverySources, ...onlineSource!.companions.flatMap(proof => proof.sources)]),
holds: online.flatMap(({ reserved, onlineSource }) => [...reserved.onlineRecoveryHolds, ...onlineSource!.companions.flatMap(proof => proof.holds)]) }))
sources: online.flatMap(({ reserved, onlineSource }) => [...reserved.legacyRecoverySources, ...(onlineSource?.companions.flatMap(proof => proof.sources) ?? [])]),
holds: online.flatMap(({ reserved, onlineSource }) => [...reserved.onlineRecoveryHolds, ...(onlineSource?.companions.flatMap(proof => proof.holds) ?? [])]) }))
throw new Error("remote_workspace_migration_blocked:remote_copyback_owned");
const readers = await Promise.allSettled(online.map(async ({ input, onlineSource, reserved }) => {
const current = await inspect(input.db, { ...input, onlineSource, operationId: reserved.operation!.id }, cohort);
@@ -429,17 +431,32 @@ async function lockMigrationRecovery(lock: MigrationTransaction, plans: Migratio
for (const reader of readers) if (reader.status === "rejected") throw reader.reason;
}
function createMigrationChildVerifier(input: MigrationInput, onlineSource: OnlineWorkspaceSource | undefined, sourceLock: MigrationTransaction) {
function createMigrationChildVerifier(input: MigrationInput, onlineSource: OnlineWorkspaceSource | undefined, sourceLock: MigrationTransaction, cohort = false) {
if (onlineSource?.kind !== "git") return undefined;
const verifier = createNestedWorkspaceImportVerifier({ db: input.db, storage: input.storage, companyId: input.companyId,
sourceLock, projectIds: onlineSource.projectIds, issueIds: onlineSource.issueIds, signal: input.signal, persistVerification: true });
type Options = Parameters<typeof prepareNestedWorkspaceImports>[0];
const initial = new Map<string, ReturnType<typeof prepareNestedWorkspaceImports>>(), final = new Map<string, ReturnType<typeof prepareNestedWorkspaceImports>>();
let pending = Promise.resolve();
const prepare = (options: Options) => {
const work = pending.then(() => verifier.prepare(options));
pending = work.then(() => undefined, () => undefined);
return work;
};
const shared = async (options: Options, cache: typeof initial) => {
await verifier.assertOwner();
const root = options.workspace.cwd ?? options.workspace.providerRef;
const key = canonical([root ? await fs.realpath(root) : null, [...(options.gitSourceRoots ?? [])].sort(), options.recordedChildren ?? null]);
let work = cache.get(key);
if (!work) { work = prepare(options); cache.set(key, work); }
const result = await work;
await verifier.assertOwner();
return result;
};
return {
prepare(options: Parameters<typeof prepareNestedWorkspaceImports>[0]) {
const work = pending.then(() => verifier.prepare(options));
pending = work.then(() => undefined, () => undefined);
return work;
},
prepare: (options: Options) => cohort ? shared(options, initial) : prepare(options),
finalize: (options: Options) => shared(options, final),
deferFinal: cohort,
async close() { await pending; await verifier.close(); },
};
}
@@ -509,7 +526,7 @@ async function captureMigration(input: MigrationInput, reserved: ReservedMigrati
const current = await captureRemoteWorkspaceDirectory({ cwd: sourceRoot!, archivePath: currentArchive, exclude, requireNoGit: onlineSource?.kind === "ordinary", gitSourceRoots: onlineSource?.gitSourceRoots, signal: input.signal });
if (current.manifestDigest !== captured.manifestDigest) throw new Error("remote_workspace_migration_source_changed");
}
if (nested.length) {
if (nested.length && !childVerifier?.deferFinal) {
const verifyScratch = path.join(scratch, "verify-nested"); await fs.mkdir(verifyScratch);
const verified = await (childVerifier?.prepare ?? prepareNestedWorkspaceImports)({ ...input, workspace: reserved.workspace,
scratch: verifyScratch, recordedChildren: nested, gitSourceRoots: onlineSource?.gitSourceRoots });
@@ -531,9 +548,9 @@ async function validateMigrationPublication(tx: MigrationTransaction, input: Mig
|| journal.issueId !== operation.issueId || journal.cwd !== operation.cwd
|| canonical(journal.metadata) !== canonical(operation.metadata)) throw new Error("workspace_cohort_journal_changed");
}
await lockMigrationParents(tx, input.companyId, reserved.workspace.sourceIssueId, onlineSource ? [
await lockMigrationParents(tx, input.companyId, reserved.workspace.sourceIssueId, onlineSource || reserved.archivedGitSource ? [
...reserved.legacyRecoverySources.map(source => source.issueId),
...onlineSource.companions.flatMap(proof => proof.sources.map(source => source.issueId)),
...(onlineSource?.companions.flatMap(proof => proof.sources.map(source => source.issueId)) ?? []),
] : []);
for (const actionId of [...new Set([...reserved.finalizedRecoveryHolds, ...reserved.onlineRecoveryHolds].map(held => held.actionId))].sort()) {
await tx.select({ id: issueRecoveryActions.id }).from(issueRecoveryActions).where(and(
@@ -741,6 +758,7 @@ export async function migrateRemoteWorkspaceCohort(input: {
const sourceProof = createHash("sha256").update(canonical({ scope: scopeIdentity(members[0].onlineSource),
members: initial.map(workspace => ({ workspaceId: workspace.id, fingerprint: fingerprint(workspace) })) })).digest("hex");
const pending = [];
let unchangedMembers = true;
for (const workspace of initial) {
const marker = object(workspace.metadata?.remoteWorkspaceMigration);
if (marker.schema !== SCHEMA || typeof marker.operationId !== "string") continue;
@@ -749,11 +767,14 @@ export async function migrateRemoteWorkspaceCohort(input: {
eq(workspaceOperations.id, marker.operationId), eq(workspaceOperations.phase, "remote_workspace_migration")));
if (!operation?.metadata?.cohortMigration) throw new Error("workspace_cohort_foreign_journal");
if (operation.status !== "running" || operation.finishedAt !== null) throw new Error("workspace_cohort_journal_changed");
unchangedMembers &&= marker.sourceFingerprint === fingerprint(workspace)
&& operation.metadata.sourceFingerprint === marker.sourceFingerprint;
pending.push(cohortSchema.parse(operation.metadata.cohortMigration));
}
const cohort: WorkspaceMigrationCohort = pending[0] ?? { schema: "paperclip.remote-workspace-cohort.v1", id: randomUUID(), companyId,
let cohort: WorkspaceMigrationCohort = pending[0] ?? { schema: "paperclip.remote-workspace-cohort.v1", id: randomUUID(), companyId,
sourceProof, members: workspaceIds.map(workspaceId => ({ workspaceId, operationId: randomUUID() })) };
if (cohort.companyId !== companyId || cohort.sourceProof !== sourceProof
const refreshSourceProof = cohort.sourceProof !== sourceProof;
if (cohort.companyId !== companyId || refreshSourceProof && (pending.length !== workspaceIds.length || !unchangedMembers)
|| canonical(cohort.members.map(member => member.workspaceId)) !== canonical(workspaceIds)
|| new Set(cohort.members.map(member => member.operationId)).size !== workspaceIds.length
|| pending.some(marker => canonical(marker) !== canonical(cohort))) throw new Error("workspace_cohort_membership_changed");
@@ -785,8 +806,44 @@ export async function migrateRemoteWorkspaceCohort(input: {
return reservation.value;
});
await lockMigrationRecovery(lock, plans, cohort);
if (refreshSourceProof) {
const refreshedCohort = { ...cohort, sourceProof };
const operations = await input.db.transaction(async tx => {
await lockMigrationParents(tx, companyId, null, plans.flatMap(plan => [plan.reserved.workspace.sourceIssueId!,
...plan.reserved.legacyRecoverySources.map(source => source.issueId),
...plan.onlineSource!.companions.flatMap(proof => proof.sources.map(source => source.issueId))]));
const locked = await tx.select().from(executionWorkspaces).where(and(eq(executionWorkspaces.companyId, companyId),
inArray(executionWorkspaces.id, workspaceIds))).orderBy(executionWorkspaces.id).for("update");
if (locked.length !== plans.length || plans.some(plan => {
const workspace = locked.find(row => row.id === plan.input.workspaceId)!;
return fingerprint(workspace) !== plan.reserved.sourceFingerprint
|| canonical(workspace.metadata?.remoteWorkspaceMigration) !== canonical(plan.reserved.workspace.metadata?.remoteWorkspaceMigration);
})) throw new Error("workspace_cohort_source_changed");
await preflight(tx);
const updated = [];
for (const plan of plans) {
signal.throwIfAborted();
const operation = plan.reserved.operation!;
const [current] = await tx.update(workspaceOperations).set({ metadata: { ...operation.metadata,
cohortMigration: refreshedCohort }, updatedAt: new Date() }).where(and(
eq(workspaceOperations.companyId, companyId), eq(workspaceOperations.executionWorkspaceId, plan.input.workspaceId),
eq(workspaceOperations.id, operation.id), eq(workspaceOperations.phase, "remote_workspace_migration"),
eq(workspaceOperations.status, "running"), sql`${workspaceOperations.finishedAt} is null`,
sql`${workspaceOperations.issueId} is not distinct from ${operation.issueId}::uuid`,
sql`${workspaceOperations.cwd} is not distinct from ${operation.cwd}`,
eq(workspaceOperations.metadata, operation.metadata!))).returning();
if (!current) throw new Error("workspace_cohort_journal_changed");
updated.push(current);
}
await lock.execute(sql`select 1`);
signal.throwIfAborted();
return updated;
});
for (const [index, plan] of plans.entries()) plan.reserved.operation = operations[index];
cohort = refreshedCohort;
}
const captures: Array<CapturedMigration | undefined> = Array(plans.length);
const childVerifier = createMigrationChildVerifier(plans[0].input, plans[0].onlineSource, lock);
const childVerifier = createMigrationChildVerifier(plans[0].input, plans[0].onlineSource, lock, true);
let next = 0, failure: unknown;
const worker = async () => {
while (!signal.aborted && next < plans.length) {
@@ -800,6 +857,15 @@ export async function migrateRemoteWorkspaceCohort(input: {
for (const peer of peers) if (peer.status === "rejected") failure ??= peer.reason;
if (failure) throw failure;
signal.throwIfAborted();
const nestedReaders = await Promise.allSettled(plans.map(async (plan, index) => {
const captured = captures[index]!;
if (!captured.nested.length) return;
const scratch = path.join(captured.scratch, "verify-nested"); await fs.mkdir(scratch);
const verified = await (childVerifier?.finalize ?? prepareNestedWorkspaceImports)({ ...plan.input, workspace: plan.reserved.workspace,
scratch, recordedChildren: captured.nested, gitSourceRoots: plan.onlineSource?.gitSourceRoots });
if (canonical(verified) !== canonical(captured.nested)) throw new Error("nested_workspace_source_changed");
}));
for (const reader of nestedReaders) if (reader.status === "rejected") throw reader.reason;
await lock.execute(sql`select 1`);
await lock.transaction(async tx => {
await lockMigrationParents(tx, companyId, null, plans.flatMap(plan => [
+10
View File
@@ -588,6 +588,16 @@ foreign inodes fail before any signal. Native Linux calibration exercises both
descriptor launches with synthetic owned processes and no provider credentials;
it does not qualify paid Pi behavior or change previous failed grades.
These fixtures run without `paperclip-runnerd --trusted-launch-root`, so the
Runner still hands providers a sealed memfd Node and the memfd assertions above
are unchanged. Under a trusted launch root (the agent computer's read-only Runner
ROM) the Runner instead holds the ROM's own Node file. Kimi admission then takes
its existing linked-descriptor branch: one link, the same inode as the parent's
`/proc/<pid>/exe`, and the complete bytes hashed against `nodeSha256`. It never
accepts that file as a memfd. Pi admission binds to the native distribution
snapshot's Node, which the ACPX closure copies whether or not a trusted root is
set.
The private resource-admission marker and raw cleanup results control recovery-state retention independently of evidence packaging. A worker crash after admission keeps the owner-only recovery database; a confirmed pre-allocation bootstrap failure does not. Neither the marker nor the database enters published evidence.
## Task workspace fixture source
+2
View File
@@ -1,3 +1,4 @@
import { CancelledError } from "@tanstack/react-query";
import { describe, expect, it } from "vitest";
import { ApiError } from "./api-error";
import {
@@ -37,6 +38,7 @@ describe("classifyError", () => {
["422", apiError(422), "invalid"],
["500", apiError(500, { error: "boom" }), "unknown"],
["an abort", new DOMException("Aborted", "AbortError"), "aborted"],
["a React Query cancellation", new CancelledError({ revert: false }), "aborted"],
["a programming TypeError", new TypeError("Cannot read properties of undefined"), "unknown"],
["a plain Error", new Error("nope"), "unknown"],
["undefined", undefined, "unknown"],
+5 -2
View File
@@ -12,6 +12,8 @@
* by hand-rolled fetches (health, uploads) classify the same way.
*/
import { CancelledError } from "@tanstack/react-query";
export type ErrorKind =
| "transient"
| "auth"
@@ -181,8 +183,9 @@ function readableServerMessage(err: unknown): string | null {
// --- Classification ---------------------------------------------------------------
function isAbortError(err: unknown): boolean {
const name = record(err)?.name;
return name === "AbortError" || name === "CancelledError";
// React Query's `CancelledError` keeps the default `name` ("Error"), so it
// can only be recognized by class.
return record(err)?.name === "AbortError" || err instanceof CancelledError;
}
function isNetworkTypeError(err: unknown): boolean {
@@ -13,7 +13,7 @@ import { parseRunnerGoalCommand, TaskChatComposer } from "./TaskChatComposer";
import { ComposerAddMenu } from "./ComposerAddMenu";
import { QuestionForm } from "./QuestionForm";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { Agent, HeartbeatRun } from "@paperclipai/shared";
import type { Agent, HeartbeatRun, IssueWorkMode } from "@paperclipai/shared";
import { agentsApi } from "@/api/agents";
import { instanceSettingsApi } from "@/api/instanceSettings";
import { CoordinatorPresentation } from "@/components/coordinator/CoordinatorPresentation";
@@ -1201,6 +1201,143 @@ describe("TaskChatComposer", () => {
expect(onAdd).toHaveBeenCalledTimes(2);
});
it("reflects an externally updated task mode after mounting", async () => {
const onAdd = vi.fn();
const onWorkModeChange = vi.fn();
renderComposer({ onAdd, onWorkModeChange, workMode: "standard" });
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')).toBeNull();
renderComposer({ onAdd, onWorkModeChange, workMode: "planning" });
await flushAsync();
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')?.getAttribute("data-pending-work-mode"))
.toBe("planning");
});
it("keeps a local draft mode while persisted task data refreshes", async () => {
const onAdd = vi.fn();
const onWorkModeChange = vi.fn();
renderComposer({ onAdd, onWorkModeChange, workMode: "standard" });
pressKey("Tab", { shiftKey: true });
renderComposer({ onAdd, onWorkModeChange, workMode: "ask" });
await flushAsync();
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')?.getAttribute("data-pending-work-mode"))
.toBe("planning");
expect(onWorkModeChange).not.toHaveBeenCalled();
// Matching task data does not acknowledge an unsent local choice.
renderComposer({ onAdd, onWorkModeChange, workMode: "planning" });
renderComposer({ onAdd, onWorkModeChange, workMode: "standard" });
await flushAsync();
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')?.getAttribute("data-pending-work-mode"))
.toBe("planning");
});
it("keeps the chosen mode and message when an optimistic mode save rolls back", async () => {
const onAdd = vi.fn();
let rejectSave!: () => void;
function OptimisticModeHarness() {
const [workMode, setWorkMode] = useState<IssueWorkMode>("standard");
return <TaskChatComposer onAdd={onAdd} workMode={workMode} onWorkModeChange={(mode) => {
setWorkMode(mode);
return new Promise<void>((_resolve, reject) => {
rejectSave = () => {
setWorkMode("standard");
reject(new Error("Mode save rejected"));
};
});
}} />;
}
render(<OptimisticModeHarness />);
pressKey("Tab", { shiftKey: true });
typeText("Keep this planning message");
pressKey("Enter");
await flushAsync();
await act(async () => rejectSave());
await flushAsync();
expect(editable().textContent).toBe("Keep this planning message");
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')?.getAttribute("data-pending-work-mode"))
.toBe("planning");
expect(onAdd).not.toHaveBeenCalled();
});
it.each([
["standard", "planning", "standard"],
["ask", "standard", "ask"],
] as const)("keeps next draft mode %s → %s → %s through successful send", async (savedMode, sentMode, nextMode) => {
let resolveSend!: () => void;
const onAdd = vi.fn().mockReturnValue(new Promise<void>((resolve) => { resolveSend = resolve; }));
function PendingSendHarness() {
const [workMode, setWorkMode] = useState<IssueWorkMode>(savedMode);
return <TaskChatComposer onAdd={onAdd} workMode={workMode}
onWorkModeChange={async (mode) => { setWorkMode(mode); }} />;
}
const selectedMode = () => container.querySelector('[data-testid="task-chat-composer-mode"]')
?.getAttribute("data-pending-work-mode") ?? "standard";
render(<PendingSendHarness />);
pressKey("Tab", { shiftKey: true });
expect(selectedMode()).toBe(sentMode);
typeText("First message");
pressKey("Enter");
await flushAsync();
expect(onAdd).toHaveBeenCalledTimes(1);
if (nextMode === "standard") {
flushSync(() => container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-mode"]')!.click());
} else {
pressKey("Tab", { shiftKey: true });
pressKey("Tab", { shiftKey: true });
}
expect(selectedMode()).toBe(nextMode);
typeText("Next message");
await act(async () => resolveSend());
await flushAsync();
expect(selectedMode()).toBe(nextMode);
expect(editable().textContent).toBe("Next message");
});
it.each([
["receipt", false], ["receipt", true],
["resend", false], ["resend", true],
] as const)("settles the sent mode through %s without clearing a newer choice (%s)", async (method, newerChoice) => {
const key = `mode-settlement-${method}-${newerChoice}`;
const onAdd = vi.fn().mockRejectedValueOnce(new CommentSubmissionUnknownError()).mockResolvedValue(undefined);
const onWorkModeChange = vi.fn().mockResolvedValue(undefined);
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
client.setQueryData(queryKeys.auth.session, { user: { id: "user-1" } });
const show = (workMode: IssueWorkMode, confirmedSubmissionIds = new Set<string>()) => render(
<QueryClientProvider client={client}><TaskChatComposer onAdd={onAdd} workMode={workMode}
onWorkModeChange={onWorkModeChange} draftKey={key} confirmedSubmissionIds={confirmedSubmissionIds} /></QueryClientProvider>,
);
show("standard");
await flushAsync();
pressKey("Tab", { shiftKey: true });
typeText("First message");
pressKey("Enter", { metaKey: true });
await flushAsync();
expect(onAdd).toHaveBeenCalledTimes(1);
const intent = loadDraftSubmission(key)!;
expect(intent).not.toBeNull();
show("planning");
if (newerChoice) pressKey("Tab", { shiftKey: true });
if (method === "receipt") show("planning", new Set([intent.attemptId]));
else {
const resend = Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Resend now")!;
flushSync(() => resend.click());
}
await flushAsync();
expect(loadDraftSubmission(key)).toBeNull();
show("standard");
await flushAsync();
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')?.getAttribute("data-pending-work-mode") ?? "standard")
.toBe(newerChoice ? "ask" : "standard");
expect(onAdd).toHaveBeenCalledTimes(method === "receipt" ? 1 : 2);
if (method === "resend") expect(onAdd.mock.calls[1]?.[4]).toBe(intent.attemptId);
client.clear();
});
it("cycles the pending mode with Shift+Tab and applies it on submit", async () => {
const onAdd = vi.fn().mockResolvedValue(undefined);
const onWorkModeChange = vi.fn().mockResolvedValue(undefined);
@@ -1226,6 +1363,11 @@ describe("TaskChatComposer", () => {
expect(onWorkModeChange).toHaveBeenCalledWith("planning");
expect(onAdd).toHaveBeenCalledWith("do the plan", undefined, undefined, undefined, expect.any(String));
renderComposer({ onAdd, onWorkModeChange, workMode: "ask" });
await flushAsync();
expect(container.querySelector('[data-testid="task-chat-composer-mode"]')?.getAttribute("data-pending-work-mode"))
.toBe("ask");
});
it("cycles Auto, Plan, and Ask modes with Cmd+Period while focused", () => {
@@ -354,7 +354,7 @@ type ComposerAttachment = {
type QueuedEditBackup = {
body: string;
attachments: ComposerAttachment[];
pendingMode: IssueWorkMode;
pendingMode: IssueWorkMode | null;
pendingAssignee: string | null;
};
@@ -451,8 +451,10 @@ export function TaskChatComposer({
useState<HTMLElement | null>(null);
const [takeoverControlsSlot, setTakeoverControlsSlot] =
useState<HTMLElement | null>(null);
const [localPendingMode, setPendingMode] = useState<IssueWorkMode>(workMode);
const pendingMode = creation ? workMode : localPendingMode;
const [pendingModeOverride, setPendingMode] = useState<IssueWorkMode | null>(null);
const modeChoiceGeneration = useRef(0);
const sentModeChoice = useRef<{ attemptId: string; generation: number } | null>(null);
const pendingMode = creation ? workMode : pendingModeOverride ?? workMode;
const [pendingAssignee, setPendingAssignee] = useState<string | null>(null);
const coordinator = useCoordinatorPresentation();
const [localRunSettings, setLocalRunSettings] = useState<ComposerRunSettings | null>(null);
@@ -556,7 +558,7 @@ export function TaskChatComposer({
queuedEditBackupRef.current = {
body: bodyRef.current,
attachments: attachmentsRef.current,
pendingMode,
pendingMode: pendingModeOverride,
pendingAssignee: pendingAssigneeRef.current,
};
if (draftKey) saveDraft(draftKey, bodyRef.current);
@@ -584,7 +586,7 @@ export function TaskChatComposer({
}
previousQueuedEditIdRef.current = nextId;
}, [draftKey, pendingMode, queuedEdit]);
}, [draftKey, pendingModeOverride, queuedEdit]);
useEffect(() => {
if (!draftKey || queuedEdit) return;
@@ -704,10 +706,18 @@ export function TaskChatComposer({
}
function changeMode(mode: IssueWorkMode) {
modeChoiceGeneration.current += 1;
setPendingMode(mode);
if (creation) void onWorkModeChange?.(mode);
}
function settleSentMode(attemptId: string) {
const choice = sentModeChoice.current;
if (choice?.attemptId !== attemptId) return;
if (modeChoiceGeneration.current === choice.generation) setPendingMode(null);
sentModeChoice.current = null;
}
async function uploadImage(file: File): Promise<string> {
const id = crypto.randomUUID();
setAttachments((prev) => [
@@ -926,6 +936,7 @@ export function TaskChatComposer({
const submittedBody = bodyRef.current;
const submittedAttachments = attachmentsRef.current;
const submittedAssignee = pendingAssigneeRef.current;
const submittedModeGeneration = modeChoiceGeneration.current;
const trimmed = submittedBody.trim();
const goalCommand = queuedEdit
? ({ matched: false } as const)
@@ -1088,6 +1099,7 @@ export function TaskChatComposer({
pendingDraftRef.current = { draftKey, attemptId, submittedBody, submittedAttachmentIds: attachmentIds, request, requestOwner };
changeBody(bodyRef.current);
}
sentModeChoice.current = { attemptId, generation: submittedModeGeneration };
if (runSettings) {
await onAdd(fullBody, reopen, reassignment, attachmentIds.length ? attachmentIds : undefined, attemptId, runSettings);
} else {
@@ -1098,6 +1110,7 @@ export function TaskChatComposer({
if (draftKey) settleDraftSubmission(draftKey, attemptId,
mountedTaskKey.current === draftKey ? bodyRef.current : undefined);
if (mountedTaskKey.current !== draftKey) return;
settleSentMode(attemptId);
const submittedIds = new Set(submittedAttachments.map((item) => item.id));
setAttachments((current) =>
current.filter((item) => !submittedIds.has(item.id)),
@@ -1149,6 +1162,7 @@ export function TaskChatComposer({
const settlementKey = JSON.stringify([draftKey, submission.attemptId]);
if (settledSubmissionIds.current.has(settlementKey)) return;
settledSubmissionIds.current.add(settlementKey);
settleSentMode(submission.attemptId);
const nextDraft = submission.nextDraftOffset === undefined
? "" : bodyRef.current.slice(submission.nextDraftOffset);
if (draftKey) settleDraftSubmission(draftKey, submission.attemptId, nextDraft);
+11
View File
@@ -278,6 +278,17 @@ describe("createAppQueryClient", () => {
unsubscribe();
});
it("does not report a query that was cancelled without reverting", async () => {
const queryFn = vi.fn(() => new Promise<string>(() => {}));
const observer = new QueryObserver(client, { queryKey: ["issues", "detail", "PAP-1"], queryFn });
const unsubscribe = observer.subscribe(() => {});
await vi.advanceTimersByTimeAsync(0);
await client.cancelQueries({ queryKey: ["issues", "detail"] }, { revert: false });
expect(observer.getCurrentResult().error?.message).toBe("CancelledError");
expect(reportError).not.toHaveBeenCalled();
unsubscribe();
});
it("leaves a cache-only alias stale instead of refetching it without a queryFn", async () => {
client.setQueryData(["issues", "detail", "issue-uuid"], { id: "issue-uuid", title: "Seeded" });
const queryFn = vi.fn(async () => "fetched");