Files
PaperClipAI/server/src/services/heartbeat/environment-selection.ts
T
DottaandPaperclip cc5136ca02 fix(workspaces): run projectless isolated tasks and chats without a repo (#22972)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Execution workspace isolation controls how each task and
conversation gets a working directory
> - When isolated workspaces are enabled (including with
`enableIsolatedWorkspacesByDefault`), a task or conversation without a
project or repository can resolve to `isolated_workspace` without an
explicit `workspaceStrategy`
> - Wakeup preflight synthesized the default `git_worktree` strategy and
blocked projectless tasks with `workspace_worktree_requires_project`,
while `shouldUseIsolatedTaskDirectory` only allowed `low_trust_review` +
`sandbox` and failed standard local, sandbox, and plugin runs with
`git_worktree_base_not_git_checkout` or
`plugin_workspace_strategy_unsupported`
> - This pull request admits repository-free isolated tasks and
conversations into private isolated task directories across local,
sandbox, and plugin environments while preserving explicit Git worktree
validation, SSH preflight blocking, cross-task archived-workspace
protection, and low-trust sandbox containment
> - The benefit is that projectless tasks, projectless agent chats, and
repository-free project tasks run cleanly with persistent isolated
directories across turns, without weakening Git worktree isolation for
repository-backed projects

## Linked Issues or Issue Description

Fixes: #20962

Refs #20963, #19860, #14766, #13636

Relationship to #20963: #20963 enables private task directories for
standard local repository-free tasks and guards
`hasSelectedExecutionWorkspace`. This pull request builds on that
direction by also:
- Allowing repository-free isolated tasks without an explicit
`workspaceStrategy` to pass wakeup preflight in
`server/src/services/heartbeat/queue.ts` via the canonical
`shouldUseIsolatedTaskDirectory` predicate with resolved trust preset
and environment driver (otherwise projectless tasks and chats with
`mode: "isolated_workspace"` are blocked with
`workspace_worktree_requires_project` before environment selection runs,
while SSH, explicit `git_worktree`, and cross-task/shared archived
bindings remain blocked pre-dispatch).
- Supporting standard `sandbox` (Paperclip Cloud) and `plugin`
environments in `shouldUseIsolatedTaskDirectory` (including multi-turn
ordinary plugin task directory reuse via `isBoundPluginTaskDirectory`),
not only `local` / `null`.
- Scoping `!hasSelectedExecutionWorkspace` strictly to `trustPreset ===
"standard"` so `low_trust_review` sandbox containment remains unchanged.
- Preserving `nativeChatWorkspaceScope` isolation (zero referenced
project roots) in `workspace-preparation.ts` when an external chat also
uses a private task directory.

## What Changed

- `server/src/services/isolated-task-directory.ts`: Extract
`hasExplicitWorkspaceStrategy`, add a `standard`-scoped
`hasSelectedExecutionWorkspace` guard, and allow
`shouldUseIsolatedTaskDirectory` for `standard` trust on `local`,
`sandbox`, `plugin`, and `null` drivers while keeping `low_trust_review`
sandbox containment unchanged and keeping `ssh`, `denied`, selected
standard workspaces, and explicit strategies excluded.
- `server/src/services/provider-fresh-workspace.ts`: Add
`isBoundPluginTaskDirectory` recognizing both fresh plugin attempt
directories and ordinary task-owned plugin directories
(`/workspaces/<issueId>` with matching `runnerTaskWorkspaceOwner`,
`projectWorkspaceId === null`, and no `runnerTaskFreshWorkspace`) so
multi-turn repository-free plugin tasks reuse their bound workspace
without hitting `plugin_workspace_strategy_unsupported`.
- `server/src/services/heartbeat/queue.ts`: Call the canonical
`shouldUseIsolatedTaskDirectory` during wakeup preflight with resolved
`trustPreset` (`resolveCoreTrustPreset`) and effective
`environmentDriver` (honoring `executionWorkspaceSettings.environmentId`
for `low_trust_review`, `executionMode === "kubernetes"`, and
`enableManagedSandboxOnly`, and allowing verified exclusively task-owned
archived/cleanup_failed task directories matching
`readTaskDirectoryRetention` or `issue_terminal` cleanup while blocking
cross-task/shared archived bindings) to resolve
`effectivePreflightStrategy` to `"project_primary"` instead of adding a
bypass flag on `isUnrunnableWorktreeCombo`.
- `server/src/services/heartbeat/environment-selection.ts`: Use
`isBoundPluginTaskDirectory` for bound plugin task directory reuse and
pass `hasSelectedExecutionWorkspace` into
`shouldUseIsolatedTaskDirectory` so existing or tampered standard
workspace bindings still go through binding validation.
- `server/src/services/heartbeat/workspace-preparation.ts`: Force
`project_primary` strategy for host and plugin preparation when
`useIsolatedTaskDirectory` is active (outside `remoteAuthority`), and
keep projectless `nativeChatWorkspaceScope` runs on the external-chat
directory branch so referenced projects are not attached.
- `doc/experimental/issue-worktree-support.md`: Document private
isolated task directory behavior for repository-free isolated tasks and
conversations.
- Tests: Extend `isolated-task-directory.test.ts`,
`provider-fresh-workspace.test.ts`, `workspace-preparation.test.ts`, and
`heartbeat-workspace-source-trust.test.ts` with unit and
embedded-Postgres E2E coverage across local, sandbox, plugin, and SSH
environments (projectless tasks, projectless chats, repo-free projects,
2-turn local/sandbox/plugin workspace reuse, git-backed project
`git_worktree` regression, explicit projectless `git_worktree` block,
SSH pre-dispatch block, low-trust projectless sandbox on SSH-default
agent, cross-task archived workspace blocking, and exclusively
task-owned archived directory reopening).

## Verification

- `pnpm exec vitest run
server/src/services/isolated-task-directory.test.ts
server/src/services/provider-fresh-workspace.test.ts
server/src/__tests__/execution-workspace-policy.test.ts` — 3 files, 101
passed (101).
- `pnpm exec vitest run
server/src/services/heartbeat/workspace-preparation.test.ts -t "prepares
a repository-free local task directory|reuses a bound ordinary
repository-free plugin task directory|names incompatible Core project
storage"` — 3 passed (including 2-turn ordinary plugin task directory
reuse + explicit `git_worktree` rejection).
- `pnpm exec vitest run
server/src/__tests__/heartbeat-workspace-source-trust.test.ts -t "in a
company with no repository|still uses git_worktree"` — 9 passed with
embedded Postgres (projectless tasks, projectless chats, repo-free
projects on local and sandbox, git-backed project `git_worktree`,
explicit projectless `git_worktree` block, SSH pre-dispatch block,
low-trust projectless sandbox on SSH-default agent, cross-task archived
workspace pre-dispatch block, and own archived isolated task directory
reopening).
- `pnpm exec vitest run
server/src/__tests__/heartbeat-workspace-branch-containment.test.ts -t
"blocks projectless isolated git-worktree issues before dispatch"` — 1
passed.
- `pnpm --filter @paperclipai/server typecheck` — passed (0 errors
across all 7 layers).
- `node scripts/check-test-budget.mjs --files
server/src/services/isolated-task-directory.test.ts
server/src/services/provider-fresh-workspace.test.ts
server/src/services/heartbeat/workspace-preparation.test.ts
server/src/__tests__/heartbeat-workspace-source-trust.test.ts` — PASS
(110 nightly suites validated, 4 test files checked).
- `git diff --check` — clean; no secrets, artifacts, or internal IDs.
- Sharded PR CI on `eb2b11ee9b`: **66/66** executed checks `SUCCESS` (0
failing, 0 pending, 7 skipped, 2 non-blocking neutral Paperclip Review),
including `ci / verify`, `ci / e2e` + all 16 E2E shards, all 20 General
server shards + chat + workspaces-b, all 9 Serialized server shards, all
Verify Paperclip Runner lanes, `Build`, `Typecheck + Release Registry`,
`policy`, `Superagent Security Scan`, `Socket Security`, `Contributor
trust`, `commitperclip`, `Snyk`, and `Greptile Review` (5/5).

## Risks

- Repository-free tasks and conversations with `mode:
"isolated_workspace"` and no explicit `workspaceStrategy` now run in
private task directories under
`<instanceRoot>/isolated-workspaces/<companyId>/<issueId>` (or
`/workspaces/<issueId>` on plugin environments / remote empty workspaces
under `remoteAuthority`) instead of failing preflight or Git checkout
validation.
- Explicit `workspaceStrategy` requirements (including `git_worktree`,
`existingBranch`, and `provisionCommand`), SSH pre-dispatch blocking,
cross-task archived workspace blocking, low-trust sandbox confinement,
tampered-binding checks (`hasSelectedExecutionWorkspace`), and
`git_worktree` isolation for git-backed projects remain unchanged.
- No database migrations, schema changes, or API contract changes.

## Model Used

- Claude Opus 4.6 (`claude-opus-4-6`) in Antigravity with tool use,
shell execution, and extended thinking.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-25 15:32:12 -06:00

599 lines
33 KiB
TypeScript

import { assertProviderApiPlacementPolicy, resolveProviderApiPlacement } from "../native-runtime/provider-api-placement.js";
import { heartbeatExternalProvider, nativeExecutionUsesTaskWorkspace } from "./external-provider.js";
import { heartbeatRuns, issues, type Db, type agents } from "@paperclipai/db";
import { and, eq } from "drizzle-orm";
import { readGitCacheExpiration } from "../git-workspace-restoration.js";
import { readRemoteWorkspaceAuthority, type ExecutionWorkspace, type InstanceSettings, type IssueExecutionWorkspaceSettings, type ProjectExecutionWorkspacePolicy } from "@paperclipai/shared";
import { parseObject } from "../../adapters/utils.js";
import { logger } from "../../middleware/logger.js";
import { parseNativeExecutionInput } from "../../vendor/paperclip-runner/index.js";
import { isExecutionForcedToKubernetes } from "../execution-allowlist.js";
import { parseExecutionPolicyBootstrapEnv } from "../execution-policy-bootstrap.js";
import {
parseIssueExecutionWorkspaceSettings,
resolveEffectiveWorkspaceStrategyType,
resolveExecutionWorkspaceEnvironmentId,
resolveExecutionWorkspaceMode,
resolveSharedWorkspaceConcurrency,
type ParsedExecutionWorkspaceMode,
} from "../execution-workspace-policy.js";
import { assertTaskWorkspaceExecutionAccess, assertTaskWorkspaceSourceProjectAccess } from "../task-workspace-access.js";
import { isBoundIsolatedTaskDirectory, shouldUseIsolatedTaskDirectory } from "../isolated-task-directory.js";
import { readTaskDirectoryRetention } from "../isolated-task-directory-retention.js";
import { isBoundPluginTaskDirectory } from "../provider-fresh-workspace.js";
import {
findNativeChatWorkspaceScope,
nativeChatWorkspaceCwd,
nativeChatWorkspaceMatches,
} from "../native-runtime/native-chat-workspace.js";
import { readNativeWorkspaceSyncReference } from "../native-runtime/native-workspace-sync.js";
import { NativeRunnerOwnershipUnverifiedError } from "../native-runtime/native-runner-ownership.js";
import type { environmentService } from "../environments.js";
import type { executionWorkspaceService } from "../execution-workspaces.js";
import type { instanceSettingsService } from "../instance-settings.js";
import type { TrustPresetResolution } from "../trust-preset-resolver.js";
import { WORKSPACE_BUSY_RETRY_REASON } from "../../modules/run-dispatch/index.js";
import { WorkspaceBusyDeferral, type createHeartbeatRetries } from "./retries.js";
import { ConfigurationIncompleteFailure } from "./run-preparation.js";
import { resolveNativeRecoveryExecutionWorkspaceBinding, resolveExecutionWorkspaceReuseRequestForIssue, WorkspaceValidationFailure } from "./workspaces.js";
type Issue = typeof issues.$inferSelect;
function gitCacheExpirationRemovedWorkspace(workspace: Parameters<typeof readGitCacheExpiration>[0]) {
if (!readRemoteWorkspaceAuthority(workspace.metadata)) return readGitCacheExpiration(workspace)?.workspaceRemoved === true;
const expiration = parseObject(workspace.metadata?.gitCacheExpiration);
return expiration.schema === "paperclip.git-cache-expiration.v1" && expiration.workspaceRemoved === true
&& Number.isSafeInteger(expiration.generation) && expiration.generation === workspace.metadata?.lifecycleGeneration;
}
export async function resolveSshAuthenticationBeforeRouting(input: {
agentDefaultEnvironmentId: string | null;
lowTrustIssueEnvironmentId: string | null;
environmentsSvc: Pick<ReturnType<typeof environmentService>, "getById">;
instanceSettings: { get(): Promise<{
defaultEnvironmentId: InstanceSettings["defaultEnvironmentId"];
general: Pick<InstanceSettings["general"], "executionMode">;
}> };
}): Promise<"host" | "managed" | null> {
const settings = await input.instanceSettings.get();
if (isExecutionForcedToKubernetes({ executionMode: settings.general.executionMode })) return null;
const id = input.lowTrustIssueEnvironmentId ?? input.agentDefaultEnvironmentId ?? settings.defaultEnvironmentId;
if (!id) return null;
const environment = await input.environmentsSvc.getById(id);
return environment?.driver === "ssh" ? environment.config.useHostAuth === false ? "managed" : "host" : null;
}
/** Selects policy and reuse inputs; lease acquisition and cleanup belong to the executor. */
export interface HeartbeatEnvironmentSelectionInput {
run: Pick<typeof heartbeatRuns.$inferSelect,
"id" | "runtimeMode" | "runnerProfileJson" | "scheduledRetryReason" | "scheduledRetryAttempt"> & { contextSnapshot?: Record<string, unknown> | null };
agent: Pick<typeof agents.$inferSelect,
"id" | "companyId" | "adapterType" | "adapterConfig" | "defaultEnvironmentId">;
task: {
freshWorkspace?: import("../fresh-workspace-continuation.js").ContinuationReadiness | null;
issueRef: Pick<Issue, "id" | "projectWorkspaceId" | "executionWorkspaceId" | "executionWorkspacePreference"> | null;
issueContext: Pick<Issue, "assigneeAgentId" | "executionWorkspaceSettings"> | null;
issueId: string | null;
context: Record<string, unknown>;
executionProjectId: string | null;
workspaceProjectContext: { hasWorkspace: boolean } | null;
boundSourceWorkspace: ExecutionWorkspace | null;
hasSelectedWorkspaceSource: boolean;
taskWorkspaceIntent: Issue["workspaceSelection"];
responsibleUserId: string | null;
};
policy: {
trustPreset: TrustPresetResolution;
requestedExecutionWorkspaceMode: ParsedExecutionWorkspaceMode;
isolatedWorkspacesEnabled: boolean;
projectExecutionWorkspacePolicy: ProjectExecutionWorkspacePolicy | null;
issueExecutionWorkspaceSettings: IssueExecutionWorkspaceSettings | null;
};
config: {
config: Record<string, unknown>;
sourceWorkspaceConfig: Record<string, unknown>;
issueAssigneeOverrides: { adapterConfig: Record<string, unknown> | null } | null;
};
services: {
executionWorkspacesSvc: Pick<ReturnType<typeof executionWorkspaceService>, "getStoredById" | "validateStoredSelectionForRun"
| "reopenClosedIsolatedExecutionWorkspaceForIssue" | "clearReopenPendingConsumptionForUnconsumedReopen">;
environmentsSvc: Pick<ReturnType<typeof environmentService>,
"ensureLocalEnvironment" | "findManagedSandboxEnvironment" | "findKubernetesEnvironment" | "ensureKubernetesEnvironment" | "getById" | "getLeaseById">;
instanceSettings: Pick<ReturnType<typeof instanceSettingsService>, "get" | "getExperimental">;
findSharedWorkspaceHolder: ReturnType<typeof createHeartbeatRetries>["findSharedWorkspaceHolder"];
findExecutionWorkspaceHolder: ReturnType<typeof createHeartbeatRetries>["findExecutionWorkspaceHolder"];
};
}
function readNonEmptyString(value: unknown): string | null {
return typeof value === "string" && value.trim().length > 0 ? value : null;
}
export async function selectHeartbeatEnvironment(db: Db, input: HeartbeatEnvironmentSelectionInput) {
const { run, agent } = input;
const { issueRef, issueContext, issueId, context, executionProjectId, workspaceProjectContext, boundSourceWorkspace, hasSelectedWorkspaceSource, taskWorkspaceIntent, responsibleUserId } = input.task;
const {
trustPreset, requestedExecutionWorkspaceMode, isolatedWorkspacesEnabled: runtimeWorkspaceSelectionEnabled,
projectExecutionWorkspacePolicy, issueExecutionWorkspaceSettings,
} = input.policy;
const { config, sourceWorkspaceConfig, issueAssigneeOverrides } = input.config;
const { executionWorkspacesSvc, environmentsSvc, instanceSettings, findSharedWorkspaceHolder, findExecutionWorkspaceHolder } = input.services;
// A native run's execution input is immutable once persisted. Recovery must therefore
// restore the workspace bound to that input rather than consulting the issue's current
// workspace pointer: a newer run may already have moved or cleared the issue binding while
// this older provider session is still recoverable.
const persistedRunnerProfile = parseObject(run.runnerProfileJson);
const persistedNativeExecutionInput =
run.runtimeMode === "native" &&
persistedRunnerProfile.nativeExecutionInput !== undefined
? parseNativeExecutionInput(
persistedRunnerProfile.nativeExecutionInput,
)
: null;
// This retained name covers both external bridges; neither adopts task files.
const isDotRun = heartbeatExternalProvider({ run, agent }) !== null;
const providerApiPlacement = resolveProviderApiPlacement({ run, agent });
const controllerOnly = isDotRun || providerApiPlacement !== null;
const persistedNativeExecutionWorkspaceId =
providerApiPlacement ? null : persistedNativeExecutionInput?.binding.executionWorkspaceId ?? null;
const fresh = input.task.freshWorkspace?.mode === "fresh_isolated_workspace";
const requestedExecutionWorkspaceId = controllerOnly ? null :
persistedNativeExecutionWorkspaceId ??
readNonEmptyString(issueRef?.executionWorkspaceId);
let existingExecutionWorkspace = requestedExecutionWorkspaceId
? await executionWorkspacesSvc.getStoredById(agent.companyId, requestedExecutionWorkspaceId)
: null;
if (existingExecutionWorkspace && issueId && !controllerOnly && !fresh
&& existingExecutionWorkspace.id === readNonEmptyString(issueRef?.executionWorkspaceId)
&& (existingExecutionWorkspace.status === "archived" || existingExecutionWorkspace.status === "cleanup_failed")
&& (gitCacheExpirationRemovedWorkspace(existingExecutionWorkspace as Parameters<typeof readGitCacheExpiration>[0])
|| readTaskDirectoryRetention(existingExecutionWorkspace) !== null
|| (existingExecutionWorkspace.sourceIssueId === issueId
&& existingExecutionWorkspace.cleanupReason?.startsWith("issue_terminal") === true))) {
const [boundIssue] = await db.select({ id: issues.id, companyId: issues.companyId, projectId: issues.projectId })
.from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, agent.companyId)));
if (!boundIssue) throw new Error("Execution workspace issue is unavailable");
const actor = { agentId: agent.id, actorType: "agent" };
const reopened = await executionWorkspacesSvc.reopenClosedIsolatedExecutionWorkspaceForIssue({
workspaceId: existingExecutionWorkspace.id,
issue: boundIssue,
actor,
authorizationActor: { type: "agent", agentId: agent.id, companyId: agent.companyId, source: "agent_jwt", runId: run.id,
onBehalfOfUserId: responsibleUserId === "local-board" ? null : responsibleUserId },
});
if (!reopened.ok) throw new Error(reopened.message);
if (reopened.reopened) {
await executionWorkspacesSvc.clearReopenPendingConsumptionForUnconsumedReopen({
workspaceId: existingExecutionWorkspace.id, issue: boundIssue, actor, expectedGeneration: reopened.generation,
});
}
existingExecutionWorkspace = await executionWorkspacesSvc.getStoredById(agent.companyId, existingExecutionWorkspace.id);
}
const retainedDirectory = input.task.freshWorkspace?.mode === "reuse_current_workspace" ? input.task.freshWorkspace : null;
const retainedWorkspace = input.task.freshWorkspace?.mode === "resume_stopped_native_workspace"
|| input.task.freshWorkspace?.mode === "reuse_issue_workspace" ? input.task.freshWorkspace : retainedDirectory;
if (retainedWorkspace && (issueRef?.executionWorkspaceId !== retainedWorkspace.workspaceId ||
existingExecutionWorkspace?.id !== retainedWorkspace.workspaceId || existingExecutionWorkspace.cwd !== retainedWorkspace.cwd)) {
throw new WorkspaceValidationFailure("The saved Retry workspace binding changed.", {
workspaceValidation: { reason: retainedDirectory ? "isolated_task_directory_binding_mismatch"
: retainedWorkspace.mode === "reuse_issue_workspace" ? "retry_workspace_binding_mismatch" : "stopped_native_workspace_binding_mismatch", issueId },
});
}
const nativeRecoveryExecutionWorkspaceId =
resolveNativeRecoveryExecutionWorkspaceBinding({
bindingId: persistedNativeExecutionWorkspaceId,
persistedWorkspaceFound: existingExecutionWorkspace !== null,
});
const workspaceReuseRequest =
resolveExecutionWorkspaceReuseRequestForIssue({
issueExecutionWorkspaceId: requestedExecutionWorkspaceId,
issueExecutionWorkspacePreference: controllerOnly ? null : nativeRecoveryExecutionWorkspaceId || retainedWorkspace
? "reuse_existing"
: (issueRef?.executionWorkspacePreference ?? null),
existingExecutionWorkspaceStatus:
existingExecutionWorkspace?.status ?? null,
});
const requestedShouldReuseExisting =
workspaceReuseRequest.requestedShouldReuseExisting;
const reusableExistingExecutionWorkspace =
workspaceReuseRequest.existingExecutionWorkspaceAvailable
? existingExecutionWorkspace
: null;
const workspaceAuthorizationActor = { type: "agent" as const, agentId: agent.id, companyId: agent.companyId,
source: "agent_jwt" as const, runId: run.id, onBehalfOfUserId: responsibleUserId === "local-board" ? null : responsibleUserId };
if (!controllerOnly && !persistedNativeExecutionInput && !nativeRecoveryExecutionWorkspaceId) {
const workspaceRequiringAccess = reusableExistingExecutionWorkspace ?? boundSourceWorkspace;
if (workspaceRequiringAccess && issueId) {
await assertTaskWorkspaceExecutionAccess(db, workspaceAuthorizationActor, agent.companyId, { issueId, workspaceId: workspaceRequiringAccess.id });
} else if (!controllerOnly && executionProjectId && (hasSelectedWorkspaceSource || workspaceProjectContext?.hasWorkspace)) {
await assertTaskWorkspaceSourceProjectAccess(db, workspaceAuthorizationActor, agent.companyId, executionProjectId);
}
}
const requestedReusableExecutionWorkspaceConfig =
reusableExistingExecutionWorkspace?.config ?? null;
const localEnvironment = await environmentsSvc.ensureLocalEnvironment(
agent.companyId,
);
const resolvedInstanceSettings = await instanceSettings.get();
// Managed-sandbox-only policy: a run that would land on the local
// environment is redirected onto the platform-managed sandbox row, and
// with no active managed row the resolution fails closed
// (ManagedSandboxUnavailableError) — never local. Mirrors the forced
// kubernetes execution mode below, which takes precedence when both
// regimes are active.
const managedSandboxOnly =
(await instanceSettings.getExperimental()).enableManagedSandboxOnly ===
true;
const managedSandboxEnvironment = managedSandboxOnly && !providerApiPlacement
? await environmentsSvc.findManagedSandboxEnvironment(agent.companyId)
: null;
const savedEnvironment = parseObject(parseObject(run.contextSnapshot).paperclipEnvironment);
const admittedLeaseId = persistedNativeExecutionInput && !controllerOnly
? readNonEmptyString(savedEnvironment.leaseId) ?? readNativeWorkspaceSyncReference(persistedRunnerProfile.nativeWorkspaceSync)?.leaseId
: null;
const admittedLease = admittedLeaseId ? await environmentsSvc.getLeaseById(admittedLeaseId) : null;
if (admittedLeaseId && (!admittedLease?.environmentId || admittedLease.companyId !== agent.companyId
|| admittedLease.heartbeatRunId !== run.id || admittedLease.issueId !== issueId || admittedLease.metadata?.agentId !== agent.id
|| (typeof savedEnvironment.id === "string" && savedEnvironment.id !== admittedLease.environmentId))) {
throw new ConfigurationIncompleteFailure("Cannot restore the admitted execution environment.", {
configurationIncomplete: { reason: "native_recovery_environment_binding_mismatch" },
});
}
const environmentResolution = providerApiPlacement
? { environmentId: null, source: "default" as const }
: admittedLease?.environmentId ? { environmentId: admittedLease.environmentId, source: "run" as const }
: resolveExecutionWorkspaceEnvironmentId({
lowTrustIssueEnvironmentId: trustPreset.kind === "low_trust_review"
? parseIssueExecutionWorkspaceSettings(issueContext?.executionWorkspaceSettings, {includeEnvironmentId: true})?.environmentId : null,
agentDefaultEnvironmentId: agent.defaultEnvironmentId,
instanceDefaultEnvironmentId:
resolvedInstanceSettings.defaultEnvironmentId ?? null,
localDefaultEnvironmentId: localEnvironment.id,
managedSandboxOnly,
managedSandboxEnvironmentId: managedSandboxEnvironment?.id ?? null,
});
const effectiveExecutionWorkspaceMode: ReturnType<
typeof resolveExecutionWorkspaceMode
> = requestedExecutionWorkspaceMode;
const executionPolicy = {
executionMode: resolvedInstanceSettings.general.executionMode,
// Backstop behind the resolver's local→managed redirect: the run-time
// allowlist below fails any run that still resolved to a `local`
// environment under managed-sandbox-only, so no selection path or
// tenant-set env var can land untrusted execution on the tenant
// container.
managedSandboxOnly,
};
const executionForcedToKubernetes =
isExecutionForcedToKubernetes(executionPolicy);
if (providerApiPlacement) assertProviderApiPlacementPolicy(executionPolicy);
let selectedEnvironmentId = environmentResolution.environmentId;
if (executionForcedToKubernetes && !providerApiPlacement) {
let kubernetesEnvironment =
await environmentsSvc.findKubernetesEnvironment(agent.companyId);
if (!kubernetesEnvironment) {
// Lazy recovery for companies created after the startup bootstrap ran
// (the boot hook only provisions environments for companies that exist
// at boot). Re-derive the managed-env config from the bootstrap env.
// If the process env no longer forces Kubernetes (rollback / config
// drift relative to the persisted executionMode setting), skip the
// provisioning gracefully: the guard below still refuses local
// fallback with the explicit error, instead of crashing here on
// undefined config.
let bootstrap: ReturnType<typeof parseExecutionPolicyBootstrapEnv> =
null;
let bootstrapSkipReason: string | null = null;
try {
bootstrap = parseExecutionPolicyBootstrapEnv(process.env);
if (!bootstrap) {
bootstrapSkipReason =
'PAPERCLIP_EXECUTION_MODE bootstrap env is not kubernetes-forced (absent or "any")';
}
} catch (err) {
bootstrapSkipReason = `PAPERCLIP_EXECUTION_MODE bootstrap env failed to parse: ${
err instanceof Error ? err.message : String(err)
}`;
}
if (bootstrap) {
await environmentsSvc.ensureKubernetesEnvironment(
agent.companyId,
bootstrap.kubernetesConfig,
);
kubernetesEnvironment =
await environmentsSvc.findKubernetesEnvironment(agent.companyId);
} else {
logger.warn(
{
runId: run.id,
agentId: agent.id,
companyId: agent.companyId,
reason: bootstrapSkipReason,
},
"executionMode=kubernetes is persisted but the bootstrap env cannot provision a managed Kubernetes environment; skipping lazy provisioning for this company (the run will fail with the explicit no-managed-environment error)",
);
}
}
if (!kubernetesEnvironment) {
throw new Error(
"Instance execution policy requires the Kubernetes sandbox provider " +
"(executionMode=kubernetes) but no managed Kubernetes environment is " +
"configured for this company. Configure one (PAPERCLIP_K8S_* env on the " +
"cloud instance) before running agents; refusing to fall back to local execution.",
);
}
if (kubernetesEnvironment.id !== selectedEnvironmentId) {
logger.info(
{
runId: run.id,
issueId,
agentId: agent.id,
resolvedEnvironmentId: selectedEnvironmentId,
forcedKubernetesEnvironmentId: kubernetesEnvironment.id,
},
"Forcing run onto the managed Kubernetes environment (executionMode=kubernetes)",
);
}
selectedEnvironmentId = kubernetesEnvironment.id;
}
const selectedEnvironmentForConfig =
selectedEnvironmentId === localEnvironment.id
? localEnvironment
: selectedEnvironmentId
? await environmentsSvc.getById(selectedEnvironmentId)
: null;
const nativeChatWorkspaceScope = controllerOnly ? null : await findNativeChatWorkspaceScope(db, {
adapterType: agent.adapterType,
environmentDriver: selectedEnvironmentForConfig?.driver ?? null,
companyId: agent.companyId,
agentId: agent.id,
issueId,
...(fresh ? { freshAttemptId: run.id } : {}),
admittedCwd: nativeExecutionUsesTaskWorkspace(persistedNativeExecutionInput)
? persistedNativeExecutionInput.workspace.cwd : null,
});
let nativeChatExpectedCwd = nativeChatWorkspaceScope
? nativeChatWorkspaceCwd(
nativeChatWorkspaceScope,
reusableExistingExecutionWorkspace,
requestedShouldReuseExisting,
)
: null;
if (
nativeChatWorkspaceScope &&
nativeExecutionUsesTaskWorkspace(persistedNativeExecutionInput) &&
!nativeChatWorkspaceMatches({
scope: nativeChatWorkspaceScope,
expectedCwd: nativeChatExpectedCwd,
execution: persistedNativeExecutionInput,
})
) {
// Never rewrite an admitted provider input or release ownership of an
// older process whose permissions still include the shared agent home.
throw new NativeRunnerOwnershipUnverifiedError(
"native_chat_workspace_scope_mismatch",
);
}
const materializeNativeChatWorktree = Boolean(
nativeChatWorkspaceScope?.projectId && !persistedNativeExecutionInput && !existingExecutionWorkspace &&
taskWorkspaceIntent?.selection.kind === "configured_source" &&
taskWorkspaceIntent.selection.mode === "managed_isolated" &&
requestedExecutionWorkspaceMode === "isolated_workspace" &&
resolveEffectiveWorkspaceStrategyType(requestedExecutionWorkspaceMode, sourceWorkspaceConfig) === "git_worktree",
);
if (
nativeChatWorkspaceScope &&
((!nativeChatExpectedCwd && !materializeNativeChatWorktree) ||
executionProjectId !== nativeChatWorkspaceScope.projectId)
) {
throw new ConfigurationIncompleteFailure(
"External chat requires a task-owned isolated workspace. Select a managed isolated source or an existing task-owned isolated worktree; shared project workspaces cannot be used for external chat.",
{
configurationIncomplete: {
reason: "native_chat_workspace_isolation_required",
issueId,
},
},
);
}
const sharedWorkspaceConcurrency = resolveSharedWorkspaceConcurrency({
projectPolicy: projectExecutionWorkspacePolicy,
issueSettings: issueExecutionWorkspaceSettings,
});
// A reused shared execution workspace (for example one a child task inherited from a
// parent whose run is still live) follows the same policy as a shared project workspace:
// only an explicit "allow" is unsupported outside local/SSH; otherwise wait for the holder.
// A holder silent past the staleness cutoff is still running, so its folder is not free:
// fail rather than overlap it or wait on it forever.
if (!nativeRecoveryExecutionWorkspaceId && reusableExistingExecutionWorkspace &&
effectiveExecutionWorkspaceMode === "shared_workspace" &&
selectedEnvironmentForConfig?.driver !== "local" && selectedEnvironmentForConfig?.driver !== "ssh") {
const executionWorkspaceHolder = await findExecutionWorkspaceHolder({
companyId: agent.companyId,
executionWorkspaceId: reusableExistingExecutionWorkspace.id,
excludeRunId: run.id,
});
if (executionWorkspaceHolder) {
if (executionWorkspaceHolder.stale) {
throw new ConfigurationIncompleteFailure(`This environment cannot place concurrent agents in one physical shared folder, and run ${executionWorkspaceHolder.runId} still holds this shared execution workspace after more than an hour without output. Use local/SSH sharing or isolated task workspaces.`, {
configurationIncomplete: { reason: "shared_realization_unsupported", issueId, holderRunId: executionWorkspaceHolder.runId, holderStale: true },
});
}
if (sharedWorkspaceConcurrency === "allow") {
throw new ConfigurationIncompleteFailure("This environment cannot place concurrent agents in one physical shared folder. Use local/SSH sharing or isolated task workspaces.", {
configurationIncomplete: { reason: "shared_realization_unsupported", issueId },
});
}
throw new WorkspaceBusyDeferral({
holder: executionWorkspaceHolder,
executionWorkspaceId: reusableExistingExecutionWorkspace.id,
deferralAttempt:
run.scheduledRetryReason === WORKSPACE_BUSY_RETRY_REASON
? (run.scheduledRetryAttempt ?? 0)
: 0,
wasIssueAssignee: issueContext?.assigneeAgentId === agent.id,
});
}
}
// A live holder is always consulted for shared workspaces. Depending on policy and the final
// execution target it either remains the existing deferral gate or becomes dispatch context.
// Local/SSH folders never take an exclusive workspace lock, including when older
// project or issue settings request serialization. Sandbox protection still uses
// the existing holder staleness and workspace_busy retry ladder.
if (
!controllerOnly && issueRef?.projectWorkspaceId &&
effectiveExecutionWorkspaceMode === "shared_workspace"
) {
const workspaceHolder = await findSharedWorkspaceHolder({
companyId: agent.companyId,
projectWorkspaceId: issueRef.projectWorkspaceId,
excludeIssueId: issueRef.id,
excludeRunId: run.id,
honorIsolatedWorkspaceModes: runtimeWorkspaceSelectionEnabled,
});
if (workspaceHolder) {
const environmentDriver =
selectedEnvironmentForConfig?.driver ?? null;
if (!nativeRecoveryExecutionWorkspaceId && sharedWorkspaceConcurrency === "allow" &&
(executionForcedToKubernetes || (environmentDriver !== "local" && environmentDriver !== "ssh"))) {
throw new ConfigurationIncompleteFailure("This environment cannot place concurrent agents in one physical shared folder. Use local/SSH sharing or isolated task workspaces.", {
configurationIncomplete: { reason: "shared_realization_unsupported", issueId },
});
}
const shouldSerialize =
sharedWorkspaceConcurrency !== "allow" &&
(executionForcedToKubernetes ||
(environmentDriver !== "local" &&
environmentDriver !== "ssh"));
if (shouldSerialize) {
throw new WorkspaceBusyDeferral({
holder: workspaceHolder,
projectWorkspaceId: issueRef.projectWorkspaceId,
deferralAttempt:
run.scheduledRetryReason === WORKSPACE_BUSY_RETRY_REASON
? (run.scheduledRetryAttempt ?? 0)
: 0,
wasIssueAssignee: issueContext?.assigneeAgentId === agent.id,
});
}
const holderIssueLabel =
workspaceHolder.issueIdentifier ?? workspaceHolder.issueId;
const concurrentWorkspaceNote =
`shared workspace is concurrently held by run ${workspaceHolder.runId} (issue ${holderIssueLabel}); ` +
"expect concurrent mutations, coordinate via commits";
const appendConcurrentWorkspaceNote = (value: unknown) => {
const existing = typeof value === "string" ? value.trimEnd() : "";
return existing
? `${existing}\n${concurrentWorkspaceNote}`
: concurrentWorkspaceNote;
};
context.paperclipTaskMarkdown = appendConcurrentWorkspaceNote(
context.paperclipTaskMarkdown,
);
context.paperclipTaskMarkdownAssignment = appendConcurrentWorkspaceNote(
context.paperclipTaskMarkdownAssignment,
);
if (typeof context.paperclipTaskMarkdownCompact === "string") {
context.paperclipTaskMarkdownCompact =
appendConcurrentWorkspaceNote(
context.paperclipTaskMarkdownCompact,
);
}
if (typeof context.paperclipTaskMarkdownAssignmentCompact === "string") {
context.paperclipTaskMarkdownAssignmentCompact =
appendConcurrentWorkspaceNote(
context.paperclipTaskMarkdownAssignmentCompact,
);
}
logger.info(
{
event: "shared_workspace_concurrent_dispatch",
runId: run.id,
issueId: issueRef.id,
projectWorkspaceId: issueRef.projectWorkspaceId,
holderRunId: workspaceHolder.runId,
holderIssueId: workspaceHolder.issueId,
sharedWorkspaceConcurrency,
environmentDriver,
executionForcedToKubernetes,
},
"Dispatching alongside a live shared-workspace holder",
);
}
}
if (!controllerOnly && taskWorkspaceIntent && !boundSourceWorkspace && !nativeRecoveryExecutionWorkspaceId) {
await executionWorkspacesSvc.validateStoredSelectionForRun({ companyId: agent.companyId,
actor: { type: "agent", agentId: agent.id, companyId: agent.companyId, runId: run.id, source: "agent_jwt", onBehalfOfUserId: responsibleUserId === "local-board" ? null : responsibleUserId },
selection: taskWorkspaceIntent.selection, issueId,
preserveImplicitDefaultSettings: ["project", "task_default"].includes(taskWorkspaceIntent.source) });
}
const explicitTaskDirectory = !controllerOnly && taskWorkspaceIntent?.selection.kind === "task_directory";
const explicitDirectoryStrategies = [
...(reusableExistingExecutionWorkspace?.providerType === "adapter_managed" ? [config.workspaceStrategy] : []),
issueAssigneeOverrides?.adapterConfig?.workspaceStrategy,
projectExecutionWorkspacePolicy?.workspaceStrategy, issueExecutionWorkspaceSettings?.workspaceStrategy];
// RC-58: a native restart re-prepares its admitted workspace. When that is
// the task's own bound directory (for example a fresh Retry attempt), it keeps
// its directory strategy; it never becomes the base of a new git worktree.
const boundTaskDirectory = !controllerOnly && !fresh && issueId !== null && issueRef !== null &&
(!nativeRecoveryExecutionWorkspaceId || nativeRecoveryExecutionWorkspaceId === issueRef.executionWorkspaceId) &&
requestedShouldReuseExisting && requestedExecutionWorkspaceMode === "isolated_workspace" &&
!workspaceProjectContext?.hasWorkspace && !issueRef.projectWorkspaceId &&
taskWorkspaceIntent?.selection.kind !== "configured_source" &&
(taskWorkspaceIntent?.selection.kind !== "existing" || taskWorkspaceIntent.selection.workspaceId === issueRef.executionWorkspaceId) &&
(await isBoundIsolatedTaskDirectory({ companyId: agent.companyId, issueId,
workspaceId: issueRef.executionWorkspaceId, workspace: reusableExistingExecutionWorkspace }) ||
(selectedEnvironmentForConfig?.driver === "plugin" && agent.adapterType === "paperclip_runner" &&
isBoundPluginTaskDirectory({ companyId: agent.companyId, issueId,
workspaceId: issueRef.executionWorkspaceId, workspace: reusableExistingExecutionWorkspace,
owner: { agentId: agent.id, environmentId: selectedEnvironmentForConfig.id,
pluginKey: parseObject(selectedEnvironmentForConfig.config).pluginKey ?? null,
driverKey: parseObject(selectedEnvironmentForConfig.config).driverKey ?? null } })));
const reuseTaskDirectory = boundTaskDirectory && explicitDirectoryStrategies.every(value => {
const strategy = parseObject(value);
return Object.keys(strategy).length === 0 || (Object.keys(strategy).length === 1 && strategy.type === "project_primary");
});
if (retainedDirectory && !boundTaskDirectory) throw new WorkspaceValidationFailure("The saved Retry task directory is unavailable.", {
workspaceValidation: { reason: "isolated_task_directory_binding_mismatch", issueId },
});
const useIsolatedTaskDirectory = !controllerOnly && issueRef !== null && (reuseTaskDirectory || (fresh && !workspaceProjectContext?.hasWorkspace && !issueRef.projectWorkspaceId) || shouldUseIsolatedTaskDirectory({
trustPreset: trustPreset.kind,
environmentDriver: selectedEnvironmentForConfig?.driver ?? null,
mode: requestedExecutionWorkspaceMode,
hasProjectWorkspace: workspaceProjectContext?.hasWorkspace ?? false,
projectWorkspaceId: issueRef.projectWorkspaceId,
hasSelectedExecutionWorkspace: Boolean(issueRef.executionWorkspaceId || boundSourceWorkspace) ||
requestedShouldReuseExisting || taskWorkspaceIntent?.selection.kind === "existing",
workspaceStrategies: [
config.workspaceStrategy,
issueAssigneeOverrides?.adapterConfig?.workspaceStrategy,
projectExecutionWorkspacePolicy?.workspaceStrategy,
issueExecutionWorkspaceSettings?.workspaceStrategy,
],
}));
return {
persistedRunnerProfile,
persistedNativeExecutionInput,
isDotRun,
providerApiPlacement,
existingExecutionWorkspace,
nativeRecoveryExecutionWorkspaceId,
workspaceReuseRequest,
requestedShouldReuseExisting,
reusableExistingExecutionWorkspace,
requestedReusableExecutionWorkspaceConfig,
localEnvironment,
resolvedInstanceSettings,
environmentResolution,
effectiveExecutionWorkspaceMode,
executionPolicy,
selectedEnvironmentId,
selectedEnvironmentForConfig,
nativeChatWorkspaceScope,
nativeChatExpectedCwd,
materializeNativeChatWorktree,
explicitTaskDirectory,
useIsolatedTaskDirectory,
};
}