From 3452639a819b7940b83b0189d0bd1d6818cc7c82 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:53:55 -0600 Subject: [PATCH 01/13] fix(runner): reject only the overflow call when parallel tool calls exceed the result reserve (#21913) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Native agent runs call Paperclip tools through the runner's provider tool bridge > - The bridge reserves 768 KiB for each pending call against an 8 MiB budget per turn > - When an agent sends many tool calls in parallel, the reserve for the pending calls can go over the budget, although the bytes the turn really holds are small > - The bridge then reports the durable receipt limit, and the backend stops the whole turn. The run ends as cancelled with `needs_review`, and the task stays blocked with a Retry button > - This pull request rejects only the overflow call as retryable, and keeps the turn stop for real held bytes. It also adds a server backstop: a turn stopped at the receipt limit continues by itself in a fresh session > - The benefit is that a parallel burst of tool calls no longer leaves a task waiting for a person ## Linked Issues or Issue Description **What happened?** In a restart-chaos wave, an opencode agent sent 10 parallel `get_task` calls. The turn already held about 0.7 MB of results. 10 × 768 KiB plus 0.7 MB is more than 8 MiB, so `begin_call` returned `active_turn_receipt_limit()` for the 10th call. This branch does not set `durable_run_receipt_limit_reached`, so it is a temporary reserve overflow. `handle_tool_call` sends every receipt-limit error to `stop_turn_at_tool_receipt_limit`, which interrupts the turn. The run ended as cancelled with `needs_review` and a human review request. The release then blocked the task (`native_continuation_requires_reconciliation`) and showed Retry. No continuation was scheduled. The task moved again only because a person posted a comment ten minutes later. **Expected behavior** The overflow call gets a normal, retryable rejection, and the turn continues. The agent can send the call again after a pending result arrives. If a turn does stop at the receipt limit, Paperclip continues the task in a fresh session, as it does for `agent_tool_call_loop` (#21734). The task does not show Retry. **Steps to reproduce** 1. Start a native turn that holds about 600 KiB of settled tool results. 2. Send 10 tool calls in parallel. 3. On master, the 10th call stops the turn, and the task becomes blocked with Retry. **Paperclip version or commit** `master` at c5218f5ec4 (wave), rebased on 991f773d7f. ## What Changed - `provider_bridge.rs`: the two `begin_call` branches that fail only because of the per-call result reserve now return a new retryable error (`tool_calls_in_flight`). The provider sees "Too many tool calls are in flight. This call was not executed. Wait for the pending tool results, then retry it." The branches that set `durable_run_receipt_limit_reached` (real held bytes, exact identity capacity, saturated replay history) still stop the turn. - `provider_backend.rs`: the invalid tool call result sets `retryable` from the error, so this rejection is `retryable: true`. Other rejections stay `false`. - `native-tool-receipt-limit.ts` (new): reads the persisted, source-bound `harness.diagnostic` event with code `semantic_tool_turn_receipt_limit` for the run, and holds the lane constants and the hint for the next session. - `status-arbiter.ts`: a run that did not succeed and whose runner stopped it at the receipt limit preserves the task status and schedules a retry with cause `semantic_tool_turn_receipt_limit` (and releases run resources when it was cancelled). This applies only when the task owner holds the decision, with no review, governance gate, open blocker, pause hold or prior `blocked` status, and at most 2 times per chain. Other cases keep their current path. - `native-provider-capacity-retry.ts`: the capacity retry is now one lane of a shared fresh-session retry helper. The new receipt-limit lane creates a `scheduled_retry` run due in 5 seconds with `forceFreshSession` and a liveness instruction that tells the agent to make fewer parallel calls. - `status-decision-committer.ts` and `native-run-finalizer.ts`: wire the new lane, and require the task owner under the issue lock, as for the capacity retry. - `acpx_provider_session.rs` (Claude, Cursor and other ACPX agents) handles the same retryable error per call: it drops the pending sidecar call and resolves only that call with the retryable error. Other `begin_call` errors still fail closed. - The external provider path (Dot/Muse) is out of scope and unchanged: it still fails closed on this overflow, as on master. Making a same-requestId retry safe there needs retry generations across the executor, the driver command ids and the broker receipts. That is a follow-up. - The receipt-limit backstop reads only the diagnostic of the final turn in the run's session. - A person's Stop always wins: the finalizer re-reads the saved Stop on each arbitration attempt, the retry helper refuses under the run lock, and the #21734 tool-call loop continuation is not queued, or is cancelled, for a stopped run. The runner change is runner-image content. The Daytona runner image must be rebuilt before sandboxes get the runner fix. The server backstop works with older images. ## Verification - Red then green, `provider_bridge.rs` unit test `parallel_calls_over_the_result_reserve_reject_only_the_overflow_call`: with about 600 KiB settled, 9 calls are admitted. On master the 10th returns `is_active_turn_receipt_limit()`. Now it is a retryable rejection, the durable flag stays false, and the same call is admitted after one pending result settles. - Negative, `held_result_bytes_over_the_limit_still_stop_the_turn`: real held bytes over the limit still return the receipt limit with the durable flag set. - `cargo test -p paperclip-runner-core -- --skip task_memory::`: all pass (640 lib tests plus the integration suites). The `task_memory` monitor tests are timing-based kernel OOM monitor tests that do not run correctly on macOS (one hangs); this change does not touch them, and CI runs them on Linux. - Red then green, `native-tool-receipt-limit.integration.test.ts` (real Postgres): a run stopped at the receipt limit gets one `scheduled_retry` successor with `forceFreshSession` and the hint. The release does not block the task and creates no recovery action. The task stays `in_progress`. The presentation shows `retry_scheduled` with no Retry, then `working` after promotion. With the master arbiter, no successor is created. A negative case (another diagnostic code) keeps `cancellation_run_only`. - Red then green: ACPX `receiver_rejects_only_the_tool_call_that_overflows_the_result_reserve` (11-call burst through the fake sidecar). - Red then green, server: an earlier turn's diagnostic gives no continuation; a Stop saved before or right after the finalizer's first read gives no continuation and settles the cancellation with no recovery action; the retry helper throws `NativeStatusRaceError` for a stopped run; the loop continuation is not queued, and a queued one is cancelled, for a stopped run. - `status-arbiter.test.ts`: the new branch, the 2-continuation bound, and the `blocked` exclusion. - Focused server tests pass: the new test, `native-provider-overload.integration.test.ts`, `status-arbiter.test.ts`, `native-status-arbiter-corpus.test.ts`, `heartbeat-run-dispatch-work.test.ts`, `native-run-finalizer-telemetry.test.ts`, `native-workspace-finalizer.test.ts` (306 tests). `tsc --noEmit` passes for `server`. - `pnpm verify` exits 2 (a runner-core change needs broad coverage), so required CI supplies it. ## Risks - Dot/Muse agents still lose the turn on this overflow until the follow-up lands (no change from master). - An agent that keeps more than about ten large calls in flight now gets rejections for the extra calls instead of a stopped turn. It can send them again after results arrive. Real held bytes still stop the turn. - The receipt-limit continuation starts a fresh session. The in-turn conversation is lost; the task, comments, documents and saved workspace stay. It runs at most 2 times per chain, then the current path applies. - The retry lane shares the failure-retry count with the capacity lane. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used through Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Refs #21734 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../runner-core/src/acpx_provider_session.rs | 33 ++- .../runner-core/src/bin/fake-acpx-sidecar.rs | 25 ++- .../runner-core/src/provider_backend.rs | 2 +- .../crates/runner-core/src/provider_bridge.rs | 120 ++++++++++- .../tests/acpx_provider_session.rs | 62 ++++++ .../native-provider-capacity-retry.ts | 70 +++++-- .../native-runtime/native-run-finalizer.ts | 12 +- ...ive-tool-receipt-limit.integration.test.ts | 196 ++++++++++++++++++ .../native-tool-receipt-limit.ts | 60 ++++++ .../paperclip-runner-tool-authority.test.ts | 48 +++++ .../paperclip-runner-tool-authority.ts | 14 +- .../native-runtime/status-arbiter.test.ts | 14 ++ .../services/native-runtime/status-arbiter.ts | 16 ++ .../status-decision-committer.ts | 26 ++- 14 files changed, 668 insertions(+), 30 deletions(-) create mode 100644 server/src/services/native-runtime/native-tool-receipt-limit.integration.test.ts create mode 100644 server/src/services/native-runtime/native-tool-receipt-limit.ts diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_session.rs b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_session.rs index 6da5c8d45f3..e9242bee000 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_session.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_session.rs @@ -963,6 +963,7 @@ impl AcpxProviderSession { let mut next_bridge = self.tool_bridge.clone(); let mut next_reserved_bridge = self.reserved_tool_bridge.clone(); let mut reconciled_events = Vec::with_capacity(events.len()); + let mut retryable_rejections = Vec::new(); for event in events { let mut expose_event = true; match &event { @@ -998,9 +999,19 @@ impl AcpxProviderSession { if let Err(error) = bridge.begin_call(call_id.clone(), operation_id.clone(), input.clone()) { - return Err(self.fail_closed(LocalRunnerError::invalid(format!( - "ACPX provider tool authorization failed: {error}" - )))); + if !error.is_retryable() { + return Err(self.fail_closed(LocalRunnerError::invalid(format!( + "ACPX provider tool authorization failed: {error}" + )))); + } + if let Err(error) = next_state.complete_tool(call_id, operation_id) { + return Err(self.fail_closed(error)); + } + retryable_rejections.push(( + call_id.clone(), + error.safe_provider_message().unwrap_or_default().to_owned(), + )); + expose_event = false; } } AcpxProviderStateEvent::SemanticResult(result) => { @@ -1125,6 +1136,22 @@ impl AcpxProviderSession { self.state = next_state; self.tool_bridge = next_bridge; self.reserved_tool_bridge = next_reserved_bridge; + if let Some(turn_id) = (!retryable_rejections.is_empty()) + .then(|| self.state.active_turn_id().map(str::to_owned)) + .flatten() + { + for (call_id, message) in retryable_rejections { + let response = self + .transport + .request_tool_resolve(json!({ + "callId": call_id, + "turnId": turn_id, + "error": {"message": message}, + })) + .map_err(|(error, _)| self.fail_closed(error))?; + self.verify_resolution(&response, "tool")?; + } + } if let Some(turn_id) = terminal_turn { self.offer_provider_turn(&turn_id, terminal_completed, terminal_live); } diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs b/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs index 8bd51438e54..370a840ec86 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs @@ -104,7 +104,10 @@ fn run() -> Result<(), Box> { .try_into() .map_err(|_| "lifetime fence requires three ports")?; // Only the receiver-admission fixture writes this task-owned command journal. - let mut admission_journal = if matches!(mode, "admission-tool" | "admission-tool-oversized") { + let mut admission_journal = if matches!( + mode, + "admission-tool" | "admission-tool-oversized" | "admission-tool-burst" + ) { let path = args .windows(2) .find(|pair| pair[0] == "--journal") @@ -641,7 +644,10 @@ fn run() -> Result<(), Box> { } if let Some(journal) = admission_journal.as_mut() { write_json(journal, &json!({"request":request}))?; - let response = if command == "tool.resolve" { + let response = if command == "tool.resolve" && mode == "admission-tool-burst" { + json!({"protocolVersion":GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION, + "id":id,"ok":true,"result":{"resolved":true}}) + } else if command == "tool.resolve" { json!({"protocolVersion":GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION, "id":id,"ok":true,"result":{"resolved": request["params"]["callId"] == "call-admission" @@ -660,7 +666,20 @@ fn run() -> Result<(), Box> { ) }; write_json(&mut stdout, &response)?; - if command == "turn.start" { + if command == "turn.start" && mode == "admission-tool-burst" { + for index in 0..11 { + let frame = json!({ + "protocolVersion":GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION, + "sequence":next_sequence,"eventType":"runtime.tool_called", + "runId":"run-1","turnId":request["params"]["turnId"], + "payload":{"callId":format!("call-burst-{index}"),"operationId":"issues.read", + "input":{"id":format!("issue-{index}")}}, + }); + write_json(journal, &json!({"emitted":frame}))?; + write_json(&mut stdout, &frame)?; + next_sequence += 1; + } + } else if command == "turn.start" { let frame = json!({ "protocolVersion":GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION, "sequence":next_sequence,"eventType":"runtime.tool_called", diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/provider_backend.rs b/packages/paperclip-runner/runner/crates/runner-core/src/provider_backend.rs index 7e811ce6c7d..02907217626 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/provider_backend.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/provider_backend.rs @@ -72,7 +72,7 @@ fn invalid_tool_call_result( "message": error .safe_provider_message() .unwrap_or(GENERIC_INVALID_TOOL_CALL_MESSAGE), - "retryable": false, + "retryable": error.is_retryable(), }, }), is_error: true, diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/provider_bridge.rs b/packages/paperclip-runner/runner/crates/runner-core/src/provider_bridge.rs index b1ab2939aad..bf9d33ebd24 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/provider_bridge.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/provider_bridge.rs @@ -39,6 +39,9 @@ const MAX_SETTLED_CALL_IDS: usize = 65_536; const REPLAY_FILTER_WORDS: usize = 32_768; const ACTIVE_TURN_RECEIPT_LIMIT_MESSAGE: &str = "durable provider tool receipt limit reached for the active turn"; +const TOOL_CALLS_IN_FLIGHT_MESSAGE: &str = + "too many provider tool calls are in flight for the retained result reserve"; +const TOOL_CALLS_IN_FLIGHT_HINT: &str = "Too many tool calls are in flight. This call was not executed. Wait for the pending tool results, then retry it."; const COMPLETION_INPUT_SCHEMA_HINT: &str = "Invalid paperclip_finish arguments. Required fields: reportedWorkDisposition, summary, completionClaim, evidence, and verification. When reportedWorkDisposition is yielded, continuation must include kind=response_wake or monitor, summary, and idempotencyKey."; const HUMAN_INPUT_SCHEMA_HINT: &str = "Invalid request_human_input arguments. Put version and supersedeOnUserComment at payload.version and payload.supersedeOnUserComment, never at the root. For questions, use payload.version=1 and a complete payload.questionSet. Preserve question and option IDs. Correct the arguments and retry."; const APPROVAL_INPUT_SCHEMA_HINT: &str = "Invalid request_human_input arguments. Put version and supersedeOnUserComment at payload.version and payload.supersedeOnUserComment, never at the root. Keep approval requests in their confirmation or checkbox interactionKind; do not replace them with questions. Correct the arguments and retry."; @@ -310,6 +313,17 @@ impl ProviderBridgeError { self.message == ACTIVE_TURN_RECEIPT_LIMIT_MESSAGE } + fn tool_calls_in_flight() -> Self { + Self { + message: TOOL_CALLS_IN_FLIGHT_MESSAGE.to_owned(), + safe_provider_message: Some(TOOL_CALLS_IN_FLIGHT_HINT.to_owned()), + } + } + + pub fn is_retryable(&self) -> bool { + self.message == TOOL_CALLS_IN_FLIGHT_MESSAGE + } + pub fn safe_provider_message(&self) -> Option<&str> { self.safe_provider_message.as_deref() } @@ -779,7 +793,7 @@ impl ProviderToolBridge { .and_then(|total| total.checked_add(result_reserve)) .is_none_or(|total| total > MAX_RETAINED_TOOL_VALUE_BYTES) { - return Err(ProviderBridgeError::active_turn_receipt_limit()); + return Err(ProviderBridgeError::tool_calls_in_flight()); } // Reserve the complete encoded receipt, including this exact input and // a maximum-sized result, before accepting work. An admitted call can @@ -791,7 +805,7 @@ impl ProviderToolBridge { return Err(ProviderBridgeError::active_turn_receipt_limit()); } if self.ensure_settled_result_capacity(Some(&call)).is_err() { - return Err(ProviderBridgeError::active_turn_receipt_limit()); + return Err(ProviderBridgeError::tool_calls_in_flight()); } self.pending.insert(call_id, call.clone()); Ok(call) @@ -1656,6 +1670,108 @@ mod tests { bridge } + fn get_task_bridge() -> ProviderToolBridge { + let operation = AuthorizedTool { + operation_id: "get_task".to_owned(), + version: 1, + description: "Read a task.".to_owned(), + input_schema: json!({"type": "object"}), + response_schema: json!({"type": "object"}), + }; + let mut bridge = ProviderToolBridge::default(); + bridge + .prepare(AuthorizedToolSet { + schema: TOOL_SET_SCHEMA.to_owned(), + schema_version: 1, + catalog_digest: authorized_tool_catalog_digest(std::slice::from_ref(&operation)) + .unwrap(), + operations: vec![operation], + }) + .unwrap(); + bridge + } + + fn settle_get_task(bridge: &mut ProviderToolBridge, call_id: &str, result_bytes: usize) { + bridge + .begin_call(call_id.to_owned(), "get_task".to_owned(), json!({})) + .unwrap(); + bridge + .apply_result(ToolResult { + call_id: call_id.to_owned(), + operation_id: "get_task".to_owned(), + result: json!({"body": "x".repeat(result_bytes)}), + is_error: false, + }) + .unwrap(); + } + + #[test] + fn parallel_calls_over_the_result_reserve_reject_only_the_overflow_call() { + let mut bridge = get_task_bridge(); + settle_get_task(&mut bridge, "settled", 600 * 1024); + for index in 0..9 { + bridge + .begin_call( + format!("parallel-{index}"), + "get_task".to_owned(), + json!({}), + ) + .expect("calls within the result reserve are admitted"); + } + let error = bridge + .begin_call("parallel-9".to_owned(), "get_task".to_owned(), json!({})) + .expect_err("the call that overflows the reserve is rejected"); + assert!(!error.is_active_turn_receipt_limit()); + assert!(error.is_retryable()); + assert_eq!( + error.safe_provider_message(), + Some(TOOL_CALLS_IN_FLIGHT_HINT) + ); + assert!(!bridge.durable_run_receipt_limit_reached()); + assert!(!bridge.has_call_receipt("parallel-9")); + assert_eq!(bridge.pending_calls().count(), 9); + + bridge + .apply_result(ToolResult { + call_id: "parallel-0".to_owned(), + operation_id: "get_task".to_owned(), + result: json!({"ok": true}), + is_error: false, + }) + .unwrap(); + bridge + .begin_call("parallel-9".to_owned(), "get_task".to_owned(), json!({})) + .expect("the rejected call is admitted once a pending result settles"); + assert!(!bridge.durable_run_receipt_limit_reached()); + } + + #[test] + fn held_result_bytes_over_the_limit_still_stop_the_turn() { + let mut bridge = get_task_bridge(); + let mut settled = 0; + let error = loop { + match bridge.begin_call(format!("held-{settled}"), "get_task".to_owned(), json!({})) { + Ok(_) => { + bridge + .apply_result(ToolResult { + call_id: format!("held-{settled}"), + operation_id: "get_task".to_owned(), + result: json!({"body": "x".repeat(760 * 1024)}), + is_error: false, + }) + .unwrap(); + settled += 1; + } + Err(error) => break error, + } + }; + assert!(settled >= 9); + assert_eq!(bridge.pending_calls().count(), 0); + assert!(error.is_active_turn_receipt_limit()); + assert!(!error.is_retryable()); + assert!(bridge.durable_run_receipt_limit_reached()); + } + #[test] fn completion_summary_enforces_the_canonical_unicode_character_limit() { let mut within_limit = completion_bridge(); diff --git a/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_provider_session.rs b/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_provider_session.rs index 9478a755975..3d383bc310d 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_provider_session.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_provider_session.rs @@ -385,6 +385,68 @@ fn receiver_admits_normal_tool_event_and_resolves_only_correlated_call_once() { check_tool_receiver_admission(false); } +#[test] +fn receiver_rejects_only_the_tool_call_that_overflows_the_result_reserve() { + let root = std::env::temp_dir().join(format!("acpx-burst-{}", uuid::Uuid::new_v4())); + std::fs::create_dir(&root).unwrap(); + let journal = root.join("commands.jsonl"); + let mut fixture = config("admission-tool-burst"); + fixture + .transport + .args + .extend(["--journal".to_owned(), journal.to_str().unwrap().to_owned()]); + let mut session = AcpxProviderSession::start(&fixture).unwrap(); + session + .start_turn("turn-admission", "Read the issues", &std::env::temp_dir()) + .unwrap(); + let mut exposed = 0; + while (0..10).any(|index| { + session + .state() + .pending_tool(&format!("call-burst-{index}")) + .is_none() + }) || exposed < 10 + { + exposed += session + .poll_event(Duration::from_secs(1)) + .unwrap() + .map_or(0, |events| events.len()); + } + for _ in 0..3 { + let _ = session.poll_event(Duration::from_millis(100)).unwrap(); + } + assert_eq!(exposed, 10); + assert!(session.state().pending_tool("call-burst-10").is_none()); + session + .deliver_tool_result(&paperclip_runner_core::provider_bridge::ToolResult { + call_id: "call-burst-0".to_owned(), + operation_id: "issues.read".to_owned(), + result: json!({"id":"issue-0"}), + is_error: false, + }) + .unwrap(); + session.shutdown("burst test complete").unwrap(); + let rows: Vec = std::fs::read_to_string(&journal) + .unwrap() + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect(); + let resolutions: Vec<_> = rows + .iter() + .filter_map(|row| row.get("request")) + .filter(|request| request["command"] == "tool.resolve") + .map(|request| request["params"].clone()) + .collect(); + assert_eq!(resolutions.len(), 2); + assert_eq!(resolutions[0]["callId"], "call-burst-10"); + assert!(resolutions[0]["error"]["message"] + .as_str() + .unwrap() + .contains("Too many tool calls are in flight")); + assert_eq!(resolutions[1]["callId"], "call-burst-0"); + std::fs::remove_dir_all(root).unwrap(); +} + #[test] fn pi_thinking_effective_identity_is_admitted_before_any_turn() { use paperclip_runner_core::acpx_provider_session::{ diff --git a/server/src/services/native-runtime/native-provider-capacity-retry.ts b/server/src/services/native-runtime/native-provider-capacity-retry.ts index a472054ee17..79952d5869b 100644 --- a/server/src/services/native-runtime/native-provider-capacity-retry.ts +++ b/server/src/services/native-runtime/native-provider-capacity-retry.ts @@ -5,29 +5,74 @@ import { and, eq } from "drizzle-orm"; import { agentWakeupRequests, heartbeatRuns, type Db } from "@paperclipai/db"; import { accountingForScheduledRetry, executionFailureRetryCount } from "../execution-recovery-attempt.js"; import { NATIVE_PROVIDER_CAPACITY_MAX_RETRIES, NATIVE_PROVIDER_OVERLOADED_CODE, NATIVE_PROVIDER_OVERLOADED_MESSAGE } from "./native-provider-failure.js"; +import { NATIVE_TOOL_RECEIPT_LIMIT_CODE, NATIVE_TOOL_RECEIPT_LIMIT_CONTINUATION_DELAY_MS, NATIVE_TOOL_RECEIPT_LIMIT_HINT, + NATIVE_TOOL_RECEIPT_LIMIT_MAX_CONTINUATIONS, NATIVE_TOOL_RECEIPT_LIMIT_MESSAGE, nativeRunHasStopRequest } from "./native-tool-receipt-limit.js"; +import { NativeStatusRaceError } from "./status-decision-committer.js"; -/** Called under the finalizer's issue/coordinator locks, in the status-effect transaction. */ -export async function materializeNativeProviderCapacityRetry(input: { +type NativeRetryTarget = { tx: Db; companyId: string; issueId: string; runId: string; agentId: string; -}) { +}; + +type NativeRetryLane = { + reason: string; + maxRetries: number; + delayMs: (attempt: number) => number; + message: string; + idempotencyPrefix: string; + exhaustedError: string; + context?: (run: typeof heartbeatRuns.$inferSelect) => Record; + refuseStopped?: boolean; +}; + +/** Called under the finalizer's issue/coordinator locks, in the status-effect transaction. */ +export async function materializeNativeProviderCapacityRetry(input: NativeRetryTarget) { + return materializeNativeFreshSessionRetry(input, { + reason: NATIVE_PROVIDER_OVERLOADED_CODE, + maxRetries: NATIVE_PROVIDER_CAPACITY_MAX_RETRIES, + delayMs: attempt => 60_000 * 2 ** (attempt - 1), + message: NATIVE_PROVIDER_OVERLOADED_MESSAGE, + idempotencyPrefix: "native-capacity", + exhaustedError: "native_capacity_retry_exhausted", + }); +} + +export async function materializeNativeToolReceiptLimitContinuation(input: NativeRetryTarget) { + return materializeNativeFreshSessionRetry(input, { + reason: NATIVE_TOOL_RECEIPT_LIMIT_CODE, + maxRetries: NATIVE_TOOL_RECEIPT_LIMIT_MAX_CONTINUATIONS, + delayMs: () => NATIVE_TOOL_RECEIPT_LIMIT_CONTINUATION_DELAY_MS, + message: NATIVE_TOOL_RECEIPT_LIMIT_MESSAGE, + idempotencyPrefix: "native-tool-receipt-limit", + exhaustedError: "native_tool_receipt_limit_continuation_exhausted", + refuseStopped: true, + context: run => ({ + livenessContinuationSourceRunId: run.id, + livenessContinuationReason: NATIVE_TOOL_RECEIPT_LIMIT_CODE, + livenessContinuationInstruction: NATIVE_TOOL_RECEIPT_LIMIT_HINT, + }), + }); +} + +async function materializeNativeFreshSessionRetry(input: NativeRetryTarget, lane: NativeRetryLane) { const [run] = await input.tx.select().from(heartbeatRuns).where(and( eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.id, input.runId), eq(heartbeatRuns.agentId, input.agentId), eq(heartbeatRuns.nativeIssueId, input.issueId), )).for("update"); if (!run || run.runtimeMode !== "native") throw new Error("native_capacity_retry_run_binding_mismatch"); + if (lane.refuseStopped && nativeRunHasStopRequest(run.resultJson)) throw new NativeStatusRaceError(); // Share the predecessor claim with every other failure-retry lane. const [existing] = await input.tx.select().from(heartbeatRuns).where(and( eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.retryOfRunId, run.id), )).limit(1); if (existing) return existing.id; const attempt = executionFailureRetryCount(run) + 1; - if (attempt > NATIVE_PROVIDER_CAPACITY_MAX_RETRIES) throw new Error("native_capacity_retry_exhausted"); + if (attempt > lane.maxRetries) throw new Error(lane.exhaustedError); const now = new Date(); - const dueAt = new Date(now.getTime() + 60_000 * 2 ** (attempt - 1)); + const dueAt = new Date(now.getTime() + lane.delayMs(attempt)); const retryId = randomUUID(); const predecessorContext = { ...run.contextSnapshot }; // Resume receipts and delivered wake input belong to the failed run. The @@ -45,18 +90,19 @@ export async function materializeNativeProviderCapacityRetry(input: { taskId: input.issueId, forceFreshSession: true, retryOfRunId: run.id, - retryReason: NATIVE_PROVIDER_OVERLOADED_CODE, - wakeReason: NATIVE_PROVIDER_OVERLOADED_CODE, + retryReason: lane.reason, + wakeReason: lane.reason, scheduledRetryAttempt: attempt, scheduledRetryAt: dueAt.toISOString(), - executionRetryAccounting: accountingForScheduledRetry(run, NATIVE_PROVIDER_OVERLOADED_CODE, attempt), + executionRetryAccounting: accountingForScheduledRetry(run, lane.reason, attempt), + ...lane.context?.(run), }; await notifyIssueAttentionRetentionWork(input.tx, { companyId: input.companyId, issueId: input.issueId, runId: run.id }); await notifyScheduledRetryDispatch(input.tx, { companyId: run.companyId, runId: run.id }); const [wake] = await input.tx.insert(agentWakeupRequests).values({ companyId: run.companyId, agentId: run.agentId, source: "automation", triggerDetail: "system", - reason: NATIVE_PROVIDER_OVERLOADED_CODE, status: "queued", runId: retryId, - idempotencyKey: `native-capacity:${run.companyId}:${run.id}`, + reason: lane.reason, status: "queued", runId: retryId, + idempotencyKey: `${lane.idempotencyPrefix}:${run.companyId}:${run.id}`, requestedByActorType: "system", requestedByActorId: "native_finalizer", payload: contextSnapshot, }).returning({ id: agentWakeupRequests.id }); @@ -64,9 +110,9 @@ export async function materializeNativeProviderCapacityRetry(input: { id: retryId, companyId: run.companyId, agentId: run.agentId, invocationSource: "automation", triggerDetail: "system", status: "scheduled_retry", responsibleUserId: run.responsibleUserId, wakeupRequestId: wake.id, - retryOfRunId: run.id, scheduledRetryReason: NATIVE_PROVIDER_OVERLOADED_CODE, + retryOfRunId: run.id, scheduledRetryReason: lane.reason, scheduledRetryAttempt: attempt, scheduledRetryAt: dueAt, - error: NATIVE_PROVIDER_OVERLOADED_MESSAGE, errorCode: NATIVE_PROVIDER_OVERLOADED_CODE, + error: lane.message, errorCode: lane.reason, contextSnapshot, }); return retryId; diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts index df6232eb978..eb5dd3977eb 100644 --- a/server/src/services/native-runtime/native-run-finalizer.ts +++ b/server/src/services/native-runtime/native-run-finalizer.ts @@ -32,6 +32,7 @@ import { settleExternalConversation } from "../slack-conversation-lifecycle.js"; import { executionFailureRetryCount } from "../execution-recovery-attempt.js"; import { isFailedTurnContinuationRun } from "./native-failed-turn-continuation.js"; import { readPersistedNativeFailureEvidence } from "./native-provider-failure-evidence.js"; +import { NATIVE_TOOL_RECEIPT_LIMIT_CODE, cancelStoppedRunContinuation, nativeRunHasStopRequest, readPersistedNativeToolReceiptLimitStop } from "./native-tool-receipt-limit.js"; import { explainFailedRun, explainNativeTurnFailure, NATIVE_RUN_FAILED_UNEXPLAINED } from "./native-run-failure-explanation.js"; import { dismissAutomaticCompletionReviews } from "./automatic-completion-reviews.js"; import { findSupersededExternalReviewRequests } from "./superseded-external-review-requests.js"; @@ -1607,6 +1608,10 @@ export async function finalizeNativeRun(input: { const allowIncompleteContinuation = record(sourceWake?.payload).continuationIdempotencyKey !== "native-completion-incomplete"; let supersedesAssessmentId: string | null = coordinator.assessmentId; for (let attempt = 0; attempt < 3; attempt += 1) { + const savedStop = attempt === 0 ? run.resultJson : await input.db.select({ resultJson: heartbeatRuns.resultJson }) + .from(heartbeatRuns).where(and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, run.companyId))) + .then(rows => rows[0]?.resultJson ?? run.resultJson); + const stopRequested = nativeRunHasStopRequest(savedStop); const authoritativeIssue = await input.db .select() .from(issues) @@ -1747,6 +1752,7 @@ export async function finalizeNativeRun(input: { // issue route decides `status: "done"`. Review runs keep their own path. const reviewStage = isConversation(authoritativeIssue) || reviewContext ? { kind: "none" as const } : completionReviewStageEntry(authoritativeIssue, run.agentId); + await cancelStoppedRunContinuation(input.db, { companyId: run.companyId, resultJson: savedStop }, toolCallLoopContinuationKey(run.id)); const statusInput: Parameters[0] = { requiredQualityReviewSatisfied: qualityReview.satisfied, executionStageApprovedByRun: await executionStageApprovedByRun(input.db, run, authoritativeIssue), @@ -1761,13 +1767,16 @@ export async function finalizeNativeRun(input: { providerModelRejected: providerFailure?.errorCode === "native_provider_model_rejected" && ownsProviderFailureDecision, providerOverloaded: providerFailure?.errorCode === "native_provider_overloaded" && ownsProviderFailureDecision, providerFailureSuperseded: providerFailure?.errorCode === "native_provider_overloaded" && !ownsProviderFailureDecision, + toolReceiptLimitStopped: terminalState !== "succeeded" && ownsProviderFailureDecision && !reviewContext + && !stopRequested && await readPersistedNativeToolReceiptLimitStop(input.db, run, resultRow.turnId), failureRetryCount: executionFailureRetryCount(run), // Only the task's current owner may turn its own failed continuation // into a blocker; the committer rechecks that under the issue lock. failedTurnContinuationUsed: terminalState === "failed" && ownsProviderFailureDecision && !reviewContext && await isFailedTurnContinuationRun(input.db, run, authoritativeIssue.id), toolCallLoopContinuation: assessment.reportedDisposition === "yielded" - && assessment.continuation?.idempotencyKey === toolCallLoopContinuationKey(run.id), + && assessment.continuation?.idempotencyKey === toolCallLoopContinuationKey(run.id) + && !stopRequested, ...(reviewContext ? { nativeReviewOutcome: nativeReview ? nativeReview.interaction.status === "pending" ? "pending" as const : "resolved" as const : "stale" as const } : {}), @@ -1922,6 +1931,7 @@ export async function finalizeNativeRun(input: { : undefined, requireProviderFailureOwner: decision.reasonCode?.startsWith("native_provider_overloaded") || decision.reasonCode === "native_run_failed_continuation_exhausted" + || decision.reasonCode === NATIVE_TOOL_RECEIPT_LIMIT_CODE ? { agentId: run.agentId, reviewContext } : undefined, requireBoardResponseWaitSource: decision.reasonCode === "board_response_waiting" || repairBoardResponseWait diff --git a/server/src/services/native-runtime/native-tool-receipt-limit.integration.test.ts b/server/src/services/native-runtime/native-tool-receipt-limit.integration.test.ts new file mode 100644 index 00000000000..594a1ee0262 --- /dev/null +++ b/server/src/services/native-runtime/native-tool-receipt-limit.integration.test.ts @@ -0,0 +1,196 @@ +import { randomUUID } from "node:crypto"; +import { and, eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { agents, agentWakeupRequests, companies, completionContracts, createDb, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, statusDecisionEffects, statusDecisions } from "@paperclipai/db"; +import type { ControlPlanePort, NativeExecutionInputV1, PrpEvent, PrpTerminalState } from "@paperclipai/paperclip-runner"; +import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; +import { CONTROL_PLANE_CONFORMANCE_RESULT } from "../../vendor/paperclip-runner/testing.js"; + +const provider = vi.hoisted(() => ({ execute: vi.fn() })); +const receiptLimitRead = vi.hoisted(() => ({ after: null as null | (() => Promise) })); +vi.mock("./native-tool-receipt-limit.js", async (importOriginal) => { + const original = await importOriginal(); + return { ...original, readPersistedNativeToolReceiptLimitStop: async (...args: Parameters) => { + const stopped = await original.readPersistedNativeToolReceiptLimitStop(...args); + const after = receiptLimitRead.after; + receiptLimitRead.after = null; + await after?.(); + return stopped; + } }; +}); +vi.mock("../../vendor/paperclip-runner/index.js", async (importOriginal) => ({ + ...(await importOriginal()), executeNativeSession: provider.execute, +})); +import { executePaperclipNativeSession } from "./native-session-executor.js"; +import { buildNativeCompletionContract } from "./completion-contracts.js"; +import { prepareNativeHeartbeatRun } from "./prepare-native-run.js"; +import { finalizeNativeRun } from "./native-run-finalizer.js"; +import { NATIVE_TOOL_RECEIPT_LIMIT_CODE, NATIVE_TOOL_RECEIPT_LIMIT_CONTINUATION_DELAY_MS, NATIVE_TOOL_RECEIPT_LIMIT_HINT, + readPersistedNativeToolReceiptLimitStop } from "./native-tool-receipt-limit.js"; +import { heartbeatService } from "../heartbeat.js"; +import { createPostgresWakeQueueAdapter } from "../../modules/wake-queue/adapters/postgres.js"; +import { createReleaseIssueExecution } from "../../modules/wake-queue/application/use-cases.js"; +import { taskInterruptionPresentation } from "../task-interruption-presentation.js"; +import { materializeNativeToolReceiptLimitContinuation } from "./native-provider-capacity-retry.js"; +import { NativeStatusRaceError } from "./status-decision-committer.js"; + +describe("native turn stopped at its tool receipt limit", () => { + let temporary: Awaited>; + let db: ReturnType; + const companyId = randomUUID(), agentId = randomUUID(); + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("native-tool-receipt-limit-"); + db = createDb(temporary.connectionString); + await db.insert(companies).values({ id: companyId, name: "Receipt limit regression", issuePrefix: "RCL" }); + await db.insert(agents).values({ id: agentId, companyId, name: "Receipt worker", status: "active", adapterType: "paperclip_runner", adapterConfig: { provider: "opencode", model: "test-model" } }); + }); + afterAll(async () => { await temporary?.cleanup(); }); + + let finalTurnId: string | null = null; + async function stopAtReceiptLimit(runId: string, issueId: string, diagnosticCode: string, beforeFinalize?: () => Promise, + diagnosticTurnId?: string) { + const [issue] = await db.select().from(issues).where(eq(issues.id, issueId)); + const [run] = await db.update(heartbeatRuns).set({ status: "running", runtimeMode: "native", nativeIssueId: issueId, error: null, errorCode: null }).where(eq(heartbeatRuns.id, runId)).returning(); + await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId)); + const native = await prepareNativeHeartbeatRun({ db, run, issue, environmentLeaseId: randomUUID() }); + const [contract] = await db.select().from(completionContracts).where(eq(completionContracts.issueId, issueId)); + const contractInput = buildNativeCompletionContract(issue, { revision: contract.revision }); + await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "observed" }); + const execution: NativeExecutionInputV1 = { + schema: "paperclip.native-execution-input.v1", binding: { companyId, runId, issueId, agentId, executionWorkspaceId: runId }, + provider: { kind: "codex", model: "test-model" }, + task: { identifier: issueId, title: issue.title, description: null, prompt: "Continue the task using its history.", workMode: "standard" }, + workspace: { cwd: "/tmp", repoUrl: null, repoRef: null, branchName: null }, + session: { normalizedSessionId: native.normalizedSessionId, driverKind: "codex_app_server", protocolVersion: 1, lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } }, + completionContract: { id: contract.id, sha256: contract.canonicalSha256, schemaVersion: "paperclip.completion-contract.v1", contract: contractInput }, + interactionResponses: [], credentialBindings: [], + }; + await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeExecutionInput: execution } }).where(eq(heartbeatRuns.id, runId)); + const event: PrpEvent = { + schema: "paperclip.prp.event.v1", runId, normalizedSessionId: native.normalizedSessionId, turnId: diagnosticTurnId ?? native.turnId, + sourceInstanceId: native.runnerInstanceId, sourceEventId: "receipt-limit", sourceSeq: 1, sourceKind: "runner", eventType: "harness.diagnostic", schemaVersion: 1, priority: 0, emittedAt: new Date().toISOString(), + payload: { provider: "opencode", code: diagnosticCode, operationId: "get_task", callId: "call-80", + message: "The active provider turn reached its durable semantic-tool receipt limit and was interrupted", paperclipExecuted: false }, + }; + const terminal: PrpTerminalState = { schema: "paperclip.prp.terminal.v1", turnTerminalState: "interrupted", runTerminalState: "cancelled", reportedWorkDisposition: "needs_review" }; + const result = { ...CONTROL_PLANE_CONFORMANCE_RESULT, reportedWorkDisposition: "needs_review" as const, + summary: "The OpenCode run stopped before it completed.", + completionClaim: { ...CONTROL_PLANE_CONFORMANCE_RESULT.completionClaim, contractRevision: contractInput.revision }, + attentionRequests: [{ kind: "review" as const, summary: "Review the stopped OpenCode run before continuing.", ownerClass: "human" as const }] }; + provider.execute.mockReset().mockImplementation(async (options: { controlPlane: ControlPlanePort }) => { + await options.controlPlane.openRun({ identity: { companyId, issueId, runId, agentId, sessionId: native.normalizedSessionId }, backendKind: "mock", sourceInstanceId: native.runnerInstanceId }); + await options.controlPlane.appendEvent(event); + await options.controlPlane.completeRun({ result, terminal, turnId: native.turnId }); + return { result, terminal, turnId: native.turnId, normalizedSessionId: native.normalizedSessionId, providerSessionId: "fixture-session", driverKind: "codex_app_server", driverVersion: "fixture", nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null }; + }); + const unexpected = async () => { throw new Error("Unexpected provider call"); }; + await executePaperclipNativeSession({ db, execution, runnerInstanceId: native.runnerInstanceId, backend: { descriptor: unexpected, openSession: unexpected } }); + await beforeFinalize?.(); + for (let replay = 0; replay < 2; replay++) await finalizeNativeRun({ db, runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true }); + expect(provider.execute).toHaveBeenCalledTimes(1); + finalTurnId = native.turnId; + return (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]!; + } + + function release() { + const unexpected = vi.fn(async () => { throw new Error("Unexpected recovery"); }); + return createReleaseIssueExecution({ + issueLock: createPostgresWakeQueueAdapter(db, { resolveResponsibleUserId: unexpected, getRoutineEnv: unexpected, resolveSessionBeforeForWakeup: unexpected }), + recovery: { escalateStrandedAssignedIssue: unexpected, escalateStrandedRecoveryIssueInPlace: unexpected }, + }); + } + + it("continues the task at once in a fresh session and shows no Retry", async () => { + const issueId = randomUUID(), runId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Parallel reads task", status: "in_progress", assigneeAgentId: agentId, responsibleUserId: "receipt-owner" }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, responsibleUserId: "receipt-owner", contextSnapshot: { issueId, wakeCommentId: "original-message" } }); + const stopped = await stopAtReceiptLimit(runId, issueId, NATIVE_TOOL_RECEIPT_LIMIT_CODE); + expect(stopped.status).toBe("cancelled"); + expect(await readPersistedNativeToolReceiptLimitStop(db, stopped, finalTurnId)).toBe(true); + expect(await readPersistedNativeToolReceiptLimitStop(db, stopped, "another-turn")).toBe(false); + + const [retry, ...others] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.retryOfRunId, runId))); + expect(others).toHaveLength(0); + expect(retry).toMatchObject({ status: "scheduled_retry", scheduledRetryReason: NATIVE_TOOL_RECEIPT_LIMIT_CODE, scheduledRetryAttempt: 1, + contextSnapshot: { issueId, forceFreshSession: true, livenessContinuationSourceRunId: runId, + livenessContinuationReason: NATIVE_TOOL_RECEIPT_LIMIT_CODE, livenessContinuationInstruction: NATIVE_TOOL_RECEIPT_LIMIT_HINT } }); + expect(retry!.contextSnapshot).not.toHaveProperty("wakeCommentId"); + expect(retry!.scheduledRetryAt!.getTime() - Date.now()).toBeLessThanOrEqual(NATIVE_TOOL_RECEIPT_LIMIT_CONTINUATION_DELAY_MS); + const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, runId)); + expect(decision).toMatchObject({ reasonCode: NATIVE_TOOL_RECEIPT_LIMIT_CODE }); + expect(await db.select().from(statusDecisionEffects).where(eq(statusDecisionEffects.decisionId, decision!.id))) + .toEqual(expect.arrayContaining([expect.objectContaining({ effectKind: "schedule_retry", targetType: "heartbeat_run", targetId: retry!.id })])); + + expect((await release()({ companyId, runId, now: new Date() })).outcome.kind).toBe("released"); + expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId))).toHaveLength(0); + const [issue] = await db.select().from(issues).where(eq(issues.id, issueId)); + expect(issue).toMatchObject({ status: "in_progress", assigneeAgentId: agentId }); + expect(await taskInterruptionPresentation(db, issue!)).toMatchObject({ state: "retry_scheduled", canRetry: false, userAction: null }); + const scheduler = heartbeatService(db, { runtimeEnv: {} }); + expect(await scheduler.promoteDueScheduledRetries(new Date())).toMatchObject({ promoted: 0 }); + expect(await scheduler.promoteDueScheduledRetries(retry!.scheduledRetryAt!)).toMatchObject({ promoted: 1, runIds: [retry!.id] }); + expect(await taskInterruptionPresentation(db, issue!)).toMatchObject({ state: "working", canRetry: false, userAction: null }); + expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.runId, retry!.id))).toHaveLength(1); + await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, retry!.id)); + }); + + it("does not continue a turn a person stopped while it settled", async () => { + const issueId = randomUUID(), runId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Stopped task", status: "in_progress", assigneeAgentId: agentId, responsibleUserId: "receipt-owner" }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, responsibleUserId: "receipt-owner", contextSnapshot: { issueId } }); + await stopAtReceiptLimit(runId, issueId, NATIVE_TOOL_RECEIPT_LIMIT_CODE, () => db.update(heartbeatRuns) + .set({ resultJson: { cancelledByActorType: "user", cancelledByUserId: "receipt-owner" } }).where(eq(heartbeatRuns.id, runId))); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))).toHaveLength(0); + const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, runId)); + expect(decision?.reasonCode).not.toBe(NATIVE_TOOL_RECEIPT_LIMIT_CODE); + }); + + it("settles the cancellation when a person stops the run after finalization first read it", async () => { + const issueId = randomUUID(), runId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Late stop task", status: "in_progress", assigneeAgentId: agentId, responsibleUserId: "receipt-owner" }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, responsibleUserId: "receipt-owner", contextSnapshot: { issueId } }); + await stopAtReceiptLimit(runId, issueId, NATIVE_TOOL_RECEIPT_LIMIT_CODE, async () => { + receiptLimitRead.after = () => db.update(heartbeatRuns) + .set({ resultJson: { cancelledByActorType: "user", cancelledByUserId: "receipt-owner" } }).where(eq(heartbeatRuns.id, runId)); + }); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))).toHaveLength(0); + const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId)); + expect(coordinator).toMatchObject({ phase: "committed", failureCode: null }); + const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, runId)); + expect(decision).toMatchObject({ reasonCode: "cancellation_run_only" }); + expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId))).toHaveLength(0); + }); + + it("does not continue when only an earlier turn hit the receipt limit", async () => { + const issueId = randomUUID(), runId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Earlier turn task", status: "in_progress", assigneeAgentId: agentId, responsibleUserId: "receipt-owner" }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, responsibleUserId: "receipt-owner", contextSnapshot: { issueId } }); + const stopped = await stopAtReceiptLimit(runId, issueId, NATIVE_TOOL_RECEIPT_LIMIT_CODE, undefined, "earlier-provider-turn"); + expect(await readPersistedNativeToolReceiptLimitStop(db, stopped, finalTurnId)).toBe(false); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))).toHaveLength(0); + const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, runId)); + expect(decision).toMatchObject({ reasonCode: "cancellation_run_only" }); + }); + + it("refuses to create the continuation under the run lock once a person's Stop is saved", async () => { + const issueId = randomUUID(), runId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Locked stop task", status: "in_progress", assigneeAgentId: agentId }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "cancelled", runtimeMode: "native", nativeIssueId: issueId, + contextSnapshot: { issueId }, resultJson: { cancelledByActorType: "user", cancelledByUserId: "receipt-owner" } }); + await expect(db.transaction(tx => materializeNativeToolReceiptLimitContinuation({ tx: tx as never, companyId, issueId, runId, agentId }))) + .rejects.toBeInstanceOf(NativeStatusRaceError); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))).toHaveLength(0); + expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey, `native-tool-receipt-limit:${companyId}:${runId}`))).toHaveLength(0); + }); + + it("leaves another cancelled turn to its existing recovery", async () => { + const issueId = randomUUID(), runId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Other diagnostic task", status: "in_progress", assigneeAgentId: agentId, responsibleUserId: "receipt-owner" }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, responsibleUserId: "receipt-owner", contextSnapshot: { issueId } }); + const stopped = await stopAtReceiptLimit(runId, issueId, "semantic_tool_denied"); + expect(await readPersistedNativeToolReceiptLimitStop(db, stopped, finalTurnId)).toBe(false); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))).toHaveLength(0); + const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, runId)); + expect(decision).toMatchObject({ reasonCode: "cancellation_run_only" }); + }); +}); diff --git a/server/src/services/native-runtime/native-tool-receipt-limit.ts b/server/src/services/native-runtime/native-tool-receipt-limit.ts new file mode 100644 index 00000000000..a4228c169c2 --- /dev/null +++ b/server/src/services/native-runtime/native-tool-receipt-limit.ts @@ -0,0 +1,60 @@ +import { and, eq, inArray, isNull, sql } from "drizzle-orm"; +import { agentWakeupRequests, heartbeatRunEvents, type heartbeatRuns, type Db } from "@paperclipai/db"; +import { validatePrpEvent } from "../../vendor/paperclip-runner/index.js"; +import { nativeSha256 } from "./canonical.js"; +import { readRunCancellation } from "../run-cancellation.js"; + +export const NATIVE_TOOL_RECEIPT_LIMIT_CODE = "semantic_tool_turn_receipt_limit"; +export const NATIVE_TOOL_RECEIPT_LIMIT_MAX_CONTINUATIONS = 2; +export const NATIVE_TOOL_RECEIPT_LIMIT_CONTINUATION_DELAY_MS = 5_000; +export const NATIVE_TOOL_RECEIPT_LIMIT_MESSAGE = "The agent's turn held too many tool results at once. Paperclip continues the task in a fresh session."; +export const NATIVE_TOOL_RECEIPT_LIMIT_HINT = "The previous turn stopped because it held too many tool results at once. " + + "Continue the task from its saved work. Make fewer tool calls in parallel, and do not re-read data you already have."; + +export function nativeRunHasStopRequest(resultJson: Record | null | undefined): boolean { + if (!resultJson) return false; + const cancellation = readRunCancellation(resultJson); + return Boolean(resultJson.nativeCancellation || resultJson.executionCancellation || resultJson.cancelledByActorType + || resultJson.cancelledByUserId || resultJson.interruptedByActorType || resultJson.queuedCommentInterruptQueueId + || resultJson.issueMutationStopId || resultJson.operatorInterrupted === true + || (cancellation && cancellation.initiator.type !== "system" && cancellation.initiator.type !== "provider")); +} + +export async function cancelStoppedRunContinuation( + db: Pick, + run: Pick, + idempotencyKey: string, +): Promise { + if (!nativeRunHasStopRequest(run.resultJson)) return 0; + const now = new Date(); + const cancelled = await db.update(agentWakeupRequests).set({ + status: "cancelled", finishedAt: now, updatedAt: now, error: "The run that asked for this continuation was stopped", + }).where(and( + eq(agentWakeupRequests.companyId, run.companyId), eq(agentWakeupRequests.idempotencyKey, idempotencyKey), + inArray(agentWakeupRequests.status, ["queued", "claimed", "deferred_issue_execution"]), isNull(agentWakeupRequests.runId), + )).returning({ id: agentWakeupRequests.id }); + return cancelled.length; +} + +export async function readPersistedNativeToolReceiptLimitStop( + db: Pick, + run: Pick, + turnId: string | null, +): Promise { + if (run.runtimeMode !== "native" || !run.runnerInstanceId || !run.nativeSessionId || !turnId) return false; + const rows = await db.select().from(heartbeatRunEvents).where(and( + eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id), + eq(heartbeatRunEvents.sourceInstanceId, run.runnerInstanceId), eq(heartbeatRunEvents.eventType, "harness.diagnostic"), + sql`${heartbeatRunEvents.payload}->'prpEvent'->'payload'->>'code' = ${NATIVE_TOOL_RECEIPT_LIMIT_CODE}`, + sql`${heartbeatRunEvents.payload}->'prpEvent'->>'turnId' = ${turnId}`, + )).limit(4); + return rows.some(row => { + const prpEvent = (row.payload as Record | null)?.prpEvent; + const parsed = validatePrpEvent(prpEvent); + return parsed.ok && parsed.event.runId === run.id && parsed.event.sourceKind === "runner" + && parsed.event.turnId === turnId && parsed.event.normalizedSessionId === run.nativeSessionId + && parsed.event.sourceInstanceId === run.runnerInstanceId && parsed.event.eventType === row.eventType + && parsed.event.sourceEventId === row.sourceEventId && parsed.event.sourceSeq === row.sourceSeq + && row.sourcePayloadSha256 === nativeSha256(parsed.event); + }); +} diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts index c1f69eb2620..4fbc48db02d 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts @@ -32,6 +32,7 @@ import { documentService } from "../documents.js"; import { issueService } from "../issues.js"; import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js"; import { TOOL_CALL_LOOP_HINT, ToolCallLoopError } from "./repeated-tool-failure-guard.js"; +import { cancelStoppedRunContinuation } from "./native-tool-receipt-limit.js"; import { PaperclipRunnerSemanticAuthority } from "./runner-semantic-authority.js"; import { createAssignedMcpTools } from "./assigned-mcp-tools.js"; import type { ToolGatewayService } from "../tool-gateway.js"; @@ -1638,6 +1639,53 @@ describe("PaperclipRunnerToolAuthority", () => { await db.delete(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey, key)); }); + it("queues no tool-call loop continuation for a run a person stopped, and cancels one queued before the Stop", async () => { + const authority = new PaperclipRunnerToolAuthority(db, { companyId, agentId, issueId, runId, workMode: "standard" }); + const key = `agent_tool_call_loop:${runId}`; + const loop = new ToolCallLoopError("call_api", 6, 6, ["operationId"], 400, "refused"); + await expect(authority.scheduleToolCallLoopContinuation(loop)).resolves.toBe(true); + const [before] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + const stopped = { ...before!, resultJson: { ...before!.resultJson, cancelledByActorType: "user", cancelledByUserId: "board-user" } }; + await db.update(heartbeatRuns).set({ resultJson: stopped.resultJson }).where(eq(heartbeatRuns.id, runId)); + try { + await expect(cancelStoppedRunContinuation(db, stopped, key)).resolves.toBe(1); + expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey, key))) + .map(row => row.status)).toEqual(["cancelled"]); + await db.delete(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey, key)); + await expect(authority.scheduleToolCallLoopContinuation(loop)).resolves.toBe(false); + expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey, key))).toHaveLength(0); + } finally { + await db.update(heartbeatRuns).set({ resultJson: before!.resultJson }).where(eq(heartbeatRuns.id, runId)); + await db.delete(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey, key)); + } + }); + + it("orders the loop continuation's locks task first, like Stop, so a concurrent Stop wins without a deadlock", async () => { + const authority = new PaperclipRunnerToolAuthority(db, { companyId, agentId, issueId, runId, workMode: "standard" }); + const key = `agent_tool_call_loop:${runId}`; + const loop = new ToolCallLoopError("call_api", 6, 6, ["operationId"], 400, "refused"); + const [before] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + let holdingTask!: () => void; + const taskLocked = new Promise(resolve => { holdingTask = resolve; }); + try { + const stop = db.transaction(async tx => { + await tx.select({ id: issues.id }).from(issues).where(eq(issues.id, issueId)).for("update"); + holdingTask(); + await new Promise(resolve => setTimeout(resolve, 300)); + await tx.update(heartbeatRuns).set({ resultJson: { ...before!.resultJson, cancelledByActorType: "user", cancelledByUserId: "board-user" } }) + .where(eq(heartbeatRuns.id, runId)); + }); + await taskLocked; + const scheduled = authority.scheduleToolCallLoopContinuation(loop); + await expect(stop).resolves.toBeUndefined(); + await expect(scheduled).resolves.toBe(false); + expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey, key))).toHaveLength(0); + } finally { + await db.update(heartbeatRuns).set({ resultJson: before!.resultJson }).where(eq(heartbeatRuns.id, runId)); + await db.delete(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey, key)); + } + }); + it("creates ordinary children, preserves blockers, and deduplicates across runs", async () => { const wakes: Array<{ agentId: string; options: Record }> = []; diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts index 77406c5b089..4df41025bf0 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts @@ -80,6 +80,7 @@ import { finishPendingRunnerApiCaptureDeletes, markRunnerApiCaptureEvictions, RU import { acquireRunnerApiResponseSlot, RUNNER_API_RESPONSE_DEADLINE_MS, RunnerApiCaptureReservationReclaimedError, runnerApiCompanyCaptureMaxBytes, RUNNER_API_RESPONSE_MAX_BYTES, RUNNER_API_RESPONSE_RUN_MAX_BYTES, RunnerApiResponseLimitError } from "./runner-api-response-limits.js"; import { and, desc, eq, inArray, isNull, notInArray, sql } from "drizzle-orm"; import { AGENT_TOOL_CALL_LOOP, TOOL_CALL_LOOP_HINT, toolCallLoopContinuationKey, type ToolCallLoopError } from "./repeated-tool-failure-guard.js"; +import { nativeRunHasStopRequest } from "./native-tool-receipt-limit.js"; import { enqueueWake } from "./status-decision-committer.js"; import type { Db } from "@paperclipai/db"; import { @@ -357,7 +358,13 @@ export class PaperclipRunnerToolAuthority { const review = this.binding.nativeReview; const loopContext = { sourceRunId: this.binding.runId, continuationCause: AGENT_TOOL_CALL_LOOP, tool: loop.tool, refusals: loop.refusals, runRefusals: loop.runRefusals, argumentNames: loop.argumentNames }; - await this.db.transaction(tx => enqueueWake({ + return this.db.transaction(async tx => { + await tx.select({ id: issues.id }).from(issues).where(and( + eq(issues.id, this.binding.issueId), eq(issues.companyId, this.binding.companyId))).for("update"); + const [run] = await tx.select({ resultJson: heartbeatRuns.resultJson }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.id, this.binding.runId), eq(heartbeatRuns.companyId, this.binding.companyId))).for("share"); + if (!run || nativeRunHasStopRequest(run.resultJson)) return false; + await enqueueWake({ tx: tx as unknown as Db, originRunId: this.binding.runId, companyId: this.binding.companyId, @@ -368,8 +375,9 @@ export class PaperclipRunnerToolAuthority { payload: { ...(review ?? {}), ...loopContext }, contextSnapshot: { ...(review ?? {}), forceFreshSession: true, livenessContinuationSourceRunId: this.binding.runId, livenessContinuationReason: AGENT_TOOL_CALL_LOOP, livenessContinuationInstruction: TOOL_CALL_LOOP_HINT }, - })); - return true; + }); + return true; + }); } constructor(readonly db: Db, readonly binding: Binding) {} diff --git a/server/src/services/native-runtime/status-arbiter.test.ts b/server/src/services/native-runtime/status-arbiter.test.ts index 579ddd39eaf..2a90adef678 100644 --- a/server/src/services/native-runtime/status-arbiter.test.ts +++ b/server/src/services/native-runtime/status-arbiter.test.ts @@ -157,6 +157,20 @@ describe("native status authority", () => { expect(decision.effects).toEqual([{ kind: "release_checkout" }]); }); + it("continues a turn stopped at its tool receipt limit in a fresh session, within its bound", () => { + const stopped = arbitrate({ terminalState: "cancelled", toolReceiptLimitStopped: true }); + expect(stopped).toMatchObject({ statusAction: "preserve", toStatus: "in_progress", reasonCode: "semantic_tool_turn_receipt_limit" }); + expect(stopped.effects).toEqual([ + { kind: "schedule_retry", cause: "semantic_tool_turn_receipt_limit", summary: "Continue the task in a fresh session.", agentId: expect.any(String) }, + { kind: "release_run_resources" }, + ]); + expect(arbitrate({ terminalState: "failed", toolReceiptLimitStopped: true }).effects) + .toEqual([expect.objectContaining({ kind: "schedule_retry", cause: "semantic_tool_turn_receipt_limit" })]); + expect(arbitrate({ terminalState: "cancelled", toolReceiptLimitStopped: true, failureRetryCount: 2 }).reasonCode).toBe("cancellation_run_only"); + expect(arbitrate({ terminalState: "cancelled", toolReceiptLimitStopped: true, priorIssueStatus: "blocked" }).reasonCode).toBe("cancellation_run_only"); + expect(arbitrate({ terminalState: "cancelled" }).reasonCode).toBe("cancellation_run_only"); + }); + it("treats only the authorized Board response_wake as passive and preserves governance", () => { const passive = assessment({ reportedDisposition: "yielded", diff --git a/server/src/services/native-runtime/status-arbiter.ts b/server/src/services/native-runtime/status-arbiter.ts index 26e3643e5e2..594f3011fef 100644 --- a/server/src/services/native-runtime/status-arbiter.ts +++ b/server/src/services/native-runtime/status-arbiter.ts @@ -1,6 +1,7 @@ import { COMPLETION_REVIEW_STAGE_REASON, COMPLETION_REVIEW_STAGE_REJECTED_REASON, type CompletionReviewStageEntry } from "../issue-execution-policy.js"; import type { NativeEvidenceAssessment } from "./evidence-classifier.js"; import { NATIVE_MODEL_REJECTION_MESSAGE, NATIVE_PROVIDER_CAPACITY_MAX_RETRIES, NATIVE_PROVIDER_OVERLOADED_CODE, NATIVE_PROVIDER_OVERLOADED_MESSAGE } from "./native-provider-failure.js"; +import { NATIVE_TOOL_RECEIPT_LIMIT_CODE, NATIVE_TOOL_RECEIPT_LIMIT_MAX_CONTINUATIONS } from "./native-tool-receipt-limit.js"; export const NATIVE_STATUS_ARBITER_POLICY_VERSION = "phase6-v14"; @@ -256,6 +257,7 @@ export function arbitrateNativeStatus(input: { providerModelRejected?: boolean; providerOverloaded?: boolean; providerFailureSuperseded?: boolean; + toolReceiptLimitStopped?: boolean; failureRetryCount?: number; /** * This run was itself the automatic continuation of an earlier failed turn. @@ -368,6 +370,20 @@ export function arbitrateNativeStatus(input: { ], }; } + if (input.toolReceiptLimitStopped && input.terminalState !== "succeeded" && !input.nativeReviewOutcome && + !input.governanceGate && !input.hasUnresolvedIssueBlockers && !input.hasActivePauseHold && + input.priorIssueStatus !== "blocked" && + (input.failureRetryCount ?? 0) < NATIVE_TOOL_RECEIPT_LIMIT_MAX_CONTINUATIONS) { + return { + policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION, + statusAction: "preserve", toStatus: input.priorIssueStatus, + reasonCode: NATIVE_TOOL_RECEIPT_LIMIT_CODE, unblockDescriptor: null, + effects: [ + { kind: "schedule_retry", cause: NATIVE_TOOL_RECEIPT_LIMIT_CODE, summary: "Continue the task in a fresh session.", agentId: input.agentId }, + ...(input.terminalState === "cancelled" ? [{ kind: "release_run_resources" as const }] : []), + ], + }; + } if (input.nativeReviewOutcome) { return { policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION, diff --git a/server/src/services/native-runtime/status-decision-committer.ts b/server/src/services/native-runtime/status-decision-committer.ts index 80da7787b0e..d64421cecc5 100644 --- a/server/src/services/native-runtime/status-decision-committer.ts +++ b/server/src/services/native-runtime/status-decision-committer.ts @@ -87,8 +87,9 @@ import { type ActivityPublication, } from "../activity-log.js"; import { emitAgentTaskRun } from "../agent-task-run-telemetry.js"; -import { materializeNativeProviderCapacityRetry } from "./native-provider-capacity-retry.js"; +import { materializeNativeProviderCapacityRetry, materializeNativeToolReceiptLimitContinuation } from "./native-provider-capacity-retry.js"; import { NATIVE_PROVIDER_OVERLOADED_CODE } from "./native-provider-failure.js"; +import { NATIVE_TOOL_RECEIPT_LIMIT_CODE } from "./native-tool-receipt-limit.js"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "../delivery-work-notifications.js"; export class NativeStatusRaceError extends Error { @@ -824,6 +825,19 @@ async function materializeDecisionEffect(input: { summary: effect.summary, }, }; + const [stopped] = effect.idempotencyKey === toolCallLoopContinuationKey(input.runId) + ? await input.tx.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, input.companyId), eq(agentWakeupRequests.agentId, effect.agentId), + eq(agentWakeupRequests.idempotencyKey, effect.idempotencyKey), eq(agentWakeupRequests.status, "cancelled"), + )).limit(1) + : []; + if (stopped) + return { + effectKind: effect.kind, + targetType: "agent_wakeup_request", + targetId: stopped.id, + payload: { continuationKind: effect.continuationKind, summary: effect.summary, cancelled: true }, + }; } if (effect.continuationKind === "monitor") throw new Error("Monitor delivery belongs to the issue monitor scheduler"); const wakeId = await enqueueWake({ @@ -895,8 +909,10 @@ async function materializeDecisionEffect(input: { } if (effect.kind === "schedule_retry") { failAt("continuation_materialization", input.failpoint); - if (effect.cause === NATIVE_PROVIDER_OVERLOADED_CODE) { - const retryId = await materializeNativeProviderCapacityRetry({ + if (effect.cause === NATIVE_PROVIDER_OVERLOADED_CODE || effect.cause === NATIVE_TOOL_RECEIPT_LIMIT_CODE) { + const materialize = effect.cause === NATIVE_PROVIDER_OVERLOADED_CODE + ? materializeNativeProviderCapacityRetry : materializeNativeToolReceiptLimitContinuation; + const retryId = await materialize({ tx: input.tx as unknown as Db, companyId: input.companyId, issueId: input.issue.id, runId: input.runId, agentId: effect.agentId, }); @@ -1699,8 +1715,8 @@ export async function commitNativeStatusDecision(input: { if (reasonCode === "native_provider_model_rejected" && !input.requireModelRejectionOwner) { throw new Error("native_model_rejection_owner_required"); } - if ((reasonCode.startsWith("native_provider_overloaded") || reasonCode === "native_run_failed_continuation_exhausted") - && !input.requireProviderFailureOwner) { + if ((reasonCode.startsWith("native_provider_overloaded") || reasonCode === "native_run_failed_continuation_exhausted" + || reasonCode === NATIVE_TOOL_RECEIPT_LIMIT_CODE) && !input.requireProviderFailureOwner) { throw new Error("native_provider_failure_owner_required"); } const publications: ActivityPublication[] = []; From d216e413f3447775e32adad37b9254e1fc69ce8b Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:01:51 -0600 Subject: [PATCH 02/13] test(recovery): stop the idle-backstop suite starting real runs and bound every wait (#21924) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The task recovery suites drive real recovery workers against an embedded database with a faked clock > - `issue-recovery-idle-backstop.test.ts` seeds 50 agents that take on-demand wakes, so recovery starts real `process` runs while timers are faked. A run then waits on timers that only move when the test advances, and the test waits for the run's passes with no time limit > - On master's readiness run for b4fa1c7fb1 (run 43861616674, attempt 2), server shard 6/10 went silent inside this file and was cancelled at the 20-minute job limit. Locally the same test timed out at 30 minutes in larger runs, and then the next test's setup hook timed out at the database truncate > - This pull request stops the file's agents from starting runs, as #21867 did for the agent-row census, and puts a time limit on every wait, with a message that names what it waited for > - The benefit is that this suite can no longer hang a CI shard silently; a stuck step fails within 20 seconds and says why ## Linked Issues or Issue Description Refs #21867, #21872, #21905 **What happened?** Server shard 6/10 of the readiness run for master b4fa1c7fb1 (run 43861616674, attempt 2, job 133284921313) printed "running 199 of 1988 suites", logged a completion timing line for 197 files, and was then silent from 12:15:05 until it was cancelled at 12:24:24. `issue-recovery-idle-backstop.test.ts` started at 12:12:47 and never logged its completion line. Its last output was at 12:13:34, in "recovers a task whose hint was never sent within the backstop bound". Locally, the same test hit its 30-minute test timeout in two larger multi-file runs, and the following tests' `beforeEach` (`TRUNCATE companies CASCADE`) hit the 30-second hook timeout. The logs of those runs show real runs executing inside this test: a process run starting ("running without injected PAPERCLIP_API_KEY") and `LegacyControllerLeaseLostError` raised from a faked-timer deadline in `legacy-controller-lease.ts`. Cause: `seedRecoveryPopulation` creates agents with `wakeOnDemand: true`, and the held agent in this file too. When recovery finds a stranded task it wakes the agent, and the wake starts a real run at once (`startNextQueuedRunForAgent`). The run's legacy controller lease and other waits use timers that the test fakes, while lease checks use the database clock. So the run either loses its lease when the fake clock jumps, or waits on a frozen timer. Meanwhile `advance()` waited for every delivery pass with no time limit. Whether a pass ends up waiting on such a run depends on timing, which is why the hang is rare. **Expected behavior** No fixture agent in this suite can start a run, and every wait fails with a named message within a fixed time. **Steps to reproduce** Run `issue-recovery-idle-backstop.test.ts` and grep its output for "running without injected PAPERCLIP_API_KEY" or "Legacy controller lease lost": 11 to 13 occurrences per run on master. The hang itself is rare (see Verification). **Paperclip version or commit** `master` at 9de343b3fe. ## What Changed - `helpers/recovery-population.ts`: optional `wakeOnDemand` (default `true`, so the other suites are unchanged). - `issue-recovery-idle-backstop.test.ts`: - The population and the held agent take no on-demand wakes. - The two tests that asserted a run was created now assert that recovery asked for a wake of the task. The wake queue records each one as skipped (`heartbeat.wakeOnDemand.disabled`), so the assertion still proves recovery found the task and acted. - Every wait has a 20-second real-time limit with a message naming the step: seeding, worker start, each simulated second, each set of pending delivery passes (listed by queue), each write and read. Per-test limit 2 minutes, down from 30. - `issue-recovery.test-fixture.ts`: records the queue of each pending pass (`pendingPassQueues()`), so a timed-out wait names the queues it was still waiting for. Not a product bug: no product code kept a transaction open after shutdown. The truncate timeouts came after the previous test timed out with real runs still in flight. ## Verification - Real runs started during one run of the file: 11 to 13 on master (two runs), 0 after. - The file alone: 4 passed (98 s). - Loop after the change: 15 runs (5 rounds of 3 in parallel): 15 passed, 0 hung or failed, 0 real run starts. - Before the change, my local reproduction rate was low: 3 failing multi-file runs out of about 10 large runs today (one silent hang, two with this test's 30-minute timeout). 0 of 14 targeted runs (alone, alone under load, and the 4-file combination) failed. So the loop shows the change holds; it cannot show a before/after hang count. The deterministic difference is the run starts above. - Master shard 6/10 for b4fa1c7fb1: see "What happened?". My local replay of the sharding script for that commit gave 201 of 2004 suites, against CI's 199 of 1988. The CI environment excludes some suites, so I identified the file from the job log, not from the replay. ## Risks - The two tests now prove that a wake was asked for, not that a run was created. Creating a run from a wake is covered by the wake-queue and dispatch suites, and these tests are about recovery finding the task. - Test-only change. No product code changed. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- .../__tests__/helpers/recovery-population.ts | 4 +- .../issue-recovery-idle-backstop.test.ts | 75 ++++++++++++------- .../__tests__/issue-recovery.test-fixture.ts | 10 ++- 3 files changed, 59 insertions(+), 30 deletions(-) diff --git a/server/src/__tests__/helpers/recovery-population.ts b/server/src/__tests__/helpers/recovery-population.ts index 16947d39334..15d566d813b 100644 --- a/server/src/__tests__/helpers/recovery-population.ts +++ b/server/src/__tests__/helpers/recovery-population.ts @@ -15,9 +15,11 @@ export type RecoveryPopulation = { export async function seedRecoveryPopulation(db: Db, companyId: string, counts: { agents: number; inReview: number; inProgress?: number; todo?: number; recoveryActions?: number; terminated?: number; + /** False keeps every agent from starting a run, for suites that fake timers. */ + wakeOnDemand?: boolean; }): Promise { const config = { adapterType: "process", adapterConfig: { command: process.execPath, args: ["-e", "0"], cwd: process.cwd() }, - runtimeConfig: { heartbeat: { enabled: false, intervalSec: 0, wakeOnDemand: true } }, role: "engineer" }; + runtimeConfig: { heartbeat: { enabled: false, intervalSec: 0, wakeOnDemand: counts.wakeOnDemand ?? true } }, role: "engineer" }; const [ceo] = await db.insert(agents).values({ ...config, companyId, name: "Chief", status: "idle" }).returning({ id: agents.id }); const managers = await db.insert(agents).values(Array.from({ length: 6 }, (_, index) => ({ ...config, companyId, name: `Manager ${index}`, status: "idle", reportsTo: ceo!.id }))).returning({ id: agents.id }); diff --git a/server/src/__tests__/issue-recovery-idle-backstop.test.ts b/server/src/__tests__/issue-recovery-idle-backstop.test.ts index baf8fd03798..870459fa0d7 100644 --- a/server/src/__tests__/issue-recovery-idle-backstop.test.ts +++ b/server/src/__tests__/issue-recovery-idle-backstop.test.ts @@ -1,7 +1,7 @@ import { setImmediate as immediate } from "node:timers/promises"; import { and, eq, sql } from "drizzle-orm"; import { expect, it, vi } from "vitest"; -import { agents, heartbeatRuns, issues } from "@paperclipai/db"; +import { agentWakeupRequests, agents, heartbeatRuns, issues } from "@paperclipai/db"; import { workSignalDebug } from "@paperclipai/db/work-signal-debug"; import { ISSUE_RECOVERY_BACKSTOP_MS, ISSUE_RECOVERY_FULL_BACKSTOP_MS, notifyIssueGraphRecovery } from "../services/issue-recovery-notifications.js"; @@ -14,16 +14,32 @@ import { seedRecoveryPopulation } from "./helpers/recovery-population.js"; vi.hoisted(() => { process.env.PAPERCLIP_DEBUG_WORK_SIGNALS = "stranded-assignments:1"; }); const MINUTE = 60_000; +const STEP_TIMEOUT_MS = 20_000; +const TEST_TIMEOUT_MS = 120_000; +const realSetTimeout = globalThis.setTimeout; +const realClearTimeout = globalThis.clearTimeout; type Recorded = { at: number; name: string; fields: Record }; +/** Fails with a message naming what it waited for instead of hanging. */ +function bounded(work: Promise, waitingFor: () => string): Promise { + let timer: ReturnType | undefined; + const expired = new Promise((_, reject) => { + timer = realSetTimeout(() => reject(new Error(`Timed out after ${STEP_TIMEOUT_MS} ms waiting for ${waitingFor()}`)), STEP_TIMEOUT_MS); + }); + return Promise.race([work, expired]).finally(() => realClearTimeout(timer)); +} + describeIssueRecovery("stranded-task checks at idle for a staging-shaped company", () => { const state = issueRecoveryFixture({ meter: true }); async function advance(ms: number) { const until = Date.now() + ms; while (Date.now() < until) { - await vi.advanceTimersByTimeAsync(Math.min(1000, until - Date.now())); - await Promise.allSettled([...state.passes]); await immediate(); + const at = new Date(Date.now()).toISOString(); + await bounded(vi.advanceTimersByTimeAsync(Math.min(1000, until - Date.now())), () => `simulated time to advance past ${at}`); + await bounded(Promise.allSettled([...state.passes]), + () => `delivery passes started by simulated ${at} to settle: ${state.pendingPassQueues().join(", ") || "none"}`); + await immediate(); } } @@ -53,21 +69,29 @@ describeIssueRecovery("stranded-task checks at idle for a staging-shaped company const checkedAt = (events: Recorded[], issueId: string) => events.find(event => event.name === "check" && event.fields.issueId === issueId)?.at ?? null; + /** The wakes recovery asked for on a task. No fixture agent takes on-demand + * wakes, so each is recorded as skipped and no real run starts under the + * faked clock (a run there could wait forever on a frozen timer). */ + const wakesFor = (companyId: string, issueId: string) => bounded(state.db.select({ id: agentWakeupRequests.id }) + .from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, companyId), + sql`${agentWakeupRequests.payload}->>'issueId' = ${issueId}`)), () => `the wake requests of task ${issueId} to be read`); + async function seed() { - const f = await state.fixture(); + const f = await bounded(state.fixture(), () => "the company to be created"); const population = await seedRecoveryPopulation(state.db, f.companyId, { agents: 50, inReview: 780, inProgress: 40, todo: 30, - recoveryActions: 12, terminated: 3 }); + recoveryActions: 12, terminated: 3, wakeOnDemand: false }); const [side] = await state.db.insert(issues).values({ companyId: f.companyId, title: "Finished side task", status: "done" }) .returning({ id: issues.id }); - const activity = () => state.db.transaction(tx => notifyIssueGraphRecovery(tx, { companyId: f.companyId, issueId: side!.id })); + const activity = () => bounded(state.db.transaction(tx => notifyIssueGraphRecovery(tx, { companyId: f.companyId, issueId: side!.id })), + () => "the unrelated activity hint to commit"); return { ...f, population, activity }; } async function boot() { - const f = await seed(); + const f = await bounded(seed(), () => "the staging-shaped population to be seeded"); const events = record(); vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] }); - await state.start({}); + await bounded(state.start({}), () => "the recovery workers to start"); await advance(10 * MINUTE); return { ...f, events, boot: summarize(events.splice(0)) }; } @@ -77,7 +101,7 @@ describeIssueRecovery("stranded-task checks at idle for a staging-shaped company const [held] = await state.db.insert(agents).values({ companyId: f.companyId, name: "Held worker", role: "engineer", status: "paused", lifecycleHolds: ["manual"], adapterType: "process", reportsTo: f.population.agentIds[1], createdAt: old, updatedAt: old, adapterConfig: { command: process.execPath, args: ["-e", "0"], cwd: process.cwd() }, - runtimeConfig: { heartbeat: { enabled: false, intervalSec: 0, wakeOnDemand: true } } }).returning({ id: agents.id }); + runtimeConfig: { heartbeat: { enabled: false, intervalSec: 0, wakeOnDemand: false } } }).returning({ id: agents.id }); const [waiting] = await state.db.insert(issues).values({ companyId: f.companyId, title: "Waits for its agent", status: "todo", assigneeAgentId: held!.id, createdAt: old, updatedAt: old }).returning({ id: issues.id }); return { held: held!, waiting: waiting! }; @@ -103,37 +127,34 @@ describeIssueRecovery("stranded-task checks at idle for a staging-shaped company expect(between.totalChecks).toBe(0); expect(between.statements).toBeLessThan(2_000); expect(hour.checks.backstop ?? 0).toBeLessThanOrEqual(f.population.inReview.length + 100); - }, 1_800_000); + }, TEST_TIMEOUT_MS); it("recovers a task whose hint was never sent within the backstop bound", async () => { const f = await boot(); const worker = f.population.agentIds[7]!; const now = new Date(); - const [missed] = await state.db.insert(issues).values({ companyId: f.companyId, title: "Created without a hint", status: "todo", - assigneeAgentId: worker, createdAt: now, updatedAt: now }).returning({ id: issues.id }); + const [missed] = await bounded(state.db.insert(issues).values({ companyId: f.companyId, title: "Created without a hint", status: "todo", + assigneeAgentId: worker, createdAt: now, updatedAt: now }).returning({ id: issues.id }), () => "the task without a hint to be created"); const window = await trickle(f, Math.ceil((ISSUE_RECOVERY_BACKSTOP_MS + MINUTE) / MINUTE) + 1); const checked = checkedAt(window.raw, missed!.id); expect(checked).not.toBeNull(); expect(checked! - now.getTime()).toBeLessThanOrEqual(ISSUE_RECOVERY_BACKSTOP_MS + 2 * MINUTE); - const runs = await state.db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId), - sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${missed!.id}`)); - expect(runs.length).toBeGreaterThan(0); - }, 1_800_000); + expect(await wakesFor(f.companyId, missed!.id), "recovery did not ask for a wake of the missed task").not.toHaveLength(0); + }, TEST_TIMEOUT_MS); it("re-checks a task whose only change is outside its own rows within the hourly full pass", async () => { const f = await boot(); - const { held, waiting } = await heldTask(f); - await state.db.execute(sql`update agents set status = 'idle', lifecycle_holds = '[]'::jsonb where id = ${held.id}`); + const { held, waiting } = await bounded(heldTask(f), () => "the held agent and its waiting task to be seeded"); + await bounded(state.db.execute(sql`update agents set status = 'idle', lifecycle_holds = '[]'::jsonb where id = ${held.id}`), + () => "the hold release without a hint to commit"); const changedAt = Date.now(); const window = await trickle(f, Math.ceil((ISSUE_RECOVERY_FULL_BACKSTOP_MS + 2 * MINUTE) / MINUTE)); const checks = window.raw.filter(event => event.name === "check" && event.fields.issueId === waiting.id); expect(checks.length).toBeGreaterThan(0); expect(checks[0]!.at - changedAt).toBeGreaterThan(2 * ISSUE_RECOVERY_BACKSTOP_MS); expect(checks[0]!.at - changedAt).toBeLessThanOrEqual(ISSUE_RECOVERY_FULL_BACKSTOP_MS + 2 * MINUTE); - const runs = await state.db.select({ id: heartbeatRuns.id }).from(heartbeatRuns) - .where(and(eq(heartbeatRuns.companyId, f.companyId), sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${waiting.id}`)); - expect(runs.length).toBeGreaterThan(0); - }, 1_800_000); + expect(await wakesFor(f.companyId, waiting.id), "recovery did not ask for a wake of the waiting task").not.toHaveLength(0); + }, TEST_TIMEOUT_MS); it("picks up a finished run, a user message, a raised budget and a resumed agent within a minute", async () => { const f = await boot(); @@ -142,25 +163,25 @@ describeIssueRecovery("stranded-task checks at idle for a staging-shaped company const within = async (issueId: string, act: () => Promise) => { f.events.length = 0; const at = Date.now(); - await act(); + await bounded(act(), () => `the change to task ${issueId} to commit`); await advance(60_000); const checked = checkedAt(f.events, issueId); expect(checked, issueId).not.toBeNull(); expect(checked! - at).toBeLessThanOrEqual(60_000); }; - const [run] = await state.db.select({ id: heartbeatRuns.id }).from(heartbeatRuns) - .where(sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${target!}`).limit(1); + const [run] = await bounded(state.db.select({ id: heartbeatRuns.id }).from(heartbeatRuns) + .where(sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${target!}`).limit(1), () => "the finished run to be read"); await within(target!, () => state.db.transaction(tx => notifyNativeStatusReassessment(tx, { companyId: f.companyId, runId: run!.id }))); await advance(31_000); await within(messaged!, () => issueService(state.db).addComment(messaged!, "Please look again", { userId: "recovery-user" })); await advance(31_000); await within(target!, () => state.db.transaction(tx => promoteDeferredWorkIntents(tx, { companyId: f.companyId, trigger: "pause_lifted" }))); await advance(31_000); - const { held, waiting } = await heldTask(f); + const { held, waiting } = await bounded(heldTask(f), () => "the held agent and its waiting task to be seeded"); await advance(31_000); await within(waiting.id, async () => { await state.db.update(agents).set({ status: "idle", lifecycleHolds: [], updatedAt: new Date() }).where(eq(agents.id, held.id)); await state.db.transaction(tx => promoteDeferredWorkIntents(tx, { companyId: f.companyId, trigger: "pause_lifted" })); }); - }, 1_800_000); + }, TEST_TIMEOUT_MS); }); diff --git a/server/src/__tests__/issue-recovery.test-fixture.ts b/server/src/__tests__/issue-recovery.test-fixture.ts index 8a90d73e492..1cb75fc42f3 100644 --- a/server/src/__tests__/issue-recovery.test-fixture.ts +++ b/server/src/__tests__/issue-recovery.test-fixture.ts @@ -32,6 +32,9 @@ export function issueRecoveryFixture(options: { meter?: boolean } = {}) { const tasks = new Map number | null; hasPending: () => Promise }>(); const errors: unknown[] = []; const passes = new Set>(); + // The queue each pending pass belongs to, so a bounded wait can say which + // queue it was still waiting for. + const passQueues = new Map, string>(); const extraStops: Array<() => Promise> = []; const extraDeadlines: Array<() => number | null> = []; beforeAll(async () => { @@ -61,8 +64,9 @@ export function issueRecoveryFixture(options: { meter?: boolean } = {}) { coordinator.register = (queue, task) => { tasks.set(queue, task); return register(queue, { ...task, run: signal => { - const work = task.run(signal); passes.add(work); - void work.then(() => passes.delete(work), () => passes.delete(work)); + const work = task.run(signal); passes.add(work); passQueues.set(work, queue); + const done = () => { passes.delete(work); passQueues.delete(work); }; + void work.then(done, done); return work; } }); }; @@ -254,5 +258,7 @@ export function issueRecoveryFixture(options: { meter?: boolean } = {}) { set draining(value: typeof draining) { draining = value; }, get errors() { return errors; }, get passes() { return passes; }, + /** The queues of the passes still pending, for a bounded wait's message. */ + pendingPassQueues: () => [...passes].map(pass => passQueues.get(pass) ?? "?"), }; } From fdf66c798917521eb641fd999cbc4450b6e1715c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BE=E9=87=8C=E8=BF=BD=E4=BC=8A?= <649038269@qq.com> Date: Tue, 17 Nov 2026 03:05:41 +0800 Subject: [PATCH 03/13] test(server): give the blocker history case room on a slow shard (#18720) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Its CI runs the server suite in shards so a change finishes in minutes > - One case in the attention-retention suite inserts 2100 issues and their relations, then runs EXPLAIN ANALYZE > - A single-file run takes about 90 seconds of local work, and the case itself fits in 15 seconds there > - On a two-core CI runner beside 110 other files, the case exceeds the 15s default > - This pull request gives that one case a 60s budget > - The benefit is that a slow shard stops failing for timing reasons ## Linked Issues or Issue Description **Summary** `ci / General tests (server (2/12))` fails intermittently on the same case. **Steps to reproduce** 1. Open a pull request that does not touch `server/`. 2. Wait for the shard that contains `src/__tests__/attention-retention-work.test.ts`. **Expected behavior** The case passes, as it does locally. **Actual behavior** `Error: Test timed out in 15000ms.` at `attention-retention-work.test.ts:443`. The rest of the shard passes (2197 tests). ## What Changed - Raise the timeout of the `it.each(["running", "run", "confirmation", "completed"])` case to 60 seconds. Nothing else changes: same assertions, same 2100-row fixture. ## Verification ```sh cd server npx vitest run src/__tests__/attention-retention-work.test.ts # 53 tests pass ``` The case still exercises the same query plan and the same bounded retention checks; only the wall-clock budget changed. ## Risks - Low risk. A slower failure now takes up to 60 seconds to surface on that one case. - No production code changes. ## Model Used - Provider: DeepSeek - Model ID: `deepseek-flash` - Harness: OpenCode - Capabilities used: tool calls (shell, file read/write, search) - Context window: not published by the provider ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --- server/src/__tests__/attention-retention-work.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/src/__tests__/attention-retention-work.test.ts b/server/src/__tests__/attention-retention-work.test.ts index e13d8a1931c..48a11fa94c9 100644 --- a/server/src/__tests__/attention-retention-work.test.ts +++ b/server/src/__tests__/attention-retention-work.test.ts @@ -626,7 +626,7 @@ const delay = DEFAULT_DECISION_ARCHIVE_DAYS * 86_400_000; expect(batch.deferredRootIds.size).toBe(0); expect(Boolean(batch.attention.get(root.id)?.blockingTreeLive)).toBe(kind !== "completed"); expect(parameterCounts.length).toBeLessThanOrEqual(100); - })); + }), 60_000); it("does not archive an unknown truncated blocker tree during its fresh check", async () => { const root = await insertIssue("blocked"); From 030810853160e661c8ea9a0732266cb6c493e542 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Mon, 16 Nov 2026 11:25:59 -0800 Subject: [PATCH 04/13] fix(native): pipeline tool progress events with text deltas (#21533) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Native runs store every relayed runner event in `heartbeat_run_events`. Each stored event also locks and updates the run's `heartbeat_runs` row. > - Text deltas already commit in batches. Every other event, including each `tool.execution.progressed` event, commits in its own transaction. > - Tool receipts and usage accounting lock the same run row. Under parallel tool calls, accounting failed with "other updates to the same run kept conflicting", and a provider-pack receipt save hit a lock timeout. > - #21520 made events that arrive while a batch commits join the next batch. This pull request adds tool progress events to the pipelined types, so they use those batches too. > - The benefit is fewer run-row transactions in tool-heavy turns, without changing event order. ## Linked Issues or Issue Description **What happened?** A routine run started several subagents that made about 190 tool calls in about 10 minutes. Three tool calls failed with "could not save this run's budget or usage records because other updates to the same run kept conflicting", and a provider-pack admission receipt failed with a lock timeout (55P03). Every tool progress event of the run was a separate transaction that updated the same run row. **Expected behavior** Observational events such as tool progress commit in batches, so they hold the run row lock fewer times. **Steps to reproduce** 1. Run a turn that makes many tool calls in parallel. 2. Each `tool.execution.progressed` event commits in its own transaction and updates `heartbeat_runs`. **Relevant logs or output** ``` could not save this run's budget or usage records because other updates to the same run kept conflicting native provider-pack admission receipt could not be saved (cause=55P03) ``` Related: #21531 tried letting the runner relay events faster, which would make this contention matter more. It is closed. ## What Changed - `paperclip-control-plane-port.ts`: - `pipelinedEventTypes` names `item.delta` and `tool.execution.progressed`. Both go through the batched append path and its group commit from #21520. - The text-delta boundary is now tracked when an event is appended: a pipelined event that is not a delta ends it, and a delta with text starts it. The first text delta after any other event still commits at once. - `contracts/control-plane-port.ts`: optional `pipelinedEventTypes`, and the `streaming` option documents that it applies to those types. - `native-session-runtime.ts`: the runtime pipelines the port's `pipelinedEventTypes`, and only `item.delta` when the port does not name them. - Tests: - `paperclip-control-plane-port.test.ts`: three progress events appended while a batch commits share one transaction, and a following event commits after them. - `native-session-runtime.test.ts`: progress appends start without waiting only when the port pipelines them. ## Verification - After rebasing onto current master: `pnpm exec vitest run src/services/native-runtime/paperclip-control-plane-port.test.ts` (in `server/`): 108 passed. - `npx vitest run src/native-session-runtime.test.ts` (in `packages/paperclip-runner`): 298 passed, 1 failed. `settles a governed wait through real Runner shutdown after a missing Codex terminal` needs the built Rust test binaries (`fake-codex-app-server`), which my checkout does not have. CI builds them. - `pnpm exec tsc --noEmit -p .` in `server/` (after building its workspace dependencies) and in `packages/paperclip-runner` pass. - `npx vitest run src/__tests__/chat-channels.integration.test.ts src/__tests__/heartbeat-process-recovery.test.ts src/services/native-runtime/native-plan-wait.test.ts src/services/native-runtime/paperclip-control-plane-port.test.ts` (in `server/`): 2,586 passed, 2 failed. `binds Slack tools to the admitted linked request...` reads a skills checkout that is not next to my worktree. `materializes direct external-chat finals once...` failed in the full file run but passes alone, with and without this change. ## Risks - Progress events now commit up to one transaction later than before. Their receipts and live UI updates follow their batch. - A batch that contains progress events still writes rows one by one inside its transaction, because progress events register chat-progress wakes. The gain is one transaction and one lock wait per batch, not one row update per batch. - If a batch fails, every event in it fails, and the runner resends them. That is the same as for text deltas today. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip --- .../src/contracts/control-plane-port.ts | 4 ++- .../src/native-session-runtime.test.ts | 26 ++++++++++++++++-- .../src/native-session-runtime.ts | 3 ++- .../paperclip-control-plane-port.test.ts | 27 ++++++++++++++++++- .../paperclip-control-plane-port.ts | 15 ++++++----- 5 files changed, 64 insertions(+), 11 deletions(-) diff --git a/packages/paperclip-runner/src/contracts/control-plane-port.ts b/packages/paperclip-runner/src/contracts/control-plane-port.ts index 1e7b5664a7f..98cd2aeb117 100644 --- a/packages/paperclip-runner/src/contracts/control-plane-port.ts +++ b/packages/paperclip-runner/src/contracts/control-plane-port.ts @@ -36,7 +36,8 @@ export interface AppendControlPlaneEventOptions { */ deferPostCommitObservers?: true; /** - * For an `item.delta` only, on a port with `pipelinesStreamingEvents`: the + * For an event type in the port's `pipelinedEventTypes` (only `item.delta` + * when the port does not name them), on a port with `pipelinesStreamingEvents`: the * caller does not wait for this receipt before its next append, so the port * may hold the delta briefly to commit it with later ones. */ @@ -95,6 +96,7 @@ export interface ControlPlanePort { * commits. */ readonly pipelinesStreamingEvents?: boolean; + readonly pipelinedEventTypes?: ReadonlySet; /** Commits the queued streaming deltas now, without waiting for the batch timer. */ flushStreamingEvents?(): void; normalizeReplayPayload?(payload: PrpEvent["payload"]): PrpEvent["payload"]; diff --git a/packages/paperclip-runner/src/native-session-runtime.test.ts b/packages/paperclip-runner/src/native-session-runtime.test.ts index 93813aab14b..c5a8842fc5f 100644 --- a/packages/paperclip-runner/src/native-session-runtime.test.ts +++ b/packages/paperclip-runner/src/native-session-runtime.test.ts @@ -312,7 +312,8 @@ describe("executeNativeSession recovery", () => { }); /** A batching port whose queued deltas commit only when flushed: it has no timer. */ - const batchingDeltaFixture = (events: () => AsyncGenerator, commitDelta: (sourceSeq: number) => Promise = async () => {}) => { + const batchingDeltaFixture = (events: () => AsyncGenerator, commitDelta: (sourceSeq: number) => Promise = async () => {}, + pipelinedEventTypes?: ReadonlySet) => { const capabilities = { resume: true, typedEvents: true, steering: false, interruption: true, structuredResult: true }; const session: NativeSession = { identity: () => identity, @@ -335,6 +336,7 @@ describe("executeNativeSession recovery", () => { let queued: Array<() => void> = []; const port: ControlPlanePort = { pipelinesStreamingEvents: true, + ...(pipelinedEventTypes ? { pipelinedEventTypes } : {}), flushStreamingEvents() { log.push("flush"); const flushed = queued; @@ -345,7 +347,7 @@ describe("executeNativeSession recovery", () => { async appendEvent(event: PrpEvent, options) { if (event.sourceKind !== "runner") return { cursor: 0, highestContiguousSourceSeq: event.sourceSeq, disposition: "committed" }; log.push(`append:${event.sourceSeq}`); - if (event.eventType === "item.delta") { + if ((pipelinedEventTypes ?? new Set(["item.delta"])).has(event.eventType)) { expect(options?.streaming).toBe(true); await new Promise(resolve => queued.push(resolve)); await commitDelta(event.sourceSeq); @@ -375,6 +377,26 @@ describe("executeNativeSession recovery", () => { expect(execution).toMatchObject({ nativeEventCount: 7, highestContiguousSourceSeq: 5 }); }); + it.each([true, false])("starts progress appends without waiting only when the port pipelines them (pipelined=%s)", async pipelined => { + const progress = (sourceSeq: number) => runnerEvent(sourceSeq, "tool.execution.progressed", { name: "build", status: "running" }); + const f = batchingDeltaFixture(async function* () { + for (const sourceSeq of [1, 2]) yield progress(sourceSeq); + yield streamedDelta(3); + yield runnerEvent(4, "run.result.proposed", result); + yield runnerEvent(5, "turn.completed"); + }, async () => {}, pipelined ? new Set(["item.delta", "tool.execution.progressed"]) : undefined); + const execution = await executeNativeSession({ input: preparedInput(), backend: f.backend, controlPlane: f.port, + runnerInstanceId: "runner-recovery", controlPlaneInstanceId: "control-recovery" }); + expect(f.log.slice(0, 4)).toEqual(["append:1", "append:2", "append:3", "flush"]); + if (pipelined) { + expect(f.log.indexOf("append:2")).toBeLessThan(f.log.indexOf("committed:1")); + expect(f.log.indexOf("append:4")).toBeGreaterThan(Math.max(...[1, 2, 3].map(seq => f.log.indexOf(`committed:${seq}`)))); + } else { + expect(f.log).not.toContain("committed:1"); + } + expect(execution).toMatchObject({ highestContiguousSourceSeq: 5 }); + }); + it("joins pending delta appends before a failed turn settles", async () => { let releaseCommit = () => {}; const commitReleased = new Promise(resolve => { releaseCommit = resolve; }); diff --git a/packages/paperclip-runner/src/native-session-runtime.ts b/packages/paperclip-runner/src/native-session-runtime.ts index 218f2ab52dc..e5aa6c1a5f0 100644 --- a/packages/paperclip-runner/src/native-session-runtime.ts +++ b/packages/paperclip-runner/src/native-session-runtime.ts @@ -1265,6 +1265,7 @@ async function consumeTurn( // delta's receipt settles. Every other event, and every result, waits for // the receipts of the deltas before it. const pipelinesDeltas = controlPlane.pipelinesStreamingEvents === true; + const pipelinedEventTypes: ReadonlySet = controlPlane.pipelinedEventTypes ?? new Set(["item.delta"]); let pendingDeltas: Promise[] = []; let deltaFailure = null as { error: unknown } | null; const settlePendingDeltas = async () => { @@ -1450,7 +1451,7 @@ async function consumeTurn( // A failed delta stops the turn before any later event is appended. if (deltaFailure) throw deltaFailure.error; let receipt: AppendedEventReceipt | null = null; - if (pipelinesDeltas && event.eventType === "item.delta") { + if (pipelinesDeltas && pipelinedEventTypes.has(event.eventType)) { const pending = controlPlane.appendEvent(event, { signal: appendAbort.signal, streaming: true }); const settled = pending.then(() => undefined, (error: unknown) => { deltaFailure ??= { error }; }); outstandingDeltas.add(settled); diff --git a/server/src/services/native-runtime/paperclip-control-plane-port.test.ts b/server/src/services/native-runtime/paperclip-control-plane-port.test.ts index 2975c229823..406070043ad 100644 --- a/server/src/services/native-runtime/paperclip-control-plane-port.test.ts +++ b/server/src/services/native-runtime/paperclip-control-plane-port.test.ts @@ -3,7 +3,7 @@ import { resolveExternalTestDatabaseUrl } from "../../__tests__/helpers/external import { plugins } from "@paperclipai/db"; import { readTaskPanelActivations } from "../plugin-task-panels.js"; import { startServerMetrics, stopServerMetrics } from "../server-metrics.js"; -import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { and, asc, eq, sql } from "drizzle-orm"; import { createHash, generateKeyPairSync, randomUUID } from "node:crypto"; import { mkdtemp, rm } from "node:fs/promises"; @@ -1096,6 +1096,31 @@ describe("PaperclipControlPlanePort conformance", () => { await expect(f.port.appendEvent(f.event(12), f.streamed)).resolves.toMatchObject({ cursor: 12 }); }); + it("commits progress events that arrive while a batch commits in the next single batch", async () => { + let release!: () => void; + const gate = new Promise(resolve => { release = resolve; }); + const f = await streamingFixture({ streamingBatchMs: 600_000, onCommittedEvent: async (event) => { + if (event.sourceSeq === 1) await gate; + } }); + const first = f.port.appendEvent(f.event(1, "tool.execution.progressed"), f.streamed); + await vi.waitFor(async () => expect(await f.stored()).toHaveLength(1)); + const options = db.$client.options as { debug?: unknown }; + const statements: string[] = []; + options.debug = (_connection: number, text: string) => { statements.push(text.trim().replace(/\s+/g, " ")); }; + try { + const later = [2, 3, 4].map(sourceSeq => f.port.appendEvent(f.event(sourceSeq, "tool.execution.progressed"), f.streamed)); + await new Promise(resolve => setTimeout(resolve, 50)); + expect(statements.filter(text => /^begin/i.test(text))).toHaveLength(0); + release(); + await expect(first).resolves.toMatchObject({ cursor: 1, disposition: "committed" }); + expect((await Promise.all(later)).map(receipt => receipt.cursor)).toEqual([2, 3, 4]); + expect(statements.filter(text => /^begin/i.test(text))).toHaveLength(1); + } finally { options.debug = undefined; } + const boundary = await f.port.appendEvent(f.event(5, "tool.execution.started")); + expect(boundary).toMatchObject({ cursor: 5, disposition: "committed" }); + expect(await f.stored()).toEqual([1, 2, 3, 4, 5].map(seq => ({ seq, sourceSeq: seq }))); + }); + it("observes every committed delta of a batch when one observer fails", async () => { const observed: number[] = []; const f = await streamingFixture({ streamingBatchMs: 600_000, onCommittedEvent: async (event) => { diff --git a/server/src/services/native-runtime/paperclip-control-plane-port.ts b/server/src/services/native-runtime/paperclip-control-plane-port.ts index 7afee85af21..578b82bd420 100644 --- a/server/src/services/native-runtime/paperclip-control-plane-port.ts +++ b/server/src/services/native-runtime/paperclip-control-plane-port.ts @@ -125,6 +125,7 @@ export class PaperclipControlPlanePort implements ControlPlanePort { * a delta's receipt settles; the receipt settles after its batch commits. */ readonly pipelinesStreamingEvents = true; + readonly pipelinedEventTypes: ReadonlySet = new Set(["item.delta", "tool.execution.progressed"]); readonly #streamingBatchMs: number; #streamingBatch: PendingStreamingEvent[] = []; #streamingTimer: ReturnType | null = null; @@ -133,7 +134,7 @@ export class PaperclipControlPlanePort implements ControlPlanePort { /** Deltas queued or committing. Other operations wait only when some are; otherwise they start at once. */ #streamingEventsPending = 0; /** - * False until a delta with text commits after the latest other event. Until + * False until a delta with text is appended after the latest other event. Until * then each delta commits at once, so the first text of an item, and the * time to first token, never wait for the batch timer. */ @@ -467,7 +468,7 @@ export class PaperclipControlPlanePort implements ControlPlanePort { }, assertWritable: () => this.#assertActive(options), }; - if (event.eventType === "item.delta" && !options?.deferPostCommitObservers) { + if (this.pipelinedEventTypes.has(event.eventType) && !options?.deferPostCommitObservers) { return this.#appendStreamingEvent({ event, input, options, startedAtMs: persistenceStartedAt, startedClock: persistenceClock }, options?.streaming === true); } @@ -547,7 +548,12 @@ export class PaperclipControlPlanePort implements ControlPlanePort { return new Promise((resolve, reject) => { this.#streamingBatch.push({ ...pending, resolve, reject }); this.#streamingEventsPending += 1; - if (!streaming || !this.#streamedSinceBoundary || this.#streamingBatch.length >= STREAMING_EVENT_BATCH_MAX) { + if (pending.event.eventType !== "item.delta") this.#streamedSinceBoundary = false; + const flushNow = !streaming || !this.#streamedSinceBoundary || this.#streamingBatch.length >= STREAMING_EVENT_BATCH_MAX; + if (typeof pending.event.payload.text === "string" && pending.event.payload.text.length > 0) { + this.#streamedSinceBoundary = true; + } + if (flushNow) { void this.#flushStreamingEvents(); } else { this.#streamingTimer ??= setTimeout(() => { void this.#flushStreamingEvents(); }, this.#streamingBatchMs); @@ -569,9 +575,6 @@ export class PaperclipControlPlanePort implements ControlPlanePort { this.#streamingFlushQueued = false; const batch = this.#streamingBatch; this.#streamingBatch = []; - if (batch.some(pending => typeof pending.event.payload.text === "string" && pending.event.payload.text.length > 0)) { - this.#streamedSinceBoundary = true; - } try { await this.#commitStreamingEvents(batch); } finally { this.#streamingEventsPending -= batch.length; } }); From cc9ff75cb8b88a4aa698bf774d4f2ff453558258 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Mon, 16 Nov 2026 12:13:04 -0800 Subject: [PATCH 05/13] fix(runtime): keep managed GitHub access across a controller restart (#21928) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Native runs give agents managed GitHub access through `gh` and `git` launchers on the provider's `PATH` > - A provider process can keep running while the server restarts, and the next controller adopts it > - The detaching controller deleted the launcher directory, and the adopting controller staged launchers in a new random directory > - The running provider still names the old directory, so every later `gh` or `git` call ran without credentials > - This pull request keeps the launcher directory stable for one provider session and task, and re-arms it after the restart > - The benefit is that a long run keeps its GitHub identity across a server deploy or restart ## Linked Issues or Issue Description No public issue exists. This describes the bug in-PR, with the bug template labels. **What happened?** An agent run on a Daytona sandbox used `gh` with managed GitHub access. The server restarted during the run (a rolling deploy), and the controller re-attached to the live provider process. After that, every `gh` call failed with `You are not logged into any GitHub hosts`. `git credential fill` returned no token. The agent reported that its token had "expired" and used the unauthenticated public API for the rest of the run. **Steps to reproduce** 1. Start a native run with managed GitHub access on a remote sandbox. 2. Run a `gh` command in the run. It succeeds. 3. Restart the server while the provider process is still running. The new controller re-attaches to the process. 4. Run a `gh` command again in the same run. It fails with "not logged in", and no `Paperclip: GitHub ...` diagnostic appears. **Expected behavior** After the new controller adopts the provider, `gh` and `git` get credentials from the new controller, as they did before the restart. **Root cause** - `createNativeGitHubAccess` staged the launchers in `native-session-` and put that path in the provider's `PATH`, `BASH_ENV`, and `GH_CONFIG_DIR`. - On a restart detach, `githubAccess.stop()` ran `rm -rf` on that directory (`detachReleasedWarmNativeSession`, and the run's final `github_stop` while `nativeRunsDetachingForRestart` is set). - The adopting controller made a new random directory. The provider environment cannot change after spawn, so the provider never saw it. - The shims were gone. `gh` resolved to the real binary with an empty `GH_CONFIG_DIR`, so no Paperclip diagnostic appeared. Refs #15354. That PR keeps ACPX sessions across launcher rotation in the legacy adapter path. This PR covers the native runtime path. ## What Changed - `createNativeGitHubAccess` takes an optional `launcherKey`. The launcher directory is `native-github-`, so the same provider session and task always get the same directory. - The native session executor passes a key built from `nativeSessionScopeKey` and the issue id. - `prepareGitHubOperationLaunchers` takes an optional `broker`. It then stages broker-file launchers and an owner-only `broker.json`. The launchers already read `broker.json` on each operation in this mode (`githubLauncherSource({ brokerFile: true })`). A restaged directory therefore gives the running provider the new endpoint. - Native access passes `broker` only for remote sandbox targets. A sandbox provider is the one that outlives a controller restart. Local launchers live in the shared host temp directory, so they keep the capability in the provider environment only, as before. - `stop({ preserveLaunchers: true })` keeps the launcher directory. A restart detach of an active run and of a released warm session use this option. A normal stop still removes the directory. - A final stop does not remove a directory that a newer access in the same process has already restaged. - The callback bridge runtime stays in its own per-access directory. A new bridge never shares a queue directory with an old bridge. - `syncRemoteTextFiles` takes a `private` flag. It sets `umask 077` for the whole staging script, so the upload copy, the partial file, and the final file are never readable by group or other users. Local launcher files are written to a temporary file and renamed, so a running launcher never reads a partly written file. ## Verification - New `native-github-access` test on a sandbox target: a live parent process gets credentials, the access stops with `preserveLaunchers`, and a new access with the same key re-arms the directory. The same parent PID then gets the new controller's credentials, with empty stderr. `broker.json` has mode `600`. The final stop removes the directory. - New previous-release cutover test: a provider launched with the old random-directory layout keeps working without managed GitHub after its controller removes the directory. The new controller does not resolve credentials for it. A provider that the new controller launches gets credentials. - New local regression: local launcher files do not contain the broker capability, and there is no `broker.json`. - New local restart test: a local provider adopted after a restart gets a Paperclip diagnostic and no credentials. The new controller resolves nothing for the old endpoint. - New `sandbox-callback-bridge` test: staging a private file runs with umask `077` and leaves the file at mode `600`. - New `native-github-access` test: when a superseded access stops, its successor's launchers stay usable. A different key gives a different directory. - New `native-session-executor` test: a run detached for restart while active stops its GitHub access with `{ preserveLaunchers: true }`, and creates it with a `launcherKey`. The existing overlapping-failure test now asserts `{ preserveLaunchers: false }`. - The new tests fail on the old behavior. I checked this by forcing `brokerFile: false`, forcing `preserveLaunchers = false`, removing the `umask 077` line, and writing `broker.json` for local targets. - Passed: `native-github-access` (26), `native-session-executor` + `github-operation-credentials` + `heartbeat-github-launchers` + `native-stop-accounting` + `heartbeat-project-env` (1640 passed, 7 skipped), `native-runner-restart-recovery.integration` and `heartbeat-native-restart-suspension`. - Passed: adapter-utils `execution-target`, `github-launcher`, `github-launcher-environment`, `sandbox-callback-bridge`; runner `acpx/github-launcher`, `acpx/environment`, `codex/codex-security-config`. - `pnpm --filter @paperclipai/adapter-utils typecheck` and the server `pnpm typecheck` pass. - Not run locally: `native-warm-checkpoint-ownership.integration` needs the compiled `paperclip-runnerd` binary. CI builds it. ## Previous-release story - No persisted run, session, checkpoint, or database state changes. Only the in-sandbox launcher layout changes. - A provider launched by the previous release has a random `native-session-*` launcher directory in its environment. The previous release's controller removes that directory at the cutover restart. The new controller cannot find it, so it does not re-arm it. - That provider carries forward without managed GitHub until its next spawn, which is the current behavior. The run is not refused and is not retried. `gh` and `git` run without managed credentials, as they do today after a restart. The cutover test covers this. - A provider that the new release launches gets the stable directory and survives later restarts. ## Risks - On sandbox targets, the provider can now read the bridge capability in `broker.json`, as well as in its environment. The file holds the same per-access transport token that the environment already holds, not a run token or a GitHub credential. The file and its staging copies are mode `600`, and the broker still checks the active run and grants on each request. Local targets write no `broker.json`. - Local providers that outlive a restart still lose managed GitHub. This is not a regression: master deletes the launcher directory at the detach, so the old local provider also runs without credentials there. With this PR, the local launchers stay in place and print a `Paperclip: GitHub ...` diagnostic instead of a silent "not logged in". Re-arming local providers needs a broker channel that other local runs under the same user cannot read. That is out of scope here, because `broker.json` in the shared temp directory was a security finding on this PR. - On sandbox targets, `git` and `gh` children no longer inherit `PAPERCLIP_API_URL`, `PAPERCLIP_API_KEY`, or `PAPERCLIP_GITHUB_BRIDGE_TOKEN`. Broker-file mode removes them, as it already did in its existing tests. - After a restart detach, a launcher directory stays in the workspace runtime directory. If no controller adopts the provider, that directory stays until a later access with the same key stops, or until the workspace is removed. It contains no GitHub credential. - Between the detach and the adoption, `gh` gets a transport error from the old endpoint. It then prints `broker_transport_unavailable` and continues without credentials, as before. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, test runs). Standard context window. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- .../adapter-utils/src/execution-target.ts | 11 +- .../src/remote-text-file-sync.ts | 6 +- .../src/sandbox-callback-bridge.test.ts | 25 ++++ .../native-github-access.test.ts | 111 +++++++++++++++++- .../native-runtime/native-github-access.ts | 32 +++-- .../native-session-executor.test.ts | 45 ++++++- .../native-runtime/native-session-executor.ts | 14 ++- 7 files changed, 222 insertions(+), 22 deletions(-) diff --git a/packages/adapter-utils/src/execution-target.ts b/packages/adapter-utils/src/execution-target.ts index 5e2ea679cc0..077cb38b63d 100644 --- a/packages/adapter-utils/src/execution-target.ts +++ b/packages/adapter-utils/src/execution-target.ts @@ -1832,6 +1832,7 @@ printf '\0PAPERCLIP_GIT_CONTEXT_END\0' /** Stage token-free launchers next to the execution, not in shared global Git config. */ export async function prepareGitHubOperationLaunchers(input: { runId: string; target: AdapterExecutionTarget | null | undefined; cwd: string; env: Record; + broker?: { url: string; token: string }; }): Promise> { const remote = input.target?.kind === "remote" ? input.target : null; const directory = githubOperationLauncherDirectory(input); @@ -1851,8 +1852,9 @@ export async function prepareGitHubOperationLaunchers(input: { // Remote launchers live beneath the checkout. Pin their own package scope // so an enclosing project's "type": "module" cannot reinterpret require(). ["package.json", '{"type":"commonjs"}\n'], - ...["git", "gh"].map((name) => [name, githubLauncherSource()] as const), + ...["git", "gh"].map((name) => [name, githubLauncherSource({ brokerFile: input.broker !== undefined })] as const), ...[".zshenv", ".zprofile", ".zshrc", ".bash_profile", ".bashrc", ".profile"].map((name) => [name, profile] as const), + ...(input.broker ? [["broker.json", `${JSON.stringify({ url: input.broker.url, token: input.broker.token })}\n`] as const] : []), ]); if (remote) { const runner = adapterExecutionTargetCommandRunner(remote); @@ -1863,6 +1865,7 @@ export async function prepareGitHubOperationLaunchers(input: { label: "GitHub operation launcher", action: "stage GitHub operation launcher", lockDir: path.posix.join(directory, `.${program}.lock`), executable: program === "git" || program === "gh", + private: program === "broker.json", })), ensureDirectories: [configDirectory], action: "stage GitHub operation launchers", timeoutMs: 15_000, shellCommand: adapterExecutionTargetShellCommand(remote), @@ -1870,7 +1873,11 @@ export async function prepareGitHubOperationLaunchers(input: { } else { await fs.mkdir(directory, { recursive: true, mode: 0o700 }); await fs.mkdir(configDirectory, { recursive: true, mode: 0o700 }); - for (const [program, body] of Object.entries(files)) await fs.writeFile(path.join(directory, program), body, { mode: 0o700 }); + for (const [program, body] of Object.entries(files)) { + const partial = path.join(directory, `.${program}.${randomUUID()}.partial`); + await fs.writeFile(partial, body, { mode: program === "broker.json" ? 0o600 : 0o700 }); + await fs.rename(partial, path.join(directory, program)); + } } return { ...input.env, PATH: managedPath, ZDOTDIR: directory, BASH_ENV: `${directory}/.bashrc`, GH_CONFIG_DIR: configDirectory, PAPERCLIP_GITHUB_LAUNCHER_DIR: directory }; diff --git a/packages/adapter-utils/src/remote-text-file-sync.ts b/packages/adapter-utils/src/remote-text-file-sync.ts index 309964038b9..2b2edd36d09 100644 --- a/packages/adapter-utils/src/remote-text-file-sync.ts +++ b/packages/adapter-utils/src/remote-text-file-sync.ts @@ -12,6 +12,7 @@ export interface RemoteTextFileSyncFile { action: string; lockDir: string; executable?: boolean; + private?: boolean; } export interface RemoteTextFileSyncInput extends RemoteTextFileSyncFile { @@ -52,6 +53,7 @@ function program(input: RemoteTextFileSyncFile) { const sha256 = createHash("sha256").update(input.body, "utf8").digest("hex"); const script = [ "set -eu", + ...(input.private ? ["umask 077"] : []), `remote_dir=${shellQuote(input.remoteDir)}`, `remote_path=${shellQuote(input.remotePath)}`, `remote_partial=${shellQuote(remotePartial)}`, @@ -79,7 +81,7 @@ function program(input: RemoteTextFileSyncFile) { " current_sha=\"$(hash_file \"$remote_path\" 2>/dev/null)\" || current_sha=\"\"", "fi", "if [ -n \"$current_sha\" ] && [ \"$current_sha\" = \"$expected_sha\" ]; then", - ...(input.executable ? [' chmod 700 "$remote_path"'] : []), + ...(input.executable ? [' chmod 700 "$remote_path"'] : input.private ? [' chmod 600 "$remote_path"'] : []), " printf '{\"uploaded\":false}\\n'", " exit 0", "fi", @@ -94,7 +96,7 @@ function program(input: RemoteTextFileSyncFile) { "else", ` echo ${shellQuote(`${input.label} sha verify skipped: no sha256sum/shasum on remote.`)} >&2`, "fi", - ...(input.executable ? ['chmod 700 "$remote_partial"'] : []), + ...(input.executable ? ['chmod 700 "$remote_partial"'] : input.private ? ['chmod 600 "$remote_partial"'] : []), "mv \"$remote_partial\" \"$remote_path\"", "printf '{\"uploaded\":true}\\n'", ].join("\n"); diff --git a/packages/adapter-utils/src/sandbox-callback-bridge.test.ts b/packages/adapter-utils/src/sandbox-callback-bridge.test.ts index 5222af5b201..bf59f88667b 100644 --- a/packages/adapter-utils/src/sandbox-callback-bridge.test.ts +++ b/packages/adapter-utils/src/sandbox-callback-bridge.test.ts @@ -1446,6 +1446,31 @@ describe("sandbox callback bridge", () => { ).resolves.toEqual([]); }); + it("creates every staged copy of a private file without group or other access", async () => { + const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-private-sync-")); + cleanupDirs.push(rootDir); + const shimDir = path.join(rootDir, "shim"); + const umaskLog = path.join(rootDir, "umask.log"); + await mkdir(shimDir); + await writeFile(path.join(shimDir, "base64"), + `#!/bin/sh\numask > ${JSON.stringify(umaskLog)}\nPATH=${JSON.stringify(process.env.PATH ?? "")} exec base64 "$@"\n`, { mode: 0o700 }); + const inner = createExecRunner(); + const runner = { + execute: (input: Parameters[0]) => + inner.execute({ ...input, env: { ...input.env, PATH: `${shimDir}:${process.env.PATH ?? ""}` } }), + }; + const remoteDir = path.join(rootDir, "launchers"); + const remotePath = path.posix.join(remoteDir, "broker.json"); + const result = await syncRemoteTextFileWithHashSkip({ + runner, remoteCwd: rootDir, remoteDir, remotePath, body: "{\"token\":\"fixture\"}\n", + label: "Private fixture", action: "sync private fixture", + lockDir: path.posix.join(remoteDir, ".broker.json.lock"), private: true, timeoutMs: 30_000, + }); + expect(result.uploaded).toBe(true); + expect((await readFile(umaskLog, "utf8")).trim()).toMatch(/^0?077$/); + expect((await fs.stat(remotePath)).mode & 0o777).toBe(0o600); + }); + it("test_process_session_script_rewritten_on_hash_mismatch: a mismatched remote hash still rewrites the script", async () => { const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-hashskip-cold-")); cleanupDirs.push(rootDir); diff --git a/server/src/services/native-runtime/native-github-access.test.ts b/server/src/services/native-runtime/native-github-access.test.ts index c979240c15f..847434bf850 100644 --- a/server/src/services/native-runtime/native-github-access.test.ts +++ b/server/src/services/native-runtime/native-github-access.test.ts @@ -1,6 +1,6 @@ import { afterEach, expect, it, vi } from "vitest"; import { spawn, execFile } from "node:child_process"; -import { mkdtemp, mkdir, readFile, rm, writeFile, access } from "node:fs/promises"; +import { mkdtemp, mkdir, readdir, readFile, rm, stat, writeFile, access } from "node:fs/promises"; import { promisify } from "node:util"; import type { CommandManagedDuplexChannel, CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime"; import type { DuplexObservabilityRecorder } from "@paperclipai/adapter-utils/duplex-observability"; @@ -40,11 +40,12 @@ function localDuplexChannel(command: readonly string[], cwd: string): CommandMan async function broker(resolveCredentials = vi.fn(async (binding: ReturnType) => ({ status: "available", env: { GH_TOKEN: `fixture-${binding.runId}` }, })), remote = false, bridgeUnavailable = false, onLog?: (stream: "stdout" | "stderr", chunk: string) => Promise, -duplex?: { enabled?: boolean; capability: boolean; unavailable?: boolean; startupFailure?: "lost" | "unreachable"; fallbackUnavailable?: boolean; fileProbeFails?: boolean; recorder?: DuplexObservabilityRecorder }) { - const root = await mkdtemp(path.join(tmpdir(), "native-github-reuse-")); - cleanups.push(() => rm(root, { recursive: true, force: true })); +duplex?: { enabled?: boolean; capability: boolean; unavailable?: boolean; startupFailure?: "lost" | "unreachable"; fallbackUnavailable?: boolean; fileProbeFails?: boolean; recorder?: DuplexObservabilityRecorder }, +placement: { root?: string; launcherKey?: string } = {}) { + const root = placement.root ?? await mkdtemp(path.join(tmpdir(), "native-github-reuse-")); + if (!placement.root) cleanups.push(() => rm(root, { recursive: true, force: true })); const bin = path.join(root, "real-bin"); - await mkdir(bin); + await mkdir(bin, { recursive: true }); await writeFile(path.join(bin, "gh"), `#!${process.execPath}\nprocess.stdout.write(process.env.GH_TOKEN || 'anonymous');`, { mode: 0o700 }); const execute = vi.fn(async (input) => { const startedAt = new Date().toISOString(); @@ -70,7 +71,8 @@ duplex?: { enabled?: boolean; capability: boolean; unavailable?: boolean; startu const bridgeModes: (string | undefined)[] = []; const bridges: NonNullable>>[] = []; const result = await createNativeGitHubAccess({ scope, target, cwd: root, - env: { PATH: `${bin}:${path.dirname(process.execPath)}:/usr/bin:/bin`, PAPERCLIP_API_KEY: "old-run-api-key" }, resolveCredentials, onLog }, + env: { PATH: `${bin}:${path.dirname(process.execPath)}:/usr/bin:/bin`, PAPERCLIP_API_KEY: "old-run-api-key" }, resolveCredentials, onLog, + launcherKey: placement.launcherKey }, bridgeUnavailable ? async () => { throw new Error("fixture bridge unavailable"); } : async input => { if (duplex?.fallbackUnavailable && input.enableSandboxDuplexBridge === false) throw new Error("fixture fallback unavailable"); const bridge = await startAdapterExecutionTargetPaperclipBridge(input); @@ -273,6 +275,103 @@ it.each([false, true])("keeps one live parent and its original launcher environm releaseB(); await b.stop(); await expect(access(b.env.PAPERCLIP_GITHUB_LAUNCHER_DIR)).rejects.toThrow(); }, 45_000); +function liveParent(env: Record) { + const parent = spawn(process.execPath, ["-e", ` + const {execFile}=require('node:child_process'); + require('node:readline').createInterface({input:process.stdin}).on('line', () => { + execFile('gh', [], (error, stdout, stderr) => console.log(JSON.stringify({pid:process.pid, value:stdout, error:error?.message, stderr}))); + }); + `], { env: { ...process.env, ...env }, stdio: ["pipe", "pipe", "pipe"] }); + cleanups.push(async () => { const exited = new Promise(resolve => parent.once("exit", () => resolve())); parent.kill(); await exited; }); + const lines = createInterface({ input: parent.stdout }); + return () => new Promise<{ pid: number; value: string; stderr: string }>(resolve => { + lines.once("line", line => resolve(JSON.parse(line))); parent.stdin.write("run\n"); + }); +} +it("re-arms a live sandbox provider's launchers after its controller restarts", async () => { + const remote = true; + const root = await mkdtemp(path.join(tmpdir(), "native-github-restart-")); + cleanups.push(() => rm(root, { recursive: true, force: true })); + const before = await broker(undefined, remote, false, undefined, undefined, { root, launcherKey: "session-a" }); + const operation = liveParent(before.env); + const releaseBefore = before.activate(run("run-a")); + const first = await operation(); + expect(first.value).toBe("fixture-run-a"); + releaseBefore(); + await before.stop({ preserveLaunchers: true }); + const launchers = before.env.PAPERCLIP_GITHUB_LAUNCHER_DIR; + await access(path.join(launchers, "gh")); + const after = await broker(vi.fn(async (binding: ReturnType) => ({ + status: "available", env: { GH_TOKEN: `adopted-${binding.runId}` }, + })), remote, false, undefined, undefined, { root, launcherKey: "session-a" }); + expect(after.env.PAPERCLIP_GITHUB_LAUNCHER_DIR).toBe(launchers); + expect(after.env.PAPERCLIP_GITHUB_BROKER_TOKEN).not.toBe(before.env.PAPERCLIP_GITHUB_BROKER_TOKEN); + const releaseAfter = after.activate(run("run-a")); + const adopted = await operation(); + expect(adopted).toMatchObject({ pid: first.pid, value: "adopted-run-a", stderr: "" }); + expect(await readFile(path.join(launchers, "gh"), "utf8")).not.toContain(after.env.PAPERCLIP_GITHUB_BROKER_TOKEN); + expect((await stat(path.join(launchers, "broker.json"))).mode & 0o777).toBe(0o600); + releaseAfter(); + await after.stop(); + await expect(access(launchers)).rejects.toThrow(); +}, 45_000); +it("keeps launchers a successor re-armed when a superseded access stops", async () => { + const root = await mkdtemp(path.join(tmpdir(), "native-github-successor-")); + cleanups.push(() => rm(root, { recursive: true, force: true })); + const superseded = await broker(undefined, true, false, undefined, undefined, { root, launcherKey: "session-a" }); + const successor = await broker(vi.fn(async () => ({ status: "available", env: { GH_TOKEN: "successor" } })), + true, false, undefined, undefined, { root, launcherKey: "session-a" }); + const operation = liveParent(superseded.env); + await superseded.stop(); + successor.activate(run("run-b")); + expect(await operation()).toMatchObject({ value: "successor", stderr: "" }); + const other = await broker(undefined, true, false, undefined, undefined, { root, launcherKey: "session-b" }); + expect(other.env.PAPERCLIP_GITHUB_LAUNCHER_DIR).not.toBe(successor.env.PAPERCLIP_GITHUB_LAUNCHER_DIR); +}); +it("keeps a previous-release provider running without managed GitHub after the cutover restart", async () => { + const root = await mkdtemp(path.join(tmpdir(), "native-github-cutover-")); + cleanups.push(() => rm(root, { recursive: true, force: true })); + const previous = await broker(undefined, true, false, undefined, undefined, { root }); + const operation = liveParent(previous.env); + const releasePrevious = previous.activate(run("run-a")); + expect((await operation()).value).toBe("fixture-run-a"); + releasePrevious(); + await previous.stop(); + await expect(access(previous.env.PAPERCLIP_GITHUB_LAUNCHER_DIR)).rejects.toThrow(); + const current = await broker(undefined, true, false, undefined, undefined, { root, launcherKey: "session-a" }); + expect(current.env.PAPERCLIP_GITHUB_LAUNCHER_DIR).not.toBe(previous.env.PAPERCLIP_GITHUB_LAUNCHER_DIR); + current.activate(run("run-a")); + expect(await operation()).toMatchObject({ value: "anonymous", stderr: "" }); + expect(current.resolveCredentials).not.toHaveBeenCalled(); + await expect(liveParent(current.env)()).resolves.toMatchObject({ value: "fixture-run-a" }); +}, 45_000); +it("tells a local provider adopted after a restart that managed GitHub is unavailable", async () => { + const root = await mkdtemp(path.join(tmpdir(), "native-github-local-restart-")); + cleanups.push(() => rm(root, { recursive: true, force: true })); + const before = await broker(undefined, false, false, undefined, undefined, { root, launcherKey: "session-a" }); + const operation = liveParent(before.env); + const releaseBefore = before.activate(run("run-a")); + expect((await operation()).value).toBe("fixture-run-a"); + releaseBefore(); + await before.stop({ preserveLaunchers: true }); + const after = await broker(undefined, false, false, undefined, undefined, { root, launcherKey: "session-a" }); + after.activate(run("run-a")); + const adopted = await operation(); + expect(adopted.value).toBe("anonymous"); + expect(adopted.stderr).toMatch(/^Paperclip: GitHub (broker_transport_unavailable|capability_rejected|broker_response_unavailable); continuing without managed credentials\.\n$/); + expect(after.resolveCredentials).not.toHaveBeenCalled(); +}, 45_000); +it("keeps the broker capability out of local launcher files", async () => { + const b = await broker(undefined, false, false, undefined, undefined, { launcherKey: "session-a" }); + const files = await readdir(b.env.PAPERCLIP_GITHUB_LAUNCHER_DIR, { recursive: true }); + expect(files).not.toContain("broker.json"); + for (const file of files) { + const target = path.join(b.env.PAPERCLIP_GITHUB_LAUNCHER_DIR, file); + if ((await stat(target)).isFile()) expect(await readFile(target, "utf8")).not.toContain(b.env.PAPERCLIP_GITHUB_BROKER_TOKEN); + } + b.activate(run("local")); + expect(await liveParent(b.env)()).toMatchObject({ value: "fixture-local", stderr: "" }); +}); it("rejects other scopes, concurrent bindings, browser requests and forged authority", async () => { const b = await broker(); for (const field of ["companyId", "agentId", "issueId"] as const) { diff --git a/server/src/services/native-runtime/native-github-access.ts b/server/src/services/native-runtime/native-github-access.ts index dccdf8fc7d6..f33d37b9a53 100644 --- a/server/src/services/native-runtime/native-github-access.ts +++ b/server/src/services/native-runtime/native-github-access.ts @@ -1,4 +1,4 @@ -import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto"; +import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto"; import { createServer } from "node:http"; import { cleanupGitHubOperationLaunchers, @@ -15,6 +15,8 @@ type Binding = { companyId: string; agentId: string; issueId: string; runId: str type LauncherInput = Parameters[0]; export type NativeGitHubAccess = Awaited>; +const launcherOwners = new Map(); + /** A process-lifetime transport, with authority only while its controller owns a run. * No run token or GitHub credential is stored in the provider's environment/files. * The resolver still checks the active run and current identity/grants per operation. @@ -26,10 +28,17 @@ export async function createNativeGitHubAccess(input: { env: NodeJS.ProcessEnv; resolveCredentials: (binding: Binding) => Promise; onLog?: (stream: "stdout" | "stderr", chunk: string) => Promise; + launcherKey?: string; }, startBridge = startAdapterExecutionTargetPaperclipBridge) { const duplexRequested = adapterExecutionTargetEnablesSandboxDuplexBridge(input.target); const token = randomBytes(32).toString("hex"); const location = { runId: `native-session-${randomUUID()}`, target: input.target }; + const launcherLocation = input.launcherKey === undefined ? location : { + runId: `native-github-${createHash("sha256").update(input.launcherKey).digest("hex").slice(0, 32)}`, + target: input.target, + }; + const launcherDirectory = githubOperationLauncherDirectory(launcherLocation); + const launcherOwner = Symbol("GitHub launcher owner"); let active: Binding | null = null; let stopped = false; let ready = true; @@ -82,14 +91,17 @@ export async function createNativeGitHubAccess(input: { }); server.requestTimeout = 15_000; server.headersTimeout = 10_000; - const stop = () => stopping ??= (async () => { + const stop = (options: { preserveLaunchers?: boolean } = {}) => stopping ??= (async () => { stopped = true; active = null; server.closeAllConnections(); + const removeLaunchers = !options.preserveLaunchers && launcherOwners.get(launcherDirectory) === launcherOwner; + if (removeLaunchers) launcherOwners.delete(launcherDirectory); const results = await Promise.allSettled([ stopBridge(), new Promise(resolve => server.close(() => resolve())), - cleanupGitHubOperationLaunchers(location), + ...(launcherLocation !== location ? [cleanupGitHubOperationLaunchers(location)] : []), + ...(removeLaunchers ? [cleanupGitHubOperationLaunchers(launcherLocation)] : []), ]); if (results.some(result => result.status === "rejected")) { await input.onLog?.("stderr", "[paperclip] GitHub session cleanup incomplete.\n").catch(() => undefined); @@ -161,15 +173,17 @@ export async function createNativeGitHubAccess(input: { await new Promise(resolve => server.close(() => resolve())); await input.onLog?.("stderr", "[paperclip] GitHub runtime transport unavailable; continuing without managed GitHub access.\n").catch(() => undefined); } + const broker = { + url: ready ? bridge?.env.PAPERCLIP_API_URL ?? url : "", + token: ready ? bridge?.env.PAPERCLIP_API_KEY ?? token : "", + }; + launcherOwners.set(launcherDirectory, launcherOwner); const env = await prepareGitHubOperationLaunchers({ - ...location, cwd: input.cwd, + ...launcherLocation, cwd: input.cwd, ...(input.target?.kind === "remote" ? { broker } : {}), env: { - ...githubBrokerEnvironment({ PATH: input.env.PATH }, { - url: ready ? bridge?.env.PAPERCLIP_API_URL ?? url : "", - token: ready ? bridge?.env.PAPERCLIP_API_KEY ?? token : "", - }), + ...githubBrokerEnvironment({ PATH: input.env.PATH }, broker), // Never retain an old run's bridge authentication override. - PAPERCLIP_GITHUB_BRIDGE_TOKEN: ready ? bridge?.env.PAPERCLIP_API_KEY ?? token : "", + PAPERCLIP_GITHUB_BRIDGE_TOKEN: broker.token, }, }); return { diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index 142e0c6e7e7..13fb4614f48 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -8692,6 +8692,49 @@ describe("native startup restart detachment", () => { } finally { await newerDetach; issueService.mockRestore(); } }); + it("keeps managed GitHub launchers for a provider that outlives its restart detach", async () => { + const root = await mkdtemp(join(tmpdir(), "native-github-detach-")); + const previous = process.env.PAPERCLIP_RUNNER_STATE_DIR; + process.env.PAPERCLIP_RUNNER_STATE_DIR = root; + const restarting = structuredClone(execution); + restarting.binding.runId = "restart-managed-github"; + restarting.session.normalizedSessionId = "restart-managed-github-session"; + let open!: () => void, started!: () => void; + const opening = new Promise(resolve => { open = resolve; }); + const admitted = new Promise(resolve => { started = resolve; }); + const stop = vi.fn(async (_options?: { preserveLaunchers?: boolean }) => undefined); + githubAccess.create.mockImplementationOnce(async () => ({ env: {}, ready: true, duplexRequested: false, + activate: vi.fn(() => vi.fn()), stop })); + state.execute.mockReset().mockImplementationOnce(async (options) => { + started(); + await opening; + await options.onSession({ detachControllerForRestart: async () => undefined }); + await options.onSession(null); + throw new Error("detachment closed the old event stream"); + }); + const outcome = executePaperclipNativeSession({ db: leaseDb(restarting), execution: restarting, + runnerInstanceId: "runner", useRunnerd: true, managedGitHub: true }).catch(error => error); + let detaching: Promise | undefined; + try { + await admitted; + detaching = detachNativeSessionsForRestart([restarting.binding.runId]); + open(); + expect(await detaching).toMatchObject({ detachedRunIds: [restarting.binding.runId] }); + expect(await outcome).toBeInstanceOf(NativeControllerDetachedForRestartError); + expect(githubAccess.create).toHaveBeenLastCalledWith(expect.objectContaining({ + launcherKey: expect.stringContaining(restarting.binding.issueId), + })); + expect(stop).toHaveBeenCalledExactlyOnceWith({ preserveLaunchers: true }); + } finally { + open(); + await outcome; + await detaching; + if (previous === undefined) delete process.env.PAPERCLIP_RUNNER_STATE_DIR; + else process.env.PAPERCLIP_RUNNER_STATE_DIR = previous; + await rm(root, { recursive: true, force: true }); + } + }); + it("uses one admission deadline for the whole restart sweep", async () => { const inputs = ["first", "second"].map(label => { const input = structuredClone(execution); @@ -18483,7 +18526,7 @@ describe("runnerd provider runtime wiring", () => { if (failure === "assigned") { expect(activate).toHaveBeenCalledWith(current.binding); expect(deactivate).toHaveBeenCalledOnce(); - expect(stop).toHaveBeenCalledOnce(); + expect(stop).toHaveBeenCalledExactlyOnceWith({ preserveLaunchers: false }); } } finally { releaseGitHub(); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index c48e91d92e4..c4a80912ee2 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -922,7 +922,7 @@ async function detachReleasedWarmNativeSession(entry: WarmNativeSession) { entry.controllerDetachedForRestart = true; if (!entry.session.detachControllerForRestart) throw new Error("native_session_released_detach_unavailable"); await entry.session.detachControllerForRestart(); - await entry.githubAccess?.stop(); + await entry.githubAccess?.stop({ preserveLaunchers: true }); } const warmNativeSessions = new Map(); @@ -2559,6 +2559,14 @@ function nativeSessionScopeKey(execution: NativeExecutionInput): string { }); } +function nativeGitHubLauncherKey(execution: NativeExecutionInput): string { + return canonicalJson({ + schema: "paperclip.native-github-launcher.v1", + session: nativeSessionScopeKey(execution), + issueId: execution.binding.issueId, + }); +} + // A plan acceptance or explicit reset can rotate the provider/session identity // while retaining the same task sandbox and its fixed ingress port. function nativeSessionOwnerScope( @@ -12456,6 +12464,7 @@ async function executePaperclipNativeSessionAttempt( env: resolveNativeProviderEnvironment(input.execution.provider, input.runnerEnvironment), resolveCredentials: (binding) => resolveGitHubOperationCredentials(input.db, binding), onLog: input.onLog, + launcherKey: nativeGitHubLauncherKey(input.execution), })); executionContext?.assertOpen(); releaseGitHubRun = githubAccess.activate(input.execution.binding); @@ -13878,7 +13887,8 @@ async function executePaperclipNativeSessionAttempt( settlingNativeSessionScopes.set(nativeSessionScopeKey(input.execution), input.execution.binding.runId); releaseGitHubRun?.(); if (githubAccess && (!warmSessionId || warmNativeSessions.get(warmSessionId)?.githubAccess !== githubAccess)) { - await timeController("github_stop", () => githubAccess!.stop()); + const preserveLaunchers = nativeRunsDetachingForRestart.has(input.execution.binding.runId); + await timeController("github_stop", () => githubAccess!.stop({ preserveLaunchers })); } } let postExecutionFailed = false; From fb288f5666ff7b93b81687c140f5c97ce5200a1a Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Mon, 16 Nov 2026 12:14:57 -0800 Subject: [PATCH 06/13] fix(acpx): only treat an error result as a Claude sign-in failure (#21921) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Claude agents run through the Claude ACP bridge (`claude-agent-acp` 0.73.0), which Paperclip patches in `patches/` > - The bridge reads Claude Code's final result for each turn. If the result text contains "Please run /login", the bridge fails the turn as a sign-in failure > - That check does not look at `is_error`. A successful reply that quotes the CLI's sign-in hint also fails the turn > - Agents quote that hint when they report the output of a `claude` command that they ran. The work is done, but the run fails with "ACP agent reported a terminal access failure." > - Upstream fixed this in [agentclientprotocol/claude-agent-acp#1103](https://github.com/agentclientprotocol/claude-agent-acp/pull/1103) (commit [`6e97e07`](https://github.com/agentclientprotocol/claude-agent-acp/commit/6e97e071c581002b43d9556dbd1d1376ebf9516f), released in 0.81.1), "fix: gate login result text on error state" > - This pull request ports that upstream change into the 0.73.0 bridge patch > - The benefit is that a correct, finished run is not reported as a failed sign-in ## Linked Issues or Issue Description Upstream fix: [agentclientprotocol/claude-agent-acp#1103](https://github.com/agentclientprotocol/claude-agent-acp/pull/1103) (commit [`6e97e07`](https://github.com/agentclientprotocol/claude-agent-acp/commit/6e97e071c581002b43d9556dbd1d1376ebf9516f), released in 0.81.1). This pull request ports it. Refs #14089. That pull request fixes the same class of problem in the Claude CLI lane (`execute.ts`). This pull request fixes the ACP lane. Related: #14093 shows the same error text, but it has a different cause. This pull request does not fix #14093. **What happened?** An agent ran a script that calls the `claude` CLI without credentials. The CLI printed "Not logged in · Please run /login". The agent finished its task and quoted that text in its final reply. Claude Code ended the turn with a successful result (`is_error: false`). The bridge saw "Please run /login" in the result text and failed the turn with `auth_required`. Paperclip then failed the run with "ACP agent reported a terminal access failure." **Expected behavior** A successful result completes the turn. Only an error result with the sign-in hint is a sign-in failure. **Steps to reproduce** 1. Run a Claude agent on the ACP lane. 2. Make the model's final reply contain the text "Please run /login" (for example, quote the output of `claude -p hi` without credentials). 3. See that the run fails with "ACP agent reported a terminal access failure." The new test in this pull request does these steps against a local API stand-in. **Agent adapter(s) involved** `claude_local` on the ACP engine, and the Runner's ACPX Claude profile. Both use the same patched bridge. ## What Changed - `patches/@agentclientprotocol__claude-agent-acp@0.73.0.patch`: port [agentclientprotocol/claude-agent-acp#1103](https://github.com/agentclientprotocol/claude-agent-acp/pull/1103) (commit [`6e97e07`](https://github.com/agentclientprotocol/claude-agent-acp/commit/6e97e071c581002b43d9556dbd1d1376ebf9516f), released in 0.81.1). It has two parts, the same as upstream: - The `success` result check is now `message.is_error && message.result.includes("Please run /login")`. A successful result that quotes the sign-in hint no longer fails the turn. - The goal-command check also requires `message.is_error`. A `/goal` command whose successful result quotes the sign-in hint no longer rolls the session goal back. - Both patch comments name the upstream change. All other patch hunks are unchanged. - `packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-login-text.test.ts`: a new test. It runs the real bridge and the bundled Claude Code against a local API stand-in. The model's reply quotes the sign-in hint, and the test expects the turn to complete. ## Verification - Red: on `master`'s patch, the new test fails with `{"status":"failed","error":{"message":"ACP agent reported a terminal access failure."}}`. - Green: with this patch, the new test passes (`status: "completed"`, `stopReason: "end_turn"`). - I ran Claude Code 2.1.286 (the bundled version) with no credentials. Its real sign-in failure is a result with `is_error: true` and the text "Not logged in · Please run /login". The guard still catches it. The separate synthetic sign-in message check is unchanged. - The goal-command part has no new test here. The upstream change adds a test for it. The runner's `session-goals.test.ts` passes with the new patch. - `node --test scripts/acpx-patch-packaging.test.mjs`: 26 passed. - `node --test packages/paperclip-runner/test/acpx-codex-package-contract.test.mjs`: 9 passed. - Runner real-bridge Claude tests (`acpx-runtime-adapter.claude-*.test.ts`, `acpx-runtime-adapter.test.ts`, `claude-scheduling-tools.claude-acp.test.ts`, `runner-tool-bridge.claude-*.test.ts`): 139 passed. - `claude-local` ACP tests (`acp.test.ts`, `acp.auth.test.ts`, `acp.quota.test.ts`): 95 passed. - `pnpm --filter @paperclipai/paperclip-runner run typecheck:typescript`: passed. - I did not commit `pnpm-lock.yaml`. The patch hash changes, and CI resolves the lockfile for this run. ## Risks - Low risk. The change adds one condition to each of two checks in the bridge patch. Both match the upstream change. - The bridge's `commandDigest` does not change, because the patch does not touch `dist/index.js`. Saved sessions are not reset. - A sign-in failure that Claude Code reports as a successful, non-error result is no longer caught by this check. Claude Code 2.1.286 reports sign-in failures as error results, and upstream uses the same rule. ## Model Used Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, subagents) and extended thinking. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- ...-runtime-adapter.claude-login-text.test.ts | 107 ++++++++++++++++++ ...entprotocol__claude-agent-acp@0.73.0.patch | 30 ++++- 2 files changed, 132 insertions(+), 5 deletions(-) create mode 100644 packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-login-text.test.ts diff --git a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-login-text.test.ts b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-login-text.test.ts new file mode 100644 index 00000000000..5ad29ba2763 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.claude-login-text.test.ts @@ -0,0 +1,107 @@ +import { spawn } from "node:child_process"; +import { mkdir, mkdtemp, rm } from "node:fs/promises"; +import { createServer } from "node:http"; +import { createRequire } from "node:module"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import type { AcpRuntimeEvent } from "acpx/runtime"; +import { expect, it, vi } from "vitest"; + +import { openCodexAcpxRuntime } from "./acpx-runtime-adapter.js"; +import type { VerifiedAcpxCommandLease } from "./installation-integrity.js"; +import { resolveQualifiedAcpxProfile } from "./qualified-profiles.js"; +import type { AcpxRuntimePortOpenOptions } from "./runtime-host.js"; + +const QUOTED_LOGIN_TEXT = 'The probe exited 1: "Not logged in · Please run /login". I posted its output.'; + +async function runTurn() { + const root = await mkdtemp(join(tmpdir(), "claude-login-text-")); + const home = join(root, "home"), cwd = join(root, "workspace"), config = join(home, ".claude"); + await Promise.all([mkdir(config, { recursive: true }), mkdir(cwd)]); + let sequence = 0; + const api = createServer(async (request, response) => { + let raw = ""; + for await (const chunk of request) raw += chunk; + if (request.method === "GET") { + response.writeHead(200, { "content-type": "application/json" }); + response.end(JSON.stringify({ data: [], has_more: false })); + return; + } + if (request.url?.includes("count_tokens")) { + response.writeHead(200, { "content-type": "application/json" }); + response.end(JSON.stringify({ input_tokens: 1 })); + return; + } + const body = JSON.parse(raw || "{}") as { model?: string; stream?: boolean }; + const model = body.model ?? "claude-sonnet-5"; + if (body.stream !== true) { + response.writeHead(200, { "content-type": "application/json" }); + response.end(JSON.stringify({ id: "msg_fixture", type: "message", role: "assistant", model, + content: [{ type: "text", text: "OK" }], stop_reason: "end_turn", usage: { input_tokens: 1, output_tokens: 1 } })); + return; + } + const frames: Array> = [ + { type: "message_start", message: { id: `msg_${++sequence}`, type: "message", role: "assistant", model, content: [], + stop_reason: null, stop_sequence: null, usage: { input_tokens: 7, output_tokens: 0 } } }, + { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }, + { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: QUOTED_LOGIN_TEXT } }, + { type: "content_block_stop", index: 0 }, + { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 3 } }, + { type: "message_stop" }, + ]; + response.writeHead(200, { "content-type": "text/event-stream" }); + for (const frame of frames) response.write(`event: ${frame.type}\ndata: ${JSON.stringify(frame)}\n\n`); + response.end(); + }); + await new Promise(resolve => api.listen(0, "127.0.0.1", resolve)); + const address = api.address() as { port: number }; + + const entry = createRequire(import.meta.url).resolve("@agentclientprotocol/claude-agent-acp/dist/index.js"); + const command: VerifiedAcpxCommandLease = { + spawn: (args, input) => spawn(process.execPath, [entry, ...(args ?? [])], { ...input, detached: true, stdio: ["pipe", "pipe", "pipe"] }), + close: async () => undefined, + }; + const options: AcpxRuntimePortOpenOptions = { + command, + profile: resolveQualifiedAcpxProfile("claude", "claude-sonnet-5"), + cwd, + stateDirectory: join(root, "state"), + providerSessionKey: "claude-login-text", + permissionMode: "approve-all", + permissionPolicy: { autoApprove: ["read", "write", "execute", "other"], defaultAction: "approve" }, + launchEnvironment: { HOME: home, CLAUDE_CONFIG_DIR: config, PATH: "/usr/bin:/bin", TMPDIR: root, + ANTHROPIC_API_KEY: "local-fixture-only", ANTHROPIC_BASE_URL: `http://127.0.0.1:${address.port}`, + CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_TELEMETRY: "1", DISABLE_ERROR_REPORTING: "1", ENABLE_TOOL_SEARCH: "false" }, + credentialFenceFds: [42, 43] as const, + activateCredentialFenceOwner: async () => undefined, + systemInstructions: "Report the probe output.", + mcpServers: [], + retainFailedAdmissionCleanup: vi.fn(), + } as AcpxRuntimePortOpenOptions; + let port: Awaited> | undefined; + try { + port = await openCodexAcpxRuntime(options, { + awaitProviderOwnership: async () => undefined, + awaitProviderExit: child => new Promise(resolve => child.once("exit", () => resolve())), + }); + const turn = port.startTurn({ text: "Run the probe and report its output.", requestId: "turn-1", + onPermissionRequest: async () => ({ outcome: "allow_once" }) }); + const events: AcpRuntimeEvent[] = []; + for await (const event of turn.events) events.push(event); + return { result: await turn.result, events }; + } finally { + try { await port?.close({ reason: "sign-in hint verified" }); } + finally { + api.closeAllConnections(); + await new Promise(resolve => api.close(() => resolve())); + await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }); + } + } +} + +it("completes a turn whose successful reply quotes the CLI's sign-in hint through the real ACP stream", async () => { + const { result, events } = await runTurn(); + expect(result).toMatchObject({ status: "completed", stopReason: "end_turn" }); + expect(JSON.stringify(events)).toContain("Please run /login"); +}, 60_000); diff --git a/patches/@agentclientprotocol__claude-agent-acp@0.73.0.patch b/patches/@agentclientprotocol__claude-agent-acp@0.73.0.patch index df6f4c77e00..b7e7589c717 100644 --- a/patches/@agentclientprotocol__claude-agent-acp@0.73.0.patch +++ b/patches/@agentclientprotocol__claude-agent-acp@0.73.0.patch @@ -1,5 +1,5 @@ diff --git a/dist/acp-agent.js b/dist/acp-agent.js -index 0214a50..73f0c16 100644 +index 0214a50..a68121d 100644 --- a/dist/acp-agent.js +++ b/dist/acp-agent.js @@ -2490,11 +2490,88 @@ export class ClaudeAcpAgent { @@ -117,7 +117,18 @@ index 0214a50..73f0c16 100644 await subagents.finishTask(message.task_id, message.patch.status, sendUpdate); session.liveBackgroundTasks.delete(message.task_id); } -@@ -2922,9 +3002,19 @@ export class ClaudeAcpAgent { +@@ -2794,7 +2874,9 @@ export class ClaudeAcpAgent { + session.pendingGoalUpdate = undefined; + const goalCommandFailed = message.is_error || + message.stop_reason === "refusal" || +- ("result" in message && message.result.includes("Please run /login")); ++ ("result" in message && ++ message.is_error && ++ message.result.includes("Please run /login")); + if (goalCommandFailed) { + await this.publishGoal(params.sessionId, pendingGoalUpdate.previous ?? null); + } +@@ -2922,9 +3004,19 @@ export class ClaudeAcpAgent { amount: message.total_cost_usd, currency: "USD", }, @@ -140,7 +151,16 @@ index 0214a50..73f0c16 100644 }, }); } -@@ -4506,6 +4596,48 @@ export class ClaudeAcpAgent { +@@ -3081,7 +3173,7 @@ export class ClaudeAcpAgent { + } + switch (message.subtype) { + case "success": { +- if (message.result.includes("Please run /login")) { ++ if (message.is_error && message.result.includes("Please run /login")) { + await failActiveWithSessionFailure("auth_required", RequestError.authRequired(), message.result); + break; + } +@@ -4506,6 +4598,48 @@ export class ClaudeAcpAgent { * `$/cancel_request`, and our local abort race settles even if the client * ignores it. A `cancelled` outcome, request rejection, and local abort all * surface the same "Tool use aborted" the callers already expect. */ @@ -189,7 +209,7 @@ index 0214a50..73f0c16 100644 async requestPermissionFromClient(params, toolName, signal, parentToolUseId, ownerSessionId = params.sessionId) { if (signal.aborted) throw new Error("Tool use aborted"); -@@ -5311,14 +5443,24 @@ export class ClaudeAcpAgent { +@@ -5311,14 +5445,24 @@ export class ClaudeAcpAgent { settingSources: ["user", "project", "local"], ...(thinking !== undefined && { thinking }), ...userProvidedOptions, @@ -215,7 +235,7 @@ index 0214a50..73f0c16 100644 ...mcpServers, ...(fileChangeAuditSupport ? { [FILE_CHANGE_AUDIT_SERVER_NAME]: fileChangeAuditSupport.mcpServer } -@@ -5329,6 +5471,16 @@ export class ClaudeAcpAgent { +@@ -5329,6 +5473,16 @@ export class ClaudeAcpAgent { allowDangerouslySkipPermissions: ALLOW_BYPASS, permissionMode: initialPermissionMode, canUseTool: this.canUseTool(sessionId), From b816c95f96e22dfbf68704ed4eabb75a0725d56c Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:15:43 +0000 Subject: [PATCH 07/13] chore(lockfile): refresh pnpm lockfiles (#21936) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip uses a dependency lock for reproducible builds. > - Dependency changes on master need matching lock entries. > - Paid eval reports also pin a reviewed offline correction. > - Reports must install before paid model work starts. > - This automated PR keeps the lock and report proof together. ## Linked Issues or Issue Description **What happened?** Dependency manifests on master changed after the last committed lock refresh. **Expected behavior** Frozen installs must match those manifests. Eval reports must retain matching offline lock proof. **Steps to reproduce** Run a frozen install before and after this lock refresh. ## What Changed - Refresh the dependency lock from the manifests on master. - Refresh the sandbox provider lockfiles from their manifests on master. - Include the matching offline report correction and hashes. - Resync the SDK public source proof's lock pins from the refreshed lock. ## Verification - Pinned pnpm resolution completed with lifecycle scripts disabled. - The report proof refresh accepted the reviewed committed baseline. - The workflow rejected changes outside the lock and report proof files. ## Risks The lockfile bot merges this PR without CI or review when every added package version is at least 3 days old on npm. Otherwise the PR waits for a maintainer, and the daily refresh tries again. The bot merges only the exact commit this workflow generated from manifests already reviewed on master. Unknown report lock baselines remain blocked. This update changes no permissions or paid enable gates. ## Model Used None — generated by pnpm and the deterministic report-lock updater. ## Checklist - [x] Thinking path and problem description included - [x] Generated lock and matching report proof included - [x] Release-age gate decides between bot merge and maintainer review Co-authored-by: lockfile-bot --- pnpm-lock.yaml | 10 +- tests/runner-e2e/report-lock.json | 6 +- tests/runner-e2e/report-lock.patch | 178 +++++------------- .../runner-e2e/source-sdk-public-inputs.json | 4 +- 4 files changed, 52 insertions(+), 146 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 05644099489..c533906b86f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -16,7 +16,7 @@ overrides: patchedDependencies: '@agentclientprotocol/claude-agent-acp@0.73.0': - hash: syoits7l7g3sthy3olttp2fv24 + hash: wnht4big7mwol7j2skbsa5mefq path: patches/@agentclientprotocol__claude-agent-acp@0.73.0.patch '@agentclientprotocol/codex-acp@1.6.2': hash: 2iynuypg76nxmydiylgtffhr7e @@ -186,7 +186,7 @@ importers: dependencies: '@agentclientprotocol/claude-agent-acp': specifier: ^0.73.0 - version: 0.73.0(patch_hash=syoits7l7g3sthy3olttp2fv24)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) + version: 0.73.0(patch_hash=wnht4big7mwol7j2skbsa5mefq)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) '@anthropic-ai/sdk': specifier: 0.129.0 version: 0.129.0(zod@4.6.7) @@ -511,7 +511,7 @@ importers: dependencies: '@agentclientprotocol/claude-agent-acp': specifier: 0.73.0 - version: 0.73.0(patch_hash=syoits7l7g3sthy3olttp2fv24)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) + version: 0.73.0(patch_hash=wnht4big7mwol7j2skbsa5mefq)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) '@agentclientprotocol/codex-acp': specifier: 1.6.2 version: 1.6.2(patch_hash=2iynuypg76nxmydiylgtffhr7e) @@ -904,7 +904,7 @@ importers: version: 0.5.0 '@agentclientprotocol/claude-agent-acp': specifier: 0.73.0 - version: 0.73.0(patch_hash=syoits7l7g3sthy3olttp2fv24)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) + version: 0.73.0(patch_hash=wnht4big7mwol7j2skbsa5mefq)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) '@agentclientprotocol/codex-acp': specifier: 1.6.2 version: 1.6.2(patch_hash=2iynuypg76nxmydiylgtffhr7e) @@ -9548,7 +9548,7 @@ snapshots: '@adobe/css-tools@4.5.0': {} - '@agentclientprotocol/claude-agent-acp@0.73.0(patch_hash=syoits7l7g3sthy3olttp2fv24)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))': + '@agentclientprotocol/claude-agent-acp@0.73.0(patch_hash=wnht4big7mwol7j2skbsa5mefq)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))': dependencies: '@agentclientprotocol/sdk': 1.4.0(zod@4.4.3) '@anthropic-ai/claude-agent-sdk': 0.3.286(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))(zod@4.4.3) diff --git a/tests/runner-e2e/report-lock.json b/tests/runner-e2e/report-lock.json index 33962ba7299..cda5ff85976 100644 --- a/tests/runner-e2e/report-lock.json +++ b/tests/runner-e2e/report-lock.json @@ -1,6 +1,6 @@ { - "inputSha256": "a56b6acc8743f6163d4af60b072d66c694c1061f4242f499c361d85fce318f3a", - "outputSha256": "a09e9ae44a5f4244431837b158607621b6fa276148bec3078aae2d2e5f2443f9", - "patchSha256": "325e0a90b5cb215a361ab3c3d59935161367b09b59f361080fa292a96566c95a", + "inputSha256": "a09e9ae44a5f4244431837b158607621b6fa276148bec3078aae2d2e5f2443f9", + "outputSha256": "163e7562adefa9924ee96d8b8aa45fa45e7ebe16297315c5b51040803773b9e1", + "patchSha256": "704ba0b17db951602e8aad0eabd73d2be4d788442ffbcb8fc3fd862ac64e23ac", "basis": "Generated with the trusted master lockfile refresh. Review this offline correction and its hashes with the dependency changes." } diff --git a/tests/runner-e2e/report-lock.patch b/tests/runner-e2e/report-lock.patch index 98e9fc14c63..14c35b26200 100644 --- a/tests/runner-e2e/report-lock.patch +++ b/tests/runner-e2e/report-lock.patch @@ -1,143 +1,49 @@ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml -index 48c18aed..05644099 100644 +index 05644099..c533906b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml -@@ -46,7 +46,7 @@ patchedDependencies: - hash: 55uhvnotpqyiy37rn3pqpukhei - path: patches/embedded-postgres@18.1.0-beta.16.patch - postgres@3.4.9: -- hash: eq2va53hqrnbmnygljtudtaoge -+ hash: 7s673zkrux4f7d7y4kyzk7opyu - path: patches/postgres@3.4.9.patch +@@ -16,7 +16,7 @@ overrides: - importers: -@@ -139,7 +139,7 @@ importers: - version: 17.4.2 - drizzle-orm: - specifier: 0.45.2 -- version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)) -+ version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)) - embedded-postgres: - specifier: ^18.1.0-beta.16 - version: 18.1.0-beta.16(patch_hash=55uhvnotpqyiy37rn3pqpukhei) -@@ -411,13 +411,13 @@ importers: - version: link:../shared - drizzle-orm: - specifier: ^0.45.2 -- version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)) -+ version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)) - embedded-postgres: - specifier: ^18.1.0-beta.16 - version: 18.1.0-beta.16(patch_hash=55uhvnotpqyiy37rn3pqpukhei) - postgres: - specifier: ^3.4.9 -- version: 3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge) -+ version: 3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu) - devDependencies: - '@types/node': - specifier: ^24.0.0 -@@ -1018,7 +1018,7 @@ importers: - version: 2.2.0(@grpc/grpc-js@1.14.5)(nice-grpc-common@2.0.4)(nice-grpc@2.1.17) - '@vercel/connect': - specifier: 2.3.3 -- version: 2.3.3(@chat-adapter/slack@4.39.0(patch_hash=eskb5kxp7eud5v3ostluhynfoa)(ai@7.0.130(zod@4.6.7))(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))(ai@7.0.130(zod@4.6.7))(better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)))) -+ version: 2.3.3(@chat-adapter/slack@4.39.0(patch_hash=eskb5kxp7eud5v3ostluhynfoa)(ai@7.0.130(zod@4.6.7))(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))(ai@7.0.130(zod@4.6.7))(better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)))) - acorn: - specifier: 8.18.0 - version: 8.18.0 -@@ -1036,7 +1036,7 @@ importers: - version: 3.0.1(ajv@8.20.0) - better-auth: - specifier: 1.7.16 -- version: 1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))) -+ version: 1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))) - chat: - specifier: 4.39.0 - version: 4.39.0(ai@7.0.130(zod@4.6.7))(zod@4.6.7) -@@ -1057,7 +1057,7 @@ importers: - version: 17.4.2 - drizzle-orm: - specifier: ^0.45.2 -- version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)) -+ version: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)) - embedded-postgres: - specifier: ^18.1.0-beta.16 - version: 18.1.0-beta.16(patch_hash=55uhvnotpqyiy37rn3pqpukhei) -@@ -10089,12 +10089,12 @@ snapshots: - optionalDependencies: - '@opentelemetry/api': 1.9.1 - -- '@better-auth/drizzle-adapter@1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))': -+ '@better-auth/drizzle-adapter@1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))': + patchedDependencies: + '@agentclientprotocol/claude-agent-acp@0.73.0': +- hash: syoits7l7g3sthy3olttp2fv24 ++ hash: wnht4big7mwol7j2skbsa5mefq + path: patches/@agentclientprotocol__claude-agent-acp@0.73.0.patch + '@agentclientprotocol/codex-acp@1.6.2': + hash: 2iynuypg76nxmydiylgtffhr7e +@@ -186,7 +186,7 @@ importers: dependencies: - '@better-auth/core': 1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3) - '@better-auth/utils': 0.5.1 - optionalDependencies: -- drizzle-orm: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)) -+ drizzle-orm: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)) - - '@better-auth/kysely-adapter@1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(kysely@0.29.5)': + '@agentclientprotocol/claude-agent-acp': + specifier: ^0.73.0 +- version: 0.73.0(patch_hash=syoits7l7g3sthy3olttp2fv24)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) ++ version: 0.73.0(patch_hash=wnht4big7mwol7j2skbsa5mefq)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) + '@anthropic-ai/sdk': + specifier: 0.129.0 + version: 0.129.0(zod@4.6.7) +@@ -511,7 +511,7 @@ importers: dependencies: -@@ -14013,14 +14013,14 @@ snapshots: + '@agentclientprotocol/claude-agent-acp': + specifier: 0.73.0 +- version: 0.73.0(patch_hash=syoits7l7g3sthy3olttp2fv24)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) ++ version: 0.73.0(patch_hash=wnht4big7mwol7j2skbsa5mefq)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) + '@agentclientprotocol/codex-acp': + specifier: 1.6.2 + version: 1.6.2(patch_hash=2iynuypg76nxmydiylgtffhr7e) +@@ -904,7 +904,7 @@ importers: + version: 0.5.0 + '@agentclientprotocol/claude-agent-acp': + specifier: 0.73.0 +- version: 0.73.0(patch_hash=syoits7l7g3sthy3olttp2fv24)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) ++ version: 0.73.0(patch_hash=wnht4big7mwol7j2skbsa5mefq)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7)) + '@agentclientprotocol/codex-acp': + specifier: 1.6.2 + version: 1.6.2(patch_hash=2iynuypg76nxmydiylgtffhr7e) +@@ -9548,7 +9548,7 @@ snapshots: + + '@adobe/css-tools@4.5.0': {} + +- '@agentclientprotocol/claude-agent-acp@0.73.0(patch_hash=syoits7l7g3sthy3olttp2fv24)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))': ++ '@agentclientprotocol/claude-agent-acp@0.73.0(patch_hash=wnht4big7mwol7j2skbsa5mefq)(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))': dependencies: - execa: 5.1.1 - -- '@vercel/connect@2.3.3(@chat-adapter/slack@4.39.0(patch_hash=eskb5kxp7eud5v3ostluhynfoa)(ai@7.0.130(zod@4.6.7))(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))(ai@7.0.130(zod@4.6.7))(better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))))': -+ '@vercel/connect@2.3.3(@chat-adapter/slack@4.39.0(patch_hash=eskb5kxp7eud5v3ostluhynfoa)(ai@7.0.130(zod@4.6.7))(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))(ai@7.0.130(zod@4.6.7))(better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))))': - dependencies: - '@vercel/oidc': 3.8.9 - optionalDependencies: - '@chat-adapter/slack': 4.39.0(patch_hash=eskb5kxp7eud5v3ostluhynfoa)(ai@7.0.130(zod@4.6.7))(zod@4.6.7) - '@modelcontextprotocol/sdk': 1.31.0(zod@4.6.7) - ai: 7.0.130(zod@4.6.7) -- better-auth: 1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))) -+ better-auth: 1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))) - - '@vercel/oidc@3.2.0': {} - -@@ -14279,10 +14279,10 @@ snapshots: - - before-after-hook@4.0.0: {} - -- better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))): -+ better-auth@1.7.16(@opentelemetry/api@1.9.1)(drizzle-kit@0.31.11)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)))(pg@8.18.0)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(vitest@5.0.3(@opentelemetry/api@1.9.1)(@types/node@24.13.3)(jsdom@30.0.1(@noble/hashes@2.4.0))(vite@8.2.2(@types/node@24.13.3)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))): - dependencies: - '@better-auth/core': 1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3) -- '@better-auth/drizzle-adapter': 1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge))) -+ '@better-auth/drizzle-adapter': 1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu))) - '@better-auth/kysely-adapter': 1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1)(kysely@0.29.5) - '@better-auth/memory-adapter': 1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1) - '@better-auth/mongo-adapter': 1.7.16(@better-auth/core@1.7.16(@better-auth/utils@0.5.1)(@better-fetch/fetch@1.3.3)(@opentelemetry/api@1.9.1)(better-call@1.4.5(zod@4.6.7))(jose@6.2.12)(kysely@0.29.5)(nanostores@1.5.3))(@better-auth/utils@0.5.1) -@@ -14300,7 +14300,7 @@ snapshots: - zod: 4.6.7 - optionalDependencies: - drizzle-kit: 0.31.11 -- drizzle-orm: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)) -+ drizzle-orm: 0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)) - pg: 8.18.0 - react: 19.2.8 - react-dom: 19.2.8(react@19.2.8) -@@ -14895,12 +14895,12 @@ snapshots: - esbuild: 0.25.12 - tsx: 4.23.15 - -- drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge)): -+ drizzle-orm@0.45.2(@opentelemetry/api@1.9.1)(kysely@0.29.5)(pg@8.18.0)(postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu)): - optionalDependencies: - '@opentelemetry/api': 1.9.1 - kysely: 0.29.5 - pg: 8.18.0 -- postgres: 3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge) -+ postgres: 3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu) - - dunder-proto@1.0.1: - dependencies: -@@ -16813,7 +16813,7 @@ snapshots: - dependencies: - xtend: 4.0.2 - -- postgres@3.4.9(patch_hash=eq2va53hqrnbmnygljtudtaoge): {} -+ postgres@3.4.9(patch_hash=7s673zkrux4f7d7y4kyzk7opyu): {} - - powershell-utils@0.1.0: {} - + '@agentclientprotocol/sdk': 1.4.0(zod@4.4.3) + '@anthropic-ai/claude-agent-sdk': 0.3.286(@anthropic-ai/sdk@0.129.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.31.0(zod@4.6.7))(zod@4.4.3) diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index a34d5f70074..e738504dd06 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -541,12 +541,12 @@ "packages/shared/src/worktree-seed-source.test.ts": "852856b1b5b8f4d0d3dada6501886fe50a2c2dde", "packages/shared/src/worktree-seed-source.ts": "3d1a09bed2d969feabef3400ff84fd499c1408f4", "packages/shared/tsconfig.json": "5a24989cd30dcf3749ca7e60d4e83d6ddbb14714", - "pnpm-lock.yaml": "05644099489b569367f982b14bb412439ba1b207", + "pnpm-lock.yaml": "c533906b86fb101285c5dd2d5b269ec17008a796", "scripts/ensure-plugin-build-deps.mjs": "356e0e0f80e50890067027da3003485cf5d2ccbe", "tsconfig.base.json": "2d0e41f723add0c678936eb9ae1c60eab710f8e0", "tsconfig.json": "994ee490fb97be7cc0954f4dfd88cf0723290e6c" }, - "lockSha256": "a09e9ae44a5f4244431837b158607621b6fa276148bec3078aae2d2e5f2443f9", + "lockSha256": "163e7562adefa9924ee96d8b8aa45fa45e7ebe16297315c5b51040803773b9e1", "compilerPackageSha256": "3722b30210616a13a3213ded11575ba6b2dbab10c32a5ef67afca8513e27017e", "parserPackageSha256": "6d6a65b879cd7cd249a4367c0b57cce00e78c728de45056ac2a5ca1d1f528d1a", "parserEntrySha256": "6969920ae0610df927b6b3e675d1309372c268e36d391652af8e3e0183cbe8f8", From 0e8447fe77d197fa083adeb6835232670bf9ec63 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:24:40 -0600 Subject: [PATCH 08/13] fix(release): retry the finalize install while a large tarball lags its npm metadata (#21925) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Since #21917, each canary's npm confirmation, git tag, Docker build and onboarding smoke run in `canary-finalize.yml` > - The first canary through it, `2026.1116.0-canary.814700`, passed the master-position, visibility, provenance (31 of 31) and dist-tag checks > - It then failed the clean-prefix install: the 524 MB `@paperclipai/server` tarball returned 404 while npm already listed the version > - Without a tag, nightly cannot select that canary, and no Docker image or smoke runs for it > - This pull request retries that install for a bounded time > - The benefit is that a large tarball's normal lag no longer stops a canary from finishing ## Linked Issues or Issue Description **What happened?** Canary finalize run 43927092510 for `2026.1116.0-canary.814700`: `npm error 404 Not Found - GET https://registry.npmjs.org/@paperclipai/server/-/server-2026.1116.0-canary.814700.tgz`. npm's packument records that version at 18:31:41Z. The install ran at 18:32:03Z, and the tarball still returned 404 at 18:34:39 and 18:35:15. `@paperclipai/shared` and `paperclipai` tarballs at the same version returned 200. **Expected behavior** Finalize waits, within a bound, until the published tarball downloads, then tags the canary. Refs #21917 ## What Changed - `scripts/release-lib.sh`: `wait_for_npm_installable` retries `verify_npm_installable` up to N attempts with a fixed delay. - `scripts/confirm-canary-publication.sh`: uses it with 40 attempts × 30 s (`NPM_INSTALL_VERIFY_ATTEMPTS`, `NPM_INSTALL_VERIFY_DELAY_SECONDS`). - `.github/workflows/canary-finalize.yml`: `confirm_canary` timeout 45 → 75 min, to fit the existing 30-minute visibility budget plus the 20-minute install budget. - Test and `doc/RELEASING.md`. ## Verification - `node --test scripts/release-lib.test.mjs`: 23 of 23 pass, including a new test: immediate success, recovery after 3 failures (4 attempts, warning names attempt 3/5), and failure after the bound (4 of 4 attempts). - `node --test scripts/__tests__/release-verify-workflow.test.mjs`: 73 of 73 pass. - After merge: the next canary's finalize run passes the install and pushes its tag. `canary.814700` itself is recovered by rerunning its finalize run once its tarball downloads. ## Risks - Low. A tarball that never appears still fails finalize, after 20 minutes instead of at once. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .github/workflows/canary-finalize.yml | 2 +- .github/workflows/release.yml | 6 +-- doc/RELEASING.md | 2 +- scripts/confirm-canary-publication.sh | 3 +- scripts/release-lib.sh | 31 +++++++++++++- scripts/release-lib.test.mjs | 61 ++++++++++++++++++++++++--- scripts/release.sh | 2 +- 7 files changed, 94 insertions(+), 13 deletions(-) diff --git a/.github/workflows/canary-finalize.yml b/.github/workflows/canary-finalize.yml index 5950c076d2f..cc0b56a0142 100644 --- a/.github/workflows/canary-finalize.yml +++ b/.github/workflows/canary-finalize.yml @@ -32,7 +32,7 @@ jobs: name: Confirm canary on npm and tag it if: github.repository == 'paperclipai/paperclip' && github.repository_id == '1170821064' && github.ref == 'refs/heads/master' runs-on: ubuntu-latest - timeout-minutes: 45 + timeout-minutes: 75 permissions: contents: write actions: write diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 744eea46d2a..92c8aff2ece 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -638,7 +638,7 @@ jobs: (needs.smoke_nightly.result == 'success' || (needs.smoke_nightly.result == 'skipped' && github.event_name == 'workflow_dispatch' && inputs.dry_run)) runs-on: ubuntu-latest - timeout-minutes: 150 + timeout-minutes: 170 environment: npm-canary # The workflow-level concurrency group is per event, so a forced dispatch # nightly could otherwise overlap the scheduled one and race it to the @@ -927,7 +927,7 @@ jobs: (needs.verify_beta_candidate.result == 'success' || (needs.verify_beta_candidate.result == 'skipped' && needs.select_beta.outputs.mode == 'promote')) runs-on: ubuntu-latest - timeout-minutes: 150 + timeout-minutes: 170 environment: npm-beta # Serialize beta publishes so two dispatches cannot race to the same next # -beta.N version; release.sh additionally refuses to double-publish a @@ -1392,7 +1392,7 @@ jobs: if: ${{ !cancelled() && github.event_name == 'workflow_dispatch' && inputs.channel == 'stable' && !inputs.dry_run && needs.preflight_stable.result == 'success' && needs.verify_stable.result == 'success' && needs.release_runner_source.result == 'success' && (needs.release_runner_source.outputs.required == 'false' || needs.release_runner_binaries.result == 'success') }} needs: [preflight_stable, verify_stable, release_runner_source, release_runner_binaries] runs-on: ubuntu-latest - timeout-minutes: 150 + timeout-minutes: 170 environment: npm-stable permissions: contents: write diff --git a/doc/RELEASING.md b/doc/RELEASING.md index bd0317195ca..ea58a4d96e7 100644 --- a/doc/RELEASING.md +++ b/doc/RELEASING.md @@ -109,7 +109,7 @@ Every push to `master` runs the canary path inside [`.github/workflows/release.y - requires the source commit to be on master and the canary number to come from it (`N / 100` equals the commit's master position), so a dispatch with invented inputs cannot tag another commit - checks npm provenance ([`scripts/verify-canary-provenance.mjs`](../scripts/verify-canary-provenance.mjs)): any package whose provenance names something other than `.github/workflows/release.yml` on `refs/heads/master` at the source commit fails the check. A package with no provenance is accepted, because that is the supported retry after a duplicate transparency-log entry, only the trusted release workflow can publish, and the number check above already ties the version to the commit. Brief npm errors are retried. - verifies that `canary` resolves to this version or a newer canary, and that published internal dependencies exist on npm -- installs the exact `paperclipai@` into a clean temporary prefix +- installs the exact `paperclipai@` into a clean temporary prefix, retrying every 30 s within a 20-minute deadline that also stops a stuck install (`NPM_INSTALL_VERIFY_TIMEOUT_SECONDS`, `NPM_INSTALL_VERIFY_DELAY_SECONDS`; nightly, beta and stable use the same retry for their `paperclipai@` install): npm can expose a large package's metadata minutes before its tarball downloads (on 2026-11-16 `@paperclipai/server`, about 524 MB unpacked, still returned 404 several minutes after its recorded publish time) - fails by default if npm leaves `latest` pointing at a canary; use `--allow-canary-latest` only when that state is intentional - creates and pushes the git tag `canary/vYYYY.MDD.P-canary.N` (a tag that already points at the same commit is accepted, so a rerun is safe). Nightly still selects only tagged canaries. - dispatches `docker.yml` at the tag diff --git a/scripts/confirm-canary-publication.sh b/scripts/confirm-canary-publication.sh index 47ace380829..9ab2d6ecc1f 100755 --- a/scripts/confirm-canary-publication.sh +++ b/scripts/confirm-canary-publication.sh @@ -60,6 +60,7 @@ else fi release_info "==> Installing paperclipai@${version} into a clean prefix..." -verify_npm_installable "paperclipai@${version}" "$version" || release_fail "paperclipai@${version} did not install cleanly" +wait_for_npm_installable "paperclipai@${version}" "$version" "${NPM_INSTALL_VERIFY_TIMEOUT_SECONDS:-1200}" "${NPM_INSTALL_VERIFY_DELAY_SECONDS:-30}" \ + || release_fail "paperclipai@${version} did not install cleanly" push_release_tag_at "$PUBLISH_REMOTE" "$tag_name" "$source_sha" diff --git a/scripts/release-lib.sh b/scripts/release-lib.sh index 798e34ba586..f2db11d0973 100644 --- a/scripts/release-lib.sh +++ b/scripts/release-lib.sh @@ -572,12 +572,18 @@ wait_for_npm_package_versions() { verify_npm_installable() { local package_spec="$1" local expected_version="$2" + local install_timeout_seconds="${3:-}" local install_dir local installed_version + local install=(npm install --prefix "" "$package_spec" --no-audit --no-fund) install_dir="$(mktemp -d "${TMPDIR:-/tmp}/paperclip-release-install.XXXXXX")" + install[3]="$install_dir" + if [ -n "$install_timeout_seconds" ] && command -v timeout >/dev/null 2>&1; then + install=(timeout --kill-after=10 "$install_timeout_seconds" "${install[@]}") + fi - if ! npm install --prefix "$install_dir" "$package_spec" --no-audit --no-fund; then + if ! "${install[@]}"; then rm -rf "$install_dir" return 1 fi @@ -588,6 +594,29 @@ verify_npm_installable() { [ "$installed_version" = "$expected_version" ] } +wait_for_npm_installable() { + local package_spec="$1" + local expected_version="$2" + local deadline_seconds="${3:-1200}" + local delay_seconds="${4:-30}" + local deadline=$(( $(date +%s) + deadline_seconds )) + local attempt=1 + local remaining + + while :; do + remaining=$(( deadline - $(date +%s) )) + [ "$remaining" -gt 0 ] || return 1 + if verify_npm_installable "$package_spec" "$expected_version" "$remaining"; then + return 0 + fi + remaining=$(( deadline - $(date +%s) )) + [ "$remaining" -gt 0 ] || return 1 + release_warn "${package_spec} did not install yet (attempt ${attempt}, ${remaining}s left); a large tarball can lag its metadata. Retrying in $(( delay_seconds < remaining ? delay_seconds : remaining ))s." + sleep $(( delay_seconds < remaining ? delay_seconds : remaining )) + attempt=$((attempt + 1)) + done +} + wait_for_release_registry_state() { local attempts="${1:-12}" local delay_seconds="${2:-5}" diff --git a/scripts/release-lib.test.mjs b/scripts/release-lib.test.mjs index c890ffee0ac..3e78f3e8826 100644 --- a/scripts/release-lib.test.mjs +++ b/scripts/release-lib.test.mjs @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { execFileSync } from "node:child_process"; +import { execFileSync, spawnSync } from "node:child_process"; import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -395,15 +395,22 @@ test("the workflow budget fails closed after the last registry check", () => { assert.equal(result.calls.match(/^sleep /gm)?.length, budget.verifyAttempts - 1); }); -test("every publish job budgets for build time and four delayed packages", () => { +test("every publish job budgets for build time, four delayed packages and the install deadline", () => { const { verifyAttempts, verifyDelaySeconds } = workflowVerifyBudget(); const pollingSeconds = (verifyAttempts - 1) * verifyDelaySeconds; - const requiredSeconds = 30 * 60 + 4 * pollingSeconds; + const releaseScript = readFileSync(new URL("./release.sh", import.meta.url), "utf8"); + const installDeadlineSeconds = Number(releaseScript.match(/NPM_INSTALL_VERIFY_TIMEOUT_SECONDS:-(\d+)/)?.[1]); + assert.ok(installDeadlineSeconds > 0); - for (const job of ["publish_canary", "publish_nightly", "publish_beta", "publish_stable"]) { + for (const [job, requiredSeconds] of [ + ["publish_canary", 30 * 60 + 4 * pollingSeconds], + ["publish_nightly", 30 * 60 + 4 * pollingSeconds + installDeadlineSeconds], + ["publish_beta", 30 * 60 + 4 * pollingSeconds + installDeadlineSeconds], + ["publish_stable", 30 * 60 + 4 * pollingSeconds + installDeadlineSeconds], + ]) { const body = releaseWorkflow.split(`\n ${job}:\n`)[1]?.split(/\n [a-z_]+:\n/)[0] ?? ""; const timeoutMinutes = Number(body.match(/^ timeout-minutes: (\d+)$/m)?.[1]); - assert.ok(timeoutMinutes * 60 > requiredSeconds, `${job} must leave time beyond build and polling`); + assert.ok(timeoutMinutes * 60 > requiredSeconds, `${job} must leave time beyond build, polling and the install deadline`); } }); @@ -497,3 +504,47 @@ test("a canary version is accepted only for the master commit whose position num const side = fixture.git(fixture.repo, "rev-parse", "HEAD").trim(); assert.throws(() => confirm("2026.1116.0-canary.2600", side), /is not on origin\/master/); }); + +function installRetryFixture({ failures = 0, hangSeconds = 0 }) { + const dir = mkdtempSync(join(tmpdir(), "paperclip-install-retry-")); + const bin = join(dir, "bin"); + mkdirSync(bin); + const counter = join(dir, "attempts"); + writeFileSync(counter, "0"); + writeExecutable(join(bin, "npm"), `#!/usr/bin/env bash +n=$(( $(cat "${counter}") + 1 )); echo "$n" > "${counter}" +if [ "${hangSeconds}" -gt 0 ]; then sleep "${hangSeconds}"; fi +if [ "$n" -le "${failures}" ]; then echo "npm error code E404" >&2; exit 1; fi +prefix="$3"; mkdir -p "$prefix/node_modules/paperclipai" +printf '{"version":"1.2.3"}' > "$prefix/node_modules/paperclipai/package.json" +`); + const run = (deadline, delay = 0) => { + const started = Date.now(); + const result = spawnSync("bash", ["-c", `source "${repoRoot}/scripts/release-lib.sh"; wait_for_npm_installable paperclipai@canary 1.2.3 ${deadline} ${delay}`], + { encoding: "utf8", env: { ...process.env, PATH: `${bin}:${process.env.PATH}` } }); + return { status: result.status, seconds: (Date.now() - started) / 1000, attempts: Number(readFileSync(counter, "utf8")), stderr: result.stderr }; + }; + return { run }; +} + +test("a release install is retried while its tarball lags the metadata", () => { + const recovered = installRetryFixture({ failures: 3 }).run(60); + assert.equal(recovered.status, 0); + assert.equal(recovered.attempts, 4); + assert.match(recovered.stderr, /attempt 3, \d+s left/); + assert.equal(installRetryFixture({}).run(60).attempts, 1); +}); + +const hasTimeoutCommand = spawnSync("bash", ["-c", "command -v timeout"], { encoding: "utf8" }).status === 0; + +test("install retries stop at the deadline", () => { + const exhausted = installRetryFixture({ failures: 1000 }).run(3, 1); + assert.notEqual(exhausted.status, 0); + assert.ok(exhausted.seconds < 8, `took ${exhausted.seconds}s`); +}); + +test("an install that hangs is stopped at the deadline", { skip: !hasTimeoutCommand && "needs the timeout command (GNU coreutils)" }, () => { + const hung = installRetryFixture({ hangSeconds: 120 }).run(3, 1); + assert.notEqual(hung.status, 0); + assert.ok(hung.seconds < 20, `a hung install outlived the deadline: ${hung.seconds}s`); +}); diff --git a/scripts/release.sh b/scripts/release.sh index 79b276844d8..6b7e71d8f87 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -485,7 +485,7 @@ else fi release_info " Installing paperclipai@$DIST_TAG into a clean prefix..." - if ! verify_npm_installable "paperclipai@$DIST_TAG" "$TARGET_PUBLISH_VERSION"; then + if ! wait_for_npm_installable "paperclipai@$DIST_TAG" "$TARGET_PUBLISH_VERSION" "${NPM_INSTALL_VERIFY_TIMEOUT_SECONDS:-1200}" "${NPM_INSTALL_VERIFY_DELAY_SECONDS:-30}"; then release_fail "paperclipai@$DIST_TAG did not install cleanly at expected version ${TARGET_PUBLISH_VERSION}" fi release_info " ✓ Clean-prefix install resolved ${TARGET_PUBLISH_VERSION}" From f33c4cf6f7f74ac0def2ea088ac1f4dd0a1da533 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:33:39 -0600 Subject: [PATCH 09/13] feat(links): cache rich link status in the database and load it on idle (#21746) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Task text contains links to pull requests and other work. > - A link has useful status that should be visible when a task opens. > - The current cache lives in the server process and the browser. > - A new browser or server restart has no stored status to show. > - This pull request stores link status in the database and reads it in batches. > - Idle page work updates stale status without a hover or a delay to task data. ## Linked Issues or Issue Description **Problem or motivation** PR status is unknown in a new browser until the user points to each link. The process cache cannot supply saved status after a server restart. Related work: #20593 and #20654. A search found no other PR for database link caching. **Proposed solution** Store status by company, viewer and canonical resource URL. Read saved status in one indexed batch query. After document load and core request settlement, use browser idle time to update missing or stale status. Use the same query for hover and idle work. **Alternatives considered** Adding provider calls to task reads would delay task loading. Company-wide reuse of personal GitHub results would cross viewer access boundaries. A periodic server worker would create work when no page needs the result. **Roadmap alignment** This extends the shipped rich-link feature. It does not duplicate a roadmap project or add a new provider integration. ## What Changed - Add an additive, repeat-safe `link_previews` migration. Store channel, resource kind, free-form status, JSON metadata and freshness. The table has no task relationship or GitHub status enum. - Bound each company/viewer cache to 1,000 rows across concurrent server instances. Remove rows expired for over 30 days during writes. Limit provider lookups to 600 requests per minute per scope/process. Keep cached batch reads available during backoff. - Add a database store owned by the link service. Reuse canonical results across tasks. Keep company and viewer isolation. Save hover and idle results. Preserve last known status during an outage and cache unavailable results. - Add a board-only batch GET endpoint, including viewer-role access. It reads at most 50 URLs with one indexed select and makes no provider calls. Both endpoints use private, no-store HTTP responses. - Add a page coordinator for mounted rich links. Reuse browser data, share pending reads, and defer provider work until document load, core request settlement and browser idle time. Limit automatic work to 200 unique links and three requests in flight. Remove queued work when links leave the page. Keep encoded batch URLs below 6 KB. - Keep exact navigation URLs, status styling, anchored cards and keyboard access. Add a page-load Storybook case and browser regression. The link service owns cache policy and provider calls. The browser coordinator owns page timing. The shared contract adds only the batch limit and response shape. The database adds storage because process and browser caches cannot serve a new browser session. Plugin resolver registration is outside this change; storage accepts future provider channels and status values. ## Verification - **All 93 affected tests pass:** 40 link service, real PostgreSQL and HTTP cases, plus 53 OpenAPI cases. Two SQL regressions and one HTTP case failed before the storage repair. Concurrent writers now retain at most 1,000 rows per company/viewer; cleanup removes long-expired rows and keeps recent stale status. Request backoff preserves cached reads and isolates companies/viewers. The earlier eight concurrent hydration regressions also pass. Focused store/service/unit types pass. Commands: `pnpm exec vitest run server/src/__tests__/link-previews.test.ts server/src/__tests__/link-preview-store.integration.test.ts server/src/__tests__/link-preview-routes.test.ts --maxWorkers=1` and `pnpm exec vitest run server/src/__tests__/openapi-routes.test.ts --maxWorkers=1`. - **All 50 affected server tests passed before the later server-only repairs** on the master-integrated source: 20 recovery/deadline cases, one authenticated review-counts HTTP case, 10 link-service cases, 13 real PostgreSQL cache cases and six link-route cases. Command: `pnpm exec vitest run server/src/__tests__/issue-recovery-deadlines.test.ts server/src/__tests__/tool-connection-review-counts-http.test.ts server/src/__tests__/link-previews.test.ts server/src/__tests__/link-preview-store.integration.test.ts server/src/__tests__/link-preview-routes.test.ts --maxWorkers=1`. - Reproduced the CI watchdog assertion locally twice before the test repair. Ordinary assignment recovery can win `wakeReason` while the watchdog wake coalesces into the same successful run with its full mandate. The test now verifies the persisted watchdog identity, watched issue and stopped fingerprint, plus exactly one review run. All 21 recovery/HTTP cases passed before integrating master; all 50 affected cases pass after integration. No runtime behavior was changed for this repair. - **Fresh static Storybook build and all 22 browser cases pass**, with two workers and retries disabled. They cover states, anchored hover, keyboard access, exact navigation, duplicate requests, reload persistence, expiry and saved-status hydration followed by one idle refresh. The first browser attempt could not launch because this session lacked Chromium; installing the expected browser resolved setup. That attempt had no behavioral verdict. - The cache repair remains covered by four PostgreSQL red/green regressions for expired memory and newer durable status during provider failure/timeout, plus check-time precedence and failed-read recovery. Earlier UI/database/focused server type and migration safety/compatibility/replay checks remain unchanged-input evidence. - Master `77ddf260bf9a3de3dcb8456a60f4f809d67401fd` is integrated cleanly. Link migration 0489 and its snapshot chain are unchanged. SDK source validation checks 545 inputs with no stale source identities or changed runtime/lock pins. Whitespace validation passes. - `pnpm verify --explain` returns exit 2 and requires broad CI. No full local suite or deployed acceptance is claimed. Earlier local full-server type checks exceeded memory; current-head CI supplies broad type/build/test coverage. - [Previous CI 43900336895](https://github.com/paperclipai/paperclip/actions/runs/43900336895) passed full types/build but failed on embedded PostgreSQL startup (`ECONNREFUSED`), the watchdog assertion above, and unrelated plan-task browser cleanup (activity-log foreign key on company deletion). One failed-jobs retry was requested. Its browser shard 7 now passes without code changes; the exact deletion-race cause remains unproven. The watchdog assertion is repaired in this revision. The previous failures remain recorded, not counted as an overall pass. - [Prior CI 43905482848](https://github.com/paperclipai/paperclip/actions/runs/43905482848) passed full types, build and all eight browser shards. Several test jobs were cancelled; the run has no overall pass. Its concurrent update finding is repaired. [Next CI 43909197530](https://github.com/paperclipai/paperclip/actions/runs/43909197530) also passed types, build and all browser shards, but several server jobs were cancelled. Greptile and Paperclip Review gave that revision 5/5. Its security scan found unbounded retained cache rows. The quota, retention and request-limit repair above addresses that finding. All ten review threads are resolved. - [Current CI 43912947278](https://github.com/paperclipai/paperclip/actions/runs/43912947278), fresh code reviews and a fresh security scan are pending on `335d89ef1668dcdeb66bb2059512a7c2da29e273`. Auto-merge is disabled until the current revision clears its gates. Published head: `335d89ef1668dcdeb66bb2059512a7c2da29e273`. Local head: `b37b87c704a2ba8a65233c689a6a743f4011ce14`. Both have tree `643ebd19b9729b1e6a6bb695442269c3db32be3a`; GitHub tree creation verified equality. ## Risks - Each company/viewer retains at most 1,000 rows. Writes remove excess rows and entries whose freshness expired over 30 days ago. Inactive scopes remain bounded and are cleaned on the next write. Company deletion removes all rows. No periodic worker runs. Scope writes use a transaction lock; the existing deadline and concurrency budget cover that work. - Last known status can be stale until idle or hover work completes. Provider failures keep that status through the negative-cache window. - Automatic enrichment adds bounded provider traffic. It runs only for mounted supported links, once per mount, with the existing timeout and server concurrency limit. - Cache storage is viewer-scoped because provider results can be private. New viewers load their own results. This prevents reuse across users with different repository access. ## Model Used OpenAI Codex, based on GPT-6, with reasoning, repository tools, code execution and browser automation. The runtime does not expose the exact serving model ID or context-window size. No subagents were used. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip Co-authored-by: Paperclip --- doc/link-previews.md | 65 +++ packages/db/src/migrations/0489_real_sage.sql | 14 + ...{0484_snapshot.json => 0489_snapshot.json} | 423 +++++++++++++++++- packages/db/src/migrations/meta/_journal.json | 7 + packages/db/src/schema/index.ts | 1 + packages/db/src/schema/link_previews.ts | 19 + packages/shared/src/index.ts | 2 +- packages/shared/src/link-preview.ts | 5 +- .../issue-recovery-deadlines.test.ts | 13 +- .../src/__tests__/link-preview-routes.test.ts | 48 +- .../link-preview-store.integration.test.ts | 253 +++++++++++ server/src/__tests__/link-previews.test.ts | 77 ++++ server/src/__tests__/openapi-routes.test.ts | 11 +- server/src/routes/link-previews.ts | 26 +- server/src/routes/openapi.ts | 37 +- server/src/services/link-preview-store.ts | 65 +++ server/src/services/link-previews.ts | 110 ++++- .../runner-e2e/source-sdk-public-inputs.json | 4 +- tests/storybook-visual/link-previews.spec.ts | 51 +++ ui/src/components/LinkPreview.tsx | 22 +- ui/src/components/MarkdownUrlLink.tsx | 4 +- ui/src/context/LinkPreviewContext.test.tsx | 46 ++ ui/src/context/LinkPreviewContext.tsx | 28 +- ui/src/lib/link-preview-page-loader.test.ts | 130 ++++++ ui/src/lib/link-preview-page-loader.ts | 139 ++++++ ui/src/lib/link-preview-query.ts | 24 + .../stories/tasks/link-previews.stories.tsx | 13 +- 27 files changed, 1572 insertions(+), 65 deletions(-) create mode 100644 doc/link-previews.md create mode 100644 packages/db/src/migrations/0489_real_sage.sql rename packages/db/src/migrations/meta/{0484_snapshot.json => 0489_snapshot.json} (99%) create mode 100644 packages/db/src/schema/link_previews.ts create mode 100644 server/src/__tests__/link-preview-store.integration.test.ts create mode 100644 server/src/services/link-preview-store.ts create mode 100644 ui/src/context/LinkPreviewContext.test.tsx create mode 100644 ui/src/lib/link-preview-page-loader.test.ts create mode 100644 ui/src/lib/link-preview-page-loader.ts create mode 100644 ui/src/lib/link-preview-query.ts diff --git a/doc/link-previews.md b/doc/link-previews.md new file mode 100644 index 00000000000..67d3f89184c --- /dev/null +++ b/doc/link-previews.md @@ -0,0 +1,65 @@ +# Rich link status caching + +Rich link metadata belongs to the link preview service. GitHub pull requests are +the first provider. Links retain their exact navigation URL and use a canonical +resource URL for cache identity. + +`link_previews` stores company, viewer, channel, resource kind, canonical URL, +free-form status, JSON metadata, check time and freshness expiry. It has no task +foreign key. The same resource on different tasks reuses a record. Channel, +resource kind, status and metadata are not GitHub enums; future provider adapters +can use their own values. This change does not register plugin resolvers. + +Personal provider access remains viewer-scoped. The unique index is +`(company_id, viewer_id, canonical_url)`. The empty viewer is reserved for local +trusted mode. Company/board authorization runs before cache reads. Neither cache +endpoint is accessible to agents. Personal results never enter `external_objects`. +A cache fill is derivative read data; it does not mutate tasks or produce activity +feed events. Cache HTTP responses use `private, no-store`. + +The browser registers mounted rich links after render. Up to 200 unique links +per active company view are eligible for automatic enrichment; further links +still work on hover/focus. One request reads up to 50 cached previews using one +indexed database select, without provider calls or task joins. The read-only GET +route also supports viewer-role members. Encoded request URLs stay below 6 KB. Duplicate links +share one browser query. Fresh browser results take precedence over older database +reads. Cache failures are quiet and do not block the task page. + +After document load, core query settlement and a 500ms quiet delay, browser idle +callbacks resolve stale or missing status with at most three requests in flight. +Hover/focus uses the same query and server path, so overlapping requests coalesce. +Queued links are removed on unmount and scope changes dispose the coordinator. +There is no recurring refresh, window-focus lookup or server background worker. +New links from subsequent page content get their own one-shot enrichment. + +The existing provider timeout, fixed-host lookup, managed connection selection, +public-access checks, negative cache window and process concurrency bound remain. +Provider results are stored before the successful lookup response completes when +the store is available within the shared five-second deadline. Stalled SQL keeps +its concurrency slot until it settles; the deadline still releases the response. +Expired process entries re-read durable storage before provider work. Both batch +reads and lookup fallback use check time to retain the newest known status; a +longer cache lifetime does not make an older status newer. When the durable read +fails too, provider-failure backoff stays local, so it cannot overwrite a saved +status that this process could not read. Database outages fall back to the +optional process cache/provider path. Successful +and unavailable results normally remain fresh for one minute; provider backoff +can extend that window up to one hour. Expired records retain last known status +for immediate display. An outage keeps that status and saves the negative +freshness window, so the page does not repeatedly retry. + +Each company/viewer scope retains at most 1,000 rows. A write removes rows beyond +that limit, keeping the newest check times, and rows whose freshness expired more +than 30 days before the write's check time. A transaction-scoped advisory lock +serializes writes for that scope across replicas, so concurrent URL misses cannot +exceed the cap. Cleanup makes no queries during page hydration and starts no +background worker. Inactive scopes remain bounded and are cleaned on their next +write; company deletion removes all their rows. Normal stale status remains +available until it ages out or the scope reaches its quota. Negative results use +the same cap and retention policy as known status. + +The single-link lookup route also limits each company/viewer to 600 requests per +minute per server process, using the existing in-memory request limiter. Excess +requests return 429 with Retry-After. Cached batch reads remain available during +that backoff and do not allocate stored rows. The durable quota is enforced across +replicas and remains effective when process-local request limits reset. diff --git a/packages/db/src/migrations/0489_real_sage.sql b/packages/db/src/migrations/0489_real_sage.sql new file mode 100644 index 00000000000..57c2b02e88a --- /dev/null +++ b/packages/db/src/migrations/0489_real_sage.sql @@ -0,0 +1,14 @@ +CREATE TABLE IF NOT EXISTS "link_previews" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "company_id" uuid NOT NULL CONSTRAINT "link_previews_company_id_companies_id_fk" REFERENCES "public"."companies"("id") ON DELETE cascade, + "viewer_id" text NOT NULL, + "channel" text NOT NULL, + "resource_kind" text NOT NULL, + "canonical_url" text NOT NULL, + "status" text, + "metadata" jsonb DEFAULT '{}'::jsonb NOT NULL, + "checked_at" timestamp with time zone NOT NULL, + "expires_at" timestamp with time zone NOT NULL +); +--> statement-breakpoint +CREATE UNIQUE INDEX IF NOT EXISTS "link_previews_scope_url_uq" ON "link_previews" USING btree ("company_id","viewer_id","canonical_url"); diff --git a/packages/db/src/migrations/meta/0484_snapshot.json b/packages/db/src/migrations/meta/0489_snapshot.json similarity index 99% rename from packages/db/src/migrations/meta/0484_snapshot.json rename to packages/db/src/migrations/meta/0489_snapshot.json index 1debf9ce54b..4eee50702b2 100644 --- a/packages/db/src/migrations/meta/0484_snapshot.json +++ b/packages/db/src/migrations/meta/0489_snapshot.json @@ -1,6 +1,6 @@ { - "id": "9389124c-379a-4b64-9c20-c7b37538e7c8", - "prevId": "ceaa38c4-681b-430e-9578-0854650d85b3", + "id": "dc61c7f3-cf3d-44c5-9296-86973e5f0925", + "prevId": "8f935a52-5f1e-4afe-8d13-c1770ca33968", "version": "7", "dialect": "postgresql", "tables": { @@ -6582,6 +6582,111 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.automatic_run_brakes": { + "name": "automatic_run_brakes", + "schema": "", + "columns": { + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'closed'" + }, + "reason": { + "name": "reason", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "state_changed_at": { + "name": "state_changed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "opened_at": { + "name": "opened_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "next_probe_at": { + "name": "next_probe_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "probe_run_id": { + "name": "probe_run_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "probe_successes": { + "name": "probe_successes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "release_window_started_at": { + "name": "release_window_started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "release_window_starts": { + "name": "release_window_starts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_creation_at": { + "name": "next_creation_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "automatic_run_brakes_company_id_companies_id_fk": { + "name": "automatic_run_brakes_company_id_companies_id_fk", + "tableFrom": "automatic_run_brakes", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.board_api_keys": { "name": "board_api_keys", "schema": "", @@ -36029,6 +36134,78 @@ "method": "btree", "with": {} }, + "heartbeat_runs_company_finished_idx": { + "name": "heartbeat_runs_company_finished_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "finished_at", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"heartbeat_runs\".\"finished_at\" is not null", + "concurrently": true, + "method": "btree", + "with": {} + }, + "heartbeat_runs_settled_process_identity_idx": { + "name": "heartbeat_runs_settled_process_identity_idx", + "columns": [ + { + "expression": "process_host_hash", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"heartbeat_runs\".\"runtime_mode\" = 'native' and \"heartbeat_runs\".\"status\" in ('failed', 'cancelled', 'timed_out', 'interrupted')\n and \"heartbeat_runs\".\"finished_at\" is not null\n and (\"heartbeat_runs\".\"process_pid\" is not null or \"heartbeat_runs\".\"process_group_id\" is not null or \"heartbeat_runs\".\"process_started_at\" is not null)", + "concurrently": true, + "method": "btree", + "with": {} + }, + "heartbeat_runs_pending_api_stop_idx": { + "name": "heartbeat_runs_pending_api_stop_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"heartbeat_runs\".\"status\" = 'cancelled' and \"heartbeat_runs\".\"driver_kind\" = 'cursor_cloud_api'\n and (\"heartbeat_runs\".\"result_json\"->'executionCancellation'->>'state') = 'requested'", + "concurrently": true, + "method": "btree", + "with": {} + }, "heartbeat_runs_company_created_at_desc_idx": { "name": "heartbeat_runs_company_created_at_desc_idx", "columns": [ @@ -40722,6 +40899,131 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.issue_recovery_deferrals": { + "name": "issue_recovery_deferrals", + "schema": "", + "columns": { + "queue": { + "name": "queue", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "due_at": { + "name": "due_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "issue_recovery_deferrals_issue_id_issues_id_fk": { + "name": "issue_recovery_deferrals_issue_id_issues_id_fk", + "tableFrom": "issue_recovery_deferrals", + "tableTo": "issues", + "columnsFrom": [ + "issue_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "issue_recovery_deferrals_company_id_companies_id_fk": { + "name": "issue_recovery_deferrals_company_id_companies_id_fk", + "tableFrom": "issue_recovery_deferrals", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "issue_recovery_deferrals_pk": { + "name": "issue_recovery_deferrals_pk", + "columns": [ + "queue", + "issue_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.issue_recovery_full_passes": { + "name": "issue_recovery_full_passes", + "schema": "", + "columns": { + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "queue": { + "name": "queue", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "issue_recovery_full_passes_company_id_companies_id_fk": { + "name": "issue_recovery_full_passes_company_id_companies_id_fk", + "tableFrom": "issue_recovery_full_passes", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "issue_recovery_full_passes_pk": { + "name": "issue_recovery_full_passes_pk", + "columns": [ + "company_id", + "queue" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.issue_reference_mentions": { "name": "issue_reference_mentions", "schema": "", @@ -44779,6 +45081,123 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.link_previews": { + "name": "link_previews", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "viewer_id": { + "name": "viewer_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel": { + "name": "channel", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "resource_kind": { + "name": "resource_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "canonical_url": { + "name": "canonical_url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "checked_at": { + "name": "checked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "link_previews_scope_url_uq": { + "name": "link_previews_scope_url_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "viewer_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "canonical_url", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "link_previews_company_id_companies_id_fk": { + "name": "link_previews_company_id_companies_id_fk", + "tableFrom": "link_previews", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.managed_agent_profiles": { "name": "managed_agent_profiles", "schema": "", diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index 464a6addffb..ee03bddd7a5 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -3410,6 +3410,13 @@ "when": 1794820062730, "tag": "0488_issue_recovery_full_passes", "breakpoints": true + }, + { + "idx": 489, + "version": "7", + "when": 1794841384470, + "tag": "0489_real_sage", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/index.ts b/packages/db/src/schema/index.ts index 68878bc412f..f27b014644c 100644 --- a/packages/db/src/schema/index.ts +++ b/packages/db/src/schema/index.ts @@ -290,3 +290,4 @@ export { projectTaskExecutionPolicies, executionAdmissions, executionAdmissionPr export { budgetEvaluationWork } from "./budget_evaluation_work.js"; export { tailscaleConnections } from "./tailscale_connections.js"; export { nativeProviderArtifacts, nativeProviderArtifactReferences } from "./native_provider_artifacts.js"; +export { linkPreviews } from "./link_previews.js"; diff --git a/packages/db/src/schema/link_previews.ts b/packages/db/src/schema/link_previews.ts new file mode 100644 index 00000000000..c7b7ee334aa --- /dev/null +++ b/packages/db/src/schema/link_previews.ts @@ -0,0 +1,19 @@ +import { jsonb, pgTable, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core"; +import { companies } from "./companies.js"; + +/** Optional enrichment, independent of tasks and of provider-specific status vocabularies. */ +export const linkPreviews = pgTable("link_previews", { + id: uuid("id").primaryKey().defaultRandom(), + companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }), + // Personal provider results must not be reused by another viewer. Empty is local-trusted. + viewerId: text("viewer_id").notNull(), + channel: text("channel").notNull(), + resourceKind: text("resource_kind").notNull(), + canonicalUrl: text("canonical_url").notNull(), + status: text("status"), + metadata: jsonb("metadata").$type>().notNull().default({}), + checkedAt: timestamp("checked_at", { withTimezone: true }).notNull(), + expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), +}, table => ({ + identity: uniqueIndex("link_previews_scope_url_uq").on(table.companyId, table.viewerId, table.canonicalUrl), +})); diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index efab7ad18d8..825867d65bb 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -2976,7 +2976,7 @@ export { TASK_IDENTITY_CHANGED_FIELD, issueActivityChangesTaskIdentity, } from "./issue-activity-identity.js"; -export { recognizeLinkPreview, type LinkPreviewTarget, type LinkPreviewState, type LinkPreview, type LinkPreviewResult } from "./link-preview.js"; +export { LINK_PREVIEW_BATCH_LIMIT, type LinkPreviewBatchResult, recognizeLinkPreview, type LinkPreviewTarget, type LinkPreviewState, type LinkPreview, type LinkPreviewResult } from "./link-preview.js"; export * from "./mcp-apps.js"; export * from "./tool-call-progress.js"; export * from "./mcp-skills.js"; diff --git a/packages/shared/src/link-preview.ts b/packages/shared/src/link-preview.ts index ffa5eb960a7..b7431d4c30a 100644 --- a/packages/shared/src/link-preview.ts +++ b/packages/shared/src/link-preview.ts @@ -18,10 +18,13 @@ export interface LinkPreview { export interface LinkPreviewResult { preview: LinkPreview | null; - /** Demand-driven cache lifetime; this does not schedule a refresh. */ + /** Remaining cache lifetime; zero means stale. This does not schedule a refresh. */ maxAgeMs: number; } +export const LINK_PREVIEW_BATCH_LIMIT = 50; +export interface LinkPreviewBatchResult { results: Record } + /** Recognition only. Never contacts a remote service or changes navigation. */ export function recognizeLinkPreview(href: string | null | undefined): LinkPreviewTarget | null { if (!href || href.length > 2048) return null; diff --git a/server/src/__tests__/issue-recovery-deadlines.test.ts b/server/src/__tests__/issue-recovery-deadlines.test.ts index f11f3f541f5..3543b5aa660 100644 --- a/server/src/__tests__/issue-recovery-deadlines.test.ts +++ b/server/src/__tests__/issue-recovery-deadlines.test.ts @@ -441,10 +441,19 @@ describeIssueRecovery("issue recovery production producers and deadlines", () => const [row] = await state.db.select().from(issueWatchdogs).where(eq(issueWatchdogs.id, watchdog.watchdog.id)); expect(row.watchdogIssueId).toBeTruthy(); reviewId = row.watchdogIssueId!; }, { timeout: 15_000 }); - await completed(reviewId!); + const review = await completed(reviewId!); expect(failures).toEqual([]); + // Ordinary assignment recovery can win the wake reason while the watchdog + // wake coalesces into that run. Verify its mandate and one dispatch instead. + expect(review.contextSnapshot).toMatchObject({ + watchdogId: watchdog.watchdog.id, + taskWatchdog: { + watchedIssueId: source.id, + stopFingerprint: expect.stringMatching(/^task_watchdog_stop:/), + }, + }); expect(await state.db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId), - sql`${heartbeatRuns.contextSnapshot}->>'wakeReason' = 'task_watchdog_stopped_subtree'`))).toHaveLength(1); + sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${reviewId}`))).toHaveLength(1); await finish(reviewId!); await taskWatchdogService(state.db).disableForIssue(f.companyId, source.id); if (!vi.isFakeTimers()) vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] }); await quiet(); diff --git a/server/src/__tests__/link-preview-routes.test.ts b/server/src/__tests__/link-preview-routes.test.ts index a5026be77d8..41dc53a85a9 100644 --- a/server/src/__tests__/link-preview-routes.test.ts +++ b/server/src/__tests__/link-preview-routes.test.ts @@ -4,21 +4,44 @@ import { describe, expect, it, vi } from "vitest"; import type { Db } from "@paperclipai/db"; import { linkPreviewRoutes } from "../routes/link-previews.js"; import { HttpError } from "../errors.js"; +import { createInviteRateLimiter, type InviteRateLimiter } from "../services/invite-rate-limit.js"; -function app(actor: express.Request["actor"]) { +function app(actor: express.Request["actor"], limiter?: InviteRateLimiter) { const get = vi.fn(async () => ({ preview: null, maxAgeMs: 60_000 })); + const cached = vi.fn(async () => ({ results: {} })); const server = express(); + server.use(express.json()); server.use((req, _res, next) => { req.actor = actor; next(); }); - server.use(linkPreviewRoutes(null as unknown as Db, { get })); + server.use(linkPreviewRoutes(null as unknown as Db, { get, cached }, limiter)); server.use((error: HttpError, _req: express.Request, res: express.Response, _next: express.NextFunction) => { res.status(error.status ?? 500).json({ error: error.message }); }); - return { server, get }; + return { server, get, cached }; } const board = { type: "board", source: "session", userId: "alice", companyIds: ["company-a"] } as const; const path = "/companies/company-a/link-preview"; describe("link preview routes", () => { + it("limits lookups per viewer and company without blocking cached reads", async () => { + let now = 0; + const limiter = createInviteRateLimiter({ maxRequests: 2, windowMs: 1_000, now: () => now }); + const actor = { ...board, userId: "alice", companyIds: ["company-a", "company-b"] }; + const { server, get, cached } = app(actor, limiter); + const query = { url: "https://github.com/acme/web/pull/42" }; + for (let n = 0; n < 2; n++) expect((await request(server).get(path).query(query)).status).toBe(200); + const limited = await request(server).get(path).query(query); + expect(limited.status).toBe(429); + expect(limited.headers["retry-after"]).toBe("1"); + expect(get).toHaveBeenCalledTimes(2); + expect((await request(server).get("/companies/company-a/link-previews/cached").query(query)).status).toBe(200); + expect(cached).toHaveBeenCalledTimes(1); + expect((await request(server).get("/companies/company-b/link-preview").query(query)).status).toBe(200); + actor.userId = "bob"; + expect((await request(server).get(path).query(query)).status).toBe(200); + actor.userId = "alice"; + now = 1_001; + expect((await request(server).get(path).query(query)).status).toBe(200); + }); it("passes the authenticated viewer and disables shared HTTP caching", async () => { const { server, get } = app({ ...board, companyIds: [...board.companyIds] }); const response = await request(server).get(path).query({ url: "https://github.com/acme/web/pull/42" }); @@ -38,6 +61,25 @@ describe("link preview routes", () => { expect(get).not.toHaveBeenCalled(); } }); + it("reads a bounded batch only after viewer and company authorization", async () => { + const { server, cached, get } = app({ ...board, companyIds: [...board.companyIds] }); + const response = await request(server).get("/companies/company-a/link-previews/cached").query({ url: ["https://github.com/acme/web/pull/42"] }); + expect(response.status).toBe(200); + expect(response.headers["cache-control"]).toBe("private, no-store"); + expect(cached).toHaveBeenCalledWith({ companyId: "company-a", userId: "alice" }, ["https://github.com/acme/web/pull/42"]); + expect(get).not.toHaveBeenCalled(); + for (const body of [{}, { url: ["x".repeat(2049)] }, { url: Array(51).fill("a") }]) { + expect((await request(server).get("/companies/company-a/link-previews/cached").query(body)).status).toBe(400); + } + const denied = app({ ...board, companyIds: ["company-b"] }); + expect((await request(denied.server).get("/companies/company-a/link-previews/cached")).status).toBe(403); + expect(denied.cached).not.toHaveBeenCalled(); + }); + it("lets active viewer-role members read stored statuses", async () => { + const { server, cached } = app({ ...board, companyIds: [...board.companyIds], memberships: [{ companyId: "company-a", membershipRole: "viewer", status: "active" }] }); + expect((await request(server).get("/companies/company-a/link-previews/cached").query({ url: "https://github.com/acme/web/pull/42" })).status).toBe(200); + expect(cached).toHaveBeenCalledTimes(1); + }); it("bounds and validates the URL input", async () => { const { server, get } = app({ ...board, companyIds: [...board.companyIds] }); for (const query of [{}, { url: "x".repeat(2049) }, { url: ["a", "b"] }]) { diff --git a/server/src/__tests__/link-preview-store.integration.test.ts b/server/src/__tests__/link-preview-store.integration.test.ts new file mode 100644 index 00000000000..376ff11ac7a --- /dev/null +++ b/server/src/__tests__/link-preview-store.integration.test.ts @@ -0,0 +1,253 @@ +import { randomUUID } from "node:crypto"; +import { readFile } from "node:fs/promises"; +import { companies, linkPreviews } from "@paperclipai/db"; +import { recognizeLinkPreview } from "@paperclipai/shared"; +import { sql } from "drizzle-orm"; +import { expect, it, vi } from "vitest"; +import { describeEmbeddedPostgres, useEmbeddedPostgres } from "./helpers/route-test-harness.js"; +import { createLinkPreviewStore } from "../services/link-preview-store.js"; +import { createLinkPreviewService } from "../services/link-previews.js"; + +const url = "https://github.com/acme/web/pull/42"; +const target = recognizeLinkPreview(url)!; +const preview = { target, title: "Durable PR", state: "merged" as const, author: "alice", updatedAt: null }; + +describeEmbeddedPostgres("durable link preview cache", () => { + const context = useEmbeddedPostgres("link-previews-"); + async function fixture() { + const companyId = randomUUID(); + await context.db.insert(companies).values({ id: companyId, name: "Link cache", issuePrefix: companyId }); + return { companyId, userId: "alice" }; + } + it("bounds retained rows across concurrent store instances and isolates their quotas", async () => { + const scope = await fixture(); + const other = { ...scope, userId: "bob" }; + const now = Date.now(); + const seed = Array.from({ length: 1_000 }, (_, n) => ({ + companyId: scope.companyId, viewerId: scope.userId, channel: "github", resourceKind: "pull_request", + canonicalUrl: url + n, status: null, metadata: {}, checkedAt: new Date(now - 1_000 + n), expiresAt: new Date(now + 60_000), + })); + await context.db.insert(linkPreviews).values([...seed, { ...seed[0], viewerId: other.userId }]); + const first = createLinkPreviewStore(context.db); + const second = createLinkPreviewStore(context.db); + await Promise.all(Array.from({ length: 8 }, (_, n) => (n % 2 ? first : second).write(scope, + recognizeLinkPreview(url + (1_000 + n))!, { result: { preview: null, maxAgeMs: 60_000 }, expiresAt: now + 60_000 }, now + n))); + const rows = await context.db.select().from(linkPreviews).where(sql`${linkPreviews.companyId} = ${scope.companyId}`); + expect(rows.filter(row => row.viewerId === scope.userId)).toHaveLength(1_000); + expect(rows.filter(row => row.viewerId === other.userId)).toHaveLength(1); + const saved = await first.read(scope, [recognizeLinkPreview(url + "0")!, recognizeLinkPreview(url + "1007")!]); + expect(saved.has(url + "0")).toBe(false); + expect(saved.has(url + "1007")).toBe(true); + }); + it("removes long-expired rows on writes and preserves recent stale status", async () => { + const scope = await fixture(); + const now = Date.now(); + const expired = now - 31 * 24 * 60 * 60_000; + await context.db.insert(linkPreviews).values([ + { companyId: scope.companyId, viewerId: scope.userId, channel: "github", resourceKind: "pull_request", canonicalUrl: url, + status: "merged", metadata: { title: preview.title }, checkedAt: new Date(expired - 60_000), expiresAt: new Date(expired) }, + { companyId: scope.companyId, viewerId: scope.userId, channel: "github", resourceKind: "pull_request", canonicalUrl: url + "1", + status: "merged", metadata: { title: preview.title }, checkedAt: new Date(now - 120_000), expiresAt: new Date(now - 60_000) }, + ]); + const store = createLinkPreviewStore(context.db); + await store.write(scope, recognizeLinkPreview(url + "2")!, { result: { preview: null, maxAgeMs: 60_000 }, expiresAt: now + 60_000 }, now); + const saved = await store.read(scope, [target, recognizeLinkPreview(url + "1")!, recognizeLinkPreview(url + "2")!]); + expect(saved.has(url)).toBe(false); + expect(saved.get(url + "1")?.result.preview?.state).toBe("merged"); + expect(saved.has(url + "2")).toBe(true); + }); + it.each(["failure", "success", "timeout", "stale timeout"])("keeps another replica's concurrent hydration after provider %s", async (settlement) => { + const scope = await fixture(); + const store = createLinkPreviewStore(context.db); + let now = 1_000; + const oldPreview = { ...preview, state: "open" as const }; + await store.write(scope, target, { result: { preview: oldPreview, maxAgeMs: 1_000 }, expiresAt: 2_000 }, now); + let finish!: (value: { preview: typeof oldPreview | null; maxAgeMs: number }) => void; + let started!: () => void; + const providerStarted = new Promise(done => { started = done; }); + const resolve = vi.fn(() => new Promise<{ preview: typeof oldPreview | null; maxAgeMs: number }>(done => { finish = done; started(); })); + const write = vi.fn(store.write); + const first = createLinkPreviewService([{ key: "github", resolve }], { store: { ...store, write }, now: () => now, timeoutMs: 1_000 }); + await first.cached(scope, [url]); + now = 3_000; + const pending = first.get(scope, url); + await providerStarted; + now = 4_000; + const expiresAt = settlement === "stale timeout" ? 3_500 : 34_000; + await store.write(scope, target, { result: { preview, maxAgeMs: 30_000 }, expiresAt }, now); + expect((await first.cached(scope, [url])).results[url].preview).toEqual(preview); + if (!settlement.includes("timeout")) finish({ preview: settlement === "success" ? oldPreview : null, maxAgeMs: 60_000 }); + expect(await pending).toEqual({ preview, maxAgeMs: Math.max(0, expiresAt - now) }); + // A second batch checks that the process did not retain the older status. + expect((await first.cached(scope, [url])).results[url].preview).toEqual(preview); + const saved = (await store.read(scope, [target])).get(url)!; + expect(saved.result.preview).toEqual(preview); + expect(saved.checkedAt).toBe(4_000); + expect(saved.expiresAt).toBe(expiresAt); + expect(write).not.toHaveBeenCalled(); + finish({ preview: null, maxAgeMs: 60_000 }); + }); + it.each(["open", "negative"])("rechecks expired %s memory before calling the provider", async (initialState) => { + const scope = await fixture(); + const store = createLinkPreviewStore(context.db); + let now = 1_000; + const resolve = vi.fn(async () => ({ preview: initialState === "open" ? { ...preview, state: "open" as const } : null, maxAgeMs: 60_000 })); + const first = createLinkPreviewService([{ key: "github", resolve }], { store, now: () => now }); + await first.get(scope, url); + now = 62_000; + const other = createLinkPreviewService([{ key: "github", resolve: async () => ({ preview, maxAgeMs: 60_000 }) }], { store, now: () => now }); + await other.get(scope, url); + resolve.mockRejectedValue(new Error("provider unavailable")); + + expect((await first.get(scope, url)).preview).toEqual(preview); + expect(resolve).toHaveBeenCalledTimes(1); + const saved = (await store.read(scope, [target])).get(url)!; + expect(saved.result.preview).toEqual(preview); + expect(saved.expiresAt).toBe(122_000); + }); + it.each(["failure", "timeout"])("retains the newest stale stored preview on provider %s", async (failure) => { + const scope = await fixture(); + const store = createLinkPreviewStore(context.db); + let now = 1_000; + let requests = 0; + const resolve = async (_target: import("@paperclipai/shared").LinkPreviewTarget, _scope: import("../services/link-previews.js").LinkPreviewScope, signal: AbortSignal) => { + if (++requests === 1) return { preview: { ...preview, state: "open" as const }, maxAgeMs: 60_000 }; + if (failure === "failure") throw new Error("provider unavailable"); + return new Promise((_done, reject) => signal.addEventListener("abort", () => reject(new Error("timeout")))); + }; + const first = createLinkPreviewService([{ key: "github", resolve }], { store, now: () => now, timeoutMs: 100 }); + await first.get(scope, url); + now = 62_000; + await store.write(scope, target, { result: { preview, maxAgeMs: 1_000 }, expiresAt: 63_000 }, now); + now = 64_000; + expect((await first.get(scope, url)).preview).toEqual(preview); + await vi.waitFor(async () => expect((await store.read(scope, [target])).get(url)?.expiresAt).toBe(124_000)); + expect((await store.read(scope, [target])).get(url)?.result.preview).toEqual(preview); + }); + it("compares check times rather than cache lifetimes when hydrating", async () => { + const scope = await fixture(); + const store = createLinkPreviewStore(context.db); + let now = 1_000; + await store.write(scope, target, { result: { preview: { ...preview, state: "open" }, maxAgeMs: 60_000 }, expiresAt: 61_000 }, now); + const service = createLinkPreviewService([{ key: "github", resolve: async () => ({ preview: null, maxAgeMs: 60_000 }) }], { store, now: () => now }); + await service.cached(scope, [url]); + await store.write(scope, target, { result: { preview, maxAgeMs: 1_000 }, expiresAt: 4_000 }, 3_000); + now = 5_000; + expect((await service.cached(scope, [url])).results[url]).toEqual({ preview, maxAgeMs: 0 }); + }); + it("keeps a failed durable read's fallback local and accepts recovered stored status", async () => { + const scope = await fixture(); + const store = createLinkPreviewStore(context.db); + const read = vi.fn(store.read); + let now = 1_000; + const resolve = vi.fn(async () => ({ preview: { ...preview, state: "open" as const }, maxAgeMs: 60_000 })); + const first = createLinkPreviewService([{ key: "github", resolve }], { store: { ...store, read }, now: () => now }); + await first.get(scope, url); + now = 62_000; + await store.write(scope, target, { result: { preview, maxAgeMs: 60_000 }, expiresAt: 122_000 }, now); + now = 64_000; + read.mockRejectedValueOnce(new Error("temporary database outage")); + resolve.mockRejectedValueOnce(new Error("provider unavailable")); + expect((await first.get(scope, url)).preview?.state).toBe("open"); + const saved = (await store.read(scope, [target])).get(url)!; + expect(saved.result.preview).toEqual(preview); + expect(saved.expiresAt).toBe(122_000); + expect((await first.cached(scope, [url])).results[url].preview).toEqual(preview); + }); + it.each(["missing", "failed"])("reads another replica's saved status after a %s batch read", async (initialRead) => { + const scope = await fixture(); + const store = createLinkPreviewStore(context.db); + const read = vi.fn(store.read); + if (initialRead === "failed") read.mockRejectedValueOnce(new Error("temporary database outage")); + const write = vi.fn(store.write); + const resolve = vi.fn(async () => { throw new Error("provider unavailable"); }); + const first = createLinkPreviewService([{ key: "github", resolve }], { store: { read, write } }); + expect(await first.cached(scope, [url])).toEqual({ results: {} }); + + const other = createLinkPreviewService([{ key: "github", resolve: async () => ({ preview, maxAgeMs: 60_000 }) }], { store }); + await other.get(scope, url); + expect((await first.get(scope, url)).preview).toEqual(preview); + expect(read).toHaveBeenCalledTimes(2); + expect(resolve).not.toHaveBeenCalled(); + expect(write).not.toHaveBeenCalled(); + expect((await store.read(scope, [target])).get(url)?.result.preview).toEqual(preview); + }); + it("survives service recreation, reuses canonical URLs across tasks, and isolates viewers/companies", async () => { + const scope = await fixture(); + const store = createLinkPreviewStore(context.db); + const resolve = vi.fn(async () => ({ preview, maxAgeMs: 60_000 })); + const make = () => createLinkPreviewService([{ key: "github", resolve }], { store }); + await make().get(scope, url); + const restored = await make().cached(scope, [url, "https://www.github.com/ACME/WEB/pull/42/files#review"]); + expect(Object.keys(restored.results)).toEqual([url]); + expect(restored.results[url].preview).toMatchObject({ title: preview.title, state: "merged", target: { canonicalUrl: url } }); + expect(restored.results[url].maxAgeMs).toBeGreaterThan(0); + await make().get(scope, url); + expect(resolve).toHaveBeenCalledTimes(1); + expect(await make().cached({ ...scope, userId: "bob" }, [url])).toEqual({ results: {} }); + expect(await make().cached(await fixture(), [url])).toEqual({ results: {} }); + }); + it("returns stale status immediately, refreshes on demand, and persists negative freshness", async () => { + const scope = await fixture(); + const store = createLinkPreviewStore(context.db); + let now = 1_000; + const resolve = vi.fn(async () => ({ preview, maxAgeMs: 60_000 })); + const make = () => createLinkPreviewService([{ key: "github", resolve }], { store, now: () => now }); + await make().get(scope, url); + now += 61_000; + expect((await make().cached(scope, [url])).results[url]).toEqual({ preview, maxAgeMs: 0 }); + expect(resolve).toHaveBeenCalledTimes(1); + resolve.mockRejectedValueOnce(new Error("outage")); + expect((await make().get(scope, url)).preview).toEqual(preview); + await make().get(scope, url); + expect(resolve).toHaveBeenCalledTimes(2); + const missing = url + "1"; + resolve.mockRejectedValueOnce(new Error("private")); + await make().get(scope, missing); + await make().get(scope, missing); + expect(resolve).toHaveBeenCalledTimes(3); + expect((await make().cached(scope, [missing])).results[missing].preview).toBeNull(); + }); + it("persists provider timeout freshness across service restarts without extending the response", async () => { + const scope = await fixture(); + const database = createLinkPreviewStore(context.db); + let saved!: () => void; + const persisted = new Promise(done => { saved = done; }); + const store = { ...database, write: async (...args: Parameters) => { await database.write(...args); saved(); } }; + const resolve = vi.fn((_target: import("@paperclipai/shared").LinkPreviewTarget, _scope: import("../services/link-previews.js").LinkPreviewScope, signal: AbortSignal) => new Promise((_done, reject) => { + signal.addEventListener("abort", () => reject(new Error("timeout"))); + })); + const first = createLinkPreviewService([{ key: "github", resolve }], { store, timeoutMs: 100 }); + expect((await first.get(scope, url)).preview).toBeNull(); + await persisted; + const restarted = createLinkPreviewService([{ key: "github", resolve }], { store }); + expect((await restarted.get(scope, url)).preview).toBeNull(); + expect(resolve).toHaveBeenCalledTimes(1); + expect((await restarted.cached(scope, [url])).results[url].maxAgeMs).toBeGreaterThan(0); + }); + it("reads a 50-link page in one indexed select and does not require task relationships", async () => { + const scope = await fixture(); + const store = createLinkPreviewStore(context.db); + const targets = Array.from({ length: 50 }, (_, n) => recognizeLinkPreview(url + n)!); + await Promise.all(targets.map(t => store.write(scope, t, { result: { preview: { ...preview, target: t }, maxAgeMs: 60_000 }, expiresAt: 61_000 }, 1_000))); + const select = vi.spyOn(context.db, "select"); + expect((await store.read(scope, targets)).size).toBe(50); + expect(select).toHaveBeenCalledTimes(1); + select.mockRestore(); + const plan = await context.db.execute(sql`EXPLAIN SELECT * FROM link_previews WHERE company_id = ${scope.companyId} AND viewer_id = 'alice' AND canonical_url IN (${sql.join(targets.map(t => sql`${t.canonicalUrl}`), sql`, `)})`); + expect(JSON.stringify(plan)).toContain("link_previews_scope_url_uq"); + }); + it("supports other channels/statuses and older writers cannot replace newer results", async () => { + const scope = await fixture(); + const store = createLinkPreviewStore(context.db); + const deployment = { ...target, provider: "vercel", kind: "deployment", canonicalUrl: "https://vercel.com/acme/build/123" }; + await context.db.insert(linkPreviews).values({ companyId: scope.companyId, viewerId: scope.userId, channel: deployment.provider, + resourceKind: deployment.kind, canonicalUrl: deployment.canonicalUrl, status: "deployed", metadata: { deploymentId: "123", region: "iad1" }, checkedAt: new Date(), expiresAt: new Date() }); + await store.write(scope, target, { result: { preview, maxAgeMs: 60_000 }, expiresAt: 65_000 }, 5_000); + await store.write(scope, target, { result: { preview: { ...preview, state: "open" }, maxAgeMs: 60_000 }, expiresAt: 61_000 }, 1_000); + expect((await store.read(scope, [target])).get(url)?.result.preview?.state).toBe("merged"); + const migration = await readFile(new URL("../../../packages/db/src/migrations/0489_real_sage.sql", import.meta.url), "utf8"); + for (const statement of migration.split("--> statement-breakpoint")) if (statement.trim()) await context.db.execute(sql.raw(statement)); + expect((await store.read(scope, [target])).get(url)?.result.preview?.state).toBe("merged"); + }); +}); diff --git a/server/src/__tests__/link-previews.test.ts b/server/src/__tests__/link-previews.test.ts index 5ef63cd6aef..6e4bfccfcc2 100644 --- a/server/src/__tests__/link-previews.test.ts +++ b/server/src/__tests__/link-previews.test.ts @@ -2,6 +2,8 @@ import { createServer } from "node:http"; import { once } from "node:events"; import { afterEach, describe, expect, it, vi } from "vitest"; import { createLinkPreviewService, type LinkPreviewProvider } from "../services/link-previews.js"; +import type { StoredLinkPreview } from "../services/link-preview-store.js"; +import { recognizeLinkPreview } from "@paperclipai/shared"; const scope = { companyId: "company-a", userId: "alice" }; const url = "https://github.com/acme/web/pull/42"; @@ -10,6 +12,51 @@ const provider = (resolve = vi.fn(async () => unavailable)): LinkPreviewProvider afterEach(() => vi.useRealTimers()); describe("demand-driven link preview cache", () => { + it.each(["failure", "success", "timeout", "write"])("keeps concurrent hydration newer than a pending provider %s", async (settlement) => { + vi.useFakeTimers(); + let now = 1_000; + const target = recognizeLinkPreview(url)!; + const oldPreview = { target, title: "Old status", state: "open" as const, author: null, updatedAt: null }; + const newPreview = { ...oldPreview, title: "New status", state: "merged" as const }; + let stored: StoredLinkPreview = { result: { preview: oldPreview, maxAgeMs: 1_000 }, expiresAt: 2_000, checkedAt: now }; + let finish!: (value: typeof unavailable | { preview: typeof oldPreview; maxAgeMs: number }) => void; + let finishWrite!: () => void; + const write = vi.fn(async () => { + if (settlement === "write") await new Promise(done => { finishWrite = done; }); + }); + const resolve = vi.fn(() => new Promise(done => { finish = done; })); + const service = createLinkPreviewService([{ key: "github", resolve }], { + now: () => now, timeoutMs: 20, + store: { read: async () => new Map([[url, stored]]), write }, + }); + await service.cached(scope, [url]); + now = 3_000; + const pending = service.get(scope, url); + await vi.advanceTimersByTimeAsync(0); + if (settlement === "write") { + finish({ preview: oldPreview, maxAgeMs: 60_000 }); + await vi.advanceTimersByTimeAsync(0); + expect(write).toHaveBeenCalledTimes(1); + } + now = 4_000; + stored = { result: { preview: newPreview, maxAgeMs: 30_000 }, expiresAt: 34_000, checkedAt: now }; + expect((await service.cached(scope, [url])).results[url].preview).toEqual(newPreview); + if (settlement === "write") finishWrite(); + else if (settlement === "timeout") await vi.advanceTimersByTimeAsync(21); + else finish(settlement === "failure" ? unavailable : { preview: oldPreview, maxAgeMs: 60_000 }); + expect(await pending).toEqual({ preview: newPreview, maxAgeMs: 30_000 }); + expect(await service.get(scope, url)).toEqual({ preview: newPreview, maxAgeMs: 30_000 }); + expect(resolve).toHaveBeenCalledTimes(1); + expect(write).toHaveBeenCalledTimes(settlement === "write" ? 1 : 0); + if (settlement === "timeout") { finish(unavailable); await vi.advanceTimersByTimeAsync(0); } + }); + it("omits absent records on repeated batch reads", async () => { + const service = createLinkPreviewService([provider()], { + store: { read: async () => new Map(), write: async () => {} }, + }); + expect(await service.cached(scope, [url])).toEqual({ results: {} }); + expect(await service.cached(scope, [url])).toEqual({ results: {} }); + }); it("does no work until requested and coalesces equivalent URLs", async () => { const resolve = vi.fn(async () => unavailable); const service = createLinkPreviewService([provider(resolve)]); @@ -86,6 +133,36 @@ describe("demand-driven link preview cache", () => { expect(resolve).toHaveBeenCalledTimes(2); finish(unavailable); }); + it("bounds a stalled database write and holds its concurrency slot until settlement", async () => { + vi.useFakeTimers(); + let finish!: () => void; + const write = vi.fn(async () => {}).mockImplementationOnce(() => new Promise(done => { finish = done; })); + const resolve = vi.fn(async (target: import("@paperclipai/shared").LinkPreviewTarget) => ({ preview: { target, title: "Known", state: "open" as const, author: null, updatedAt: null }, maxAgeMs: 60_000 })); + const service = createLinkPreviewService([{ key: "github", resolve }], { + store: { read: async () => new Map(), write }, timeoutMs: 20, maxConcurrent: 1, + }); + const first = service.get(scope, url); + await vi.advanceTimersByTimeAsync(21); + expect((await first).preview?.state).toBe("open"); + expect(await service.get(scope, url + "1")).toEqual(unavailable); + expect(resolve).toHaveBeenCalledTimes(1); + finish(); await vi.advanceTimersByTimeAsync(1); + await service.get(scope, url + "1"); + expect(resolve).toHaveBeenCalledTimes(2); + }); + it("keeps timeout persistence inside the concurrency budget after the provider aborts", async () => { + vi.useFakeTimers(); + let finishWrite!: () => void; + const write = vi.fn(async () => {}).mockImplementationOnce(() => new Promise(done => { finishWrite = done; })); + const resolve = vi.fn(async (_target: import("@paperclipai/shared").LinkPreviewTarget, _scope: import("../services/link-previews.js").LinkPreviewScope, signal: AbortSignal) => unavailable) + .mockImplementationOnce((_target, _scope, signal) => new Promise((_done, reject) => signal.addEventListener("abort", () => reject(new Error("timeout"))))); + const service = createLinkPreviewService([{ key: "github", resolve }], { store: { read: async () => new Map(), write }, timeoutMs: 20, maxConcurrent: 1 }); + const first = service.get(scope, url); + await vi.advanceTimersByTimeAsync(21); expect(await first).toEqual(unavailable); + await service.get(scope, url + "1"); expect(resolve).toHaveBeenCalledTimes(1); + finishWrite(); await vi.advanceTimersByTimeAsync(1); + await service.get(scope, url + "1"); expect(resolve).toHaveBeenCalledTimes(2); + }); it("aborts a real stalled HTTP read while an unrelated lookup remains responsive", async () => { const server = createServer((_req, res) => { res.writeHead(200, { "content-type": "application/json" }); res.write("{"); }); server.listen(0, "127.0.0.1"); diff --git a/server/src/__tests__/openapi-routes.test.ts b/server/src/__tests__/openapi-routes.test.ts index 399b53fc554..3a8e0157049 100644 --- a/server/src/__tests__/openapi-routes.test.ts +++ b/server/src/__tests__/openapi-routes.test.ts @@ -4,7 +4,7 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import request from "supertest"; import { describe, expect, it } from "vitest"; -import { MUSE_ASSET_VERSION, MUSE_PUBLIC_ROUTES } from "@paperclipai/shared"; +import { LINK_PREVIEW_BATCH_LIMIT, MUSE_ASSET_VERSION, MUSE_PUBLIC_ROUTES } from "@paperclipai/shared"; import { COMPANY_IMPORT_TRANSFERS_ROUTE_PATH } from "@paperclipai/shared/company-import-transfer"; import { errorHandler } from "../middleware/index.js"; import { buildOpenApiSpec, openApiRoutes, applyPluginSettingsVisibility, buildOpenApiDocument } from "../routes/openapi.js"; @@ -338,6 +338,15 @@ function loadSpecRoutes() { } describe("openapi routes", () => { + it("describes cached link results with the lookup shape and shared batch bound", () => { + const paths = buildOpenApiSpec().paths; + const batch = paths["/api/companies/{companyId}/link-previews/cached"].get; + expect(batch.description).toContain(`at most ${LINK_PREVIEW_BATCH_LIMIT} URLs`); + const lookupResult = paths["/api/companies/{companyId}/link-preview"].get.responses[200].content["application/json"].schema; + expect(batch.responses[200].content["application/json"].schema.properties.results.additionalProperties).toEqual(lookupResult); + expect(lookupResult.properties).toHaveProperty("preview"); + expect(lookupResult.properties).toHaveProperty("maxAgeMs"); + }); it("tells agents that unpriced usage in cost reports is unknown cost, not zero", () => { const paths = buildOpenApiSpec().paths; for (const segment of ["summary", "by-agent", "by-agent-model", "by-project"]) { diff --git a/server/src/routes/link-previews.ts b/server/src/routes/link-previews.ts index bd631855b2f..5236a55f516 100644 --- a/server/src/routes/link-previews.ts +++ b/server/src/routes/link-previews.ts @@ -1,11 +1,15 @@ import { Router } from "express"; import type { Db } from "@paperclipai/db"; -import { badRequest } from "../errors.js"; +import { LINK_PREVIEW_BATCH_LIMIT } from "@paperclipai/shared"; +import { createLinkPreviewStore } from "../services/link-preview-store.js"; +import { badRequest, tooManyRequests } from "../errors.js"; +import { createInviteRateLimiter, type InviteRateLimiter } from "../services/invite-rate-limit.js"; import { assertBoard, assertCompanyAccess } from "./authz.js"; import { createLinkPreviewService } from "../services/link-previews.js"; import { createGitHubLinkPreviewProvider } from "../services/github-link-preview.js"; -export function linkPreviewRoutes(db: Db, service = createLinkPreviewService([createGitHubLinkPreviewProvider(db)])) { +export function linkPreviewRoutes(db: Db, service = createLinkPreviewService([createGitHubLinkPreviewProvider(db)], { store: createLinkPreviewStore(db) }), + limiter: InviteRateLimiter = createInviteRateLimiter({ maxRequests: 600 })) { const router = Router(); router.get("/companies/:companyId/link-preview", async (req, res) => { const companyId = req.params.companyId as string; @@ -15,7 +19,25 @@ export function linkPreviewRoutes(db: Db, service = createLinkPreviewService([cr if (typeof href !== "string" || href.length > 2048) throw badRequest("A link URL is required"); // Personal repository metadata must never be stored by a proxy or shared browser cache. res.set("Cache-Control", "private, no-store"); + const limit = limiter.consume(JSON.stringify([companyId, req.actor.userId ?? null])); + res.set("X-RateLimit-Limit", String(limit.limit)); + res.set("X-RateLimit-Remaining", String(limit.remaining)); + if (!limit.allowed) { + res.set("Retry-After", String(limit.retryAfterSeconds)); + throw tooManyRequests("Link preview rate limit exceeded"); + } res.json(await service.get({ companyId, userId: req.actor.userId ?? null }, href)); }); + // Read-only batch: page hydration never waits for a remote provider. + router.get("/companies/:companyId/link-previews/cached", async (req, res) => { + const companyId = req.params.companyId as string; + assertCompanyAccess(req, companyId); + assertBoard(req); + const urls = typeof req.query.url === "string" ? [req.query.url] : req.query.url; + if (!Array.isArray(urls) || !urls.length || urls.length > LINK_PREVIEW_BATCH_LIMIT + || urls.some(url => typeof url !== "string" || url.length > 2048)) throw badRequest("A bounded list of link URLs is required"); + res.set("Cache-Control", "private, no-store"); + res.json(await service.cached({ companyId, userId: req.actor.userId ?? null }, urls as string[])); + }); return router; } diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index 8762d89f512..101c9bf9d38 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -2,7 +2,7 @@ import { catalogTeamInstallSchema, catalogTeamPreviewSchema, updateWorkspacePref import { MUSE_ASSET_VERSION, museStopBoundarySchema, museDetectorCleanupAttestationSchema, createGrokInvitationSchema, configureGrokRoutineSchema, verifyGrokRoutineSchema, recoverGrokRoutineSchema, pairGrokBindingSchema, stopGrokWorkSchema, retryGrokDeliverySchema, updateFastResponseSchema } from "@paperclipai/shared"; import { slackTestMessageSchema, slackTestMessageResultSchema, slackManagerAuthorizationSchema, slackSetupOptionsSchema, slackManagedProvisionSchema, slackManagedResultSchema, slackRegistrationSchema, slackSetupActionSchema, slackInstallAuthorizationSchema, slackRegistrationStateSchema, slackAppConfigurationSchema, slackAvatarStateSchema, slackAccountStateSchema } from "@paperclipai/shared"; import { experimentalApiMetadata } from "./experimental-api-metadata.js"; -import { ATTENTION_SOURCE_KINDS } from "@paperclipai/shared"; +import { LINK_PREVIEW_BATCH_LIMIT, ATTENTION_SOURCE_KINDS } from "@paperclipai/shared"; import { agentCaseHandoffSchema, caseWorkflowDocumentTextSchema, doneCaseHandoffSchema, createWorkflowSchema, updateWorkflowSchema, listWorkflowsSchema, readWorkflowQuerySchema } from "@paperclipai/shared"; import { experimentalApiDocs, @@ -10459,26 +10459,41 @@ registry.registerPath({ responses: { 200: r.ok(), 401: r.unauthorized, 404: r.notFound }, }); +const linkPreviewResultSchema = z.object({ + preview: z.object({ + target: z.object({ provider: z.string(), kind: z.string(), canonicalUrl: z.string(), label: z.string() }), + title: z.string(), state: z.enum(["unknown", "open", "draft", "merged", "closed", "conflicts"]), + author: z.string().nullable(), updatedAt: z.string().nullable(), + }).nullable(), + maxAgeMs: z.number(), +}); + registry.registerPath({ method: "get", path: "/api/companies/{companyId}/link-preview", tags: ["companies"], summary: "Read optional link metadata for the current board user", - description: "Company access and board authentication are required. This read uses a viewer-scoped cache and returns a quiet null preview when provider access is unavailable. It does not change tasks or schedule background work.", + description: "Company access and board authentication are required. This read uses a viewer-scoped cache and returns a quiet null preview when provider access is unavailable. Each company/viewer can make 600 lookup requests per minute per server process. Excess requests return 429 with Retry-After; cached batch reads remain available. It does not change tasks or schedule background work.", request: { params: z.object({ companyId: z.string() }), query: z.object({ url: z.string().max(2048) }) }, responses: { - 200: r.ok(z.object({ - preview: z.object({ - target: z.object({ provider: z.string(), kind: z.string(), canonicalUrl: z.string(), label: z.string() }), - title: z.string(), state: z.enum(["unknown", "open", "draft", "merged", "closed", "conflicts"]), - author: z.string().nullable(), updatedAt: z.string().nullable(), - }).nullable(), - maxAgeMs: z.number(), - })), - 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, + 200: r.ok(linkPreviewResultSchema), + 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 429: r.tooManyRequests, }, }); +registry.registerPath({ + method: "get", + path: "/api/companies/{companyId}/link-previews/cached", + tags: ["companies"], + summary: "Read a batch of stored link statuses without contacting providers", + description: `Board-only and company/viewer scoped. Reads at most ${LINK_PREVIEW_BATCH_LIMIT} URLs. Canonical links are reused across tasks. Stale records have maxAgeMs zero; absent records are omitted. This is a read-only cache projection.`, + request: { + params: z.object({ companyId: z.string() }), + query: z.object({ url: z.union([z.string().max(2048), z.array(z.string().max(2048)).min(1).max(LINK_PREVIEW_BATCH_LIMIT)]) }), + }, + responses: { 200: r.ok(z.object({ results: z.record(z.string(), linkPreviewResultSchema) })), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden }, +}); + registry.registerPath({ method: "get", path: "/api/issues/{id}/external-objects", diff --git a/server/src/services/link-preview-store.ts b/server/src/services/link-preview-store.ts new file mode 100644 index 00000000000..3bbe508f7f0 --- /dev/null +++ b/server/src/services/link-preview-store.ts @@ -0,0 +1,65 @@ +import { and, desc, eq, inArray, lt, lte, or, sql } from "drizzle-orm"; +import { linkPreviews, type Db } from "@paperclipai/db"; +import type { LinkPreviewResult, LinkPreviewTarget } from "@paperclipai/shared"; +import type { LinkPreviewScope } from "./link-previews.js"; + +export interface StoredLinkPreview { result: LinkPreviewResult; expiresAt: number; checkedAt: number } +export interface LinkPreviewStore { + read(scope: LinkPreviewScope, targets: readonly LinkPreviewTarget[]): Promise>; + write(scope: LinkPreviewScope, target: LinkPreviewTarget, entry: Omit, checkedAt: number): Promise; +} + +const MAX_ROWS_PER_VIEWER = 1_000; +const EXPIRED_RETENTION_MS = 30 * 24 * 60 * 60_000; + +export function createLinkPreviewStore(db: Db): LinkPreviewStore { + return { + async read(scope, targets) { + if (!targets.length) return new Map(); + // One covering identity-index lookup for the page, never a task join or a provider call. + const rows = await db.select().from(linkPreviews).where(and( + eq(linkPreviews.companyId, scope.companyId), eq(linkPreviews.viewerId, scope.userId ?? ""), + inArray(linkPreviews.canonicalUrl, targets.map(target => target.canonicalUrl)), + )); + const byUrl = new Map(targets.map(target => [target.canonicalUrl, target])); + return new Map(rows.flatMap(row => { + const target = byUrl.get(row.canonicalUrl); + if (!target || target.provider !== row.channel || target.kind !== row.resourceKind) return []; + const data = row.metadata; + const preview = row.status !== null && typeof data.title === "string" ? { + target, title: data.title, state: row.status as NonNullable["state"], + author: typeof data.author === "string" ? data.author : null, + updatedAt: typeof data.updatedAt === "string" ? data.updatedAt : null, + } : null; + return [[row.canonicalUrl, { result: { preview, maxAgeMs: 0 }, expiresAt: row.expiresAt.getTime(), checkedAt: row.checkedAt.getTime() }] as const]; + })); + }, + async write(scope, target, entry, checkedAt) { + const preview = entry.result.preview; + const values = { + companyId: scope.companyId, viewerId: scope.userId ?? "", channel: target.provider, + resourceKind: target.kind, canonicalUrl: target.canonicalUrl, status: preview?.state ?? null, + metadata: preview ? { title: preview.title, author: preview.author, updatedAt: preview.updatedAt } : {}, + checkedAt: new Date(checkedAt), expiresAt: new Date(entry.expiresAt), + }; + await db.transaction(async tx => { + // Serialize only this cache scope, including across server replicas. + // The row cap must hold when several distinct URLs are saved together. + const lockKey = JSON.stringify(["link-previews", values.companyId, values.viewerId]); + await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, 0))`); + await tx.insert(linkPreviews).values(values).onConflictDoUpdate({ + target: [linkPreviews.companyId, linkPreviews.viewerId, linkPreviews.canonicalUrl], + set: values, setWhere: lte(linkPreviews.checkedAt, values.checkedAt), + }); + const scopeCondition = and(eq(linkPreviews.companyId, values.companyId), eq(linkPreviews.viewerId, values.viewerId)); + // Cleanup runs on writes, without a worker or extra page-read queries. + // The identity index covers this scope, whose retained size is bounded. + await tx.delete(linkPreviews).where(and(scopeCondition, or( + lt(linkPreviews.expiresAt, new Date(checkedAt - EXPIRED_RETENTION_MS)), + inArray(linkPreviews.id, tx.select({ id: linkPreviews.id }).from(linkPreviews).where(scopeCondition) + .orderBy(desc(linkPreviews.checkedAt), desc(linkPreviews.id)).offset(MAX_ROWS_PER_VIEWER)), + ))); + }); + }, + }; +} diff --git a/server/src/services/link-previews.ts b/server/src/services/link-previews.ts index 29041b51ce9..ae8bf43300d 100644 --- a/server/src/services/link-previews.ts +++ b/server/src/services/link-previews.ts @@ -1,4 +1,5 @@ import type { LinkPreviewResult, LinkPreviewTarget } from "@paperclipai/shared"; +import type { LinkPreviewStore, StoredLinkPreview } from "./link-preview-store.js"; import { recognizeLinkPreview } from "@paperclipai/shared"; export interface LinkPreviewScope { companyId: string; userId: string | null } @@ -9,22 +10,49 @@ export interface LinkPreviewProvider { const UNAVAILABLE: LinkPreviewResult = { preview: null, maxAgeMs: 60_000 }; -/** Request-driven and process-local. No DB writes, sweep, timers while idle, or cross-viewer reuse. */ +/** Request-driven cache: durable across restarts, isolated by viewer, with no idle worker. */ export function createLinkPreviewService(providers: readonly LinkPreviewProvider[], options: { - now?: () => number; timeoutMs?: number; maxEntries?: number; maxConcurrent?: number; + store?: LinkPreviewStore; now?: () => number; timeoutMs?: number; maxEntries?: number; maxConcurrent?: number; } = {}) { const now = options.now ?? Date.now; - const cache = new Map(); + const cache = new Map(); const inFlight = new Map>(); let activeOperations = 0; const byKey = new Map(providers.map(provider => [provider.key, provider])); + function remember(key: string, entry: StoredLinkPreview) { + if ((cache.get(key)?.checkedAt ?? -Infinity) > entry.checkedAt) return; + cache.delete(key); + while (cache.size >= (options.maxEntries ?? 1_000)) cache.delete(cache.keys().next().value!); + cache.set(key, entry); + } + const keyOf = (scope: LinkPreviewScope, url: string) => JSON.stringify([scope.companyId, scope.userId, url]); + const remaining = (entry: StoredLinkPreview) => ({ ...entry.result, maxAgeMs: Math.max(0, entry.expiresAt - now()) }); + const newest = (memory: StoredLinkPreview | undefined, stored: StoredLinkPreview | undefined) => + stored && (!memory || stored.checkedAt >= memory.checkedAt) ? stored : memory; + return { + async cached(scope: LinkPreviewScope, hrefs: readonly string[]) { + const targets = [...new Map(hrefs.map(recognizeLinkPreview).filter(target => target && byKey.has(target.provider)) + .map(target => [target!.canonicalUrl, target!])).values()]; + const stored = await options.store?.read(scope, targets).catch(() => new Map()); + const results: Record = {}; + for (const target of targets) { + const key = keyOf(scope, target.canonicalUrl); + const memory = cache.get(key); + const entry = newest(memory, stored?.get(target.canonicalUrl)); + if (entry) { remember(key, entry); results[target.canonicalUrl] = remaining(entry); } + // A batch miss is not a provider result. A later lookup must still + // check durable storage, which another replica may have populated. + else cache.delete(key); + } + return { results }; + }, async get(scope: LinkPreviewScope, href: string): Promise { const target = recognizeLinkPreview(href); const provider = target && byKey.get(target.provider); if (!target || !provider) return UNAVAILABLE; - const key = JSON.stringify([scope.companyId, scope.userId, target.canonicalUrl]); + const key = keyOf(scope, target.canonicalUrl); const cached = cache.get(key); if (cached && cached.expiresAt > now()) { return { ...cached.result, maxAgeMs: cached.expiresAt - now() }; @@ -35,20 +63,74 @@ export function createLinkPreviewService(providers: readonly LinkPreviewProvider const controller = new AbortController(); let timer: ReturnType; + let previous = cached; + const checkedAt = now(); + let providerStarted = false; + let storeWriteStarted = false; + let durableReadSucceeded = !options.store; + let timeoutWrite: Promise | undefined; + const fallback = (): LinkPreviewResult => ({ preview: newest(previous, cache.get(key))?.result.preview ?? null, maxAgeMs: 60_000 }); const deadline = new Promise(resolve => { - timer = setTimeout(() => { controller.abort(); resolve(UNAVAILABLE); }, options.timeoutMs ?? 5_000); + timer = setTimeout(() => { + const current = cache.get(key); + if (current && current.checkedAt > checkedAt) { + controller.abort(); + resolve(remaining(current)); + return; + } + const result = current && current.expiresAt > now() ? remaining(current) : fallback(); + const entry = { result, expiresAt: now() + result.maxAgeMs, + checkedAt: durableReadSucceeded || storeWriteStarted ? checkedAt : previous?.checkedAt ?? 0 }; + remember(key, entry); + // Publish timeout freshness without delaying the caller. The lookup + // keeps its slot until both the provider and this write settle. + if (options.store && durableReadSucceeded && providerStarted && !storeWriteStarted) { + timeoutWrite = Promise.resolve().then(() => options.store!.write(scope, target, entry, checkedAt)).catch(() => {}); + } + controller.abort(); + resolve(result); + }, options.timeoutMs ?? 5_000); }); - // Keep an underlying operation in the concurrency budget until it settles, - // even if a credential backend ignores cancellation after our deadline. + // All underlying work, including uncancellable SQL, retains its slot until + // settlement. The caller's deadline does not release the resource budget. activeOperations++; - const operation = Promise.resolve().then(() => provider.resolve(target, scope, controller.signal)) - .catch(() => UNAVAILABLE).finally(() => { activeOperations--; }); - const request = Promise.race([operation, deadline]).then(result => { + const operation = Promise.resolve().then(async () => { + if (options.store) { + // Fresh memory returned above. Expired memory is only a fallback: + // another replica may have saved a newer result, even with a shorter TTL. + const stored = await options.store.read(scope, [target]).catch(() => null); + durableReadSucceeded = stored !== null; + previous = newest(newest(previous, cache.get(key)), stored?.get(target.canonicalUrl)); + if (!controller.signal.aborted && previous) remember(key, previous); + } + if (controller.signal.aborted) return fallback(); + if (previous && previous.expiresAt > now()) { remember(key, previous); return remaining(previous); } + providerStarted = true; + const result = await provider.resolve(target, scope, controller.signal).catch(() => UNAVAILABLE); + if (controller.signal.aborted) return fallback(); + // A page batch can hydrate another replica's newer status while the + // provider is pending. That result wins over this older lookup. + previous = newest(previous, cache.get(key)); + if (previous && previous.checkedAt > checkedAt) return remaining(previous); const bounded = { ...result, maxAgeMs: Math.max(1_000, Math.min(result.maxAgeMs, 60 * 60_000)) }; - cache.delete(key); - while (cache.size >= (options.maxEntries ?? 1_000)) cache.delete(cache.keys().next().value!); - cache.set(key, { result: bounded, expiresAt: now() + bounded.maxAgeMs }); - return bounded; + if (!bounded.preview && previous?.result.preview) bounded.preview = previous.result.preview; + const entry = { result: bounded, expiresAt: now() + bounded.maxAgeMs, + checkedAt: durableReadSucceeded || result.preview ? checkedAt : previous?.checkedAt ?? 0 }; + remember(key, entry); + // A failed durable read cannot establish which saved status a provider + // failure would replace. Keep that backoff local until storage recovers. + if (options.store && (durableReadSucceeded || result.preview)) { + storeWriteStarted = true; + await options.store.write(scope, target, entry, checkedAt).catch(() => {}); + } + return remaining(entry); + }).catch(fallback).finally(async () => { await timeoutWrite; activeOperations--; }); + const request = Promise.race([operation, deadline]).then(result => { + const current = cache.get(key); + // Hydration can also finish while the operation awaits its SQL write. + if (current && current.checkedAt > checkedAt) return remaining(current); + if (!current || current.expiresAt <= now()) remember(key, { result, expiresAt: now() + result.maxAgeMs, checkedAt }); + return result; }).finally(() => { clearTimeout(timer!); if (inFlight.get(key) === request) inFlight.delete(key); diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index e738504dd06..6d024d3da2b 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -268,7 +268,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "efab7ad18d89a60ddd3f961e35060b68424ef40b", + "packages/shared/src/index.ts": "825867d65bbb0783a2294e1838231e68669a8fc3", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", @@ -282,7 +282,7 @@ "packages/shared/src/issue-write-denial.test.ts": "e21b93aa79e6635c019ac338eff954ec618a98ed", "packages/shared/src/issue-write-denial.ts": "e6b4d72a83f6e4e76e85e34a80f88d1d69b7dfe4", "packages/shared/src/link-preview.test.ts": "136041c928343ad6272f43701b39cf95be255f3e", - "packages/shared/src/link-preview.ts": "ffa5eb960a7e4bcfa914b4d6029c9fc50f17e027", + "packages/shared/src/link-preview.ts": "b7431d4c30a12067e80e6806728b3ae7c7541f8f", "packages/shared/src/markdown-work-products.test.ts": "7293d14ad45ec2b11b5deaab4ce070c36f7c9010", "packages/shared/src/markdown-work-products.ts": "16a88cfb717f325c247a516e78b47d53871b52ed", "packages/shared/src/mcp-apps.test.ts": "848f3247bdc98af398daa144b0e44991a3f352b3", diff --git a/tests/storybook-visual/link-previews.spec.ts b/tests/storybook-visual/link-previews.spec.ts index 7d21fb31252..4e70349f802 100644 --- a/tests/storybook-visual/link-previews.spec.ts +++ b/tests/storybook-visual/link-previews.spec.ts @@ -167,3 +167,54 @@ for (const available of [true, false]) { await expect(links.nth(1)).toHaveAttribute("data-link-state", available ? "open" : "unknown"); }); } + +test("page load restores stored status and refreshes stale data on idle without hover", async ({ page }, testInfo) => { + const errors: string[] = []; + page.on("pageerror", error => errors.push(error.message)); + await page.addInitScript(() => { + const realFetch = window.fetch.bind(window); + let activeFetch = realFetch; + Object.defineProperty(window, "fetch", { + configurable: true, get: () => activeFetch, + set: (fixtureFetch: typeof fetch) => { + activeFetch = (input, init) => { + const url = input instanceof Request ? input.url : String(input); + return url.includes("/link-preview?") || url.includes("/link-previews/cached") ? realFetch(input, init) : fixtureFetch(input, init); + }; + }, + }); + }); + const canonicalUrl = "https://github.com/acme/web/pull/241"; + const preview = { target: { provider: "github", kind: "pull_request", canonicalUrl, label: "acme/web#241" }, + title: "Status from the database", state: "merged", author: "octocat", updatedAt: null }; + let cached = 0, resolved = 0; + let release!: () => void; + const refresh = new Promise(done => { release = done; }); + await page.route("**/api/companies/company-storybook/link-previews/cached?*", async route => { + cached++; + expect(new URL(route.request().url()).searchParams.getAll("url")).toEqual([canonicalUrl]); + await route.fulfill({ json: { results: { [canonicalUrl]: { preview, maxAgeMs: 0 } } } }); + }); + await page.route("**/api/companies/company-storybook/link-preview?*", async route => { + resolved++; + await refresh; + await route.fulfill({ json: { preview: { ...preview, state: "closed" }, maxAgeMs: 60_000 } }); + }); + await page.goto("/iframe.html?id=tasks-link-previews--page-load&viewMode=story&globals=theme:dark"); + await finished(page); + const links = page.locator("a[data-link-state]"); + await expect(links).toHaveCount(2); + await expect(links.first()).toHaveAttribute("data-link-state", "merged"); + await expect(links.last()).toHaveAttribute("data-link-state", "merged"); + await expect(page.getByRole("tooltip")).toHaveCount(0); + await expect.poll(() => resolved).toBe(1); + expect(cached).toBe(1); + release(); + await expect(links.first()).toHaveAttribute("data-link-state", "closed"); + await expect(links.last()).toHaveAttribute("data-link-state", "closed"); + await links.first().focus(); + await expect(page.getByRole("tooltip")).toBeVisible(); + expect(resolved).toBe(1); + await page.screenshot({ path: testInfo.outputPath("pr-status-from-database-after-idle.png"), fullPage: true }); + expect(errors).toEqual([]); +}); diff --git a/ui/src/components/LinkPreview.tsx b/ui/src/components/LinkPreview.tsx index e2c12e40c5f..d505edc10b7 100644 --- a/ui/src/components/LinkPreview.tsx +++ b/ui/src/components/LinkPreview.tsx @@ -1,12 +1,11 @@ -import { useId, useMemo, useRef, useState, type ReactElement } from "react"; +import { useEffect, useId, useMemo, useRef, useState, type ReactElement } from "react"; import { useQuery } from "@tanstack/react-query"; import { PreviewCard } from "@base-ui/react/preview-card"; import { GitMerge, GitPullRequest, GitPullRequestClosed, GitPullRequestDraft, TriangleAlert } from "lucide-react"; import type { LinkPreview as Preview, LinkPreviewResult, LinkPreviewState, LinkPreviewTarget } from "@paperclipai/shared"; import { useLinkPreviewContext, type LinkPreviewContextValue } from "@/context/LinkPreviewContext"; import { timeAgo } from "@/lib/timeAgo"; -import { retryTransientOnly } from "@/lib/query-client"; -import { queryKeys } from "@/lib/queryKeys"; +import { linkPreviewQueryOptions } from "@/lib/link-preview-query"; export const linkPreviewStateLabel: Record = { unknown: "Status unknown", open: "Open", merged: "Merged", conflicts: "Merge conflicts", draft: "Draft", closed: "Closed", @@ -18,13 +17,13 @@ export const linkPreviewStateIcon = { function PreviewCardContents({ target, preview, loading }: { target: LinkPreviewTarget; preview?: Preview | null; loading: boolean }) { const state = preview?.state ?? "unknown"; - const Icon = linkPreviewStateIcon[state]; + const Icon = linkPreviewStateIcon[state] ?? linkPreviewStateIcon.unknown; const updated = preview?.updatedAt && Number.isFinite(Date.parse(preview.updatedAt)) ? preview.updatedAt : null; return
{preview ? <>

{preview.title}

@@ -50,17 +49,8 @@ function ConnectedLinkPreview({ context, target, children }: { getBoundingClientRect: () => triggerRef.current?.getClientRects()[0] ?? new DOMRect(), get contextElement() { return triggerRef.current ?? undefined; }, }), []); - const query = useQuery({ - queryKey: queryKeys.linkPreview(context.companyId, context.userId, target.canonicalUrl), - // Optional enrichment: a failed read is a cached absence, not a global error. - queryFn: async (): Promise => { - try { return await context.load(target); } catch { return { preview: null, maxAgeMs: 60_000 }; } - }, - enabled: open, - staleTime: query => query.state.data?.maxAgeMs ?? 60_000, - gcTime: 5 * 60_000, - retry: retryTransientOnly(0), refetchOnMount: false, refetchOnWindowFocus: false, refetchOnReconnect: false, - }); + useEffect(() => context.register?.(target), [context, target.canonicalUrl]); + const query = useQuery({ ...linkPreviewQueryOptions(context, target), enabled: open }); return setOpen(true)} onBlur={() => setOpen(false)} diff --git a/ui/src/components/MarkdownUrlLink.tsx b/ui/src/components/MarkdownUrlLink.tsx index 43316bb1d80..e8787de22bf 100644 --- a/ui/src/components/MarkdownUrlLink.tsx +++ b/ui/src/components/MarkdownUrlLink.tsx @@ -57,7 +57,7 @@ export function MarkdownUrlLink({ href, children, title, style, knownState, exte const label = github?.label ? compactUrlLabel(children, href, github.label) : children; const target = recognizeLinkPreview(href); const render = (state: LinkPreviewState = knownState ?? "unknown", describedBy?: string, preview?: Preview | null) => { - const StateIcon = target ? linkPreviewStateIcon[state] : Icon; + const StateIcon = target ? linkPreviewStateIcon[state] ?? linkPreviewStateIcon.unknown : Icon; const leadingIcon = github ?