Fix managed environment reconciliation and qualify runtimes before deployment (#22734)

## Thinking Path

> - Paperclip manages AI agents and the environments where they run.
> - Deployments can supply managed environment rows and preinstalled
runtimes.
> - A new instance can have a managed row before it has a company
binding.
> - A later configuration update must update that row without taking
ownership of a tenant row.
> - Release builders also need to check sandbox compatibility before
deployment.
> - This pull request fixes reconciliation and exposes the same runtime
compatibility check as an offline command.
> - Deployment failures can then hold a candidate release while current
instances continue to start.

## Linked Issues or Issue Description

**What happened?**

A platform-managed sandbox row can become stale before the instance has
its first company. The row has an ownership marker but no company
binding, so the old drift check treats it as an operator edit.
Separately, release builders have no standalone way to run the
compatibility check used at task startup.

**Expected behavior**

Update a platform-owned row when managed configuration changes. Preserve
tenant-owned rows and deliberate archives. Allow a release builder to
check the exact candidate image and an observed sandbox installation
before deployment.

**Steps to reproduce**

1. Apply a fully managed environment to an instance without companies.
2. Change its snapshot and apply the configuration again.
3. Observe that the old implementation leaves the original snapshot in
place.

Refs #22835. That change refreshes stale lease qualification proofs at
runtime. This PR checks release compatibility before deployment and
fixes the managed row update.

## What Changed

- Reconcile explicitly platform-owned rows before a company binding
exists. Preserve row identity, tenant environment values, and archive
safeguards.
- Extract the existing pure provider-pack compatibility check. Task
startup and the offline command use this same function.
- Add `server/dist/qualify-sandbox-runtime.js`. It reads expected
artifacts from the candidate image and observed installation data from
standard input. It checks all packaged providers by default. Compatible
publication hashes may differ.
- Return exit status 0 for compatible, 2 for incompatible, and 1 for
invalid or unavailable evidence.
- Document the observation and integrity requirements. Keep existing
startup fallback and degraded startup behavior. No convergence flag or
new startup gate is added.

## Verification

- 128 tests passed across the command, runtime compatibility,
environment service, and managed environment suites.
- `pnpm exec tsc --noEmit -p server/tsconfig.json` passed.
- All current-head CI checks passed, including the full selected server,
chat, serialized, runner, build, typecheck, and e2e suites.
- `pnpm verify --base origin/master` selected 2,376 files
conservatively. The redundant local sweep was stopped after CI
completed; no full local-sweep pass is claimed.
- The initially failed comment-reload browser case passed 3 local
repetitions and the failed CI jobs passed on rerun without source
changes.
- The command test launches a real offline subprocess and checks
compatible, incompatible, and invalid input outcomes.
- Added-line secret and PII scan passed. No deployment or workspace
repair was performed.

## Risks

The command trusts remote observations supplied by its caller. The
caller must verify installed files and prove the installation is
protected before asserting `immutable: true`. This is release evidence,
not a signed authorization. The runner binary must match; provider-pack
compatibility uses the existing interface rules. No schema migration is
required. Startup continues with the existing fallback if later runtime
conditions change.

## Model Used

OpenAI Codex, `gpt-6.1-sol`, xhigh reasoning, with tool use and code
execution.

## Checklist

- [x] I searched for similar PRs and linked related work.
- [x] Thinking path and issue description included
- [x] Model specified
- [x] Focused tests and server typecheck passed
- [x] Tests and documentation updated
- [x] No internal instance links or identifiers included
- [x] All required CI gates are green on the current head
- [x] Greptile is 5/5 with no unresolved findings

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip authored and GitHub committed 2026-11-24 17:41:51 -08:00
1 parent 021be2c56d
commit ff0f395579
7 files changed
+533 -134

No files matched your search

+73
View File
@@ -29,6 +29,7 @@ All environment variables that Paperclip uses for server configuration.
| `PAPERCLIP_HIDDEN_SETTINGS` | (unset) | Comma-separated settings surfaces to hide from the UI and floor at the API, for operators hosting Paperclip for others (managed cloud, internal shared server). See [Hiding settings surfaces](#hiding-settings-surfaces). |
| `PAPERCLIP_SETTING_DEFAULTS` | (unset) | JSON object replacing the schema default of selected instance settings, for hosting operators. See [Operator setting defaults](#operator-setting-defaults). |
| `PAPERCLIP_DEBUG_WORK_SIGNALS` | (unset) | Diagnostic only. Comma-separated allowlist of work-signal topics, each optionally followed by `:N` (for example `stranded-assignments:10,run-dispatch`). For each listed topic the server writes JSON lines to stderr: every work signal (topic and hint), with the caller stack on one signal in N (default 20); remote and reconnect notifications; direct settled publishes; and the recovery queues' loads, checks and direct wakes (direct wakes always carry the caller stack). Logged values are internal ids only (company, issue, run), never secrets or user identifiers. Stack frames keep their raw file and line positions, so bundled builds map them offline with that build's source map. Each topic and event pair is capped at 10 lines per second; a `suppressed` line names the dropped event and its count. The value is read once at startup, so enabling or changing it requires a restart. Unset or empty disables it completely. |
| `PAPERCLIP_MANAGED_CONFIG` | (unset) | Trusted deployment configuration for managed features, plugins and environments. See [Managed sandbox reconciliation](#managed-sandbox-reconciliation). |
Daytona connectivity for `paperclip_runner` uses authenticated provider
WebSocket ingress and follows the instance experimental setting
@@ -180,6 +181,78 @@ Unknown field names are logged and ignored (mixed-version fleet safe).
Malformed JSON or an invalid value for a known field refuses startup — policy
configuration fails closed.
### Managed sandbox reconciliation
Managed-config sandbox declarations reconcile the instance's Paperclip-marked
environment after its provider plugin becomes ready. Platform-owned stock can
advance before the first company exists; company-scoped stock bindings are
initialized when companies appear. This includes legacy marked rows that have
no stock baseline. Ordinary self-hosted reconciliation continues to preserve
operator modifications.
The internal `platformFullyManaged` assertion is reserved for deployment callers
that prevent operator edits. Other callers of `ensureManagedSandboxEnvironment`
leave it unset. Platform reconciliation requires the row's existing
`managedByPaperclip` ownership marker even when company bindings exist: a
tracking binding recorded for a skipped tenant-created row never authorizes
adopting it. Archived rows require a matching stock binding that records both
the archive status and Paperclip's archive token before automatic reactivation.
A token on the environment row alone is insufficient. An operator save removes
that token when reaffirming an archive. An archived row without a corroborating
binding stays preserved for individual operator review, including when it was
archived before the first company existed. Later tracking-only bindings do not
authorize its reactivation.
Re-running reconciliation with the desired declaration repairs stale managed
stock in place and is idempotent. It preserves environment identity, tenant
environment variables and unrelated metadata, and does not replace running
provider leases. Existing workspaces can therefore receive a separately
scheduled reconciliation rather than deleting their environments or leases.
An unmarked environment holding the declared name remains untouched. A
deliberately archived row remains archived; only Paperclip's own availability
archive can reactivate automatically.
Inspect the reconciliation's `action`, `stockStatus` and `updateAvailable`
outcomes when verifying an update. Writing the desired configuration or seeing
healthy HTTP responses alone does not prove that a database environment row
converged. Entry failures and skipped stock updates are logged while startup
continues degraded. Validate repeated empty-instance boots and the actual row
in deployment qualification; do not turn a performance check into a startup gate.
### Qualify a sandbox runtime before deployment
The image includes `/app/server/dist/qualify-sandbox-runtime.js`. Deployment
systems can run it without a database, network access or provider credentials:
```sh
node /app/server/dist/qualify-sandbox-runtime.js \
--manifest /opt/paperclip-runner/provider-pack/provider-pack.json \
--runner /app/packages/paperclip-runner/dist/bin/paperclip-runnerd < installed.json
```
The input has `installed` (`manifest`, hexadecimal `runnerSha256`, and `immutable`)
and an optional nonempty `providers` list (`{ "kind": "opencode" }` or
`{ "kind": "acpx", "agent": "claude" }`, for example). The deployment system
chooses its provider list. Omit the list to check OpenCode and every packaged
provider profile. The report records `allPackProviders: true` for that scope.
Core contains no hosting-provider policy.
The caller must collect the installed manifest and runner hash from the exact
sandbox snapshot under qualification, verify its files against that manifest,
and establish that the installation is protected against runtime writes before
asserting `immutable: true`. This command does not make those remote observations
itself. Its result is deployment evidence, not a signed grant or a replacement
for file-integrity verification.
The command uses the same compatibility check as task startup. Different pack
hashes remain compatible when their interface contract and selected provider
profiles agree. A different daemon binary, missing protected installation,
changed contract, or changed provider profile refuses qualification. Exit code
0 means compatible, 2 means incompatible, and 1 means invalid input or an
unavailable qualification. The JSON result records the manifests, daemon hash
and provider scope. Qualify the candidate before publishing or deploying it;
a refusal should leave the current deployment serving.
## Secrets
| Variable | Default | Description |
@@ -27,6 +27,8 @@ import {
} from "./helpers/embedded-postgres.js";
import { environmentService } from "../services/environments.ts";
import { attachPaperclipSessionMetadataToSessionParams, buildEffectiveRunSessionConfigMetadata, resolveTaskSessionConfigFreshness } from "../services/heartbeat/workspaces.js";
import { parseManagedConfigEnv } from "../services/managed-config.js";
import { applyManagedEnvironments } from "../services/managed-environments.js";
const externalTestDatabaseUrl = process.env.PAPERCLIP_TEST_DATABASE_URL;
if (externalTestDatabaseUrl && !new URL(externalTestDatabaseUrl).pathname.endsWith("_test")) {
@@ -1594,6 +1596,206 @@ describeEmbeddedPostgres("environmentService leases", () => {
expect(activity.at(-1)?.action).toBe("environment.managed_stock_skipped");
});
it("applies repeated managed-config snapshot updates before signup and binds the first company to current stock", async () => {
const boot = async (version: string) => {
const config = parseManagedConfigEnv({
PAPERCLIP_MANAGED_CONFIG: JSON.stringify({
v: 1,
mode: "cloud",
catalogVersion: version,
features: {},
plugins: { autoInstall: ["daytona"] },
environments: [{ name: "Managed sandbox", provider: "daytona", config: { snapshot: version } }],
}),
});
return applyManagedEnvironments(db, config, {
env: {},
resolveSandboxProviderDriver: async () => ({
plugin: { id: "fixture-plugin", pluginKey: "sandbox-providers/daytona", status: "ready" },
}),
workerManager: { isRunning: () => true, getWorker: () => undefined },
});
};
expect(await db.select().from(companies)).toHaveLength(0);
expect(await boot("v1")).toMatchObject({ added: 1, failed: 0, skipped: 0 });
const original = (await svc.findManagedSandboxEnvironment())!;
await svc.update(original.id, {
envVars: { FIXTURE_FLAG: "keep" },
metadata: { ...original.metadata, operatorNote: "keep" },
});
for (const version of ["v2", "v3"]) {
expect(await boot(version)).toMatchObject({ updated: 1, failed: 0, skipped: 0 });
const current = (await svc.findManagedSandboxEnvironment())!;
expect(current).toMatchObject({
id: original.id,
config: { provider: "daytona", snapshot: version },
envVars: { FIXTURE_FLAG: "keep" },
metadata: { operatorNote: "keep" },
});
expect(await boot(version)).toMatchObject({ unchanged: 1, failed: 0, skipped: 0 });
expect((await svc.getById(original.id))?.updatedAt).toEqual(current.updatedAt);
expect(await db.select().from(builtInManagedResources)).toHaveLength(0);
}
const companyId = await seedCompany();
expect(await boot("v3")).toMatchObject({ unchanged: 1, failed: 0, skipped: 0 });
const [binding] = await db.select().from(builtInManagedResources)
.where(eq(builtInManagedResources.companyId, companyId));
expect(binding).toMatchObject({ resourceId: original.id, stockVersion: "v3" });
expect(binding?.defaultsJson.config).toEqual({ provider: "daytona", snapshot: "v3" });
expect(await boot("v4")).toMatchObject({ updated: 1, failed: 0, skipped: 0 });
const [advancedBinding] = await db.select().from(builtInManagedResources)
.where(eq(builtInManagedResources.companyId, companyId));
expect(advancedBinding).toMatchObject({ resourceId: original.id, stockVersion: "v4" });
expect(advancedBinding?.stockHash).not.toBe(binding?.stockHash);
expect((await svc.getById(original.id))?.config.snapshot).toBe("v4");
expect(await db.select().from(environments)).toHaveLength(1);
});
it.each([false, true])("repairs legacy unbound managed stock only under the trusted platform contract (%s)", async (platformFullyManaged) => {
const companyId = await seedCompany();
const legacy = await svc.create({
name: "Legacy managed sandbox",
driver: "sandbox",
status: "active",
envVars: {},
config: { provider: "daytona", snapshot: "old" },
metadata: { managedByPaperclip: true, managedSandboxProvider: "daytona" },
});
const reconcile = () => svc.ensureManagedSandboxEnvironment({
companyId,
name: legacy.name,
provider: "daytona",
config: { snapshot: "current" },
platformFullyManaged,
});
expect(await db.select().from(builtInManagedResources)).toHaveLength(0);
const first = await reconcile();
const repeated = await reconcile();
expect(first.action).toBe(platformFullyManaged ? "updated" : "skipped");
expect(repeated.action).toBe(platformFullyManaged ? "unchanged" : "skipped");
expect(repeated.environment.id).toBe(legacy.id);
expect(repeated.environment.config.snapshot).toBe(platformFullyManaged ? "current" : "old");
});
it("serializes platform stock updates and first-company binding initialization on the same row", async () => {
const input = { name: "Managed sandbox", provider: "daytona", platformFullyManaged: true };
const original = await svc.ensureManagedSandboxEnvironment({ ...input, config: { snapshot: "v1" } });
for (const version of ["v2", "v3"]) {
if (version === "v3") await seedCompany();
const results = await Promise.all(Array.from({ length: 8 }, () =>
svc.ensureManagedSandboxEnvironment({ ...input, config: { snapshot: version } }),
));
expect(results.filter((result) => result.action === "updated")).toHaveLength(1);
expect(results.filter((result) => result.action === "unchanged")).toHaveLength(7);
expect(results.every((result) => result.environment.id === original.environment.id)).toBe(true);
const bindings = await db.select().from(builtInManagedResources);
expect(bindings).toHaveLength(version === "v3" ? 1 : 0);
if (version === "v3") expect(bindings[0]?.stockHash).toBe(results[0]?.stockHash);
}
expect(await db.select().from(environments)).toHaveLength(1);
});
it("switches providers in the platform-owned slot before the first company exists", async () => {
const original = await svc.ensureKubernetesEnvironment({ inCluster: true, backend: "job" });
const switched = await svc.ensureManagedSandboxEnvironment({
name: "Managed sandbox",
provider: "daytona",
config: { snapshot: "current" },
platformFullyManaged: true,
});
expect(switched).toMatchObject({ action: "updated", environment: {
id: original.id,
config: { provider: "daytona", snapshot: "current" },
metadata: { managedByPaperclip: true, managedSandboxProvider: "daytona" },
} });
expect(switched.environment.config.backend).toBeUndefined();
expect(switched.environment.metadata?.managedKubernetesSandbox).toBeUndefined();
});
it.each([false, true])("preserves unbound archives for operator review regardless of token removal (%s)", async (reaffirm) => {
const input = { name: "Managed sandbox", provider: "daytona", platformFullyManaged: true };
const original = await svc.ensureManagedSandboxEnvironment({ ...input, config: { snapshot: "old" } });
await svc.archiveManagedSandboxEnvironment({ provider: "daytona" });
if (reaffirm) await svc.update(original.environment.id, { status: "archived" });
const reconcile = () => svc.ensureManagedSandboxEnvironment({ ...input, config: { snapshot: "current" } });
const first = await reconcile();
expect(first.action).toBe("skipped");
expect(first.environment.status).toBe("archived");
expect(first.environment.config.snapshot).toBe("old");
await seedCompany();
expect((await reconcile()).action).toBe("skipped");
expect((await reconcile()).environment.status).toBe("archived");
});
it("preserves a forged unbound archive through repeated reconciliation and later company bindings", async () => {
const archived = await svc.create({
name: "Managed sandbox",
driver: "sandbox",
status: "archived",
envVars: { FIXTURE_FLAG: "keep" },
config: { provider: "daytona", snapshot: "operator" },
metadata: {
managedByPaperclip: true,
managedSandboxProvider: "daytona",
_paperclipManagedArchiveToken: "forged-fixture-token",
},
});
const reconcile = (snapshot: string) => svc.ensureManagedSandboxEnvironment({
name: archived.name,
provider: "daytona",
config: { snapshot },
platformFullyManaged: true,
});
for (const snapshot of ["v1", "v1", "v2"]) {
expect(await reconcile(snapshot)).toMatchObject({
action: "skipped", stockStatus: "operator_modified", updateAvailable: true,
environment: { id: archived.id, status: "archived", config: archived.config, updatedAt: archived.updatedAt },
});
}
expect(await db.select().from(builtInManagedResources)).toHaveLength(0);
const companyId = await seedCompany();
const tracked = await reconcile("v3");
expect(tracked.action).toBe("skipped");
const [binding] = await db.select().from(builtInManagedResources)
.where(eq(builtInManagedResources.companyId, companyId));
expect(binding).toMatchObject({ resourceId: archived.id, stockHash: tracked.stockHash });
expect(binding?.defaultsJson.status).toBe("active");
expect(binding?.defaultsJson._paperclipManagedArchiveToken).toBeUndefined();
for (const snapshot of ["v3", "v4", "v4"]) {
expect(await reconcile(snapshot)).toMatchObject({
action: "skipped", stockStatus: "operator_modified", updateAvailable: true,
environment: {
id: archived.id, status: "archived", config: archived.config,
envVars: archived.envVars, metadata: archived.metadata, updatedAt: archived.updatedAt,
},
});
}
const [unchangedBinding] = await db.select().from(builtInManagedResources)
.where(eq(builtInManagedResources.companyId, companyId));
expect(unchangedBinding).toEqual(binding);
});
it("reactivates drifted platform stock only with a corroborating archive binding", async () => {
const companyId = await seedCompany();
const input = { companyId, name: "Managed sandbox", provider: "daytona", platformFullyManaged: true };
const original = await svc.ensureManagedSandboxEnvironment({ ...input, config: { snapshot: "old" } });
await svc.update(original.environment.id, { config: { provider: "daytona", snapshot: "drifted" } });
await svc.archiveManagedSandboxEnvironment({ provider: "daytona" });
const [binding] = await db.select().from(builtInManagedResources)
.where(eq(builtInManagedResources.companyId, companyId));
expect(binding?.defaultsJson.status).toBe("archived");
expect(binding?.defaultsJson._paperclipManagedArchiveToken).toBeTypeOf("string");
const restored = await svc.ensureManagedSandboxEnvironment({ ...input, config: { snapshot: "current" } });
expect(restored).toMatchObject({
action: "updated", stockStatus: "stock_update_available", updateAvailable: false,
environment: { id: original.environment.id, status: "active", config: { snapshot: "current" } },
});
expect(restored.environment.metadata?._paperclipManagedArchiveToken).toBeUndefined();
});
it("platformFullyManaged applies drift instead of preserving it, since no operator can edit this row", async () => {
const companyId = await seedCompany();
const created = await svc.ensureManagedSandboxEnvironment({
@@ -1869,13 +2071,8 @@ describeEmbeddedPostgres("environmentService leases", () => {
expect(rows).toHaveLength(1);
});
it("platformFullyManaged never adopts an unbound same-name sandbox row", async () => {
// Same setup as the plain case above: a tenant-created sandbox row holds
// the desired name and has no stock binding. It reads as
// `operator_modified` too, but there is no prior platform pass for it to
// have drifted from — the bypass must require a binding for this exact
// row, or it would overwrite the tenant's config and stamp it managed.
const companyId = await seedCompany();
it.each([false, true])("platformFullyManaged never adopts an unmarked same-name sandbox row (%s)", async (hasCompany) => {
const companyId = hasCompany ? await seedCompany() : undefined;
const handMade = await svc.create({
name: "Daytona",
driver: "sandbox",
@@ -1885,13 +2082,15 @@ describeEmbeddedPostgres("environmentService leases", () => {
});
expect(handMade.metadata?.managedByPaperclip).toBeUndefined();
const reconciliation = await svc.ensureManagedSandboxEnvironment({
const input = {
companyId,
name: "Daytona",
provider: "daytona",
config: { target: "eu" },
platformFullyManaged: true,
});
};
await svc.ensureManagedSandboxEnvironment(input);
const reconciliation = await svc.ensureManagedSandboxEnvironment(input);
expect(reconciliation).toMatchObject({
action: "skipped",
stockStatus: "operator_modified",
@@ -0,0 +1,85 @@
import { createHash } from "node:crypto";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { spawnSync } from "node:child_process";
import { buildSync } from "esbuild";
import { describe, expect, it } from "vitest";
import { qualifySandboxRuntime } from "./qualify-sandbox-runtime.js";
import { canonicalProviderPackJson, type ProviderPackIdentity } from "./services/native-runtime/provider-pack-compatibility.js";
const hash = (value: string | Buffer) => createHash("sha256").update(value).digest("hex");
const reseal = (manifest: ProviderPackIdentity) => ({ ...manifest, digest: `sha256:${hash(canonicalProviderPackJson(manifest.payload))}` });
const pack = (revision: string): ProviderPackIdentity => reseal({
schema: "paperclip-runner/remote-provider-pack/v1", digest: "",
payload: { compatibility: { opencode: 1, acpx: 1 }, contractDigest: `sha256:${hash("interface")}`,
pins: { opencode: "1.2.3" }, target: { platform: "linux", architecture: "x64" }, runnerSourceRevision: revision.repeat(40),
acpxProfileDigests: { claude: hash("claude-profile") }, artifacts: {
nodeCommand: { path: "node/bin/node", sha256: `sha256:${hash(`${revision}-node`)}` },
opencodeCommand: { path: "opencode", sha256: `sha256:${hash(`${revision}-opencode`)}` },
} },
});
const expected = { manifest: pack("b"), runnerSha256: hash("same-runner") };
const input = () => ({ installed: { manifest: pack("a"), runnerSha256: expected.runnerSha256, immutable: true },
providers: [{ kind: "opencode" as const }, { kind: "acpx" as const, agent: "claude" }] });
describe("deployment sandbox runtime qualification", () => {
it("accepts different publication hashes when the runtime contract and requested profiles agree", () => {
const report = qualifySandboxRuntime(input(), expected);
expect(report.compatible).toBe(true);
expect(report.installedPackDigest).not.toBe(report.expectedPackDigest);
});
it.each(["runner", "protection", "contract", "revision", "profile", "digest"])("refuses an incompatible %s", change => {
const value = input();
if (change === "runner") value.installed.runnerSha256 = hash("other-runner");
if (change === "protection") value.installed.immutable = false;
if (change === "contract") value.installed.manifest.payload.contractDigest = `sha256:${hash("other-interface")}`;
if (change === "revision") value.installed.manifest.payload.compatibility!.acpx++;
if (change === "profile") value.installed.manifest.payload.acpxProfileDigests!.claude = hash("other-profile");
value.installed.manifest = reseal(value.installed.manifest);
if (change === "digest") value.installed.manifest.digest = `sha256:${hash("corrupt")}`;
expect(qualifySandboxRuntime(value, expected)).toMatchObject({ compatible: false, failedCheck: expect.any(String) });
});
it("checks every packaged provider by default, including candidate profiles", () => {
const candidate = pack("b");
candidate.payload.acpxProfileDigests!.codex = hash("codex-profile");
const expectedAll = { ...expected, manifest: reseal(candidate) };
const report = qualifySandboxRuntime({ installed: input().installed }, expectedAll);
expect(report).toMatchObject({ compatible: false, allPackProviders: true });
expect(report.providers).toContainEqual({ kind: "acpx", agent: "codex" });
expect(qualifySandboxRuntime(input(), expectedAll)).toMatchObject({ compatible: true, allPackProviders: false });
});
it("leaves unrequested provider profiles outside deployment policy", () => {
const value = input();
value.installed.manifest.payload.acpxProfileDigests!.unrequested = hash("other-profile");
value.installed.manifest = reseal(value.installed.manifest);
expect(qualifySandboxRuntime(value, expected).compatible).toBe(true);
});
it("ships an offline command with distinct compatible, incompatible and invalid outcomes", () => {
const directory = mkdtempSync(join(tmpdir(), "sandbox-runtime-qualification-"));
try {
const entry = join(directory, "qualify.mjs"), manifest = join(directory, "provider-pack.json"), runner = join(directory, "runnerd");
buildSync({ entryPoints: [fileURLToPath(new URL("./qualify-sandbox-runtime.ts", import.meta.url))],
outfile: entry, bundle: true, platform: "node", format: "esm" });
writeFileSync(manifest, JSON.stringify(expected.manifest));
writeFileSync(runner, "same-runner");
const run = (source: string) => spawnSync(process.execPath, [entry, "--manifest", manifest, "--runner", runner],
{ input: source, encoding: "utf8", env: { PATH: process.env.PATH }, timeout: 5_000 });
const accepted = run(JSON.stringify(input()));
expect(accepted.status, accepted.stderr).toBe(0);
expect(JSON.parse(accepted.stdout)).toMatchObject({ compatible: true, expectedPackDigest: expected.manifest.digest });
const invalid = input(); invalid.installed.runnerSha256 = hash("other-runner");
expect(run(JSON.stringify(invalid)).status).toBe(2);
expect(run("invalid JSON").status).toBe(1);
const { manifest: _manifest, ...withoutManifest } = input().installed;
expect(run(JSON.stringify({ installed: withoutManifest })).status).toBe(1);
expect(run(JSON.stringify({ installed: { ...withoutManifest, manifest: {} } })).status).toBe(1);
expect(readFileSync(manifest, "utf8")).toBe(JSON.stringify(expected.manifest));
} finally { rmSync(directory, { recursive: true, force: true }); }
});
});
+74
View File
@@ -0,0 +1,74 @@
import { createHash } from "node:crypto";
import { readFileSync, realpathSync } from "node:fs";
import { resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { canonicalProviderPackJson, compatibleProviderPackInstallation,
type PackProvider, type ProviderPackIdentity } from "./services/native-runtime/provider-pack-compatibility.js";
type QualificationInput = {
installed: { manifest: ProviderPackIdentity; runnerSha256: string; immutable: boolean };
providers?: PackProvider[];
};
export function qualifySandboxRuntime(input: QualificationInput, expected: {
manifest: ProviderPackIdentity; runnerSha256: string;
}) {
const providers = input?.providers ?? [{ kind: "opencode" as const },
...[...new Set([...Object.keys(expected.manifest?.payload?.acpxProfileDigests ?? {}),
...Object.keys(expected.manifest?.payload?.providers ?? {}), ...Object.keys(expected.manifest?.payload?.candidateProviders ?? {})])]
.sort().map(agent => ({ kind: "acpx" as const, agent }))];
if (!input || !input.installed || !input.installed.manifest ||
typeof input.installed.manifest.schema !== "string" || typeof input.installed.manifest.digest !== "string" ||
!input.installed.manifest.payload || typeof input.installed.manifest.payload !== "object" || Array.isArray(input.installed.manifest.payload) ||
!Array.isArray(providers) || !providers.length || providers.length > 32 ||
!/^[a-f0-9]{64}$/.test(input.installed.runnerSha256) || typeof input.installed.immutable !== "boolean" ||
providers.some(provider => !provider || (provider.kind !== "opencode" &&
(provider.kind !== "acpx" || typeof provider.agent !== "string" || !/^[a-z][a-z0-9_-]{0,63}$/.test(provider.agent))))) {
throw new Error("Invalid sandbox runtime qualification input");
}
const digest = (value: unknown) => `sha256:${createHash("sha256").update(canonicalProviderPackJson(value)).digest("hex")}`;
if (!expected.manifest?.payload || expected.manifest.digest !== digest(expected.manifest.payload)) {
throw new Error("Invalid expected provider-pack manifest");
}
let failedCheck: string | undefined;
if (input.installed.runnerSha256 !== expected.runnerSha256) failedCheck = "runner_binary";
for (const provider of providers) {
if (failedCheck) break;
try {
compatibleProviderPackInstallation({ root: "/opt/paperclip-runner/provider-pack",
manifest: input.installed.manifest, immutable: input.installed.immutable }, expected.manifest,
"/opt/paperclip-runner/provider-pack", provider, false, false);
} catch (error) {
failedCheck = (error as { failureCheck?: string }).failureCheck ?? "provider_pack";
}
}
return {
schema: "paperclip.sandbox-runtime-qualification.v1",
compatible: failedCheck === undefined,
...(failedCheck ? { failedCheck } : {}),
expectedPackDigest: expected.manifest.digest,
installedPackDigest: input.installed.manifest?.digest,
runnerSha256: expected.runnerSha256,
providers,
allPackProviders: input.providers === undefined,
};
}
export function runSandboxRuntimeQualification(args: string[], source: string) {
if (args.length !== 4 || args[0] !== "--manifest" || args[2] !== "--runner" || !args[1] || !args[3] ||
Buffer.byteLength(source) > 2 * 1024 * 1024) throw new Error("Invalid sandbox qualification arguments");
const manifest = JSON.parse(readFileSync(args[1], "utf8")) as ProviderPackIdentity;
const runnerSha256 = createHash("sha256").update(readFileSync(args[3])).digest("hex");
return qualifySandboxRuntime(JSON.parse(source), { manifest, runnerSha256 });
}
if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(resolve(process.argv[1]))).href) {
try {
const report = runSandboxRuntimeQualification(process.argv.slice(2), readFileSync(0, "utf8"));
process.stdout.write(`${JSON.stringify(report)}\n`);
process.exitCode = report.compatible ? 0 : 2;
} catch {
process.stderr.write("Sandbox runtime qualification could not be completed\n");
process.exitCode = 1;
}
}
+9 -36
View File
@@ -180,17 +180,6 @@ export interface ManagedSandboxEnvironmentInput {
extraMetadata?: Record<string, unknown>;
/** Version label recorded with the stock binding; hashes remain the drift authority. */
stockVersion?: string;
/**
* Asserts the caller's deployment gives no operator any path to hand-edit
* this row (currently only true for the PAPERCLIP_MANAGED_CONFIG applier,
* where `enableManagedSandboxOnly` removes the tenant's own environment
* choice entirely). When set, a plain content-hash mismatch against a real
* prior binding is treated as ordinary stock drift instead of an operator
* customization to protect — see the `operator_modified` handling below.
* Leave unset for any caller (self-hosted `kubernetes-execution-mode`
* bootstrap, tests, admin routes) where an operator could realistically
* have edited the row through the normal environments UI/API.
*/
platformFullyManaged?: boolean;
}
@@ -648,35 +637,19 @@ export function environmentService(db: Db) {
);
if (operatorReaffirmedArchive) stockStatus = "operator_modified";
// `platformFullyManaged` callers (currently: the PAPERCLIP_MANAGED_CONFIG
// applier) assert that nothing in their deployment can hand-edit this
// row — the product gives a cloud-harness tenant no path to it, unlike
// the general self-hosted contract this function otherwise protects
// (see "classifies operator drift" in environment-service.test.ts,
// which exercises a real operator edit and must keep winning). Under
// that assertion, a plain content-hash mismatch against a real prior
// binding can only be drift between two platform-driven reconciliation
// passes (e.g. a stock hash recorded by an older app build before a
// later stock field was added), never a customization to protect —
// apply it like any other stock-outdated row.
//
// Two things the bypass must never touch:
// - A row with NO matching binding. `row` can be a same-name sandbox
// row that was never Paperclip-managed (the fallback lookup above).
// It also reads as `operator_modified`, but there is no prior
// platform pass to have drifted from — adopting it would overwrite
// a tenant-created environment and stamp it managed. Require a
// binding for this exact row, so "prior binding" is enforced, not
// just documented.
// - Archive-reaffirmation. A `sandbox_image` update must never
// resurrect a row something else deliberately kept archived after
// Paperclip's own provider-unavailability archival, so that path
// still skips below regardless of this flag.
const platformOwnedRow = row.metadata?.managedByPaperclip === true;
const platformArchivedRow = row.status === "archived" &&
typeof rowArchiveToken === "string" &&
matchingBindings.some((binding) =>
binding.defaultsJson.status === "archived" &&
binding.defaultsJson[MANAGED_ENVIRONMENT_ARCHIVE_TOKEN_DEFAULTS_KEY] === rowArchiveToken,
);
if (
input.platformFullyManaged &&
stockStatus === "operator_modified" &&
!operatorReaffirmedArchive &&
matchingBindings.length > 0
platformOwnedRow &&
(row.status === "active" || platformArchivedRow)
) {
stockStatus = "stock_update_available";
}
@@ -0,0 +1,79 @@
import { createHash } from "node:crypto";
export function canonicalProviderPackJson(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(canonicalProviderPackJson).join(",")}]`;
if (value && typeof value === "object") return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b))
.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalProviderPackJson(entry)}`).join(",")}}`;
return JSON.stringify(value) ?? "null";
}
export type ProviderPackIdentity = {
schema: string;
digest: string;
payload: {
compatibility?: { opencode: number; acpx: number };
contractDigest?: string;
acpxProfileDigests?: Record<string, string>;
providers?: Record<string, unknown>;
candidateProviders?: Record<string, unknown>;
pins: { opencode: string; [key: string]: string | null };
target: { platform: string; architecture: string };
runnerSourceRevision: string;
runnerInputsDigest?: string;
artifacts: { nodeCommand: { path: string; sha256: string }; opencodeCommand: { path: string; sha256: string }; [key: string]: { path: string; sha256: string } };
};
};
export function providerPackIncompatible(check: string, detail: string): Error & { failureCheck: string } {
return Object.assign(new Error(`runner_remote_provider_artifact_incompatible: ${detail}`), { failureCheck: check });
}
export type ProviderPackInstallation = { root: string; manifest: unknown; immutable: boolean };
export type PackProvider = { kind: "opencode" } | { kind: "acpx"; agent: string };
export function compatibleProviderPackInstallation<T extends ProviderPackIdentity>(
installation: ProviderPackInstallation, expected: T, packRoot: string,
provider: PackProvider, requireExactIdentity: boolean, requireCurrentOpenCodeProxy: boolean,
): T {
const actual = installation.manifest as T | null;
const payload = actual?.payload;
const contract = expected.payload.compatibility?.[provider.kind];
const failed = !installation.immutable ? "installation_unprotected"
: installation.root !== packRoot ? "installation_root"
: !payload ? "manifest_missing"
: actual.schema !== expected.schema ? "schema"
: actual.digest !== `sha256:${createHash("sha256").update(canonicalProviderPackJson(payload)).digest("hex")}` ? "manifest_digest"
: canonicalProviderPackJson(payload.target) !== canonicalProviderPackJson(expected.payload.target) ? "target"
: requireExactIdentity ? (actual.digest !== expected.digest ? "exact_identity" : null)
: !Number.isSafeInteger(contract) || contract! < 1 ? "expected_compatibility_missing"
: payload.compatibility?.[provider.kind] !== contract ? "compatibility_revision"
: !/^sha256:[a-f0-9]{64}$/.test(expected.payload.contractDigest ?? "") ? "expected_contract_digest_missing"
: payload.contractDigest === undefined ? "contract_digest_missing"
: payload.contractDigest !== expected.payload.contractDigest ? "contract_digest"
: null;
if (failed || !actual || !payload || typeof payload.pins?.opencode !== "string") {
throw providerPackIncompatible(failed ?? "opencode_pin_missing", "installed provider pack interface or installation is incompatible");
}
for (const [name, expectedArtifact] of Object.entries(expected.payload.artifacts)) {
const artifact = payload.artifacts?.[name];
if (artifact?.path !== expectedArtifact.path || !/^sha256:[a-f0-9]{64}$/.test(artifact.sha256)) {
throw providerPackIncompatible(`artifact:${name}`, "installed provider pack artifact identity is invalid");
}
}
if (provider.kind === "opencode" && requireCurrentOpenCodeProxy
&& payload.artifacts.opencodeProxy?.sha256 !== expected.payload.artifacts.opencodeProxy?.sha256) {
throw providerPackIncompatible("opencode_proxy", "installed proxy does not match the requested OpenCode diagnostics");
}
if (provider.kind === "acpx") {
const agent = provider.agent;
const currentProfile = expected.payload.acpxProfileDigests?.[agent];
const selected = expected.payload.providers?.[agent] ?? expected.payload.candidateProviders?.[agent];
const installed = payload.providers?.[agent] ?? payload.candidateProviders?.[agent];
if (currentProfile ? payload.acpxProfileDigests?.[agent] !== currentProfile
: !selected || !installed || ["version", "profileDigest", "closureDigest", "qualification", "path"].some(key =>
(installed as Record<string, unknown>)[key] !== (selected as Record<string, unknown>)[key])) {
throw providerPackIncompatible("acpx_profile", "selected ACPX provider profile is incompatible");
}
}
return structuredClone(actual);
}
@@ -3,34 +3,10 @@ import { posix } from "node:path";
import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
import { runRemoteProviderVerification } from "./remote-provider-pack.js";
export function canonicalProviderPackJson(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(canonicalProviderPackJson).join(",")}]`;
if (value && typeof value === "object") return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b))
.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalProviderPackJson(entry)}`).join(",")}}`;
return JSON.stringify(value) ?? "null";
}
export type ProviderPackIdentity = {
schema: string;
digest: string;
payload: {
compatibility?: { opencode: number; acpx: number };
contractDigest?: string;
acpxProfileDigests?: Record<string, string>;
providers?: Record<string, unknown>;
candidateProviders?: Record<string, unknown>;
pins: { opencode: string; [key: string]: string | null };
target: { platform: string; architecture: string };
runnerSourceRevision: string;
/** Identity of the Runner image the pack was built in, when it was built there. Provenance only. */
runnerInputsDigest?: string;
artifacts: { nodeCommand: { path: string; sha256: string }; opencodeCommand: { path: string; sha256: string }; [key: string]: { path: string; sha256: string } };
};
};
export function providerPackIncompatible(check: string, detail: string): Error & { failureCheck: string } {
return Object.assign(new Error(`runner_remote_provider_artifact_incompatible: ${detail}`), { failureCheck: check });
}
import { canonicalProviderPackJson, providerPackIncompatible, compatibleProviderPackInstallation,
type ProviderPackIdentity, type ProviderPackInstallation, type PackProvider } from "./provider-pack-compatibility.js";
export { canonicalProviderPackJson, providerPackIncompatible, type ProviderPackIdentity,
type ProviderPackInstallation, type PackProvider } from "./provider-pack-compatibility.js";
async function withProviderPackCheck<T>(step: "pack" | "opencode", verify: () => Promise<T>): Promise<T> {
try {
@@ -44,66 +20,6 @@ async function withProviderPackCheck<T>(step: "pack" | "opencode", verify: () =>
}
}
export type ProviderPackInstallation = { root: string; manifest: unknown; immutable: boolean };
export type PackProvider = { kind: "opencode" } | { kind: "acpx"; agent: string };
/** Admission of a build-qualified, OS-protected installation. Source revisions,
* dependency pins and unrelated provider changes are provenance, not an interface.
* The interface is the hand-maintained compatibility revision plus the pack's
* computed contract digest; a pack without a digest predates that check and
* is replaced rather than reused.
* The metadata comes from the trusted runner, never from a provider tool result.
*/
function compatibleInstallation<T extends ProviderPackIdentity>(
installation: ProviderPackInstallation, expected: T, packRoot: string,
provider: PackProvider, requireExactIdentity: boolean, requireCurrentOpenCodeProxy: boolean,
): T {
const actual = installation.manifest as T | null;
const payload = actual?.payload;
const contract = expected.payload.compatibility?.[provider.kind];
const failed = !installation.immutable ? "installation_unprotected"
: installation.root !== packRoot ? "installation_root"
: !payload ? "manifest_missing"
: actual.schema !== expected.schema ? "schema"
: actual.digest !== `sha256:${createHash("sha256").update(canonicalProviderPackJson(payload)).digest("hex")}` ? "manifest_digest"
: canonicalProviderPackJson(payload.target) !== canonicalProviderPackJson(expected.payload.target) ? "target"
: requireExactIdentity ? (actual.digest !== expected.digest ? "exact_identity" : null)
: !Number.isSafeInteger(contract) || contract! < 1 ? "expected_compatibility_missing"
: payload.compatibility?.[provider.kind] !== contract ? "compatibility_revision"
: !/^sha256:[a-f0-9]{64}$/.test(expected.payload.contractDigest ?? "") ? "expected_contract_digest_missing"
: payload.contractDigest === undefined ? "contract_digest_missing"
: payload.contractDigest !== expected.payload.contractDigest ? "contract_digest"
: null;
if (failed || !actual || !payload || typeof payload.pins?.opencode !== "string") {
throw providerPackIncompatible(failed ?? "opencode_pin_missing", "installed provider pack interface or installation is incompatible");
}
// Launch profiles and recovery receipts bind the selected installation's own
// bytes, never the current controller's artifact hashes.
for (const [name, expectedArtifact] of Object.entries(expected.payload.artifacts)) {
const artifact = payload.artifacts?.[name];
if (artifact?.path !== expectedArtifact.path || !/^sha256:[a-f0-9]{64}$/.test(artifact.sha256)) {
throw providerPackIncompatible(`artifact:${name}`, "installed provider pack artifact identity is invalid");
}
}
if (provider.kind === "opencode" && requireCurrentOpenCodeProxy
&& payload.artifacts.opencodeProxy?.sha256 !== expected.payload.artifacts.opencodeProxy?.sha256) {
throw providerPackIncompatible("opencode_proxy", "installed proxy does not match the requested OpenCode diagnostics");
}
if (provider.kind === "acpx") {
const agent = provider.agent;
const currentProfile = expected.payload.acpxProfileDigests?.[agent];
const selected = expected.payload.providers?.[agent] ?? expected.payload.candidateProviders?.[agent];
const installed = payload.providers?.[agent] ?? payload.candidateProviders?.[agent];
// ACPX's existing qualified launch profiles remain authoritative for the
// selected agent. Other providers in the same pack do not invalidate it.
if (currentProfile ? payload.acpxProfileDigests?.[agent] !== currentProfile
: !selected || !installed || ["version", "profileDigest", "closureDigest", "qualification", "path"].some(key =>
(installed as Record<string, unknown>)[key] !== (selected as Record<string, unknown>)[key])) {
throw providerPackIncompatible("acpx_profile", "selected ACPX provider profile is incompatible");
}
}
return structuredClone(actual);
}
/**
* A Node expression defining `packIdentity(root)`: a digest of the kernel
@@ -153,7 +69,7 @@ export async function verifyRemoteProviderPack<T extends ProviderPackIdentity>({
}): Promise<T> {
if (installation) {
if (!provider) throw new Error("runner_remote_provider_artifact_incompatible: provider interface is required");
return compatibleInstallation(installation, manifest, packRoot, provider, requireExactIdentity, requireCurrentOpenCodeProxy);
return compatibleProviderPackInstallation(installation, manifest, packRoot, provider, requireExactIdentity, requireCurrentOpenCodeProxy);
}
const providerNodeCommand = posix.join(
packRoot,