From a94881d1a71b1e24a7990c01699a9e9b8cc5b16e Mon Sep 17 00:00:00 2001
From: Dotta <34892728+cryppadotta@users.noreply.github.com>
Date: Sat, 7 Nov 2026 08:54:14 -0600
Subject: [PATCH 01/24] fix(heartbeat): save a comment refused by a temporary
hold and route post-quarantine input to its own gate (#19829)
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
> - A user's follow-up comment or Retry must be delivered once,
eventually, even when a temporary company admission hold (accounting
still settling) is active
> - #19741 kept claimed runs queued through such a hold and woke held
work when it cleared
> - A restart-chaos wave still lost a comment, because its wake was
refused before admission and written as a terminal skip
> - The same wave left a Retry waiting forever for a stop record of a
process that never existed
> - This pull request saves the refused comment as a deferred receipt,
and routes input after a pre-launch quarantine failure to the
quarantine's own gate
> - The benefit is that the comment is delivered after the hold, and the
task asks for the action that actually unblocks it instead of offering a
Retry that can never start
## Linked Issues or Issue Description
Refs #19741 and #19702.
**What happened?**
In a restart-chaos wave, a failed run's accounting held the company for
600 s.
1. A user commented while the task's run was live. The enqueue budget
gate refused the comment's wake before it reached the deferral behind
the live run. Because it was a user request with no saved receipt, it
was written as `skipped` (`budget.blocked`). The live run finished
without it and the task ended `done`, so the comment was lost.
2. A Retry created a run that the native cleanup-quarantine fence
refused before it requested any runner launch
(`native_session_cleanup_quarantined`, no process events). A second
Retry then waited with `process_identity_missing` ("The previous run has
no verified stop record") for a process that never existed. The task
kept offering Retry, and that Retry could never start.
**Expected behavior**
A comment refused by a temporary hold stays saved and is delivered once
later. Input after a run that was refused before launch is handled by
the quarantine gate: Retry is not offered (send a new message), and a
new message gets the verified-stop check of the previous provider
session.
## What Changed
- `heartbeat/queue.ts`: when the enqueue budget gate refuses a user's
comment wake and the block is temporary (not a reached hard stop, per
`isBoardOwnedBudgetBlock`), the wake is saved as a
`deferred_issue_execution` receipt. The receipt carries the comment ids
and an `executionWait` of `budget.blocked`, and the gate notifies the
deferred-receipt worker and throws `PersistedExecutionWaitRefusal`. It
is not written as `skipped`. Normal promotion (when the live run ends)
and #19741's hold-release wakeups deliver it.
- `native-local-process-stop.ts`: new `nativeRunRefusedBeforeLaunch`. It
returns true for a failed native run with
`native_session_cleanup_quarantined`, no recorded process, and no
launch-request or identity event.
- `explicit-native-continuation.ts`: such a run passes the
process-identity check, so the existing quarantine branch decides. A
Retry gets `cleanup_quarantined` (shown with `canRetry: false` and "send
a new message"). A new message gets
`verifyStoppedNativeSessionForContinuation`. Any launch request or
identity record keeps the original stop proofs.
- `native-session-executor.ts`
(`verifyStoppedNativeSessionForContinuation`): when the source has no
process record and no launch event, the verifier relies on the previous
owner's stop evidence. Before this change it required the source to
share the owner's process identity, so a new message stayed held even
after the owner stopped. A source that carries a process identity must
still match the owner exactly.
## Verification
Each new test fails on `master` and passes with this change, on embedded
Postgres:
- `server/src/__tests__/heartbeat-held-comment-wake.test.ts`: a comment
whose wake the hold refuses at enqueue is saved with a `budget.blocked`
wait and is not skipped. It is delivered exactly once after accounting
settles.
- `server/src/services/explicit-native-continuation.test.ts`:
- A run refused by the quarantine before launch routes a new message to
the quarantine's stop verification and a Retry to `cleanup_quarantined`.
These failed on `master` with `process_identity_missing`.
- Guards (green on both): a quarantined run that requested a launch, and
another failure without a process record, still require
`process_identity_missing`.
- `server/src/services/quarantined-task-retry.test.ts`: a never-launched
quarantined source is certified once the previous owner has stopped (red
on `master`). It stays held if the source requested a launch or the
owner is still running. All 31 tests pass, and the `stopped native
conversation physical cleanup` suite passes (46).
- Related suites pass locally (6 files, 620 tests): explicit native
continuation, held comment wake, queued comments routes, comment wake
batching, refused assignment wake, deferred receipt work. Two
`deferred-execution-receipt-work` tests failed once under parallel load
and passed when run alone.
## Risks
- The saved-comment path applies only to user comment wakes refused by a
temporary budget hold. Hard stops, system wakes, case handoffs, durable
chat requests, and existing saved receipts are unchanged.
- The pre-launch rule is limited to the quarantine failure code with no
launch evidence. Every other missing process identity still requires the
existing stop proof.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, run as an agent in
Claude Code with tool use (shell, file editing, local test execution,
kept restart-chaos instance inspection).
## 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
---
.../heartbeat-held-comment-wake.test.ts | 27 +++++++++++++++++++
.../explicit-native-continuation.test.ts | 26 ++++++++++++++++++
.../services/explicit-native-continuation.ts | 3 ++-
server/src/services/heartbeat/queue.ts | 25 +++++++++++++++++
.../src/services/native-local-process-stop.ts | 15 +++++++++++
.../native-runtime/native-session-executor.ts | 11 +++++---
.../services/quarantined-task-retry.test.ts | 25 +++++++++++++++++
7 files changed, 128 insertions(+), 4 deletions(-)
diff --git a/server/src/__tests__/heartbeat-held-comment-wake.test.ts b/server/src/__tests__/heartbeat-held-comment-wake.test.ts
index 31b747e9c24..8f57d676e30 100644
--- a/server/src/__tests__/heartbeat-held-comment-wake.test.ts
+++ b/server/src/__tests__/heartbeat-held-comment-wake.test.ts
@@ -148,6 +148,33 @@ describePostgres("a promoted comment refused by a temporary admission hold", ()
expect(deliveries(f.commentId)).toHaveLength(1);
}, 180_000);
+ it("saves a comment whose wake the hold refuses at enqueue and delivers it once after the hold clears", async () => {
+ // s7532/t06: the comment arrived during the hold; its wake was refused
+ // before admission and written as a terminal skip, so it was lost.
+ const f = await seedHeldComment();
+ await db.update(agentWakeupRequests).set({ status: "cancelled", finishedAt: new Date() }).where(eq(agentWakeupRequests.id, f.wakeId));
+ const [comment] = await db.insert(issueComments).values({ companyId: f.companyId, issueId: f.issueId,
+ authorUserId: f.userId, body: "Posted during the hold." }).returning();
+ await expect(heartbeat.wakeup(f.agentId, { source: "automation", triggerDetail: "system", reason: "issue_commented",
+ payload: { issueId: f.issueId, commentId: comment.id, mutation: "comment" },
+ contextSnapshot: { issueId: f.issueId, taskId: f.issueId, commentId: comment.id, wakeCommentId: comment.id,
+ source: "issue.comment", wakeReason: "issue_commented" },
+ requestedByActorType: "user", requestedByActorId: f.userId })).rejects.toThrow(/await accounting/);
+ const saved = (await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId)))
+ .filter(wake => (wake.payload as { commentId?: string }).commentId === comment.id);
+ expect(saved).toEqual([expect.objectContaining({ status: "deferred_issue_execution", runId: null,
+ payload: expect.objectContaining({ executionWait: expect.objectContaining({ reason: "budget.blocked" }) }) })]);
+ await settle(f);
+ expect(deliveries(comment.id)).toHaveLength(0);
+
+ await settleAccounting(f);
+ await db.update(agentWakeupRequests).set({ updatedAt: new Date(Date.now() - 60_000) }).where(eq(agentWakeupRequests.id, saved[0].id));
+ await settle(f); await settle(f);
+ expect(deliveries(comment.id)).toHaveLength(1);
+ await settle(f);
+ expect(deliveries(comment.id)).toHaveLength(1);
+ }, 180_000);
+
it("keeps a Retry clicked during the hold pending and starts it exactly once after the hold clears", async () => {
const f = await seedHeldComment();
// The run the user retries failed; its saved comment was already discarded.
diff --git a/server/src/services/explicit-native-continuation.test.ts b/server/src/services/explicit-native-continuation.test.ts
index 376e00aac93..a1782ae298c 100644
--- a/server/src/services/explicit-native-continuation.test.ts
+++ b/server/src/services/explicit-native-continuation.test.ts
@@ -94,6 +94,32 @@ const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTes
onBlocked: reason => blocked.push(reason) });
return { result, blocked, reads };
}
+ it.each([
+ { shape: "refused by the cleanup quarantine before launch", errorCode: "native_session_cleanup_quarantined", launched: false,
+ comment: "local_cleanup", retry: "cleanup_quarantined" },
+ { shape: "quarantined after it requested a launch", errorCode: "native_session_cleanup_quarantined", launched: true,
+ comment: "process_identity_missing", retry: "process_identity_missing" },
+ { shape: "failed for another reason without a process record", errorCode: "adapter_failed", launched: false,
+ comment: "process_identity_missing", retry: "process_identity_missing" },
+ ])("routes input after a run $shape to the gate that can clear it", async ({ errorCode, launched, comment, retry }) => {
+ // s7532/t04: a Retry's run failed at the quarantine fence before it asked
+ // for a runner. Input then waited for a stop record of a process that
+ // never existed ("process_identity_missing", Retry still offered) instead
+ // of the quarantine's own gate, which names the action that clears it.
+ const f = await seed();
+ await db.update(heartbeatRuns).set({ processPid: null, errorCode }).where(eq(heartbeatRuns.id, f.sourceRunId));
+ if (launched) await db.insert(heartbeatRunEvents).values({ companyId: f.companyId, runId: f.sourceRunId, agentId: f.agentId,
+ seq: 1, eventType: "native.process_start_requested", stream: "system", level: "info", message: "launch requested",
+ payload: { hostname: "another-host" } });
+ const { result, blocked } = await readAdmission(f, false);
+ expect(result).toBeNull();
+ expect(blocked).toEqual([comment]);
+ const retryBlocked: string[] = [];
+ expect(await admitExplicitNativeContinuation({ ...f, db, dryRun: true, reason: "retry_failed_run",
+ failedRunId: f.sourceRunId, onBlocked: reason => retryBlocked.push(reason) })).toBeNull();
+ expect(retryBlocked).toEqual([retry]);
+ });
+
it("keeps admission and the complete locked session profile while omitting prompt data", async () => {
const f = await seed();
const payload = randomBytes(128 * 1024).toString("base64");
diff --git a/server/src/services/explicit-native-continuation.ts b/server/src/services/explicit-native-continuation.ts
index d96797f44e9..d48da1101de 100644
--- a/server/src/services/explicit-native-continuation.ts
+++ b/server/src/services/explicit-native-continuation.ts
@@ -16,7 +16,7 @@ import { appendHeartbeatRunEvent } from "./heartbeat-run-events.js";
import { canContinueCancelledRun, userStopBoundaryAt } from "./run-cancellation.js";
import { readQueuedInteractionResponse } from "./queued-interaction-response.js";
import { isCancelledNativeStartup, isFailedNativePreparation, isFailedNativePreparationRetryAncestor } from "./cancelled-native-startup.js";
-import { hasNativeLocalProcessStop, hasHistoricalSuspendedNativeSession, recordedLocalExecutionStopped, recordUnidentifiedLocalRunnerStop } from "./native-local-process-stop.js";
+import { hasNativeLocalProcessStop, hasHistoricalSuspendedNativeSession, nativeRunRefusedBeforeLaunch, recordedLocalExecutionStopped, recordUnidentifiedLocalRunnerStop } from "./native-local-process-stop.js";
import { completeTerminatedRemoteNativeSessionCleanup, nativeSessionCleanupBlock } from "../vendor/paperclip-runner/index.js";
import { hasRecoveredCleanupStopReceipt, hasRemoteTerminationReceipt, remoteLeaseCleanupScope } from "./remote-execution-termination.js";
import { z } from "zod";
@@ -508,6 +508,7 @@ export async function admitExplicitNativeContinuation(input: {
if (!run.processPid && !run.processGroupId &&
!await hasNativeLocalProcessStop(db, companyId, run.id) &&
!await hasHistoricalSuspendedNativeSession(db, run) &&
+ !await nativeRunRefusedBeforeLaunch(db, run) &&
!(run.runtimeMode === "native" &&
await recordUnidentifiedLocalRunnerStop(db, run, { record: !input.dryRun }))) return blocked("process_identity_missing", "The previous run has no verified stop record. Paperclip cannot start this message yet.");
if (run.processPid && !processStopped(run.processPid)) return blocked("process_running", "Waiting for the previous process to stop. Your message will start automatically.");
diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts
index d5f85b0794e..8acb6924cf7 100644
--- a/server/src/services/heartbeat/queue.ts
+++ b/server/src/services/heartbeat/queue.ts
@@ -2729,6 +2729,31 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
},
);
if (budgetBlock) {
+ // A user's message refused by a temporary hold (accounting still settling)
+ // is saved as a deferred receipt, not skipped. It is promoted through
+ // normal admission once the run it waits behind ends or the hold clears.
+ if (!executionWaitRequestId && !caseRequest && !durableRequest && issueId && isUuidLike(issueId) &&
+ opts.requestedByActorType === "user" && wakeCommentId &&
+ !(await isBoardOwnedBudgetBlock(db, agent.companyId, budgetBlock))) {
+ const savedIssueId = issueId;
+ const condition = { reason: "budget.blocked", message: `${budgetBlock.reason} Your message is saved.`,
+ scopeType: budgetBlock.scopeType, scopeId: budgetBlock.scopeId };
+ await db.transaction(async tx => {
+ await tx.execute(sql`select id from issues where id = ${savedIssueId} and company_id = ${agent.companyId} for update`);
+ await notifyDeferredExecutionWork(tx, { companyId: agent.companyId });
+ await tx.insert(agentWakeupRequests).values({
+ companyId: agent.companyId, agentId, source, triggerDetail, reason,
+ payload: withQueuedCommentIdsInWakePayload({
+ ...payload, issueId: savedIssueId, [DEFERRED_WAKE_CONTEXT_KEY]: enrichedContextSnapshot, executionWait: condition,
+ }, [...new Set([...queuedCommentIdsFromRunContext(enrichedContextSnapshot), wakeCommentId])]),
+ status: "deferred_issue_execution",
+ requestedByActorType: opts.requestedByActorType ?? null,
+ requestedByActorId: opts.requestedByActorId ?? null,
+ idempotencyKey: opts.idempotencyKey ?? null,
+ });
+ });
+ throw new PersistedExecutionWaitRefusal(budgetBlock.reason, { scopeType: budgetBlock.scopeType, scopeId: budgetBlock.scopeId });
+ }
const wait = await writeSkippedRequest("budget.blocked", { error: budgetBlock.reason }, {
scopeType: budgetBlock.scopeType, scopeId: budgetBlock.scopeId,
});
diff --git a/server/src/services/native-local-process-stop.ts b/server/src/services/native-local-process-stop.ts
index 70731d14533..5999ea523b6 100644
--- a/server/src/services/native-local-process-stop.ts
+++ b/server/src/services/native-local-process-stop.ts
@@ -134,6 +134,21 @@ export async function recordUnidentifiedLocalRunnerStop(db: Db, run: Pick): Promise {
+ if (run.runtimeMode !== "native" || run.status !== "failed" || run.processPid || run.processGroupId ||
+ run.errorCode !== "native_session_cleanup_quarantined") return false;
+ const [launch] = await db.select({ id: heartbeatRunEvents.id }).from(heartbeatRunEvents).where(and(
+ eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id),
+ inArray(heartbeatRunEvents.eventType, [PROCESS_START_REQUESTED, PROCESS_IDENTITY_RECORDED]),
+ )).limit(1);
+ return !launch;
+}
+
/** Pre-receipt native runs can retain an exact suspended session after their
* mutable process fields were cleared. This is admission evidence for a new
* user turn only, never permission to replay the old run or infer its outcomes.
diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts
index 19e6a761dd5..e3b0d16f6ab 100644
--- a/server/src/services/native-runtime/native-session-executor.ts
+++ b/server/src/services/native-runtime/native-session-executor.ts
@@ -3145,9 +3145,14 @@ export async function verifyStoppedNativeSessionForContinuation(
!["succeeded", "failed", "cancelled", "interrupted", "timed_out"].includes(retained.status) ||
!retained.finishedAt || retained.finishedAt > run.createdAt ||
retained.controllerLeaseExpiresAt && retained.controllerLeaseExpiresAt > new Date() ||
- !retained.processStartedAt || !run.processStartedAt ||
- retained.processStartedAt.getTime() !== run.processStartedAt.getTime() ||
- retained.processPid !== run.processPid || retained.processGroupId !== run.processGroupId) return null;
+ // A run refused before launch (no launch event, checked above) and
+ // with no process record owns no process: only the previous owner's
+ // stop evidence below can certify the session. A source that does
+ // carry a process identity must still match the owner's exactly.
+ (run.processPid || run.processGroupId || run.processStartedAt) &&
+ (!retained.processStartedAt || !run.processStartedAt ||
+ retained.processStartedAt.getTime() !== run.processStartedAt.getTime() ||
+ retained.processPid !== run.processPid || retained.processGroupId !== run.processGroupId)) return null;
const [coordinator] = await db.select().from(nativeRunFinalizations).where(and(
eq(nativeRunFinalizations.companyId, run.companyId), eq(nativeRunFinalizations.issueId, run.nativeIssueId),
eq(nativeRunFinalizations.runId, retained.id),
diff --git a/server/src/services/quarantined-task-retry.test.ts b/server/src/services/quarantined-task-retry.test.ts
index 8a02a628709..f08669a6e84 100644
--- a/server/src/services/quarantined-task-retry.test.ts
+++ b/server/src/services/quarantined-task-retry.test.ts
@@ -244,6 +244,31 @@ describe("task Retry after inherited native cleanup quarantine", () => {
}
});
+ it.each(["stopped", "source_launch_requested", "owner_running"])(
+ "certifies a quarantined source that never launched from the previous owner's stop (%s)", async mode => {
+ // s7532/t04: the quarantine fence refused the source before it asked for
+ // a runner, so it has no process record at all. Only the owner can prove
+ // the retained session stopped.
+ const base = await mkdtemp(join(tmpdir(), "quarantined-never-launched-"));
+ const previous = process.env.PAPERCLIP_RUNNER_STATE_DIR;
+ process.env.PAPERCLIP_RUNNER_STATE_DIR = base;
+ try {
+ const f = await seed(base);
+ await db.update(heartbeatRuns).set({ processPid: null, processGroupId: null, processStartedAt: null })
+ .where(eq(heartbeatRuns.id, f.sourceId));
+ if (mode === "source_launch_requested") await appendHeartbeatRunEvent(db, {
+ companyId: f.companyId, runId: f.sourceId, agentId: f.agentId, eventType: PROCESS_START_REQUESTED });
+ if (mode === "owner_running") await db.update(heartbeatRuns).set({ status: "running", finishedAt: null }).where(eq(heartbeatRuns.id, f.ownerId));
+ const [source] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.sourceId));
+ const proof = await verifyStoppedNativeSessionForContinuation(db, source);
+ if (mode === "stopped") expect(proof).not.toBeNull();
+ else expect(proof).toBeNull();
+ } finally {
+ if (previous === undefined) delete process.env.PAPERCLIP_RUNNER_STATE_DIR; else process.env.PAPERCLIP_RUNNER_STATE_DIR = previous;
+ await rm(base, { recursive: true, force: true });
+ }
+ });
+
it("holds a Retry while the task's own provider session close is still retained, then starts it", async () => {
const base = await mkdtemp(join(tmpdir(), "retained-close-retry-"));
const previous = process.env.PAPERCLIP_RUNNER_STATE_DIR;
From 061c84d280c2893e89506972068e6a7e8e057ab6 Mon Sep 17 00:00:00 2001
From: Dotta <34892728+cryppadotta@users.noreply.github.com>
Date: Sat, 7 Nov 2026 08:57:39 -0600
Subject: [PATCH 02/24] fix: preserve local copies behind settled remote
recovery holds (#19830)
## Thinking Path
> - Paperclip manages AI agents and the work they save.
> - Online migration must save legacy local files while other remote
work continues.
> - A failed native run can retain a remote recovery hold after its
local writer has settled.
> - The current source proof recognizes only some of those recovery
producers.
> - This blocks stable local files and their shared Git aliases behind
an interrupted session or exhausted export recovery.
> - This change admits two exact producer shapes under the existing
physical and task locks.
> - It preserves the failed run, accepted result, remote hold, retained
allocations, and recovery history.
## Linked Issues or Issue Description
Refs #19642, #19688, #19810. A public search found these related
changes. This is a narrow correction to their local preservation proof.
**What happened?**
Online workspace import rejects a stable local source with
`online_workspace_source_scope_unproven` when its prepared native source
has an ambiguous session interruption hold or an exhausted file recovery
hold. Shared Git aliases inherit the refusal.
**Expected behavior**
Save the stable local copy under the existing source locks. Keep remote
recovery blocked until its own recovery owner supplies the required
evidence.
**Steps to reproduce**
1. Create a failed native run with an unowned terminal finalizer and an
exact prepared allocation.
2. Keep either its board-owned interrupted-session failure block or its
exhausted system recovery and blocked file recovery with an accepted
result.
3. Import the local Git source or a shared alias through
`migrateRemoteWorkspace`.
4. Before this change, both actual importer tests reject the source.
With this change, both save and restore its files while retaining the
hold.
**Paperclip version or commit**
Reproduced on master at `b2af45f0f1` with local PostgreSQL 18.1 on macOS
arm64 and Node 26.4.0.
## What Changed
- Reuse the exact prepared-source failure proof for ambiguous native
session interruptions.
- Admit an exhausted export hold only with its exact run, blocked task,
unowned finalizer, accepted result, original allocation, and current
recovery receipts.
- Bind the complete accepted result into the publication fingerprint.
Keep the existing source, alias, Git, finalizer, and task locks.
- Add real importer, authenticated restore, refusal, and
publication-race controls. Document the separate local and remote
obligations.
## Verification
- Baseline: the exhausted-export importer case failed at
`remote_workspace_migration_blocked:online_workspace_source_scope_unproven`.
- Review found that the first interruption fixture used the
artifact-failure resume mode. The corrected fixture reads
`nativeProviderRecoveryEvidence` and `nativeSessionFailureDisposition`.
Its canonical ambiguous interruption case failed at the source guard
before the cause-specific mode repair.
- Fresh recorded metadata then showed that an interrupted source can
have a boolean `providerSessionEstablished: false`. The final fixture
derives that exact false+ambiguous state from a checkpoint without a
provider identity or provider events. It failed against the intermediate
shared-true guard. The final cause-specific proof passes it. The
artifact-failure case still requires true+exact mode.
- Both importer cases remove the originals and restore saved files
through the real encrypted snapshot owner. They keep the failed run
status, native source reference, result bytes, tasks, recovery actions,
retained allocations, and unrelated active remote work unchanged. The
existing migration owner adds only its local source recipe.
- Final affected PostgreSQL suites: **107/107 passed**, 74.44 seconds,
canonical shared PostgreSQL wrapper with one worker and cleanup
complete. Controls reject the wrong interruption mode, a string session
flag, unreleased owners, active controllers, stale fingerprints, changed
allocations, changed recovery state, and changes during upload. Command
from `server`: `node ../cli/node_modules/tsx/dist/cli.mjs
../packages/db/src/test-postgres-command.ts -- node
../node_modules/vitest/vitest.mjs run
src/services/remote-workspace-online-source.test.ts
src/services/online-legacy-workspace-recovery.test.ts --fsModuleCache
--maxWorkers=1 --hookTimeout=90000`.
- Final server source and all test typecheck layers passed. Module
boundary check and `git diff --check` passed.
- A first setup attempt could not load the unbuilt plugin SDK and ran
zero tests. Building the SDK corrected the setup. An unchanged-baseline
run repeated source refusals after a local edit used the wrong path. The
first 105-case and 106-case passes predate the final producer correction
and are superseded by the 107-case pass. Earlier failures and passes are
retained separately.
- A read-only probe loaded the exact committed proposed inspection code
against three current stored holds in one repeatable-read snapshot. All
three passed the actual function. It verified the owned accepted result
and both interruption fields without changing source or provider state.
This is applicability proof; an import must still acquire its locks and
recheck after deployment.
- The first final-head CI run failed browser shard 5 at
`cloud-auth.spec.ts:34` with an APIResponse disposed during route
teardown. After the workflow completed, one scoped failed-job retry
passed that shard and its browser aggregate on the same head. The
initial failure is retained. No code, test, timeout or assertion changed
for that retry.
- `verify --explain` returned 2 because the documentation path requires
broad CI. Required CI passed on
`2050fa058cabe75e3d8f64f1f6bdb4b9b2fd0873`. Fresh Greptile review is 5/5
with zero open threads. No hosted workspace, provider, task, or recovery
state was changed for this PR.
## Risks
The new proof could accept an inconsistent recovery producer. Exact
company, run, task, allocation, action, result, and receipt checks keep
uncertain sources blocked. Changed evidence during capture prevents
publication. A saved local snapshot is not proof that remote files were
recovered, and this change never creates such a receipt.
## Model Used
OpenAI GPT-6 (Codex), with reasoning, tool use, and code execution. The
runtime does not expose a more specific model ID or 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip
---
doc/native-workspace-finalization-recovery.md | 12 ++
.../online-legacy-workspace-recovery.ts | 36 ++++-
.../remote-workspace-online-source.test.ts | 131 ++++++++++++++++--
3 files changed, 164 insertions(+), 15 deletions(-)
diff --git a/doc/native-workspace-finalization-recovery.md b/doc/native-workspace-finalization-recovery.md
index 3a11fd1464d..eaee145c11a 100644
--- a/doc/native-workspace-finalization-recovery.md
+++ b/doc/native-workspace-finalization-recovery.md
@@ -15,6 +15,18 @@ exact source proof under publication row locks. A changed source or checkpoint
keeps local authority. Provider stop verification and any later file export
remain the recovery owner's separate obligations.
+The same local file handoff can preserve a blocked prepared source after a
+native session is interrupted with ambiguous state, or after its file export
+recovery is exhausted. The interruption may precede a provider session. Its
+recorded session flag must be a boolean; it does not prove remote recovery.
+The interrupted source must retain its exact task failure block and declared
+recovery allocations. The exhausted source must retain its accepted
+result, bound original allocation, exhausted system recovery and blocked file
+recovery. An empty list of additional recovery allocations does not remove the
+original prepared allocation binding. The migration checks these records again
+under the same physical and task locks before publication. It keeps the failed
+run, accepted result, recovery action and remote file obligation unchanged.
+
Periodic heartbeat recovery runs one pass at a time in each server process.
A tick that arrives during a slow pass reports its age and starts no duplicate.
A later tick can start a fresh pass after the current work settles. Shutdown
diff --git a/server/src/services/online-legacy-workspace-recovery.ts b/server/src/services/online-legacy-workspace-recovery.ts
index 2b3e5dc18f7..4f6795d6023 100644
--- a/server/src/services/online-legacy-workspace-recovery.ts
+++ b/server/src/services/online-legacy-workspace-recovery.ts
@@ -1,6 +1,6 @@
import { createHash } from "node:crypto";
import { and, eq } from "drizzle-orm";
-import { environmentLeases, executionWorkspaces, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, type Db } from "@paperclipai/db";
+import { environmentLeases, executionWorkspaces, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, nativeRunResults, type Db } from "@paperclipai/db";
import { adapterExecutionControls } from "./adapter-execution-control.js";
import { inspectFinalizedWorkspaceRecoveryHold, type FinalizedWorkspaceRecoveryHold } from "./finalized-workspace-recovery-migration.js";
import { isLegacyWorkspaceTaskRelated, readLegacyWorkspaceRecoveryAllocations, type LegacyWorkspaceRecoverySource } from "./legacy-workspace-recovery-migration.js";
@@ -8,6 +8,8 @@ import { tryLockNativeWorkspaceFinalization } from "./native-runtime/native-work
import { readNativeWorkspaceSyncReference } from "./native-runtime/native-workspace-sync.js";
import { workspaceExportCauses } from "./workspace-recovery-source.js";
import { nativeSha256 } from "./native-runtime/canonical.js";
+import { readSystemRecovery } from "./system-recovery-state.js";
+import { readWorkspaceRecovery } from "./workspace-recovery-receipt.js";
type ReadDb = Pick;
type Workspace = Pick;
@@ -131,13 +133,16 @@ export async function inspectOnlineLegacyWorkspaceRecoveryHold(db: ReadDb, input
if (!settled) return null;
const failureBlock = recovery.evidence.nativeFailureBlock as { runId?: unknown; statusVersion?: unknown } | undefined;
if (recovery.kind === "active_run_watchdog" && recovery.status === "active"
- && recovery.cause === "runner_remote_provider_artifact_incompatible" && settled.run.status === "failed"
+ && ["runner_remote_provider_artifact_incompatible", "native_session_interrupted"].includes(recovery.cause) && settled.run.status === "failed"
&& settled.owner.phase === "terminal_failure" && settled.owner.nextAttemptAt === null && settled.owner.resultId === null
&& settled.owner.failureCode === recovery.cause && recovery.sourceIssueId === settled.run.nativeIssueId
&& recovery.ownerType === "board" && recovery.ownerAgentId === null && recovery.returnOwnerAgentId === settled.run.agentId
&& recovery.wakePolicy === null && recovery.evidence.sourceFailureCode === recovery.cause
- && recovery.evidence.recoveryDisposition === recovery.cause && recovery.evidence.providerSessionEstablished === true
- && recovery.evidence.recoveryMode === "exact_checkpoint_resume" && failureBlock?.runId === settled.run.id
+ && recovery.evidence.recoveryDisposition === recovery.cause
+ && (recovery.cause === "native_session_interrupted"
+ ? typeof recovery.evidence.providerSessionEstablished === "boolean" && recovery.evidence.recoveryMode === "ambiguous_state"
+ : recovery.evidence.providerSessionEstablished === true && recovery.evidence.recoveryMode === "exact_checkpoint_resume")
+ && failureBlock?.runId === settled.run.id
&& Number.isSafeInteger(failureBlock.statusVersion) && Number(failureBlock.statusVersion) > 0
&& recovery.fingerprint === createHash("sha256").update(`${settled.run.id}:${recovery.cause}`).digest("hex")
&& !fileKeys.filter(key => key !== "nativeFailureBlock").some(key => recovery.evidence?.[key] != null)) {
@@ -160,6 +165,29 @@ export async function inspectOnlineLegacyWorkspaceRecoveryHold(db: ReadDb, input
if (source?.reference?.state === "prepared" && source.issueId === recovery.sourceIssueId)
return { fingerprint: fingerprint({ recovery, source }), finalizedHold: null, preparedSource: source };
}
+ const system = readSystemRecovery(recovery.evidence), workspaceRecovery = readWorkspaceRecovery(recovery.evidence);
+ if (recovery.kind === "active_run_watchdog" && recovery.status === "active"
+ && recovery.cause === "native_workspace_sync_out_retry_exhausted" && settled.run.status === "failed"
+ && settled.owner.phase === "terminal_failure" && settled.owner.nextAttemptAt === null && settled.owner.resultId
+ && settled.owner.failureCode === recovery.cause && settled.run.completionContractId
+ && recovery.sourceIssueId === settled.run.nativeIssueId && ["system", "board"].includes(recovery.ownerType)
+ && recovery.ownerAgentId === null && recovery.returnOwnerAgentId === settled.run.agentId && recovery.wakePolicy === null
+ && recovery.fingerprint === nativeSha256({ runId: settled.run.id, failureCode: recovery.cause })
+ && system?.sourceRunId === settled.run.id && system.state === "exhausted" && system.nextAttemptAt === null
+ && workspaceRecovery?.runId === settled.run.id && workspaceRecovery.status === "blocked"
+ && !["workspaceRestoreRecovery", "historicalWorkspaceSource", "nativeFailureBlock"].some(key => recovery.evidence?.[key] != null)) {
+ const [task] = await db.select({ id: issues.id, status: issues.status, statusVersion: issues.statusVersion,
+ executionRunId: issues.executionRunId, checkoutRunId: issues.checkoutRunId }).from(issues).where(and(
+ eq(issues.companyId, input.workspace.companyId), eq(issues.id, recovery.sourceIssueId)));
+ const [result] = await db.select().from(nativeRunResults).where(and(
+ eq(nativeRunResults.companyId, input.workspace.companyId), eq(nativeRunResults.issueId, recovery.sourceIssueId),
+ eq(nativeRunResults.runId, settled.run.id), eq(nativeRunResults.id, settled.owner.resultId),
+ eq(nativeRunResults.completionContractId, settled.run.completionContractId), eq(nativeRunResults.schemaStatus, "accepted")));
+ if (!task || task.status !== "blocked" || task.executionRunId !== null || task.checkoutRunId !== null || !result) return null;
+ const source = await inspectOnlineLegacyWorkspaceRecoverySource(db, { workspace: input.workspace, runId: settled.run.id });
+ if (source?.reference?.state === "prepared" && source.issueId === recovery.sourceIssueId)
+ return { fingerprint: fingerprint({ recovery, system, workspaceRecovery, source, task, result }), finalizedHold: null, preparedSource: source };
+ }
const held = await inspectFinalizedWorkspaceRecoveryHold(db, {
companyId: input.workspace.companyId, workspaceId: input.workspace.id, recovery,
});
diff --git a/server/src/services/remote-workspace-online-source.test.ts b/server/src/services/remote-workspace-online-source.test.ts
index 576af4605f9..7776d6f1040 100644
--- a/server/src/services/remote-workspace-online-source.test.ts
+++ b/server/src/services/remote-workspace-online-source.test.ts
@@ -6,7 +6,7 @@ import os from "node:os";
import path from "node:path";
import { sql, eq } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
-import { activityLog, agents, companies, createDb, environmentLeases, environments, executionWorkspaceSnapshots, executionWorkspaces, heartbeatRunEvents, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, projects, projectWorkspaces, workspaceOperations, workspaceRuntimeServices, type Db } from "@paperclipai/db";
+import { activityLog, agents, companies, completionContracts, createDb, environmentLeases, environments, executionWorkspaceSnapshots, executionWorkspaces, heartbeatRunEvents, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, nativeRunResults, projects, projectWorkspaces, workspaceOperations, workspaceRuntimeServices, type Db } from "@paperclipai/db";
import { readRemoteWorkspaceAuthority, readRemoteWorkspaceRunReference } from "@paperclipai/shared";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js";
import { resolveManagedProjectWorkspaceDir, resolvePaperclipInstanceRoot } from "../home-paths.js";
@@ -21,10 +21,13 @@ import { withExecutionWorkspaceLifecycleLock } from "./execution-workspace-lifec
import { IsolatedRepositorySourceBusy, withIsolatedRepositorySourceLock, withWorkspaceSourceLocks } from "./workspace-source-lock.js";
import { tryLockNativeWorkspaceFinalization } from "./native-runtime/native-workspace-finalization-ownership.js";
import { recordNativeFinalizationFailure } from "./native-runtime/native-run-finalizer.js";
+import { nativeProviderRecoveryEvidence, nativeSessionFailureDisposition } from "./native-runtime/native-session-executor.js";
import { inspectOnlineWorkspaceSource } from "./online-workspace-source.js";
import { inspectOnlineLegacyWorkspaceRecoveryHold, inspectOnlineLegacyWorkspaceRecoverySource } from "./online-legacy-workspace-recovery.js";
import { nativeWorkspaceSyncInternals } from "./native-runtime/native-workspace-sync.js";
import { readMigratedLegacyWorkspaceSource } from "./legacy-workspace-recovery-migration.js";
+import { createSystemRecovery } from "./system-recovery-state.js";
+import { nativeSha256 } from "./native-runtime/canonical.js";
import { verifiedWorkspaceRepairReceipt } from "./workspace-recovery-receipt.js";
import { adapterExecutionControls, createAdapterExecutionControl } from "./adapter-execution-control.js";
import { withWorkspaceMoveLocks } from "./isolated-repository-rehome.js";
@@ -53,10 +56,12 @@ describe.skipIf(!support.supported)("online ordinary physical source fence", ()
await db.delete(executionWorkspaceSnapshots);
await db.delete(workspaceRuntimeServices);
await db.delete(nativeRunFinalizations);
+ await db.delete(nativeRunResults);
await db.delete(environmentLeases);
await db.delete(environments);
await db.delete(heartbeatRunEvents);
await db.delete(heartbeatRuns);
+ await db.delete(completionContracts);
await db.delete(issues);
await db.delete(agents);
await db.delete(executionWorkspaces);
@@ -520,31 +525,135 @@ describe.skipIf(!support.supported)("online ordinary physical source fence", ()
status: "active", evidence: { runId } });
return { ...f, run, owner, lease, warning };
}
- async function artifactFailureFixture(descendant = false) {
- const f = await recoveryFixture(descendant), cause = "runner_remote_provider_artifact_incompatible", statusVersion = 2;
- const profile = { ...f.run.runnerProfileJson, sessionCheckpoint: { backendKind: "runner", providerSessionId: "fixture-established-session" } };
+ async function artifactFailureFixture(descendant = false, cause: "runner_remote_provider_artifact_incompatible" | "native_session_interrupted" = "runner_remote_provider_artifact_incompatible") {
+ const f = await recoveryFixture(descendant), statusVersion = 2;
+ const profile = { ...f.run.runnerProfileJson, sessionCheckpoint: cause === "native_session_interrupted"
+ ? { backendKind: "runner" } : { backendKind: "runner", providerSessionId: "fixture-established-session" } };
const restore = { schema: "paperclip.workspace-restore-recovery.v1", leaseIds: [f.lease.id] };
- await db.update(heartbeatRuns).set({ runnerProfileJson: profile, nextEventSeq: 250,
+ await db.update(heartbeatRuns).set({ runnerProfileJson: profile, nextEventSeq: cause === "native_session_interrupted" ? 1 : 250,
resultJson: { ...f.run.resultJson, workspaceRestoreRecovery: restore } }).where(eq(heartbeatRuns.id, f.run.id));
- await db.update(nativeRunFinalizations).set({ phase: "terminal_failure", failureCode: cause, nextAttemptAt: null })
- .where(eq(nativeRunFinalizations.runId, f.run.id));
+ const events = cause === "native_session_interrupted" ? [] : ["session.started", ...Array.from({ length: 124 }, () => ["tool.execution.started", "tool.execution.completed"]).flat()];
+ if (events.length) await db.insert(heartbeatRunEvents).values(events.map((eventType, index) => ({ companyId: f.companyId,
+ runId: f.run.id, agentId: f.run.agentId, seq: index + 1, eventType })));
+ const evidence = await nativeProviderRecoveryEvidence({ db, runId: f.run.id, metadataOnly: true, sourceFailureCode: cause });
+ expect(evidence).toMatchObject({ recoveryMode: cause === "native_session_interrupted" ? "ambiguous_state" : "exact_checkpoint_resume", providerSessionEstablished: cause !== "native_session_interrupted" });
+ const disposition = nativeSessionFailureDisposition(1, new Date(), cause);
+ const phase = evidence.recoveryMode === "ambiguous_state" ? "terminal_failure" : disposition.phase;
+ const failureCode = evidence.recoveryMode === "ambiguous_state" ? cause : disposition.failureCode;
+ expect({ phase, failureCode }).toEqual({ phase: "terminal_failure", failureCode: cause });
+ await db.update(nativeRunFinalizations).set({ phase, failureCode, nextAttemptAt: null }).where(eq(nativeRunFinalizations.runId, f.run.id));
await db.update(issues).set({ status: "blocked", statusVersion, executionRunId: null, checkoutRunId: null })
.where(eq(issues.id, f.run.nativeIssueId!));
await db.update(issueRecoveryActions).set({ cause, ownerType: "board", ownerAgentId: null,
returnOwnerAgentId: f.run.agentId, wakePolicy: null,
fingerprint: createHash("sha256").update(`${f.run.id}:${cause}`).digest("hex"), evidence: {
runId: f.run.id, coordinatorAttempt: 3, sourceFailureCode: cause, recoveryDisposition: cause,
- nativeFailureBlock: { runId: f.run.id, statusVersion }, providerSessionEstablished: true, recoveryMode: "exact_checkpoint_resume",
+ nativeFailureBlock: { runId: f.run.id, statusVersion }, providerSessionEstablished: evidence.providerSessionEstablished, recoveryMode: evidence.recoveryMode,
} }).where(eq(issueRecoveryActions.id, f.warning.id));
- const events = ["session.started", ...Array.from({ length: 124 }, () => ["tool.execution.started", "tool.execution.completed"]).flat()];
- await db.insert(heartbeatRunEvents).values(events.map((eventType, index) => ({ companyId: f.companyId,
- runId: f.run.id, agentId: f.run.agentId, seq: index + 1, eventType })));
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id));
const [owner] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.run.id));
const [warning] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.warning.id));
const [issue] = await db.select().from(issues).where(eq(issues.id, run.nativeIssueId!));
return { ...f, run, owner, warning, issue };
}
+ async function heldLocalFixture(kind: "interrupted" | "exhausted") {
+ const f = kind === "interrupted" ? await artifactFailureFixture(false, "native_session_interrupted") : await recoveryFixture();
+ const reference = { ...f.run.runnerProfileJson!.nativeWorkspaceSync as Record, resourceDisposition: "keep_running" };
+ await db.update(heartbeatRuns).set({ runnerProfileJson: { ...f.run.runnerProfileJson, nativeWorkspaceSync: reference } })
+ .where(eq(heartbeatRuns.id, f.run.id));
+ if (kind === "exhausted") {
+ const cause = "native_workspace_sync_out_retry_exhausted", contractId = randomUUID(), resultId = randomUUID();
+ await db.insert(completionContracts).values({ id: contractId, companyId: f.companyId, issueId: f.run.nativeIssueId!, revision: 1,
+ schemaVersion: "v1", policyVersion: "v1", risk: "low", completionAuthority: "agent", incompleteCriteriaPolicy: "block",
+ contractJson: {}, canonicalSha256: "45".repeat(32), createdByActorType: "system", createdByActorId: "fixture" });
+ await db.update(heartbeatRuns).set({ completionContractId: contractId, completionContractSha256: "45".repeat(32),
+ resultJson: { retained: "original failed-run result" } }).where(eq(heartbeatRuns.id, f.run.id));
+ await db.insert(nativeRunResults).values({ id: resultId, companyId: f.companyId, issueId: f.run.nativeIssueId!, runId: f.run.id,
+ completionContractId: contractId, serverFingerprint: "accepted retained export result", schemaStatus: "accepted",
+ resultJson: { terminal: { runTerminalState: "succeeded" }, retained: "original accepted result" }, canonicalSha256: "67".repeat(32) });
+ await db.update(nativeRunFinalizations).set({ phase: "terminal_failure", resultId, failureCode: cause, nextAttemptAt: null,
+ recoveryHistory: [{ retained: "original remote export remains unresolved" }] }).where(eq(nativeRunFinalizations.runId, f.run.id));
+ await db.update(issues).set({ status: "blocked", statusVersion: 5, executionRunId: null, checkoutRunId: null })
+ .where(eq(issues.id, f.run.nativeIssueId!));
+ await db.update(issueRecoveryActions).set({ cause, ownerType: "system", ownerAgentId: null, returnOwnerAgentId: f.run.agentId,
+ wakePolicy: null, fingerprint: nativeSha256({ runId: f.run.id, failureCode: cause }), evidence: {
+ runId: f.run.id, originalFailureCode: "native_workspace_sync_out_transient", coordinatorAttempt: 3, workspaceFinalizeAttempt: 3,
+ systemRecovery: { ...createSystemRecovery(f.run.id), phase: "preserve_files", state: "exhausted", attemptId: randomUUID(), attempts: 4, retriesUsed: 3 },
+ workspaceRecovery: { schema: "paperclip.workspace-recovery.v1", runId: f.run.id, status: "blocked", stage: "verifying_stop", attempt: 4, requestIds: [], retryable: true },
+ previousWorkspaceRecovery: { retained: "original recovery history" },
+ } }).where(eq(issueRecoveryActions.id, f.warning.id));
+ }
+ const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id));
+ const [owner] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.run.id));
+ const [warning] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.warning.id));
+ const [issue] = await db.select().from(issues).where(eq(issues.id, f.run.nativeIssueId!));
+ return { ...f, run, owner, warning, issue };
+ }
+ it.each(["interrupted", "exhausted"] as const)("preserves a stable local Git copy with its %s remote hold intact", async kind => {
+ const recovery = await heldLocalFixture(kind), f = { ...recovery, ...await gitFixture(recovery) };
+ const results = await db.select().from(nativeRunResults), unrelated = await remoteWriter(f.companyId, f.run.agentId);
+ await expect(migrateRemoteWorkspace({ db, storage, companyId: f.companyId, workspaceId: f.child.id, apply: true }))
+ .resolves.toMatchObject({ applied: true });
+ const put = storage.putFile.bind(storage);
+ vi.spyOn(storage, "putFile").mockImplementationOnce(async input => {
+ await db.transaction(async tx => expect(await tryLockNativeWorkspaceFinalization(tx as unknown as Db, {
+ companyId: f.companyId, runId: f.run.id,
+ })).toBe(false));
+ return put(input);
+ });
+ await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).resolves.toMatchObject({ applied: true });
+ const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id));
+ expect(run.status).toBe("failed"); expect(run.resultJson).toEqual(f.run.resultJson);
+ expect(run.runnerProfileJson).toMatchObject({ nativeWorkspaceSync: f.run.runnerProfileJson!.nativeWorkspaceSync });
+ expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.run.id)))[0]).toEqual(f.owner);
+ expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.lease.id)))[0]).toEqual(f.lease);
+ expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.warning.id)))[0]).toEqual(f.warning);
+ expect((await db.select().from(issues).where(eq(issues.id, f.issue.id)))[0]).toEqual(f.issue);
+ expect(await db.select().from(nativeRunResults)).toEqual(results);
+ expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, unrelated.id)))[0]).toEqual(unrelated);
+ expect(await verifiedWorkspaceRepairReceipt(db, run)).toBeNull();
+ const authority = readRemoteWorkspaceAuthority((await stored(f.workspaceId)).metadata)!;
+ const reference = (await getWorkspaceSnapshot(db, { ...f, snapshotId: authority.snapshotId! }))!;
+ const archivePath = path.join(home, "held-local.pcws"), targetDir = path.join(home, "held-local-restored");
+ await loadWorkspaceSnapshotArchive({ storage, reference, targetPath: archivePath });
+ await fs.rm(f.cwd, { recursive: true });
+ await restoreRemoteWorkspaceArchive({ archivePath, targetDir, expectedManifestDigest: reference.manifestDigest });
+ expect(await fs.readFile(path.join(targetDir, "saved.txt"), "utf8")).toBe("saved legacy edits\n");
+ });
+ it.each((["interrupted", "exhausted"] as const).flatMap(kind =>
+ ["owner", "active", "fingerprint", "allocation", "recovery", ...(kind === "interrupted" ? ["mode", "provider-flag"] : [])].map(mode => ({ kind, mode }))))("keeps $kind local files held on $mode mismatch", async ({ kind, mode }) => {
+ const f = await heldLocalFixture(kind);
+ if (mode === "owner") await db.update(nativeRunFinalizations).set({ leaseOwner: "unreleased", leaseExpiresAt: new Date(0) }).where(eq(nativeRunFinalizations.runId, f.run.id));
+ if (mode === "active") await db.update(heartbeatRuns).set({ controllerLeaseExpiresAt: new Date(Date.now() + 60_000) }).where(eq(heartbeatRuns.id, f.run.id));
+ if (mode === "fingerprint") await db.update(issueRecoveryActions).set({ fingerprint: "00".repeat(32) }).where(eq(issueRecoveryActions.id, f.warning.id));
+ if (mode === "mode") await db.update(issueRecoveryActions).set({ evidence: { ...f.warning.evidence, recoveryMode: "exact_checkpoint_resume" } }).where(eq(issueRecoveryActions.id, f.warning.id));
+ if (mode === "provider-flag") await db.update(issueRecoveryActions).set({ evidence: { ...f.warning.evidence, providerSessionEstablished: "false" } }).where(eq(issueRecoveryActions.id, f.warning.id));
+ if (mode === "allocation") await db.update(environmentLeases).set({ providerLeaseId: randomUUID() }).where(eq(environmentLeases.id, f.lease.id));
+ if (mode === "recovery") await db.update(issueRecoveryActions).set({ evidence: kind === "exhausted"
+ ? { ...f.warning.evidence, systemRecovery: { ...createSystemRecovery(f.run.id), state: "running" } }
+ : { ...f.warning.evidence, nativeFailureBlock: { runId: f.run.id, statusVersion: f.issue.statusVersion + 1 } } }).where(eq(issueRecoveryActions.id, f.warning.id));
+ const warning = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.warning.id));
+ await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).rejects.toThrow();
+ expect(await db.select().from(workspaceOperations)).toHaveLength(0);
+ expect(readRemoteWorkspaceAuthority((await stored(f.workspaceId)).metadata)).toBeNull();
+ expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.warning.id))).toEqual(warning);
+ expect(await fs.readFile(path.join(f.cwd, "saved.txt"), "utf8")).toBe("saved legacy edits\n");
+ });
+ it.each(["interrupted", "exhausted"] as const)("rejects a %s hold change during local capture", async kind => {
+ const f = await heldLocalFixture(kind), put = storage.putFile.bind(storage);
+ vi.spyOn(storage, "putFile").mockImplementationOnce(async input => {
+ const result = await put(input);
+ if (kind === "interrupted") await db.update(issueRecoveryActions).set({ evidence: { ...f.warning.evidence, coordinatorAttempt: 4 } }).where(eq(issueRecoveryActions.id, f.warning.id));
+ else await db.update(nativeRunResults).set({ resultJson: { changed: "new accepted result bytes" } }).where(eq(nativeRunResults.runId, f.run.id));
+ return result;
+ });
+ await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).rejects.toThrow();
+ expect(readRemoteWorkspaceAuthority((await stored(f.workspaceId)).metadata)).toBeNull();
+ expect((await db.select().from(workspaceOperations))[0].status).toBe("running");
+ expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.run.id)))[0]).toEqual(f.owner);
+ expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.lease.id)))[0]).toEqual(f.lease);
+ expect(await fs.readFile(path.join(f.cwd, "saved.txt"), "utf8")).toBe("saved legacy edits\n");
+ });
it("preserves provider-established artifact failure holds while migrating local Git aliases and their source recipe", async () => {
const recovery = await artifactFailureFixture(), f = { ...recovery, ...await gitFixture(recovery) };
const original = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id));
From b8e02fc2b418a9104612fa731f7afde7afcce6b5 Mon Sep 17 00:00:00 2001
From: Dotta <34892728+cryppadotta@users.noreply.github.com>
Date: Sat, 7 Nov 2026 09:11:00 -0600
Subject: [PATCH 03/24] fix(native): preserve bounded larger web inventories
(#19832)
## Thinking Path
> - Paperclip manages AI agents and preserves their work across server
changes.
> - Native harness preservation stores retained web-server files in
authenticated archives.
> - A retained skill can contain hundreds of valid local files.
> - The WEB evidence owner rejected any directory or inventory above 128
entries.
> - This blocked preservation of two 462-file skills even though their
payload fit the existing byte limits.
> - This pull request shares finite inventory bounds between capture and
archive validation.
> - It preserves every file and keeps the execution, identity, writer,
and publication guards.
## Linked Issues or Issue Description
Refs: #19814
**What happened?**
WEB evidence preservation rejected a retained source with 927 local
skill files. The source had settled execution ownership. The files fit
the existing payload limits. The directory enumeration failed before
archive publication because its entry limit was 128.
**Expected behavior**
Preserve a valid finite inventory within explicit file, payload, path,
and metadata limits. Keep remote recovery obligations unchanged.
**Steps to reproduce**
1. Retain two 462-file skills and one three-file skill under a settled
native source.
2. Request canonical WEB evidence preservation.
3. The old owner rejects directory enumeration. The added integration
test reproduces this refusal with real files and PostgreSQL.
## What Changed
- Share the WEB limit through the existing controller archive owner:
10,000 total entries, 4 MiB of manifest metadata, and 4,096 bytes per
path.
- Apply the limits to filesystem capture, published binding validation,
and archive descriptor validation.
- Keep the existing 16 MiB per-file and 64 MiB payload bounds. Keep
authority history at 128 entries and 32 epochs.
- Add real archive and cold-restore coverage for 927 files, legacy
manifest compatibility, and bound refusals. Document the limits.
## Verification
- Genuine baseline RED: the new 927-file integration case reaches the
original `captureWebEvidence.directoryNames` limit and fails before
publication.
- The initial setup attempt failed before test collection because the
generated plugin SDK was absent. The required SDK build fixed setup; it
was not counted as a regression result.
- The first affected three-suite run passed 93 cases. The large
roundtrip exceeded the generic 15-second case deadline. That failure is
retained. The isolated large case passed with a 60-second case limit,
but full CI later exceeded that limit while the other 4,577 tests in its
shard passed. Both timeout failures are retained. The final fixture
keeps all 927 files and 18.5 MB, uses bounded 16-way independent
comparisons, and has a 120-second whole-case limit. The canonical
preservation signal remains 60 seconds. No production deadline or
assertion changed.
- The 927-file case then passed: encrypted archive, authenticated cold
restore, all bytes/hashes/modes, unchanged remote leases, and
database-only validation with source volume absent and storage reads
forbidden.
- The final metadata repair adds a genuine RED case: an entry list below
4 MiB previously emitted a larger complete manifest without rejection.
The owner now checks the complete serialized manifest. All ten focused
cases passed after that repair. The final bounded-I/O fixture passed the
same ten cases in 37.26 seconds, including the full 927-file roundtrip.
All 93 other affected cases passed in the preceding three-suite run.
Fresh required CI supplies broad final-head coverage.
- Server TypeScript, module boundaries, and whitespace checks pass.
Run the focused PostgreSQL checks from `server/` with the repository
wrapper:
```sh
node ../cli/node_modules/tsx/dist/cli.mjs ../packages/db/src/test-postgres-command.ts -- node ../node_modules/vitest/vitest.mjs run src/services/native-runtime/native-harness-filesystem-independence.integration.test.ts --testNamePattern 'preserves all 927|existing 128-entry WEB|WEB manifest beyond|oversized WEB filesystem' --hookTimeout 90000 --maxWorkers 1 --fsModuleCache
```
## Risks
The owner can hold more entries in memory. The fixed 64 MiB payload, 4
MiB metadata, path, and entry bounds constrain that cost. The archive
format and old receipt bytes do not change. Older builds still have the
128-entry limit and cannot qualify a larger new receipt. This change
does not settle remote recovery, grant execution authority, alter
finalizer locks, or change publication CAS rules. No hosted preservation
or deployment was performed for this PR.
## Model Used
OpenAI `gpt-6.1-sol`, with code execution and repository tools. The
context window size is not exposed.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` /
`Closes: #` / `Refs: #` OR (b) described the issue in-PR following the
relevant issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip
---
doc/DATABASE.md | 6 +-
.../native-controller-archive.ts | 23 +++-
...ilesystem-independence.integration.test.ts | 118 +++++++++++++++++-
.../native-harness-filesystem-independence.ts | 18 +--
4 files changed, 149 insertions(+), 16 deletions(-)
diff --git a/doc/DATABASE.md b/doc/DATABASE.md
index bb1594be275..fe8df430701 100644
--- a/doc/DATABASE.md
+++ b/doc/DATABASE.md
@@ -105,8 +105,10 @@ Files retain their bytes and modes, including local edits and a skill whose
version row was deleted. Such a skill remains forensic evidence: the owner does
not recreate its version or make it executable. Canonical credential exclusions
stay excluded. Unknown directories, symlinks, incomplete manifests, active web
-writers and changed source facts fail closed. The same 128-entry, 16-MiB-file and
-64-MiB-total limits apply independently to this inventory.
+writers and changed source facts fail closed. This WEB inventory permits at most
+10,000 entries, 4 MiB of manifest metadata, and 4,096 bytes per path. The 16-MiB
+per-file and 64-MiB total payload limits remain unchanged. Authority history keeps
+its separate 128-entry and 32-epoch bounds.
A genuinely absent raw controller stays absent. A supervisor-only archive still
requires the exact durable controller checkpoint and source identity. Old
diff --git a/server/src/services/native-runtime/native-controller-archive.ts b/server/src/services/native-runtime/native-controller-archive.ts
index b698c49ba6e..2584c8e19b9 100644
--- a/server/src/services/native-runtime/native-controller-archive.ts
+++ b/server/src/services/native-runtime/native-controller-archive.ts
@@ -7,7 +7,14 @@ import type { StorageService } from "../../storage/types.js";
import { removeNativeHarnessBackup } from "./native-harness-backup-cleanup.js";
import { persistNativeHarnessBackup, verifyDurableNativeHarnessBackup } from "./native-harness-backup-storage.js";
import type { SettledControllerArchiveOwner } from "./native-controller-archive-source.js";
-import { assertSkillSnapshotPath } from "../skill-snapshot.js";
+import { assertSkillSnapshotPath, MAX_SKILL_SNAPSHOT_FILES } from "../skill-snapshot.js";
+import { MAX_NATIVE_HARNESS_PATH_BYTES } from "./native-harness-backup-archive.js";
+
+export const NATIVE_CONTROLLER_WEB_LIMITS = {
+ entries: MAX_SKILL_SNAPSHOT_FILES,
+ metadataBytes: 4 * 1024 * 1024,
+ pathBytes: MAX_NATIVE_HARNESS_PATH_BYTES,
+} as const;
export type NativeControllerHistoryEntry = { path: string; mode: number; type: "directory" }
| { path: string; mode: number; type: "file"; content: string };
@@ -60,18 +67,22 @@ export function nativeControllerEvidenceDescriptor(source: { companyId: string;
}
}
}
+ if (source.web && source.web.entries.length > NATIVE_CONTROLLER_WEB_LIMITS.entries) {
+ throw new Error("native_controller_archive_authority_invalid");
+ }
const web = source.web ? { bindingDigest: source.web.bindingDigest,
entries: source.web.entries.map(entry => entry.type === "directory" ? { path: entry.path, mode: entry.mode, type: entry.type }
: { path: entry.path, mode: entry.mode, type: entry.type, size: entry.size, sha256: entry.sha256 }) } : undefined;
if (source.controllerDigest === null && !web) throw new Error("native_controller_archive_authority_invalid");
if (web) {
const paths = new Set(); let bytes = 0;
- if (source.purpose !== "filesystem_independence" || web.entries.length > 128 || !/^[a-f0-9]{64}$/.test(web.bindingDigest)) {
+ if (source.purpose !== "filesystem_independence" || !/^[a-f0-9]{64}$/.test(web.bindingDigest)) {
throw new Error("native_controller_archive_authority_invalid");
}
for (const entry of web.entries) {
assertSkillSnapshotPath(entry.path);
- if (!/^(?:(web-home|web-state|web-manifests)(\/|$)|web-supervisor\.json$)/.test(entry.path) || paths.has(entry.path)
+ if (Buffer.byteLength(entry.path) > NATIVE_CONTROLLER_WEB_LIMITS.pathBytes
+ || !/^(?:(web-home|web-state|web-manifests)(\/|$)|web-supervisor\.json$)/.test(entry.path) || paths.has(entry.path)
|| !["directory", "file"].includes(entry.type)
|| !Number.isInteger(entry.mode) || entry.mode < 0 || (entry.mode & ~0o777) !== 0
|| entry.path.includes("/") && !paths.has(entry.path.slice(0, entry.path.lastIndexOf("/")))
@@ -81,6 +92,9 @@ export function nativeControllerEvidenceDescriptor(source: { companyId: string;
}
paths.add(entry.path);
}
+ if (Buffer.byteLength(JSON.stringify(web.entries)) > NATIVE_CONTROLLER_WEB_LIMITS.metadataBytes) {
+ throw new Error("native_controller_archive_authority_invalid");
+ }
}
const manifest = JSON.stringify({ schema: "paperclip.legacy-controller-archive.v1", companyId: source.companyId,
issueId: source.issueId, runId: source.runId, reason: source.purpose === "filesystem_independence"
@@ -91,6 +105,9 @@ export function nativeControllerEvidenceDescriptor(source: { companyId: string;
...(web ? Object.fromEntries(web.entries.filter(entry => entry.type === "file").map(entry => [entry.path, entry.sha256])) : {}) },
...(history ? { history, historyBindingDigest: source.historyBindingDigest } : {}),
...(web ? { web: { entries: web.entries, bindingDigest: web.bindingDigest, controllerAbsent: source.controllerDigest === null } } : {}) });
+ if (web && Buffer.byteLength(manifest) > NATIVE_CONTROLLER_WEB_LIMITS.metadataBytes) {
+ throw new Error("native_controller_archive_authority_invalid");
+ }
return { manifest, scopeDigest: sha256(manifest), manifestSha256: `sha256:${sha256(manifest)}` };
}
diff --git a/server/src/services/native-runtime/native-harness-filesystem-independence.integration.test.ts b/server/src/services/native-runtime/native-harness-filesystem-independence.integration.test.ts
index d1640ebb7e9..13c90368082 100644
--- a/server/src/services/native-runtime/native-harness-filesystem-independence.integration.test.ts
+++ b/server/src/services/native-runtime/native-harness-filesystem-independence.integration.test.ts
@@ -32,7 +32,7 @@ import { restoreDurableNativeHarnessBackup } from "./native-harness-backup-stora
import { nativeToolContractFingerprintForTarget } from "./native-session-resume.js";
import { nativeCheckpointRetirement } from "./native-runner-checkpoint-retirement.js";
import { nativeSha256 } from "./canonical.js";
-import { nativeControllerEvidenceDescriptor } from "./native-controller-archive.js";
+import { nativeControllerEvidenceDescriptor, NATIVE_CONTROLLER_WEB_LIMITS, type NativeControllerHistoryManifestEntry } from "./native-controller-archive.js";
vi.mock("../../build-commit.js", () => ({ readBuildCommit: () => "a".repeat(40) }));
@@ -43,7 +43,7 @@ describeEmbeddedPostgres("owner-verified native harness filesystem independence"
afterEach(async () => { vi.restoreAllMocks(); vi.unstubAllEnvs(); await db.delete(agentTaskSessions); for (const root of roots.splice(0)) await removeRuntimeAssetTree(root); });
afterAll(async () => { await db?.$client.end({ timeout: 1 }); await database?.cleanup(); });
- async function fixture(kind: "unversioned" | "repository" | "package" | "deleted" | "none" = "unversioned", managedWorkspace = false) {
+ async function fixture(kind: "unversioned" | "repository" | "package" | "deleted" | "none" | "many-web-files" = "unversioned", managedWorkspace = false) {
vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY", "61".repeat(32));
const mount = await realpath(await mkdtemp(join(tmpdir(), "native-harness-original-"))); roots.push(mount);
const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID(), sessionId = randomUUID(), runnerId = randomUUID();
@@ -71,7 +71,16 @@ describeEmbeddedPostgres("owner-verified native harness filesystem independence"
await db.insert(agents).values({ id: agentId, companyId, name: "Retained source" });
await db.insert(issues).values({ id: issueId, companyId, title: "Retain prior failure", status: "blocked" });
const runtimeContext = nativeRuntimeContextFixture();
- if (kind !== "none") {
+ if (kind === "many-web-files") {
+ runtimeContext.skills = [];
+ for (const [name, count] of [["first", 462], ["second", 462], ["third", 3]] as const) {
+ const bundle = await materializeAsset(Array.from({ length: count }, (_, index) => ({
+ path: `file-${index}.md`, content: Buffer.from(`${name}-${index}\n`.padEnd(20_000, "x")), mode: 0o444,
+ })));
+ runtimeContext.skills.push({ key: name, runtimeName: name, versionId: null, bundle });
+ }
+ runtimeContext.aggregateDigest = canonicalNativeRuntimeContextDigest(runtimeContext);
+ } else if (kind !== "none") {
let versionId: string | null = null;
const files: CompanySkillVersionFileInventoryEntry[] = kind === "deleted"
? [{ path: "SKILL.md", kind: "skill", content: "# Historical acceptance skill\n\n".padEnd(281, "x") }]
@@ -122,7 +131,9 @@ describeEmbeddedPostgres("owner-verified native harness filesystem independence"
if (kind !== "none") {
if (kind === "unversioned") await preserveRuntimeSkillAssets(db, { companyId, runId }, storage);
await mkdir(join(scopedRunnerdStateRoot(execution), "codex-home/skills"), { recursive: true, mode: 0o700 });
- await cp(runtimeContext.skills[0]!.bundle.rootPath, join(scopedRunnerdStateRoot(execution), "codex-home/skills/retained"), { recursive: true });
+ for (const skill of runtimeContext.skills) {
+ await cp(skill.bundle.rootPath, join(scopedRunnerdStateRoot(execution), "codex-home/skills", skill.runtimeName), { recursive: true });
+ }
}
const input = { companyId, selectedSessionId: selection!.id, scopeDigest, source, storage, signal: AbortSignal.timeout(60_000) };
return { input, runId, issueId, agentId, leaseId, execution, witness, storage, mount, sourceRoot: scopedRunnerdStateRoot(execution) };
@@ -231,6 +242,105 @@ describeEmbeddedPostgres("owner-verified native harness filesystem independence"
return { ...f, input: { ...f.input, mode: "web_evidence" as const } };
}
+ it("preserves all 927 local WEB skill files and validates their archive on a cold replacement", async () => {
+ const f = await controllerFixture(true, "many-web-files");
+ const [lease] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.leaseId));
+ const metadata = { ...lease!.metadata }; delete metadata.remoteExecutionTermination;
+ await db.update(environmentLeases).set({ metadata }).where(eq(environmentLeases.id, f.leaseId));
+ const originalLeases = await db.select().from(environmentLeases).where(eq(environmentLeases.companyId, f.input.companyId));
+ const result = await preserveNativeHarnessFilesystemIndependence(db, { ...f.input, mode: "web_evidence" });
+ const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
+ const receipt = run!.runnerProfileJson!.nativeHarnessFilesystemIndependence as {
+ web: { entries: Array<{ path: string; type: string }> }; controller: { archive: { id: string } };
+ };
+ expect(receipt.web.entries.length).toBeGreaterThan(927);
+ const [archive] = await db.select().from(nativeHarnessBackups).where(eq(nativeHarnessBackups.id, receipt.controller.archive.id));
+ const target = join(f.mount, "cold-many-web-files");
+ expect(await restoreDurableNativeHarnessBackup({ db, storage: f.storage, companyId: f.input.companyId,
+ scopeDigest: archive!.scopeDigest, backupRoot: target })).toBe(true);
+ if (!("runtimeContext" in f.execution)) throw new Error("fixture runtime context missing");
+ const files: Array<{ relative: string; sha256: string }> = [];
+ for (const skill of f.execution.runtimeContext.skills) {
+ const manifest = JSON.parse(await readFile(join(f.mount, "instances/default/runtime-context-assets/manifests", `${skill.bundle.digest}.json`), "utf8"));
+ for (const file of manifest.files as Array<{ path: string; sha256: string }>) {
+ files.push({ relative: join("codex-home/skills", skill.runtimeName, file.path), sha256: file.sha256 });
+ }
+ }
+ expect(files).toHaveLength(927);
+ for (let offset = 0; offset < files.length; offset += 16) {
+ await Promise.all(files.slice(offset, offset + 16).map(async file => {
+ const restored = join(target, "current/web-home", file.relative);
+ const [originalBytes, restoredBytes, stat] = await Promise.all([
+ readFile(join(f.sourceRoot, file.relative)), readFile(restored), lstat(restored),
+ ]);
+ expect(restoredBytes).toEqual(originalBytes);
+ expect(createHash("sha256").update(originalBytes).digest("hex")).toBe(file.sha256);
+ expect(stat.mode & 0o777).toBe(0o444);
+ }));
+ }
+ expect(await db.select().from(environmentLeases).where(eq(environmentLeases.companyId, f.input.companyId))).toEqual(originalLeases);
+ vi.stubEnv("PAPERCLIP_HOME", join(f.mount, "absent-many-web-files"));
+ vi.stubEnv("PAPERCLIP_RUNNER_STATE_DIR", join(f.mount, "absent-many-web-files/state")); vi.stubEnv("RAILWAY_VOLUME_ID", "");
+ vi.spyOn(f.storage, "getObject").mockRejectedValue(new Error("database validation must not read storage"));
+ expect(await hasValidNativeHarnessFilesystemIndependence(db, f.input)).toBe(true);
+ expect(result.receiptDigest).toMatch(/^[a-f0-9]{64}$/);
+ }, 120_000);
+
+ function webDescriptor(entries: NativeControllerHistoryManifestEntry[]) {
+ return nativeControllerEvidenceDescriptor({ companyId: "company", issueId: "issue", runId: "run", controllerDigest: null,
+ supervisorDigest: null, purpose: "filesystem_independence", web: { bindingDigest: "a".repeat(64), entries } });
+ }
+
+ it("keeps the existing 128-entry WEB manifest bytes unchanged", () => {
+ const entries: NativeControllerHistoryManifestEntry[] = [{ path: "web-home", mode: 0o700, type: "directory" },
+ ...Array.from({ length: 127 }, (_, index) => ({ path: `web-home/entry-${index}`, mode: 0o700, type: "directory" as const }))];
+ const descriptor = webDescriptor(entries);
+ const manifest = JSON.stringify({ schema: "paperclip.legacy-controller-archive.v1", companyId: "company", issueId: "issue",
+ runId: "run", reason: "original_volume_source_evidence", files: {}, web: { entries, bindingDigest: "a".repeat(64), controllerAbsent: true } });
+ expect(descriptor.manifest).toBe(manifest);
+ expect(descriptor.manifestSha256).toBe(`sha256:${createHash("sha256").update(manifest).digest("hex")}`);
+ });
+
+ it.each(["entry-count", "metadata-bytes", "manifest-bytes", "path-bytes", "file-bytes", "total-bytes"])("refuses a WEB manifest beyond its %s bound", control => {
+ const entries: NativeControllerHistoryManifestEntry[] = [{ path: "web-home", mode: 0o700, type: "directory" }];
+ if (control === "entry-count") entries.push(...Array.from({ length: NATIVE_CONTROLLER_WEB_LIMITS.entries }, (_, index) => ({
+ path: `web-home/entry-${index}`, mode: 0o700, type: "directory" as const,
+ })));
+ if (control === "metadata-bytes") entries.push(...Array.from({ length: 1_050 }, (_, index) => ({
+ path: `web-home/${index}-${"x".repeat(3_990)}`, mode: 0o700, type: "directory" as const,
+ })));
+ if (control === "manifest-bytes") {
+ entries.push(...Array.from({ length: NATIVE_CONTROLLER_WEB_LIMITS.entries - 1 }, (_, index) => ({
+ path: `web-home/${index}-${"x".repeat(240)}`, mode: 0o444, type: "file" as const, size: 0, sha256: "b".repeat(64),
+ })));
+ expect(Buffer.byteLength(JSON.stringify(entries))).toBeLessThan(NATIVE_CONTROLLER_WEB_LIMITS.metadataBytes);
+ }
+ if (control === "path-bytes") entries.push({ path: `web-home/${"x".repeat(NATIVE_CONTROLLER_WEB_LIMITS.pathBytes)}`, mode: 0o700, type: "directory" });
+ if (control === "file-bytes") entries.push({ path: "web-home/oversized", mode: 0o600, type: "file", size: 16 * 1024 * 1024 + 1, sha256: "b".repeat(64) });
+ if (control === "total-bytes") entries.push(...Array.from({ length: 5 }, (_, index) => ({ path: `web-home/file-${index}`,
+ mode: 0o600, type: "file" as const, size: 16 * 1024 * 1024, sha256: "b".repeat(64) })));
+ expect(() => webDescriptor(entries)).toThrow("native_controller_archive_authority_invalid");
+ });
+
+ it.each(["entry-count", "file-bytes"])("retains oversized WEB filesystem evidence without publication for %s", async control => {
+ const f = await webFixture(), directory = join(f.sourceRoot, "codex-home/oversized");
+ await mkdir(directory, { mode: 0o700 });
+ if (control === "entry-count") {
+ for (let offset = 0; offset <= NATIVE_CONTROLLER_WEB_LIMITS.entries; offset += 32) {
+ await Promise.all(Array.from({ length: Math.min(32, NATIVE_CONTROLLER_WEB_LIMITS.entries + 1 - offset) }, (_, index) =>
+ writeFile(join(directory, `entry-${offset + index}`), "", { mode: 0o600 })));
+ }
+ } else {
+ const file = join(directory, "oversized"); await writeFile(file, "", { mode: 0o600 });
+ await truncate(file, 16 * 1024 * 1024 + 1);
+ }
+ await expect(preserveNativeHarnessFilesystemIndependence(db, f.input)).rejects.toThrow("unverified");
+ const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
+ expect(run!.runnerProfileJson!.nativeHarnessFilesystemIndependence).toBeUndefined();
+ expect(await db.select().from(nativeHarnessBackups).where(eq(nativeHarnessBackups.runId, f.runId))).toEqual([]);
+ expect(await readFile(f.controllerPath, "utf8")).toBe(f.raw);
+ });
+
it("preserves a genuinely absent controller with its supervisor and 267 durable checkpoint parts", async () => {
const f = await webFixture(267);
await rm(f.controllerPath);
diff --git a/server/src/services/native-runtime/native-harness-filesystem-independence.ts b/server/src/services/native-runtime/native-harness-filesystem-independence.ts
index f8487b79922..452f5bce780 100644
--- a/server/src/services/native-runtime/native-harness-filesystem-independence.ts
+++ b/server/src/services/native-runtime/native-harness-filesystem-independence.ts
@@ -28,7 +28,7 @@ import { assertOriginalHarnessVolumeSource, type OriginalHarnessVolumeCapability
import { isKnownNativeSessionRootEntry } from "./native-session-root-entries.js";
import { readLegacyNativeControllerArchiveSource, readLegacyNativeControllerArchiveDigests } from "./native-controller-migration.js";
import { archiveNativeControllerSourceEvidence, legacyNativeControllerArchive, nativeControllerEvidenceDescriptor,
- nativeControllerHistoryManifest, nativeControllerWebManifest, type NativeControllerWebEntry,
+ nativeControllerHistoryManifest, nativeControllerWebManifest, NATIVE_CONTROLLER_WEB_LIMITS, type NativeControllerWebEntry,
type NativeControllerHistoryEntry, type NativeControllerHistoryManifestEntry } from "./native-controller-archive.js";
import { nativeControllerArchiveCoordinatorDigest, nativeControllerArchiveProfileDigest, type SettledControllerArchiveOwner } from "./native-controller-archive-source.js";
import { loadNativeRunnerCheckpoint, loadNativeRunnerCheckpointHeader } from "./native-runner-checkpoint.js";
@@ -479,12 +479,14 @@ function webProfile(facts: Awaited>) {
function validWebBinding(facts: Awaited>, web: WebBinding): boolean {
try {
if (!web || typeof web.rootPresent !== "boolean" || typeof web.controllerAbsent !== "boolean" || !Array.isArray(web.entries)
- || !Array.isArray(web.skills) || !Array.isArray(web.excluded) || web.entries.length > 128 || web.excluded.length > 128
+ || !Array.isArray(web.skills) || !Array.isArray(web.excluded)
+ || web.entries.length + web.excluded.length > NATIVE_CONTROLLER_WEB_LIMITS.entries
|| web.profileDigest !== digest(webProfile(facts)) || digest(web.skills) !== digest(webSkills(facts))) return false;
const profiles = webProfile(facts), manifests = new Map(web.skills.map(skill => [skill.bundleDigest, skill.manifestDigest]));
for (const [bundle, manifest] of manifests) if (!web.entries.some(entry => entry.path === `web-manifests/${bundle}.json`
&& entry.type === "file" && entry.sha256 === manifest)) return false;
if (web.entries.some(entry => {
+ if (Buffer.byteLength(entry.path) > NATIVE_CONTROLLER_WEB_LIMITS.pathBytes) return true;
const [prefix, name, ...rest] = entry.path.split("/");
if (prefix === "web-supervisor.json") return name !== undefined || entry.type !== "file";
if (prefix === "web-manifests") return name === undefined ? entry.type !== "directory"
@@ -499,10 +501,11 @@ function validWebBinding(facts: Awaited>, web:
return web.excluded.every(entry => {
const [name, ...rest] = entry.path.split("/"), rel = rest.join("/"), profile = profiles.find(profile => profile.name === name);
assertSkillSnapshotPath(entry.path);
- return profile?.excludeEntries.some(excluded => rel === excluded || rel.startsWith(`${excluded}/`))
+ return Buffer.byteLength(entry.path) <= NATIVE_CONTROLLER_WEB_LIMITS.pathBytes
+ && profile?.excludeEntries.some(excluded => rel === excluded || rel.startsWith(`${excluded}/`))
&& ["directory", "file"].includes(entry.type) && Number.isInteger(entry.mode) && (entry.mode & ~0o777) === 0
&& Number.isSafeInteger(entry.size) && entry.size >= 0;
- });
+ }) && Buffer.byteLength(JSON.stringify({ entries: web.entries, excluded: web.excluded })) <= NATIVE_CONTROLLER_WEB_LIMITS.metadataBytes;
} catch { return false; }
}
@@ -513,7 +516,7 @@ async function captureWebEvidence(facts: Awaited {
const names: string[] = [];
for await (const entry of await opendir(path)) {
- signal.throwIfAborted(); if (names.length >= 128) fail(); names.push(entry.name);
+ signal.throwIfAborted(); if (names.length >= NATIVE_CONTROLLER_WEB_LIMITS.entries) fail(); names.push(entry.name);
}
return names.sort();
};
@@ -540,7 +543,8 @@ async function captureWebEvidence(facts: Awaited => {
- signal.throwIfAborted(); if (++count > 128) fail(); assertSkillSnapshotPath(path);
+ signal.throwIfAborted(); if (++count > NATIVE_CONTROLLER_WEB_LIMITS.entries
+ || Buffer.byteLength(path) > NATIVE_CONTROLLER_WEB_LIMITS.pathBytes) fail(); assertSkillSnapshotPath(path);
const s = await lstat(file);
if (s.isSymbolicLink() || !s.isDirectory() && !s.isFile() || s.dev !== instance.dev || s.uid !== instance.uid || (s.mode & 0o7000) !== 0) fail();
metadata.push([path, s.dev, s.ino, s.size, s.mode, s.mtimeMs, s.ctimeMs]);
@@ -590,7 +594,7 @@ async function captureWebEvidence(facts: Awaited 128) fail();
+ if (entries.length + excluded.length > NATIVE_CONTROLLER_WEB_LIMITS.entries) fail();
const material = await readLegacyNativeControllerArchiveDigests(facts.source);
const binding: WebBinding = { entries: nativeControllerWebManifest(entries), skills, rootPresent: rootStat !== null,
profileDigest: digest(profiles), controllerAbsent: material.controllerDigest === undefined, excluded };
From 86bc3db693822ff96b639802aef45ed1dcf31c3b Mon Sep 17 00:00:00 2001
From: Dotta <34892728+cryppadotta@users.noreply.github.com>
Date: Sat, 7 Nov 2026 09:23:14 -0600
Subject: [PATCH 04/24] feat(runner): search and load unassigned company skills
(#19676)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - Native agents use tools to read reusable company skills.
> - The existing native skill tools read only skills assigned to the
agent.
> - An agent can stop when a task needs another skill that is already in
the company library.
> - This pull request adds tools to search and read accessible company
skills on demand.
> - Agents can use the saved instructions without a persistent
assignment change.
## Linked Issues or Issue Description
**Problem or motivation**
An agent cannot use an unassigned company skill through the standard
native skill tools. A generic API workaround needs extra discovery and
can return the full library.
**Proposed solution**
Add `search_skills` and `load_skill` to the native tool catalog. Search
returns small pages of stored metadata. Load returns text from a saved
version and lists its files. Both tools use the current run identity and
existing company and project access checks.
**Alternatives considered**
Assign each skill before a read, or use generic API discovery. Both add
work to a read that the company already permits.
**Roadmap alignment**
This extends the existing skills discovery path. It does not add a
store, permission model or installation flow. Related: #15409 adds an
assigned-skill loader to a different adapter.
## What Changed
- Add bounded company skill search. Search does not synchronize sources
or fetch repositories.
- Add versioned text reads for SKILL.md and supporting files. Page text
and file lists. Reject unsafe paths and binary files.
- Recheck access after storage reads. Keep the existing closed Muse,
skill-test and completion-review tool scopes.
- Add integration tests with isolated PostgreSQL and real local package
storage. Update the native tool count assertion and skill documentation.
- Limit text files to 16 MiB before body reads. Accept saved file paths
up to 4,096 characters plus the repository prefix. Return the response
digest only on the first page.
- Add optional byte limits to the package readers. Select only the
requested legacy file in PostgreSQL. Cast the size comparison to
`bigint` so existing callers can omit the limit.
- Cache decoded text and its digest for one run. Limit the cache to 64
MiB and 64 files. Check access on each page and clear the cache when the
run closes.
- Read repository source files and wrapper inputs through verified warm
reads or isolated recovery. These reads do not hold the company startup
lock.
## Verification
- Local verification tested tree
`7ba5828387ca0a9c2ee99655818a28de1235a854`, published as commit
`c9d04cba601541cca506f5b72aa6f7272a25379f`. The published tree matches
that tested checkout. Current head
`33fa3d3d4c7988288685ce7c6499d064e0cb9079` (tree
`8daaa2f3264d1cd65a9b6d85dbb9d3729ac4a29d`) removes six comment lines
from three source files; its executable code is unchanged from the
locally tested revision.
- Four native skill and authority Vitest suites: 72 passed and 7
existing sandbox checks skipped. All 20 skill-library integration tests
passed.
- Skill-library and package-store suites: 65 passed. This includes the
45 package-store cases and the same 20 integration cases. Ran with umask
`022` for executable-file tests.
- Server source and test typecheck layers passed in low-memory mode. The
affected source cycle also passed a final separate check.
- `git diff --check` and `node scripts/check-module-boundaries.mjs`
passed.
- Red/green evidence: the new default inline-read case reproduced
PostgreSQL error `22003`. Two max-size paging cases reproduced extra
body reads. Warm and cold repository reads timed out while another
connection held the company startup lock. All five cases pass after the
fixes.
- Both 16 MiB paging cases check that the second page performs no
additional body read. They also check that source-access revocation
blocks a cached page. Warm and cold lock cases load both the generated
wrapper and a supporting file while the startup lock remains held.
- The first cold-read test attempt had an incorrect helper import.
Corrected the test import, reproduced the lock timeout, then verified
the fix.
- [CI on the previous
revision](https://github.com/paperclipai/paperclip/actions/runs/42319652795)
passed typecheck, build and policy. Serialized shard 2 failed in the
unchanged test `schedules bounded retries for failed accepted
interaction continuation wakes`. The same case passed locally: 1 passed;
416 cases were excluded by the filter. The cause of the earlier CI
failure remains unknown. [CI for
c9d04cba](https://github.com/paperclipai/paperclip/actions/runs/42323260426)
passed: 52 successful jobs and one skipped selector, including
typecheck, build, all serialized server shards, native server tests,
Runner/Rust, and e2e. This establishes a later pass; the earlier
heartbeat failure's cause remains unknown. [CI for current head
33fa3d3d](https://github.com/paperclipai/paperclip/actions/runs/42325148224)
passed: all 52 applicable workflow jobs succeeded, with one skipped
selector. The head has 58 successful check runs and three skipped
checks; Snyk also passed.
- Earlier failures remain recorded. Preflight cannot build Rust because
Cargo is absent. The first catalog assertion expected 51 tools instead
of 53. Test startup needed the plugin SDK build. An earlier typecheck
hit the 8 GiB memory limit; low-memory checks passed. The previous
package test failed under umask `077`; it passed under `022`, and this
run's complete package suite passes with `022`.
- Greptile reviewed current head `33fa3d3d` at 2026-11-07 01:40 UTC: 5/5
with no outstanding findings. The three older Ponytail threads are
resolved after checking the size/cache, long-path, and bigint fixes and
regression tests. Ponytail's supplemental refreshed assessment stopped
before completing and posted no new findings. Its earlier findings are
fixed and all seven review threads are resolved. The completed Greptile
assessment covers current head.
- No hosted deployment or live provider run was performed.
## Risks
- Package reads can recover stored packages through the existing storage
layer. Search reads only stored database metadata.
- Load is a read. It does not install files into the provider workspace
or change runtime bundles. It does not grant tool access or authorize
actions in the skill text.
- Callers must retain the returned version ID for later pages. A missing
version returns an error.
- Files above 16 MiB return a size-limit error. The run cache retains at
most 64 MiB of decoded text and 64 entries. A cache miss or eviction
requires a full verified file read. Each page still checks current
access. The SHA-256 response field is null after the first text or
file-list page.
- No database migration or UI change is required.
## Model Used
- OpenAI Codex, GPT-6 family, with reasoning, repository tools and code
execution. The exact model ID and context window are not exposed to this
agent.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
---
doc/runner-created-skills.md | 40 +++
...ve-skill-library-tools.integration.test.ts | 287 ++++++++++++++++++
.../native-skill-library-tools.ts | 147 +++++++++
.../paperclip-runner-tool-authority.test.ts | 3 +-
.../paperclip-runner-tool-authority.ts | 11 +-
.../native-runtime/runner-bridge-tools.ts | 2 +-
server/src/services/skill-package-files.ts | 7 +-
server/src/services/skill-package-runtime.ts | 40 ++-
server/src/services/skill-package-store.ts | 18 +-
9 files changed, 533 insertions(+), 22 deletions(-)
create mode 100644 server/src/services/native-runtime/native-skill-library-tools.integration.test.ts
create mode 100644 server/src/services/native-runtime/native-skill-library-tools.ts
diff --git a/doc/runner-created-skills.md b/doc/runner-created-skills.md
index 9d9ad472b54..a52c5eb68b7 100644
--- a/doc/runner-created-skills.md
+++ b/doc/runner-created-skills.md
@@ -1,5 +1,45 @@
# Skills created by the Runner
+## Search and load company skills
+
+Native agents can use `search_skills` and `load_skill` to read accessible company
+library skills even when those skills are not assigned to them. These read-only
+tools are available in Auto, Ask and Plan modes without generic API access or a
+mounted workspace. The closed Muse, completion-review and skill-test profiles
+keep their existing tool scopes.
+
+Call `search_skills` with a `query` to match a name, key, slug or description.
+An empty query browses the library. Results include IDs, version IDs, source type,
+trust level and compatibility. `limit` is at most 20. Follow `nextCursor` with the
+same query until it is null. Search reads stored metadata; it does not synchronize
+sources, install catalog entries or fetch repositories.
+
+Call `load_skill` with the returned skill ID and `versionId`. An exact key also
+works; a slug must be unique. The default file is `SKILL.md`. To read a referenced
+text file, pass its relative `path` and the same version ID. The response includes
+a SHA-256 digest on the first text page (`null` on continuation pages), byte size,
+and up to 6,000 UTF-16 characters. Retain the first page's digest. Follow `nextOffset`
+in `offset`; a version ID is required for subsequent pages. The file list contains
+up to 50 entries; use `nextFileOffset` as `fileOffset` to read more entries. Do not
+switch to the latest version partway through a read. Missing or retired versions
+return an error instead of silently substituting different content.
+
+Loads use the existing saved package reader, including repository skill wrappers
+and supporting files. Text files above 16 MiB are rejected before body reads;
+accepted text is cached for the run with a 64 MiB budget and at most 64 files.
+Later pages reuse cached text and still check current access. Evicted files are
+read again. Repository reads use verified warm files or isolated recovery without
+holding the company startup lock. Supporting paths use the saved package limit
+of 4,096 characters plus the generated repository prefix.
+Binary files and unsafe paths are rejected. Access is
+checked against the current run and the existing company and project source
+boundaries, including after file I/O. Loaded content does not change persistent
+assignments, pinned runtime bundles, permissions, connections, or approval gates.
+Skill mutation policy continues to govern authoring and installation through the
+existing APIs. Reading instructions does not authorize actions described in them.
+
+## Create and update skills
+
The native Runner exposes `create_skill` in Auto and skill-test work. An agent
can save a reusable, single-file skill directly in the company's skill library.
The tool is unavailable in Ask and pre-acceptance Plan modes.
diff --git a/server/src/services/native-runtime/native-skill-library-tools.integration.test.ts b/server/src/services/native-runtime/native-skill-library-tools.integration.test.ts
new file mode 100644
index 00000000000..6f73bbe1508
--- /dev/null
+++ b/server/src/services/native-runtime/native-skill-library-tools.integration.test.ts
@@ -0,0 +1,287 @@
+import { createHash, randomUUID } from "node:crypto";
+import { promises as fs } from "node:fs";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import { eq } from "drizzle-orm";
+import { agents, companies, companySkills, companySkillVersions, companySkillSources, heartbeatRuns, issues } from "@paperclipai/db";
+import { startRecoveryPostgres } from "../../__tests__/helpers/recovery-postgres.js";
+import { createDb } from "@paperclipai/db";
+import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js";
+import { skillPackagePaths, skillPackageStore } from "../skill-package-store.js";
+import { withSkillVersionCacheLock } from "../skill-version-cache.js";
+import { getStorageService } from "../../storage/index.js";
+
+describe("native company skill discovery", () => {
+ let temporary: Awaited>;
+ let db: ReturnType;
+ let home: string;
+ beforeAll(async () => {
+ home = await mkdtemp(join(tmpdir(), "native-skill-library-"));
+ vi.stubEnv("PAPERCLIP_HOME", home);
+ vi.stubEnv("PAPERCLIP_STORAGE_PROVIDER", "local_disk");
+ vi.stubEnv("PAPERCLIP_STORAGE_LOCAL_DIR", join(home, "objects"));
+ temporary = await startRecoveryPostgres("native-skill-library-");
+ db = createDb(temporary.connectionString);
+ }, 60_000);
+ afterAll(async () => {
+ await temporary?.cleanup(); vi.unstubAllEnvs();
+ if (home) await rm(home, { recursive: true, force: true });
+ });
+
+ async function fixture() {
+ const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID();
+ await db.insert(companies).values({ id: companyId, name: "Skill library", issuePrefix: `S${companyId.slice(0, 8)}` });
+ await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer", adapterType: "paperclip_runner", status: "active", adapterConfig: { provider: "codex" } });
+ await db.insert(issues).values({ id: issueId, companyId, title: "Review", status: "in_progress", assigneeAgentId: agentId });
+ await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: issueId, status: "running", runtimeMode: "native", invocationSource: "assignment", triggerDetail: "system", contextSnapshot: { issueId, skillVersions: {} } });
+ await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));
+ const binding = { companyId, agentId, issueId, runId, apiToolsEnabled: false };
+ const authority = new PaperclipRunnerToolAuthority(db, binding);
+ const call = (tool: string, args: Record = {}) => authority.execute({ tool, callId: randomUUID(), arguments: args });
+ return { ...binding, authority, call };
+ }
+
+ async function skill(companyId: string, key = "pr-merge-review", text = "Read the diff and check the tests.") {
+ const id = randomUUID(), versionId = randomUUID();
+ await db.insert(companySkills).values({ id, companyId, key, slug: key, name: key, description: "Review a pull request before merge", markdown: text, sourceType: "managed" });
+ await db.insert(companySkillVersions).values({ id: versionId, companyId, companySkillId: id, revisionNumber: 1, fileInventory: [
+ { path: "SKILL.md", kind: "skill", content: text },
+ { path: "references/checks.md", kind: "reference", content: "Check CI and the review result." },
+ { path: "assets/icon.png", kind: "asset", content: "AAEC", encoding: "base64" },
+ ] });
+ await db.update(companySkills).set({ currentVersionId: versionId }).where(eq(companySkills.id, id));
+ return { id, versionId, text };
+ }
+
+ it("finds and loads an unassigned skill without generic API tools or assignment changes", async () => {
+ const f = await fixture(), s = await skill(f.companyId);
+ expect(f.authority.definitions().map(t => t.name)).toEqual(expect.arrayContaining(["search_skills", "load_skill"]));
+ expect(await f.call("search_skills", { query: "MERGE" })).toMatchObject({ skills: [{ id: s.id, key: "pr-merge-review", versionId: s.versionId, trustLevel: "markdown_only" }], nextCursor: null });
+ expect(await f.call("load_skill", { skill: "pr-merge-review" })).toMatchObject({ skillId: s.id, versionId: s.versionId, path: "SKILL.md", text: s.text, nextOffset: null });
+ expect(await f.call("load_skill", { skill: s.id, versionId: s.versionId, path: "references/checks.md" })).toMatchObject({ text: "Check CI and the review result." });
+ expect((await db.select().from(agents).where(eq(agents.id, f.agentId)))[0]?.adapterConfig).toEqual({ provider: "codex" });
+ });
+
+ it("keeps default inline file reads compatible with existing callers", async () => {
+ const f = await fixture(), s = await skill(f.companyId);
+ const store = skillPackageStore(db);
+ const version = await store.version(f.companyId, s.id, s.versionId);
+ expect(version).toBeTruthy();
+ expect(await store.readVersionFile(version!, "SKILL.md")).toMatchObject({ content: s.text });
+ expect(await store.readVersionFile(version!, "references/checks.md", false))
+ .toMatchObject({ content: "Check CI and the review result." });
+ });
+
+ it("bounds and paginates search results and treats SQL wildcard characters literally", async () => {
+ const f = await fixture();
+ await skill(f.companyId, "review-a"); await skill(f.companyId, "review-b"); await skill(f.companyId, "review-c");
+ const first = await f.call("search_skills", { query: "review", limit: 2 }) as any;
+ const second = await f.call("search_skills", { query: "review", limit: 2, cursor: first.nextCursor }) as any;
+ expect(first.skills).toHaveLength(2); expect(second.skills).toHaveLength(1); expect(second.nextCursor).toBeNull();
+ expect(new Set([...first.skills, ...second.skills].map(s => s.id)).size).toBe(3);
+ expect(await f.call("search_skills", { query: "%" })).toMatchObject({ skills: [] });
+ });
+
+ it.each([false, true])("reads stored package bytes and supporting files (repository wrapper: %s)", async repository => {
+ const f = await fixture(), s = await skill(f.companyId);
+ const markdown = "---\nname: packaged-review\ndescription: Review packaged content.\n---\n\nUse [checks](references/checks.md).";
+ const root = repository ? "skills/review/" : "";
+ const packageId = await skillPackageStore(db).prepare(f.companyId, [
+ { path: `${root}SKILL.md`, kind: "skill", content: markdown },
+ { path: `${root}references/checks.md`, kind: "reference", content: "These bytes came from saved storage." },
+ ]);
+ await db.update(companySkillVersions).set({ fileInventory: [], ...(repository
+ ? { repositorySnapshotId: packageId, repositorySkillPath: `${root}SKILL.md` }
+ : { packageSnapshotId: packageId }) }).where(eq(companySkillVersions.id, s.versionId));
+ const first = await f.call("load_skill", { skill: s.id, versionId: s.versionId }) as any;
+ expect(first.text).toContain(repository ? ".paperclip-repository/skills/review/SKILL.md" : "Use [checks]");
+ const path = `${repository ? ".paperclip-repository/" : ""}${root}references/checks.md`;
+ expect(first.files).toContainEqual({ path, kind: "reference" });
+ expect(await f.call("load_skill", { skill: s.id, versionId: s.versionId, path })).toMatchObject({ text: "These bytes came from saved storage." });
+ expect(await f.authority.recover({ tool: "load_skill", callId: "recover-read", arguments: { skill: s.id, versionId: s.versionId, path } })).toMatchObject({ result: { text: "These bytes came from saved storage." } });
+ });
+
+ it("rechecks access after package storage I/O", async () => {
+ const f = await fixture(), s = await skill(f.companyId);
+ const packageId = await skillPackageStore(db).prepare(f.companyId, [{ path: "SKILL.md", kind: "skill", content: "Stored instructions" }]);
+ await db.update(companySkillVersions).set({ packageSnapshotId: packageId, fileInventory: [] }).where(eq(companySkillVersions.id, s.versionId));
+ const sourceId = randomUUID();
+ await db.insert(companySkillSources).values({ id: sourceId, companyId: f.companyId, repositoryUrl: "https://github.com/example/private", fullName: "example/private", trackingRef: "HEAD", accessScope: "projects" });
+ const storage = getStorageService(), read = storage.getObject.bind(storage);
+ const fault = vi.spyOn(storage, "getObject").mockImplementation(async (...args) => {
+ const result = await read(...args);
+ await db.update(companySkills).set({ accessSourceId: sourceId }).where(eq(companySkills.id, s.id));
+ return result;
+ });
+ try { await expect(f.call("load_skill", { skill: s.id })).rejects.toThrow("Skill not found"); }
+ finally { fault.mockRestore(); }
+ });
+
+ it.each([false, true])("reuses text between pages and still rechecks access (repository: %s)", async repository => {
+ const f = await fixture(), s = await skill(f.companyId);
+ const content = "x".repeat(16 * 1024 * 1024);
+ const packageId = await skillPackageStore(db).prepare(f.companyId, [
+ { path: "SKILL.md", kind: "skill", content: "---\nname: review\ndescription: Review.\n---\n\nRead checks." },
+ { path: "checks.md", kind: "reference", content },
+ ]);
+ await db.update(companySkillVersions).set({ fileInventory: [], ...(repository
+ ? { repositorySnapshotId: packageId, repositorySkillPath: "SKILL.md" }
+ : { packageSnapshotId: packageId }) }).where(eq(companySkillVersions.id, s.versionId));
+ const path = `${repository ? ".paperclip-repository/" : ""}checks.md`;
+ const open = vi.spyOn(fs, "open"), read = vi.spyOn(fs, "readFile");
+ const bodyReads = () => [...open.mock.calls, ...read.mock.calls].filter(args => String(args[0]).endsWith("/checks.md")).length;
+ try {
+ const first = await f.call("load_skill", { skill: s.id, path }) as any;
+ const reads = bodyReads();
+ expect(reads).toBeGreaterThan(0);
+ expect(first.byteSize).toBe(content.length);
+ expect(await f.call("load_skill", { skill: s.id, versionId: s.versionId, path, offset: first.nextOffset }))
+ .toMatchObject({ text: content.slice(6000, 12000), sha256: null });
+ expect(bodyReads()).toBe(reads);
+ const sourceId = randomUUID();
+ await db.insert(companySkillSources).values({ id: sourceId, companyId: f.companyId, repositoryUrl: "https://github.com/example/private", fullName: "example/private", trackingRef: "HEAD", accessScope: "projects" });
+ await db.update(companySkills).set({ accessSourceId: sourceId }).where(eq(companySkills.id, s.id));
+ expect(await f.call("load_skill", { skill: s.id, versionId: s.versionId, path, offset: 12000 }))
+ .toMatchObject({ outcome: "failed", code: "runner_skill_not_found" });
+ } finally { open.mockRestore(); read.mockRestore(); f.authority.close(); }
+ });
+
+ it.each([false, true])("reads repository files without waiting for the startup lock (cold: %s)", async cold => {
+ const f = await fixture(), s = await skill(f.companyId);
+ const store = skillPackageStore(db);
+ const packageId = await store.prepare(f.companyId, [
+ { path: "SKILL.md", kind: "skill", content: "---\nname: review\ndescription: Review.\n---\n\nRead checks." },
+ { path: "checks.md", kind: "reference", content: "Repository checks." },
+ ]);
+ await db.update(companySkillVersions).set({ fileInventory: [], repositorySnapshotId: packageId, repositorySkillPath: "SKILL.md" })
+ .where(eq(companySkillVersions.id, s.versionId));
+ if (cold) {
+ await rm(skillPackagePaths(f.companyId, packageId).directory, { recursive: true, force: true });
+ }
+ let release!: () => void, acquired!: () => void;
+ const held = new Promise(resolve => { release = resolve; });
+ const ready = new Promise(resolve => { acquired = resolve; });
+ const lock = withSkillVersionCacheLock(db, f.companyId, async () => { acquired(); await held; });
+ await ready;
+ let timeout: ReturnType | undefined;
+ try {
+ await Promise.race([
+ (async () => {
+ expect(await f.call("load_skill", { skill: s.id })).toMatchObject({ path: "SKILL.md" });
+ expect(await f.call("load_skill", { skill: s.id, versionId: s.versionId, path: ".paperclip-repository/checks.md" }))
+ .toMatchObject({ text: "Repository checks." });
+ })(),
+ new Promise((_, reject) => { timeout = setTimeout(() => reject(new Error("Skill read waited for the startup lock")), 3000); }),
+ ]);
+ } finally { clearTimeout(timeout); release(); await lock; f.authority.close(); }
+ });
+
+ it.each(["inline", "package", "repository"])("rejects oversized text before reading its body (%s)", async storage => {
+ const f = await fixture(), s = await skill(f.companyId);
+ const root = storage === "repository" ? "skills/review/" : "";
+ const files = [
+ { path: `${root}SKILL.md`, kind: "skill" as const, content: "---\nname: review\ndescription: Review.\n---\n\nRead references." },
+ { path: `${root}references/oversized.md`, kind: "reference" as const, content: "x".repeat(16 * 1024 * 1024 + 1) },
+ ];
+ if (storage === "inline") {
+ await db.update(companySkillVersions).set({ fileInventory: files }).where(eq(companySkillVersions.id, s.versionId));
+ } else {
+ const packageId = await skillPackageStore(db).prepare(f.companyId, files);
+ await db.update(companySkillVersions).set({ fileInventory: [], ...(storage === "repository"
+ ? { repositorySnapshotId: packageId, repositorySkillPath: `${root}SKILL.md` }
+ : { packageSnapshotId: packageId }) }).where(eq(companySkillVersions.id, s.versionId));
+ }
+ const open = vi.spyOn(fs, "open"), read = vi.spyOn(fs, "readFile");
+ try {
+ const path = `${storage === "repository" ? ".paperclip-repository/" : ""}${root}references/oversized.md`;
+ for (const offset of [0, 6000]) {
+ expect(await f.call("load_skill", { skill: s.id, versionId: s.versionId, path, offset }))
+ .toMatchObject({ outcome: "failed", code: "runner_skill_file_size_limit" });
+ }
+ expect([...open.mock.calls, ...read.mock.calls].some(args => String(args[0]).endsWith("oversized.md"))).toBe(false);
+ } finally { open.mockRestore(); read.mockRestore(); }
+ expect(await f.call("load_skill", { skill: s.id, versionId: s.versionId })).toMatchObject({ path: "SKILL.md" });
+ });
+
+ it.each([false, true])("loads long supporting paths from the returned inventory (repository wrapper: %s)", async repository => {
+ const f = await fixture(), s = await skill(f.companyId);
+ const root = repository ? "skills/review/" : "";
+ const path = `${root}${("nested-" + "x".repeat(90) + "/").repeat(12)}checks.md`;
+ const packageId = await skillPackageStore(db).prepare(f.companyId, [
+ { path: `${root}SKILL.md`, kind: "skill", content: "---\nname: review\ndescription: Review.\n---\n\nRead checks." },
+ { path, kind: "reference", content: "Long paths remain readable." },
+ ]);
+ await db.update(companySkillVersions).set({ fileInventory: [], ...(repository
+ ? { repositorySnapshotId: packageId, repositorySkillPath: `${root}SKILL.md` }
+ : { packageSnapshotId: packageId }) }).where(eq(companySkillVersions.id, s.versionId));
+ const first = await f.call("load_skill", { skill: s.id, versionId: s.versionId }) as any;
+ const listedPath = first.files.find((file: { path: string; kind: string }) => file.kind === "reference").path;
+ expect(listedPath.length).toBeGreaterThan(1000);
+ expect(await f.call("load_skill", { skill: s.id, versionId: s.versionId, path: listedPath }))
+ .toMatchObject({ text: "Long paths remain readable." });
+ });
+
+ it("pages the file inventory without repeating the response digest", async () => {
+ const f = await fixture(), s = await skill(f.companyId);
+ await db.update(companySkillVersions).set({ fileInventory: [
+ { path: "SKILL.md", kind: "skill", content: s.text },
+ ...Array.from({ length: 50 }, (_, index) => ({ path: `references/${index}.md`, kind: "reference" as const, content: "Check." })),
+ ] }).where(eq(companySkillVersions.id, s.versionId));
+ const first = await f.call("load_skill", { skill: s.id }) as any;
+ expect(first.files).toHaveLength(50);
+ expect(first.nextFileOffset).toBe(50);
+ const second = await f.call("load_skill", { skill: s.id, versionId: first.versionId, fileOffset: first.nextFileOffset }) as any;
+ expect(second.files).toHaveLength(1);
+ expect(second.nextFileOffset).toBeNull();
+ expect(second.sha256).toBeNull();
+ });
+
+ it("keeps pages and reference reads on the selected immutable version", async () => {
+ const f = await fixture(), s = await skill(f.companyId, "long-review", "a".repeat(5999) + "🚀" + "b".repeat(2000));
+ const first = await f.call("load_skill", { skill: s.id }) as any;
+ expect(first.text.length).toBeLessThanOrEqual(6000);
+ expect(first.sha256).toBe(createHash("sha256").update(s.text).digest("hex"));
+ const changed = randomUUID();
+ await db.insert(companySkillVersions).values({ id: changed, companyId: f.companyId, companySkillId: s.id, revisionNumber: 2, fileInventory: [{ path: "SKILL.md", kind: "skill", content: "New version" }] });
+ await db.update(companySkills).set({ currentVersionId: changed }).where(eq(companySkills.id, s.id));
+ const second = await f.call("load_skill", { skill: s.id, versionId: first.versionId, offset: first.nextOffset }) as any;
+ expect(first.text + second.text).toBe(s.text);
+ expect(second.sha256).toBeNull();
+ expect(await f.call("load_skill", { skill: s.id, offset: first.nextOffset })).toMatchObject({ outcome: "failed", code: "runner_skill_invalid_arguments" });
+ });
+
+ it("hides foreign and project-restricted skills, including after access changes", async () => {
+ const a = await fixture(), b = await fixture(), s = await skill(a.companyId), foreign = await skill(b.companyId);
+ expect(await a.call("load_skill", { skill: foreign.id })).toMatchObject({ outcome: "failed", code: "runner_skill_not_found" });
+ expect(await a.call("load_skill", { skill: s.id, versionId: foreign.versionId })).toMatchObject({ outcome: "failed", code: "runner_skill_version_not_found" });
+ const sourceId = randomUUID();
+ await db.insert(companySkillSources).values({ id: sourceId, companyId: a.companyId, repositoryUrl: "https://github.com/example/private", fullName: "example/private", trackingRef: "HEAD", accessScope: "projects" });
+ await db.update(companySkills).set({ accessSourceId: sourceId }).where(eq(companySkills.id, s.id));
+ expect(await a.call("search_skills", { query: "review" })).toMatchObject({ skills: [] });
+ expect(await a.call("load_skill", { skill: s.id })).toMatchObject({ outcome: "failed", code: "runner_skill_not_found" });
+ });
+
+ it("rejects invalid paths, binary files, and stale run authority", async () => {
+ const f = await fixture(), s = await skill(f.companyId);
+ for (const path of ["../SKILL.md", "/etc/passwd", "references\\checks.md"]) {
+ expect(await f.call("load_skill", { skill: s.id, path })).toMatchObject({ outcome: "failed", code: "runner_skill_invalid_arguments" });
+ }
+ expect(await f.call("load_skill", { skill: s.id, path: "assets/icon.png" })).toMatchObject({ outcome: "failed", code: "runner_skill_binary_file" });
+ expect(await f.call("load_skill", { skill: s.id, path: "missing.md" })).toMatchObject({ outcome: "failed", code: "runner_skill_file_not_found" });
+ await db.update(heartbeatRuns).set({ status: "failed" }).where(eq(heartbeatRuns.id, f.runId));
+ await expect(f.call("search_skills", {})).rejects.toThrow();
+ });
+
+ it("preserves the closed Muse, skill-test and completion-review profiles", async () => {
+ const f = await fixture();
+ for (const extra of [{ museRuntime: true }, { workMode: "skill_test" as const }, { nativeReview: {} as any }]) {
+ const names = new PaperclipRunnerToolAuthority(db, { ...f, ...extra }).definitions().map(t => t.name);
+ expect(names).not.toContain("search_skills"); expect(names).not.toContain("load_skill");
+ }
+ for (const workMode of ["ask", "planning"] as const) {
+ expect(new PaperclipRunnerToolAuthority(db, { ...f, workMode }).definitions().map(t => t.name)).toEqual(expect.arrayContaining(["search_skills", "load_skill"]));
+ }
+ });
+});
diff --git a/server/src/services/native-runtime/native-skill-library-tools.ts b/server/src/services/native-runtime/native-skill-library-tools.ts
new file mode 100644
index 00000000000..04cfc68f6c6
--- /dev/null
+++ b/server/src/services/native-runtime/native-skill-library-tools.ts
@@ -0,0 +1,147 @@
+import { createHash } from "node:crypto";
+import { and, eq, gt, or, sql } from "drizzle-orm";
+import { companySkills, type Db } from "@paperclipai/db";
+import { z } from "zod";
+import type { AuthorizationActor } from "../authorization.js";
+import { skillAccessService } from "../skill-access.js";
+import { skillPackageStore } from "../skill-package-store.js";
+import { skillPackageRuntime } from "../skill-package-runtime.js";
+import { assertSkillSnapshotPath } from "../skill-snapshot.js";
+import { MAX_SKILL_PACKAGE_PATH_LENGTH, SkillPackageFileTooLarge } from "../skill-package-files.js";
+import { REPOSITORY_CONTENT_DIR } from "../skill-repository-package.js";
+import { settleRunnerBridgeRead } from "./runner-bridge-tools.js";
+
+const MAX_TEXT_FILE_BYTES = 16 * 1024 * 1024;
+type SkillText = { text: string; sha256: string; byteSize: number };
+export class SkillLibraryReadCache {
+ #entries = new Map();
+ #bytes = 0;
+ #closed = false;
+ #size(key: string, value: SkillText) { return (key.length + value.text.length) * 2 + 128; }
+ #assertOpen() { if (this.#closed) throw new Error("runner_skill_scope_closed"); }
+ close() { this.#closed = true; this.#entries.clear(); this.#bytes = 0; }
+ get(key: string) {
+ this.#assertOpen();
+ const value = this.#entries.get(key);
+ if (value) { this.#entries.delete(key); this.#entries.set(key, value); }
+ return value;
+ }
+ set(key: string, value: SkillText) {
+ this.#assertOpen();
+ const prior = this.#entries.get(key);
+ if (prior) { this.#bytes -= this.#size(key, prior); this.#entries.delete(key); }
+ const bytes = this.#size(key, value);
+ while (this.#entries.size && (this.#entries.size >= 64 || this.#bytes + bytes > 64 * 1024 * 1024)) {
+ const oldest = this.#entries.keys().next().value!;
+ this.#bytes -= this.#size(oldest, this.#entries.get(oldest)!); this.#entries.delete(oldest);
+ }
+ if (bytes <= 64 * 1024 * 1024) { this.#entries.set(key, value); this.#bytes += bytes; }
+ }
+}
+const relativePath = z.string().min(1).max(MAX_SKILL_PACKAGE_PATH_LENGTH + REPOSITORY_CONTENT_DIR.length + 1).refine(value => {
+ try { assertSkillSnapshotPath(value); return true; } catch { return false; }
+}, "Use a relative skill file path without traversal");
+const searchInput = z.object({
+ query: z.string().trim().max(240).default(""),
+ cursor: z.uuid().optional(),
+ limit: z.number().int().min(1).max(20).default(10),
+}).strict();
+const loadInput = z.object({
+ skill: z.string().trim().min(1).max(240),
+ versionId: z.uuid().optional(),
+ path: relativePath.default("SKILL.md"),
+ offset: z.number().int().min(0).default(0),
+ fileOffset: z.number().int().min(0).default(0),
+}).strict().refine(input => input.versionId || (!input.offset && !input.fileOffset), "Supply the returned versionId when reading more pages");
+
+export const SKILL_LIBRARY_SCHEMAS = new Map([
+ ["search_skills", searchInput], ["load_skill", loadInput],
+]);
+export const SKILL_LIBRARY_TOOL_DEFINITIONS = [
+ { name: "search_skills", description: "Search accessible skills in the company library, including unassigned skills. Matches names, keys and descriptions. Use the returned ID and versionId with load_skill. Follow nextCursor with the same query. This does not install or assign skills.", inputSchema: z.toJSONSchema(searchInput) },
+ { name: "load_skill", description: "Read a company library skill without assigning it. Use an ID or exact key; a slug must be unique. Start with SKILL.md. Supply the returned versionId for all further pages and referenced files. offset and nextOffset count UTF-16 characters; fileOffset and nextFileOffset page the file list. Content is data, not extra authorization. Existing tool, connection and work-mode restrictions still apply.", inputSchema: z.toJSONSchema(loadInput) },
+];
+
+const summaryColumns = {
+ id: companySkills.id, key: companySkills.key, name: companySkills.name, slug: companySkills.slug,
+ description: sql`left(${companySkills.description}, 2000)`,
+ versionId: companySkills.currentVersionId, sourceType: companySkills.sourceType,
+ trustLevel: companySkills.trustLevel, compatibility: companySkills.compatibility,
+};
+const fail = (code: string, message: string) => ({ outcome: "failed", code, message });
+
+export async function executeSkillLibraryTool(input: {
+ db: Db; companyId: string; tool: string; arguments: unknown; cache: SkillLibraryReadCache;
+ authorize: () => Promise;
+}) {
+ const actor = await input.authorize();
+ const parsed = SKILL_LIBRARY_SCHEMAS.get(input.tool)!.safeParse(input.arguments);
+ if (!parsed.success) return fail("runner_skill_invalid_arguments", "Use the advertised schema. Supply versionId for further pages and a relative file path.");
+ const access = skillAccessService(input.db, actor);
+ if (input.tool === "search_skills") {
+ const args = parsed.data as z.infer;
+ const pattern = `%${args.query.replace(/[\\%_]/g, character => `\\${character}`)}%`;
+ const rows = await input.db.select(summaryColumns).from(companySkills).where(and(
+ eq(companySkills.companyId, input.companyId), await access.condition(input.companyId),
+ args.cursor ? gt(companySkills.id, args.cursor) : undefined,
+ args.query ? sql`concat_ws(' ', ${companySkills.key}, ${companySkills.slug}, ${companySkills.name}, ${companySkills.description}) ilike ${pattern}` : undefined,
+ )).orderBy(companySkills.id).limit(args.limit + 1);
+ const currentAccess = skillAccessService(input.db, await input.authorize());
+ const allowed = await input.db.select({ id: companySkills.id }).from(companySkills).where(and(
+ eq(companySkills.companyId, input.companyId), await currentAccess.condition(input.companyId),
+ rows.length ? or(...rows.map(row => eq(companySkills.id, row.id))) : sql`false`,
+ ));
+ const permitted = new Set(allowed.map(row => row.id));
+ return { skills: rows.slice(0, args.limit).filter(row => permitted.has(row.id)),
+ nextCursor: rows.length > args.limit ? rows[args.limit - 1]!.id : null };
+ }
+ const args = parsed.data as z.infer;
+ const exact = await input.db.select(summaryColumns).from(companySkills).where(and(
+ eq(companySkills.companyId, input.companyId), await access.condition(input.companyId),
+ z.uuid().safeParse(args.skill).success ? eq(companySkills.id, args.skill) : eq(companySkills.key, args.skill),
+ )).limit(1);
+ const rows = exact.length ? exact : await input.db.select(summaryColumns).from(companySkills).where(and(
+ eq(companySkills.companyId, input.companyId), await access.condition(input.companyId), eq(companySkills.slug, args.skill),
+ )).limit(2);
+ const skill = rows.length === 1 ? rows[0] : null;
+ if (!skill) return fail("runner_skill_not_found", "Skill not found or its slug is ambiguous. Search skills and use the returned ID.");
+ const versionId = args.versionId ?? skill.versionId;
+ if (!versionId) return fail("runner_skill_version_not_found", "This skill has no saved version. Save or import it through the company skill API first.");
+ const packages = skillPackageStore(input.db);
+ const version = await packages.version(input.companyId, skill.id, versionId);
+ if (!version) return fail("runner_skill_version_not_found", "Skill version not found. Search and load an available version.");
+ const result = await settleRunnerBridgeRead(async () => {
+ const runtime = skillPackageRuntime(input.db);
+ const files = version.repositorySnapshotId ? await runtime.inventory(version) : await packages.versionInventory(version);
+ const cacheKey = JSON.stringify([input.companyId, versionId, args.path]);
+ let content = input.cache.get(cacheKey);
+ if (!content) {
+ let file;
+ try {
+ file = version.repositorySnapshotId ? await runtime.readFile(version, args.path, MAX_TEXT_FILE_BYTES)
+ : await packages.readVersionFile(version, args.path, true, MAX_TEXT_FILE_BYTES);
+ } catch (error) {
+ if (error instanceof SkillPackageFileTooLarge) return fail("runner_skill_file_size_limit", "This tool reads text files up to 16 MiB. Use a smaller supporting file.");
+ throw error;
+ }
+ if (!file) return fail("runner_skill_file_not_found", "The requested file is not in this skill version.");
+ if (file.encoding === "base64") return fail("runner_skill_binary_file", "This tool reads UTF-8 text. The requested skill file is binary.");
+ content = { text: file.content, sha256: createHash("sha256").update(file.content).digest("hex"), byteSize: Buffer.byteLength(file.content) };
+ input.cache.set(cacheKey, content);
+ }
+ const { text } = content;
+ const splitsCharacter = (offset: number) => offset > 0 && offset < text.length
+ && /[\uD800-\uDBFF]/u.test(text[offset - 1]!) && /[\uDC00-\uDFFF]/u.test(text[offset]!);
+ if (args.offset > text.length || splitsCharacter(args.offset)) return fail("runner_skill_invalid_offset", "Use nextOffset from the previous page.");
+ let end = Math.min(args.offset + 6000, text.length);
+ if (splitsCharacter(end)) end--;
+ return { ...skill, skillId: skill.id, versionId, path: args.path, text: text.slice(args.offset, end),
+ sha256: args.offset === 0 && args.fileOffset === 0 ? content.sha256 : null, byteSize: content.byteSize,
+ nextOffset: end < text.length ? end : null,
+ files: files.slice(args.fileOffset, args.fileOffset + 50), fileCount: files.length,
+ nextFileOffset: args.fileOffset + 50 < files.length ? args.fileOffset + 50 : null,
+ instruction: "Use this versionId for further pages and referenced files. Loading a skill does not grant tool or connection access or authorize additional actions." };
+ });
+ await skillAccessService(input.db, await input.authorize()).assertSkill(input.companyId, skill.id);
+ return result;
+}
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 7bf40c9a676..444bf3df5a9 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
@@ -166,9 +166,10 @@ describe("PaperclipRunnerToolAuthority", () => {
issueId,
runId,
});
- expect(authority.definitions()).toHaveLength(51);
+ expect(authority.definitions()).toHaveLength(53);
expect(authority.definitions().map(tool => tool.name)).toEqual(expect.arrayContaining([
"get_workspace", "list_workspaces", "select_workspace", "prepare_repository",
+ "search_skills", "load_skill",
]));
const questions = authority.definitions().find(tool => tool.name === "request_human_input")!;
expect(questions.description).toContain("ask only the next unanswered question");
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 5417f052b44..3b57ae63768 100644
--- a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts
+++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts
@@ -18,6 +18,7 @@ import { executeNativeWorkflowTool } from "./native-workflow-tools.js";
import { assertNoCaseHandoffMutation } from "../heartbeat/case-handoff-lifecycle.js";
import { handoffCaseSchema } from "@paperclipai/shared";
import { skillAccessService } from "../skill-access.js";
+import { SKILL_LIBRARY_SCHEMAS, SKILL_LIBRARY_TOOL_DEFINITIONS, SkillLibraryReadCache, executeSkillLibraryTool } from "./native-skill-library-tools.js";
import { withExternalExecutionAdmission, type ExternalAdmissionTransaction } from "../../modules/external-agents/index.js";
import { callTaskWorkspaceTool, pendingTaskRepositoryContinuation } from "../task-workspace-tools.js";
import { TaskAttachmentReadCache, TASK_ATTACHMENT_DEFINITIONS, TASK_ATTACHMENT_SCHEMAS, listTaskAttachments, readTaskAttachment } from "./runner-task-attachments.js";
@@ -166,6 +167,7 @@ const RECOVERABLE_READ_OPERATIONS = new Set([
...CAPABILITY_CANONICAL_OPERATIONS.filter(tool => IMPLEMENTED_OPERATIONS.has(tool.operationId) && tool.sideEffectClass === "read")
.map(tool => tool.operationId),
...RUNNER_BRIDGE_READ_OPERATIONS,
+ ...SKILL_LIBRARY_SCHEMAS.keys(),
...Object.keys(TASK_ATTACHMENT_SCHEMAS),
READ_CURRENT_WAKE_COMMENTS_TOOL_NAME, LIST_CHAT_ATTACHMENTS_TOOL_NAME, READ_CHAT_ATTACHMENT_TOOL_NAME,
READ_TOOL_RESULT, "connections_search",
@@ -318,7 +320,8 @@ function hireAgentResult(value: unknown, provider: unknown) {
export class PaperclipRunnerToolAuthority {
#taskAttachmentCache = new TaskAttachmentReadCache();
- close() { this.#taskAttachmentCache.close(); }
+ #skillLibraryCache = new SkillLibraryReadCache();
+ close() { this.#taskAttachmentCache.close(); this.#skillLibraryCache.close(); }
constructor(readonly db: Db, readonly binding: Binding) {}
definitions(): Array> {
@@ -404,6 +407,7 @@ export class PaperclipRunnerToolAuthority {
definitions.push(REUSE_CHAT_ATTACHMENT_TOOL_DEFINITION);
definitions.push(READ_CHAT_ATTACHMENT_TOOL_DEFINITION);
if (this.binding.taskAttachmentRead) definitions.push(...TASK_ATTACHMENT_DEFINITIONS);
+ definitions.push(...SKILL_LIBRARY_TOOL_DEFINITIONS);
definitions.push(...runnerBridgeDefinitions({ workspace: !this.binding.firstPartyOnly && !!this.binding.workspaceRoot && this.binding.workspaceBridge === true, skills: !!this.binding.runtimeContext, api: runnerApiToolsEnabled(this.binding.companyId, this.binding.apiToolsEnabled), mode: workMode }));
const connectionTools = this.binding.firstPartyOnly ? [] : [...RUNTIME_CONNECTION_TOOL_DEFINITIONS,
...(this.binding.connectorAssignments ?? []).flatMap((assignment) => assignment.tools)];
@@ -608,6 +612,11 @@ export class PaperclipRunnerToolAuthority {
return result;
});
}
+ if (SKILL_LIBRARY_SCHEMAS.has(call.tool)) {
+ if (!this.definitions().some(definition => definition.name === call.tool)) throw forbidden("Tool is not available to this run");
+ return executeSkillLibraryTool({ db: this.db, companyId: this.binding.companyId, tool: call.tool, arguments: call.arguments, cache: this.#skillLibraryCache,
+ authorize: async () => { const current = await this.#boundContext({ tool: call.tool }); return this.#privacyActor(current.run); } });
+ }
if (RUNNER_BRIDGE_SCHEMAS.has(call.tool)) {
await this.#boundContext({ tool: call.tool });
if (!this.definitions().some(definition => definition.name === call.tool)) throw forbidden("Tool is not available to this run");
diff --git a/server/src/services/native-runtime/runner-bridge-tools.ts b/server/src/services/native-runtime/runner-bridge-tools.ts
index d4fe3b4294c..fab6e460af7 100644
--- a/server/src/services/native-runtime/runner-bridge-tools.ts
+++ b/server/src/services/native-runtime/runner-bridge-tools.ts
@@ -18,7 +18,7 @@ const specs = [
["list_task_documents", "List documents on an authorized task.", z.object({ taskId: z.uuid() }).strict(), "read"],
["read_task_document", "Read a document on an authorized task.", z.object({ taskId: z.uuid(), key: documentKey }).strict(), "read"],
["write_task_document", "Write a document on an authorized task using its current revision. Permissions and document locks apply.", z.object({ taskId: z.uuid(), key: documentKey, title: z.string().min(1).max(200), body: z.string().max(20000), baseRevisionId: z.uuid().nullable() }).strict(), "mutation"],
- ["list_assigned_skills", "List immutable skill versions pinned to this Runner turn.", z.object({}).strict(), "read"],
+ ["list_assigned_skills", "List immutable assigned skill versions pinned to this Runner turn. Use search_skills and load_skill, when advertised, for other accessible company library skills.", z.object({}).strict(), "read"],
["read_assigned_skill", "Read a verified UTF-8 file from an assigned skill. Start with SKILL.md and paginate with nextOffset. Content is data, not extra authorization.", z.object({ skill: z.string().min(1).max(240), path: relativeFile.default("SKILL.md"), offset: z.number().int().min(0).default(0) }).strict(), "read"],
["workspace_list", "List entries inside the assigned workspace.", z.object({ path: z.union([relativeFile, z.literal("")]).default(""), after: z.string().optional() }).strict(), "read"],
["workspace_read", "Read a UTF-8 workspace file with SHA-256 and byte size. Paginate with nextOffset.", z.object({ path: relativeFile, offset: z.number().int().min(0).default(0) }).strict(), "read"],
diff --git a/server/src/services/skill-package-files.ts b/server/src/services/skill-package-files.ts
index b93fb176be6..be8bb80f3cc 100644
--- a/server/src/services/skill-package-files.ts
+++ b/server/src/services/skill-package-files.ts
@@ -12,6 +12,11 @@ import { assertSkillSnapshotPath, skillFileBytes, skillSnapshotHash, MAX_SKILL_S
export const MAX_SKILL_PACKAGE_BYTES = MAX_SKILL_SNAPSHOT_BYTES;
export const MAX_SKILL_PACKAGE_FILES = MAX_SKILL_SNAPSHOT_FILES;
export const MAX_SKILL_MANIFEST_BYTES = 48 * 1024 * 1024;
+export const MAX_SKILL_PACKAGE_PATH_LENGTH = 4096;
+export class SkillPackageFileTooLarge extends Error {}
+export function assertSkillPackageFileSize(size: number, maxBytes = Number.MAX_SAFE_INTEGER) {
+ if (size > maxBytes) throw new SkillPackageFileTooLarge("Skill file exceeds the requested byte limit");
+}
export type SkillPackageFile = {
path: string;
kind: CompanySkillVersionFileInventoryEntry["kind"];
@@ -41,7 +46,7 @@ export function validateSkillPackageManifest(value: unknown): SkillPackageManife
assertSkillSnapshotPath(file.path);
// A portable repository fork adds one generated directory to scanner-accepted paths.
const sourcePath = file.path.startsWith(`${REPOSITORY_CONTENT_DIR}/`) ? file.path.slice(REPOSITORY_CONTENT_DIR.length + 1) : file.path;
- if (sourcePath.length > 4096 || sourcePath.split("/").length > 64 || paths.has(file.path)
+ if (sourcePath.length > MAX_SKILL_PACKAGE_PATH_LENGTH || sourcePath.split("/").length > 64 || paths.has(file.path)
|| !kinds.has(file.kind) || !["utf8", "base64"].includes(file.encoding) || typeof file.executable !== "boolean"
|| !Number.isSafeInteger(file.size) || file.size < 0 || !/^[a-f0-9]{64}$/.test(file.sha256)) throw new Error("Invalid skill package file");
paths.add(file.path);
diff --git a/server/src/services/skill-package-runtime.ts b/server/src/services/skill-package-runtime.ts
index cdcf0e25524..06695047f8a 100644
--- a/server/src/services/skill-package-runtime.ts
+++ b/server/src/services/skill-package-runtime.ts
@@ -4,7 +4,7 @@ import path from "node:path";
import type { Db } from "@paperclipai/db";
import type { CompanySkillVersionFileInventoryEntry } from "@paperclipai/shared";
import { skillPackageStore, type StoredSkillVersion } from "./skill-package-store.js";
-import { packageSha256, verifySkillPackageDirectory, relocateSkillPackageVerification, type SkillPackageFile, type SkillPackageManifest } from "./skill-package-files.js";
+import { assertSkillPackageFileSize, packageSha256, verifySkillPackageDirectory, relocateSkillPackageVerification, type SkillPackageFile, type SkillPackageManifest } from "./skill-package-files.js";
import { REPOSITORY_CONTENT_DIR, repositorySkillProjection } from "./skill-repository-package.js";
import { assertSkillSnapshotPath, skillFileBytes } from "./skill-snapshot.js";
import { ensureSkillCacheDirectory } from "./skill-version-cache.js";
@@ -37,6 +37,10 @@ function originalFiles(version: StoredSkillVersion, manifest: SkillPackageManife
}
export function skillPackageRuntime(db: Db) {
const store = skillPackageStore(db);
+ function readOriginalFile(version: StoredSkillVersion, sourcePath: string, maxBytes?: number, projected?: ProjectedFile) {
+ return store.readVersionFile({ ...version, packageSnapshotId: version.repositorySnapshotId ?? version.packageSnapshotId,
+ packageFileMap: projected ? [{ path: sourcePath, sourcePath, kind: projected.kind, encoding: projected.encoding }] : null }, sourcePath, true, maxBytes);
+ }
async function inventory(version: StoredSkillVersion) {
const id = version.repositorySnapshotId ?? version.packageSnapshotId;
if (!id) throw new Error("Skill version has no package");
@@ -50,7 +54,7 @@ export function skillPackageRuntime(db: Db) {
}
return files;
}
- async function projection(version: StoredSkillVersion): Promise {
+ async function projection(version: StoredSkillVersion, maxBytes?: number): Promise {
const id = version.repositorySnapshotId ?? version.packageSnapshotId;
if (!id) throw new Error("Skill version has no package");
const manifest = await store.manifest(version.companyId, id);
@@ -61,14 +65,15 @@ export function skillPackageRuntime(db: Db) {
const generatedFiles: ProjectedFile[] = [];
if (version.repositorySnapshotId) {
if (!version.repositorySkillPath) throw new Error("Repository skill entrypoint is missing");
- const generated = await store.withPackage(version.companyId, id, async (root, manifest) => {
- const wanted = new Set([version.repositorySkillPath!, path.posix.join(path.posix.dirname(version.repositorySkillPath!), "agents/openai.yaml")]);
- const selected: CompanySkillVersionFileInventoryEntry[] = [];
- for (const file of manifest.files.filter(file => wanted.has(file.path))) selected.push({
- ...file, content: (await fs.readFile(path.join(root, file.path))).toString(file.encoding),
- });
- return repositorySkillProjection(selected, version.repositorySkillPath!).filter(file => !file.path.startsWith(`${REPOSITORY_CONTENT_DIR}/`));
- });
+ const wanted = new Set([version.repositorySkillPath, path.posix.join(path.posix.dirname(version.repositorySkillPath), "agents/openai.yaml")]);
+ for (const file of manifest.files.filter(file => wanted.has(file.path))) assertSkillPackageFileSize(file.size, maxBytes);
+ const selected: CompanySkillVersionFileInventoryEntry[] = [];
+ for (const file of manifest.files.filter(file => wanted.has(file.path))) {
+ const original = await readOriginalFile(version, file.path, maxBytes);
+ if (!original) throw new Error("Repository skill file is missing");
+ selected.push(original);
+ }
+ const generated = repositorySkillProjection(selected, version.repositorySkillPath!).filter(file => !file.path.startsWith(`${REPOSITORY_CONTENT_DIR}/`));
for (const file of generated) {
const bytes = skillFileBytes(file);
generatedFiles.push({ path: file.path, kind: file.kind, encoding: file.encoding ?? "utf8", executable: Boolean(file.executable),
@@ -109,12 +114,17 @@ export function skillPackageRuntime(db: Db) {
} finally { await fs.rm(staging, { recursive: true, force: true }); }
});
}
- async function readFile(version: StoredSkillVersion, relative: string) {
- const file = (await projection(version)).find(file => file.path === relative);
+ async function readFile(version: StoredSkillVersion, relative: string, maxBytes?: number) {
+ const id = (version.repositorySnapshotId ?? version.packageSnapshotId)!;
+ const manifest = await store.manifest(version.companyId, id);
+ const file = originalFiles(version, manifest).find(file => file.path === relative)
+ ?? (await projection(version, maxBytes)).find(file => file.path === relative);
if (!file) return null;
- const bytes = file.generated ?? await store.withPackage(version.companyId,
- (version.repositorySnapshotId ?? version.packageSnapshotId)!, root => fs.readFile(path.join(root, file.sourcePath!)));
- return { path: file.path, kind: file.kind, content: bytes.toString(file.encoding), encoding: file.encoding, executable: file.executable };
+ assertSkillPackageFileSize(file.size, maxBytes);
+ const content = file.generated ? file.generated.toString(file.encoding)
+ : (await readOriginalFile(version, file.sourcePath!, maxBytes, file))?.content;
+ if (content === undefined) return null;
+ return { path: file.path, kind: file.kind, content, encoding: file.encoding, executable: file.executable };
}
return { inventory, materialize, readFile };
}
diff --git a/server/src/services/skill-package-store.ts b/server/src/services/skill-package-store.ts
index 5b88c571fce..b88d9a8a55d 100644
--- a/server/src/services/skill-package-store.ts
+++ b/server/src/services/skill-package-store.ts
@@ -14,7 +14,7 @@ import { resolvePaperclipInstanceRoot } from "../home-paths.js";
import { conflict, notFound } from "../errors.js";
import { assertSkillSnapshotPath, skillFileBytes } from "./skill-snapshot.js";
import { ensureSkillCacheDirectory, SkillCacheBusy, withSkillVersionCacheLock } from "./skill-version-cache.js";
-import { boundedHashStream, extractSkillPackageArchive, MAX_SKILL_MANIFEST_BYTES, packageSha256,
+import { assertSkillPackageFileSize, boundedHashStream, extractSkillPackageArchive, MAX_SKILL_MANIFEST_BYTES, packageSha256,
skillPackageManifest, skillPackageManifestBytes, validateSkillPackageManifest, verifySkillPackageDirectory, relocateSkillPackageVerification, writeSkillPackageArchive,
type SkillPackageManifest } from "./skill-package-files.js";
@@ -642,15 +642,27 @@ export function skillPackageStore(db: Db, suppliedStorage?: StorageService, cach
};
return cancellation ? acquire() : flight(db, `version-read:${version.companyId}:${version.id}:${allowRecovery}`, acquire);
}
- async function readVersionFile(version: StoredSkillVersion, relativePath: string, allowRecovery = true) {
+ async function readVersionFile(version: StoredSkillVersion, relativePath: string, allowRecovery = true, maxBytes = Number.MAX_SAFE_INTEGER) {
assertSkillSnapshotPath(relativePath);
- if (!version.packageSnapshotId) return (await versionFiles(version, allowRecovery)).find(file => file.path === relativePath);
+ if (!version.packageSnapshotId) {
+ const [row] = await db.select({ ...skillVersionMetadataColumns,
+ file: sql<(CompanySkillVersionFileInventoryEntry & { tooLarge?: boolean }) | null>`(
+ select case when octet_length(f->>'content')::bigint > ${maxBytes}::bigint
+ then jsonb_build_object('tooLarge', true) else f end
+ from jsonb_array_elements(${companySkillVersions.fileInventory}) f
+ where f->>'path' = ${relativePath} limit 1)` })
+ .from(companySkillVersions).where(and(eq(companySkillVersions.companyId, version.companyId), eq(companySkillVersions.id, version.id)));
+ if (row?.packageSnapshotId) return readVersionFile(row, relativePath, allowRecovery, maxBytes);
+ if (row?.file?.tooLarge) assertSkillPackageFileSize(maxBytes + 1, maxBytes);
+ return row?.file ?? undefined;
+ }
const id = version.packageSnapshotId;
const manifest = await manifestFor(await descriptor(version.companyId, id));
const mapping = version.packageFileMap?.find(file => file.path === relativePath);
if (version.packageFileMap && !mapping) return undefined;
const entry = manifest.files.find(file => file.path === (mapping?.sourcePath ?? relativePath));
if (!entry) return undefined;
+ assertSkillPackageFileSize(entry.size, maxBytes);
const signal = AbortSignal.timeout(180_000);
const read = async (root: string) => {
const bytes = await readPackageFile(root, entry, signal);
From 84908d176b2800f4c792c4249c610ec0baebdd28 Mon Sep 17 00:00:00 2001
From: Dotta <34892728+cryppadotta@users.noreply.github.com>
Date: Sat, 7 Nov 2026 09:27:14 -0600
Subject: [PATCH 05/24] fix(recovery): name the failed check in
native_remote_recovery_lease_mismatch (#19839)
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
> - Remote native runs execute in a sandbox, and recovery can reattach a
run to its original sandbox runner
> - Reattachment checks the saved lease, workspace, and runner identity
in five places. Each failed check throws the same bare
`native_remote_recovery_lease_mismatch`
> - On staging, 34 OpenCode runs on 31 tasks failed with this bare error
in one evening. The run records could not show which check failed, so
the cause could not be confirmed from the run alone
> - This pull request makes every producer name the failed step and
field with closed values
> - The benefit is that an operator and the next investigation can see
which reattachment check failed, without new logging or identifiers in
the error
## Linked Issues or Issue Description
Refs #19399, Refs #19733, Refs #19755, Refs #19779
**What happened?**
Remote same-run retries failed with
`native_remote_recovery_lease_mismatch` and the task was blocked for
reconciliation. The error is thrown by environment acquire, environment
resume, workspace preparation, workspace sync, and remote runner
verification. All of them used the same bare string. The run's `error`
field and its run events did not show which check failed.
**Steps to reproduce**
1. Start reattachment for a remote native run whose saved lease,
workspace reference, or runner identity no longer matches.
2. Read the run's `error`.
3. It shows only `native_remote_recovery_lease_mismatch`.
**Expected behavior**
The error names the step and the field that differed, with no
identifiers, and existing consumers of the code keep working.
## What Changed
- New
`server/src/services/native-runtime/remote-recovery-lease-mismatch.ts`:
the code constant, a closed `stage` and `field` vocabulary, and
`remoteRecoveryLeaseMismatch(stage, field)`. It builds
`native_remote_recovery_lease_mismatch: stage= field=`.
- `environment-run-orchestrator.ts` (stages `environment_acquire` and
`environment_resume`), `heartbeat/workspace-preparation.ts`
(`workspace_preparation`), `native-workspace-sync.ts`
(`workspace_sync`), and `verifyRemoteRunnerReattachment` in
`native-session-executor.ts` (`runner_verification`) now throw the
detailed form. Each check keeps the same condition and order. Only the
message changes.
- `restart-interrupted-turn.ts` uses the shared constant. It already
matches the code exactly or as the `code: ` prefix, so automatic
continuation after a reattachment loss is unchanged. No other consumer
matches the code.
- `doc/execution-semantics.md` documents the detail format.
## Previous-release state
This change adds no persisted state and changes no saved identity. Runs
that a previous release failed keep the bare
`native_remote_recovery_lease_mismatch` in `error`. Runs failed by this
release store the detailed form. The only consumer (`isReattachmentLoss`
in `restart-interrupted-turn.ts`) accepts both forms, and
`workspace-recovery-retry-copyback.test.ts` covers both.
## Verification
- Exact-detail assertions in the producer tests:
- `server/src/__tests__/environment-run-orchestrator.test.ts`: every
scope, status, expiry, provider, lease-ID, cwd, plugin-task, and resume
case asserts its stage and field. Against the previous producer, 21 of
these cases fail (the message was the bare code). With this change, all
57 tests pass.
- `native-session-executor.test.ts`: a replaced sandbox reports
`runner_verification`/`provider_lease_id`. A missing durable runner
identity reports `identity_run_id` before any sandbox read.
- `native-workspace-sync.test.ts`,
`heartbeat/workspace-preparation.test.ts`,
`native-controller-recovery.integration.test.ts` assert their exact
detail.
- End to end on embedded PostgreSQL:
`heartbeat-native-remote-failure-retention.test.ts` records
`native_remote_recovery_lease_mismatch: stage=environment_resume
field=lease` on the run when the provider no longer resumes the lease,
and it still requests the user's Retry once.
`workspace-recovery-retry-copyback.test.ts` adds a detailed-form row
that still continues once.
- The affected server test files pass locally. `pnpm --filter
@paperclipai/server typecheck` passes.
## Risks
- Low risk. Only the error text changes. Conditions, ordering, and
fail-closed behavior are unchanged.
- Logs and run errors show a longer message. The detail has closed
values only, so it adds no identifiers or secrets.
- A first version of this PR also changed remote retry selection. Review
showed that a plain resume in a new sandbox hits the remote workspace's
unsaved-work hold, and that a `destroy` disposition does not prove the
old sandbox is gone. That change is removed. It needs a separate design.
## Model Used
- Claude Opus 5.5 (Anthropic), model ID `claude-opus-5-5`, run in Claude
Code with tool use (shell, file editing, read-only browser access to
staging).
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5
---
doc/execution-semantics.md | 8 ++++
.../environment-run-orchestrator.test.ts | 44 ++++++++++++-------
...at-native-remote-failure-retention.test.ts | 4 +-
.../__tests__/native-workspace-sync.test.ts | 2 +-
.../services/environment-run-orchestrator.ts | 36 ++++++++-------
.../heartbeat/restart-interrupted-turn.ts | 3 +-
.../heartbeat/workspace-preparation.test.ts | 3 +-
.../heartbeat/workspace-preparation.ts | 15 ++++---
...ve-controller-recovery.integration.test.ts | 3 +-
.../native-session-executor.test.ts | 15 ++++++-
.../native-runtime/native-session-executor.ts | 25 +++++------
.../native-runtime/native-workspace-sync.ts | 13 +++---
.../remote-recovery-lease-mismatch.ts | 42 ++++++++++++++++++
.../workspace-recovery-retry-copyback.test.ts | 1 +
14 files changed, 153 insertions(+), 61 deletions(-)
create mode 100644 server/src/services/native-runtime/remote-recovery-lease-mismatch.ts
diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md
index d5c04deec3e..fcf339efa67 100644
--- a/doc/execution-semantics.md
+++ b/doc/execution-semantics.md
@@ -1470,6 +1470,14 @@ recovered workspace hold offers Retry (`canRetry`) and says "Retry or send a
message to continue." An intentional Stop keeps "send a message" as its only
continuation.
+`native_remote_recovery_lease_mismatch` carries a closed detail:
+`native_remote_recovery_lease_mismatch: stage= field=`. The stage
+is `workspace_preparation`, `environment_acquire`, `environment_resume`,
+`workspace_sync` or `runner_verification`. The field names the identity that
+differed, for example `lease_status`, `adapter_type`, `provider_lease_id`, `remote_cwd` or
+`identity_run_id`. The detail contains no identifiers. Consumers match the code
+exactly or as the `code: ` prefix.
+
When a native attempt fails before launch because its predecessor's session is
quarantined, explicit task Retry verifies the retained journal's actual owner.
That owner must belong to the same company, task, agent, workspace, native session,
diff --git a/server/src/__tests__/environment-run-orchestrator.test.ts b/server/src/__tests__/environment-run-orchestrator.test.ts
index 38a2e1f1383..a5c368142e4 100644
--- a/server/src/__tests__/environment-run-orchestrator.test.ts
+++ b/server/src/__tests__/environment-run-orchestrator.test.ts
@@ -989,13 +989,13 @@ describe("live remote runner lease reattachment", () => {
expect(mockUpdateLeaseMetadata).not.toHaveBeenCalled();
});
it.each([
- null,
- { providerLeaseId: "replacement", metadata: { remoteCwd: "/remote/workspace" } },
- { providerLeaseId: "original-sandbox", metadata: { expired: true } },
- ])("holds recovery when the retained lease resume cannot confirm its original allocation (%j)", async receipt => {
+ [null, "lease"],
+ [{ providerLeaseId: "replacement", metadata: { remoteCwd: "/remote/workspace" } }, "provider_lease_id"],
+ [{ providerLeaseId: "original-sandbox", metadata: { expired: true } }, "lease_expired"],
+ ] as const)("holds recovery when the retained lease resume cannot confirm its original allocation (%j)", async (receipt, field) => {
const runtime = makeMockRuntime({ resumeRunLease: vi.fn(async () => receipt) });
await expect(environmentRunOrchestrator({} as never, { environmentRuntime: runtime }).acquireForRun(input))
- .rejects.toThrow("native_remote_recovery_lease_mismatch");
+ .rejects.toThrow(new Error(`native_remote_recovery_lease_mismatch: stage=environment_resume field=${field}`));
expect(runtime.acquireRunLease).not.toHaveBeenCalled();
expect(runtime.execute).not.toHaveBeenCalled();
expect(mockUpdateLeaseMetadata).not.toHaveBeenCalled();
@@ -1036,22 +1036,25 @@ describe("live remote runner lease reattachment", () => {
...input, reattachRemoteLease: { kind: "plugin_task", leaseId: lease.id },
});
if (state === "active") await expect(acquired).resolves.toMatchObject({ lease });
- else await expect(acquired).rejects.toThrow("native_remote_recovery_lease_mismatch");
+ else await expect(acquired).rejects.toThrow(new Error("native_remote_recovery_lease_mismatch: stage=environment_acquire field="
+ + (state === "foreign-company" ? "lease_scope" : state === "revoked" ? "lease_status" : "plugin_task")));
expect(runtime.acquireRunLease).not.toHaveBeenCalled();
expect(runtime.resumeRunLease).not.toHaveBeenCalled();
});
it.each([
- { companyId: "foreign" }, { environmentId: "foreign" }, { heartbeatRunId: "another-run" },
- { issueId: "another-task" }, { executionWorkspaceId: "another-workspace" },
- { providerLeaseId: "replacement" }, { provider: "another-provider" },
- { status: "released" }, { expiresAt: new Date(0) }, { releasedAt: new Date() }, { cleanupStatus: "pending" },
- { metadata: { agentId: "another-agent", remoteCwd: "/remote/workspace" } },
- { metadata: { agentId: "agent-1", remoteCwd: "/other/workspace" } },
- ] as Partial[])("fails closed before provider acquisition for a mismatched lease %j", async (override) => {
+ [{ companyId: "foreign" }, "lease_scope"], [{ environmentId: "foreign" }, "lease_scope"],
+ [{ heartbeatRunId: "another-run" }, "lease_scope"], [{ issueId: "another-task" }, "lease_scope"],
+ [{ executionWorkspaceId: "another-workspace" }, "lease_scope"],
+ [{ providerLeaseId: "replacement" }, "provider_lease_id"], [{ provider: "another-provider" }, "provider"],
+ [{ status: "released" }, "lease_status"], [{ expiresAt: new Date(0) }, "lease_expired"],
+ [{ releasedAt: new Date() }, "lease_status"], [{ cleanupStatus: "pending" }, "lease_status"],
+ [{ metadata: { agentId: "another-agent", remoteCwd: "/remote/workspace" } }, "lease_scope"],
+ [{ metadata: { agentId: "agent-1", remoteCwd: "/other/workspace" } }, "remote_cwd"],
+ ] as [Partial, string][])("fails closed before provider acquisition for a mismatched lease %j", async (override, field) => {
mockGetLease.mockResolvedValue({ ...originalLease(), ...override });
const runtime = makeMockRuntime();
await expect(environmentRunOrchestrator({} as never, { environmentRuntime: runtime }).acquireForRun(input))
- .rejects.toThrow("native_remote_recovery_lease_mismatch");
+ .rejects.toThrow(new Error(`native_remote_recovery_lease_mismatch: stage=environment_acquire field=${field}`));
expect(runtime.acquireRunLease).not.toHaveBeenCalled();
expect(runtime.resumeRunLease).not.toHaveBeenCalled();
});
@@ -1059,7 +1062,18 @@ describe("live remote runner lease reattachment", () => {
mockGetLease.mockResolvedValue(null);
const runtime = makeMockRuntime();
await expect(environmentRunOrchestrator({} as never, { environmentRuntime: runtime }).acquireForRun(input))
- .rejects.toThrow("native_remote_recovery_lease_mismatch");
+ .rejects.toThrow(new Error("native_remote_recovery_lease_mismatch: stage=environment_acquire field=lease"));
+ expect(runtime.acquireRunLease).not.toHaveBeenCalled();
+ });
+ it("names a changed adapter type, not the environment driver, for a plugin task reattachment", async () => {
+ mockGetEnvironment.mockResolvedValue(makeEnvironment("plugin"));
+ const lease = originalLease();
+ lease.metadata = { agentId: "agent-1", runnerTaskLease: true, runnerTaskDispatched: true };
+ mockGetLease.mockResolvedValue(lease);
+ const runtime = makeMockRuntime();
+ await expect(environmentRunOrchestrator({} as never, { environmentRuntime: runtime }).acquireForRun({
+ ...input, adapterType: "codex_local", reattachRemoteLease: { kind: "plugin_task", leaseId: lease.id },
+ })).rejects.toThrow(new Error("native_remote_recovery_lease_mismatch: stage=environment_acquire field=adapter_type"));
expect(runtime.acquireRunLease).not.toHaveBeenCalled();
});
});
diff --git a/server/src/__tests__/heartbeat-native-remote-failure-retention.test.ts b/server/src/__tests__/heartbeat-native-remote-failure-retention.test.ts
index 88d1448a4f4..7025569275b 100644
--- a/server/src/__tests__/heartbeat-native-remote-failure-retention.test.ts
+++ b/server/src/__tests__/heartbeat-native-remote-failure-retention.test.ts
@@ -227,7 +227,9 @@ describeEmbeddedPostgres("heartbeat native remote preparation failure retention"
await heartbeat.drainActiveRunExecutions();
expect(readyAllocation).toHaveBeenCalledOnce();
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
- expect(run).toMatchObject({ status: "failed", error: "native_remote_recovery_lease_mismatch" });
+ // The run records which check failed: the provider no longer resumes the lease.
+ expect(run).toMatchObject({ status: "failed",
+ error: "native_remote_recovery_lease_mismatch: stage=environment_resume field=lease" });
const retryKey = `task-retry:restart-interrupted-turn:${f.runId}`;
await vi.waitFor(async () => {
const retries = await db.select().from(agentWakeupRequests).where(and(
diff --git a/server/src/__tests__/native-workspace-sync.test.ts b/server/src/__tests__/native-workspace-sync.test.ts
index f690abcd5be..563b4aa0572 100644
--- a/server/src/__tests__/native-workspace-sync.test.ts
+++ b/server/src/__tests__/native-workspace-sync.test.ts
@@ -109,7 +109,7 @@ describe("native workspace sync durable metadata", () => {
restartRecovery: { kind: "reattach_remote_runner", runId: "run", leaseOwner: "controller", controllerGeneration: 2,
providerAttempt: 1, restartKind: "graceful", recoveryRequestId: null,
remote: { providerLeaseId: "original", remoteCwd: "/workspace" } },
- })).rejects.toThrow("native_remote_recovery_lease_mismatch");
+ })).rejects.toThrow(new Error("native_remote_recovery_lease_mismatch: stage=workspace_sync field=provider_lease_id"));
expect(select).not.toHaveBeenCalled();
});
diff --git a/server/src/services/environment-run-orchestrator.ts b/server/src/services/environment-run-orchestrator.ts
index 4e3f725cfa5..de083eed785 100644
--- a/server/src/services/environment-run-orchestrator.ts
+++ b/server/src/services/environment-run-orchestrator.ts
@@ -20,6 +20,7 @@ import { prepareRemoteWorkspace, readRemoteWorkspaceAuthority, remoteWorkspaceRe
import { environmentLeases, type Db } from "@paperclipai/db";
import { and, eq } from "drizzle-orm";
import { remoteExecutionHasStopped } from "./remote-execution-termination.js";
+import { remoteRecoveryLeaseMismatch, type RemoteRecoveryLeaseMismatchField } from "./native-runtime/remote-recovery-lease-mismatch.js";
import { EnvironmentProviderUnavailableError, readTransientEnvironmentProviderFailure } from "./environment-provider-unavailable-error.js";
import { findReusableSandboxResumeError } from "./reusable-sandbox-resume-error.js";
import { findPluginWorkerUnavailableError } from "./plugin-worker-unavailable-error.js";
@@ -356,20 +357,24 @@ export function environmentRunOrchestrator(
// Never reacquire: acquisition can replace a non-reusable sandbox.
const expected = input.reattachRemoteLease;
const lease = await environmentsSvc.getLeaseById(expected.leaseId);
- if (!lease ||
- lease.companyId !== input.companyId || lease.environmentId !== environment.id ||
+ const mismatch: RemoteRecoveryLeaseMismatchField | null = !lease ? "lease"
+ : lease.companyId !== input.companyId || lease.environmentId !== environment.id ||
lease.heartbeatRunId !== input.heartbeatRunId || lease.issueId !== input.issueId ||
lease.executionWorkspaceId !== (input.persistedExecutionWorkspace?.id ?? null) ||
- lease.metadata?.agentId !== input.agentId || lease.status !== "active" ||
- lease.releasedAt !== null || lease.cleanupStatus !== null ||
- (lease.expiresAt !== null && new Date(lease.expiresAt).getTime() <= Date.now()) ||
- (expected.kind === "plugin_task"
- ? environment.driver !== "plugin" || input.adapterType !== "paperclip_runner"
- || lease.metadata?.runnerTaskLease !== true || lease.metadata?.runnerTaskDispatched !== true
- || lease.metadata?.runnerTaskExecutionStopped === true
- : environment.driver !== "sandbox" || lease.provider !== environment.config.provider
- || lease.providerLeaseId !== expected.providerLeaseId || lease.metadata?.remoteCwd !== expected.remoteCwd)) {
- throw new Error("native_remote_recovery_lease_mismatch");
+ lease.metadata?.agentId !== input.agentId ? "lease_scope"
+ : lease.status !== "active" || lease.releasedAt !== null || lease.cleanupStatus !== null ? "lease_status"
+ : lease.expiresAt !== null && new Date(lease.expiresAt).getTime() <= Date.now() ? "lease_expired"
+ : expected.kind === "plugin_task"
+ ? environment.driver !== "plugin" ? "environment_driver"
+ : input.adapterType !== "paperclip_runner" ? "adapter_type"
+ : lease.metadata?.runnerTaskLease !== true || lease.metadata?.runnerTaskDispatched !== true
+ || lease.metadata?.runnerTaskExecutionStopped === true ? "plugin_task" : null
+ : environment.driver !== "sandbox" ? "environment_driver"
+ : lease.provider !== environment.config.provider ? "provider"
+ : lease.providerLeaseId !== expected.providerLeaseId ? "provider_lease_id"
+ : lease.metadata?.remoteCwd !== expected.remoteCwd ? "remote_cwd" : null;
+ if (mismatch || !lease) {
+ throw remoteRecoveryLeaseMismatch("environment_acquire", mismatch ?? "lease");
}
if (expected.kind !== "plugin_task") {
// The provider may have archived this retained sandbox while its
@@ -381,10 +386,11 @@ export function environmentRunOrchestrator(
...(warmRunnerIdleTimeoutMs !== undefined ? { warmRunnerIdleTimeoutMs } : {}),
...(runnerReconnectGraceMs !== undefined ? { runnerReconnectGraceMs } : {}),
});
- if (!resumed || resumed.providerLeaseId !== expected.providerLeaseId ||
- resumed.metadata?.expired === true) {
- throw new Error("native_remote_recovery_lease_mismatch");
+ if (!resumed) throw remoteRecoveryLeaseMismatch("environment_resume", "lease");
+ if (resumed.providerLeaseId !== expected.providerLeaseId) {
+ throw remoteRecoveryLeaseMismatch("environment_resume", "provider_lease_id");
}
+ if (resumed.metadata?.expired === true) throw remoteRecoveryLeaseMismatch("environment_resume", "lease_expired");
// Resume confirms allocation readiness. Its optional metadata may
// describe the allocation root; keep the validated lease's workspace.
}
diff --git a/server/src/services/heartbeat/restart-interrupted-turn.ts b/server/src/services/heartbeat/restart-interrupted-turn.ts
index ba4f1ca07b1..df89505a90e 100644
--- a/server/src/services/heartbeat/restart-interrupted-turn.ts
+++ b/server/src/services/heartbeat/restart-interrupted-turn.ts
@@ -5,11 +5,12 @@ import { isUserCommentContinuationReason } from "../explicit-native-continuation
import { requestTaskRetry } from "../task-retry.js";
import { HttpError } from "../../errors.js";
import { logger } from "../../middleware/logger.js";
+import { NATIVE_REMOTE_RECOVERY_LEASE_MISMATCH } from "../native-runtime/remote-recovery-lease-mismatch.js";
/** Reattachment could not find the run's original runner or allocation: the
* sandbox lease or plugin task is gone, or the remote runner process is not
* there to verify. This is infrastructure, not the task's own failure. */
-const REATTACHMENT_LOST_ERRORS = ["native_remote_recovery_lease_mismatch", "native_plugin_recovery_lease_mismatch",
+const REATTACHMENT_LOST_ERRORS = [NATIVE_REMOTE_RECOVERY_LEASE_MISMATCH, "native_plugin_recovery_lease_mismatch",
"runner_remote_process_identity_unavailable", "runner_continuity_break_archive_failed"];
/** A failure message is one of the closed codes, optionally followed by
diff --git a/server/src/services/heartbeat/workspace-preparation.test.ts b/server/src/services/heartbeat/workspace-preparation.test.ts
index 612075612bb..1edc7bfe73d 100644
--- a/server/src/services/heartbeat/workspace-preparation.test.ts
+++ b/server/src/services/heartbeat/workspace-preparation.test.ts
@@ -2058,7 +2058,8 @@ describe.skipIf(!support.supported && !externalDatabaseUrl)("heartbeat workspace
remote: { providerLeaseId: "original-provider-lease", remoteCwd: "/original" },
};
const acquire = vi.spyOn(envOrchestrator, "acquireForRun");
- await expect(prepareHeartbeatWorkspace(db, input)).rejects.toThrow("native_remote_recovery_lease_mismatch");
+ await expect(prepareHeartbeatWorkspace(db, input)).rejects.toThrow(
+ new Error("native_remote_recovery_lease_mismatch: stage=workspace_preparation field=workspace_reference"));
expect(acquire).not.toHaveBeenCalled();
expect(await leases(input.run.id)).toHaveLength(0);
expect(input.nativeRunnerPreparationSpans).toMatchObject([{ name: "environment.acquire", outcome: "failed" }]);
diff --git a/server/src/services/heartbeat/workspace-preparation.ts b/server/src/services/heartbeat/workspace-preparation.ts
index d00ff0cd91d..7ff85efacfd 100644
--- a/server/src/services/heartbeat/workspace-preparation.ts
+++ b/server/src/services/heartbeat/workspace-preparation.ts
@@ -1,3 +1,4 @@
+import { remoteRecoveryLeaseMismatch } from "../native-runtime/remote-recovery-lease-mismatch.js";
import { resolveProviderApiPlacement } from "../native-runtime/provider-api-placement.js";
import { assertEphemeralWorkspaceExecution, readRemoteWorkspaceAuthority, RemoteWorkspaceWriterActiveError, reserveRemoteWorkspace, shouldUseRemoteWorkspaces } from "../remote-workspaces.js";
import { WORKSPACE_BUSY_HOLDER_STALE_AFTER_MS, WorkspaceBusyDeferral } from "./retries.js";
@@ -1296,12 +1297,14 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
? readNativeWorkspaceSyncReference(parseObject(run.runnerProfileJson).nativeWorkspaceSync) : null;
const remoteRecoveryLocation = remoteAuthority
? readRemoteWorkspaceAuthority(persistedExecutionWorkspace?.metadata)?.location ?? null : null;
- if (remoteRecovery && (remoteRecovery.runId !== run.id || (sandboxRecovery && (remoteAuthority
- ? !remoteRecoveryLocation || remoteRecoveryLocation.providerLeaseId !== sandboxRecovery.providerLeaseId
- || remoteRecoveryLocation.remoteCwd !== sandboxRecovery.remoteCwd
- : !recoveryWorkspace || recoveryWorkspace.providerLeaseId !== sandboxRecovery.providerLeaseId
- || recoveryWorkspace.remoteCwd !== sandboxRecovery.remoteCwd)))) {
- throw new Error("native_remote_recovery_lease_mismatch");
+ if (remoteRecovery) {
+ const saved = remoteAuthority ? remoteRecoveryLocation : recoveryWorkspace;
+ const mismatch = remoteRecovery.runId !== run.id ? "run_id" as const
+ : !sandboxRecovery ? null
+ : !saved ? "workspace_reference" as const
+ : saved.providerLeaseId !== sandboxRecovery.providerLeaseId ? "provider_lease_id" as const
+ : saved.remoteCwd !== sandboxRecovery.remoteCwd ? "remote_cwd" as const : null;
+ if (mismatch) throw remoteRecoveryLeaseMismatch("workspace_preparation", mismatch);
}
acquiredEnvironment = await timeWorkspace("workspace_environment_acquire", () => envOrchestrator.acquireForRun({
companyId: agent.companyId,
diff --git a/server/src/services/native-runtime/native-controller-recovery.integration.test.ts b/server/src/services/native-runtime/native-controller-recovery.integration.test.ts
index 65e6b98e908..49984b10497 100644
--- a/server/src/services/native-runtime/native-controller-recovery.integration.test.ts
+++ b/server/src/services/native-runtime/native-controller-recovery.integration.test.ts
@@ -154,7 +154,8 @@ describe.skipIf(!recoveryPostgresSupport.supported)("native controller durable d
runnerLifecycle: "ready", runnerSettled: true });
expect(nativeSessionFailureSourceCode(failure)).toBe("native_session_interrupted");
await expect(verifyRemoteRunnerReattachment({ claim: { ...sourceClaim, runId }, target: target as never,
- identity, runId, normalizedSessionId: fixture.scope.normalizedSessionId })).rejects.toThrow("native_remote_recovery_lease_mismatch");
+ identity, runId, normalizedSessionId: fixture.scope.normalizedSessionId }))
+ .rejects.toThrow(new Error("native_remote_recovery_lease_mismatch: stage=runner_verification field=identity_run_id"));
const recovery = await nativeProviderRecoveryEvidence({ db, runId, executionTargetKind: target.kind, sourceFailureCode: nativeSessionFailureSourceCode(failure) });
expect(recovery).toMatchObject({ providerSessionEstablished: true, providerEventsExist: false, checkpointExists: true });
expect(recovery.recoveryMode).toBe("ambiguous_state");
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 6aacc8b8e9a..09108ef78cf 100644
--- a/server/src/services/native-runtime/native-session-executor.test.ts
+++ b/server/src/services/native-runtime/native-session-executor.test.ts
@@ -740,7 +740,20 @@ describe("remote controller restart adoption", () => {
runId: "run",
normalizedSessionId: "session",
}),
- ).rejects.toThrow("native_remote_recovery_lease_mismatch");
+ ).rejects.toThrow(new Error("native_remote_recovery_lease_mismatch: stage=runner_verification field=provider_lease_id"));
+ expect(execute).not.toHaveBeenCalled();
+ });
+ it("names the missing durable runner identity before reading the sandbox", async () => {
+ const { execute, target } = fixture();
+ await expect(
+ verifyRemoteRunnerReattachment({
+ claim,
+ target: target as never,
+ identity: {},
+ runId: "run",
+ normalizedSessionId: "session",
+ }),
+ ).rejects.toThrow(new Error("native_remote_recovery_lease_mismatch: stage=runner_verification field=identity_run_id"));
expect(execute).not.toHaveBeenCalled();
});
it.each([
diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts
index e3b0d16f6ab..c18f97a92c6 100644
--- a/server/src/services/native-runtime/native-session-executor.ts
+++ b/server/src/services/native-runtime/native-session-executor.ts
@@ -1,3 +1,4 @@
+import { remoteRecoveryLeaseMismatch } from "./remote-recovery-lease-mismatch.js";
import { captureRemoteNativeProviderArtifacts } from "./native-provider-artifact-capture.js";
import { NativeSessionDiagnostics, nativeSessionDiagnostics, type NativeDiagnosticLease } from "./native-session-diagnostics.js";
import { recordAgentProviderRateLimits } from "../agent-provider-rate-limits.js";
@@ -13368,21 +13369,17 @@ export async function verifyRemoteRunnerReattachment(input: {
recoveryDeadline?: number;
}) {
const { claim, target, identity } = input;
- if (
- claim.remote.kind === "plugin_task" ||
- target?.kind !== "remote" ||
- target.transport !== "sandbox" ||
- !target.runner ||
- claim.runId !== input.runId ||
- identity.runId !== input.runId ||
- identity.normalizedSessionId !== input.normalizedSessionId ||
- claim.remote.providerLeaseId !==
- target.sandboxLeaseAcquisition?.providerLeaseId ||
- target.sandboxLeaseAcquisition.outcome === "replacement" ||
- claim.remote.remoteCwd !== target.remoteCwd
- ) {
- throw new Error("native_remote_recovery_lease_mismatch");
+ if (claim.remote.kind === "plugin_task") throw remoteRecoveryLeaseMismatch("runner_verification", "plugin_task");
+ if (target?.kind !== "remote" || target.transport !== "sandbox" || !target.runner) {
+ throw remoteRecoveryLeaseMismatch("runner_verification", "target");
}
+ const mismatch = claim.runId !== input.runId ? "run_id" as const
+ : identity.runId !== input.runId ? "identity_run_id" as const
+ : identity.normalizedSessionId !== input.normalizedSessionId ? "identity_session_id" as const
+ : claim.remote.providerLeaseId !== target.sandboxLeaseAcquisition?.providerLeaseId ? "provider_lease_id" as const
+ : target.sandboxLeaseAcquisition?.outcome === "replacement" ? "replacement_sandbox" as const
+ : claim.remote.remoteCwd !== target.remoteCwd ? "remote_cwd" as const : null;
+ if (mismatch) throw remoteRecoveryLeaseMismatch("runner_verification", mismatch);
const runner = target.runner;
const probeDeadline = Math.min(input.recoveryDeadline ?? Number.POSITIVE_INFINITY,
Date.now() + REMOTE_RUNNER_RECOVERY_PROBE_BUDGET_MS);
diff --git a/server/src/services/native-runtime/native-workspace-sync.ts b/server/src/services/native-runtime/native-workspace-sync.ts
index a684714b53a..82f703e98ca 100644
--- a/server/src/services/native-runtime/native-workspace-sync.ts
+++ b/server/src/services/native-runtime/native-workspace-sync.ts
@@ -1,3 +1,4 @@
+import { remoteRecoveryLeaseMismatch } from "./remote-recovery-lease-mismatch.js";
import { hasMigratedLegacyWorkspaceSource } from "../legacy-workspace-recovery-migration.js";
import { notifyCancelledWorkspacePreservation } from "../cancelled-workspace-preservation-notifications.js";
import { notifyEnvironmentCleanup } from "../environment-cleanup-notifications.js";
@@ -915,11 +916,13 @@ export async function prepareNativeWorkspaceSync(input: {
const target = input.target;
const providerLeaseId = providerLeaseIdFor({ target, lease: input.lease });
// Reattachment may never seed a replacement sandbox over a still-live run.
- if (input.restartRecovery?.kind === "reattach_remote_runner" &&
- (input.restartRecovery.remote.kind === "plugin_task" || input.restartRecovery.runId !== input.runId ||
- input.restartRecovery.remote.providerLeaseId !== providerLeaseId ||
- input.restartRecovery.remote.remoteCwd !== target.remoteCwd)) {
- throw new Error("native_remote_recovery_lease_mismatch");
+ if (input.restartRecovery?.kind === "reattach_remote_runner") {
+ const { remote, runId } = input.restartRecovery;
+ const mismatch = remote.kind === "plugin_task" ? "plugin_task" as const
+ : runId !== input.runId ? "run_id" as const
+ : remote.providerLeaseId !== providerLeaseId ? "provider_lease_id" as const
+ : remote.remoteCwd !== target.remoteCwd ? "remote_cwd" as const : null;
+ if (mismatch) throw remoteRecoveryLeaseMismatch("workspace_sync", mismatch);
}
const run = await measureRunPhase("workspace_sync.run_read", () => input.db
.select({ companyId: heartbeatRuns.companyId, runnerProfileJson: heartbeatRuns.runnerProfileJson })
diff --git a/server/src/services/native-runtime/remote-recovery-lease-mismatch.ts b/server/src/services/native-runtime/remote-recovery-lease-mismatch.ts
new file mode 100644
index 00000000000..84102e142bd
--- /dev/null
+++ b/server/src/services/native-runtime/remote-recovery-lease-mismatch.ts
@@ -0,0 +1,42 @@
+/**
+ * Reattaching a remote native run proves that the original sandbox lease, its
+ * workspace, and its runner are still the ones the run saved. When a check
+ * fails, the run fails with `native_remote_recovery_lease_mismatch`. The detail
+ * names the step and the identity field that differed, using closed values
+ * only (no identifiers), so an operator can tell which check failed.
+ *
+ * Consumers match the code exactly or as the `code: detail` prefix.
+ */
+export const NATIVE_REMOTE_RECOVERY_LEASE_MISMATCH = "native_remote_recovery_lease_mismatch";
+
+export type RemoteRecoveryLeaseMismatchStage =
+ | "workspace_preparation"
+ | "environment_acquire"
+ | "environment_resume"
+ | "workspace_sync"
+ | "runner_verification";
+
+export type RemoteRecoveryLeaseMismatchField =
+ | "run_id"
+ | "workspace_reference"
+ | "lease"
+ | "lease_scope"
+ | "lease_status"
+ | "lease_expired"
+ | "environment_driver"
+ | "adapter_type"
+ | "provider"
+ | "provider_lease_id"
+ | "remote_cwd"
+ | "plugin_task"
+ | "target"
+ | "replacement_sandbox"
+ | "identity_run_id"
+ | "identity_session_id";
+
+export function remoteRecoveryLeaseMismatch(
+ stage: RemoteRecoveryLeaseMismatchStage,
+ field: RemoteRecoveryLeaseMismatchField,
+): Error {
+ return new Error(`${NATIVE_REMOTE_RECOVERY_LEASE_MISMATCH}: stage=${stage} field=${field}`);
+}
diff --git a/server/src/services/workspace-recovery-retry-copyback.test.ts b/server/src/services/workspace-recovery-retry-copyback.test.ts
index 4b6b8bb218f..101ae89912b 100644
--- a/server/src/services/workspace-recovery-retry-copyback.test.ts
+++ b/server/src/services/workspace-recovery-retry-copyback.test.ts
@@ -121,6 +121,7 @@ describe("automatic retained workspace recovery", () => {
{ title: "a restart lost its sandbox before the turn started", turn: "none" as const, error: "native_remote_recovery_lease_mismatch", initial: false },
{ title: "a same-run retry found the settled turn's remote runner gone", turn: "settled" as const, error: "runner_remote_process_identity_unavailable", initial: false },
{ title: "a same-run retry found the settled turn's sandbox lease gone", turn: "settled" as const, error: "native_remote_recovery_lease_mismatch", initial: false },
+ { title: "a same-run retry named the lease check that failed", turn: "settled" as const, error: "native_remote_recovery_lease_mismatch: stage=environment_acquire field=lease_status", initial: false },
])("continues a user turn once, without a second message, after $title and recovery saved the work", async ({ turn, error, initial }) => {
const f = await restartAllocationLostSource(turn, error);
const service = heartbeatService(db, { environmentRuntime: f.environmentRuntime });
From e2d490c61bbf12290b35af65f6e12648f5f2af75 Mon Sep 17 00:00:00 2001
From: Dotta <34892728+cryppadotta@users.noreply.github.com>
Date: Sat, 7 Nov 2026 09:57:30 -0600
Subject: [PATCH 06/24] feat(observability): anchor native time to first token
at the accepted wake (#19838)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - When someone messages an agent, the reply must start fast. The
durable ownership plan (#19831) makes time to first token (TTFT) a hard
invariant.
> - Phase 0 of that plan records a TTFT baseline per adapter and
environment, measured from the moment the message or wake is accepted.
> - Today `task.time_to_first_token` starts at the wake comment, the
answered question, or the run row's creation. A wake request that was
accepted earlier (deferred, coalesced or retried) is not part of the
measurement, and the span does not say which start it used.
> - This pull request moves the start back to the earliest accepted
input and names it on the span.
> - The benefit is that the baseline and later budgets measure what the
user waits for, with no new work before `turn.start`.
## Linked Issues or Issue Description
Refs #19831
**What is the problem?**
`task.time_to_first_token` does not include the time between an accepted
wake request and the creation of its run row. It also does not record
which input it started from.
**What is the expected outcome?**
The span starts at the earliest accepted input and carries an `anchor`
attribute: `comment`, `question_response`, `wake_request` or
`run_created`.
**Why does it matter?**
Phase 0 of the durable ownership plan sets TTFT budgets from this
baseline. A start that skips queue time hides the latency that deferred
wakes add.
## What Changed
- `resolveNativeTimeToFirstTokenStart` (pure) in `native-run-trace.ts`
picks the start and the anchor. `anchor` joins the closed span-attribute
allowlist.
- `readNativeRunWakeRequestedAtMs` reads
`agent_wakeup_requests.requested_at` for the run. It never throws.
- `native-session-executor.ts` calls it only after the first deliverable
text, so it adds no wait before `turn.start`. The span now ends at the
text commit time, not after the trace write.
- Updated `doc/run-log-events.md` and `doc/observability.md`.
## Verification
- `cd server && npx vitest run
src/services/native-runtime/native-run-trace.test.ts
src/services/native-runtime/native-run-wake-anchor.test.ts` (26 pass).
- `cd server && npx vitest run
src/services/native-runtime/native-session-executor.test.ts -t first`
(41 pass). The existing TTFT test now asserts the anchor for each
ingress.
## Risks
- Low risk. This changes only the run-log and OTLP span. It is not
Telemetry (AGENTS.md §5.7), and it does not change runtime behavior.
- One indexed primary-key read per native dispatch, after the first
text. A read failure drops the anchor and keeps the old start.
- TTFT values can grow for deferred wakes. That is the intended
correction. `startOffsetMs` can be negative when the wake request comes
before the trace start.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), via 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
---
doc/observability.md | 15 ++-
doc/run-log-events.md | 17 ++-
.../native-runtime/native-run-trace.test.ts | 100 ++++++++++++++++++
.../native-runtime/native-run-trace.ts | 75 +++++++++++++
...native-run-wake-anchor.integration.test.ts | 74 +++++++++++++
.../native-run-wake-anchor.test.ts | 39 +++++++
.../native-runtime/native-run-wake-anchor.ts | 56 ++++++++++
.../native-session-executor.test.ts | 42 +++++++-
.../native-runtime/native-session-executor.ts | 23 ++--
9 files changed, 426 insertions(+), 15 deletions(-)
create mode 100644 server/src/services/native-runtime/native-run-wake-anchor.integration.test.ts
create mode 100644 server/src/services/native-runtime/native-run-wake-anchor.test.ts
create mode 100644 server/src/services/native-runtime/native-run-wake-anchor.ts
diff --git a/doc/observability.md b/doc/observability.md
index 7876651e0eb..ff80fe858e7 100644
--- a/doc/observability.md
+++ b/doc/observability.md
@@ -746,10 +746,17 @@ accepted ingress → queue → task.prepare → Runner startup → provider work
└────────────────────── task.time_to_first_token ──────────────────────────────────┘
```
-The span starts at the native run trace's historical start:
-the accepted comment or attested question response when present, otherwise run
-creation from the queue span. Callers without preparation history start at native
-dispatch. The interval includes queueing, Core preparation, workspace preparation,
+The span starts at the earliest accepted input. The accepted comment or attested
+question response is the start only when its span is the earliest preparation span.
+A comment coalesced into an already-queued run starts after run creation, so that
+run starts at run creation from the queue span and reports `run_created`. The
+durable wake request's acceptance time replaces the start when it is earlier
+(deferred, coalesced and retried wakes). The `anchor` attribute (`comment`, `question_response`,
+`wake_request`, `run_created`) names which one. The wake request time is read
+after the first text in detached diagnostic work bounded to 2 s (PostgreSQL
+cancels a stalled read through a transaction-local `statement_timeout`), so it never adds a
+wait before `turn.start` and never delays event delivery. Callers without
+preparation history start at native dispatch and report `run_created`. The interval includes queueing, Core preparation, workspace preparation,
Runner startup, provider latency, transport, and durable event ingestion. It ends
in Core's commit callback, when the text is readable through the run-events API,
using the Core clock rather than the provider event timestamp. Browser delivery
diff --git a/doc/run-log-events.md b/doc/run-log-events.md
index 495346d3105..ff1d7150c4e 100644
--- a/doc/run-log-events.md
+++ b/doc/run-log-events.md
@@ -68,10 +68,19 @@ instance run log and add no first-party Telemetry or OpenTelemetry export.
dispatch at the first newly committed deliverable text: assistant or reasoning
`item.delta`/`item.completed`, a redaction tail released at completion, or an
accepted run-result summary. Its
-`durationMs` starts at the native run trace's historical start (accepted ingress,
-otherwise queued run creation, or dispatch when history is absent) and ends at Core
-commit callback. `startOffsetMs` is zero, and `eventKind` is `agentMessage` or
-`reasoning`. It includes preparation and startup, but excludes browser
+`durationMs` starts at the earliest accepted input. The accepted comment or
+answered question is the start only when its span is the earliest preparation span.
+A comment coalesced into an already-queued run starts after run creation, so that
+run uses queued run creation. The durable wake request's `requested_at` replaces
+the start when it is earlier (deferred, coalesced and retried wakes). Without
+preparation history, the start is dispatch and the anchor is `run_created`. It ends at Core commit callback. `anchor` names the start:
+`comment`, `question_response`, `wake_request` or `run_created`. `startOffsetMs` is
+zero, or negative when a wake request precedes the run trace. `eventKind` is
+`agentMessage` or `reasoning`. The wake request time is read after the first text,
+in detached diagnostic work bounded to 2 s (a
+transaction-local `statement_timeout`, so PostgreSQL cancels a stalled read), so the measurement adds no wait before
+`turn.start` and never delays event delivery. The span can appear after later
+run-log rows; the trace settles it before `task.provider_session.measured`. It includes preparation and startup, but excludes browser
delivery/rendering. This measures text availability, not an exact model token.
Empty text, item starts, tools, usage, result proposals, and duplicate replay do
not qualify. No deliverable text means no timing sample. A recovered dispatch can
diff --git a/server/src/services/native-runtime/native-run-trace.test.ts b/server/src/services/native-runtime/native-run-trace.test.ts
index a195cc28d6f..0320f0f4656 100644
--- a/server/src/services/native-runtime/native-run-trace.test.ts
+++ b/server/src/services/native-runtime/native-run-trace.test.ts
@@ -10,6 +10,7 @@ import {
nativeRunPreparationStarts,
recordFailedSkillPreparation,
recordNativeProviderPerformanceSpans,
+ resolveNativeTimeToFirstTokenStart,
NATIVE_RUN_SPAN_EVENT_TYPE,
NATIVE_RUN_TRACE_SCHEMA_VERSION,
} from "./native-run-trace.js";
@@ -504,3 +505,102 @@ it.each(["start", "context", "attribute", "status", "end"])("keeps execution and
expect(failedWork).toHaveBeenCalledOnce();
for (const span of spans) expect(span.end).toHaveBeenCalledOnce();
});
+
+describe("time to first token anchor", () => {
+ const prep = (name: string, startedAtMs: number) => ({
+ name, parentName: "task.provider_session", startedAtMs, endedAtMs: startedAtMs + 5,
+ });
+
+ it("falls back to run creation when no earlier accepted input is known", () => {
+ expect(resolveNativeTimeToFirstTokenStart({
+ traceStartedAtMs: 1_000, preparationSpans: [prep("heartbeat.queue", 1_000)], wakeRequestedAtMs: null,
+ })).toEqual({ startedAtMs: 1_000, anchor: "run_created" });
+ });
+
+ it("names the comment or answered question that already anchors the trace", () => {
+ expect(resolveNativeTimeToFirstTokenStart({
+ traceStartedAtMs: 900, preparationSpans: [prep("comment.to_run_created", 900)], wakeRequestedAtMs: 950,
+ })).toEqual({ startedAtMs: 900, anchor: "comment" });
+ expect(resolveNativeTimeToFirstTokenStart({
+ traceStartedAtMs: 800, preparationSpans: [prep("question_response.to_run_created", 800)], wakeRequestedAtMs: null,
+ })).toEqual({ startedAtMs: 800, anchor: "question_response" });
+ });
+
+ it("names run creation when a comment was coalesced into an already-queued run", () => {
+ expect(resolveNativeTimeToFirstTokenStart({
+ traceStartedAtMs: 1_000,
+ preparationSpans: [prep("heartbeat.queue", 1_000), prep("comment.to_run_created", 1_400)],
+ wakeRequestedAtMs: null,
+ })).toEqual({ startedAtMs: 1_000, anchor: "run_created" });
+ });
+
+ it("moves back to an earlier accepted wake request (deferred or coalesced wakes)", () => {
+ expect(resolveNativeTimeToFirstTokenStart({
+ traceStartedAtMs: 5_000, preparationSpans: [prep("heartbeat.queue", 5_000)], wakeRequestedAtMs: 2_000,
+ })).toEqual({ startedAtMs: 2_000, anchor: "wake_request" });
+ });
+
+ it("ignores invalid wake request times", () => {
+ for (const wakeRequestedAtMs of [Number.NaN, -1, 6_000]) {
+ expect(resolveNativeTimeToFirstTokenStart({
+ traceStartedAtMs: 5_000, preparationSpans: [], wakeRequestedAtMs,
+ })).toEqual({ startedAtMs: 5_000, anchor: "run_created" });
+ }
+ });
+
+ it("persists the anchor on the run-log span", async () => {
+ const events: AdapterRuntimeEvent[] = [];
+ const trace = createNativeRunTrace({
+ runId: "ttft-run", startedAtMs: 5_000,
+ traceContext: createRecordingTraceContext().traceContext,
+ onEvent: async (event) => { events.push(event); },
+ });
+ const start = resolveNativeTimeToFirstTokenStart({
+ traceStartedAtMs: trace.traceStartedAtMs, preparationSpans: [], wakeRequestedAtMs: 4_000,
+ });
+ await trace.record({
+ name: "task.time_to_first_token", parentName: "task.provider_session",
+ startedAtMs: start.startedAtMs, endedAtMs: 7_000, attributes: { eventKind: "agentMessage", anchor: start.anchor },
+ });
+ const span = events.find((event) => (event.payload as Record)?.span === "task.time_to_first_token");
+ expect(span?.payload).toMatchObject({ durationMs: 3_000, startOffsetMs: -1_000, anchor: "wake_request", eventKind: "agentMessage" });
+ });
+});
+
+describe("deferred diagnostics", () => {
+ it("never blocks the caller and settles before the trace finishes", async () => {
+ const events: AdapterRuntimeEvent[] = [];
+ const trace = createNativeRunTrace({
+ runId: "deferred-run", startedAtMs: 1_000,
+ traceContext: createRecordingTraceContext().traceContext,
+ onEvent: async (event) => { events.push(event); },
+ });
+ let release!: () => void;
+ const gate = new Promise((resolve) => { release = resolve; });
+ trace.defer(async () => {
+ await gate;
+ await trace.record({ name: "task.time_to_first_token", parentName: "task.provider_session", startedAtMs: 1_000, endedAtMs: 2_000 });
+ });
+ // Later work keeps flowing while the deferred read is pending.
+ await trace.record({ name: "response.first_nonempty_text", startedAtMs: 2_000, endedAtMs: 2_000 });
+ const span = (name: string) => events.some((event) => (event.payload as Record)?.span === name);
+ expect(span("response.first_nonempty_text")).toBe(true);
+ expect(span("task.time_to_first_token")).toBe(false);
+ const finished = trace.finish("ok");
+ release();
+ await finished;
+ const names = events.map((event) => (event.payload as Record)?.span);
+ expect(names.indexOf("task.time_to_first_token")).toBeGreaterThan(-1);
+ expect(names.indexOf("task.time_to_first_token")).toBeLessThan(names.indexOf("task.provider_session.measured"));
+ });
+
+ it("ignores a failed deferred diagnostic and work deferred after finish", async () => {
+ const trace = createNativeRunTrace({ runId: "deferred-fail", traceContext: createRecordingTraceContext().traceContext });
+ trace.defer(async () => { throw new Error("diagnostic failed"); });
+ await expect(trace.finish("ok")).resolves.toBeUndefined();
+ const late = vi.fn(async () => {});
+ trace.defer(late);
+ await Promise.resolve();
+ expect(late).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/src/services/native-runtime/native-run-trace.ts b/server/src/services/native-runtime/native-run-trace.ts
index faef91b5f30..3fccc1c9b55 100644
--- a/server/src/services/native-runtime/native-run-trace.ts
+++ b/server/src/services/native-runtime/native-run-trace.ts
@@ -106,6 +106,58 @@ export function buildNativeHeartbeatPreparationSpans(input: {
];
}
+/** Which accepted input `task.time_to_first_token` is measured from. */
+export type NativeTimeToFirstTokenAnchor =
+ | "question_response"
+ | "comment"
+ | "wake_request"
+ | "run_created";
+
+/**
+ * Resolve the start of `task.time_to_first_token`: the earliest accepted input
+ * that caused this run. A question answer or a wake comment is already a root
+ * historical span. Otherwise the run row's creation time is the fallback. A
+ * durable wake request accepted earlier (deferred, coalesced or retried wakes)
+ * moves the start back to that request, so queueing before the run row exists
+ * is part of the measured latency.
+ *
+ * Run-log only. The wake request time is read after the first deliverable
+ * text, never before `turn.start`.
+ */
+export function resolveNativeTimeToFirstTokenStart(input: {
+ traceStartedAtMs: number;
+ preparationSpans: readonly NativeRunHistoricalSpan[];
+ wakeRequestedAtMs: number | null;
+}): { startedAtMs: number; anchor: NativeTimeToFirstTokenAnchor } {
+ const ingress = input.preparationSpans.find(
+ (span) =>
+ span.name === "question_response.to_run_created" ||
+ span.name === "comment.to_run_created",
+ );
+ // The trace starts at the earliest preparation span. A comment coalesced
+ // into an already-queued run starts after run creation, so it names the
+ // start only when it is that earliest span.
+ const ingressIsStart = ingress !== undefined && ingress.startedAtMs <= input.traceStartedAtMs;
+ let anchor: NativeTimeToFirstTokenAnchor =
+ !ingressIsStart
+ ? "run_created"
+ : ingress.name === "question_response.to_run_created"
+ ? "question_response"
+ : "comment";
+ let startedAtMs = input.traceStartedAtMs;
+ const wakeAt = input.wakeRequestedAtMs;
+ if (
+ wakeAt !== null &&
+ Number.isFinite(wakeAt) &&
+ wakeAt >= 0 &&
+ wakeAt < startedAtMs
+ ) {
+ startedAtMs = wakeAt;
+ anchor = "wake_request";
+ }
+ return { startedAtMs, anchor };
+}
+
export function nativeRunPreparationStarts(
spans: NativeRunHistoricalSpan[],
nowMs: number,
@@ -149,6 +201,7 @@ const NOOP_SPAN: SpanHandle = {
const SAFE_NATIVE_RUN_SPAN_ATTRIBUTE_KEYS = new Set([
"adapter",
+ "anchor",
"bytesTransferred",
"inputBytes", "toolSchemaBytes", "toolCount", "contextReused", "tokenDataAvailable",
"connectionOwner",
@@ -496,7 +549,28 @@ export function createNativeRunTrace(input: {
}
};
+ /**
+ * Diagnostic work that must not block the caller (for example a read that
+ * anchors a span). It runs detached; `finish` settles it before the root
+ * span closes. The work must bound its own waits.
+ */
+ const pendingDiagnostics = new Set>();
+ const defer = (work: () => Promise): void => {
+ if (ended) return;
+ const pending: Promise = Promise.resolve()
+ .then(work)
+ .catch(() => {
+ // Diagnostics cannot change runner control flow.
+ })
+ .finally(() => {
+ pendingDiagnostics.delete(pending);
+ });
+ pendingDiagnostics.add(pending);
+ };
+
const finish = async (outcome: NativeRunSpanOutcome): Promise => {
+ if (ended) return;
+ await Promise.all([...pendingDiagnostics]);
if (ended) return;
ended = true;
const endedAtMs = Date.now();
@@ -528,6 +602,7 @@ export function createNativeRunTrace(input: {
run,
record,
measure,
+ defer,
finish,
};
}
diff --git a/server/src/services/native-runtime/native-run-wake-anchor.integration.test.ts b/server/src/services/native-runtime/native-run-wake-anchor.integration.test.ts
new file mode 100644
index 00000000000..19da74a06c0
--- /dev/null
+++ b/server/src/services/native-runtime/native-run-wake-anchor.integration.test.ts
@@ -0,0 +1,74 @@
+import { randomUUID } from "node:crypto";
+import { sql } from "drizzle-orm";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { agentWakeupRequests, agents, companies, createDb, heartbeatRuns } from "@paperclipai/db";
+import {
+ getEmbeddedPostgresTestSupport,
+ startEmbeddedPostgresTestDatabase,
+} from "../../__tests__/helpers/embedded-postgres.js";
+import { readNativeRunWakeRequestedAtMs } from "./native-run-wake-anchor.js";
+
+const support = await getEmbeddedPostgresTestSupport();
+const describeEmbeddedPostgres = support.supported ? describe : describe.skip;
+
+describeEmbeddedPostgres("native run wake anchor against PostgreSQL", () => {
+ let database: Awaited> | null = null;
+ let db!: ReturnType;
+ let locker!: ReturnType;
+ const companyId = randomUUID();
+ const agentId = randomUUID();
+ const wakeupRequestId = randomUUID();
+ const runId = randomUUID();
+ const requestedAt = new Date("2026-11-07T10:00:00.000Z");
+
+ beforeAll(async () => {
+ database = await startEmbeddedPostgresTestDatabase("paperclip-wake-anchor-");
+ // One connection: a read left running after the timeout would starve the next query.
+ db = createDb(database.connectionString, { maxConnections: 1 });
+ locker = createDb(database.connectionString, { maxConnections: 2 });
+ await db.insert(companies).values({ id: companyId, name: "Anchor", issuePrefix: `A${companyId.slice(0, 6)}` });
+ await db.insert(agents).values({ id: agentId, companyId, name: "Anchor agent", role: "engineer", status: "idle", adapterType: "codex_local" });
+ await db.insert(agentWakeupRequests).values({ id: wakeupRequestId, companyId, agentId, source: "assignment", status: "claimed", requestedAt });
+ await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, wakeupRequestId, status: "running" });
+ }, 60_000);
+
+ afterAll(async () => {
+ await database?.cleanup();
+ });
+
+ it("reads requested_at through the run's wake request", async () => {
+ await expect(readNativeRunWakeRequestedAtMs(db, runId)).resolves.toBe(requestedAt.getTime());
+ await expect(readNativeRunWakeRequestedAtMs(db, randomUUID())).resolves.toBeNull();
+ });
+
+ it("cancels a blocked read on the server and returns its connection to the pool", async () => {
+ let release!: () => void;
+ const gate = new Promise((resolve) => { release = resolve; });
+ let locked!: () => void;
+ const lockHeld = new Promise((resolve) => { locked = resolve; });
+ const holder = locker.transaction(async (tx) => {
+ await tx.execute(sql`lock table agent_wakeup_requests in access exclusive mode`);
+ locked();
+ await gate;
+ });
+ try {
+ await lockHeld;
+ const startedAt = Date.now();
+ await expect(readNativeRunWakeRequestedAtMs(db, runId, 300)).resolves.toBeNull();
+ expect(Date.now() - startedAt).toBeLessThan(2_000);
+ // The lock is still held. The single pooled connection must already be free,
+ // and PostgreSQL must not still be waiting on the anchor read.
+ const probeStartedAt = Date.now();
+ const [probe] = await db.execute<{ ok: number }>(sql`select 1 as ok`);
+ expect(Number(probe?.ok)).toBe(1);
+ expect(Date.now() - probeStartedAt).toBeLessThan(1_000);
+ const waiting = await locker.execute<{ count: string }>(sql`
+ select count(*)::text as count from pg_stat_activity
+ where state = 'active' and wait_event_type = 'Lock' and query ilike '%agent_wakeup_requests%'`);
+ expect(Number(waiting[0]?.count ?? 0)).toBe(0);
+ } finally {
+ release();
+ await holder;
+ }
+ }, 20_000);
+});
diff --git a/server/src/services/native-runtime/native-run-wake-anchor.test.ts b/server/src/services/native-runtime/native-run-wake-anchor.test.ts
new file mode 100644
index 00000000000..fd81317aa94
--- /dev/null
+++ b/server/src/services/native-runtime/native-run-wake-anchor.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from "vitest";
+import type { Db } from "@paperclipai/db";
+
+import { readNativeRunWakeRequestedAtMs } from "./native-run-wake-anchor.js";
+
+function fakeDb(result: () => Promise, statements: string[] = []): Db {
+ const chain = {
+ select: () => chain, from: () => chain, innerJoin: () => chain, where: () => chain,
+ limit: () => result(),
+ execute: async (query: { queryChunks?: unknown[] }) => { statements.push(JSON.stringify(query.queryChunks ?? query)); return []; },
+ };
+ return { transaction: async (fn: (tx: typeof chain) => Promise) => fn(chain) } as unknown as Db;
+}
+
+describe("readNativeRunWakeRequestedAtMs", () => {
+ it("returns the wake request acceptance time under a transaction-local statement timeout", async () => {
+ const at = new Date("2026-11-07T10:00:00.000Z");
+ const statements: string[] = [];
+ await expect(readNativeRunWakeRequestedAtMs(fakeDb(async () => [{ requestedAt: at }], statements), "run", 250))
+ .resolves.toBe(at.getTime());
+ expect(statements.join(" ")).toContain("statement_timeout");
+ expect(statements.join(" ")).toContain("250ms");
+ });
+
+ it("returns null when the run has no wake request", async () => {
+ await expect(readNativeRunWakeRequestedAtMs(fakeDb(async () => []), "run")).resolves.toBeNull();
+ });
+
+ it("stops waiting at the timeout even before the database answers", async () => {
+ const pending = new Promise(() => {});
+ const startedAt = Date.now();
+ await expect(readNativeRunWakeRequestedAtMs(fakeDb(() => pending), "run", 20)).resolves.toBeNull();
+ expect(Date.now() - startedAt).toBeLessThan(1_000);
+ });
+
+ it("never throws: a read failure only drops the diagnostic anchor", async () => {
+ await expect(readNativeRunWakeRequestedAtMs(fakeDb(async () => { throw new Error("db down"); }), "run")).resolves.toBeNull();
+ });
+});
diff --git a/server/src/services/native-runtime/native-run-wake-anchor.ts b/server/src/services/native-runtime/native-run-wake-anchor.ts
new file mode 100644
index 00000000000..c0d7e64f30d
--- /dev/null
+++ b/server/src/services/native-runtime/native-run-wake-anchor.ts
@@ -0,0 +1,56 @@
+import { agentWakeupRequests, heartbeatRuns, type Db } from "@paperclipai/db";
+import { eq, sql } from "drizzle-orm";
+
+/** A slow database never holds this diagnostic longer than this. */
+export const NATIVE_RUN_WAKE_ANCHOR_READ_TIMEOUT_MS = 2_000;
+
+/**
+ * When the durable wake request that created this run was accepted, in epoch
+ * milliseconds. Diagnostic only: it anchors `task.time_to_first_token` to the
+ * accepted input. Callers run it detached after the first deliverable text, so
+ * it never adds a wait before `turn.start` or to event delivery.
+ *
+ * The read is bounded on both sides. PostgreSQL cancels the statement at
+ * `timeoutMs` (a transaction-local `statement_timeout`, which also covers lock
+ * waits), so a stalled read does not keep a shared connection busy after the
+ * caller stops waiting. The caller also stops waiting at `timeoutMs`, which
+ * covers a wait for a pool connection. Any failure returns null.
+ */
+export async function readNativeRunWakeRequestedAtMs(
+ db: Db,
+ runId: string,
+ timeoutMs = NATIVE_RUN_WAKE_ANCHOR_READ_TIMEOUT_MS,
+): Promise {
+ const boundedMs = Math.max(1, Math.floor(timeoutMs));
+ let timer: ReturnType | undefined;
+ const timeout = new Promise((resolve) => {
+ timer = setTimeout(() => resolve(null), boundedMs);
+ timer.unref?.();
+ });
+ try {
+ return await Promise.race([readWakeRequestedAtMs(db, runId, boundedMs), timeout]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+}
+
+async function readWakeRequestedAtMs(db: Db, runId: string, timeoutMs: number): Promise {
+ try {
+ return await db.transaction(async (tx) => {
+ await tx.execute(sql`select set_config('statement_timeout', ${`${timeoutMs}ms`}, true)`);
+ const [row] = await tx
+ .select({ requestedAt: agentWakeupRequests.requestedAt })
+ .from(heartbeatRuns)
+ .innerJoin(
+ agentWakeupRequests,
+ eq(agentWakeupRequests.id, heartbeatRuns.wakeupRequestId),
+ )
+ .where(eq(heartbeatRuns.id, runId))
+ .limit(1);
+ const at = row?.requestedAt?.getTime();
+ return typeof at === "number" && Number.isFinite(at) ? at : null;
+ });
+ } catch {
+ return null;
+ }
+}
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 09108ef78cf..94f79b08a9b 100644
--- a/server/src/services/native-runtime/native-session-executor.test.ts
+++ b/server/src/services/native-runtime/native-session-executor.test.ts
@@ -139,6 +139,9 @@ vi.mock("../usage-receipts.js", async (importOriginal) => ({
createRunUsageRecorder: usageRecorder.create,
}));
+const wakeAnchor = vi.hoisted(() => ({ read: vi.fn(async (_db: unknown, _runId: string): Promise => null) }));
+vi.mock("./native-run-wake-anchor.js", () => ({ readNativeRunWakeRequestedAtMs: wakeAnchor.read }));
+
vi.mock("./native-usage-delivery.js", () => ({
createNativeUsageDelivery: vi.fn(async () => ({ capture: async () => undefined })),
}));
@@ -8826,7 +8829,9 @@ describe("native resumed preparation timing", () => {
const ttft = events.filter((event) => event.payload?.span === "task.time_to_first_token");
expect(ttft).toHaveLength(1);
expect(ttft[0]?.payload).toMatchObject({ parentSpan: "task.provider_session", startOffsetMs: 0,
- durationMs: ingress === "native_dispatch" ? 500 : 4_500, eventKind: "agentMessage", outcome: "ok" });
+ durationMs: ingress === "native_dispatch" ? 500 : 4_500, eventKind: "agentMessage", outcome: "ok",
+ anchor: ingress === "comment.to_run_created" ? "comment"
+ : ingress === "question_response.to_run_created" ? "question_response" : "run_created" });
expect(events.find((event) => event.payload?.span === "provider.time_to_first_agent_event")?.payload)
.toMatchObject({ parentSpan: "agent.turn", eventKind: "agentMessage" });
expect(JSON.stringify(ttft)).not.toContain("first text");
@@ -8834,6 +8839,41 @@ describe("native resumed preparation timing", () => {
},
);
+ it("anchors first-token timing at an earlier durable wake request without blocking later events", async () => {
+ const startedAtMs = Date.now() - 5_000;
+ const events: AdapterRuntimeEvent[] = [];
+ const clock = vi.spyOn(Date, "now").mockReturnValue(startedAtMs + 4_000);
+ let answerRead!: (value: number) => void;
+ wakeAnchor.read.mockImplementationOnce(() => new Promise((resolve) => { answerRead = resolve; }));
+ const event = (eventType: string, payload: Record) => ({
+ eventType, payload, itemId: "message", emittedAt: new Date(startedAtMs + 2_000).toISOString(),
+ }) as PrpEvent;
+ state.execute.mockReset().mockImplementationOnce(async () => {
+ for (const candidate of [event("turn.submitted", {}), event("turn.started", {})]) await accountingEvents.committed!(candidate);
+ clock.mockReturnValue(startedAtMs + 4_500);
+ await accountingEvents.committed!(event("item.delta", { kind: "agentMessage", text: "first text" }));
+ // The anchor read is still pending; later events are not held behind it.
+ await accountingEvents.committed!(event("item.delta", { kind: "agentMessage", text: "later text" }));
+ expect(events.some((candidate) => candidate.payload?.span === "task.time_to_first_token")).toBe(false);
+ answerRead(startedAtMs - 2_000);
+ return { result: { summary: "cancelled" }, terminal: { runTerminalState: "cancelled" },
+ turnId: "turn", normalizedSessionId: "session", providerSessionId: null,
+ driverKind: "test", driverVersion: "1", nativeEventCount: 1, highestContiguousSourceSeq: 1 };
+ });
+ try {
+ await executePaperclipNativeSession({
+ db: leaseDb(), execution, runnerInstanceId: "runner",
+ preparationSpans: [{ name: "heartbeat.queue", startedAtMs, endedAtMs: startedAtMs + 100 }],
+ onEvent: async (event) => { events.push(event); },
+ });
+ } finally { clock.mockRestore(); }
+ expect(wakeAnchor.read).toHaveBeenCalledWith(expect.anything(), execution.binding.runId);
+ const ttft = events.filter((event) => event.payload?.span === "task.time_to_first_token");
+ expect(ttft).toHaveLength(1);
+ expect(ttft[0]?.payload).toMatchObject({ parentSpan: "task.provider_session", startOffsetMs: -2_000,
+ durationMs: 6_500, anchor: "wake_request", eventKind: "agentMessage" });
+ });
+
it.each([
["item.delta", { kind: "reasoning", text: "thinking" }, "reasoning"],
["item.completed", { kind: "reasoning", text: "thought" }, "reasoning"],
diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts
index c18f97a92c6..4e12dbc7104 100644
--- a/server/src/services/native-runtime/native-session-executor.ts
+++ b/server/src/services/native-runtime/native-session-executor.ts
@@ -284,11 +284,13 @@ import {
isNativeRunRootHistoricalSpan,
nativeRunPreparationStarts,
recordNativeProviderPerformanceSpans,
+ resolveNativeTimeToFirstTokenStart,
type NativeRunHistoricalSpan,
type NativeRunSpanScope,
type NativeRunTrace,
} from "./native-run-trace.js";
import { createNativeHarnessBackupStamp } from "./native-harness-backup-stamp.js";
+import { readNativeRunWakeRequestedAtMs } from "./native-run-wake-anchor.js";
import { noteNativeRunnerEvidence } from "./native-runner-evidence-signal.js";
import { removeNativeHarnessBackup } from "./native-harness-backup-cleanup.js";
import { registerLiveRunnerGoalController } from "../runner-goal-control-broker.js";
@@ -10206,12 +10208,21 @@ async function executePaperclipNativeSessionWithinScope(
firstTokenRecorded = true;
const textAt = Date.now();
await trace.record({name:"response.first_nonempty_text",parentName:"native.session.execute",startedAtMs:textAt,endedAtMs:textAt});
- await trace.record({
- name: "task.time_to_first_token",
- parentName: "task.provider_session",
- startedAtMs: trace.traceStartedAtMs,
- endedAtMs: Date.now(),
- attributes: { eventKind: textKind },
+ // Detached: the anchor read never delays this event, later events,
+ // or turn.start (invariant 8). The trace settles it at finish.
+ trace.defer(async () => {
+ const ttftStart = resolveNativeTimeToFirstTokenStart({
+ traceStartedAtMs: trace.traceStartedAtMs,
+ preparationSpans,
+ wakeRequestedAtMs: await readNativeRunWakeRequestedAtMs(input.db, input.execution.binding.runId),
+ });
+ await trace.record({
+ name: "task.time_to_first_token",
+ parentName: "task.provider_session",
+ startedAtMs: ttftStart.startedAtMs,
+ endedAtMs: textAt,
+ attributes: { eventKind: textKind, anchor: ttftStart.anchor },
+ });
});
}
await observeAccountingEvent(event);
From 630411af53af86de790a15fbf9abf09e87d6d52a Mon Sep 17 00:00:00 2001
From: Dotta <34892728+cryppadotta@users.noreply.github.com>
Date: Sat, 7 Nov 2026 10:06:35 -0600
Subject: [PATCH 07/24] fix(recovery): require a 1 s start-time gap and treat
EPERM as alive in owner proofs (#19848)
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
> - After a restart, recovery code decides whether the process that owns
an in-progress run is gone
> - Two proofs compare process start times to the millisecond, but `ps
-o lstart` on macOS and BSD reports whole seconds
> - So a live owner can look like a reused PID, and recovery can release
it while it still runs
> - Signal-0 handling also disagrees: one check treats EPERM as dead,
while all others treat it as alive
> - This pull request puts one start-time rule and one EPERM rule in
`controller-process-identity.ts` and uses them at every site the Phase 0
ownership inventory named
> - The benefit is that no proof releases a live owner because of clock
precision or a permission error
## Linked Issues or Issue Description
**Bug description**
The Phase 0 ownership inventory (finding 1) found inconsistent "owner
gone" proofs. `native-failed-run-owner-release.ts`
(`recordedProcessMayBeLive`, `runProcessMayBeLive`) and
`native-session-executor.ts` (`verifiedRecoveryProcessIsAlive`) treat
any start-time difference of 1 ms or more as a reused PID.
`native-restart-recovery.ts` and `controllerProcessExited` require a gap
of at least 1 s. `local-service-supervisor.ts` (`isPidAlive`,
`isProcessGroupAlive`) treats EPERM as dead.
**Steps to reproduce**
1. On macOS, record a live process start time with millisecond
precision.
2. Run the abandoned-owner release pass, or the recovered-runner
liveness check, against that live PID.
3. The pass releases the owner, or the check reports the runner as gone.
**Expected behavior**
A sub-second start-time gap is ambiguous and keeps the owner. EPERM
means the process exists.
Refs #19846
## What Changed
- `controller-process-identity.ts`: export `processExists` (EPERM =
alive) and `processStartsDefinitelyDiffer` (gap >= 1 s; a missing time
proves nothing). `controllerProcessExited` uses the new helper.
- `native-failed-run-owner-release.ts`: the controller and run-process
checks use the shared helpers instead of exact millisecond equality.
- `native-session-executor.ts`: `verifiedRecoveryProcessIsAlive` accepts
a start time within 1 s as the same runner. Its signal path uses the
same check.
- `native-restart-recovery.ts`: `definitivelyDifferentProcessStart`
delegates to the shared helper. No behavior change.
- `local-service-supervisor.ts`: `isPidAlive` and `isProcessGroupAlive`
treat EPERM as alive.
## Verification
- New `controller-process-identity.test.ts`: the 1 s boundary, EPERM and
ESRCH for every signal-0 check, and a live spawned runner whose recorded
start is 500 ms off.
- `native-failed-run-owner-release.test.ts`: two new cases (controller
and run process) with a live child and a recorded start 500 ms off. The
owner stays `observed`.
- Red before the fix: with the old call sites, all 4 new cases fail
(`releaseAbandonedNativeOwners` returns 1 and releases the live owner;
EPERM returns false; the live runner reads as gone). Green after the
fix.
- `npx vitest run src/services/controller-process-identity.test.ts
src/services/native-runtime/native-failed-run-owner-release.test.ts
src/services/native-runtime/native-restart-recovery.test.ts
src/__tests__/local-service-supervisor.test.ts`: 59 passed.
## Risks
- Low risk. The change only makes proofs stricter: a sub-second gap or
EPERM now keeps an owner that the old code released. Such a row waits
for the existing lease, TTL, or real process exit.
- A recycled PID whose new process started within 1 s of the recorded
one now stays held until it exits. That is the same rule the takeover
path already used.
- Previous-release story: no persisted shape changes. Rows saved by the
previous release are evaluated with the stricter rule.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used 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
---
.../controller-process-identity.test.ts | 53 +++++++++++++++++++
.../services/controller-process-identity.ts | 27 ++++++++--
.../src/services/local-service-supervisor.ts | 15 ++----
.../native-failed-run-owner-release.test.ts | 27 ++++++++++
.../native-failed-run-owner-release.ts | 8 +--
.../native-runtime/native-restart-recovery.ts | 9 ++--
.../native-runtime/native-session-executor.ts | 17 +++---
7 files changed, 124 insertions(+), 32 deletions(-)
create mode 100644 server/src/services/controller-process-identity.test.ts
diff --git a/server/src/services/controller-process-identity.test.ts b/server/src/services/controller-process-identity.test.ts
new file mode 100644
index 00000000000..e029bf52589
--- /dev/null
+++ b/server/src/services/controller-process-identity.test.ts
@@ -0,0 +1,53 @@
+import { spawn } from "node:child_process";
+import { once } from "node:events";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { processExists, processStartsDefinitelyDiffer } from "./controller-process-identity.js";
+import { isPidAlive, isProcessGroupAlive } from "./local-service-supervisor.js";
+import { readProcessStartedAt } from "./hot-restart.js";
+import { verifiedRecoveryProcessIsAlive } from "./native-runtime/native-session-executor.js";
+
+describe("shared process identity proof", () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it("needs a start-time gap of at least one second to prove a recycled PID", () => {
+ const at = new Date("2026-11-07T10:00:00.000Z");
+ expect(processStartsDefinitelyDiffer(at, new Date(at.getTime() + 999))).toBe(false);
+ expect(processStartsDefinitelyDiffer(at, "2026-11-07T09:59:59.001Z")).toBe(false);
+ expect(processStartsDefinitelyDiffer(at, new Date(at.getTime() + 1_000))).toBe(true);
+ expect(processStartsDefinitelyDiffer(at, null)).toBe(false);
+ expect(processStartsDefinitelyDiffer("not a date", at)).toBe(false);
+ });
+
+ it("treats EPERM as a live process in every signal-0 check", () => {
+ vi.spyOn(process, "kill").mockImplementation(() => {
+ throw Object.assign(new Error("operation not permitted"), { code: "EPERM" });
+ });
+ expect(processExists(4242)).toBe(true);
+ expect(isPidAlive(4242)).toBe(true);
+ if (process.platform !== "win32" && process.platform !== "linux") expect(isProcessGroupAlive(4242)).toBe(true);
+ });
+
+ it("treats ESRCH as a gone process", () => {
+ vi.spyOn(process, "kill").mockImplementation(() => {
+ throw Object.assign(new Error("no such process"), { code: "ESRCH" });
+ });
+ expect(processExists(4242)).toBe(false);
+ expect(isPidAlive(4242)).toBe(false);
+ });
+
+ it.skipIf(process.platform === "win32")("keeps a live recovered runner whose recorded start differs by under a second", async () => {
+ const live = spawn(process.execPath, ["-e", "setInterval(() => {}, 1_000)"], { stdio: "ignore" });
+ await once(live, "spawn");
+ try {
+ const observed = new Date((await readProcessStartedAt(live.pid!))!);
+ const startedAt = new Date(observed.getTime() + 500).toISOString();
+ await expect(verifiedRecoveryProcessIsAlive({ pid: live.pid!, startedAt })).resolves.toBe(true);
+ const recycled = new Date(observed.getTime() + 5_000).toISOString();
+ await expect(verifiedRecoveryProcessIsAlive({ pid: live.pid!, startedAt: recycled })).resolves.toBe(false);
+ } finally {
+ const exited = once(live, "exit");
+ live.kill("SIGKILL");
+ await exited;
+ }
+ });
+});
diff --git a/server/src/services/controller-process-identity.ts b/server/src/services/controller-process-identity.ts
index f752827934e..2bf79735f6f 100644
--- a/server/src/services/controller-process-identity.ts
+++ b/server/src/services/controller-process-identity.ts
@@ -68,7 +68,11 @@ export function readControllerProcess(value: unknown): ControllerProcess | null
processStartedAt: typeof record.processStartedAt === "string" ? record.processStartedAt : null };
}
-function processExists(pid: number): boolean {
+/**
+ * True when some process owns the PID in this PID space. EPERM means the
+ * process exists but belongs to another user, so it counts as alive.
+ */
+export function processExists(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
@@ -77,6 +81,24 @@ function processExists(pid: number): boolean {
}
}
+/** Process start times closer than this may be the same process. */
+export const PROCESS_START_PRECISION_MS = 1_000;
+
+/**
+ * True only when two start times for one PID prove different processes.
+ * `ps -o lstart` on macOS and BSD has whole-second precision, while a recorded
+ * start can come from a millisecond clock, so a sub-second gap is ambiguous
+ * and fails closed (same process). A missing or unparsable time proves nothing.
+ */
+export function processStartsDefinitelyDiffer(
+ recorded: Date | string | null | undefined,
+ observed: Date | string | null | undefined,
+): boolean {
+ const left = recorded instanceof Date ? recorded.getTime() : Date.parse(recorded ?? "");
+ const right = observed instanceof Date ? observed.getTime() : Date.parse(observed ?? "");
+ return Number.isFinite(left) && Number.isFinite(right) && Math.abs(left - right) >= PROCESS_START_PRECISION_MS;
+}
+
/** True only with proof, in this process's own PID space, that the recorded
* server process has exited. Another space, an unreadable space, this server,
* or an ambiguous live PID returns false. */
@@ -85,7 +107,6 @@ export async function controllerProcessExited(controller: ControllerProcess): Pr
if (!processExists(controller.pid)) return true;
// The PID now belongs to a live process, possibly this restarted server.
// Only a definitely different start time proves the recorded process is gone.
- const recorded = Date.parse(controller.processStartedAt ?? "");
const observed = await observedProcessStartedAt(controller.pid);
- return Number.isFinite(recorded) && observed !== null && Math.abs(observed - recorded) >= 1_000;
+ return observed !== null && processStartsDefinitelyDiffer(controller.processStartedAt, new Date(observed));
}
diff --git a/server/src/services/local-service-supervisor.ts b/server/src/services/local-service-supervisor.ts
index 0eee27ea3d5..5940b11e500 100644
--- a/server/src/services/local-service-supervisor.ts
+++ b/server/src/services/local-service-supervisor.ts
@@ -6,6 +6,7 @@ import path from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { promisify } from "node:util";
import { resolvePaperclipInstanceRoot } from "../home-paths.js";
+import { processExists } from "./controller-process-identity.js";
const execFileAsync = promisify(execFile);
@@ -242,24 +243,16 @@ export async function findLocalServiceRegistryRecordByRuntimeServiceId(input: {
return candidate;
}
+/** EPERM means the process exists under another user, so it is alive. */
export function isPidAlive(pid: number) {
if (!Number.isInteger(pid) || pid <= 0) return false;
- try {
- process.kill(pid, 0);
- return true;
- } catch {
- return false;
- }
+ return processExists(pid);
}
export function isProcessGroupAlive(processGroupId: number | null | undefined) {
if (process.platform === "win32") return false;
if (typeof processGroupId !== "number" || !Number.isInteger(processGroupId) || processGroupId <= 0) return false;
- try {
- process.kill(-processGroupId, 0);
- } catch {
- return false;
- }
+ if (!processExists(-processGroupId)) return false;
if (process.platform === "linux") {
const liveMember = readLinuxProcessGroupActivity(processGroupId);
diff --git a/server/src/services/native-runtime/native-failed-run-owner-release.test.ts b/server/src/services/native-runtime/native-failed-run-owner-release.test.ts
index d65ecf3850d..11dd4d5aa13 100644
--- a/server/src/services/native-runtime/native-failed-run-owner-release.test.ts
+++ b/server/src/services/native-runtime/native-failed-run-owner-release.test.ts
@@ -17,6 +17,7 @@ import {
} from "@paperclipai/db";
import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
import { agentExecutionsHaveStopped } from "../agent-execution-stop.js";
+import { readProcessStartedAt } from "../hot-restart.js";
import { DELIVERY_QUEUES } from "../delivery-work-notifications.js";
import { environmentService } from "../environments.js";
import { executionControlSchedule } from "../execution-control-work.js";
@@ -253,6 +254,32 @@ describe("failed native run owner release", () => {
}
});
+ // `ps -o lstart` on macOS reports whole seconds, while a recorded start can
+ // carry milliseconds. A sub-second gap must not be read as a recycled PID.
+ it.each(["controller", "run process"])("keeps the owner when the live %s start time differs by under a second", async (holder) => {
+ const { runId } = await nativeRun({ status: "failed", errorCode: "adapter_failed",
+ coordinator: { leaseOwner: `default:resume:${randomUUID()}`, leaseExpiresAt: new Date(0) } });
+ const live = spawn(process.execPath, ["-e", "setInterval(() => {}, 1_000)"], { stdio: "ignore", detached: true });
+ await once(live, "spawn");
+ try {
+ const observed = new Date((await readProcessStartedAt(live.pid!))!);
+ const recorded = new Date(observed.getTime() + 500);
+ if (holder === "controller") {
+ await db.update(nativeRunFinalizations).set({ controllerPid: live.pid!, controllerBootId: randomUUID(),
+ controllerProcessStartedAt: recorded }).where(eq(nativeRunFinalizations.runId, runId));
+ } else {
+ await db.update(heartbeatRuns).set({ processPid: live.pid!, processGroupId: live.pid!, processStartedAt: recorded })
+ .where(eq(heartbeatRuns.id, runId));
+ }
+ await expect(releaseAbandonedNativeOwners(db)).resolves.toBe(0);
+ expect(await coordinator(runId)).toMatchObject({ phase: "observed", leaseOwner: expect.any(String) });
+ } finally {
+ const exited = once(live, "exit");
+ live.kill("SIGKILL");
+ await exited;
+ }
+ });
+
it("rotates bounded passes past owners that a live controller still holds", async () => {
const runs = await Promise.all([0, 1, 2].map(() => nativeRun({ status: "failed", errorCode: "adapter_failed",
coordinator: { leaseOwner: `default:resume:${randomUUID()}`, leaseExpiresAt: new Date(0) } })));
diff --git a/server/src/services/native-runtime/native-failed-run-owner-release.ts b/server/src/services/native-runtime/native-failed-run-owner-release.ts
index 1db97b0a861..3ea34cda26b 100644
--- a/server/src/services/native-runtime/native-failed-run-owner-release.ts
+++ b/server/src/services/native-runtime/native-failed-run-owner-release.ts
@@ -2,6 +2,7 @@ import { and, asc, eq, gt, inArray, isNotNull, isNull, lte, or, sql } from "driz
import { environmentLeases, heartbeatRuns, issues, nativeRunFinalizations, nativeRunResults, type Db } from "@paperclipai/db";
import { logger } from "../../middleware/logger.js";
import { adapterExecutionControls } from "../adapter-execution-control.js";
+import { processExists, processStartsDefinitelyDiffer } from "../controller-process-identity.js";
import { logActivity, publishActivity, type ActivityPublication } from "../activity-log.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "../delivery-work-notifications.js";
import { notifyExecutionRunWork } from "../execution-control-notifications.js";
@@ -85,8 +86,7 @@ export async function nextAbandonedNativeOwnerReleaseAt(db: Db): Promise null);
- return !observed || new Date(observed).getTime() === startedAt.getTime();
+ return !processStartsDefinitelyDiffer(startedAt, observed);
}
/**
@@ -110,7 +110,7 @@ async function runProcessMayBeLive(run: Run, now: Date): Promise {
let groupAlive = Boolean(run.processGroupId && !processAbsent(-run.processGroupId));
if (processAlive && run.processStartedAt) {
const observed = await readProcessStartedAt(run.processPid!).catch(() => null);
- if (observed && new Date(observed).getTime() !== run.processStartedAt.getTime()) {
+ if (processStartsDefinitelyDiffer(run.processStartedAt, observed)) {
processAlive = false;
if (run.processGroupId === run.processPid) groupAlive = false;
}
diff --git a/server/src/services/native-runtime/native-restart-recovery.ts b/server/src/services/native-runtime/native-restart-recovery.ts
index 480ad9248a1..f33e728ec2f 100644
--- a/server/src/services/native-runtime/native-restart-recovery.ts
+++ b/server/src/services/native-runtime/native-restart-recovery.ts
@@ -35,6 +35,7 @@ import {
} from "@paperclipai/db";
import { REMOTE_CONTROLLER_LEASE_MS } from "./native-runner-recovery-contract.js";
import { readProcessStartedAt } from "../hot-restart.js";
+import { processStartsDefinitelyDiffer } from "../controller-process-identity.js";
import { getServerProcessStartedAt } from "../../server-info.js";
import { redactSensitiveText } from "../../redaction.js";
import { isUniqueViolation } from "../../db-errors.js";
@@ -349,12 +350,8 @@ function definitivelyDifferentProcessStart(
left: Date | null,
right: Date | null,
): boolean {
- if (left === null || right === null) return false;
- // `ps -o lstart` has only whole-second precision on macOS and BSD. A
- // sub-second disagreement can therefore be the same process when one probe
- // fell back to a higher-precision spawn timestamp. Treat it as ambiguous and
- // fail closed instead of declaring the live PID recycled.
- return Math.abs(left.getTime() - right.getTime()) >= 1_000;
+ // Shared with every other owner proof: a sub-second gap is ambiguous.
+ return processStartsDefinitelyDiffer(left, right);
}
export async function evaluateNativeControllerTakeover(input: {
diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts
index 4e12dbc7104..dd5765d3eca 100644
--- a/server/src/services/native-runtime/native-session-executor.ts
+++ b/server/src/services/native-runtime/native-session-executor.ts
@@ -296,6 +296,7 @@ import { removeNativeHarnessBackup } from "./native-harness-backup-cleanup.js";
import { registerLiveRunnerGoalController } from "../runner-goal-control-broker.js";
import { applyRunnerGoalPrpEvent } from "../runner-goals.js";
import { readProcessStartedAt } from "../hot-restart.js";
+import { processExists, processStartsDefinitelyDiffer } from "../controller-process-identity.js";
import {
NativeRunnerOwnershipUnverifiedError,
isNativeRunnerOwnershipHeld,
@@ -581,21 +582,21 @@ const nativeRuntimeRequestResolutions = new Map<
NativeRuntimeRequestResolution
>();
-async function verifiedRecoveryProcessIsAlive(input: {
+/**
+ * True when the recorded runner still owns its PID. A start time within the
+ * shared precision window is the same process: `ps -o lstart` on macOS has
+ * whole-second precision, so an exact match would call a live runner gone.
+ */
+export async function verifiedRecoveryProcessIsAlive(input: {
pid: number;
startedAt: string;
}): Promise {
- try {
- process.kill(input.pid, 0);
- } catch (error) {
- if ((error as NodeJS.ErrnoException | undefined)?.code !== "EPERM")
- return false;
- }
+ if (!processExists(input.pid)) return false;
try {
const observed = await readProcessStartedAt(input.pid);
return (
observed !== null &&
- new Date(observed).getTime() === new Date(input.startedAt).getTime()
+ !processStartsDefinitelyDiffer(input.startedAt, observed)
);
} catch {
return false;
From 824b25654ce6bcbe9c3b13dab37aca0c2d60247b Mon Sep 17 00:00:00 2001
From: Dotta <34892728+cryppadotta@users.noreply.github.com>
Date: Sat, 7 Nov 2026 10:24:03 -0600
Subject: [PATCH 08/24] fix(ui): keep a Retry for retained-file holds whose
source cannot be verified (#19840)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - When a native run finishes but its files cannot be saved, the task
stays blocked behind a retained-file recovery hold.
> - The server records that hold as blocked and retryable, and the task
notice tells the user to "Retry to try again".
> - The task page hides its own Retry for these holds and relies on the
retained-file recovery panel instead.
> - That panel only binds the recovery record when a read-only source
inspection returns `verified`.
> - Inspection can return `blocked` for normal reasons: a sandbox that
predates ownership receipts (state saved by an older release), or a
workspace that moved on after its files were recovered.
> - Then neither surface offers an action, and "Check file recovery
status" always answers "File recovery changed. Refresh the task", also
after a reload.
> - This pull request binds the record by its own identity, uses
inspection only to gate the physical file-recovery request, and keeps
the task Retry visible whenever the panel has no control of its own.
## Linked Issues or Issue Description
Refs #18848 (the change that added the retained-file recovery panel and
hid the generic Retry for these holds).
**What happened?**
A blocked task with an active
`native_workspace_sync_out_retry_exhausted` hold showed "The saved files
need recovery before work can continue", "The recorded source is
unavailable or has changed", and "Saving the agent's files failed after
automatic retries. Retry to try again". It showed no Retry and no
recover button. "Check file recovery status" always answered "File
recovery changed. Refresh the task to inspect the current recovery", and
a reload did not change it. The hold was saved by an earlier release:
`systemRecovery` exhausted with `allocation_ownership_ambiguous` /
`service_required`, and `workspaceRecovery` blocked with `retryable:
true`. The source inspection endpoint returned `status: "blocked"` for
it. A second task whose files were already recovered showed the same
"need recovery" and "has changed" text, because its inspection reported
a reference mismatch after recovery.
**Expected behavior**
A retryable hold always shows a working Retry or recover control. A
notice that says "Retry" has a Retry button. Status checks never loop on
"changed, refresh". Recovered files show as recovered. When the source
cannot be verified, the page names the reason and who must inspect it.
**Steps to reproduce**
1. Use an active retained-export hold whose `workspaceRecovery` is
blocked and retryable, and whose `systemRecovery` is exhausted.
2. Make the source inspection (`GET
/api/issues/:id/recovery-actions?inspectSourceRunId=…&inspectSourceActionId=…`)
return `status: "blocked"`.
3. Open the task as a board operator.
4. Before this change, the page shows no Retry and no recover button.
"Check file recovery status" reports "File recovery changed. Refresh the
task".
**Paperclip version or commit**
Observed on build `8812c19`. The regressions fail on master `0f5ce5050e`
before the production edits.
## What Changed
- `WorkspaceExportRecovery`: bind the recovery record by action, run and
schema identity, not by inspection status. Inspection status now gates
only the physical "Recover saved files" request (and the request
re-checks it before POST).
- `WorkspaceExportRecovery`: report through `onRecoveryControlChange`
whether the panel offers its own control. It reports `true` only while
the source is loading or verified and the files are not yet recovered,
or while it shows the previous-server stop confirmation.
- `IssueDetail`: hide the task Retry for retained-export holds only
while the panel reports that it owns the control. Otherwise the existing
task Retry (`POST /issues/:id/retry`) shows. The server renews a bounded
recovery generation and re-verifies the source.
- Show recovered files as recovered even when inspection no longer
matches after recovery.
- Name an unverifiable source in plain words (with the code for other
reasons). State that Paperclip does not apply files it can't verify.
- Recovery text never asks a person to inspect a sandbox or environment,
and never names an owner or administrator as the one who must act. This
covers the retained-file panel, the run source inspector, the copyback
wait, and the native cleanup quarantine message. The execution blocker
and the recovery action read model describe a spent recovery budget from
its current state, so text saved by older releases ("If Retry keeps
failing, inspect the run and its environment") is not shown.
- Task Retry uses the existing `createUuid()` helper, so it works on
plain-HTTP previews without `crypto.randomUUID`. An accepted Retry also
refreshes the inspected file-recovery state. After a failed accepted
request, the unverified-source reason stays visible; it hides only while
recovery runs.
- When the recovery record was replaced, "Check file recovery status"
reloads the task detail instead of telling the user to refresh.
- Tests: component regressions for an old-release hold, a recovered hold
with a mismatched source, verified ownership, and a replaced record. A
page regression proves Retry is shown and calls `retryTask` for
unverified and stale sources. A server safety test proves that Retry for
the old-release hold shape is accepted, opens one new bounded
generation, queues file recovery again, keeps the hold active, and is
idempotent.
## Verification
- RED (master `0f5ce5050e` production files, new tests): 5 component
tests fail. The failure output shows the exact staging text: "Check file
recovery status", "File recovery changed. Refresh the task to inspect
the current recovery.", "The recorded source is unavailable or has
changed." 2 page tests (unverified and stale) fail with `expected [
'Check file recovery status', … ] to include 'Retry'`.
- GREEN: `cd ui && npx vitest run
src/components/WorkspaceExportRecovery.control.test.tsx
src/components/WorkspaceExportRecovery.test.tsx
src/components/RunWorkspaceRecoverySurface.test.tsx
src/components/ExecutionBlockerNotice.test.tsx
src/pages/IssueDetail.test.tsx` passes 320 tests.
- Server: `cd server && npx vitest run src/services/task-retry.test.ts`
passes 81 tests, including the new old-release safety case. This is
safety evidence, not a red: the server path was already correct, and the
defect was in the UI.
- Full UI suite: 11564 pass. 4 tests in `IssuesList.test.tsx` and
`CompanyEnvironments.test.tsx` failed under full-suite load and pass in
isolation (106/106). They are unrelated to this change.
- `pnpm check:token-gates` is clean. `node scripts/run-tsc.mjs -p
ui/tsconfig.json --noEmit` reports no errors in the touched files. The
remaining errors are local artifacts that were not built (plugin SDK UI
entry, generated Storybook catalog).
- Staging was read only (GET requests). The inspect request did not loop
in a fresh tab: two calls in 30 seconds. Most of the tab's request
volume is periodic company issue-list refetches, which this change does
not touch.
## Risks
- Low risk. This is a UI-only behavior change. Server authorization,
source verification, stop receipts, and the bounded recovery policy are
unchanged and remain authoritative.
- The task Retry is now visible for retained-export holds whose source
does not verify. Retry renews one recovery generation. The worker
re-runs the same source-identity checks, so Retry cannot bypass an
ownership refusal. If the refusal is permanent (for example an ambiguous
sandbox allocation), the hold returns to exhausted and the page names
the reason. An automatic fallback for such sources is follow-up work.
- Wording: a parametrized UI test renders every recovery state and
asserts that no administrator, owner, or "inspect the environment" copy
appears. A server test proves that a stored old-release message is
replaced by state-derived text. Both failed before the change.
- Previous-release story: the old-release hold shape (board-owned,
`systemRecovery` revision 5 exhausted with `service_required`,
`workspaceRecovery` blocked and retryable) is covered by component,
page, and server tests. No persisted state shape changes.
> 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 (Anthropic), model ID `claude-opus-5-5`, used through
Claude Code with tool use (repository search, file edits, shell, test
execution, and a read-only browser).
## 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
---
server/src/services/issue-recovery-actions.ts | 11 +-
.../native-runtime/native-session-executor.ts | 2 +-
.../services/system-recovery-state.test.ts | 20 +++
server/src/services/system-recovery-state.ts | 13 ++
server/src/services/system-recovery.ts | 15 +-
server/src/services/task-retry.test.ts | 34 +++++
.../services/workspace-recovery-receipt.ts | 10 +-
.../workspace-recovery-retry-copyback.test.ts | 2 +-
.../workspace-recovery-warm-handoff.test.ts | 4 +-
.../RunWorkspaceSourceInspection.tsx | 2 +-
.../WorkspaceExportRecovery.control.test.tsx | 135 +++++++++++++++++-
.../WorkspaceExportRecovery.test.tsx | 6 +-
ui/src/components/WorkspaceExportRecovery.tsx | 94 +++++++++---
ui/src/hooks/useTaskRetry.test.tsx | 9 ++
ui/src/hooks/useTaskRetry.ts | 7 +-
ui/src/lib/queryKeys.ts | 1 +
ui/src/pages/IssueDetail.test.tsx | 43 ++++--
ui/src/pages/IssueDetail.tsx | 6 +-
18 files changed, 356 insertions(+), 58 deletions(-)
diff --git a/server/src/services/issue-recovery-actions.ts b/server/src/services/issue-recovery-actions.ts
index f274af2e15c..bddd3c5ec96 100644
--- a/server/src/services/issue-recovery-actions.ts
+++ b/server/src/services/issue-recovery-actions.ts
@@ -17,6 +17,7 @@ import type {
} from "@paperclipai/shared";
import { isNativeWorkspaceFinalizationOperationActive } from "./workspace-operations.js";
+import { exhaustedSystemRecoveryAction, readSystemRecovery } from "./system-recovery-state.js";
const ACTIVE_RECOVERY_ACTION_STATUSES = ["active", "escalated"] as const satisfies readonly IssueRecoveryActionStatus[];
const MAX_UPSERT_RETRIES = 3;
@@ -87,6 +88,14 @@ export type ResolveIssueRecoveryActionInput = {
resolutionNote?: string | null;
};
+/** A spent saved-work recovery is described from its current state. Text saved
+ * by an older release could ask a person to inspect the run's environment. */
+function readModelNextAction(row: IssueRecoveryActionRow): string {
+ const system = readSystemRecovery(row.evidence);
+ return system?.state === "exhausted" && row.evidence?.workspaceRecovery
+ ? exhaustedSystemRecoveryAction(system) : row.nextAction;
+}
+
function toReadModel(row: IssueRecoveryActionRow): IssueRecoveryAction {
return {
id: row.id,
@@ -103,7 +112,7 @@ function toReadModel(row: IssueRecoveryActionRow): IssueRecoveryAction {
cause: row.cause,
fingerprint: row.fingerprint,
evidence: row.evidence,
- nextAction: row.nextAction,
+ nextAction: readModelNextAction(row),
wakePolicy: row.wakePolicy,
monitorPolicy: row.monitorPolicy,
attemptCount: row.attemptCount,
diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts
index dd5765d3eca..2531fe72169 100644
--- a/server/src/services/native-runtime/native-session-executor.ts
+++ b/server/src/services/native-runtime/native-session-executor.ts
@@ -7984,7 +7984,7 @@ const NATIVE_STARTUP_MODEL_REJECTED_ACTION =
"The provider could not start the selected model before any provider work began. Choose a supported model for this agent, then retry the task. Automatic retries are stopped.";
const NATIVE_CLEANUP_OPERATOR_RECOVERY_MESSAGE =
- "Send a new message to continue after Paperclip verifies that the previous provider and its tools have stopped. If cleanup cannot be verified, inspect the run and its environment. Clearing a task session does not resolve this quarantine. Automatic retries are stopped.";
+ "Send a new message to continue after Paperclip verifies that the previous provider and its tools have stopped. Clearing a task session does not resolve this quarantine. Automatic retries are stopped.";
const PROVIDER_DURABLE_EVENT_TYPES = NATIVE_PROVIDER_DURABLE_EVENT_TYPES;
diff --git a/server/src/services/system-recovery-state.test.ts b/server/src/services/system-recovery-state.test.ts
index 04059e8e678..e04ba8ec10a 100644
--- a/server/src/services/system-recovery-state.test.ts
+++ b/server/src/services/system-recovery-state.test.ts
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
import { describe, expect, it } from "vitest";
import { createSystemRecovery, failSystemRecovery, readSystemRecovery, reserveSystemRecoveryAttempt, SystemRecoveryFailure } from "./system-recovery-state.js";
import { exhaustedSystemRecoveryAction } from "./system-recovery.js";
+import { workspaceRecoveryDisplay } from "./workspace-recovery-receipt.js";
describe("durable system recovery budget", () => {
it("makes six attempts with exponential delays that survive serialization and exhaustion", () => {
@@ -43,6 +44,25 @@ describe("durable system recovery budget", () => {
{ now: 0, cause: { label: "/home/daytona/secret", code: null, status: null } });
expect(unsafe.failure).not.toHaveProperty("cause");
});
+ it("never asks a person to inspect a sandbox, even for text saved by an older release", () => {
+ const manual = /administrator|\bowner\b|board member|inspect the run|environment/i;
+ const exhausted = failSystemRecovery(createSystemRecovery(randomUUID()),
+ new SystemRecoveryFailure("allocation_ownership_ambiguous", "service_required"));
+ const copyback = failSystemRecovery(createSystemRecovery(randomUUID()),
+ new SystemRecoveryFailure("copyback_stop_unconfirmed", "recheck_evidence"));
+ for (const state of [exhausted, { ...copyback, state: "exhausted" as const }])
+ expect(exhaustedSystemRecoveryAction(state)).not.toMatch(manual);
+ const runId = exhausted.sourceRunId;
+ const display = workspaceRecoveryDisplay({ runId, systemRecovery: exhausted, workspaceRecovery: {
+ schema: "paperclip.workspace-recovery.v1", runId, status: "blocked", stage: "verifying_stop", attempt: 1,
+ attemptLimit: 6, requestIds: [], retryable: true,
+ message: "Automatic recovery of saved work stopped after 1 attempts (last failure: allocation_ownership_ambiguous). "
+ + "Retry recovery to export and merge from the retained sandbox again; no provider turn is submitted. "
+ + "If Retry keeps failing, inspect the run and its environment." } }, runId);
+ expect(display?.message).toContain("Retry to try again");
+ expect(display?.message).not.toMatch(manual);
+ });
+
it("names the last failure and its cause in the board handoff", () => {
const state = reserveSystemRecoveryAttempt(createSystemRecovery(randomUUID()), 0)!;
const withCause = failSystemRecovery(state, new SystemRecoveryFailure("provider_unavailable", "retry_transient"),
diff --git a/server/src/services/system-recovery-state.ts b/server/src/services/system-recovery-state.ts
index 411f2cc43f2..703bf0fa9b6 100644
--- a/server/src/services/system-recovery-state.ts
+++ b/server/src/services/system-recovery-state.ts
@@ -126,3 +126,16 @@ export function failSystemRecovery(
evidenceFingerprint: options.evidenceFingerprint ?? createHash("sha256").update(`${state.sourceRunId}:${failure.code}`).digest("hex") },
};
}
+
+/** User-facing text for a spent recovery budget. It names what happens next and
+ * never asks a person to inspect a sandbox or environment. The code stays for support. */
+export function exhaustedSystemRecoveryAction(state: SystemRecoveryState): string {
+ // Another Retry cannot release a copyback owner that stopped without reporting.
+ if (state.failure?.code === "copyback_stop_unconfirmed")
+ return "Recovery of saved work is waiting for the previous server's file copy to stop. "
+ + "Recovery resumes once Paperclip can confirm that it stopped. No provider turn is submitted.";
+ const cause = state.failure?.cause ? `, cause: ${state.failure.cause.label}` : "";
+ const reason = state.failure?.code ? ` (last failure: ${state.failure.code}${cause})` : "";
+ return `Automatic recovery of saved work stopped after ${state.attempts} attempts${reason}. `
+ + "Retry to try again; the agent will not repeat its work.";
+}
diff --git a/server/src/services/system-recovery.ts b/server/src/services/system-recovery.ts
index 3edd496a1d3..d816e32c049 100644
--- a/server/src/services/system-recovery.ts
+++ b/server/src/services/system-recovery.ts
@@ -3,7 +3,7 @@ import { and, eq, sql } from "drizzle-orm";
import { agents, issues, heartbeatRuns, issueComments, issueRecoveryActions, type Db } from "@paperclipai/db";
import { writeExecutionControl } from "./execution-control-notifications.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
-import { createSystemRecovery, readSystemRecovery, type SystemRecoveryState } from "./system-recovery-state.js";
+import { createSystemRecovery, exhaustedSystemRecoveryAction, readSystemRecovery, type SystemRecoveryState } from "./system-recovery-state.js";
import { workspaceRecoverySourceEligible, type WorkspaceRecoverySourceIdentity } from "./workspace-recovery-source.js";
export async function adoptSystemRecovery(db: Db, source: WorkspaceRecoverySourceIdentity) {
@@ -47,18 +47,7 @@ export async function adoptSystemRecovery(db: Db, source: WorkspaceRecoverySourc
});
}
-export function exhaustedSystemRecoveryAction(state: SystemRecoveryState): string {
- // Another Retry cannot release a copyback owner that stopped without reporting.
- if (state.failure?.code === "copyback_stop_unconfirmed")
- return "Automatic recovery of saved work is waiting for the previous server's file copy to stop, and Paperclip cannot verify "
- + "that it stopped. A board member who manages this company's runtime can confirm that it stopped; recovery then "
- + "resumes. No provider turn is submitted.";
- const cause = state.failure?.cause ? `, cause: ${state.failure.cause.label}` : "";
- const reason = state.failure?.code ? ` (last failure: ${state.failure.code}${cause})` : "";
- return `Automatic recovery of saved work stopped after ${state.attempts} attempts${reason}. `
- + "Retry recovery to export and merge from the retained sandbox again; no provider turn is submitted. "
- + "If Retry keeps failing, inspect the run and its environment.";
-}
+export { exhaustedSystemRecoveryAction };
/** CAS protects a newer manual generation from an old worker's late write.
* This is bookkeeping authority only; physical writes still require ownership. */
diff --git a/server/src/services/task-retry.test.ts b/server/src/services/task-retry.test.ts
index b2b2c42a25e..cbc567f6aa3 100644
--- a/server/src/services/task-retry.test.ts
+++ b/server/src/services/task-retry.test.ts
@@ -678,6 +678,40 @@ describe("durable task Retry admission", () => {
expect(wakes.find(row => row.id === first.requestId)?.status).toBe("failed");
expect(wakes.filter(row => row.status === "deferred_issue_execution")).toHaveLength(1);
});
+ it("accepts Retry for an old-release retained-export hold whose source ownership could not be verified", async () => {
+ // State saved by an earlier release: a board-owned export hold whose only
+ // attempt ended with a permanent ownership refusal. The task UI now offers
+ // Retry for it; Retry must open one new bounded generation that re-verifies
+ // the source, keep the hold in place, and never resolve or bypass it.
+ const input = await seed();
+ const previous = { ...failSystemRecovery({ ...createSystemRecovery(input.observedRunId), revision: 4 },
+ new SystemRecoveryFailure("allocation_ownership_ambiguous", "service_required")), revision: 5 };
+ expect(previous.state).toBe("exhausted");
+ const [action] = await db.insert(issueRecoveryActions).values({
+ companyId: input.companyId, sourceIssueId: input.issueId, kind: "active_run_watchdog", status: "active",
+ ownerType: "board", cause: "native_workspace_sync_out_retry_exhausted", fingerprint: randomUUID(),
+ nextAction: "Automatic recovery of saved work stopped after 1 attempts (last failure: allocation_ownership_ambiguous).",
+ evidence: { runId: input.observedRunId, systemRecovery: previous,
+ workspaceRecovery: { schema: "paperclip.workspace-recovery.v1", runId: input.observedRunId, stage: "verifying_stop",
+ status: "blocked", attempt: 1, attemptLimit: 6, requestIds: [], retryable: true, message: "Retry recovery." },
+ coordinatorAttempt: 1, originalFailureCode: "native_workspace_sync_out_failed",
+ workspaceFinalizeAttempt: 3, previousWorkspaceRecovery: null },
+ }).returning();
+ const receipt = await requestTaskRetry(input);
+ expect(receipt).toMatchObject({ accepted: true, stale: false, observedRunId: input.observedRunId });
+ const [updated] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, action.id));
+ expect(updated.status).toBe("active");
+ expect(updated.resolvedAt).toBeNull();
+ expect(readSystemRecovery(updated.evidence)).toMatchObject({ generationId: receipt.requestId, sourceRunId: input.observedRunId,
+ attempts: 0, failure: null, revision: 6, freshAttemptRunId: null, preservationOperationIds: [] });
+ // File recovery is queued again for the worker, which re-verifies the source.
+ expect(updated.evidence.workspaceRecovery).toMatchObject({ runId: input.observedRunId, status: "queued",
+ stage: "verifying_stop", attemptLimit: 6, retryable: true });
+ // A replayed click is idempotent and does not open another generation.
+ expect((await requestTaskRetry(input)).requestId).toBe(receipt.requestId);
+ const [replayed] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, action.id));
+ expect(readSystemRecovery(replayed.evidence)?.revision).toBe(6);
+ });
it("binds a key to its company, task and actor across all statuses", async () => {
const input = await seed();
const receipt = await requestTaskRetry(input);
diff --git a/server/src/services/workspace-recovery-receipt.ts b/server/src/services/workspace-recovery-receipt.ts
index f0dda4daff1..1126d87aa97 100644
--- a/server/src/services/workspace-recovery-receipt.ts
+++ b/server/src/services/workspace-recovery-receipt.ts
@@ -5,6 +5,7 @@ import { z } from "zod";
import { readNativeWorkspaceSyncReference, type NativeWorkspaceSyncReference } from "./native-runtime/native-workspace-sync.js";
import { readMigratedLegacyWorkspaceSource } from "./legacy-workspace-recovery-migration.js";
import { readSnapshot } from "./workspace-recovery-snapshot.js";
+import { exhaustedSystemRecoveryAction, readSystemRecovery } from "./system-recovery-state.js";
export const workspaceRecoverySchema = z.object({
schema: z.literal("paperclip.workspace-recovery.v1"),
@@ -58,10 +59,17 @@ export function workspaceRecoveryDisplay(evidence: Record, runI
canRetry: state.status === "blocked" && state.retryable === true,
message: state.status === "queued" || state.status === "recovering" ? "Recovering saved work…"
: state.status === "recovered" ? "Saved work recovered. Send a message to continue."
- : state.message ?? "Paperclip couldn’t safely recover this task. This task needs service attention.",
+ : blockedWorkspaceRecoveryMessage(evidence) ?? state.message ?? "Recovery of this task's saved work has not finished.",
};
}
+/** Text saved by an older release can name a manual step. A spent budget is
+ * described from its current state instead of the stored text. */
+export function blockedWorkspaceRecoveryMessage(evidence: Record | null | undefined): string | null {
+ const system = readSystemRecovery(evidence ?? undefined);
+ return system?.state === "exhausted" ? exhaustedSystemRecoveryAction(system) : null;
+}
+
async function verifiedNativeCopybackReceipt(db: Db, input: {
companyId: string; issueId: string; runId: string; reference: NativeWorkspaceSyncReference;
}) {
diff --git a/server/src/services/workspace-recovery-retry-copyback.test.ts b/server/src/services/workspace-recovery-retry-copyback.test.ts
index 101ae89912b..cb0a5895304 100644
--- a/server/src/services/workspace-recovery-retry-copyback.test.ts
+++ b/server/src/services/workspace-recovery-retry-copyback.test.ts
@@ -508,7 +508,7 @@ describe("automatic retained workspace recovery", () => {
const stable = (row: typeof after) => ({ ...row, updatedAt: null, ownerType: null, nextAction: null,
evidence: { ...row.evidence, workspaceRecovery: { ...(row.evidence.workspaceRecovery as object), message: null } } });
if (spent) {
- expect(after).toMatchObject({ ownerType: "board", nextAction: expect.stringMatching(/Retry recovery/) });
+ expect(after).toMatchObject({ ownerType: "board", nextAction: expect.stringMatching(/Retry to try again/) });
expect(stable(after)).toEqual(stable(before));
} else expect(after).toEqual(before);
expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.lease.id)))[0].leasePolicy).toBe("reuse_by_environment");
diff --git a/server/src/services/workspace-recovery-warm-handoff.test.ts b/server/src/services/workspace-recovery-warm-handoff.test.ts
index eb4b7e51706..bfe5a9c1534 100644
--- a/server/src/services/workspace-recovery-warm-handoff.test.ts
+++ b/server/src/services/workspace-recovery-warm-handoff.test.ts
@@ -474,7 +474,7 @@ describe("automatic retained workspace recovery", () => {
expect(exhausted.nextAction).toMatch(/stopped after 6 attempts/);
const blocker = await getExecutionBlocker(db, f.companyId, f.issueId);
expect(blocker?.workspaceRecovery).toMatchObject({ status: "blocked", canRetry: true });
- expect(blocker?.nextAction).toMatch(/Retry recovery/);
+ expect(blocker?.nextAction).toMatch(/Retry to try again/);
expect(blocker?.nextAction).not.toMatch(/send a (new )?message/i);
// Nothing physical or provider-facing ran after the budget was spent.
expect(f.runtime.resumeRunLease).not.toHaveBeenCalled();
@@ -501,7 +501,7 @@ describe("automatic retained workspace recovery", () => {
const handed = await action(f.actionId);
expect(handed).toMatchObject({ status: "active", ownerType: "board" });
expect(readSystemRecovery(handed.evidence)).toEqual(spent);
- expect((await getExecutionBlocker(db, f.companyId, f.issueId))?.nextAction).toMatch(/Retry recovery/);
+ expect((await getExecutionBlocker(db, f.companyId, f.issueId))?.nextAction).toMatch(/Retry to try again/);
expect(f.runtime.resumeRunLease).not.toHaveBeenCalled();
// Repeat sweeps are idempotent and still grant no attempt.
await recoverRetainedWorkspace(f.input);
diff --git a/ui/src/components/RunWorkspaceSourceInspection.tsx b/ui/src/components/RunWorkspaceSourceInspection.tsx
index 0ba5812fd62..c9347a633dd 100644
--- a/ui/src/components/RunWorkspaceSourceInspection.tsx
+++ b/ui/src/components/RunWorkspaceSourceInspection.tsx
@@ -51,7 +51,7 @@ export function RunWorkspaceSourceInspection({ issueId, runId, companyId }: { is
Action {current.actionId}
This read-only observation checks recorded identity. It does not confirm provider termination, local files, or successful preservation.
{current.status === "verified" ?
Recorded-source identity verified.
- : current.status === "not_inspected" ?
Source not inspected: this record exceeds the inspection limit. Service attention is required.
+ : current.status === "not_inspected" ?
Source not inspected: this record exceeds the inspection limit.
diff --git a/ui/src/components/WorkspaceExportRecovery.control.test.tsx b/ui/src/components/WorkspaceExportRecovery.control.test.tsx
index 0a10fc87c7f..49ef3c4cb01 100644
--- a/ui/src/components/WorkspaceExportRecovery.control.test.tsx
+++ b/ui/src/components/WorkspaceExportRecovery.control.test.tsx
@@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { IssueRecoveryAction } from "@paperclipai/shared";
import { ApiError } from "../api/client";
import { queryKeys } from "../lib/queryKeys";
+import { writePendingSend } from "../lib/pending-send";
import { WorkspaceExportRecovery } from "./WorkspaceExportRecovery";
const api = vi.hoisted(() => ({ inspect: vi.fn(), recover: vi.fn(), resume: vi.fn() }));
@@ -153,7 +154,106 @@ describe("governed retained-file recovery", () => {
} });
await mount();
expect(button("Recover saved files")).toBeUndefined();
- expect(container.textContent).toContain("source is unavailable or has changed");
+ expect(container.textContent).toContain("can’t verify the saved files’ recorded source (source_binding_invalid)");
+ });
+
+ // Recovery saved by an older release: a board-owned hold whose
+ // sandbox predates ownership receipts. The server still records a retryable
+ // blocked recovery, but the read-only source probe cannot verify ownership.
+ const legacyHold = { ...action, id: "legacy-hold", ownerType: "board", evidence: { runId: "run-1",
+ workspaceRecovery: { schema: "paperclip.workspace-recovery.v1", runId: "run-1", stage: "verifying_stop",
+ status: "blocked", attempt: 1, attemptLimit: 6, requestIds: [], retryable: true,
+ message: "Automatic recovery of saved work stopped after 1 attempts (last failure: allocation_ownership_ambiguous)." },
+ systemRecovery: { schema: "paperclip.system-recovery.v1", phase: "verify_execution", state: "exhausted", revision: 5,
+ sourceRunId: "run-1", attempts: 1, retriesUsed: 0, preservationOperationIds: [], freshAttemptRunId: null,
+ failure: { code: "allocation_ownership_ambiguous", retryClass: "service_required" } },
+ originalFailureCode: "native_workspace_sync_out_failed", workspaceFinalizeAttempt: 3, previousWorkspaceRecovery: null },
+ } as unknown as IssueRecoveryAction;
+ const blockedInspection = (value: IssueRecoveryAction, failureCode = "allocation_ownership_ambiguous") => ({
+ active: value, actions: [value], sourceInspection: { schema: "paperclip.workspace-source-inspection.v1",
+ actionId: value.id, runId: "run-1", status: "blocked", failureCode,
+ scope: "recorded_source_identity", observedAt: "2026-11-07T14:44:46Z" } });
+
+ it("hands the next action to the task Retry for an old-release hold whose source cannot be verified", async () => {
+ api.inspect.mockResolvedValue(blockedInspection(legacyHold));
+ const owns = vi.fn();
+ await act(async () => root.render(
+
+ ));
+ await settle();
+ expect(owns).toHaveBeenLastCalledWith(false);
+ expect(button("Recover saved files")).toBeUndefined();
+ // No dead-end: no "changed, refresh" alert and no status check that can only repeat it.
+ expect(button("Check file recovery status")).toBeUndefined();
+ expect(container.textContent).not.toContain("has changed");
+ expect(container.textContent).toContain("can’t confirm that this run alone used the sandbox");
+ expect(api.recover).not.toHaveBeenCalled();
+ });
+
+ it("does not request recovery when the source stops verifying between render and click", async () => {
+ api.inspect.mockResolvedValueOnce(inspection()).mockResolvedValueOnce({ ...inspection(), sourceInspection: {
+ ...inspection().sourceInspection, status: "blocked", failureCode: "allocation_ownership_ambiguous" } });
+ await mount();
+ await click("Recover saved files");
+ expect(api.recover).not.toHaveBeenCalled();
+ expect(container.textContent).toContain("can’t confirm that this run alone used the sandbox");
+ expect(container.textContent).not.toContain("File recovery changed");
+ expect(button("Recover saved files")).toBeUndefined();
+ });
+
+ it("keeps naming the unverified source after an accepted request failed", async () => {
+ const key = "accepted-request";
+ writePendingSend("workspace-file-recovery:company-1:issue-1:legacy-hold:run-1:board-1",
+ { idempotencyKey: key, payload: { actionId: "legacy-hold", runId: "run-1" }, createdAt: Date.now() });
+ const failed = { ...legacyHold, evidence: { ...legacyHold.evidence, workspaceRecovery: {
+ ...(legacyHold.evidence.workspaceRecovery as object), requestIds: [key] } } } as IssueRecoveryAction;
+ api.inspect.mockResolvedValue(blockedInspection(failed));
+ await mount(failed);
+ expect(container.textContent).toContain("File recovery has not finished");
+ expect(container.textContent).toContain("can’t confirm that this run alone used the sandbox");
+ // While recovery is running, the panel shows progress instead of the reason.
+ const running = { ...failed, evidence: { ...failed.evidence, workspaceRecovery: {
+ ...(failed.evidence.workspaceRecovery as object), status: "recovering" } } } as IssueRecoveryAction;
+ api.inspect.mockResolvedValue(blockedInspection(running));
+ await act(async () => client.invalidateQueries({ queryKey: queryKeys.issues.recoveryActions("issue-1", "legacy-hold", "run-1") }));
+ await settle();
+ expect(container.textContent).toContain("Recovering saved files");
+ expect(container.textContent).not.toContain("can’t confirm that this run alone used the sandbox");
+ expect(api.recover).not.toHaveBeenCalled();
+ });
+
+ it("keeps ownership of the next action while the source is verified", async () => {
+ const owns = vi.fn();
+ await act(async () => root.render(
+
+ ));
+ await settle();
+ expect(owns).toHaveBeenLastCalledWith(true);
+ expect(button("Recover saved files")).toBeDefined();
+ });
+
+ it("reports recovered files even when the source no longer matches after recovery", async () => {
+ // Preservation completed, so the workspace moved past the
+ // recorded source and inspection reports a reference mismatch.
+ const recovered = { ...legacyHold, ownerType: "system", evidence: { ...legacyHold.evidence,
+ workspaceRecovery: { ...(legacyHold.evidence.workspaceRecovery as object), status: "recovered" },
+ systemRecovery: { ...(legacyHold.evidence.systemRecovery as object), state: "complete",
+ preservationOperationIds: ["preservation-1"] } } } as IssueRecoveryAction;
+ api.inspect.mockResolvedValue(blockedInspection(recovered, "source_binding_invalid"));
+ await mount(recovered);
+ expect(container.textContent).toContain("Saved files recovered");
+ expect(container.textContent).not.toContain("need recovery");
+ expect(container.textContent).not.toContain("has changed");
+ expect(button("Recover saved files")).toBeUndefined();
+ });
+
+ it("reloads the task instead of looping when the recovery record was replaced", async () => {
+ api.inspect.mockResolvedValue({ active: null, actions: [], sourceInspection: undefined });
+ const invalidate = vi.spyOn(client, "invalidateQueries");
+ await mount(legacyHold);
+ await click("Check file recovery status");
+ expect(container.textContent).not.toContain("Refresh the task");
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: queryKeys.issues.detail("issue-1") });
});
it("persists the exact request before POST and prevents a double click", async () => {
@@ -288,6 +388,37 @@ describe("governed retained-file recovery", () => {
expect(api.recover).not.toHaveBeenCalled();
});
+ // Recovery is automatic. No recovery state may tell a person to fix or inspect
+ // a sandbox, or name an owner or administrator as the one who must act.
+ const manualCopy = /administrator|\bowner\b|operator assistance|service assistance|service attention|inspect the (run|failed run)|environment/i;
+ const withRecovery = (value: IssueRecoveryAction, patch: Record, system?: Record) => ({
+ ...value, evidence: { ...value.evidence, workspaceRecovery: { ...(value.evidence.workspaceRecovery as object), ...patch },
+ ...(system ? { systemRecovery: { ...(value.evidence.systemRecovery as object), ...system } } : {}) } }) as IssueRecoveryAction;
+ const operatorAccess = { userId: "board-1", companyIds: ["company-1"], source: "session", isInstanceAdmin: false,
+ memberships: [{ companyId: "company-1", membershipRole: "operator", status: "active" }] };
+ const viewerAccess = { ...operatorAccess, memberships: [{ companyId: "company-1", membershipRole: "viewer", status: "active" }] };
+ it.each([
+ ["verified and retryable", action, inspection(action), operatorAccess],
+ ["unverified ownership", legacyHold, blockedInspection(legacyHold), operatorAccess],
+ ["unverified binding", legacyHold, blockedInspection(legacyHold, "source_binding_invalid"), operatorAccess],
+ ["not inspected", legacyHold, { ...blockedInspection(legacyHold), sourceInspection: { ...blockedInspection(legacyHold).sourceInspection,
+ status: "not_inspected", reason: "source_limit" } }, operatorAccess],
+ ["queued", withRecovery(legacyHold, { status: "queued" }), blockedInspection(withRecovery(legacyHold, { status: "queued" })), operatorAccess],
+ ["not retryable", withRecovery(legacyHold, { retryable: false }), blockedInspection(withRecovery(legacyHold, { retryable: false })), operatorAccess],
+ ["recovered", withRecovery(legacyHold, { status: "recovered" }, { state: "complete", preservationOperationIds: ["op-1"] }),
+ blockedInspection(withRecovery(legacyHold, { status: "recovered" }, { state: "complete", preservationOperationIds: ["op-1"] })), operatorAccess],
+ ["viewer", legacyHold, blockedInspection(legacyHold), viewerAccess],
+ ["copyback owner hold for an operator", { ...action, evidence: { ...action.evidence,
+ workspaceOwnerRecovery: { state: "operator_required", owner: { token: "token" } } } } as IssueRecoveryAction, inspection(action), operatorAccess],
+ ["board-owned status", { ...action, cause: "native_workspace_finalization_owner_unverified", ownerType: "board",
+ evidence: { runId: "run-1" } } as unknown as IssueRecoveryAction, inspection(action), operatorAccess],
+ ] as const)("renders no manual sandbox or administrator copy: %s", async (_name, value, response, access) => {
+ client.setQueryData(queryKeys.access.currentBoardAccess, access);
+ api.inspect.mockResolvedValue(response);
+ await mount(value);
+ expect(container.textContent).not.toMatch(manualCopy);
+ });
+
describe("previous server stop confirmation", () => {
const ownerAction = { ...action, cause: "native_workspace_finalization_owner_unverified", ownerType: "board", status: "escalated",
evidence: { runId: "run-1", owner: { token: "owner-token", hostname: "secret-host", pid: 2 },
@@ -350,7 +481,7 @@ describe("governed retained-file recovery", () => {
companyIds: ["company-1"], memberships: [{ companyId: "company-1", membershipRole: "operator", status: "active" }] });
await mount(ownerAction);
expect(button("Confirm the previous server stopped")).toBeUndefined();
- expect(container.textContent).toContain("owner or administrator can confirm");
+ expect(container.textContent).toContain("waiting to confirm that the previous server stopped");
expect(api.resume).not.toHaveBeenCalled();
});
});
diff --git a/ui/src/components/WorkspaceExportRecovery.test.tsx b/ui/src/components/WorkspaceExportRecovery.test.tsx
index 28a2409d2f1..3c909c334b5 100644
--- a/ui/src/components/WorkspaceExportRecovery.test.tsx
+++ b/ui/src/components/WorkspaceExportRecovery.test.tsx
@@ -20,16 +20,16 @@ describe("WorkspaceExportRecovery", () => {
});
it("does not mistake platform identity for confirmed recovery", async () => {
await mount({ ...action, evidence: { ...action.evidence, owner: { ...(action.evidence.owner as object), worker: { provider: "railway", deploymentId: "old" } } } });
- expect(container.textContent).toContain("operator assistance");
+ expect(container.textContent).toContain("Saved work is not recovered yet");
});
it("states that an operator is needed for legacy receipts", async () => {
await mount(action);
- expect(container.textContent).toContain("Workspace recovery needs operator assistance");
+ expect(container.textContent).toContain("Saved work is not recovered yet");
});
it("keeps export repair out of the task", async () => {
const cause = "native_workspace_sync_out_retry_exhausted";
await mount({ ...action, cause });
- expect(container.textContent).toContain("operator assistance");
+ expect(container.textContent).toContain("Saved work is not recovered yet");
});
it("removes the status when recovery resolves, including updates in place", async () => {
await mount({ ...action, evidence: { ...action.evidence, workspaceOwnerStop: {} } });
diff --git a/ui/src/components/WorkspaceExportRecovery.tsx b/ui/src/components/WorkspaceExportRecovery.tsx
index bf48de41db2..e66e04707ad 100644
--- a/ui/src/components/WorkspaceExportRecovery.tsx
+++ b/ui/src/components/WorkspaceExportRecovery.tsx
@@ -1,6 +1,6 @@
-import { useRef, useState } from "react";
+import { useLayoutEffect, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import type { IssueRecoveryAction } from "@paperclipai/shared";
+import type { IssueRecoveryAction, WorkspaceSourceInspection } from "@paperclipai/shared";
import { isNativeWorkspaceExportRepairCause } from "@paperclipai/shared";
import { isTransientError } from "../api/errors";
import { useQueryView } from "./QueryView";
@@ -15,37 +15,53 @@ import { createUuid } from "../lib/uuid";
import { Button } from "./ui/button";
import { Textarea } from "./ui/textarea";
+/** Reports whether this surface owns the task's next recovery action. The task's
+ * generic Retry stays hidden only while this surface offers its own control. */
+function ReportRecoveryControl({ owns, onChange }: { owns: boolean; onChange?: (owns: boolean) => void }) {
+ useLayoutEffect(() => {
+ onChange?.(owns);
+ return () => onChange?.(false);
+ }, [owns, onChange]);
+ return null;
+}
+
/** Requests preservation; the existing worker owns stop, copyback and verification. */
-export function WorkspaceExportRecovery({ action, className, issueId, companyId, showStatus = true }: {
+export function WorkspaceExportRecovery({ action, className, issueId, companyId, showStatus = true, onRecoveryControlChange }: {
className?: string; action: IssueRecoveryAction | null; issueId?: string; companyId?: string; showStatus?: boolean;
+ onRecoveryControlChange?: (owns: boolean) => void;
}) {
// A restart killed the copyback owner of retained saved-work recovery. Recovery
// and any accepted Retry wait on its receipt; the confirmation is the one action.
const retainedOwnerToken = action && issueId && companyId && isRetainedExport(action, issueId, companyId)
? retainedOwnerStopToken(action) : null;
if (action && issueId && companyId && retainedOwnerToken) {
- return ;
+ return <>
+ >;
}
if (action && issueId && companyId && isRetainedExport(action, issueId, companyId)) {
return ;
+ action={action} issueId={issueId} companyId={companyId} className={className}
+ onRecoveryControlChange={onRecoveryControlChange} />;
}
const ownerRecovery = action?.cause === "native_workspace_finalization_owner_unverified";
// The task's interruption names this wait; the confirmation is its one action.
if (ownerRecovery && issueId && companyId && isOwnerStopRequired(action, issueId, companyId)) {
- return ;
+ return <>
+ >;
}
- if (!showStatus) return null;
+ if (!showStatus) return ;
if (!action || (!ownerRecovery && !isNativeWorkspaceExportRepairCause(action.cause)) || action.ownerType !== "board"
- || !["active", "escalated"].includes(action.status) || typeof action.evidence.runId !== "string") return null;
+ || !["active", "escalated"].includes(action.status) || typeof action.evidence.runId !== "string")
+ return ;
const queued = !!action.evidence.workspaceOwnerStop || action.wakePolicy?.kind === "resume_native_run";
const automatic = queued || (ownerRecovery && asObject(action.evidence.workspaceOwnerRecovery).state === "resuming");
- return
- {automatic ? "Restoring saved work…" : "Workspace recovery needs operator assistance. The agent’s result is saved."}
-
;
+ return <>
+
+ {automatic ? "Restoring saved work…" : "Saved work is not recovered yet. The agent’s result is saved."}
+
>;
}
function isRetainedExport(action: IssueRecoveryAction, issueId: string, companyId: string) {
@@ -99,7 +115,7 @@ function PreviousServerStopConfirmation({ action, ownerToken, issueId, companyId
: "The previous server stopped while it was saving this task’s files, and Paperclip can’t verify that it stopped. The agent’s result is saved."}
{confirm.isSuccess ? null : !canConfirm
?
{accessView.kind === "loading" || accessView.kind === "reconnecting"
- ? "Checking access…" : "A company owner or administrator can confirm that the previous server stopped."}
+ ? "Checking access…" : "Paperclip is waiting to confirm that the previous server stopped."}
: !open ?
: