Integrate current master into sleep-12-decision-target-invalidation

Preserve upstream fixes and append stack migrations after master history. Keep SQL bytes unchanged and generate snapshots from the integrated schema. Validate the target-branch migration ordering.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-27 01:36:11 -05:00
commit 8f6f87cbcd
355 files changed
+15252 -1102

No files matched your search

@@ -9,6 +9,9 @@ import { grantsForHumanRole } from "../services/company-member-roles.js";
import { agentRoutes } from "../routes/agents.js";
import { environmentRoutes } from "../routes/environments.js";
import { errorHandler } from "../middleware/error-handler.js";
import { environmentService } from "../services/environments.js";
import { resolveEnvironmentDriverConfigForRuntime } from "../services/environment-config.js";
import { fingerprintEnvironmentSandboxProviderConfig, SANDBOX_PLATFORM_PROBE_METADATA_KEY } from "../services/environment-custom-image-runtime.js";
const probe = vi.hoisted(() => vi.fn());
vi.mock("../services/environment-probe.js", async original => ({
@@ -69,6 +72,53 @@ describe.skipIf(!support.supported)("agent-scoped runner qualification", () => {
expect(generic.status).toBe(403);
expect(probe).toHaveBeenCalledTimes(1);
});
it("lets the owner requalify an existing native runner's saved computer without changing its configuration", async () => {
await db.update(agents).set({ adapterType: "paperclip_runner", adapterConfig: { provider: "opencode", model: "example/model" } })
.where(eq(agents.id, agentId));
const before = await db.select().from(agents).where(eq(agents.id, agentId));
const response = await qualify();
expect(response.status).toBe(200);
expect(response.body).toMatchObject({ ok: true, details: { platformQualificationRecorded: true } });
expect(probe).toHaveBeenCalledWith(db, expect.objectContaining({ id: environmentId }),
expect.objectContaining({ companyId, assertCompanyBinding: true, acquireSandboxRuntimeLease: true }));
expect(await db.select().from(agents).where(eq(agents.id, agentId))).toEqual(before);
expect(JSON.stringify(response.body)).not.toMatch(/provider-secret|private-id/);
expect((await request(app).post(`/api/environments/${environmentId}/probe?companyId=${companyId}`).send({})).status).toBe(403);
});
it("reuses a current native snapshot proof without invalidating it or allocating another probe", async () => {
await db.update(agents).set({ adapterType: "paperclip_runner", adapterConfig: { provider: "opencode" } }).where(eq(agents.id, agentId));
const config = { provider: "daytona", snapshot: "managed-snapshot" };
const fingerprint = fingerprintEnvironmentSandboxProviderConfig(config);
const saved = (await environmentService(db).getById(environmentId))!;
const runtime = await resolveEnvironmentDriverConfigForRuntime(db, companyId, saved, { applyCustomImageTemplate: true, readOnlyCustomImageTemplate: true });
const runtimeFingerprint = fingerprintEnvironmentSandboxProviderConfig(runtime.config as typeof config);
const metadata = { [SANDBOX_PLATFORM_PROBE_METADATA_KEY]: { [companyId]: {
v: 2, companyId, baseConfigFingerprint: fingerprint, runtimeConfigFingerprint: runtimeFingerprint,
snapshot: config.snapshot, template: null,
snapshotIdentity: { provider: "daytona", requestedRef: config.snapshot, id: randomUUID(), name: config.snapshot,
organizationId: "fixture-organization", createdAt: new Date().toISOString() },
facts: { platform: "linux", architecture: "x64", libc: "glibc", glibcVersion: "2.36" },
} } };
await db.update(environments).set({ metadata }).where(eq(environments.id, environmentId));
expect((await qualify()).body).toMatchObject({ ok: true, details: { platformQualificationRecorded: true } });
expect(probe).not.toHaveBeenCalled();
expect((await db.select().from(environments).where(eq(environments.id, environmentId)))[0]?.metadata).toEqual(metadata);
});
it.each(["revoked", "changed-computer", "foreign-computer"])("keeps native saved-computer qualification closed for %s authority", async state => {
await db.update(agents).set({ adapterType: "paperclip_runner", adapterConfig: { provider: "opencode" } }).where(eq(agents.id, agentId));
if (state === "revoked") await db.delete(principalPermissionGrants).where(eq(principalPermissionGrants.principalId, userId));
if (state === "changed-computer") await db.update(agents).set({ defaultEnvironmentId: null }).where(eq(agents.id, agentId));
if (state === "foreign-computer") {
const other = randomUUID();
await db.insert(companies).values({ id: other, name: "Other", issuePrefix: `F${other.slice(0, 7)}` });
await db.insert(builtInManagedResources).values({ companyId: other, bundleKey: "test", resourceKind: "environment", resourceKey: "computer", resourceId: environmentId, stockVersion: "test", stockHash: "test" });
}
expect((await qualify()).status).toBe(state === "changed-computer" ? 409 : 403);
expect(probe).not.toHaveBeenCalled();
});
it("rejects an owner whose configure grant is absent before any provider work", async () => {
await db.delete(principalPermissionGrants).where(eq(principalPermissionGrants.principalId, userId));
expect((await qualify()).status).toBe(403);
@@ -46,6 +46,11 @@ const mockEnvironmentRuntime = vi.hoisted(() => ({
}));
const mockResolveEnvironmentExecutionTarget = vi.hoisted(() => vi.fn());
const mockPluginEnvironmentRequiresAgent = vi.hoisted(() => vi.fn(async () => false));
vi.mock("../services/plugin-environment-driver.js", async importOriginal => ({
...(await importOriginal<typeof import("../services/plugin-environment-driver.js")>()),
pluginEnvironmentRequiresAgent: mockPluginEnvironmentRequiresAgent,
}));
const mockInstanceSettingsService = vi.hoisted(() => ({
get: vi.fn(async () => ({ defaultEnvironmentId: null as string | null })),
getGeneral: vi.fn(async () => ({ censorUsernameInLogs: false, executionMode: "local" })),
@@ -1053,6 +1058,19 @@ describe("agent test-environment route", () => {
mockResolveNewAgentRunnerForCompany.mockClear();
});
it("reports the missing agent prerequisite without acquiring a lease or probing the host", async () => {
mockPluginEnvironmentRequiresAgent.mockResolvedValueOnce(true);
mockResolveNewAgentRunnerForCompany.mockResolvedValueOnce({ adapterType: "paperclip_runner", adapterConfig: { provider: "codex" } });
const app = await createApp();
const res = await request(app)
.post("/api/companies/company-1/adapters/codex_local/test-environment")
.send({ adapterConfig: {}, environmentId: pluginEnvironment.id });
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(res.body).toMatchObject({ status: "warn", checks: [{ code: "environment_agent_required", level: "warn" }] });
expect(mockEnvironmentRuntime.acquireRunLease).not.toHaveBeenCalled();
expect(testEnvironmentSpy).not.toHaveBeenCalled();
});
it("checks the plugin driver against the resolved Runner adapter, not the requested harness", async () => {
mockResolveNewAgentRunnerForCompany.mockResolvedValueOnce({ adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "claude" } });
const app = await createApp();
@@ -231,6 +231,102 @@ describe("awsSecretsManagerProvider", () => {
expect(init?.signal).toBeInstanceOf(AbortSignal);
});
it("preserves classified AWS create errors returned by the JSON gateway", async () => {
delete process.env.AWS_PROFILE;
delete process.env.AWS_DEFAULT_PROFILE;
delete process.env.AWS_CONFIG_FILE;
delete process.env.AWS_SHARED_CREDENTIALS_FILE;
delete process.env.AWS_SDK_LOAD_CONFIG;
process.env.AWS_ACCESS_KEY_ID = "AKIA_CREATE_ERROR_TEST";
process.env.AWS_SECRET_ACCESS_KEY = "test-secret-key";
vi.spyOn(globalThis, "fetch").mockResolvedValue(
new Response(
JSON.stringify({
__type: "AccessDeniedException",
message:
"User: arn:aws:sts::123456789012:assumed-role/prod/Paperclip is not authorized to perform secretsmanager:CreateSecret",
}),
{ status: 400 },
),
);
const provider = createAwsSecretsManagerProvider({
config: {
region: "us-west-1",
endpoint: "https://secretsmanager.us-west-1.amazonaws.com",
deploymentId: "prod",
prefix: "paperclip",
kmsKeyId: null,
environmentTag: "production",
providerOwnerTag: "paperclip",
deleteRecoveryWindowDays: 30,
},
});
await expect(
provider.createSecret({
value: "super-secret-value",
context: {
companyId: "company-1",
secretKey: "openai-api-key",
secretName: "OpenAI API Key",
version: 1,
},
}),
).rejects.toMatchObject({
code: "access_denied",
status: 403,
operation: "CreateSecret",
message: "AWS Secrets Manager denied the request. Check IAM permissions for this provider vault.",
rawMessage: expect.stringContaining("AccessDeniedException"),
});
});
it("classifies missing runtime AWS credentials as access denied", async () => {
const provider = createAwsSecretsManagerProvider({
config: {
region: "us-east-1",
endpoint: "https://secretsmanager.us-east-1.amazonaws.com",
deploymentId: "prod-use1",
prefix: "paperclip",
kmsKeyId: null,
environmentTag: "production",
providerOwnerTag: "paperclip",
deleteRecoveryWindowDays: 30,
},
gateway: {
async createSecret() {
throw new Error("CredentialsProviderError: Could not load credentials from any providers");
},
async putSecretValue() {
throw new Error("not used");
},
async getSecretValue() {
throw new Error("not used");
},
async deleteSecret() {
throw new Error("not used");
},
},
});
await expect(
provider.createSecret({
value: "super-secret-value",
context: {
companyId: "company-1",
secretKey: "openai-api-key",
secretName: "OpenAI API Key",
version: 1,
},
}),
).rejects.toMatchObject({
code: "access_denied",
status: 403,
rawMessage: "CredentialsProviderError: Could not load credentials from any providers",
});
});
it("creates new AWS secret versions against a namespace-valid existing secret reference", async () => {
const calls: Array<{ op: string; input: Record<string, unknown> }> = [];
const provider = createAwsSecretsManagerProvider({
File diff suppressed because it is too large. Load diff
@@ -274,4 +274,54 @@ describeEmbeddedPostgres("dashboard service", () => {
// process_lost kills that recovered must not leak into the failed breakdown.
expect(bucket?.failedByErrorCode.process_lost).toBeUndefined();
});
it("counts a recovered shutdown interrupt toward recovered, not other", async () => {
const companyId = randomUUID();
const agentId = randomUUID();
const day = utcDay(-1);
const shutdown = randomUUID();
const shutdownRetry = randomUUID();
const stranded = randomUUID();
await db.insert(companies).values({
id: companyId,
name: "Paperclip",
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
requireBoardApprovalForNewAgents: false,
});
await db.insert(agents).values({
id: agentId,
companyId,
name: "CodexCoder",
role: "engineer",
status: "running",
adapterType: "codex_local",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
});
const base = {
companyId,
agentId,
invocationSource: "assignment" as const,
createdAt: day,
};
await db.insert(heartbeatRuns).values([
{ ...base, id: shutdown, status: "interrupted", errorCode: "server_shutdown_interrupted" },
{ ...base, id: shutdownRetry, status: "succeeded", retryOfRunId: shutdown },
{ ...base, id: stranded, status: "interrupted", errorCode: "server_shutdown_interrupted" },
]);
const summary = await dashboardService(db).summary(companyId);
const bucket = summary.runActivity.find((entry) => entry.date === utcDateKey(day));
expect(bucket).toMatchObject({
succeeded: 1,
recovered: 1,
failed: 0,
other: 1,
total: 3,
failedByErrorCode: {},
});
});
});
@@ -321,6 +321,22 @@ describe("durable inbound chat scheduler receipts", () => {
});
});
it("reconsiders the same held inbound receipt only through its live durable owner", async () => {
const f = await fixture();
const clearHold = await executionHold(f);
const request = f.request();
expect(await f.wake(request)).toBeNull();
await clearHold();
const reconsidered = createDurableChatWakeupRequest({ ...request, resumeDeferred: true });
const [first, second] = await Promise.all([f.wake(reconsidered), f.wake(reconsidered)]);
const receipts = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.agentId, f.agentId));
expect(receipts).toHaveLength(1);
expect(receipts[0]).toMatchObject({ id: request.id, status: "queued", requestedAt: request.requestedAt });
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.wakeupRequestId, request.id))).toHaveLength(1);
expect(first?.id ?? second?.id).toBe(receipts[0].runId);
expect(f.authorize.mock.calls.length).toBeGreaterThan(1);
});
async function retryFixture(deferred = false) {
const f = await fixture(deferred);
const applicationId = randomUUID(),
@@ -764,6 +764,20 @@ describe("environmentRunOrchestrator — realizeForRun", () => {
describe("native runner lifecycle changes before lease acquisition", () => {
it.each([undefined, "account:generation"])("uses a warm plugin lease only with a managed credential identity: %s", async managedAiCredentialIdentity => {
const environment = { ...makeEnvironment("plugin"), config: { pluginKey: "fixture", driverKey: "tasks", driverConfig: {} } };
mockGetEnvironment.mockResolvedValue(environment);
const acquireRunLease = vi.fn(async input => ({ environment: input.environment,
lease: makeLease({ leasePolicy: input.environment.config.runnerLifecycleMode === "warm" ? "reuse_by_environment" : "ephemeral" }), leaseContext: {} }));
const orchestrator = environmentRunOrchestrator({} as never, { environmentRuntime: makeMockRuntime({ acquireRunLease }) });
const result = await orchestrator.acquireForRun({ companyId: "company-1", selectedEnvironmentId: "env-1", localEnvironmentId: "local",
adapterType: "paperclip_runner", adapterConfig: { lifecycleMode: "warm" }, managedAiCredentialIdentity,
issueId: "task-1", heartbeatRunId: "run-1", agentId: "agent-1", persistedExecutionWorkspace: null, executionWorkspaceSettings: null });
expect(result.environment.config.runnerLifecycleMode).toBe(managedAiCredentialIdentity ? "warm" : "per_turn");
expect(result.lease.leasePolicy).toBe(managedAiCredentialIdentity ? "reuse_by_environment" : "ephemeral");
expect(environment.config).not.toHaveProperty("runnerLifecycleMode");
});
it("requests a reusable lease when an existing task switches from per-turn to warm", async () => {
const environment = { ...makeEnvironment("sandbox"), config: { provider: "daytona", reuseLease: false } };
mockGetEnvironment.mockResolvedValue(environment);
@@ -824,7 +824,7 @@ describeEmbeddedPostgres("environmentRuntimeService", () => {
const cold = await runtime.acquireRunLease({ ...input, environment, heartbeatRunId: seeded.runId });
expect(cold.lease.leasePolicy).toBe("ephemeral");
await runtime.releaseRunLeases(seeded.runId, "released");
const warmEnvironment = resolveRunnerEnvironmentForRun(environment, "paperclip_runner", { lifecycleMode: "warm" });
const warmEnvironment = resolveRunnerEnvironmentForRun(environment, "paperclip_runner", { lifecycleMode: "warm" }, undefined, "selected-account:generation");
const warmRunId = randomUUID();
await db.insert(heartbeatRuns).values({ id: warmRunId, companyId: seeded.companyId, agentId: seeded.agentId, status: "running" });
const warm = await runtime.acquireRunLease({ ...input, environment: warmEnvironment, heartbeatRunId: warmRunId });
@@ -0,0 +1,196 @@
import { createHash, randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { and, eq } from "drizzle-orm";
import { agents, companies, companySkills, createDb, environments, pluginCompanySettings, plugins, resourceLifecycleEvents, type Db } from "@paperclipai/db";
import type { PaperclipPluginManifestV1 } from "@paperclipai/shared";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { environmentSkillConfig } from "../services/environment-skills.js";
import { pluginAgentRuntimeState } from "../services/plugin-agent-runtime-state.js";
import { companySkillService } from "../services/company-skills.js";
import { instanceSettingsService } from "../services/instance-settings.js";
import { withSkillActor } from "../services/skill-access.js";
import { buildNativeRuntimeContext } from "../services/native-runtime/runtime-context.js";
const support = await getEmbeddedPostgresTestSupport();
const describeDatabase = support.supported ? describe : describe.skip;
describeDatabase("environment managed skills", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: Db;
let home: string;
let companyId: string;
let pluginId: string;
let manifest: PaperclipPluginManifestV1;
let environment: { driver: string; config: Record<string, unknown> };
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("paperclip-environment-skills-"); db = createDb(database.connectionString);
home = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-environment-skills-"));
}, 90_000);
afterAll(async () => { await database?.cleanup(); if (home) {
const release = async (directory: string): Promise<void> => {
await fs.chmod(directory, 0o700);
for (const entry of await fs.readdir(directory, { withFileTypes: true })) if (entry.isDirectory()) await release(path.join(directory, entry.name));
};
await release(home); await fs.rm(home, { recursive: true, force: true });
} });
afterEach(() => vi.unstubAllEnvs());
beforeEach(async () => {
vi.stubEnv("PAPERCLIP_HOME", home);
companyId = randomUUID(); pluginId = randomUUID();
manifest = { id: `fixture.${pluginId}`, apiVersion: 1, version: "1.0.0", displayName: "Desktop", description: "Fixture", author: "Tests", categories: ["automation"],
capabilities: ["environment.drivers.register", "skills.managed", "agents.lifecycle.manage", "events.subscribe"],
resourceLifecycle: ["agent_runtime"], entrypoints: { worker: "worker.js" },
environmentDrivers: [{ driverKey: "desktop", displayName: "Desktop", skillKeys: ["computer-use"], configSchema: {} }],
skills: [{ skillKey: "computer-use", displayName: "Computer use", slug: "computer-use",
markdown: "---\nname: computer-use\ndescription: Use the installed desktop tools.\n---\n\nRead references/linux.md.",
files: [{ path: "references/linux.md", content: "Use the installed cua-driver." }] }] };
await db.insert(companies).values({ id: companyId, name: "Environment skills", issuePrefix: `E${companyId.slice(0, 6)}` });
await db.insert(plugins).values({ id: pluginId, pluginKey: manifest.id, packageName: "fixture", version: "1.0.0", status: "ready", manifestJson: manifest });
environment = { driver: "plugin", config: { pluginKey: manifest.id, driverKey: "desktop", driverConfig: {} } };
});
it("installs the company skill and delivers its versioned files through runtime sync and the native snapshot", async () => {
const config = { paperclipSkillSync: { desiredSkills: [] } };
const [selection, concurrent] = await Promise.all([environmentSkillConfig(db, companyId, environment, config), environmentSkillConfig(db, companyId, environment, config)]);
expect(concurrent).toEqual(selection);
const selected = selection.config;
const [skill] = await db.select().from(companySkills).where(and(eq(companySkills.companyId, companyId), eq(companySkills.key, `plugin/fixture-${pluginId}/computer-use`)));
expect(selected).toMatchObject({ paperclipSkillSync: { desiredSkills: [skill.key] } });
expect(config.paperclipSkillSync.desiredSkills).toEqual([]);
const [env] = await db.insert(environments).values({ name: "Desktop", ...environment }).returning();
const [agent] = await db.insert(agents).values({ companyId, name: "Worker", adapterType: "paperclip_runner", defaultEnvironmentId: env.id,
lifecycleRequiredPluginIds: [pluginId], adapterConfig: config }).returning();
const state = await pluginAgentRuntimeState(db, pluginId, companyId, agent.id);
expect(state!.skills).toEqual([expect.objectContaining({ key: skill.key, runtimeName: expect.stringMatching(/^plugin-.*-computer-use--/), versionId: expect.any(String) })]);
await withSkillActor({ type: "agent", agentId: agent.id, companyId, source: "agent_key" }, async () => {
await companySkillService(db).withRuntimeSkillEntries(companyId, { selectionConfig: selected, snapshotLatest: true }, async entries => {
const context = await buildNativeRuntimeContext({ db, agent, runId: randomUUID(), runtimeConfig: selected, runtimeSkillEntries: entries });
expect(context.skills).toEqual([expect.objectContaining({ key: skill.key, runtimeName: state!.skills[0].runtimeName, versionId: state!.skills[0].versionId })]);
expect(await fs.readFile(path.join(context.skills[0].bundle.rootPath, "references/linux.md"), "utf8")).toContain("cua-driver");
});
});
await db.update(agents).set({ defaultEnvironmentId: null }).where(eq(agents.id, agent.id));
await instanceSettingsService(db).update({ defaultEnvironmentId: env.id });
expect((await pluginAgentRuntimeState(db, pluginId, companyId, agent.id))!.skills).toEqual(state!.skills);
await instanceSettingsService(db).update({ defaultEnvironmentId: null });
expect((await pluginAgentRuntimeState(db, pluginId, companyId, agent.id))!.skills).toEqual([]);
expect((await pluginAgentRuntimeState(db, pluginId, companyId, agent.id, env.id))!.skills).toEqual(state!.skills);
await expect(pluginAgentRuntimeState(db, pluginId, companyId, agent.id, randomUUID())).rejects.toMatchObject({ status: 422 });
const invalidSkill = { skillKey: "new-invalid", displayName: "New invalid skill", markdown: "---\nname: new-invalid\nmetadata:\n sources:\n - kind: github-dir\n repo: fixture/skills\n---\nUnpinned." };
const changedManifest = { ...manifest, skills: [...manifest.skills!, invalidSkill], environmentDrivers: manifest.environmentDrivers!.map(driver => ({ ...driver, skillKeys: [...driver.skillKeys!, "new-invalid"] })) };
await db.update(plugins).set({ manifestJson: changedManifest }).where(eq(plugins.id, pluginId));
expect((await pluginAgentRuntimeState(db, pluginId, companyId, agent.id, env.id))!.skills).toEqual(state!.skills);
await expect(environmentSkillConfig(db, companyId, environment, config)).rejects.toThrow(/pinned Git commit/);
await db.update(plugins).set({ manifestJson: manifest }).where(eq(plugins.id, pluginId));
const pinned = { paperclipSkillSync: { desiredSkills: [{ key: skill.key, versionId: state!.skills[0].versionId }] } };
expect((await environmentSkillConfig(db, companyId, environment, pinned)).config).toEqual(pinned);
await db.update(companySkills).set({ markdown: "Agent customization" }).where(eq(companySkills.id, skill.id));
await environmentSkillConfig(db, companyId, environment, config);
expect((await db.select().from(companySkills).where(eq(companySkills.id, skill.id)))[0].markdown).toBe("Agent customization");
});
it("installs and refreshes environment skills through lifecycle reconciliation before any run", async () => {
const [env] = await db.insert(environments).values({ name: randomUUID(), ...environment }).returning();
const [agent] = await db.insert(agents).values({ companyId, name: "Background worker", adapterType: "paperclip_runner", defaultEnvironmentId: env.id,
lifecycleRequiredPluginIds: [pluginId], adapterConfig: { paperclipSkillSync: { desiredSkills: [] } } }).returning();
expect((await pluginAgentRuntimeState(db, pluginId, companyId, agent.id))!.skills).toEqual([]);
const states = await Promise.all([1, 2].map(() => pluginAgentRuntimeState(db, pluginId, companyId, agent.id, undefined, true)));
expect(states[0]!.skills).toEqual(states[1]!.skills);
const [skill] = await db.select().from(companySkills).where(and(eq(companySkills.companyId, companyId), eq(companySkills.key, `plugin/fixture-${pluginId}/computer-use`)));
expect(skill.slug).toMatch(/^plugin-.*-computer-use$/);
const runtime = states[0]!.skills[0];
expect(await fs.readFile(path.join(runtime.source, "SKILL.md"), "utf8")).toContain(`name: "${skill.slug}"`);
const events = () => db.select().from(resourceLifecycleEvents).where(and(eq(resourceLifecycleEvents.companyId, companyId), eq(resourceLifecycleEvents.resourceType, "agent_runtime")));
const before = (await events()).length;
const edited = skill.markdown + "\nCompany edit.";
await fs.chmod(path.join(skill.sourceLocator!, "SKILL.md"), 0o600);
await fs.writeFile(path.join(skill.sourceLocator!, "SKILL.md"), edited);
await db.update(companySkills).set({ markdown: edited }).where(eq(companySkills.id, skill.id));
expect((await events()).slice(before).map(event => event.resourceId)).toEqual([agent.id]);
const refreshed = (await pluginAgentRuntimeState(db, pluginId, companyId, agent.id, undefined, true))!.skills[0];
expect(refreshed.versionId).not.toBe(runtime.versionId);
expect(await fs.readFile(path.join(refreshed.source, "SKILL.md"), "utf8")).toContain("Company edit.");
const settled = (await events()).length;
await pluginAgentRuntimeState(db, pluginId, companyId, agent.id, undefined, true);
expect(await events()).toHaveLength(settled);
const changedManifest = { ...manifest, skills: [...manifest.skills!, { skillKey: "extra", displayName: "Extra" }],
environmentDrivers: manifest.environmentDrivers!.map(driver => ({ ...driver, skillKeys: [...driver.skillKeys!, "extra"] })) };
await db.update(plugins).set({ manifestJson: changedManifest }).where(eq(plugins.id, pluginId));
expect((await events()).slice(settled).map(event => event.resourceId)).toEqual([agent.id]);
expect((await pluginAgentRuntimeState(db, pluginId, companyId, agent.id, undefined, true))!.skills).toHaveLength(2);
const saved = await db.select().from(agents).where(eq(agents.id, agent.id));
expect(saved[0].adapterConfig).toEqual(agent.adapterConfig);
await db.delete(companySkills).where(eq(companySkills.id, skill.id));
expect((await pluginAgentRuntimeState(db, pluginId, companyId, agent.id, undefined, true))!.skills).toHaveLength(2);
});
it("queues background delivery for inherited defaults and changed environment requirements", async () => {
const [env] = await db.insert(environments).values({ name: randomUUID(), ...environment }).returning();
const [agent] = await db.insert(agents).values({ companyId, name: "Inherited worker", adapterType: "paperclip_runner", lifecycleRequiredPluginIds: [pluginId] }).returning();
const events = () => db.select().from(resourceLifecycleEvents).where(and(eq(resourceLifecycleEvents.companyId, companyId), eq(resourceLifecycleEvents.resourceType, "agent_runtime")));
let before = (await events()).length;
await instanceSettingsService(db).update({ defaultEnvironmentId: env.id });
expect((await events()).slice(before).map(event => event.resourceId)).toEqual([agent.id]);
await pluginAgentRuntimeState(db, pluginId, companyId, agent.id, undefined, true);
before = (await events()).length;
const [settings] = await db.insert(pluginCompanySettings).values({ companyId, pluginId, enabled: true }).returning();
for (let change = 0; change < 3; change++) {
await db.update(pluginCompanySettings).set({ settingsJson: { localFolders: { path: `fixture-${change}` } } }).where(eq(pluginCompanySettings.id, settings.id));
}
expect(await events()).toHaveLength(before);
await db.update(pluginCompanySettings).set({ enabled: false }).where(eq(pluginCompanySettings.id, settings.id));
expect((await events()).slice(before).map(event => event.resourceId)).toEqual([agent.id]);
await db.update(pluginCompanySettings).set({ enabled: true }).where(eq(pluginCompanySettings.id, settings.id));
expect((await events()).slice(before).map(event => event.resourceId)).toEqual([agent.id, agent.id]);
before = (await events()).length;
await db.delete(pluginCompanySettings).where(eq(pluginCompanySettings.id, settings.id));
expect(await events()).toHaveLength(before);
await expect(db.transaction(async tx => {
await tx.update(environments).set({ config: { ...environment.config, driverKey: "unrelated" } }).where(eq(environments.id, env.id));
throw new Error("rollback");
})).rejects.toThrow("rollback");
expect(await events()).toHaveLength(before);
await db.update(environments).set({ config: { ...environment.config, driverKey: "unrelated" } }).where(eq(environments.id, env.id));
expect((await events()).slice(before).map(event => event.resourceId)).toEqual([agent.id]);
expect((await pluginAgentRuntimeState(db, pluginId, companyId, agent.id, undefined, true))!.skills).toEqual([]);
before = (await events()).length;
await instanceSettingsService(db).update({ defaultEnvironmentId: null });
expect((await events()).slice(before).map(event => event.resourceId)).toEqual([agent.id]);
});
it("delivers the required plugin skill and reports a same-name company assignment as shadowed", async () => {
const name = `plugin-${pluginId}-computer-use`;
const original = await companySkillService(db).createLocalSkill(companyId, { name, markdown: `---\nname: ${name}\n---\nCompany instructions.\n` });
const config = { paperclipSkillSync: { desiredSkills: [original.key] } };
const [env] = await db.insert(environments).values({ name: randomUUID(), ...environment }).returning();
const [agent] = await db.insert(agents).values({ companyId, name: "Conflicting worker", adapterType: "paperclip_runner", defaultEnvironmentId: env.id,
lifecycleRequiredPluginIds: [pluginId], adapterConfig: config }).returning();
const state = await pluginAgentRuntimeState(db, pluginId, companyId, agent.id, undefined, true);
const key = `plugin/fixture-${pluginId}/computer-use`;
expect(state!.skills.map(skill => skill.key)).toEqual([key]);
expect(state!.shadowedSkills).toEqual([{ key: original.key, shadowedBy: key }]);
for (const reference of [name, original.key.toUpperCase(), `${name}--${createHash("sha256").update(original.key).digest("hex").slice(0, 10)}`]) {
const aliased = await environmentSkillConfig(db, companyId, environment, { paperclipSkillSync: { desiredSkills: [reference] } });
expect(aliased.config).toMatchObject({ paperclipSkillSync: { desiredSkills: [key] } });
expect(aliased.shadowedSkills).toEqual(state!.shadowedSkills);
}
expect((await db.select().from(companySkills).where(eq(companySkills.id, original.id)))[0]).toMatchObject({ markdown: original.markdown, slug: original.slug });
expect((await db.select().from(agents).where(eq(agents.id, agent.id)))[0].adapterConfig).toEqual(config);
await db.update(agents).set({ defaultEnvironmentId: null }).where(eq(agents.id, agent.id));
const restored = await pluginAgentRuntimeState(db, pluginId, companyId, agent.id, undefined, true);
expect(restored!.skills.map(skill => skill.key)).toEqual([original.key]);
expect(restored!.shadowedSkills).toBeUndefined();
});
it("keeps installations company-scoped and rejects disabled providers", async () => {
const peerId = randomUUID();
await db.insert(companies).values({ id: peerId, name: "Peer", issuePrefix: `P${peerId.slice(0, 6)}` });
await environmentSkillConfig(db, companyId, environment, {});
await environmentSkillConfig(db, peerId, environment, {});
const peerSkills = await db.select().from(companySkills).where(and(eq(companySkills.companyId, peerId), eq(companySkills.key, `plugin/fixture-${pluginId}/computer-use`)));
expect(peerSkills).toHaveLength(1);
const skills = await db.select().from(companySkills).where(and(eq(companySkills.companyId, companyId), eq(companySkills.key, `plugin/fixture-${pluginId}/computer-use`)));
expect(peerSkills[0].id).not.toBe(skills[0].id);
await db.insert(pluginCompanySettings).values({ companyId, pluginId, enabled: false });
await expect(environmentSkillConfig(db, companyId, environment, {})).rejects.toMatchObject({ status: 422 });
expect(await environmentSkillConfig(db, companyId, { driver: "local", config: null }, {})).toEqual({ config: {}, skillKeys: [] });
expect(await environmentSkillConfig(db, companyId, { ...environment, config: { ...environment.config, driverKey: "unrelated" } }, {})).toEqual({ config: {}, skillKeys: [] });
});
});
@@ -59,16 +59,41 @@ databaseSuite("environment task lease authority", () => {
await db.update(environmentLeases).set({ cleanupStatus: "failed" }).where(eq(environmentLeases.id, oldLeaseId));
await expect(authorize()).rejects.toThrow("not authorized");
await db.update(environmentLeases).set({ cleanupStatus: "success" }).where(eq(environmentLeases.id, oldLeaseId));
let sessionStateAvailable = false;
const operations: string[] = [];
const workers = { getWorker: () => ({ supportedMethods: ["environmentTask"] }),
call: async (_id: string, _method: string, params: any) => ["read_state", "archive_state"].includes(params.operation.kind)
? { kind: "state", taskId: params.taskId, state: { schema: "paperclip.runner.durable.state.v1", lifecycle: "suspended",
...(params.operation.identity ?? params.operation.priorIdentity) } }
: params.operation.kind === "status"
? (operations.push("status"), { kind: "status", taskId: params.taskId, phase: "completed", executionStopped: true, sessionStateAvailable })
: { kind: "accepted", taskId: params.taskId },
} as unknown as PluginWorkerManager;
const runtime = environmentRuntimeService(db, { pluginWorkerManager: workers });
const runner = { runnerId: "runner", leaseId: oldLeaseId, sessionId: "session", runId: nextRunId,
turnId: "turn", itemId: "item", harness: "codex", protocolMin: 1, protocolMax: 3 };
const checkpointIdentity = { ...priorIdentity, turnId: "prior-turn", itemId: "prior-item" };
const [source] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, oldLeaseId));
await db.update(environmentLeases).set({ metadata: { ...source.metadata, runnerTaskSessionRetained: false } }).where(eq(environmentLeases.id, oldLeaseId));
await expect(authorize()).rejects.toThrow("not authorized");
await expect(resolvePluginTaskResume(db, { companyId, leaseId: nextLeaseId, priorIdentity, inspectCheckpoint: true })).resolves.toBe("old-task");
const inspect = () => runtime.task({ companyId, leaseId: nextLeaseId, operation: {
kind: "read_state", identity: checkpointIdentity, resumeFrom: "old-task",
} });
await expect(inspect()).rejects.toThrow("not authorized");
await expect(authorize()).rejects.toThrow("not authorized");
// Discovery cannot launch, and cannot bypass the original termination receipt.
await expect(runtime.task({ companyId, leaseId: nextLeaseId, operation: {
kind: "submit", preparedLaunchId: "fixture", projectIds: [], bootstrapTicket: "fixture", runner, resumeFrom: "old-task",
} })).rejects.toThrow("resume identity mismatch");
await db.update(environmentLeases).set({ cleanupStatus: "failed" }).where(eq(environmentLeases.id, oldLeaseId));
await expect(inspect()).rejects.toThrow("not authorized");
expect(operations).toEqual(["status"]);
await db.update(environmentLeases).set({ cleanupStatus: "success" }).where(eq(environmentLeases.id, oldLeaseId));
sessionStateAvailable = true;
await expect(inspect()).resolves.toMatchObject({ kind: "state" });
expect(operations).toEqual(["status", "status"]);
await expect(authorize()).resolves.toBe("old-task");
for (const operation of [
{ kind: "read_state" as const, identity: checkpointIdentity, resumeFrom: "old-task" },
{ kind: "archive_state" as const, priorIdentity: checkpointIdentity, archiveKey: "a".repeat(24), resumeFrom: "old-task" },
@@ -111,6 +136,12 @@ databaseSuite("environment task lease authority", () => {
const retryLeaseId = randomUUID();
await db.insert(environmentLeases).values({ id: retryLeaseId, companyId, environmentId, heartbeatRunId: thirdRunId,
status: "active", provider: prior.provider, providerLeaseId: "retry-task", metadata: pin });
const retryIdentity = { ...checkpointIdentity, runId: thirdRunId, turnId: "turn", itemId: "item" };
await expect(resolvePluginTaskResume(db, { companyId, leaseId: retryLeaseId,
priorIdentity: retryIdentity })).resolves.toBe("third-task");
await expect(runtime.task({ companyId, leaseId: retryLeaseId, operation: {
kind: "read_state", identity: retryIdentity, resumeFrom: "third-task",
} })).resolves.toMatchObject({ kind: "state", state: { ...retryIdentity, lifecycle: "suspended" } });
await expect(runtime.task({ companyId, leaseId: retryLeaseId, operation: { ...submit, projectIds: [], resumeFrom: "third-task" } })).resolves.toMatchObject({ kind: "accepted" });
const [retry] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, retryLeaseId));
await db.update(environmentLeases).set({ status: "released", cleanupStatus: "success", releasedAt: new Date(),
@@ -326,7 +326,7 @@ describe("GitHub external object provider", () => {
status: 403,
headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(Math.floor(Date.now() / 1000) + 120) },
}),
{ ok: false, liveness: "unreachable", errorCode: "github_rate_limited" },
{ ok: false, liveness: "rate_limited", errorCode: "github_rate_limited" },
],
])("maps %s responses to provider-safe results", async (_name, githubResponse, expected) => {
const provider = createGitHubExternalObjectProvider({} as any, {
@@ -498,7 +498,7 @@ describe("GitHub external object provider", () => {
expect(JSON.stringify(result)).not.toContain("http");
});
it("classifies a 404 as unreachable when the repository probe is rate-limited", async () => {
it("classifies a 404 as rate-limited when the repository probe is rate-limited", async () => {
const fetch = vi.fn(async (url: string) => {
if (url.endsWith("/repos/acme/app")) {
return new Response("", {
@@ -519,8 +519,8 @@ describe("GitHub external object provider", () => {
expect(result).toEqual(
expect.objectContaining({
ok: false,
liveness: "unreachable",
errorCode: "github_repo_probe_failed",
liveness: "rate_limited",
errorCode: "github_rate_limited",
}),
);
expect(result).not.toEqual(
@@ -528,6 +528,180 @@ describe("GitHub external object provider", () => {
);
expect(JSON.stringify(result)).not.toContain("http");
});
it("classifies an authenticated rate limit as rate-limited rather than unreachable", async () => {
const fetch = vi.fn(async () => new Response("", {
status: 403,
headers: { "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(Math.floor(Date.now() / 1000) + 120) },
}));
const provider = createGitHubExternalObjectProvider({} as any, {
fetch,
tokenProvider: async () => "ghp_secret",
});
const resolver = provider.resolvers.find((entry) => entry.objectType === "pull_request")!;
const result = await resolver.resolve({
companyId: "company-1",
object: githubObject("pull/42", "pull_request"),
});
expect(result).toEqual(
expect.objectContaining({ ok: false, liveness: "rate_limited", errorCode: "github_rate_limited" }),
);
expect(JSON.stringify(result)).not.toContain("ghp_secret");
});
it("classifies a 429 as rate-limited", async () => {
const fetch = vi.fn(async () => new Response("", {
status: 429,
headers: { "retry-after": "60" },
}));
const provider = createGitHubExternalObjectProvider({} as any, { fetch, tokenProvider: null });
const resolver = provider.resolvers.find((entry) => entry.objectType === "pull_request")!;
const result = await resolver.resolve({
companyId: "company-1",
object: githubObject("pull/42", "pull_request"),
});
expect(result).toEqual(
expect.objectContaining({ ok: false, liveness: "rate_limited", errorCode: "github_rate_limited" }),
);
});
it("limits a server-environment token to public repositories and never fetches a private object", async () => {
const fetch = vi.fn(async (url: string) => {
if (url.endsWith("/repos/acme/app")) return response({ private: true, full_name: "acme/app" });
return response({ state: "open", draft: false, merged: false, title: "Private PR" });
});
const provider = createGitHubExternalObjectProvider({} as any, {
fetch,
credentialProvider: async () => ({ token: "env-token", source: "server_env", secretName: null }),
});
const resolver = provider.resolvers.find((entry) => entry.objectType === "pull_request")!;
const result = await resolver.resolve({
companyId: "company-1",
object: githubObject("pull/42", "pull_request"),
});
expect(result).toEqual(
expect.objectContaining({
ok: false,
liveness: "auth_required",
errorCode: "github_repo_requires_company_token",
}),
);
expect(fetch).not.toHaveBeenCalledWith(expect.stringContaining("/pulls/42"), expect.anything());
expect(JSON.stringify(result)).not.toContain("env-token");
});
it("fails closed when a server-environment token probe does not confirm the repository is public", async () => {
const fetch = vi.fn(async (url: string) => {
// No `private` flag: public visibility is not positively confirmed.
if (url.endsWith("/repos/acme/app")) return response({ full_name: "acme/app" });
return response({ state: "open", draft: false, merged: false, title: "Unconfirmed PR" });
});
const provider = createGitHubExternalObjectProvider({} as any, {
fetch,
credentialProvider: async () => ({ token: "env-token", source: "server_env", secretName: null }),
});
const resolver = provider.resolvers.find((entry) => entry.objectType === "pull_request")!;
const result = await resolver.resolve({
companyId: "company-1",
object: githubObject("pull/42", "pull_request"),
});
expect(result).toEqual(
expect.objectContaining({
ok: false,
liveness: "auth_required",
errorCode: "github_repo_requires_company_token",
}),
);
expect(fetch).not.toHaveBeenCalledWith(expect.stringContaining("/pulls/42"), expect.anything());
expect(JSON.stringify(result)).not.toContain("env-token");
});
it("uses a server-environment token to resolve a public repository", async () => {
const fetch = vi.fn(async (url: string) => {
if (url.endsWith("/repos/acme/app")) return response({ private: false });
return response({ state: "open", draft: false, merged: false, title: "Public PR" });
});
const provider = createGitHubExternalObjectProvider({} as any, {
fetch,
credentialProvider: async () => ({ token: "env-token", source: "server_env", secretName: null }),
});
const resolver = provider.resolvers.find((entry) => entry.objectType === "pull_request")!;
const result = await resolver.resolve({
companyId: "company-1",
object: githubObject("pull/42", "pull_request"),
});
expect(result.ok).toBe(true);
expect(fetch).toHaveBeenCalledWith("https://api.github.com/repos/acme/app/pulls/42", expect.anything());
});
it("re-verifies public access for a server-environment token instead of reusing a cached verdict", async () => {
let repoPrivate = false;
const fetch = vi.fn(async (url: string) => {
if (url.endsWith("/repos/acme/app")) return response({ private: repoPrivate });
return response({ state: "open", draft: false, merged: false, title: "acme/app PR" });
});
const provider = createGitHubExternalObjectProvider({} as any, {
fetch,
credentialProvider: async () => ({ token: "env-token", source: "server_env", secretName: null }),
});
const resolver = provider.resolvers.find((entry) => entry.objectType === "pull_request")!;
// First refresh while the repository is public: the object resolves.
const publicResult = await resolver.resolve({
companyId: "company-1",
object: githubObject("pull/42", "pull_request"),
});
expect(publicResult.ok).toBe(true);
// The repository becomes private inside the probe-cache TTL. The server token
// still has access, but this company did not authorize it, so the second object
// must not reuse the cached "public" verdict to read private details.
repoPrivate = true;
const privateResult = await resolver.resolve({
companyId: "company-1",
object: githubObject("pull/43", "pull_request"),
});
expect(privateResult).toEqual(
expect.objectContaining({
ok: false,
liveness: "auth_required",
errorCode: "github_repo_requires_company_token",
}),
);
expect(fetch).not.toHaveBeenCalledWith(expect.stringContaining("/pulls/43"), expect.anything());
expect(JSON.stringify(privateResult)).not.toContain("env-token");
});
it("lets a company-scoped token resolve a private repository", async () => {
const fetch = vi.fn(async (url: string) => {
if (url.endsWith("/repos/acme/app")) return response({ private: true });
return response({ state: "open", draft: false, merged: false, title: "Private PR" });
});
const provider = createGitHubExternalObjectProvider({} as any, {
fetch,
credentialProvider: async () => ({ token: "company-token", source: "company_secret", secretName: "GITHUB_TOKEN" }),
});
const resolver = provider.resolvers.find((entry) => entry.objectType === "pull_request")!;
const result = await resolver.resolve({
companyId: "company-1",
object: githubObject("pull/42", "pull_request"),
});
expect(result.ok).toBe(true);
expect(fetch).toHaveBeenCalledWith("https://api.github.com/repos/acme/app/pulls/42", expect.anything());
});
});
describeEmbeddedPostgres("externalObjectService", () => {
@@ -98,13 +98,13 @@ rl.on("line", (line) => {
id: message.id,
result: {
ok: true,
supportedMethods: ["getData", "performAction"],
supportedMethods: ["getData", "performAction", "resourceLifecycle", "workspaceOperation"],
},
});
return;
}
if (method === "getData" || method === "performAction") {
if (["getData", "performAction", "resourceLifecycle", "workspaceOperation"].includes(method)) {
sendNestedHostRequest(message, message.paperclipInvocation?.id);
return;
}
@@ -12,6 +12,7 @@ import {
createIssueGitRemoteAuthProvider,
describeGitAuthFailure,
isGitHubHttpsRemoteUrl,
resolveGitHubApiCredential,
scrubGitCredentialText,
} from "../services/git-credentials.ts";
@@ -48,6 +49,32 @@ describe("isGitHubHttpsRemoteUrl", () => {
});
});
describe("resolveGitHubApiCredential", () => {
it("prefers a company secret over the server environment and marks it company-scoped", async () => {
const secrets = buildSecretsFake({ GH_TOKEN: "gh-token" });
const credential = await resolveGitHubApiCredential(fakeDb, "company-1", {
secrets,
env: { GITHUB_TOKEN: "env-token" },
});
expect(credential).toEqual({ token: "gh-token", source: "company_secret", secretName: "GH_TOKEN" });
});
it("falls back to the server environment and marks it server_env so callers can restrict it", async () => {
const secrets = buildSecretsFake({});
const credential = await resolveGitHubApiCredential(fakeDb, "company-1", {
secrets,
env: { GITHUB_TOKEN: "env-token" },
});
expect(credential).toEqual({ token: "env-token", source: "server_env", secretName: null });
});
it("returns null when neither a secret nor the environment provides a token", async () => {
const secrets = buildSecretsFake({});
const credential = await resolveGitHubApiCredential(fakeDb, "company-1", { secrets, env: {} });
expect(credential).toBeNull();
});
});
describe("createGitRemoteAuthProvider", () => {
const githubUrl = "https://github.com/example/repo.git";
@@ -82,6 +82,60 @@ describe("GitHub grant metadata", () => {
});
});
it("does not count a suspended installation as repository access", async () => {
// GitHub still lists a suspended installation and its repositories for the
// user token, but the token cannot write to them or read private ones.
const request = vi.fn<typeof fetch>(async (input) => {
const url = new URL(String(input));
if (url.pathname === "/user") return json({ id: 42, login: "octocat" });
if (url.pathname === "/user/installations") {
return json({ installations: [
{ id: 101, repository_selection: "all", suspended_at: "2026-10-22T01:33:41Z", html_url: "https://github.com/organizations/paperclipai/settings/installations/101", account: { login: "paperclipai" } },
{ id: 102, repository_selection: "selected", suspended_at: null, account: { login: "octocat" } },
] });
}
if (url.pathname === "/user/installations/101/repositories") {
return json({ repositories: [{ id: 1, full_name: "paperclipai/a" }] });
}
if (url.pathname === "/user/installations/102/repositories") {
return json({ repositories: [{ id: 2, full_name: "octocat/b" }] });
}
throw new Error(`Unexpected GitHub path: ${url.pathname}`);
});
await expect(loadGitHubGrantMetadata("ghu_secret", request)).resolves.toMatchObject({
installationCount: 1,
repositoryCount: 1,
repositorySelection: "selected",
installationIds: ["102"],
installationOwnerLogins: ["octocat"],
repositories: [{ id: "2", fullName: "octocat/b", installationId: "102" }],
});
});
it("points an all-suspended account at the suspended installation to restore access", async () => {
const request = vi.fn<typeof fetch>(async (input) => {
const url = new URL(String(input));
if (url.pathname === "/user") return json({ id: 42, login: "octocat" });
if (url.pathname === "/user/installations") {
return json({ installations: [
{ id: 101, app_slug: "paperclip-staging", repository_selection: "all", suspended_at: "2026-10-22T01:33:41Z", html_url: "https://github.com/organizations/paperclipai/settings/installations/101" },
] });
}
if (url.pathname === "/user/installations/101/repositories") {
return json({ repositories: [{ id: 1, full_name: "paperclipai/a" }] });
}
throw new Error(`Unexpected GitHub path: ${url.pathname}`);
});
await expect(loadGitHubGrantMetadata("ghu_secret", request)).rejects.toMatchObject({
message: expect.stringContaining("suspended"),
details: {
code: "github_installation_required",
installationUrl: "https://github.com/apps/paperclip-staging/installations/new",
managementUrl: "https://github.com/organizations/paperclipai/settings/installations/101",
},
});
});
it("does not report a partial repository list when a later page fails", async () => {
const request = vi.fn<typeof fetch>()
.mockResolvedValueOnce(json({ id: 42, login: "octocat" }))
@@ -0,0 +1,84 @@
import { describe, expect, it, vi } from "vitest";
import type { Db } from "@paperclipai/db";
import { loadGitHubGrantMetadata } from "../services/tool-access.js";
import { createConnectionHealth } from "../services/tool-access/catalog/health.js";
vi.mock("../services/tool-access/connections/projection.js", () => ({
toConnection: (row: { id: string; healthStatus: string; healthMessage: string | null }) => ({
id: row.id,
healthStatus: row.healthStatus,
healthMessage: row.healthMessage,
}),
}));
const SUSPENDED_INSTALLATION_URL = "https://github.com/organizations/paperclipai/settings/installations/101";
function json(value: unknown): Response {
return new Response(JSON.stringify(value), { headers: { "content-type": "application/json" } });
}
// GitHub's view of an account whose only installation is suspended.
const suspendedGitHub = vi.fn<typeof fetch>(async (input) => {
const url = new URL(String(input));
if (url.pathname === "/user") return json({ id: 42, login: "octocat" });
if (url.pathname === "/user/installations") {
return json({ installations: [
{ id: 101, app_slug: "paperclip-staging", repository_selection: "all", suspended_at: "2026-10-22T01:33:41Z", html_url: SUSPENDED_INSTALLATION_URL },
] });
}
if (url.pathname === "/user/installations/101/repositories") {
return json({ repositories: [{ id: 1, full_name: "paperclipai/a" }] });
}
throw new Error(`Unexpected GitHub path: ${url.pathname}`);
});
function githubConnectionHealth() {
const connection = {
id: "conn-1",
companyId: "company-1",
connectionPurpose: "tools",
transport: "mcp_remote",
credentialPolicy: "shared",
config: { sourceTemplateKey: "github", oauth: { connectorProfile: "github.code" } },
healthStatus: "ok",
healthMessage: null,
};
const db = {
select: () => ({ from: () => ({ where: async () => [{ id: "grant-1", kind: "organization", status: "active" }] }) }),
update: () => ({
set: (values: Record<string, unknown>) => ({
where: () => ({ returning: async () => [{ ...connection, ...values }] }),
}),
}),
} as unknown as Db;
return createConnectionHealth(db, {
now: () => new Date(),
audit: vi.fn(async () => undefined),
getConnectionRow: async () => connection as never,
discovery: {} as never,
setupPolicy: { assertConnectorConnectionSetupEnabled: async () => undefined } as never,
resolveCredentialHeaders: vi.fn() as never,
refreshManagedGitHubGrantAccess: (async () => {
await loadGitHubGrantMetadata("ghu_secret", suspendedGitHub);
}) as never,
ensureRuntimeSlot: vi.fn() as never,
stdioTemplateId: vi.fn() as never,
});
}
describe("GitHub Refresh access recovery", () => {
it("keeps the suspended installation's settings link on the health-check failure", async () => {
const { checkConnectionHealth } = githubConnectionHealth();
await expect(checkConnectionHealth("conn-1", { actorType: "user", actorId: "user-1" } as never)).rejects.toMatchObject({
status: 422,
message: expect.stringContaining("suspended"),
details: {
code: "github_installation_required",
managementUrl: SUSPENDED_INSTALLATION_URL,
installationUrl: "https://github.com/apps/paperclip-staging/installations/new",
connection: { id: "conn-1", healthStatus: "error", healthMessage: expect.stringContaining("suspended") },
},
});
});
});
@@ -1,3 +1,4 @@
import { githubCredentialsFixture } from "./helpers/github-credentials-fixture.js";
import { createNativeGitHubAccess } from "../services/native-runtime/native-github-access.js";
import express from "express";
import request from "supertest";
@@ -71,129 +72,7 @@ const support = await getEmbeddedPostgresTestSupport();
await database?.cleanup();
vi.unstubAllEnvs();
}, 60_000);
async function seed() {
const companyId = randomUUID(),
agentId = randomUUID(),
runId = randomUUID(),
issueId = randomUUID();
await db.insert(companies).values({
id: companyId,
name: companyId,
issuePrefix: companyId.slice(0, 8),
});
await db.insert(agents).values({
id: agentId,
companyId,
name: "Shared",
role: "engineer",
adapterType: "codex_local",
});
await db
.insert(issues)
.values({ id: issueId, companyId, title: "Identity test" });
await db.insert(heartbeatRuns).values({
id: runId,
companyId,
agentId,
status: "running",
contextSnapshot: { issueId },
});
await db.insert(companyMemberships).values(
["A", "B"].map((principalId) => ({
companyId,
principalType: "user",
principalId,
status: "active",
membershipRole: "member",
})),
);
await initializeRunIdentity(db, {
companyId,
runId,
responsibleUserId: "A",
cause: "instruction",
});
return { companyId, agentId, runId, issueId };
}
async function grant(
input: Awaited<ReturnType<typeof seed>>,
user: string,
dedicated = false,
) {
const applicationId = randomUUID(),
connectionId = randomUUID(),
secretId = randomUUID(),
definitionId = randomUUID(),
id = randomUUID();
await db.insert(toolApplications).values({
id: applicationId,
companyId: input.companyId,
name: applicationId,
type: "mcp_http",
});
await db.insert(toolConnections).values({
id: connectionId,
companyId: input.companyId,
applicationId,
name: connectionId,
uid: connectionId,
transport: "mcp_remote",
status: "active",
enabled: true,
credentialPolicy: dedicated ? "per_agent" : "per_user",
config: { sourceTemplateKey: "github" },
});
await db.insert(toolConnectionInstalls).values({
companyId: input.companyId,
connectionId,
targetType: "agent",
targetId: input.agentId,
});
if (!dedicated)
await db.insert(userSecretDefinitions).values({
id: definitionId,
companyId: input.companyId,
key: definitionId,
name: "Test GitHub",
});
await db.insert(companySecrets).values({
id: secretId,
companyId: input.companyId,
key: secretId,
name: `Test token ${secretId}`,
scope: dedicated ? "company" : "user",
ownerUserId: dedicated ? null : user,
userSecretDefinitionId: dedicated ? null : definitionId,
});
await db.insert(connectionGrants).values({
id,
companyId: input.companyId,
connectionId,
kind: dedicated ? "agent" : "user",
subjectUserId: dedicated ? null : user,
subjectAgentId: dedicated ? input.agentId : null,
status: "active",
credentialSecretRefs: [
{
secretId,
configPath: "oauth.access_token",
versionSelector: "latest",
},
],
providerTenant: {
github: {
userId: user,
login: user,
installationCount: 1,
repositoryCount: 1,
repositorySelection: "selected",
installationIds: ["1"],
installationOwnerLogins: [user],
},
},
});
return { id, connectionId, secretId, definitionId };
}
const { seed, grant, switchTo } = githubCredentialsFixture(() => db);
it.each(["config", "transportConfig"] as const)("reads only current GitHub identity connections via %s", async location => {
const input = await seed(), selected = await grant(input, "A");
const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, selected.connectionId));
@@ -260,24 +139,6 @@ const support = await getEmbeddedPostgresTestSupport();
} finally { capture.flush(); await observed.$client.end(); }
});
async function switchTo(
input: Awaited<ReturnType<typeof seed>>,
user: string,
) {
const id = randomUUID();
await db.insert(issueComments).values({
id,
companyId: input.companyId,
issueId: input.issueId,
authorUserId: user,
body: "Next instruction",
});
const context = await reserveSteeredIdentity(db, {
...input,
messageId: id,
});
await acceptSteeredIdentity(db, context!);
}
it("resolves A → B → A without retaining tokens, and records only redacted diagnostics", async () => {
const input = await seed();
await grant(input, "A");
@@ -7,7 +7,7 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { eq } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { agents, authUsers, companies, companyMemberships, companySkills, createDb, heartbeatRunEvents, heartbeatRuns, issues, projects } from "@paperclipai/db";
import { agents, authUsers, companies, companyMemberships, companySkills, createDb, heartbeatRunEvents, heartbeatRuns, issues, projects, plugins, environments } from "@paperclipai/db";
import { companySkillService } from "../services/company-skills.js";
import { withSkillVersionCacheLock } from "../services/skill-version-cache.js";
import { registerServerAdapter, unregisterServerAdapter, type AdapterExecutionContext } from "../adapters/index.js";
@@ -220,24 +220,71 @@ describePostgres("heartbeat execution configuration through adapter dispatch", (
}
});
async function configuration(f: Awaited<ReturnType<typeof seed>>, config: Record<string, unknown>, snapshot: Record<string, unknown> = {}, type = "paperclip_runner", explicitTaskDirectory = false, requestedExecutionWorkspaceMode: HeartbeatExecutionConfigurationInput["policy"]["requestedExecutionWorkspaceMode"] = "shared_workspace") {
async function configuration(f: Awaited<ReturnType<typeof seed>>, config: Record<string, unknown>, snapshot: Record<string, unknown> = {}, type = "paperclip_runner", explicitTaskDirectory = false, requestedExecutionWorkspaceMode: HeartbeatExecutionConfigurationInput["policy"]["requestedExecutionWorkspaceMode"] = "shared_workspace", selectedEnvironmentForConfig: HeartbeatExecutionConfigurationInput["environment"]["selectedEnvironmentForConfig"] = null) {
const [agent] = await db.update(agents).set({ adapterType: type, adapterConfig: config }).where(eq(agents.id, f.agentId)).returning();
const [run] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, issueId: f.issueId, scopeKind: "issue", status: "running", contextSnapshot: snapshot }).returning();
const resolvedInstanceSettings = await instanceSettingsService(db).get();
return { run, prepare: () => prepareHeartbeatExecutionConfiguration(db, {
const appendRunEvent = vi.fn();
return { run, appendRunEvent, prepare: () => prepareHeartbeatExecutionConfiguration(db, {
run, agent,
task: { issueId: f.issueId, context: { ...snapshot, issueId: f.issueId }, responsibleUserId: null,
acceptedPlanContinuationWake: false, acceptedPlanWakeRoutingDecision: null,
taskProjectContext: null, routineEnvContext: { routineId: null, env: null, responsibleUserId: null } },
config: { sourceWorkspaceConfig: config, aiBinding: undefined },
policy: { trustPreset: { kind: "standard", preset: "standard", boundary: null, sourcePresets: {} }, useIsolatedTaskDirectory: false, explicitTaskDirectory, requestedExecutionWorkspaceMode },
environment: { selectedEnvironmentId: null, selectedEnvironmentForConfig: null,
environment: { selectedEnvironmentId: selectedEnvironmentForConfig?.id ?? null, selectedEnvironmentForConfig,
resolvedInstanceSettings, persistedNativeExecutionInput: null },
services: { secretsSvc: secretService(db), companySkills: companySkillService(db), appendRunEvent: vi.fn(), finalizeAiConnectionBusyDeferral: vi.fn() },
services: { secretsSvc: secretService(db), companySkills: companySkillService(db), appendRunEvent, finalizeAiConnectionBusyDeferral: vi.fn() },
onFailureSecretsResolved: () => {}, onManagedAiRuntimeAcquired: () => {}, onIdentityRedactorPrepared: () => {},
}) };
}
it("does not install new environment declarations when recovering a saved skill selection", async () => {
const f = await seed(), pluginId = randomUUID(), pluginKey = `fixture.${randomUUID()}`;
await db.insert(plugins).values({ id: pluginId, pluginKey, packageName: "fixture", version: "1.0.0", status: "ready",
manifestJson: { id: pluginKey, apiVersion: 1, version: "1.0.0", displayName: "Fixture", description: "Fixture", author: "Tests", categories: ["automation"],
capabilities: ["environment.drivers.register", "skills.managed"], entrypoints: { worker: "worker.js" },
environmentDrivers: [{ driverKey: "tasks", displayName: "Tasks", configSchema: {}, skillKeys: ["new-invalid"] }],
skills: [{ skillKey: "new-invalid", displayName: "New invalid skill", markdown: "---\nname: new-invalid\nmetadata:\n sources:\n - kind: github-dir\n repo: fixture/skills\n---\nUnpinned." }] } });
const [environment] = await db.insert(environments).values({ name: "Fixture", driver: "plugin", config: { pluginKey, driverKey: "tasks", driverConfig: {} } }).returning();
const config = { paperclipSkillSync: { desiredSkills: [] } };
const restoring = await configuration(f, config, { skillVersions: {}, skillSelectionSnapshot: true }, "paperclip_runner", false, "shared_workspace", environment);
expect(await restoring.prepare()).toMatchObject({ prepared: true, runtimeSkillEntries: [] });
const fresh = await configuration(f, config, {}, "paperclip_runner", false, "shared_workspace", environment);
const rejected = await fresh.prepare().then(() => false, error => { expect(error.message).toMatch(/pinned Git commit/); return true; });
expect(rejected).toBe(true);
});
it("reports a shadowed assignment and captures only the required plugin skill", async () => {
const f = await seed(), pluginId = randomUUID(), pluginKey = `fixture.${randomUUID()}`;
const name = `plugin-${pluginKey.split(".").at(-1)}-desktop`;
const existing = await companySkillService(db).createLocalSkill(f.companyId, { name, markdown: `---\nname: ${name}\n---\nCompany skill.` });
await db.insert(plugins).values({ id: pluginId, pluginKey, packageName: "fixture", version: "1.0.0", status: "ready",
manifestJson: { id: pluginKey, apiVersion: 1, version: "1.0.0", displayName: "Fixture", description: "Fixture", author: "Tests", categories: ["automation"],
capabilities: ["environment.drivers.register", "skills.managed"], entrypoints: { worker: "worker.js" },
environmentDrivers: [{ driverKey: "tasks", displayName: "Tasks", configSchema: {}, skillKeys: ["desktop"] }],
skills: [{ skillKey: "desktop", displayName: "Desktop" }] } });
const [environment] = await db.insert(environments).values({ name: randomUUID(), driver: "plugin", config: { pluginKey, driverKey: "tasks" } }).returning();
await db.update(issues).set({ description: `Use [company skill](skill://${existing.id}).` }).where(eq(issues.id, f.issueId));
const config = { paperclipSkillSync: { desiredSkills: [existing.key] } };
const run = await configuration(f, config, {}, "paperclip_runner", false, "shared_workspace", environment);
const result = await run.prepare();
expect(result.prepared).toBe(true);
if (!result.prepared) throw new Error("Configuration did not finish");
const key = `plugin/${pluginKey.replaceAll(".", "-")}/desktop`;
expect(result.runtimeSkillEntries.map(skill => skill.key)).toEqual([key]);
expect(run.appendRunEvent).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ eventType: "skills.shadowed", level: "warn",
message: expect.stringContaining(existing.key), payload: { shadowedSkills: [{ key: existing.key, shadowedBy: key }] } }));
const [saved] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run.run.id));
expect(saved.contextSnapshot!.shadowedSkills).toEqual([{ key: existing.key, shadowedBy: key }]);
expect(Object.keys(saved.contextSnapshot!.skillVersions as object)).toEqual([key]);
const recovery = await configuration(f, config, saved.contextSnapshot!, "paperclip_runner", false, "shared_workspace", environment);
const resumed = await recovery.prepare();
expect(resumed.prepared).toBe(true);
if (!resumed.prepared) throw new Error("Recovery did not finish");
expect(resumed.runtimeSkillEntries.map(skill => skill.key)).toEqual([key]);
expect(recovery.appendRunEvent.mock.calls.some(([, event]) => event.eventType === "skills.shadowed")).toBe(false);
});
it("keeps default task-directory configuration stable when the directory is reused", async () => {
const f = await seed();
const initial = await (await configuration(f, {}, {}, "paperclip_runner", true)).prepare();
@@ -93,7 +93,7 @@ describeEmbeddedPostgres("heartbeat plugin environments", () => {
await stopDb?.();
});
it("dispatches a plugin-only project without Core workspace files through the native heartbeat boundary", async () => {
it("dispatches a plugin-owned account per-turn without Core workspace files through the native heartbeat boundary", async () => {
const companyId = randomUUID(), projectId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), sourceId = randomUUID();
const environmentId = randomUUID(), pluginId = randomUUID(), pluginKey = `test.tasks.${pluginId}`;
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-task-heartbeat-")); tempRoots.push(root);
@@ -112,11 +112,11 @@ describeEmbeddedPostgres("heartbeat plugin environments", () => {
capabilities: ["environment.drivers.register", "workspaces.manage", "events.subscribe"], resourceLifecycle: ["project"],
workspaceProvider: { modes: ["shared_workspace", "isolated_workspace", "operator_branch"], strategies: ["project_primary", "git_worktree"] },
entrypoints: { worker: "worker.js" },
environmentDrivers: [{ driverKey: "tasks", displayName: "Tasks", supportsTasks: true, configSchema: { type: "object" } }] } });
environmentDrivers: [{ driverKey: "tasks", displayName: "Tasks", supportsTasks: true, warmTaskVersion: 1, configSchema: { type: "object" } }] } });
await db.insert(environments).values({ id: environmentId, companyId, name: "Tasks", driver: "plugin", status: "active",
config: { pluginKey, driverKey: "tasks", driverConfig: {} } });
await db.insert(agents).values({ id: agentId, companyId, name: "Task agent", role: "engineer", status: "idle",
adapterType: "paperclip_runner", adapterConfig: { provider: "codex", model: "gpt-6.1-sol" }, runtimeConfig: {},
adapterType: "paperclip_runner", adapterConfig: { provider: "codex", model: "gpt-6.1-sol", lifecycleMode: "warm" }, runtimeConfig: {},
defaultEnvironmentId: environmentId, permissions: {} });
await db.insert(issues).values({ id: issueId, companyId, projectId, projectWorkspaceId: sourceId, title: "Task-only dispatch", status: "in_progress",
assigneeAgentId: agentId, issueNumber: 1, identifier: "TASK-1" });
@@ -129,14 +129,15 @@ describeEmbeddedPostgres("heartbeat plugin environments", () => {
if (method === "environmentReleaseLease" || method === "environmentDestroyLease") return undefined;
throw new Error(`Unexpected task provider call: ${method}`);
});
const workerManager = { isRunning: () => true, getWorker: () => ({ supportedMethods: ["workspaceOperation", "environmentTask", "environmentAcquireLease", "environmentReleaseLease", "environmentDestroyLease"] }), call } as unknown as PluginWorkerManager;
const workerManager = { isRunning: () => true, getWorker: () => ({ supportedMethods: ["workspaceOperation", "environmentTask", "environmentAcquireLease", "environmentResumeLease", "environmentReleaseLease", "environmentDestroyLease"] }), call } as unknown as PluginWorkerManager;
const entered = vi.fn(() => { throw new Error("synthetic_native_boundary_reached"); });
const heartbeat = heartbeatService(db, { pluginWorkerManager: workerManager, nativeSessionBackendFactory: entered });
heartbeats.push(heartbeat);
const run = await heartbeat.wakeup(agentId, { source: "on_demand", triggerDetail: "manual", contextSnapshot: { issueId, projectId } });
expect(run).not.toBeNull();
await vi.waitFor(async () => { expect((await heartbeat.getRun(run!.id))?.status).toBe("failed"); }, { timeout: 10_000 });
expect(entered).toHaveBeenCalledWith(expect.objectContaining({ binding: expect.objectContaining({ runId: run!.id, companyId, issueId }) }));
expect(entered).toHaveBeenCalledWith(expect.objectContaining({ binding: expect.objectContaining({ runId: run!.id, companyId, issueId }),
session: expect.objectContaining({ lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } }) }));
expect((await heartbeat.getRun(run!.id))?.error).toContain("synthetic_native_boundary_reached");
await heartbeat.drainActiveRunExecutions();
expect(call).toHaveBeenCalledWith(pluginId, "environmentDestroyLease", expect.objectContaining({ providerLeaseId: "heartbeat-task-attempt" }));
@@ -0,0 +1,151 @@
import { randomUUID } from "node:crypto";
import { agents, companies, companyMemberships, companySecrets, connectionGrants, heartbeatRuns, issueComments, issues, toolApplications, toolConnectionInstalls, toolConnections, userSecretDefinitions, type Db } from "@paperclipai/db";
import { initializeRunIdentity, reserveSteeredIdentity, acceptSteeredIdentity } from "../../services/run-identity.js";
export function githubCredentialsFixture(getDb: () => Db) {
async function seed() {
const db = getDb();
const companyId = randomUUID(),
agentId = randomUUID(),
runId = randomUUID(),
issueId = randomUUID();
await db.insert(companies).values({
id: companyId,
name: companyId,
issuePrefix: companyId.slice(0, 8),
});
await db.insert(agents).values({
id: agentId,
companyId,
name: "Shared",
role: "engineer",
adapterType: "codex_local",
});
await db
.insert(issues)
.values({ id: issueId, companyId, title: "Identity test" });
await db.insert(heartbeatRuns).values({
id: runId,
companyId,
agentId,
status: "running",
contextSnapshot: { issueId },
});
await db.insert(companyMemberships).values(
["A", "B"].map((principalId) => ({
companyId,
principalType: "user",
principalId,
status: "active",
membershipRole: "member",
})),
);
await initializeRunIdentity(db, {
companyId,
runId,
responsibleUserId: "A",
cause: "instruction",
});
return { companyId, agentId, runId, issueId };
}
async function grant(
input: Awaited<ReturnType<typeof seed>>,
user: string,
dedicated = false,
) {
const db = getDb();
const applicationId = randomUUID(),
connectionId = randomUUID(),
secretId = randomUUID(),
definitionId = randomUUID(),
id = randomUUID();
await db.insert(toolApplications).values({
id: applicationId,
companyId: input.companyId,
name: applicationId,
type: "mcp_http",
});
await db.insert(toolConnections).values({
id: connectionId,
companyId: input.companyId,
applicationId,
name: connectionId,
uid: connectionId,
transport: "mcp_remote",
status: "active",
enabled: true,
credentialPolicy: dedicated ? "per_agent" : "per_user",
config: { sourceTemplateKey: "github" },
});
await db.insert(toolConnectionInstalls).values({
companyId: input.companyId,
connectionId,
targetType: "agent",
targetId: input.agentId,
});
if (!dedicated)
await db.insert(userSecretDefinitions).values({
id: definitionId,
companyId: input.companyId,
key: definitionId,
name: "Test GitHub",
});
await db.insert(companySecrets).values({
id: secretId,
companyId: input.companyId,
key: secretId,
name: `Test token ${secretId}`,
scope: dedicated ? "company" : "user",
ownerUserId: dedicated ? null : user,
userSecretDefinitionId: dedicated ? null : definitionId,
});
await db.insert(connectionGrants).values({
id,
companyId: input.companyId,
connectionId,
kind: dedicated ? "agent" : "user",
subjectUserId: dedicated ? null : user,
subjectAgentId: dedicated ? input.agentId : null,
status: "active",
credentialSecretRefs: [
{
secretId,
configPath: "oauth.access_token",
versionSelector: "latest",
},
],
providerTenant: {
github: {
userId: user,
login: user,
installationCount: 1,
repositoryCount: 1,
repositorySelection: "selected",
installationIds: ["1"],
installationOwnerLogins: [user],
},
},
});
return { id, connectionId, secretId, definitionId };
}
async function switchTo(
input: Awaited<ReturnType<typeof seed>>,
user: string,
) {
const db = getDb();
const id = randomUUID();
await db.insert(issueComments).values({
id,
companyId: input.companyId,
issueId: input.issueId,
authorUserId: user,
body: "Next instruction",
});
const context = await reserveSteeredIdentity(db, {
...input,
messageId: id,
});
await acceptSteeredIdentity(db, context!);
}
return { seed, grant, switchTo };
}
+90 -1
View File
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { execute } from "@paperclipai/adapter-pi-local/server";
import { discoverPiModels, execute, testEnvironment } from "@paperclipai/adapter-pi-local/server";
async function writeFakePiCommand(commandPath: string): Promise<void> {
const script = `#!/usr/bin/env node
@@ -207,4 +207,93 @@ describe("pi_local execute", () => {
await fs.rm(root, { recursive: true, force: true });
}
});
it("isolates server secrets during execution, model discovery, and environment probes", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-pi-env-"));
const workspace = path.join(root, "workspace");
const commandPath = path.join(root, "pi");
const envDumpPath = path.join(root, "captured-env.json");
await fs.mkdir(workspace, { recursive: true });
await fs.writeFile(commandPath, `#!/usr/bin/env node
require("node:fs").appendFileSync(${JSON.stringify(envDumpPath)}, JSON.stringify({ args: process.argv.slice(2), env: process.env }) + "\\n");
if (process.argv.includes("--list-models")) {
console.log("provider model");
console.log("google gemini-3-flash-preview");
process.exit(0);
}
console.log(JSON.stringify({ type: "agent_start" }));
console.log(JSON.stringify({ type: "turn_end", message: { role: "assistant", content: [{ type: "text", text: "hello" }] }, toolResults: [] }));
console.log(JSON.stringify({ type: "agent_end", messages: [] }));
`, "utf8");
await fs.chmod(commandPath, 0o755);
const serverSecrets = {
PAPERCLIP_AGENT_JWT_SECRET: "server-jwt-secret",
PAPERCLIP_TOOL_ACTION_SIGNING_SECRET: "server-tool-action-secret",
PAPERCLIP_SECRETS_MASTER_KEY_FILE: "/server/master.key",
};
const permittedEnv = {
PAPERCLIP_RUNTIME_API_URL: "https://runtime.example.test",
PAPERCLIP_LISTEN_HOST: "127.0.0.1",
PAPERCLIP_LISTEN_PORT: "3100",
};
const inheritedEnv = { ...serverSecrets, ...permittedEnv };
const previous = { HOME: process.env.HOME, ...Object.fromEntries(Object.keys(inheritedEnv).map((k) => [k, process.env[k]])) };
process.env.HOME = root;
Object.assign(process.env, inheritedEnv);
try {
// Discover directly so execute/testEnvironment cannot pre-sanitize this input.
await discoverPiModels({ command: commandPath, cwd: workspace, env: { AGENT_SETTING: "kept" } });
await execute({
runId: "run-pi-env-leak",
agent: { id: "agent-env", companyId: "company-env", name: "Pi Agent", adapterType: "pi_local", adapterConfig: {} },
runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: null },
config: {
command: commandPath,
cwd: workspace,
model: "google/gemini-3-flash-preview",
promptTemplate: "Keep working.",
env: { AGENT_SETTING: "kept" },
},
context: {},
authToken: "run-jwt-token",
onLog: async () => {},
});
const diagnostics = await testEnvironment({
companyId: "company-env",
adapterType: "pi_local",
config: {
command: commandPath,
cwd: workspace,
model: "google/gemini-3-flash-preview",
env: { AGENT_SETTING: "kept" },
},
});
expect(diagnostics.status).toBe("pass");
const captures = (await fs.readFile(envDumpPath, "utf8")).trim().split("\n").map(
(line) => JSON.parse(line) as { args: string[]; env: Record<string, string> },
);
const discovery = captures.find(({ args }) => args.includes("--list-models"));
const execution = captures.find(({ env }) => env.PAPERCLIP_AGENT_ID === "agent-env");
const probe = captures.find(({ args }) => args.includes("Respond with hello."));
expect(discovery).toBeDefined();
expect(execution).toBeDefined();
expect(probe).toBeDefined();
for (const capture of [discovery!, execution!, probe!]) {
for (const key of Object.keys(serverSecrets)) expect(capture.env).not.toHaveProperty(key);
expect(capture.env.AGENT_SETTING).toBe("kept");
expect(capture.env).toMatchObject(permittedEnv);
}
expect(execution!.env.PAPERCLIP_API_KEY).toBe("run-jwt-token");
} finally {
for (const [key, value] of Object.entries(previous)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
await fs.rm(root, { recursive: true, force: true });
}
});
});
@@ -14,6 +14,7 @@ import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import { companySkillService } from "../services/company-skills.js";
import { buildHostServices } from "../services/plugin-host-services.js";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
@@ -119,7 +120,8 @@ describeEmbeddedPostgres("plugin-managed skills", () => {
expect(created.status).toBe("created");
expect(created.skill).toMatchObject({
name: "Wiki Maintainer Skill",
name: "plugin-managed-skills-test-wiki-maintainer",
slug: "plugin-managed-skills-test-wiki-maintainer",
key: "plugin/paperclip-managed-skills-test/wiki-maintainer",
sourceType: "catalog",
fileInventory: expect.arrayContaining([
@@ -144,6 +146,35 @@ describeEmbeddedPostgres("plugin-managed skills", () => {
});
});
it("keeps a same-slug user skill separate through automatic install, reset, and relinking", async () => {
const { companyId, services } = await seedCompanyAndPlugin();
const original = await companySkillService(db).createLocalSkill(companyId, { name: "Wiki Maintainer Skill", markdown: "# User instructions\n" });
const created = await services.skills.managedReconcile({ companyId, skillKey: "wiki-maintainer" });
expect(created.skillId).not.toBe(original.id);
expect(created.skill!.key).toBe("plugin/paperclip-managed-skills-test/wiki-maintainer");
expect(created.skill!.slug).toBe("plugin-managed-skills-test-wiki-maintainer");
expect(created.skill!.markdown).toContain('name: "plugin-managed-skills-test-wiki-maintainer"');
await services.skills.managedReset({ companyId, skillKey: "wiki-maintainer" });
await db.delete(pluginManagedResources).where(eq(pluginManagedResources.resourceId, created.skillId!));
const relinked = await services.skills.managedReconcile({ companyId, skillKey: "wiki-maintainer" });
expect(relinked.skillId).toBe(created.skillId);
expect((await db.select().from(companySkills).where(eq(companySkills.id, original.id)))[0]).toMatchObject({ key: original.key, slug: original.slug, markdown: original.markdown });
});
it("claims the plugin name while preserving a conflicting company skill as a separate record", async () => {
const { companyId, services } = await seedCompanyAndPlugin();
const original = await companySkillService(db).createLocalSkill(companyId, {
name: "plugin-managed-skills-test-wiki-maintainer", markdown: "# User instructions\n",
});
const installed = await services.skills.managedReconcile({ companyId, skillKey: "wiki-maintainer" });
expect(installed.skill!.slug).toBe(original.slug);
expect(installed.skill!.id).not.toBe(original.id);
await services.skills.managedReset({ companyId, skillKey: "wiki-maintainer" });
const records = (await db.select().from(companySkills)).filter(skill => [original.key, installed.skill!.key].includes(skill.key));
expect(records).toHaveLength(2);
expect(records.find(skill => skill.id === original.id)).toMatchObject({ key: original.key, markdown: original.markdown });
expect(await db.select().from(pluginManagedResources)).toEqual([expect.objectContaining({ resourceId: installed.skill!.id })]);
});
it("preserves operator edits during reconcile and restores manifest defaults on reset", async () => {
const { companyId, services } = await seedCompanyAndPlugin();
const created = await services.skills.managedReconcile({ companyId, skillKey: "wiki-maintainer" });
@@ -168,7 +199,7 @@ describeEmbeddedPostgres("plugin-managed skills", () => {
const reset = await services.skills.managedReset({ companyId, skillKey: "wiki-maintainer" });
expect(reset.status).toBe("reset");
expect(reset.skill).toMatchObject({
name: "Wiki Maintainer Skill",
name: "plugin-managed-skills-test-wiki-maintainer",
description: "Use LLM Wiki tools to maintain company knowledge.",
});
expect(reset.skill?.markdown).toContain("key: \"plugin/paperclip-managed-skills-test/wiki-maintainer\"");
@@ -248,6 +279,18 @@ describeEmbeddedPostgres("plugin-managed skills", () => {
expect(reset.defaultDrift).toBeNull();
});
it("preserves unrelated YAML while replacing quoted and multiline identity fields", async () => {
const declaration = manifest();
declaration.skills = [{ skillKey: "yaml-skill", displayName: "YAML skill", markdown:
'---\n"name": |\n Previous name\nslug: old-slug\ndescription: >\n Keep this folded description.\nmetadata:\n "category": desktop\n# Keep this comment.\n---\nBody stays unchanged.\n' }];
const { companyId, services } = await seedCompanyAndPlugin(declaration);
const created = await services.skills.managedReconcile({ companyId, skillKey: "yaml-skill" });
expect(created.skill!.markdown).toContain('name: "plugin-managed-skills-test-yaml-skill"');
expect(created.skill!.markdown).not.toContain("Previous name");
expect(created.skill!.markdown).toContain('description: >\n Keep this folded description.\nmetadata:\n "category": desktop\n# Keep this comment.');
expect(created.skill!.markdown).toMatch(/Body stays unchanged\.\n$/);
await services.skills.managedReset({ companyId, skillKey: "yaml-skill" });
});
it("adds the canonical managed key to manifest-provided markdown skills", async () => {
const pluginManifest = manifest();
pluginManifest.skills = [
@@ -274,8 +317,8 @@ describeEmbeddedPostgres("plugin-managed skills", () => {
expect(created.status).toBe("created");
expect(created.skill).toMatchObject({
key: "plugin/paperclip-managed-skills-test/markdown-skill",
name: "markdown-skill",
name: "plugin-managed-skills-test-markdown-skill",
});
expect(created.skill?.markdown).toContain("key: \"plugin/paperclip-managed-skills-test/markdown-skill\"");
expect(created.skill?.markdown).toContain('key: "plugin/paperclip-managed-skills-test/markdown-skill"');
});
});
@@ -64,6 +64,30 @@ databaseSuite("Core plugin Runner task lifecycle", () => {
});
afterAll(async () => { await stopDb?.(); });
it("does not allocate agent-dependent setup leases before the agent is prepared", async () => {
const companyId = randomUUID(), pluginId = randomUUID(), environmentId = randomUUID(), agentId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Setup lease fixture", issuePrefix: "SETUP" });
await db.insert(plugins).values({ id: pluginId, pluginKey: pluginId, packageName: "@test/agent-owned-tasks", version: "1.0.0", status: "ready",
manifestJson: { agentLifecycle: true, capabilities: ["agents.lifecycle.manage", "environment.drivers.register"],
environmentDrivers: [{ driverKey: "tasks", supportsTasks: true, requiresAgent: true }] } as never });
await db.insert(environments).values({ id: environmentId, name: "Agent computer", driver: "plugin", status: "active",
config: { pluginKey: pluginId, driverKey: "tasks", driverConfig: {} } });
const call = vi.fn();
const setup = agentEnvironmentTestService(db, { call } as never);
const input = { companyId, environmentId, adapterType: "paperclip_runner" };
expect((await setup.resolveAdapterTestExecutionContext(input)).fallbackChecks).toMatchObject([{ code: "environment_agent_required", level: "warn" }]);
await db.insert(agents).values({ id: agentId, companyId, name: "Draft", lifecycleState: "preparing", lifecycleHolds: ["setup"], status: "paused" });
expect((await setup.resolveAdapterTestExecutionContext({ ...input, agentId })).fallbackChecks).toMatchObject([{ code: "environment_agent_preparing", level: "warn" }]);
await db.update(companies).set({ requireBoardApprovalForNewAgents: true }).where(eq(companies.id, companyId));
await db.update(agents).set({ lifecycleState: "paused", pauseReason: "setup" }).where(eq(agents.id, agentId));
expect((await setup.resolveAdapterTestExecutionContext({ ...input, agentId })).fallbackChecks).toMatchObject([{ code: "environment_agent_approval_required", level: "warn" }]);
const foreign = randomUUID();
await db.insert(companies).values({ id: foreign, name: "Other company", issuePrefix: "OTHER" });
expect((await setup.resolveAdapterTestExecutionContext({ ...input, companyId: foreign, agentId })).fallbackChecks).toMatchObject([{ code: "environment_agent_preparing" }]);
expect(call).not.toHaveBeenCalled();
expect(await db.select().from(environmentLeases).where(eq(environmentLeases.environmentId, environmentId))).toEqual([]);
});
it("uses an acquired lease through SDK RPC, native dispatch, connection, stop proof and release", async () => {
const companyId = randomUUID(), agentId = randomUUID(), runId = randomUUID();
const environmentId = randomUUID(), pluginId = randomUUID(), projectId = randomUUID();
@@ -280,6 +280,33 @@ describe("plugin-worker-manager stderr failure context", () => {
}
});
it("mints project Git scope only for project lifecycle and workspace operations", async () => {
const handle = createPluginWorkerHandle("test.plugin", {
entrypointPath: INVOCATION_SCOPE_WORKER_ENTRYPOINT, manifest: TEST_MANIFEST, config: {},
instanceInfo: { instanceId: "instance-1", hostVersion: "1.0.0" }, apiVersion: 1,
hostHandlers: { "companies.get": (async (_params, context) => context?.invocationScope) as never },
});
const common = { companyId: "company-a", params: { mode: "echo", requestedCompanyId: "company-a" } };
try {
await handle.start();
await expect(handle.call("resourceLifecycle", { ...common, resourceType: "project", resourceId: "project-a" } as never))
.resolves.toEqual({ companyId: "company-a", projectGit: { projectId: "project-a" } });
await expect(handle.call("resourceLifecycle", { ...common, resourceType: "agent", resourceId: "agent-a" } as never))
.resolves.toEqual({ companyId: "company-a" });
for (const kind of ["prepare", "inspect", "remove", "finalize"]) {
const params = { ...common, projectId: "project-a", runId: "run-a", agentId: "agent-a", operation: {
kind, source: { id: "workspace-a" }, binding: { projectWorkspaceId: "workspace-a" } } };
await expect(handle.call("workspaceOperation", params as never)).resolves.toEqual({ companyId: "company-a",
...(kind === "finalize" ? {} : { projectGit: { projectId: "project-a", workspaceId: "workspace-a", operation: kind,
...(kind === "prepare" ? { runId: "run-a", agentId: "agent-a" } : {}) } }) });
}
await expect(handle.call("workspaceOperation", { ...common, projectId: "project-a", runId: null, agentId: null,
operation: { kind: "prepare", source: { id: "workspace-a" } } } as never)).resolves.toEqual({ companyId: "company-a", projectGit: { projectId: "project-a", workspaceId: "workspace-a", operation: "prepare" } });
await expect(handle.call("workspaceOperation", { ...common, projectId: "project-a", runId: null, agentId: "agent-a",
operation: { kind: "prepare", source: { id: "workspace-a" } } } as never)).resolves.toEqual({ companyId: "company-a" });
} finally { await handle.stop().catch(() => undefined); }
});
it("passes performAction invocation scope to nested worker host calls", async () => {
const companiesGet = vi.fn(async (
params: { companyId: string },
@@ -0,0 +1,320 @@
import express from "express";
import request from "supertest";
import { eq } from "drizzle-orm";
import { randomUUID } from "node:crypto";
import { beforeAll, afterAll, describe, expect, it, vi } from "vitest";
import { createDb, authUsers, companyMemberships, connectionGrants, executionWorkspaces, heartbeatRuns, instanceUserRoles, issues, projectAccessMembers, projects, projectWorkspaces, resourceLifecycleEvents, toolConnectionInstalls, toolConnections } from "@paperclipai/db";
import { LOW_TRUST_REVIEW_PRESET } from "@paperclipai/shared";
import { ghFetch } from "../services/github-fetch.js";
import { projectRoutes } from "../routes/projects.js";
import { projectGitAuthorizationService } from "../services/project-git-authorization.js";
import { errorHandler } from "../middleware/index.js";
import { githubCredentialsFixture } from "./helpers/github-credentials-fixture.js";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
const vault = vi.hoisted(() => ({
resolveUserSecretValue: vi.fn(async (_company: string, input: { responsibleUserId: string }) => ({ value: `test-token-${input.responsibleUserId}` })),
resolveSecretValue: vi.fn(async () => "test-dedicated-token"),
}));
vi.mock("../services/secrets.js", () => ({ secretService: () => vault }));
vi.mock("../services/github-fetch.js", async importOriginal => ({
...await importOriginal<typeof import("../services/github-fetch.js")>(),
ghFetch: vi.fn(async () => new Response(null, { status: 404 })),
}));
const support = await getEmbeddedPostgresTestSupport();
(support.supported ? describe : describe.skip)("explicit project Git authorization", () => {
let db: ReturnType<typeof createDb>, database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
const { seed, grant, switchTo } = githubCredentialsFixture(() => db);
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("paperclip-project-git-authorization-");
db = createDb(database.connectionString);
await db.insert(authUsers).values(["A", "B"].map(id => ({
id, name: id, email: `${id}@example.invalid`, createdAt: new Date(), updatedAt: new Date(),
})));
}, 30_000);
afterAll(async () => { await database?.cleanup(); }, 60_000);
async function projectAuthorizationFixture() {
const input = await seed();
const selected = await grant(input, "A");
const [project] = await db.insert(projects).values({ companyId: input.companyId, name: "Authorized project" }).returning();
const [workspace] = await db.insert(projectWorkspaces).values({ companyId: input.companyId, projectId: project.id,
name: "Repository", repoUrl: "https://github.com/fixture/project.git" }).returning();
await db.update(issues).set({ projectId: project.id, projectWorkspaceId: workspace.id }).where(eq(issues.id, input.issueId));
await db.insert(toolConnectionInstalls).values({ companyId: input.companyId, connectionId: selected.connectionId, targetType: "company", targetId: input.companyId });
const [saved] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, selected.id));
await db.update(connectionGrants).set({ providerTenant: { ...saved.providerTenant, github: { ...saved.providerTenant!.github!,
lastAccessRefreshAt: "2020-01-01T00:00:00Z", repositories: [{ id: "1", fullName: "fixture/project", installationId: "1", private: true }] } } }).where(eq(connectionGrants.id, selected.id));
const service = projectGitAuthorizationService(db);
const request = { companyId: input.companyId, projectId: project.id, workspaceId: workspace.id };
return { input, selected, project, workspace, service, request, scope: { projectId: project.id } };
}
it("uses explicit project consent without a task and journals consent changes", async () => {
const f = await projectAuthorizationFixture();
await expect(f.service.resolve(f.request, f.scope)).rejects.toThrow("Authorize this project");
expect(await f.service.read(f.input.companyId, f.project.id, "B")).toMatchObject({ options: [] });
await expect(f.service.set(f.input.companyId, f.project.id, "B", f.selected.id)).rejects.toThrow("own active");
const saved = await f.service.set(f.input.companyId, f.project.id, "A", f.selected.id);
expect(saved).toMatchObject({ grantId: f.selected.id, authorizedByUserId: "A" });
expect(JSON.stringify(saved)).not.toContain("test-token");
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, f.input.runId));
await db.update(issues).set({ responsibleUserId: "B" }).where(eq(issues.id, f.input.issueId));
expect(await f.service.resolve(f.request, f.scope)).toBe("test-token-A");
expect((await db.select().from(resourceLifecycleEvents).where(eq(resourceLifecycleEvents.resourceId, f.project.id))).length).toBeGreaterThan(0);
await f.service.set(f.input.companyId, f.project.id, "A", null);
await expect(f.service.resolve(f.request, f.scope)).rejects.toThrow("Authorize this project");
});
it("rechecks the consenting user's project access before background credential export", async () => {
const f = await projectAuthorizationFixture();
await f.service.set(f.input.companyId, f.project.id, "A", f.selected.id);
await db.update(projects).set({ visibility: "private" }).where(eq(projects.id, f.project.id));
await db.insert(projectAccessMembers).values({ companyId: f.input.companyId, projectId: f.project.id, subjectType: "user", subjectId: "A" });
expect(await f.service.resolve(f.request, f.scope)).toBe("test-token-A");
await db.delete(projectAccessMembers).where(eq(projectAccessMembers.projectId, f.project.id));
vault.resolveUserSecretValue.mockClear();
await expect(f.service.resolve(f.request, f.scope)).rejects.toThrow("private");
expect(vault.resolveUserSecretValue).not.toHaveBeenCalled();
});
it("rechecks current Cloud owner elevation for consent on another user's private project", async () => {
const f = await projectAuthorizationFixture();
await db.update(projects).set({ visibility: "private", privacyOwnerUserId: "B" }).where(eq(projects.id, f.project.id));
vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "fixture-tenant-token");
vi.stubEnv("PAPERCLIP_CLOUD_API_ORIGIN", "https://cloud.example.invalid");
vi.stubEnv("PAPERCLIP_CLOUD_STACK_ID", "fixture-stack");
vi.stubEnv("PAPERCLIP_STACK_SLUG", "fixture-stack");
const managed = (enabled: boolean) => vi.stubEnv("PAPERCLIP_MANAGED_CONFIG", JSON.stringify({
v: 1, mode: "cloud", catalogVersion: "test", features: { enableOwnerInstanceAdmin: enabled }, plugins: { autoInstall: [] },
}));
const portfolio = (role = "owner", stackSlug = "fixture-stack") => Response.json({ stacks: [{ stackSlug, role, isCurrent: true }] });
const fetch = vi.fn(async () => portfolio());
vi.stubGlobal("fetch", fetch); managed(true);
try {
const app = express(); app.use(express.json());
app.use((req, _res, next) => { req.actor = { type: "board", source: "cloud_tenant", userId: "A",
companyIds: [f.input.companyId], isInstanceAdmin: true }; next(); });
app.use("/api", projectRoutes(db)); app.use(errorHandler);
expect((await request(app).put(`/api/projects/${f.project.id}/git-authorization`).send({ grantId: f.selected.id })).status).toBe(200);
expect(await f.service.resolve(f.request, f.scope)).toBe("test-token-A");
const cleanup = { ...f.scope, workspaceId: f.workspace.id, operation: "remove" as const };
expect(await f.service.resolve(f.request, cleanup)).toBe("test-token-A");
expect(fetch).toHaveBeenCalledWith(new URL("https://cloud.example.invalid/v1/tenant/portfolio"), expect.objectContaining({
headers: expect.objectContaining({ "x-paperclip-cloud-user-id": "A", "x-paperclip-cloud-stack-id": "fixture-stack" }),
}));
// Stale local roles must never replace current Cloud authority.
await db.insert(instanceUserRoles).values({ userId: "A", role: "instance_admin" });
for (const denied of ["role", "setting", "unavailable", "stack"] as const) {
managed(denied !== "setting");
fetch.mockImplementation(async () => denied === "unavailable" ? new Response(null, { status: 503 })
: portfolio(denied === "role" ? "admin" : "owner", denied === "stack" ? "different-stack" : "fixture-stack"));
vault.resolveUserSecretValue.mockClear();
await expect(f.service.resolve(f.request, cleanup)).rejects.toThrow("private");
expect(vault.resolveUserSecretValue).not.toHaveBeenCalled();
}
await db.insert(projectAccessMembers).values({ companyId: f.input.companyId, projectId: f.project.id, subjectType: "user", subjectId: "A" });
fetch.mockImplementation(async () => new Response(null, { status: 503 }));
expect(await f.service.resolve(f.request, cleanup)).toBe("test-token-A");
} finally {
await db.delete(instanceUserRoles).where(eq(instanceUserRoles.userId, "A"));
vi.unstubAllGlobals(); vi.unstubAllEnvs();
}
});
it("does not lend background consent to a low-trust project", async () => {
const f = await projectAuthorizationFixture();
await f.service.set(f.input.companyId, f.project.id, "A", f.selected.id);
await db.update(projects).set({ executionWorkspacePolicy: { authorizationPolicy: { trustBoundary: {
mode: LOW_TRUST_REVIEW_PRESET, companyId: f.input.companyId, projectIds: [f.project.id],
} } } }).where(eq(projects.id, f.project.id));
vault.resolveUserSecretValue.mockClear();
await expect(f.service.resolve(f.request, f.scope)).rejects.toThrow("low-trust");
expect(vault.resolveUserSecretValue).not.toHaveBeenCalled();
});
it("uses the connection's current repository access for sources added after project authorization", async () => {
const f = await projectAuthorizationFixture();
await f.service.set(f.input.companyId, f.project.id, "A", f.selected.id);
const [workspace] = await db.insert(projectWorkspaces).values({ companyId: f.input.companyId,
projectId: f.project.id, name: "Added repository", repoUrl: "https://github.com/fixture/added",
metadata: { githubRepositoryUrl: "https://github.com/fixture/added", githubRepositoryPrivate: true },
}).returning();
const request = { ...f.request, workspaceId: workspace.id };
vault.resolveUserSecretValue.mockClear();
await expect(f.service.resolve(request, f.scope)).rejects.toThrow("does not include this repository");
expect(vault.resolveUserSecretValue).not.toHaveBeenCalled();
const [saved] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, f.selected.id));
await db.update(connectionGrants).set({ providerTenant: { ...saved.providerTenant, github: { ...saved.providerTenant!.github!,
repositoryCount: 2, repositories: [...saved.providerTenant!.github!.repositories!,
{ id: "2", fullName: "fixture/added", installationId: "1", private: true }],
} } }).where(eq(connectionGrants.id, f.selected.id));
expect(await f.service.resolve(request, f.scope)).toBe("test-token-A");
await db.update(connectionGrants).set({ providerTenant: saved.providerTenant }).where(eq(connectionGrants.id, f.selected.id));
vault.resolveUserSecretValue.mockClear();
await expect(f.service.resolve(request, f.scope)).rejects.toThrow("does not include this repository");
expect(vault.resolveUserSecretValue).not.toHaveBeenCalled();
});
it("never requests credentials or requires a connection for a known public repository", async () => {
const f = await projectAuthorizationFixture();
await db.update(projectWorkspaces).set({ metadata: { githubRepositoryUrl: "https://github.com/fixture/project", githubRepositoryPrivate: false } }).where(eq(projectWorkspaces.id, f.workspace.id));
await db.update(connectionGrants).set({ providerTenant: null, status: "revoked" }).where(eq(connectionGrants.id, f.selected.id));
vi.mocked(ghFetch).mockClear(); vault.resolveUserSecretValue.mockClear();
expect(await f.service.resolve(f.request, f.scope)).toBeNull();
expect(ghFetch).not.toHaveBeenCalled(); expect(vault.resolveUserSecretValue).not.toHaveBeenCalled();
});
it.each(["inspect", "remove"] as const)("allows authorized %s after archive while denying provisioning and revoked consent", async operation => {
const f = await projectAuthorizationFixture();
await db.update(projectWorkspaces).set({ metadata: { githubRepositoryUrl: "https://github.com/fixture/project", githubRepositoryPrivate: true } })
.where(eq(projectWorkspaces.id, f.workspace.id));
await f.service.set(f.input.companyId, f.project.id, "A", f.selected.id);
await db.update(projects).set({ archivedAt: new Date() }).where(eq(projects.id, f.project.id));
const scope = { ...f.scope, workspaceId: f.workspace.id, operation };
expect(await f.service.resolve(f.request, scope)).toBe("test-token-A");
vault.resolveUserSecretValue.mockClear();
for (const deniedScope of [f.scope, { ...f.scope, operation }, { ...scope, operation: "prepare" as const },
{ ...scope, workspaceId: randomUUID() }, { ...scope, runId: f.input.runId, agentId: f.input.agentId }]) {
await expect(f.service.resolve(f.request, deniedScope)).rejects.toThrow();
}
await expect(f.service.set(f.input.companyId, f.project.id, "A", f.selected.id)).rejects.toThrow("Active project");
await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, f.selected.id));
await expect(f.service.resolve(f.request, scope)).rejects.toThrow("authorization is unavailable");
await f.service.set(f.input.companyId, f.project.id, "A", null);
await expect(f.service.resolve(f.request, scope)).rejects.toThrow("Authorize this project");
expect(vault.resolveUserSecretValue).not.toHaveBeenCalled();
});
it.each(["revoked", "disabled"])("ignores %s private catalog entries when the current repository is public", async stale => {
const f = await projectAuthorizationFixture();
if (stale === "revoked") await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, f.selected.id));
else await db.update(toolConnections).set({ enabled: false }).where(eq(toolConnections.id, f.selected.connectionId));
const current = await grant(f.input, "A");
const [saved] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, current.id));
await db.update(connectionGrants).set({ providerTenant: { ...saved.providerTenant, github: { ...saved.providerTenant!.github!,
repositories: [{ id: "1", fullName: "fixture/project", installationId: "1", private: false }] } } }).where(eq(connectionGrants.id, current.id));
vault.resolveUserSecretValue.mockClear(); vi.mocked(ghFetch).mockClear();
expect(await f.service.resolve(f.request, f.scope)).toBeNull();
expect(vault.resolveUserSecretValue).not.toHaveBeenCalled(); expect(ghFetch).not.toHaveBeenCalled();
});
it.each([true, false])("uses refreshed catalog visibility after a repository becomes private=%s", async isPrivate => {
const f = await projectAuthorizationFixture();
await db.update(projectWorkspaces).set({ metadata: { githubRepositoryUrl: "https://github.com/fixture/project", githubRepositoryPrivate: !isPrivate } }).where(eq(projectWorkspaces.id, f.workspace.id));
const [saved] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, f.selected.id));
await db.update(connectionGrants).set({ providerTenant: { ...saved.providerTenant, github: { ...saved.providerTenant!.github!,
repositories: [{ id: "1", fullName: "fixture/project", installationId: "1", private: isPrivate }] } } }).where(eq(connectionGrants.id, f.selected.id));
await f.service.set(f.input.companyId, f.project.id, "A", f.selected.id);
expect(await f.service.resolve(f.request, f.scope)).toBe(isPrivate ? "test-token-A" : null);
});
it("uses repository access refresh time rather than unrelated grant updates for conflicting active catalogs", async () => {
const f = await projectAuthorizationFixture(), current = await grant(f.input, "A");
for (const [id, privateValue, refreshedAt] of [[f.selected.id, true, "2020-01-01T00:00:00Z"], [current.id, false, "2021-01-01T00:00:00Z"]] as const) {
const [saved] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, id));
await db.update(connectionGrants).set({ providerTenant: { ...saved.providerTenant, github: { ...saved.providerTenant!.github!,
lastAccessRefreshAt: refreshedAt, repositories: [{ id: "1", fullName: "fixture/project", installationId: "1", private: privateValue }] } } }).where(eq(connectionGrants.id, id));
}
await db.update(connectionGrants).set({ updatedAt: new Date() }).where(eq(connectionGrants.id, f.selected.id));
expect(await f.service.resolve(f.request, f.scope)).toBeNull();
});
it("never lets a legacy catalog's OAuth update outrank an observed repository refresh", async () => {
const f = await projectAuthorizationFixture(), legacy = await grant(f.input, "A");
const [saved] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, legacy.id));
await db.update(connectionGrants).set({ updatedAt: new Date(), providerTenant: { ...saved.providerTenant, github: { ...saved.providerTenant!.github!,
repositories: [{ id: "1", fullName: "fixture/project", installationId: "1", private: false }] } } }).where(eq(connectionGrants.id, legacy.id));
await f.service.set(f.input.companyId, f.project.id, "A", f.selected.id);
expect(await f.service.resolve(f.request, f.scope)).toBe("test-token-A");
});
it("discovers legacy URL-only public sources anonymously and defers unknown private sources", async () => {
const f = await projectAuthorizationFixture();
await db.update(projectWorkspaces).set({ repoUrl: "https://github.com/fixture/legacy" }).where(eq(projectWorkspaces.id, f.workspace.id));
vi.mocked(ghFetch).mockResolvedValueOnce(Response.json({ full_name: "fixture/legacy", private: false }));
expect(await f.service.resolve(f.request, f.scope)).toBeNull();
const [, options] = vi.mocked(ghFetch).mock.calls.at(-1)!;
expect(new Headers(options?.headers).has("Authorization")).toBe(false);
await expect(f.service.resolve(f.request, f.scope)).rejects.toThrow("visibility is unavailable");
});
it.each(["grant", "connection", "membership", "repository", "archive"])("rechecks %s and never falls back to another grant", async change => {
const f = await projectAuthorizationFixture();
await f.service.set(f.input.companyId, f.project.id, "A", f.selected.id);
await grant(f.input, "A");
if (change === "grant") await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, f.selected.id));
if (change === "connection") await db.update(toolConnections).set({ enabled: false }).where(eq(toolConnections.id, f.selected.connectionId));
if (change === "membership") await db.update(companyMemberships).set({ status: "suspended" }).where(eq(companyMemberships.companyId, f.input.companyId));
if (change === "repository") await db.update(projectWorkspaces).set({ repoUrl: "https://github.com/fixture/other" }).where(eq(projectWorkspaces.id, f.workspace.id));
if (change === "archive") await db.update(projects).set({ archivedAt: new Date() }).where(eq(projects.id, f.project.id));
vault.resolveUserSecretValue.mockClear();
await expect(f.service.resolve(f.request, f.scope)).rejects.toThrow();
expect(vault.resolveUserSecretValue).not.toHaveBeenCalled();
});
it("uses the live foreground run rather than project consent and denies mismatched scopes", async () => {
const f = await projectAuthorizationFixture();
await f.service.set(f.input.companyId, f.project.id, "A", f.selected.id);
await grant(f.input, "B");
await switchTo(f.input, "B");
expect(await f.service.resolve(f.request, { ...f.scope, runId: f.input.runId, agentId: f.input.agentId })).toBe("test-token-B");
for (const scope of [undefined, { projectId: randomUUID() }, { ...f.scope, workspaceId: randomUUID() }]) {
await expect(f.service.resolve(f.request, scope)).rejects.toThrow();
}
await expect(f.service.resolve({ ...f.request, workspaceId: randomUUID() }, f.scope)).rejects.toThrow();
await expect(f.service.resolve({ ...f.request, companyId: randomUUID() }, f.scope)).rejects.toThrow();
});
it.each(["configured", "bound"])("authorizes a %s workspace selected from another project, but not an unselected source", async selection => {
const f = await projectAuthorizationFixture();
const [taskProject] = await db.insert(projects).values({ companyId: f.input.companyId, name: "Task project" }).returning();
const [bound] = selection === "bound" ? await db.insert(executionWorkspaces).values({
companyId: f.input.companyId, projectId: f.project.id, projectWorkspaceId: f.workspace.id,
sourceIssueId: f.input.issueId, name: "Selected workspace", mode: "isolated_workspace", strategyType: "git_worktree", status: "idle",
}).returning() : [];
await db.update(issues).set({ projectId: taskProject.id,
projectWorkspaceId: selection === "configured" ? f.workspace.id : null,
executionWorkspaceId: bound?.id ?? null,
}).where(eq(issues.id, f.input.issueId));
const scope = { ...f.scope, workspaceId: f.workspace.id, runId: f.input.runId, agentId: f.input.agentId };
expect(await f.service.resolve(f.request, scope)).toBe("test-token-A");
const [unselected] = await db.insert(projectWorkspaces).values({ companyId: f.input.companyId,
projectId: f.project.id, name: "Unselected source", repoUrl: f.workspace.repoUrl,
}).returning();
vault.resolveUserSecretValue.mockClear();
await expect(f.service.resolve({ ...f.request, workspaceId: unselected.id }, { ...scope, workspaceId: unselected.id })).rejects.toThrow();
expect(vault.resolveUserSecretValue).not.toHaveBeenCalled();
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, f.input.runId));
await expect(f.service.resolve(f.request, scope)).rejects.toThrow();
expect(vault.resolveUserSecretValue).not.toHaveBeenCalled();
});
it.each(["", "secret://fixture", "invalid\ntoken"])("rejects invalid transient credential material", async token => {
const f = await projectAuthorizationFixture();
await f.service.set(f.input.companyId, f.project.id, "A", f.selected.id);
vault.resolveUserSecretValue.mockResolvedValueOnce({ value: token });
await expect(f.service.resolve(f.request, f.scope)).rejects.toThrow("credential unavailable");
});
it.each(["task", "source"])("checks access to the %s project before exporting foreground credentials", async privateProject => {
const f = await projectAuthorizationFixture();
const [taskProject] = await db.insert(projects).values({ companyId: f.input.companyId, name: "Task project" }).returning();
await db.update(issues).set({ projectId: taskProject.id }).where(eq(issues.id, f.input.issueId));
await db.update(projects).set({ visibility: "private" })
.where(eq(projects.id, privateProject === "task" ? taskProject.id : f.project.id));
vault.resolveUserSecretValue.mockClear();
vi.stubEnv("PAPERCLIP_ISSUE_PRIVACY_MODE", "enforce");
try {
await expect(f.service.resolve(f.request, { ...f.scope, runId: f.input.runId, agentId: f.input.agentId })).rejects.toThrow();
expect(vault.resolveUserSecretValue).not.toHaveBeenCalled();
} finally { vi.unstubAllEnvs(); }
});
it("never lends project consent to low-trust foreground preparation", async () => {
const f = await projectAuthorizationFixture();
await f.service.set(f.input.companyId, f.project.id, "A", f.selected.id);
await db.update(issues).set({ sourceTrust: { preset: LOW_TRUST_REVIEW_PRESET, disposition: "quarantined", sourceIssueId: f.input.issueId } })
.where(eq(issues.id, f.input.issueId));
vault.resolveUserSecretValue.mockClear();
await expect(f.service.resolve(f.request, { ...f.scope, runId: f.input.runId, agentId: f.input.agentId })).rejects.toThrow("low-trust");
expect(vault.resolveUserSecretValue).not.toHaveBeenCalled();
});
it("requires a board project writer and grant owner on the consent route", async () => {
const f = await projectAuthorizationFixture();
function app(userId: string, agent = false) {
const app = express(); app.use(express.json());
app.use((req, _res, next) => { req.actor = agent ? { type: "agent", agentId: f.input.agentId, companyId: f.input.companyId }
: { type: "board", source: "session", userId, companyIds: [f.input.companyId], isInstanceAdmin: true }; next(); });
app.use("/api", projectRoutes(db)); app.use(errorHandler); return app;
}
const url = `/api/projects/${f.project.id}/git-authorization`;
expect((await request(app("B")).put(url).send({ grantId: f.selected.id })).status).toBe(403);
expect((await request(app("A", true)).put(url).send({ grantId: f.selected.id })).status).toBe(403);
expect((await request(app("A")).put(url).send({ grantId: f.selected.id })).status).toBe(200);
const read = await request(app("A")).get(url);
expect(read.status).toBe(200); expect(JSON.stringify(read.body)).not.toContain("test-token");
expect((await request(app("A")).put(url).send({ grantId: null })).status).toBe(200);
});
});
@@ -33,6 +33,14 @@ const support = await getEmbeddedPostgresTestSupport();
expect(fetched?.workspaces.filter((workspace) => workspace.isPrimary)).toHaveLength(1);
expect(fetched?.workspaces.every((workspace) => workspace.companyId === companyId)).toBe(true);
});
it("retains and refreshes repository visibility without replacing the workspace", async () => {
const svc = projectService(db);
const source = { ...repo("30"), private: true };
const created = await svc.createWithRepositories(companyId, { name: "Visibility" }, [source]);
expect(created.workspaces[0].metadata).toMatchObject({ githubRepositoryPrivate: true, githubRepositoryUrl: source.url });
const updated = await svc.replaceRepositories(created.id, [{ ...source, private: false }]);
expect(updated?.workspaces[0]).toMatchObject({ id: created.workspaces[0].id, metadata: { githubRepositoryPrivate: false, githubRepositoryUrl: source.url } });
});
it("adds/removes repos, promotes the remaining primary, and preserves legacy and local config", async () => {
const svc = projectService(db);
const created = await svc.createWithRepositories(companyId, { name: "Edit" }, [repo("3"), repo("4")]);
@@ -3409,6 +3409,9 @@ describeEmbeddedPostgres("secretService", () => {
requiredCapability: "secretsmanager:CreateSecret",
},
});
expect((thrown as HttpError).details?.actionableMessage).toContain(
"Ensure the Paperclip server runtime can resolve valid AWS credentials",
);
expect(JSON.stringify(thrown)).not.toContain("arn:aws");
expect(JSON.stringify(thrown)).not.toContain("123456789012");
expect(thrown instanceof Error ? thrown.message : String(thrown)).not.toContain("arn:aws");
@@ -1,6 +1,8 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { classifyTaskWatchdogSubtree, type TaskWatchdogClassifierIssue } from "../services/task-watchdogs.ts";
import { createIncompleteTaskWatchdogScanReporter } from "../services/task-watchdog-diagnostics.ts";
const companyId = "company-1";
const sourceId = "source-1";
const childId = "child-1";
@@ -35,6 +37,45 @@ function classify(overrides: Partial<Parameters<typeof classifyTaskWatchdogSubtr
}
describe("task watchdog subtree classifier", () => {
it("reports an unchanged incomplete scan once across startup and a day of periodic ticks", () => {
const warn = vi.fn();
const report = createIncompleteTaskWatchdogScanReporter(warn);
report({ incomplete: 2, incompleteIssueIds: [sourceId, childId] }, "startup");
for (let tick = 0; tick < 2880; tick += 1) {
report({ incomplete: 2, incompleteIssueIds: [childId, sourceId] }, "periodic");
}
expect(warn).toHaveBeenCalledTimes(1);
expect(warn).toHaveBeenCalledWith(
{ incomplete: 2, newIncompleteIssueIds: [sourceId, childId] },
"startup task-watchdog reconciliation found incomplete subtree scans",
);
});
it("reports new incomplete issues and reports a resolved issue if it becomes incomplete again", () => {
const warn = vi.fn();
const report = createIncompleteTaskWatchdogScanReporter(warn);
report({ incomplete: 1, incompleteIssueIds: [sourceId] }, "startup");
report({ incomplete: 2, incompleteIssueIds: [sourceId, childId] }, "periodic");
expect(warn).toHaveBeenLastCalledWith(
{ incomplete: 2, newIncompleteIssueIds: [childId] },
"periodic task-watchdog reconciliation found incomplete subtree scans",
);
report({ incomplete: 0, incompleteIssueIds: [] }, "periodic");
expect(warn).toHaveBeenCalledTimes(2);
report({ incomplete: 1, incompleteIssueIds: [sourceId] }, "periodic");
expect(warn).toHaveBeenCalledTimes(3);
expect(warn).toHaveBeenLastCalledWith(
{ incomplete: 1, newIncompleteIssueIds: [sourceId] },
"periodic task-watchdog reconciliation found incomplete subtree scans",
);
});
it("does not produce a stopped fingerprint from an incomplete scan", () => {
const result = classify({ subtreeIncomplete: true });
expect(result.state).toBe("incomplete");
expect(result).not.toHaveProperty("stopFingerprint");
});
it("suppresses watchdog wakeups while watched subtree work has a live path", () => {
const result = classify({
issues: [
@@ -437,6 +437,81 @@ describeEmbeddedPostgres("task watchdog scheduler", () => {
expect(wakes).toHaveLength(1);
});
async function seedDeepSubtree() {
const companyId = await seedCompany();
const sourceId = await seedIssue(companyId, { status: "blocked", issueNumber: 1000 });
let boundaryId = sourceId;
for (let depth = 1; depth < 100; depth += 1) {
boundaryId = await seedIssue(companyId, {
parentId: boundaryId, status: "blocked", identifier: `DEEP-${depth}`, issueNumber: 1000 + depth,
});
}
const agentId = await seedAgent(companyId);
const watchdog = await seedWatchdog(companyId, sourceId, agentId);
return { companyId, sourceId, boundaryId, agentId, watchdog, ...createService() };
}
it("rejects an incomplete subtree before dispatching a stopped review", async () => {
const x = await seedDeepSubtree();
const omittedId = await seedIssue(x.companyId, {
parentId: x.boundaryId, status: "blocked", issueNumber: 1100,
});
await db.insert(heartbeatRuns).values({
companyId: x.companyId, agentId: x.agentId, status: "running",
contextSnapshot: { issueId: omittedId },
});
expect(await x.service.reconcileTaskWatchdogs({ companyId: x.companyId }))
.toMatchObject({ checked: 1, triggered: 0, incomplete: 1, incompleteIssueIds: [x.sourceId], skipped: 0 });
expect(x.wakes).toHaveLength(0);
const [persisted] = await db.select().from(issueWatchdogs).where(eq(issueWatchdogs.id, x.watchdog.id));
expect(persisted!.watchdogIssueId).toBeNull();
expect(persisted!.lastObservedFingerprint).toBeNull();
});
it("allows a complete boundary leaf but revokes its scope when an omitted child appears", async () => {
const x = await seedDeepSubtree();
expect((await x.service.reconcileTaskWatchdogs({ companyId: x.companyId })).triggered).toBe(1);
const [persisted] = await db.select().from(issueWatchdogs).where(eq(issueWatchdogs.id, x.watchdog.id));
const scope = {
kind: "watchdog" as const, watchdogId: x.watchdog.id, companyId: x.companyId,
watchedIssueId: x.sourceId, stopFingerprint: persisted!.lastObservedFingerprint,
};
expect((await x.service.revalidateMutationScope(scope)).allowed).toBe(true);
const omittedId = await seedIssue(x.companyId, {
parentId: x.boundaryId, status: "blocked", issueNumber: 1100,
});
await db.insert(heartbeatRuns).values({
companyId: x.companyId, agentId: x.agentId, status: "running",
contextSnapshot: { issueId: omittedId },
});
const incomplete = await x.service.revalidateMutationScope(scope);
expect(incomplete.allowed).toBe(false);
expect(incomplete.classification?.state).toBe("incomplete");
expect(incomplete.reason).toContain("incomplete");
expect(await x.service.reconcileForIssueAndAncestors(x.companyId, x.sourceId))
.toMatchObject({ triggered: 0, incomplete: 1, incompleteIssueIds: [x.sourceId], skipped: 0 });
expect(x.wakes).toHaveLength(1);
await db.update(issues).set({ parentId: x.sourceId }).where(eq(issues.id, omittedId));
const visible = await x.service.revalidateMutationScope(scope);
expect(visible.allowed).toBe(false);
expect(visible.classification?.state).toBe("live");
});
it("does not treat excluded boundary children as a truncated watched subtree", async () => {
const x = await seedDeepSubtree();
const hiddenId = await seedIssue(x.companyId, { parentId: x.boundaryId, issueNumber: 1100 });
await db.update(issues).set({ hiddenAt: new Date() }).where(eq(issues.id, hiddenId));
const harnessId = await seedIssue(x.companyId, { parentId: x.boundaryId, issueNumber: 1103 });
await db.update(issues).set({ harnessKind: "test" }).where(eq(issues.id, harnessId));
await seedIssue(x.companyId, {
parentId: x.boundaryId, issueNumber: 1101, originKind: "task_watchdog", originId: x.boundaryId,
});
const otherCompanyId = await seedCompany();
await seedIssue(otherCompanyId, { parentId: x.boundaryId, issueNumber: 1102 });
expect((await x.service.reconcileTaskWatchdogs({ companyId: x.companyId })).triggered).toBe(1);
expect(x.wakes).toHaveLength(1);
});
it("reconciles ancestor watchdogs for a descendant issue mutation", async () => {
const companyId = await seedCompany();
const sourceId = await seedIssue(companyId, { identifier: "WDOG-ANCESTOR", status: "done" });
@@ -1428,7 +1428,8 @@ describeEmbeddedPostgres("tool gateway service", () => {
(query.includes('min(') || query.includes('"expires_at" <=') || query.includes('"expires_at" is not null'))) reads.push({ query, params: [...params] });
};
try { await settle(6000); } finally { db.$client.options.debug = debug; }
expect(reads.some(read => read.query.includes('"expires_at" <=') || query.includes('"expires_at" is not null'))).toBe(true);
expect(reads.some(read => read.query.includes('"expires_at" <='))).toBe(true);
expect(reads.some(read => read.query.includes('"expires_at" is not null'))).toBe(true);
for (const read of reads) {
expect(read.query).toContain('"tool_action_requests"."company_id" =');
expect(read.params).toContain(fixture.company.id);
+6
View File
@@ -97,6 +97,7 @@ import detectPort from "detect-port";
import { createApp } from "./app.js";
import { loadConfig } from "./config.js";
import { logger } from "./middleware/logger.js";
import { createIncompleteTaskWatchdogScanReporter } from "./services/task-watchdog-diagnostics.js";
import { setStartupRecoveryPhase } from "./startup-recovery-state.js";
import {
StartupRefusalError,
@@ -939,6 +940,9 @@ async function startServerWithDatabaseTeardown(
}
};
const pluginWorkerManager = createPluginWorkerManager();
const reportIncompleteWatchdogScans = createIncompleteTaskWatchdogScanReporter(
(details, message) => logger.warn(details, message),
);
const heartbeat = config.heartbeatSchedulerEnabled
? heartbeatService(db as any, { pluginWorkerManager })
: null;
@@ -1771,6 +1775,7 @@ async function startServerWithDatabaseTeardown(
}
const taskWatchdogsReconciled = await heartbeat.reconcileTaskWatchdogs();
reportIncompleteWatchdogScans(taskWatchdogsReconciled, "startup");
if (taskWatchdogsReconciled.triggered > 0) {
logger.warn(
{ ...taskWatchdogsReconciled },
@@ -1959,6 +1964,7 @@ async function startServerWithDatabaseTeardown(
})
.then(async () => {
const reconciled = await heartbeat.reconcileTaskWatchdogs();
reportIncompleteWatchdogScans(reconciled, "periodic");
if (reconciled.triggered > 0) {
logger.warn({ ...reconciled }, "periodic task-watchdog reconciliation triggered watchdog work");
}
@@ -16,7 +16,7 @@ import { errorHandler } from "../../../middleware/error-handler.js";
import { createLifecycleDriver } from "../../../services/agent-lifecycle-driver.js";
import { randomUUID } from "node:crypto";
import { and, eq, sql } from "drizzle-orm";
import { agents, approvals, projects, issues, heartbeatRuns, nativeRunFinalizations, budgetPolicies, environmentLeases, agentApiKeys, activityLog, agentConfigRevisions, userCompanyPreferences, companies, companyMemberships, principalPermissionGrants, plugins, pluginCompanySettings, createDb, type Db } from "@paperclipai/db";
import { agents, approvals, projects, issues, heartbeatRuns, nativeRunFinalizations, budgetPolicies, environmentLeases, environments, agentApiKeys, activityLog, agentConfigRevisions, userCompanyPreferences, companies, companyMemberships, principalPermissionGrants, plugins, pluginCompanySettings, createDb, type Db } from "@paperclipai/db";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js";
import { createAgentLifecycle, configureAgentLifecycle, startAgentLifecycle } from "../../../services/agent-lifecycle.js";
@@ -48,6 +48,24 @@ const support = await getEmbeddedPostgresTestSupport();
async function hire(status = "idle") { return createAgentLifecycle(db).requestHire(companyId, { name: "Agent", status, adapterType: "process" }); }
async function current(id: string) { return (await db.select().from(agents).where(eq(agents.id, id)))[0]!; }
it.each((["codex", "claude"] as const).flatMap(provider => ["direct", "setup", "approval"].map(path => [provider, path] as const)))("defaults a newly hired %s agent on a warm task environment to warm execution through %s", async (provider, path) => {
const pluginId = randomUUID(), environmentId = randomUUID();
await db.insert(plugins).values({ id: pluginId, pluginKey: pluginId, packageName: "warm-hire-fixture", version: "1.0.0", status: "ready",
manifestJson: { capabilities: ["environment.drivers.register"], environmentDrivers: [{ driverKey: "tasks", supportsTasks: true, warmTaskVersion: 1 }] } as never });
await db.insert(environments).values({ id: environmentId, name: `Warm computer ${environmentId}`, driver: "plugin",
config: { pluginKey: pluginId, driverKey: "tasks", driverConfig: {} } });
const adapterConfig = provider === "claude" ? { provider: "acpx", acpxAgent: "claude", model: "claude-sonnet-4-6", lifecycleMode: "per_turn" }
: { provider: "codex", model: "gpt-5.6-luna", lifecycleMode: "per_turn" };
const lifecycle = createAgentLifecycle(db);
const input = { name: "Warm hire", adapterType: "paperclip_runner", adapterConfig, defaultEnvironmentId: environmentId };
const draft = path === "setup" ? await lifecycle.requestHire(companyId, input, { setupOnly: true }) : null;
const hired = await lifecycle.requestHire(companyId, { ...input, ...(path === "approval" ? { status: "pending_approval" } : {}) }, draft ? { setupAgentId: draft.id } : undefined);
if (path === "approval") await lifecycle.approveHire(hired.id, "board");
expect((await current(hired.id)).adapterConfig).toMatchObject({ ...adapterConfig, lifecycleMode: "warm" });
await createAgentLifecycle(db).updateConfiguration(hired.id, { adapterConfig: { ...(await current(hired.id)).adapterConfig, lifecycleMode: "per_turn" } });
expect((await current(hired.id)).adapterConfig.lifecycleMode).toBe("per_turn");
});
it("rejects an outdated configuration snapshot under the write lock", async () => {
const agent = await hire();
const snapshot = await current(agent.id);
@@ -116,29 +134,8 @@ const support = await getEmbeddedPostgresTestSupport();
expect(agent).not.toHaveProperty("lifecycleOperation");
});
it("keeps early setup inactive and completes the same record without renaming it", async () => {
const runHost = vi.fn(async () => "complete" as const);
const work = worker(runHost);
const lifecycle = createAgentLifecycle(db);
const id = randomUUID();
const input = { id, name: "Early agent", adapterType: "process" };
const first = await lifecycle.requestHire(companyId, input, { setupOnly: true });
const retry = await lifecycle.requestHire(companyId, input, { setupOnly: true });
expect(first.id).toBe(id);
expect(retry.id).toBe(id);
await work.process(id);
expect(runHost).not.toHaveBeenCalled();
expect(await current(id)).toMatchObject({ status: "paused", lifecycleState: "paused", lifecycleHolds: ["setup"] });
expect(await db.select().from(principalPermissionGrants).where(eq(principalPermissionGrants.principalId, id))).toHaveLength(0);
await expect(agentConfiguration(db).createApiKey(id, "Incomplete setup")).rejects.toThrow("Finish agent setup");
await expect(lifecycle.resumeAgent(id)).rejects.toThrow("Finish agent setup");
const finished = await lifecycle.requestHire(companyId, { id, name: "Early agent", adapterType: "process", status: "idle" }, { setupAgentId: id });
expect(finished).toMatchObject({ id, name: "Early agent" });
await work.process(id);
expect(await current(id)).toMatchObject({ status: "idle", lifecycleState: "ready", lifecycleHolds: [] });
expect(await db.select().from(agents).where(eq(agents.companyId, companyId))).toHaveLength(1);
await expect(lifecycle.requestHire(companyId, { id, name: "Early agent" }, { setupAgentId: id })).rejects.toThrow("no longer available");
});
it("freezes the final setup configuration for hire approval", async () => {
const lifecycle = createAgentLifecycle(db);
@@ -160,6 +157,7 @@ const support = await getEmbeddedPostgresTestSupport();
expect((await current(setup.id)).lifecycleHolds).toEqual(["setup"]);
});
it("creates a board-owned setup before requesting approval for its final configuration", async () => {
await db.update(companies).set({ requireBoardApprovalForNewAgents: true }).where(eq(companies.id, companyId));
await db.insert(companyMemberships).values(["board", "other-creator"].map(principalId => ({ companyId, principalType: "user", principalId, membershipRole: "member" })));
@@ -0,0 +1,156 @@
import { randomUUID } from "node:crypto";
import express from "express";
import request from "supertest";
import { eq } from "drizzle-orm";
import { agents, companies, companyMemberships, principalPermissionGrants, environments, plugins, createDb, type Db } from "@paperclipai/db";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js";
import { createAgentLifecycle, configureAgentLifecycle, createAgentLifecycleEffects } from "../../../services/agent-lifecycle.js";
import { agentService as agentConfiguration } from "../../../services/agents.js";
import { createLifecycleDriver } from "../../../services/agent-lifecycle-driver.js";
import { agentRoutes } from "../../../routes/agents.js";
import { errorHandler } from "../../../middleware/error-handler.js";
import { createLifecycleStore as createStore } from "../adapters/postgres.js";
import type { LifecycleAgent } from "../application/ports.js";
const createLifecycleStore = (db: Db) => createStore(db, createAgentLifecycleEffects());
const support = await getEmbeddedPostgresTestSupport();
(support.supported ? describe : describe.skip)("agent setup lifecycle", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: Db;
let companyId: string;
const workers: ReturnType<typeof configureAgentLifecycle>[] = [];
beforeAll(async () => { database = await startEmbeddedPostgresTestDatabase("paperclip-agent-setup-"); db = createDb(database.connectionString); }, 90_000);
afterAll(async () => { for (const work of workers) await work.stop(); await database?.cleanup(); });
beforeEach(async () => {
for (const work of workers) await work.stop();
companyId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Setup test", issuePrefix: `S${companyId.slice(0, 7)}` });
});
function worker(runHost: (agent: LifecycleAgent) => Promise<"complete" | "pending"> = async () => "complete") {
const work = configureAgentLifecycle(db, { requiredPluginIds: async () => [], runPlugin: async () => "complete", runHost });
workers.push(work); return work;
}
async function current(id: string) { return (await db.select().from(agents).where(eq(agents.id, id)))[0]!; }
it("keeps early setup inactive and completes the same record without renaming it", async () => {
const runHost = vi.fn(async () => "complete" as const);
const work = worker(runHost);
const lifecycle = createAgentLifecycle(db);
const id = randomUUID();
const input = { id, name: "Early agent", adapterType: "process" };
const first = await lifecycle.requestHire(companyId, input, { setupOnly: true });
const retry = await lifecycle.requestHire(companyId, input, { setupOnly: true });
expect(first.id).toBe(id);
expect(retry.id).toBe(id);
await work.process(id);
expect(runHost).not.toHaveBeenCalled();
expect(await current(id)).toMatchObject({ status: "paused", lifecycleState: "paused", lifecycleHolds: ["setup"] });
expect(await db.select().from(principalPermissionGrants).where(eq(principalPermissionGrants.principalId, id))).toHaveLength(0);
await expect(agentConfiguration(db).createApiKey(id, "Incomplete setup")).rejects.toThrow("Finish agent setup");
await expect(lifecycle.resumeAgent(id)).rejects.toThrow("Finish agent setup");
const finished = await lifecycle.requestHire(companyId, { id, name: "Early agent", adapterType: "process", status: "idle" }, { setupAgentId: id });
expect(finished).toMatchObject({ id, name: "Early agent" });
await work.process(id);
expect(await current(id)).toMatchObject({ status: "idle", lifecycleState: "ready", lifecycleHolds: [] });
expect(await db.select().from(agents).where(eq(agents.companyId, companyId))).toHaveLength(1);
await expect(lifecycle.requestHire(companyId, { id, name: "Early agent" }, { setupAgentId: id })).rejects.toThrow("no longer available");
});
it("prepares agent-dependent drafts, stays idle until finish, and invalidates changed environments", async () => {
const pluginId = randomUUID(), environmentId = randomUUID();
await db.insert(plugins).values({ id: pluginId, pluginKey: pluginId, packageName: "agent-environment-test", version: "1.0.0", status: "ready",
manifestJson: { agentLifecycle: true, capabilities: ["agents.lifecycle.manage", "environment.drivers.register"],
environmentDrivers: [{ driverKey: "tasks", requiresAgent: true, supportsTasks: true }] } as never });
await db.insert(environments).values({ id: environmentId, name: "Agent-owned test computer", driver: "plugin", status: "active",
config: { pluginKey: pluginId, driverKey: "tasks", driverConfig: {} } });
const call = vi.fn(async (_id, _method, input) => ({ operationId: input.operationId, version: input.version, status: "complete" }));
const driver = createLifecycleDriver(db, { call } as never);
const runHost = vi.fn(async () => "complete" as const);
const work = configureAgentLifecycle(db, { ...driver, requiredPluginIds: async () => [pluginId], runHost });
workers.push(work);
const lifecycle = createAgentLifecycle(db);
const id = randomUUID();
const input = { id, name: "Early computer", adapterType: "paperclip_runner", adapterConfig: { provider: "codex" }, defaultEnvironmentId: environmentId };
const draft = await lifecycle.requestHire(companyId, input, { setupOnly: true, runnerResolved: true });
expect(draft).toMatchObject({ lifecycleState: "preparing", status: "paused", pauseReason: "setup" });
await work.process(id);
expect(await current(id)).toMatchObject({ lifecycleState: "verifying", status: "paused", lifecycleHolds: ["setup"] });
expect(call.mock.calls.map(([, , request]) => request.phase)).toEqual(["preparing"]);
const store = createLifecycleStore(db);
expect(await store.pending(100, new Date())).not.toContain(id);
expect(await store.claim(id, "unexpected", new Date())).toBeNull();
await work.process(id);
expect(runHost).toHaveBeenCalledTimes(1);
await expect(agentConfiguration(db).createApiKey(id, "Incomplete computer")).rejects.toThrow("Finish agent setup");
await expect(lifecycle.resumeAgent(id)).rejects.toThrow("Finish agent setup");
await lifecycle.pauseAgent(id, "budget"); await work.process(id);
expect(await current(id)).toMatchObject({ lifecycleState: "paused", lifecycleHolds: ["setup", "budget"] });
await lifecycle.updateConfiguration(id, { adapterConfig: { provider: "codex", model: "changed" } });
expect((await current(id)).lifecycleState).toBe("paused");
await store.change(id, "reconcile"); await work.process(id);
expect(await current(id)).toMatchObject({ lifecycleState: "verifying", lifecycleHolds: ["setup"] });
await lifecycle.updateConfiguration(id, { adapterConfig: { provider: "codex", model: "prepared" } });
await work.process(id);
expect((await current(id)).lifecycleState).toBe("verifying");
const [local] = await db.select().from(environments).where(eq(environments.driver, "local"));
await lifecycle.updateConfiguration(id, { defaultEnvironmentId: local.id }); await work.process(id);
expect((await current(id)).lifecycleState).toBe("paused");
await lifecycle.updateConfiguration(id, { defaultEnvironmentId: environmentId }); await work.process(id);
expect((await current(id)).lifecycleState).toBe("verifying");
await lifecycle.updateConfiguration(id, { defaultEnvironmentId: local.id });
expect((await current(id)).lifecycleState).toBe("pausing");
await lifecycle.updateConfiguration(id, { defaultEnvironmentId: environmentId });
await work.process(id);
expect((await current(id)).lifecycleState).toBe("verifying");
const finished = await lifecycle.requestHire(companyId, input, { setupAgentId: id, runnerResolved: true });
expect(finished.id).toBe(id);
await work.process(id);
expect(await current(id)).toMatchObject({ lifecycleState: "ready", lifecycleHolds: [] });
expect(call.mock.calls.map(([, , request]) => request.phase).at(-1)).toBe("verifying");
});
it("does not prepare agent-owned resources before required hire approval", async () => {
const pluginId = randomUUID(), environmentId = randomUUID();
await db.update(companies).set({ requireBoardApprovalForNewAgents: true }).where(eq(companies.id, companyId));
await db.insert(plugins).values({ id: pluginId, pluginKey: pluginId, packageName: "approval-computer-test", version: "1.0.0", status: "ready",
manifestJson: { agentLifecycle: true, capabilities: ["agents.lifecycle.manage", "environment.drivers.register"],
environmentDrivers: [{ driverKey: "tasks", requiresAgent: true, supportsTasks: true }] } as never });
await db.insert(environments).values({ id: environmentId, name: "Approval computer", driver: "plugin", status: "active",
config: { pluginKey: pluginId, driverKey: "tasks", driverConfig: {} } });
const runHost = vi.fn(async () => "complete" as const);
const work = worker(runHost);
const lifecycle = createAgentLifecycle(db);
const draft = await lifecycle.requestHire(companyId, { name: "Unapproved computer", adapterType: "paperclip_runner",
adapterConfig: { provider: "codex" }, defaultEnvironmentId: environmentId }, { setupOnly: true, runnerResolved: true });
await work.process(draft.id);
await lifecycle.updateConfiguration(draft.id, { adapterConfig: { provider: "codex", model: "changed" } });
await work.process(draft.id);
expect(await current(draft.id)).toMatchObject({ lifecycleState: "paused", lifecycleHolds: ["setup"] });
expect(runHost).not.toHaveBeenCalled();
});
it("lets only the setup creator configure and retry a stopping draft with creation permission", async () => {
await db.insert(companyMemberships).values(["setup-owner", "setup-other"].map(principalId => ({ companyId,
principalType: "user", principalId, membershipRole: "member" })));
await db.insert(principalPermissionGrants).values(["setup-owner", "setup-other"].map(principalId => ({ companyId,
principalType: "user", principalId, permissionKey: "agents:create" })));
const lifecycle = createAgentLifecycle(db);
const draft = await lifecycle.requestHire(companyId, { name: "Stopping setup", adapterType: "process" },
{ setupOnly: true, createdByUserId: "setup-owner" });
await db.update(agents).set({ lifecycleState: "pausing" }).where(eq(agents.id, draft.id));
function app(userId: string) {
const value = express(); value.use(express.json());
value.use((req, _res, next) => { req.actor = { type: "board", source: "session", userId,
companyIds: [companyId], memberships: [{ companyId, membershipRole: "member", status: "active" }] }; next(); });
value.use("/api", agentRoutes(db)); value.use(errorHandler); return value;
}
const updated = await request(app("setup-owner")).patch(`/api/agents/${draft.id}`).send({ runtimeConfig: { heartbeat: { enabled: false } } });
expect(updated.status, JSON.stringify(updated.body)).toBe(200);
await request(app("setup-owner")).post(`/api/agents/${draft.id}/lifecycle/retry`).send({}).expect(200);
await request(app("setup-other")).patch(`/api/agents/${draft.id}`).send({ runtimeConfig: { heartbeat: { enabled: true } } }).expect(403);
await request(app("setup-other")).post(`/api/agents/${draft.id}/lifecycle/retry`).send({}).expect(403);
await expect(lifecycle.requestHire(companyId, { name: draft.name }, { setupAgentId: draft.id })).rejects.toThrow("no longer available");
expect((await current(draft.id)).lifecycleState).toBe("pausing");
});
});
@@ -21,10 +21,17 @@ export async function updateAgentConfiguration(tx: Db, effects: LifecycleEffects
assertConfigurationFields(patch);
const changed = ["adapterType", "adapterConfig", "runtimeConfig", "defaultEnvironmentId"].some(key =>
Object.prototype.hasOwnProperty.call(patch, key) && !jsonEqual(patch[key as keyof typeof patch], current[key as keyof typeof current]));
const invalidate = changed && ["preparing", "verifying", "resuming"].includes(current.lifecycleState);
const prepareSetup = changed && current.lifecycleHolds.length === 1 && current.lifecycleHolds[0] === "setup"
&& ["paused", "preparing", "verifying"].includes(current.lifecycleState)
&& await effects.setupRequiresPreparation(tx, current.companyId,
Object.prototype.hasOwnProperty.call(patch, "defaultEnvironmentId") ? patch.defaultEnvironmentId : current.defaultEnvironmentId);
const invalidate = changed && (["preparing", "verifying", "resuming"].includes(current.lifecycleState) || prepareSetup);
if (invalidate) await effects.notifyWork(tx);
const [updated] = await tx.update(agents).set({ ...patch, updatedAt: new Date(), ...(invalidate ? {
lifecycleVersion: current.lifecycleVersion + 1, lifecycleError: null,
...(prepareSetup ? { lifecycleState: "preparing" as const } : {}),
...(!prepareSetup && current.lifecycleHolds.includes("setup") && ["preparing", "verifying"].includes(current.lifecycleState)
? { lifecycleState: "pausing" as const } : {}),
lifecycleOperation: { ...current.lifecycleOperation!, id: randomUUID(), hostComplete: false,
completedPluginIds: [], leaseOwner: undefined, leaseUntil: undefined, retryAt: undefined },
} : {}) }).where(eq(agents.id, id)).returning();
@@ -6,6 +6,7 @@ import type { ActivityPublication } from "../../../types/activity-publication.js
/** Services supply integrations; lifecycle owns the transaction and state writes. */
export interface LifecycleEffects {
setupRequiresPreparation(db: Db, companyId: string, environmentId?: string | null): Promise<boolean>;
notifyWork(db: Db): Promise<void>;
reportFailure(context: LifecycleFailure, error: unknown): void;
deleteDependencies(db: Db, companyId: string, agentId: string): Promise<void>;
@@ -13,6 +13,12 @@ export function assertRootDatabase(db: Db) {
type LifecycleRow = typeof agents.$inferSelect;
type ChangeOptions = { version?: number; owner?: string; reason?: string };
// Prepared drafts wait for the wizard; they have no background verification obligation.
export const pendingLifecycleWork = and(
inArray(agents.lifecycleState, ["preparing", "verifying", "pausing", "resuming", "terminating", "cleaning_up"]),
sql`not (${agents.lifecycleState} = 'verifying' and ${agents.lifecycleHolds} @> '["setup"]'::jsonb)`,
);
/** The caller owns the accounting transaction and has locked this agent. */
async function changeLockedAgent(tx: Db, effects: LifecycleEffects, agent: LifecycleRow,
command: LifecycleCommand, options: ChangeOptions = {}, policyHolds?: string[], restartPause = false) {
@@ -47,14 +53,17 @@ async function changeLockedAgent(tx: Db, effects: LifecycleEffects, agent: Lifec
}
if (command === "pause") holds = [...new Set([...holds, reason])];
if (command === "resume") holds = holds.filter(hold => reason === "user" ? ["budget", "company_archived", "company_paused"].includes(hold) : hold !== reason);
const blockingHolds = holds.filter(hold => hold !== "setup" || !["preparing", "verifying"].includes(agent.lifecycleState));
let next = command === "reconcile"
? holds.length && !["pausing", "paused"].includes(agent.lifecycleState) ? "pausing" as const
? blockingHolds.length && !["pausing", "paused"].includes(agent.lifecycleState) ? "pausing" as const
: !holds.length && agent.lifecycleState === "paused" ? "resuming" as const : agent.lifecycleState
: command === "resume" && (holds.length || agent.lifecycleState === "pausing") ? agent.lifecycleState
: transition(agent.lifecycleState, command, agent.lifecycleOperation?.resumeState);
if (restartPause && next === "paused") next = "pausing";
if (command === "complete" && next === "ready" && holds.length) next = "pausing";
if (command === "complete" && next === "paused" && !holds.length) next = "resuming";
if (["complete", "reconcile"].includes(command) && next === "paused" && holds.length === 1 && holds[0] === "setup"
&& await effects.setupRequiresPreparation(tx, agent.companyId, agent.defaultEnvironmentId)) next = "preparing";
if (next === agent.lifecycleState) {
if (JSON.stringify(holds) !== JSON.stringify(agent.lifecycleHolds) || agent.pauseReason !== (holds[0] ?? null)) {
const [updated] = await tx.update(agents).set({ lifecycleHolds: holds, pauseReason: holds[0] ?? null }).where(eq(agents.id, agent.id)).returning();
@@ -131,7 +140,7 @@ export function createLifecycleStore(db: Db, effects: LifecycleEffects): Lifecyc
lifecycleOperation: sql`coalesce(${agents.lifecycleOperation}, '{"id":"", "hostComplete":false, "completedPluginIds":[], "attempts":0}'::jsonb)
|| jsonb_build_object('leaseOwner', ${owner}::text, 'leaseUntil', ${(new Date(now.getTime() + 120_000)).toISOString()}::text,
'attempts', coalesce((${agents.lifecycleOperation}->>'attempts')::integer, 0) + 1)`,
}).where(and(eq(agents.id, id), inArray(agents.lifecycleState, ["preparing", "verifying", "pausing", "resuming", "terminating", "cleaning_up"]),
}).where(and(eq(agents.id, id), pendingLifecycleWork,
sql`(${agents.lifecycleState} in ('pausing', 'terminating', 'cleaning_up') or exists (
select 1 from ${companies} where ${companies.id} = ${agents.companyId} and ${companies.status} = 'active'))`,
sql`coalesce((${agents.lifecycleOperation}->>'leaseUntil')::timestamptz, '-infinity') <= ${now.toISOString()}::timestamptz`,
@@ -179,7 +188,7 @@ export function createLifecycleStore(db: Db, effects: LifecycleEffects): Lifecyc
},
async pending(limit, now) {
return db.select({ id: agents.id }).from(agents).where(and(
inArray(agents.lifecycleState, ["preparing", "verifying", "pausing", "resuming", "terminating", "cleaning_up"]),
pendingLifecycleWork,
sql`coalesce((${agents.lifecycleOperation}->>'leaseUntil')::timestamptz, '-infinity') <= ${now.toISOString()}::timestamptz`,
sql`coalesce((${agents.lifecycleOperation}->>'retryAt')::timestamptz, '-infinity') <= ${now.toISOString()}::timestamptz`,
)).orderBy(asc(agents.updatedAt), asc(agents.id)).limit(limit).then(rows => rows.map(row => row.id));
@@ -4,6 +4,7 @@ import { and, eq, sql } from "drizzle-orm";
import { agents, agentApiKeys, companies, type Db } from "@paperclipai/db";
import { conflict, notFound } from "../../../errors.js";
import { agentRecordQueries, type CreateAgentOptions, type CreateAgentData } from "../../../lib/agent-records.js";
import { isAgentSetupDraft } from "../domain/policy.js";
export function agentRecords(db: Db, effects: LifecycleEffects) {
const { getById } = agentRecordQueries(db);
@@ -25,7 +26,7 @@ export function agentRecords(db: Db, effects: LifecycleEffects) {
if (!existing) throw notFound("Agent setup not found");
return existing;
}
if (setup && (setup.lifecycleState !== "paused" || !setup.lifecycleHolds.includes("setup"))) {
if (setup && (!isAgentSetupDraft(setup) || setup.lifecycleState === "pausing" || !setup.lifecycleHolds.includes("setup"))) {
throw conflict("Agent setup is no longer available");
}
if (options?.setupAgentId && !setup) throw notFound("Agent setup not found");
@@ -35,8 +36,9 @@ export function agentRecords(db: Db, effects: LifecycleEffects) {
const [company] = await tx.select({ status: companies.status }).from(companies).where(eq(companies.id, companyId));
const companyHolds = company?.status === "paused" ? ["company_paused"] : company?.status === "archived" ? ["company_archived"] : [];
const holds = [...(status === "paused" ? [pauseReason ?? "manual"] : []), ...companyHolds];
const prepareSetup = options?.setupOnly && !companyHolds.length && await effects.setupRequiresPreparation(txDb, companyId, prepared.defaultEnvironmentId);
const lifecycleState = status === "pending_approval" ? "pending_approval" : status === "terminated" ? "terminated"
: status === "paused" ? "paused" : companyHolds.length ? "pausing" : "preparing";
: prepareSetup ? "preparing" : status === "paused" ? "paused" : companyHolds.length ? "pausing" : "preparing";
if (lifecycleState === "preparing" || lifecycleState === "pausing") await effects.notifyWork(tx);
const values: typeof agents.$inferInsert = {
...prepared,
@@ -5,6 +5,10 @@ export class AgentLifecycleConflict extends Error {
constructor(message: string) { super(message); this.name = "AgentLifecycleConflict"; }
}
export function isAgentSetupDraft(agent: { lifecycleState?: string; pauseReason?: string | null }) {
return agent.pauseReason === "setup" && ["paused", "preparing", "verifying", "pausing"].includes(agent.lifecycleState ?? "");
}
export function canConfigureAgentConnection(agent: { lifecycleState: string; status: string }): boolean {
return agent.lifecycleState === "preparing" || agent.lifecycleState === "verifying"
|| (agent.lifecycleState === "ready" && !["paused", "terminated", "pending_approval"].includes(agent.status));
+3 -4
View File
@@ -8,7 +8,7 @@ import { updateAgentConfiguration } from "./adapters/configuration.js";
import type { AgentConfigurationPatch, UpdateAgentOptions } from "../../lib/agent-records.js";
import { purgeAgent } from "./adapters/deletion.js";
import { agentRecords } from "./adapters/records.js";
import { assertRootDatabase, createLifecycleStore } from "./adapters/postgres.js";
import { assertRootDatabase, createLifecycleStore, pendingLifecycleWork } from "./adapters/postgres.js";
import { hasCompanyHoldMismatch, projectCompanyHolds } from "./adapters/company-policy.js";
import { createLifecycleWorker } from "./application/worker.js";
import type { LifecycleDriver } from "./application/ports.js";
@@ -16,12 +16,11 @@ import type { LifecycleDriver } from "./application/ports.js";
export { applyAgentPolicyHoldsInTransaction } from "./adapters/postgres.js";
export { companyHoldMismatch, fenceActiveCompanyAgentStopsInTransaction } from "./adapters/company-policy.js";
export { AgentLifecycleConflict, canConfigureAgentConnection, isAgentAwaitingSetup } from "./domain/policy.js";
export { AgentLifecycleConflict, canConfigureAgentConnection, isAgentAwaitingSetup, isAgentSetupDraft } from "./domain/policy.js";
export type { HireDecisionTarget } from "./adapters/approvals.js";
export type { LifecycleDriver, LifecycleAgent, LifecycleFailure } from "./application/ports.js";
const pendingStates = ["preparing", "verifying", "pausing", "resuming", "terminating", "cleaning_up"] as const;
const wakes = new WeakMap<Db, () => void>();
const workers = new WeakMap<Db, ReturnType<typeof createLifecycleWorker>>();
@@ -116,7 +115,7 @@ export function startAgentLifecycle(db: Db, effects: LifecycleEffects, driver: L
const [pending] = await db.select({ due: sql<number | null>`min(greatest(
coalesce(extract(epoch from (${agents.lifecycleOperation}->>'leaseUntil')::timestamptz) * 1000, 0),
coalesce(extract(epoch from (${agents.lifecycleOperation}->>'retryAt')::timestamptz) * 1000, 0)))::double precision` })
.from(agents).where(inArray(agents.lifecycleState, pendingStates));
.from(agents).where(pendingLifecycleWork);
const due = pending?.due == null ? null : Number(pending.due);
const now = Date.now();
// Already-due work uses the coordinator's bounded retry. A zero-delay
+9 -8
View File
@@ -7,6 +7,7 @@ import { resolveNewAgentRunnerForCompany } from "../services/agent-runner-select
import { agentEnvironmentTestService } from "../services/agent-environment-test.js";
import { qualifyAgentRunner } from "../services/agent-runner-qualification.js";
import { createAgentLifecycle } from "../services/agent-lifecycle.js";
import { isAgentSetupDraft } from "../modules/agent-lifecycle/index.js";
import { agentIdentityService } from "../services/agent-identity.js";
import { aiConnectionRouterService, poolMemberRuntimeConfig } from "../services/ai-connection-router.js";
@@ -1797,7 +1798,7 @@ export function agentRoutes(
id: string; companyId: string; createdByUserId?: string | null; lifecycleState?: string; pauseReason?: string | null;
}, allowCompleted = false) {
if (req.actor.type === "board" && req.actor.userId && targetAgent.createdByUserId === req.actor.userId
&& (allowCompleted || (targetAgent.lifecycleState === "paused" && targetAgent.pauseReason === "setup"))) {
&& (allowCompleted || isAgentSetupDraft(targetAgent))) {
await assertCanCreateAgentsForCompany(req, targetAgent.companyId);
return;
}
@@ -3181,7 +3182,7 @@ export function agentRoutes(
const testEnvironmentId = await resolveAdapterTestEnvironmentId(companyId, environmentId, binding.provider === "github");
if (testEnvironmentId) await assertAdapterTestEnvironmentForCompany(companyId, testEnvironmentId, adapterType);
const hasSavedAgent = !newAgent || (isUuidLike(agentId) && Boolean(await svc.getById(agentId)));
if (!hasSavedAgent && !test && testEnvironmentId && (await environmentsSvc.getById(testEnvironmentId))?.driver === "plugin") {
if (newAgent && !test && testEnvironmentId && (await environmentsSvc.getById(testEnvironmentId))?.driver === "plugin") {
// The lifecycle verifies the saved agent after its plugin can create the agent-owned computer.
return { connectionId: selection.connection.id };
}
@@ -3229,7 +3230,7 @@ export function agentRoutes(
if (savedAgent.companyId !== companyId) throw notFound("Agent not found");
await assertCanConfigureAgentSetup(req, savedAgent);
}
const testingSetup = savedAgent?.lifecycleState === "paused" && savedAgent.pauseReason === "setup";
const testingSetup = savedAgent ? isAgentSetupDraft(savedAgent) : false;
const poolBinding = requestedBinding ?? (savedAgent?.runtimeConfig?.aiConnection ? aiRuntimeConnectionBindingSchema.parse(savedAgent.runtimeConfig.aiConnection) : undefined);
const requestedEnvironmentId = await resolveAdapterTestEnvironmentId(
companyId,
@@ -5546,7 +5547,7 @@ export function agentRoutes(
&& (["openai_dot", "muse"].includes(String(rawEffectiveAdapterConfig.provider)) || ["openai_dot", "muse"].includes(String(existingRunnerProvider)))) {
await assertSelectableAdapterType(requestedAdapterType, rawEffectiveAdapterConfig);
}
if (!(existing.lifecycleState === "paused" && existing.pauseReason === "setup") && (
if (!isAgentSetupDraft(existing) && (
changingAdapterType ||
(requestedAdapterType === "paperclip_runner" &&
(requestedAdapterConfig !== null ||
@@ -5581,7 +5582,7 @@ export function agentRoutes(
}
const nextAiConfig = (patchData.adapterConfig ?? existing.adapterConfig) as Record<string, unknown>;
if (existing.runtimeConfig.aiConnection && requestedRuntimeConfig && !requestedRuntimeConfig.aiConnection
&& !(existing.lifecycleState === "paused" && existing.pauseReason === "setup")) {
&& !isAgentSetupDraft(existing)) {
const existingBinding = aiRuntimeConnectionBindingSchema.safeParse(existing.runtimeConfig.aiConnection).data;
if (existingBinding && agentHarnessType(existing.adapterType, existing.adapterConfig) === agentHarnessType(requestedAdapterType, nextAiConfig)
&& (existingBinding.mode === "router" || isAiConnectionCompatible(existingBinding,
@@ -5590,7 +5591,7 @@ export function agentRoutes(
}
}
if (!requestedRuntimeConfig?.aiConnection && !existing.runtimeConfig.aiConnection
&& !(existing.lifecycleState === "paused" && existing.pauseReason === "setup")
&& !isAgentSetupDraft(existing)
&& requestedAdapterType === "paperclip_runner" && nextAiConfig.provider === "acpx"
&& nextAiConfig.acpxAgent === "copilot"
&& (touchesAdapterConfiguration || Object.prototype.hasOwnProperty.call(patchData, "defaultEnvironmentId"))) {
@@ -5606,7 +5607,7 @@ export function agentRoutes(
const copilotConfigurationChanged = requestedAdapterType === "paperclip_runner" && aiConfig.provider === "acpx" && aiConfig.acpxAgent === "copilot"
&& (touchesAdapterConfiguration || Object.prototype.hasOwnProperty.call(patchData, "defaultEnvironmentId"));
if (runtimeSettings || changed || copilotConfigurationChanged || (nextAiBinding.mode === "router" && requestedAdapterType !== existing.adapterType)) {
const configuringSetup = existing.lifecycleState === "paused" && existing.pauseReason === "setup";
const configuringSetup = isAgentSetupDraft(existing);
await validateManagedAgentBinding(req, existing.companyId, existing.id, requestedAdapterType, aiConfig, nextAiBinding,
(patchData.defaultEnvironmentId !== undefined ? patchData.defaultEnvironmentId : existing.defaultEnvironmentId) as string | null,
!configuringSetup && (!runtimeSettings || changed), configuringSetup, Boolean(runtimeSettings));
@@ -5684,7 +5685,7 @@ export function agentRoutes(
const id = req.params.id as string;
const existing = await getAccessibleAgent(req, res, id);
if (!existing) return;
await assertCanUpdateAgent(req, existing);
await assertCanConfigureAgentSetup(req, existing);
const agent = await svcLifecycle.retry(id);
if (!agent) { res.status(404).json({ error: "Agent not found" }); return; }
const actor = getActorInfo(req);
+4
View File
@@ -528,6 +528,8 @@ function noopTaskWatchdogService(): TaskWatchdogService {
live: 0,
pendingFirstRun: 0,
alreadyReviewed: 0,
incomplete: 0,
incompleteIssueIds: [],
skipped: 0,
watchdogIssueIds: [],
}),
@@ -535,6 +537,8 @@ function noopTaskWatchdogService(): TaskWatchdogService {
checked: 0,
triggered: 0,
pendingFirstRun: 0,
incomplete: 0,
incompleteIssueIds: [],
skipped: 0,
watchdogIssueIds: [],
}),
+21
View File
@@ -1430,6 +1430,8 @@ const BOARD_ONLY_OPERATIONS = new Set([
"GET /api/companies/{companyId}/project-repositories",
"PUT /api/projects/{id}/repositories",
"GET /api/projects/{id}/git-authorization",
"PUT /api/projects/{id}/git-authorization",
"DELETE /api/issues/{id}/documents/{key}",
"GET /api/companies/{companyId}/decisions",
"GET /api/cloud/stacks",
@@ -5004,6 +5006,25 @@ registry.registerPath({
},
});
const projectGitAuthorizationResponse = z.object({
grantId: z.string().uuid().nullable(),
authorizedByUserId: z.string().nullable(),
options: z.array(z.object({ grantId: z.string().uuid(), connectionName: z.string(), login: z.string() })),
});
registry.registerPath({
method: "get", path: "/api/projects/{id}/git-authorization", tags: ["projects"],
summary: "Read background project GitHub authorization and the viewer's eligible grants",
request: { params: z.object({ id: z.string() }) },
responses: { 200: r.ok(projectGitAuthorizationResponse), 401: r.unauthorized, 403: r.forbidden, 404: r.notFound },
});
registry.registerPath({
method: "put", path: "/api/projects/{id}/git-authorization", tags: ["projects"],
summary: "Authorize or revoke a personal GitHub grant for background project work",
description: "Board project workspace writers can select only their own active company-installed grant. No task authority or token is stored.",
request: { params: z.object({ id: z.string() }), body: jsonBody(z.object({ grantId: z.string().uuid().nullable() }).strict()) },
responses: { 200: r.ok(projectGitAuthorizationResponse), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound },
});
registry.registerPath({
method: "put",
path: "/api/projects/{id}/repositories",
+17
View File
@@ -1,3 +1,4 @@
import { projectGitAuthorizationService } from "../services/project-git-authorization.js";
import { skillAccessRequestContext } from "../services/skill-access.js";
import { createHash } from "node:crypto";
import { and, eq, sql } from "drizzle-orm";
@@ -296,6 +297,22 @@ export function projectRoutes(db: Db) {
res.json(await toolAccessService(db).listProjectRepositories(companyId, viewer.userId, viewer.localTrusted));
});
router.get("/projects/:id/git-authorization", async (req, res) => {
assertBoard(req);
const project = await getAccessibleResource(req, res, svc.getById(req.params.id as string), "Project not found");
if (!project || !(await assertProjectReadAllowed(req, res, project))) return;
if (!req.actor.userId) throw forbidden("A signed-in user is required");
res.json(await projectGitAuthorizationService(db).read(project.companyId, project.id, req.actor.userId));
});
router.put("/projects/:id/git-authorization", validate(z.object({ grantId: z.string().uuid().nullable() }).strict()), async (req, res) => {
assertBoard(req);
const project = await getAccessibleResource(req, res, svc.getById(req.params.id as string), "Project not found");
if (!project || !(await assertProjectReadAllowed(req, res, project)) || !(await assertProjectWorkspaceWriteAllowed(req, res, project))) return;
if (!req.actor.userId) throw forbidden("A signed-in user is required");
res.json(await projectGitAuthorizationService(db).set(project.companyId, project.id, req.actor.userId, req.body.grantId));
});
router.put("/projects/:id/repositories", validate(z.object({ repositoryIds: z.array(z.string().regex(/^\d+$/)) })), async (req, res) => {
assertBoard(req);
const project = await getAccessibleResource(req, res, svc.getById(req.params.id as string), "Project not found");
@@ -840,7 +840,11 @@ function asAwsSecretsManagerMaterial(value: StoredSecretVersionMaterial): AwsSec
function classifyAwsProviderError(message: string): SecretProviderClientErrorCode {
if (/ResourceExistsException|AlreadyExists/i.test(message)) return "conflict";
if (/ResourceNotFoundException|NotFound/i.test(message)) return "not_found";
if (/AccessDeniedException|AccessDenied|UnrecognizedClientException|InvalidClientTokenId|not authorized/i.test(message)) {
if (
/AccessDeniedException|AccessDenied|CredentialsProviderError|Could not load credentials|credential provider chain|UnrecognizedClientException|InvalidClientTokenId|ExpiredTokenException|InvalidSignatureException|SignatureDoesNotMatch|not authorized/i.test(
message,
)
) {
return "access_denied";
}
if (/Throttl|TooManyRequests|RequestLimitExceeded|Rate exceeded/i.test(message)) return "throttled";
@@ -870,6 +874,9 @@ function awsProviderSafeMessage(code: SecretProviderClientErrorCode): string {
}
function normalizeAwsError(operation: string, error: unknown): never {
if (error instanceof SecretProviderClientError) {
throw error;
}
const rawMessage = error instanceof Error ? error.message : String(error);
const code = classifyAwsProviderError(rawMessage);
throw new SecretProviderClientError({
@@ -96,6 +96,8 @@ Create ordinary assigned tasks, never subtasks of this conversation. Give each t
For review or follow-up tasks, include the existing source materials the assignee needs, not just task identifiers or a rubric. Read the source task's saved documents and comments, then copy the relevant existing content into the handoff or attach resources the recipient can actually read. A new task's tools may only expose its own documents and history. Supplying existing source material is coordination, not creating the assigned deliverable.
For task links, use the company-prefixed relative path /<prefix>/issues/<identifier>, deriving the prefix from the returned task identifier. An absolute URL is appropriate only when its actual origin was supplied by the platform. Never invent a hostname for a Paperclip link.
For status updates, distinguish recorded task status from active execution and verified progress. Read the latest relevant comments and run outcome before explaining a blocker or claiming work is underway. Use the advertised API tools for another task's details when needed. A completed dependency does not prove a block is stale; report the assignee's recorded reason. Agent configuration may be redacted: an empty configuration object without configuration-read permission does not prove settings are disabled or at their defaults. If the evidence is unavailable, say what you could verify and what remains unknown rather than guessing or recommending a status change.
Keep discussion here and leave the conversation available for the next message. Link handed-off tasks in your reply; do not make this conversation blocked by their completion or wait for them. Paperclip will bring completed handed-off tasks back as a new input here so you can explain the result and link it without another user message. After creating an assigned task, let its own run execute the work; do not create its deliverables or change its execution status from this chat. Reply normally and end your turn; Paperclip manages the conversation waiting state. Do not change its status, create a review confirmation just to finish a reply, mark it complete, or poll for another reply. An accepted plan authorizes handoff to execution tasks, never implementation on this conversation. Honor normal approvals. Ask mode is non-mutating. Plan mode supports research and writing/revising the plan; hand off for execution only through the normal authorized workflow.`;
+22 -1
View File
@@ -2,7 +2,8 @@ import { join } from "node:path";
import { probePluginRunnerEnvironment } from "./native-runtime/plugin-runner-probe.js";
import { registerPluginTaskCredentialHandoff } from "./plugin-task-credential-writeback.js";
import { randomUUID } from "node:crypto";
import type { Db } from "@paperclipai/db";
import { agents, companies, type Db } from "@paperclipai/db";
import { and, eq } from "drizzle-orm";
import type { AdapterExecutionTarget } from "@paperclipai/adapter-utils/execution-target";
import type { AdapterEnvironmentCheck } from "@paperclipai/adapter-utils";
import { parseObject } from "@paperclipai/adapter-utils/server-utils";
@@ -19,6 +20,7 @@ import { validateAiApiKey } from "./ai-api-key-test.js";
import { probeCopilotExecutionTarget } from "./copilot-connection-probe.js";
import type { PluginWorkerManager } from "./plugin-worker-manager.js";
import { assertEnvironmentSelectionForCompany } from "./environment-selection.js";
import { pluginEnvironmentRequiresAgent } from "./plugin-environment-driver.js";
const asRecord = (value: unknown): Record<string, unknown> | null => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : null;
export function agentEnvironmentTestService(db: Db, pluginWorkerManager?: PluginWorkerManager) {
const instanceSettings = instanceSettingsService(db);
@@ -212,6 +214,25 @@ export function agentEnvironmentTestService(db: Db, pluginWorkerManager?: Plugin
// agent lease) and archive it on release instead of deleting it, so the
// operator can inspect the exact sandbox from the provider dashboard while
// provider-side expiry reaps it later.
if (environment.driver === "plugin" && await pluginEnvironmentRequiresAgent(db, environment)) {
const [agent] = input.agentId ? await db.select({ state: agents.lifecycleState, pauseReason: agents.pauseReason,
requiresApproval: companies.requireBoardApprovalForNewAgents }).from(agents)
.innerJoin(companies, eq(companies.id, agents.companyId))
.where(and(eq(agents.id, input.agentId), eq(agents.companyId, input.companyId))) : [];
if (agent?.state === "paused" && agent.pauseReason === "setup" && agent.requiresApproval) return {
executionTarget: null, environmentName: environment.name, fallbackChecks: [{
code: "environment_agent_approval_required", level: "warn",
message: "The selected account will be verified on the agent computer after hire approval.",
}], release: noopRelease,
};
if (!agent || ["paused", "preparing"].includes(agent.state)) return {
executionTarget: null, environmentName: environment.name, fallbackChecks: [{
code: !input.agentId ? "environment_agent_required" : "environment_agent_preparing", level: "warn",
message: !input.agentId ? "This environment needs a saved agent before its connection can be tested."
: "The agent computer is being prepared. Test the connection when preparation finishes.",
}], release: noopRelease,
};
}
const testEnvironment = environment.driver === "sandbox"
? {
...environment,
+5 -1
View File
@@ -12,7 +12,7 @@ import { secretService, assertClaudeOAuthBindingInvariant } from "./secrets.js";
import { agentCredentialService } from "./agent-credentials.js";
import { agentIdentityService } from "./agent-identity.js";
import { initializePrimaryAgent } from "./primary-agent.js";
import { resolveNewAgentRunnerForCompany } from "./agent-runner-selection.js";
import { resolveAgentRunnerTaskDriverForCompany, resolveNewAgentRunnerForCompany } from "./agent-runner-selection.js";
export async function prepareAgentHire(db: Db, companyId: string, input: CreateAgentData, options?: CreateAgentOptions): Promise<CreateAgentData> {
const { runner, ...data } = input;
@@ -44,6 +44,10 @@ export async function prepareAgentHire(db: Db, companyId: string, input: CreateA
? await secretService(db).normalizeAdapterConfigForPersistence(companyId, data.adapterConfig, { adapterType })
: {};
const adapterConfig = normalizePaperclipRunnerAdapterConfig(adapterType, rawAdapterConfig);
if (adapterType === "paperclip_runner" && !["openai_dot", "grok_bot", "muse"].includes(String(adapterConfig.provider)) &&
(await resolveAgentRunnerTaskDriverForCompany(db, companyId, data.defaultEnvironmentId))?.warmTaskVersion === 1) {
adapterConfig.lifecycleMode = "warm";
}
await agentCredentialService(db).enforceClaudeOAuthBindingClaim(db, {
companyId, consume: true, environmentId: data.defaultEnvironmentId ?? null,
childAdapterConfig: adapterConfig, claudeLogin: options?.claudeLogin,
+15 -1
View File
@@ -1,5 +1,6 @@
import { logger } from "../middleware/logger.js";
import type { Db } from "@paperclipai/db";
import { companies, type Db } from "@paperclipai/db";
import { eq } from "drizzle-orm";
import * as lifecycle from "../modules/agent-lifecycle/index.js";
import { withAccountingTransaction } from "./accounting-transaction.js";
import { budgetServiceInTransaction, policyBlocks, type BudgetServiceHooks } from "./budgets.js";
@@ -12,12 +13,25 @@ import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notificatio
import { fenceActiveCompanyAgentStopsInTransaction as fenceActiveCompanyStops } from "../modules/agent-lifecycle/index.js";
import { applyAgentPolicyHoldsInTransaction } from "../modules/agent-lifecycle/index.js";
import { trackIdleWork } from "./task-admission.js";
import { environmentService } from "./environments.js";
import { instanceSettingsService } from "./instance-settings.js";
import { pluginEnvironmentRequiresAgent } from "./plugin-environment-driver.js";
export { scheduleAgentLifecycle, processAgentLifecycle } from "../modules/agent-lifecycle/index.js";
export type { LifecycleDriver, LifecycleAgent } from "../modules/agent-lifecycle/index.js";
export function createAgentLifecycleEffects(_hooks: BudgetServiceHooks = {}): lifecycle.LifecycleEffects {
return {
async setupRequiresPreparation(db, companyId, environmentId) {
const id = environmentId ?? (await instanceSettingsService(db).get()).defaultEnvironmentId;
const environment = id ? await environmentService(db).getById(id) : null;
if (!environment || !await pluginEnvironmentRequiresAgent(db, environment)) return false;
const [company] = await db.select({ requiresApproval: companies.requireBoardApprovalForNewAgents }).from(companies).where(eq(companies.id, companyId));
if (!company || company.requiresApproval) return false;
const bound = await environmentService(db).listBoundCompanyIds(environment.id);
if (bound.length && !bound.includes(companyId)) throw new lifecycle.AgentLifecycleConflict("The environment belongs to another company");
return true;
},
notifyWork: tx => notifyDeliveryWork(tx, DELIVERY_QUEUES.agentLifecycle),
reportFailure(context, error) {
const code = lifecycle.lifecycleFailureCode(error);
@@ -2,7 +2,7 @@ import type { Db } from "@paperclipai/db";
import type { Agent, EnvironmentProbeResult } from "@paperclipai/shared";
import { conflict, unprocessable } from "../errors.js";
import { resolveAgentRunnerEnvironmentForCompany } from "./agent-runner-selection.js";
import { probeEnvironment } from "./environment-probe.js";
import { probeEnvironment, readSandboxPlatformQualification } from "./environment-probe.js";
import type { PluginWorkerManager } from "./plugin-worker-manager.js";
export async function qualifyAgentRunner(
@@ -11,16 +11,24 @@ export async function qualifyAgentRunner(
expectedEnvironmentId: string,
pluginWorkerManager?: PluginWorkerManager,
): Promise<EnvironmentProbeResult> {
if (!["claude_local", "codex_local"].includes(agent.adapterType)) {
throw unprocessable("This agent does not need a runner upgrade.");
if (!["claude_local", "codex_local", "paperclip_runner"].includes(agent.adapterType)) {
throw unprocessable("This agent does not support computer qualification.");
}
const { environment } = await resolveAgentRunnerEnvironmentForCompany(db, agent.companyId, agent.defaultEnvironmentId);
if (!environment || environment.id !== expectedEnvironmentId) {
throw conflict("The agent's computer changed. Save any environment changes, reload, and retry the upgrade.");
throw conflict(agent.adapterType === "paperclip_runner"
? "The agent's computer changed. Save the computer selection, reload, and run its test again."
: "The agent's computer changed. Save any environment changes, reload, and retry the upgrade.");
}
if (environment.driver !== "sandbox") {
throw unprocessable("This computer does not need sandbox qualification.");
}
// A normal native-agent Test still probes its runtime. Reuse a valid saved
// platform proof so that test does not invalidate a healthy computer first.
if (agent.adapterType === "paperclip_runner" && await readSandboxPlatformQualification(db, environment, agent.companyId)) {
return { ok: true, driver: "sandbox", summary: "The agent's computer is qualified for runner selection.",
details: { platformQualificationRecorded: true } };
}
const result = await probeEnvironment(db, environment, {
companyId: agent.companyId,
pluginWorkerManager,
@@ -33,7 +41,8 @@ export async function qualifyAgentRunner(
ok: result.ok,
driver: "sandbox",
summary: qualified ? "The agent's computer is qualified for runner selection."
: "Could not qualify the agent's computer. Retry the upgrade or keep Legacy runner.",
: agent.adapterType === "paperclip_runner" ? "Could not verify the saved computer. Run test again."
: "Could not qualify the agent's computer. Retry the upgrade or keep Legacy runner.",
details: {
platformQualificationRecorded: qualified,
...(typeof result.details?.leaseId === "string" ? { leaseId: result.details.leaseId } : {}),
@@ -12,7 +12,7 @@ vi.mock("./environment-config.js", async () => ({
}));
vi.mock("./plugin-registry.js", () => ({ pluginRegistryService: () => ({ getByKey: state.pluginByKey }) }));
vi.mock("@paperclipai/adapter-utils/ssh", () => ({ runSshCommand: state.ssh }));
import { AGENT_RUNNER_SSH_PLATFORM_COMMAND, agentRunnerAvailability, resolveAgentRunnerTargetForCompany, resolveNewAgentRunner, resolveNewAgentRunnerForCompany } from "./agent-runner-selection.js";
import { AGENT_RUNNER_SSH_PLATFORM_COMMAND, agentRunnerAvailability, resolveAgentRunnerTaskDriverForCompany, resolveAgentRunnerTargetForCompany, resolveNewAgentRunner, resolveNewAgentRunnerForCompany } from "./agent-runner-selection.js";
import { buildCodexAcpConfig, resolveCodexExecutionEngine } from "@paperclipai/adapter-codex-local/server";
import { secretService } from "./secrets.js";
import * as localPlatform from "../lib/agent-runner-platform.js";
@@ -522,6 +522,24 @@ describe("Runner-only plugin environments", () => {
expect(agentRunnerAvailability("gemini_local", target)).toEqual({ supportedRunners: ["legacy"], defaultRunner: "legacy" });
expect(state.ssh).not.toHaveBeenCalled();
});
it("carries warm task capability from the selected driver without provider gates", async () => {
state.pluginByKey.mockResolvedValue(plugin({ supportsTasks: true, warmTaskVersion: 1 }));
expect(await resolveAgentRunnerTargetForCompany({} as never, "company", "computer"))
.toEqual({ driver: "plugin", runnerTasks: true, warmTaskVersion: 1 });
expect(await resolveAgentRunnerTaskDriverForCompany({} as never, "company", "computer"))
.toMatchObject({ driverKey: "tasks", supportsTasks: true, warmTaskVersion: 1 });
});
it.each(["ssh", "sandbox"])("does not qualify a %s runner while inspecting hire defaults", async driver => {
state.getEnvironment.mockResolvedValue({ ...pluginEnvironment, driver, config: { provider: "fake" } });
expect(await resolveAgentRunnerTaskDriverForCompany({} as never, "company", "computer")).toBeUndefined();
expect(state.ssh).not.toHaveBeenCalled();
expect(state.sandboxQualification).not.toHaveBeenCalled();
expect(state.pluginByKey).not.toHaveBeenCalled();
if (driver === "sandbox") await expect(resolveAgentRunnerTargetForCompany({} as never, "company", "computer"))
.rejects.toThrow("The fake sandbox provider cannot execute runs.");
});
it("saves a Claude agent on the plugin environment as Paperclip Runner", async () => {
const saved = await resolveNewAgentRunnerForCompany({} as never, "company", { adapterType: "claude_local", defaultEnvironmentId: "computer" });
expect(saved).toMatchObject({ adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "claude" } });
+22 -7
View File
@@ -15,6 +15,7 @@ export type RunnerTarget = {
driver: string; platform?: string; architecture?: string; libc?: "glibc" | "musl" | "unknown"; glibcVersion?: string;
/** A plugin environment whose driver declares Runner task execution. It runs agents only through Paperclip Runner. */
runnerTasks?: boolean;
warmTaskVersion?: 1;
};
export const AGENT_RUNNER_SSH_PLATFORM_COMMAND = "uname -s; uname -m; if paperclip_glibc_version=$(getconf GNU_LIBC_VERSION 2>/dev/null) && [ -n \"$paperclip_glibc_version\" ]; then printf 'glibc\\n%s\\n' \"$paperclip_glibc_version\"; else case \"$(ldd --version 2>&1)\" in *musl*) printf 'musl\\n' ;; *) printf 'unknown\\n' ;; esac; fi";
export interface AgentRunnerSelection {
@@ -293,7 +294,10 @@ export async function resolveAgentRunnerTargetForCompany(db: Db, companyId: stri
const { environment, driver } = await resolveAgentRunnerEnvironmentForCompany(db, companyId, defaultEnvironmentId);
let target: RunnerTarget = driver === "local" ? localAgentRunnerTarget()
: { driver };
if (driver === "plugin" && environment && await pluginEnvironmentRunsRunnerTasks(db, environment)) target = { driver, runnerTasks: true };
if (driver === "plugin" && environment) {
const taskDriver = await pluginEnvironmentRunnerTaskDriver(db, environment);
if (taskDriver) target = { driver, runnerTasks: true, ...(taskDriver.warmTaskVersion === 1 ? { warmTaskVersion: 1 as const } : {}) };
}
if (driver === "sandbox" && environment) {
const { readSandboxPlatformQualification } = await import("./environment-probe.js");
const qualified = await readSandboxPlatformQualification(db, environment, companyId);
@@ -312,6 +316,18 @@ export async function resolveAgentRunnerTargetForCompany(db: Db, companyId: stri
}
export async function resolveAgentRunnerEnvironmentForCompany(db: Db, companyId: string, defaultEnvironmentId?: string | null) {
const resolved = await resolveAgentEnvironmentForCompany(db, companyId, defaultEnvironmentId);
if (resolved.environment?.driver === "sandbox" && resolved.environment.config?.provider === "fake") throw unprocessable("The fake sandbox provider cannot execute runs.");
return resolved;
}
// Hiring defaults inspect capabilities without probing or qualifying an already selected runner.
export async function resolveAgentRunnerTaskDriverForCompany(db: Db, companyId: string, defaultEnvironmentId?: string | null) {
const { environment, driver } = await resolveAgentEnvironmentForCompany(db, companyId, defaultEnvironmentId);
return driver === "plugin" && environment ? pluginEnvironmentRunnerTaskDriver(db, environment) : undefined;
}
async function resolveAgentEnvironmentForCompany(db: Db, companyId: string, defaultEnvironmentId?: string | null) {
const { instanceSettingsService } = await import("./instance-settings.js");
const { environmentService } = await import("./environments.js");
const settings = await instanceSettingsService(db).get();
@@ -331,7 +347,6 @@ export async function resolveAgentRunnerEnvironmentForCompany(db: Db, companyId:
const boundCompanyIds = await envs.listBoundCompanyIds(environment.id);
if (boundCompanyIds.length > 0 && !boundCompanyIds.includes(companyId)) throw forbidden("The selected environment belongs to another company.", { code: "environment_company_mismatch" });
if (environment.status === "archived") throw unprocessable("Environment is archived.");
if (environment.driver === "sandbox" && environment.config?.provider === "fake") throw unprocessable("The fake sandbox provider cannot execute runs.");
}
return { environment, driver: environment?.driver ?? "local" };
}
@@ -339,17 +354,17 @@ export async function resolveAgentRunnerEnvironmentForCompany(db: Db, companyId:
// The plugin's manifest declaration decides whether its environment runs
// Runner tasks. Run admission separately verifies a ready plugin and a live
// worker, so a plugin that is down still selects the Runner and fails its run.
async function pluginEnvironmentRunsRunnerTasks(db: Db, environment: Parameters<typeof parseEnvironmentDriverConfig>[0]): Promise<boolean> {
async function pluginEnvironmentRunnerTaskDriver(db: Db, environment: Parameters<typeof parseEnvironmentDriverConfig>[0]) {
let config: { pluginKey: string; driverKey: string };
try {
const parsed = parseEnvironmentDriverConfig(environment);
if (parsed.driver !== "plugin") return false;
if (parsed.driver !== "plugin") return undefined;
config = parsed.config;
} catch {
return false;
return undefined;
}
const { pluginRegistryService } = await import("./plugin-registry.js");
const plugin = await pluginRegistryService(db).getByKey(config.pluginKey);
return Boolean(plugin?.manifestJson.capabilities.includes("environment.drivers.register")
&& plugin.manifestJson.environmentDrivers?.some(driver => driver.driverKey === config.driverKey && driver.supportsTasks === true));
return plugin?.manifestJson.capabilities.includes("environment.drivers.register")
? plugin.manifestJson.environmentDrivers?.find(driver => driver.driverKey === config.driverKey && driver.supportsTasks === true) : undefined;
}
+2 -1
View File
@@ -836,7 +836,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
const { publicationFiles } = createOutboundAttachments(db, { get storage() { return options.storage; } });
const { authorizeInboundWakeup, authorizeGitHubTaskRetryBatch, authorizeInboundWorkStart, authorizeFastResponse } = createInboundWakeAuthority(db, { runtimeCallbackEndpoint, lockCurrentPrincipalAuthorization });
const { ingestAttachments, attachmentOmissionDetail } = createInboundAttachments(db, { authorizeInboundWakeup, lifecycleRuntimeFence, sanitizeFilename, issuesSvc, isExternalActionAuthorizationChange, redactError, get storage() { return options.storage; } });
const { stageInboundWakeup, acceptInboundWakeup, settleRejectedInboundWakeups, processInboundWakeup } = createInboundWakeups(db, { authorizeInboundWakeup, authorizeInboundWorkStart, attachmentOmissionDetail, isExternalActionAuthorizationChange, redactError, fetchImpl, get heartbeat() { return options.heartbeat; } });
const { stageInboundWakeup, acceptInboundWakeup, settleRejectedInboundWakeups, processInboundWakeup, unregisterDeferredWakeOwner } = createInboundWakeups(db, { authorizeInboundWakeup, authorizeInboundWorkStart, attachmentOmissionDetail, isExternalActionAuthorizationChange, redactError, fetchImpl, get heartbeat() { return options.heartbeat; } });
const { settleTelegramAttachmentOnlyFailure } = createTelegramAttachmentFailure(db, {
attachmentOmissionDetail, runtimeContextForRecord, endpointRecord, stageProviderEffect, scheduleProviderEffect,
});
@@ -3529,6 +3529,7 @@ return {
shutdown: async () => {
shuttingDown = true;
await Promise.allSettled(pendingFailedRetries());
unregisterDeferredWakeOwner();
unregisterFailedRetryAuthority();
unregisterSlackTaskAuthority();
voice.unregisterAgentTools();
@@ -1,5 +1,8 @@
import { safeChatWakeAuthorityReason, type ChatWakeAuthorityReason } from "./inbound/wakeup-authorization-error.js";
import { adapterExecutionControls } from "../adapter-execution-control.js";
import { admitExplicitNativeContinuation } from "../explicit-native-continuation.js";
import { continuingTeamsFilePublication, type ContinuingTeamsFileTransfer } from "./microsoft-teams/file-transfer-source.js";
import { readTaskChatRetryIntent, taskChatRetryCanAwaitRecovery, taskChatRetryExecutionStopped } from "./task-retry-authority.js";
import { readTaskChatRetryIntent, taskChatRetryCanAwaitRecovery, taskChatRetryExecutionStopped, taskChatRetryAdmittedContinuationStopped } from "./task-retry-authority.js";
import { notifyChatActionWork, notifyChatPublicationWork } from "../chat-work-notifications.js";
import { FAILED_RUN_RETRY_STALE_MS, dueChatAction } from "../chat-action-work.js";
import { readChatAuthorizationRun } from "./authorization-run-read.js";
@@ -125,10 +128,13 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti
} = options;
const failedChatRetryDenied = () =>
const failedChatRetryDenied = (reason?: "accepted_result_without_new_input" |
"prior_result_publication" | "prior_interaction" | "source_authorization", authorityReason?: ChatWakeAuthorityReason) =>
conflict(
"The exact failed chat request can no longer be retried safely. Check its current connection, access, and recovery state.",
{ code: "chat_failed_run_retry_not_authorized" },
reason === "accepted_result_without_new_input"
? "This attempt already recorded a result. Send a new message on the task to continue from the saved work."
: "The exact failed chat request can no longer be retried safely. Check its current connection, access, and recovery state.",
{ code: "chat_failed_run_retry_not_authorized", ...(reason ? { reason } : {}), ...(reason === "source_authorization" && authorityReason ? { authorityReason } : {}) },
);
class FailedChatRetryPublicationReadError extends Error {
constructor() {
@@ -197,24 +203,48 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti
}
}
/** The reviewed-chat ownership check runs before runtime/profile resolution
* or provider startup. Recognize only that exact persisted failure together
* with its sole system diagnostic and absence of execution evidence. A
* generic setup error (or a prior-session display hint) is not this proof. */
async function isPreProviderReviewedChatFailure(
/** Certify known preparation boundaries from their server-owned failure
* contract and absence of execution evidence. Other workspace validations
* may run after acquisition and must not inherit this exception. A saved
* session display hint never establishes containment or resume authority. */
async function isPreProviderChatFailure(
tx: DbOrTransaction,
run: typeof heartbeatRuns.$inferSelect,
allowWorkspacePreparation = false,
): Promise<boolean> {
const diagnostic = "reviewed_chat_execution_binding_not_authorized";
const retryDiagnostic = "The exact failed chat request can no longer be retried safely. Check its current connection, access, and recovery state.";
const failedRetry = run.errorCode === "chat_failed_run_retry_not_authorized" && run.error === retryDiagnostic;
const validation = run.resultJson?.workspaceValidation as Record<string, unknown> | undefined;
const recovery = run.resultJson?.executionRecovery as Record<string, unknown> | undefined;
const workspacePreparation = allowWorkspacePreparation && run.errorCode === "workspace_validation_failed" &&
validation?.reason === "isolated_task_directory_binding_mismatch" &&
typeof validation.issueId === "string" && validation.issueId === run.contextSnapshot?.issueId &&
(run.issueId === null || run.issueId === validation.issueId) &&
(run.contextSnapshot?.taskId === undefined || run.contextSnapshot.taskId === validation.issueId) &&
Object.keys(validation).every(key => ["reason", "issueId"].includes(key)) &&
recovery?.kind === "bootstrap" && recovery.providerWorkStarted === false &&
Object.keys(recovery).every(key => ["kind", "providerWorkStarted"].includes(key)) &&
run.resultJson?.stopReason === "adapter_failed" &&
Object.keys(run.resultJson).every(key => ["executionRecovery", "workspaceValidation", "stopReason",
"effectiveTimeoutSec", "timeoutConfigured", "timeoutFired", "timeoutSource"].includes(key));
const diagnostic = failedRetry ? retryDiagnostic : workspacePreparation ? run.error : "reviewed_chat_execution_binding_not_authorized";
const dispatchOnlyProfile = failedRetry || workspacePreparation;
if (
adapterExecutionControls.has(run.id) ||
(run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date()) ||
run.runtimeMode !== "legacy" ||
run.errorCode !== "setup_failed" ||
run.error !== diagnostic ||
(!failedRetry && !workspacePreparation && run.errorCode !== "setup_failed") ||
run.status !== "failed" || !run.finishedAt ||
(failedRetry && run.sessionIdBefore !== null) ||
(dispatchOnlyProfile && JSON.stringify(run.runnerProfileJson) !== JSON.stringify({ adapterDispatch: { adapterType: "paperclip_runner" } })) ||
!diagnostic || run.error !== diagnostic ||
(workspacePreparation && run.usageJson !== null &&
Object.keys(run.usageJson).some(key => key !== "ledgerScope")) ||
[
run.runtimeModeResolverVersion,
run.runtimeModeReason,
run.runtimeModeResolvedAt,
run.runnerProfileJson,
...(dispatchOnlyProfile ? [] : [run.runnerProfileJson]),
run.runnerInstanceId,
run.nativeSessionId,
run.nativeIssueId,
@@ -237,7 +267,7 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti
run.lastOutputAt,
run.lastOutputStream,
run.lastOutputBytes,
run.usageJson,
...(workspacePreparation ? [] : [run.usageJson]),
run.exitCode,
run.signal,
].some((value) => value !== null) ||
@@ -254,14 +284,52 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti
eq(heartbeatRunEvents.runId, run.id),
),
)
.limit(2)
.orderBy(asc(heartbeatRunEvents.seq))
.limit(workspacePreparation ? 4 : 3)
.for("share", { noWait: true });
const event = events[0];
let preparationOffset = 0;
const warning = events[0];
if (workspacePreparation && warning?.eventType === "agent_observability.unavailable") {
// This known warning is written by configuration preparation, before
// workspace allocation. It is not evidence that a provider executed.
if (warning.seq !== 1 || warning.agentId !== run.agentId || warning.stream !== "system" || warning.level !== "warn" ||
warning.message !== "Company observability was not applied: this harness is not supported." ||
warning.payload?.reason !== "unsupported_harness" || (typeof warning.payload.revision !== "string" || !isUuidLike(warning.payload.revision)) ||
Object.keys(warning.payload).some(key => !["reason", "revision"].includes(key)) ||
warning.sourceInstanceId !== null || warning.sourceEventId !== null || warning.sourceSeq !== null ||
warning.sourcePayloadSha256 !== null || warning.protocolSchemaVersion !== null) return false;
preparationOffset = 1;
}
const event = events[preparationOffset];
const measured = events[preparationOffset + 1];
if (failedRetry) {
const explicit = run.contextSnapshot?.explicitUserContinuation as Record<string, unknown> | undefined;
const hint = run.contextSnapshot?.chatFailedRunRetry as Record<string, unknown> | undefined;
const intentId = run.contextSnapshot?.taskRetryRequestId;
if (typeof intentId !== "string" || !run.retryOfRunId || !run.wakeupRequestId ||
hint?.version !== 1 || hint.actionId !== run.wakeupRequestId || hint.failedRunId !== run.retryOfRunId ||
explicit?.previousRunId !== run.retryOfRunId || explicit.taskRetryRequestId !== intentId ||
explicit.commentId !== run.contextSnapshot?.wakeCommentId) return false;
const prior = await readTaskChatRetryIntent(tx as unknown as Db, { companyId: run.companyId,
issueId: String(run.contextSnapshot?.issueId), agentId: run.agentId,
sourceRunId: run.retryOfRunId, intentId, chatActionId: run.wakeupRequestId });
if (!prior || prior.wake.status !== "coalesced" || prior.wake.runId !== run.id) return false;
}
if (failedRetry || workspacePreparation) {
if (!measured || measured.seq !== 2 + preparationOffset || measured.agentId !== run.agentId ||
measured.eventType !== "lifecycle" || measured.stream !== "system" ||
measured.message !== "task.run.measured" || measured.sourceInstanceId !== null ||
measured.sourceEventId !== null || measured.sourceSeq !== null || measured.sourcePayloadSha256 !== null ||
measured.protocolSchemaVersion !== null || typeof measured.payload?.durationMs !== "number" ||
!Number.isFinite(measured.payload.durationMs) || measured.payload.durationMs < 0 ||
measured.payload?.durableSettlement !== true || measured.payload?.outcome !== "failed" ||
measured.payload?.phase !== "task.run.measured") return false;
}
if (
events.length !== 1 ||
events.length !== (failedRetry || workspacePreparation ? 2 + preparationOffset : 1) ||
!event ||
event.agentId !== run.agentId ||
event.seq !== 1 ||
event.seq !== 1 + preparationOffset ||
event.eventType !== "error" ||
event.stream !== "system" ||
event.level !== "error" ||
@@ -553,10 +621,11 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti
async function assertFailedNativeRetryState(
tx: DbOrTransaction,
source: Pick<FailedChatRetrySource, "failedRunId" | "issueId" | "agentId">,
source: Pick<FailedChatRetrySource, "failedRunId" | "issueId" | "agentId" | "commentIds" | "taskRetryInput" | "requestedByActorType" | "requestedByActorId">,
companyId: string,
taskRetryIntentId?: string,
allowPendingRecovery = false,
executionRunId?: string,
) {
const [run] = await tx
.select()
@@ -573,7 +642,25 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti
if (taskRetryIntentId) {
if (!await readTaskChatRetryIntent(tx as unknown as Db, { companyId, issueId: source.issueId,
agentId: source.agentId, sourceRunId: run.id, intentId: taskRetryIntentId })) throw failedChatRetryDenied();
if (await taskChatRetryExecutionStopped(tx as unknown as Db, run)) return;
const previousComments = new Set(source.taskRetryInput?.sourceActionIds.length
? retryCommentIds(run.contextSnapshot ?? {}, source.taskRetryInput) : []);
const newInput = source.taskRetryInput?.sourceActionIds.length && source.requestedByActorType === "user" &&
source.commentIds.length && source.commentIds.every(id => !previousComments.has(id));
if (newInput) {
// Persisting independent input may wait behind an unknown executor.
// Promotion still requires the ordinary new-user-turn stop proof.
if (allowPendingRecovery) return;
if (executionRunId && await taskChatRetryAdmittedContinuationStopped(tx as unknown as Db, run, {
issueId: source.issueId, intentId: taskRetryIntentId, successorRunId: executionRunId,
commentId: source.commentIds.at(-1)!,
})) return;
if (await admitExplicitNativeContinuation({ db: tx as Db, companyId, issueId: source.issueId,
agentId: source.agentId, actorType: "user", actorId: source.requestedByActorId,
reason: "issue_commented", commentId: source.commentIds.at(-1)!, successorRunId: taskRetryIntentId,
dryRun: true })) return;
}
if (await taskChatRetryExecutionStopped(tx as unknown as Db, run) ||
await isPreProviderChatFailure(tx, run, true)) return;
if (allowPendingRecovery && await taskChatRetryCanAwaitRecovery(
tx as unknown as Db, run, source.issueId, taskRetryIntentId,
)) return;
@@ -719,7 +806,7 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti
"process_exit",
"timeout",
].includes(failedRun.errorCode ?? "") ||
(evidence.kind === "retry" && await isPreProviderReviewedChatFailure(tx, evidence.run))
(evidence.kind === "retry" && await isPreProviderChatFailure(tx, evidence.run))
)) ||
(!input.publication &&
["backlog", "done", "cancelled"].includes(issue.status))
@@ -732,6 +819,22 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti
if (failedRun.runtimeMode === "native" && evidence.kind === "retry" && !input.taskRetryIntentId)
await failedNativeRetryCoordinator(tx, evidence.run, issue.id);
const context = failedRun.contextSnapshot ?? {};
const selection = input.taskRetryInput && taskRetryInputSchema.safeParse(input.taskRetryInput);
if (selection && !selection.success) throw failedChatRetryDenied();
const selectedInput = selection?.success ? selection.data : undefined;
if (input.taskRetryIntentId && !input.committedResponse && failedRun.status === "failed" &&
failedRun.runtimeMode === "native" && failedRun.nativeIssueId === issue.id &&
context.issueId === issue.id && context.source === "issue.tree_resume" &&
!selectedInput?.sourceActionIds.length) {
// An inherited requester is not permission to replay a recorded result.
// Explain the existing refusal before raw chat-source validation hides
// the supported new-message path. This branch grants no continuation.
const [recorded] = await tx.select({ id: nativeRunResults.id }).from(nativeRunResults).where(and(
eq(nativeRunResults.companyId, input.companyId), eq(nativeRunResults.issueId, issue.id),
eq(nativeRunResults.runId, failedRun.id), eq(nativeRunResults.schemaStatus, "accepted"),
)).limit(1).for("share", { noWait: true });
if (recorded) throw failedChatRetryDenied("accepted_result_without_new_input");
}
const provider = CHAT_PROVIDERS.find(
(value) => context.source === `chat:${value}`,
);
@@ -742,13 +845,11 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti
(context.taskKey !== issue.identifier && context.taskKey !== issue.id)
)
throw failedChatRetryDenied();
const selection = input.taskRetryInput && taskRetryInputSchema.safeParse(input.taskRetryInput);
if (selection && !selection.success) throw failedChatRetryDenied();
const selectedInput = selection?.success ? selection.data : undefined;
if (selectedInput && (!input.taskRetryIntentId || provider !== "github")) throw failedChatRetryDenied();
const reauthorization = input.taskRetryReauthorization ?? (selectedInput ? {
intentId: input.taskRetryIntentId!, sourceRunId: failedRun.id, runtimeFence: selectedInput.runtimeFence,
} : undefined);
if (reauthorization && selectedInput?.skippedActionIds) reauthorization.skippedActionIds = selectedInput.skippedActionIds;
const pendingSources = selectedInput?.sourceActionIds.length ? await tx.select().from(chatActions).where(and(
eq(chatActions.companyId, input.companyId), eq(chatActions.kind, "inbound_wakeup"),
sql`${chatActions.payload}->>'issueId' = ${issue.id}`,
@@ -859,6 +960,11 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti
),
)
.limit(1);
const previousComments = new Set(pendingSources?.length ? retryCommentIds(context, selectedInput) : []);
const independentFailedInput = input.taskRetryIntentId && pendingSources?.length &&
pendingSources.every(action => action.payload.requestedByActorType === "user") &&
commentIds.every(id => !previousComments.has(id)) && failedRun.status === "failed" &&
(accepted?.resultJson.terminal as Record<string, unknown> | undefined)?.runTerminalState === "failed";
const [resultPublication] = await tx
.select({ id: chatPublications.id })
.from(chatPublications)
@@ -869,6 +975,10 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti
input.committedResponse
? eq(chatPublications.state, "delivery_unknown")
: undefined,
// A distinct admitted user request does not replay the failed
// result's output. Preserve that terminal publication as history;
// pending or uncertain delivery still owns its external effects.
independentFailedInput ? ne(chatPublications.state, "failed") : undefined,
continuingUnknownPublicationId
? ne(chatPublications.id, continuingUnknownPublicationId)
: undefined,
@@ -884,13 +994,10 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti
),
)
.limit(1);
if (
(!input.committedResponse && accepted) ||
resultPublication ||
question ||
answerDelivery
)
throw failedChatRetryDenied();
if (!input.committedResponse && accepted && !independentFailedInput)
throw failedChatRetryDenied(input.taskRetryIntentId ? "accepted_result_without_new_input" : undefined);
if (resultPublication) throw failedChatRetryDenied(input.taskRetryIntentId ? "prior_result_publication" : undefined);
if (question || answerDelivery) throw failedChatRetryDenied(input.taskRetryIntentId ? "prior_interaction" : undefined);
if (context.chatFailedRunRetry && !pendingSources) {
const hint = context.chatFailedRunRetry as Record<string, unknown>;
const [priorIntent] = await tx
@@ -1069,7 +1176,7 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti
const invalidated = new Set(lifecycleRows.map(row => lifecycleKey(row.target, row.context)));
const batch = reauthorization ? await authorizeGitHubTaskRetryBatch(tx, ordered, {
nonblocking: true, terminal: input.publication === true, taskRetry: reauthorization,
}).catch(error => { if (isExternalActionAuthorizationChange(error)) throw failedChatRetryDenied(); throw error; }) : null;
}).catch(error => { if (isExternalActionAuthorizationChange(error)) throw failedChatRetryDenied(input.taskRetryIntentId ? "source_authorization" : undefined, safeChatWakeAuthorityReason(error)); throw error; }) : null;
const canonicalSources: Array<Record<string, unknown>> = [];
let destination: Awaited<ReturnType<typeof authorizeInboundWakeup>> | null =
null;
@@ -1080,16 +1187,21 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti
...(reauthorization ? { taskRetry: reauthorization } : {}),
}).catch((error) => {
if (isExternalActionAuthorizationChange(error))
throw failedChatRetryDenied();
throw failedChatRetryDenied(input.taskRetryIntentId ? "source_authorization" : undefined, safeChatWakeAuthorityReason(error));
throw error;
});
if (reauthorization && !reauthorization.runtimeFence) reauthorization.runtimeFence = destination.retryRuntimeFence;
const delivery = deliveriesById.get(action.deliveryId!);
const current = actionsById.get(action.id);
const comment = commentsById.get(String(action.payload.commentId));
const receipt = receiptsById.get(action.id);
const skippedInput = pendingSources && selectedInput?.skippedActionIds?.includes(action.id) &&
receipt?.status === "skipped" && !receipt.runId &&
["budget.blocked", "agent.not_invokable"].includes(receipt.reason ?? "") &&
action.payload.requestedByActorType === "user";
if (
!current ||
current.status !== "processed" ||
(current.status !== "processed" && !(skippedInput && current.status === "failed")) ||
inboundWakeScope(current) !== inboundWakeScope(action) ||
!delivery ||
delivery.state !== "processed" ||
@@ -1106,7 +1218,6 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti
)
throw failedChatRetryDenied();
if (invalidated.has(lifecycleKey(delivery.providerEventId, lifecycleRuntimeFence(delivery)))) throw failedChatRetryDenied();
const receipt = receiptsById.get(action.id);
if (!receipt) throw failedChatRetryDenied();
assertFailedRetryReceipt(
createDurableChatWakeupRequest({
@@ -1125,7 +1236,7 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti
receipt,
);
if (pendingSources) {
const direct = receipt.status === "deferred_issue_execution" && !receipt.runId
const direct = (receipt.status === "deferred_issue_execution" || skippedInput) && !receipt.runId
&& receipt.payload?.coalescedIntoWakeupRequestId === undefined;
const owned = input.retryActionId && receipt.status === "coalesced"
&& receipt.payload?.coalescedIntoWakeupRequestId === input.retryActionId;
@@ -1164,7 +1275,7 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti
owner.agentId !== input.agentId ||
owner.requestedByActorType !== receipt.requestedByActorType ||
owner.requestedByActorId !== receipt.requestedByActorId)) ||
["skipped", "cancelled"].includes(receipt.status)
(!skippedInput && ["skipped", "cancelled"].includes(receipt.status))
)
throw failedChatRetryDenied();
canonicalSources.push({
@@ -1457,7 +1568,7 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti
});
await assertFailedNativeRetryState(tx, source, input.companyId,
typeof source.intent.payload.taskRetryIntentId === "string" ? source.intent.payload.taskRetryIntentId : undefined,
input.phase === "admission");
input.phase === "admission", input.phase === "execution" ? input.runId : undefined);
const context = input.contextSnapshot;
const hint = context.chatFailedRunRetry as
| Record<string, unknown>
@@ -1,6 +1,8 @@
import { createHash } from "node:crypto";
import { and, eq, or } from "drizzle-orm";
import { chatActions, chatGitHubReviews, type Db } from "@paperclipai/db";
import { HttpError } from "../../../errors.js";
import { chatRunSourceMessageId } from "../run-origin.js";
import { and, desc, eq, or, sql } from "drizzle-orm";
import { chatActions, chatConversations, chatEndpointResources, chatEndpoints, chatGitHubReviews, chatMessageLinks, heartbeatRuns, toolConnections, type Db } from "@paperclipai/db";
export async function hasPublishedGitHubReview(db: Db, binding: {
companyId: string;
@@ -27,3 +29,69 @@ export async function hasPublishedGitHubReview(db: Db, binding: {
)).limit(1);
return !!publication;
}
type WaitRun = Pick<typeof heartbeatRuns.$inferSelect,
"id" | "companyId" | "agentId" | "responsibleUserId" | "activeIdentityContextId" | "nativeIssueId" | "issueId" | "contextSnapshot">;
/** Passive review waits inherit the same accepted requester lineage as GitHub
* tools. This is not a grant to publish, run a monitor, or reuse attachments. */
export async function readInheritedGitHubReviewWait(db: Db, run: WaitRun) {
if (!run.activeIdentityContextId || !run.nativeIssueId) return null;
let commentId: string | null;
try {
commentId = await chatRunSourceMessageId(db, run, { provider: "github" });
} catch (error) {
if (error instanceof HttpError && error.status === 403) return { kind: "revoked" as const };
throw error;
}
if (!commentId) return null;
const [review] = await db.select({
id: chatGitHubReviews.id, endpointId: chatGitHubReviews.endpointId,
state: chatGitHubReviews.state, repository: chatGitHubReviews.repository,
repositoryId: chatGitHubReviews.repositoryId, headSha: chatGitHubReviews.headSha,
assessment: chatGitHubReviews.assessment, reviewRunId: chatGitHubReviews.runId,
connectionEnabled: toolConnections.enabled, connectionStatus: toolConnections.status,
reviewAgentId: heartbeatRuns.agentId, reviewCompanyId: heartbeatRuns.companyId,
resourceRepository: chatEndpointResources.providerResourceId,
resourceRepositoryId: sql<string | null>`${chatEndpointResources.metadata}->>'providerRepositoryId'`,
pullNumber: chatGitHubReviews.pullNumber, thread: chatConversations.externalThreadId,
}).from(chatMessageLinks)
.innerJoin(chatConversations, and(eq(chatConversations.id, chatMessageLinks.conversationId),
eq(chatConversations.companyId, run.companyId), eq(chatConversations.issueId, run.nativeIssueId)))
.innerJoin(chatEndpoints, and(eq(chatEndpoints.id, chatConversations.endpointId),
eq(chatEndpoints.companyId, run.companyId), eq(chatEndpoints.provider, "github"),
eq(chatEndpoints.assignedAgentId, run.agentId)))
.leftJoin(toolConnections, and(eq(toolConnections.id, chatEndpoints.connectionId),
eq(toolConnections.companyId, run.companyId)))
.innerJoin(chatEndpointResources, and(eq(chatEndpointResources.id, chatConversations.resourceId),
eq(chatEndpointResources.companyId, run.companyId), eq(chatEndpointResources.endpointId, chatEndpoints.id)))
.innerJoin(chatGitHubReviews, and(eq(chatGitHubReviews.endpointId, chatEndpoints.id),
eq(chatGitHubReviews.companyId, run.companyId), eq(chatGitHubReviews.issueId, run.nativeIssueId)))
.leftJoin(heartbeatRuns, eq(heartbeatRuns.id, chatGitHubReviews.runId))
.where(and(eq(chatMessageLinks.companyId, run.companyId), eq(chatMessageLinks.commentId, commentId),
eq(chatMessageLinks.direction, "inbound")))
.orderBy(desc(chatGitHubReviews.createdAt), desc(chatGitHubReviews.id)).limit(1);
// A newer unreviewed head cannot inherit the prior head's publication.
if (!review) return null;
if (!review.connectionEnabled || review.connectionStatus !== "active" || review.state !== "completed" ||
review.reviewCompanyId !== run.companyId || review.reviewAgentId !== run.agentId ||
review.assessment?.reviewedCommit !== review.headSha ||
review.resourceRepository.toLowerCase() !== review.repository.toLowerCase() ||
review.resourceRepositoryId !== review.repositoryId ||
review.thread.toLowerCase() !== `github:${review.repository}:${review.pullNumber}`.toLowerCase()) return { kind: "revoked" as const };
const [publication] = await db.select({ id: chatActions.id }).from(chatActions).where(and(
eq(chatActions.companyId, run.companyId), eq(chatActions.endpointId, review.endpointId),
eq(chatActions.kind, "github_review_publication"), eq(chatActions.status, "processed"),
eq(chatActions.providerActionId, `github_publication:${run.nativeIssueId}:assessment:${createHash("sha256").update(JSON.stringify(review.id)).digest("hex")}`),
)).limit(1);
if (!publication) return { kind: "revoked" as const };
// The caller must still verify live task ownership, destination and principal
// policy. This normalized source is used only by the passive-wait boundary.
return { kind: "published" as const, endpointId: review.endpointId, reviewId: review.id, reviewRunId: review.reviewRunId,
headSha: review.headSha, context: {
source: "chat:github", paperclipHarnessCheckedOut: true,
wakeCommentId: commentId, wakeCommentIds: [commentId],
paperclipWake: { checkedOutByHarness: true, externalChatProvider: "github",
issue: { id: run.nativeIssueId }, commentIds: [commentId] },
} };
}
@@ -1,6 +1,6 @@
import { and, eq, inArray } from "drizzle-orm";
import { chatActions, chatConversations, chatDeliveries, chatEndpointResources, chatMessageLinks, issueComments, toolConnections } from "@paperclipai/db";
import { forbidden } from "../../../errors.js";
import { and, eq, inArray, isNull, lt, sql } from "drizzle-orm";
import { agentWakeupRequests, chatActions, chatConversations, chatDeliveries, chatEndpointResources, chatMessageLinks, issueComments, toolConnections } from "@paperclipai/db";
import { chatWakeAuthorityDenied } from "../inbound/wakeup-authorization-error.js";
import type { DbOrTransaction, EndpointRow, LifecycleRuntimeFence } from "../runtime-types.js";
import { credentialFingerprint } from "../credential-fingerprint.js";
import { readTaskChatRetryIntent } from "../task-retry-authority.js";
@@ -9,8 +9,25 @@ export type TaskRetryWakeAuthority = {
intentId: string;
sourceRunId: string;
runtimeFence?: LifecycleRuntimeFence;
skippedActionIds?: string[];
};
async function skippedTaskRetryInputs(tx: DbOrTransaction, actions: Array<typeof chatActions.$inferSelect>,
authority: TaskRetryWakeAuthority) {
const first = actions[0];
const ids = actions.filter(action => action.status === "failed" && action.payload.requestedByActorType === "user" &&
authority.skippedActionIds?.includes(action.id)).map(action => action.id);
if (!first || !ids.length) return new Set<string>();
const rows = await tx.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and(
eq(agentWakeupRequests.companyId, first.companyId), inArray(agentWakeupRequests.id, ids),
eq(agentWakeupRequests.agentId, String(first.payload.agentId)), eq(agentWakeupRequests.status, "skipped"),
isNull(agentWakeupRequests.runId), inArray(agentWakeupRequests.reason, ["budget.blocked", "agent.not_invokable"]),
eq(agentWakeupRequests.requestedByActorType, "user"),
eq(agentWakeupRequests.requestedByActorId, String(first.payload.requestedByActorId)),
));
return new Set(rows.map(row => row.id));
}
export function githubTaskRetryAppMatches(endpoint: EndpointRow, delivery: typeof chatDeliveries.$inferSelect,
response: { payload: Record<string, unknown> } | undefined) {
const original = delivery.normalizedEvent.githubAuthority as { botExternalId?: unknown } | undefined;
@@ -18,6 +35,37 @@ export function githubTaskRetryAppMatches(endpoint: EndpointRow, delivery: typeo
: response?.payload.botExternalId === endpoint.botExternalId && response.payload.agentId === endpoint.assignedAgentId;
}
/** Legacy intake did not persist an App ID when admission stopped before
* acknowledgement. An earlier request ledger proves this endpoint had already
* claimed the App: response payloads are server-owned and a non-null endpoint
* claim cannot be replaced by setup, reconnect, or lifecycle repair. This is
* identity evidence only; the earlier response is never replayed. */
async function githubTaskRetryAppAuthorized(tx: DbOrTransaction, endpoint: EndpointRow,
delivery: typeof chatDeliveries.$inferSelect, response: { payload: Record<string, unknown> } | undefined) {
if (githubTaskRetryAppMatches(endpoint, delivery, response)) return true;
const original = delivery.normalizedEvent.githubAuthority as { botExternalId?: unknown } | undefined;
// Never substitute historical evidence for an explicit conflicting binding.
if (original?.botExternalId !== undefined || response || !endpoint.botExternalId || !delivery.conversationId) return false;
const [prior] = await tx.select({ id: chatActions.id }).from(chatActions)
.innerJoin(chatDeliveries, and(eq(chatDeliveries.id, chatActions.deliveryId),
eq(chatDeliveries.companyId, chatActions.companyId), eq(chatDeliveries.endpointId, chatActions.endpointId),
eq(chatDeliveries.conversationId, chatActions.conversationId), eq(chatDeliveries.principalId, chatActions.principalId)))
.innerJoin(chatMessageLinks, and(eq(chatMessageLinks.deliveryId, chatDeliveries.id),
eq(chatMessageLinks.companyId, chatDeliveries.companyId), eq(chatMessageLinks.endpointId, chatDeliveries.endpointId),
eq(chatMessageLinks.conversationId, chatDeliveries.conversationId), eq(chatMessageLinks.direction, "inbound")))
.where(and(eq(chatActions.companyId, endpoint.companyId), eq(chatActions.endpointId, endpoint.id),
eq(chatActions.conversationId, delivery.conversationId), eq(chatActions.kind, "github_response_comment"),
eq(chatActions.status, "processed"), eq(chatDeliveries.state, "processed"),
eq(chatActions.providerActionId, sql<string>`'github_response:' || ${chatDeliveries.id}::text`),
sql`jsonb_typeof(${chatActions.payload}->'botExternalId') = 'string'`,
sql`${chatActions.payload}->>'botExternalId' = ${endpoint.botExternalId}`,
sql`jsonb_typeof(${chatActions.payload}->'agentId') = 'string'`,
sql`${chatActions.payload}->>'agentId' = ${endpoint.assignedAgentId}`,
lt(chatActions.createdAt, delivery.createdAt), lt(chatDeliveries.createdAt, delivery.createdAt)))
.limit(1);
return Boolean(prior);
}
export function githubTaskRetryDestinationMatches(delivery: typeof chatDeliveries.$inferSelect,
conversation: typeof chatConversations.$inferSelect, resource: typeof chatEndpointResources.$inferSelect | null) {
const originalResource = delivery.normalizedEvent.resource as { providerResourceId?: unknown } | undefined;
@@ -33,27 +81,28 @@ export function githubTaskRetryDestinationMatches(delivery: typeof chatDeliverie
export async function githubTaskRetryRuntimeFence(tx: DbOrTransaction, endpoint: EndpointRow,
action: typeof chatActions.$inferSelect, delivery: typeof chatDeliveries.$inferSelect,
authority: TaskRetryWakeAuthority): Promise<LifecycleRuntimeFence> {
const deny = () => forbidden("This accepted chat message is no longer authorized to start work",
{ code: "chat_action_authorization_changed" });
const deny = chatWakeAuthorityDenied;
const retry = await readTaskChatRetryIntent(tx as Parameters<typeof readTaskChatRetryIntent>[0], {
companyId: action.companyId, issueId: String(action.payload.issueId),
agentId: String(action.payload.agentId), sourceRunId: authority.sourceRunId, intentId: authority.intentId,
});
if (!retry || endpoint.provider !== "github" || !endpoint.botExternalId || action.kind !== "inbound_wakeup"
|| action.status !== "processed" || delivery.state !== "processed") throw deny();
const skipped = await skippedTaskRetryInputs(tx, [action], authority);
if (!retry) throw deny("retry_intent");
if (endpoint.provider !== "github" || !endpoint.botExternalId || action.kind !== "inbound_wakeup"
|| (action.status !== "processed" && !skipped.has(action.id)) || delivery.state !== "processed") throw deny("source_receipt");
const [response] = await tx.select({ payload: chatActions.payload }).from(chatActions).where(and(
eq(chatActions.companyId, action.companyId), eq(chatActions.endpointId, endpoint.id),
eq(chatActions.conversationId, action.conversationId!), eq(chatActions.deliveryId, delivery.id),
eq(chatActions.kind, "github_response_comment"),
));
if (!githubTaskRetryAppMatches(endpoint, delivery, response)) throw deny();
if (!(await githubTaskRetryAppAuthorized(tx, endpoint, delivery, response))) throw deny("app_binding");
const [connection] = await tx.select({ refs: toolConnections.credentialSecretRefs,
enabled: toolConnections.enabled, status: toolConnections.status }).from(toolConnections).where(and(
eq(toolConnections.companyId, endpoint.companyId), eq(toolConnections.id, endpoint.connectionId),
));
if (!connection?.enabled || connection.status !== "active") throw deny();
if (!connection?.enabled || connection.status !== "active") throw deny("connection_access");
const generation = Number((endpoint.setup as { runtimeGeneration?: unknown }).runtimeGeneration ?? 0);
if (!Number.isSafeInteger(generation) || generation < 0) throw deny();
if (!Number.isSafeInteger(generation) || generation < 0) throw deny("runtime_generation");
return authority.runtimeFence ?? { generation, credentialFingerprint: credentialFingerprint(connection.refs ?? []) };
}
@@ -71,16 +120,17 @@ export function createGitHubTaskRetryBatchAuthority<T extends GitHubRetryBinding
) => Promise<T>) {
async function authorizeGitHubTaskRetryBatch(tx: DbOrTransaction, actions: Array<typeof chatActions.$inferSelect>,
notice: { nonblocking: true; terminal: boolean; taskRetry: TaskRetryWakeAuthority }) {
const deny = () => forbidden("This accepted chat message is no longer authorized to start work",
{ code: "chat_action_authorization_changed" });
const deny = chatWakeAuthorityDenied;
const first = actions[0];
if (!first) throw deny();
if (!first) throw deny("batch_scope");
const skipped = await skippedTaskRetryInputs(tx, actions, notice.taskRetry);
const commonScope = (action: typeof chatActions.$inferSelect) => JSON.stringify([
action.companyId, action.endpointId, action.conversationId, action.principalId, action.kind, action.status,
action.companyId, action.endpointId, action.conversationId, action.principalId, action.kind,
skipped.has(action.id) ? "processed" : action.status,
...["version", "issueId", "agentId", "sessionGeneration", "requestedByActorType", "requestedByActorId"]
.map(key => action.payload[key]),
]);
if (actions.some(action => commonScope(action) !== commonScope(first))) throw deny();
if (actions.some(action => commonScope(action) !== commonScope(first))) throw deny("batch_scope");
const deliveries = await tx.select().from(chatDeliveries).where(and(eq(chatDeliveries.companyId, first.companyId),
inArray(chatDeliveries.id, actions.map(action => action.deliveryId!))));
const byDelivery = new Map(deliveries.map(delivery => [delivery.id, delivery]));
@@ -102,21 +152,21 @@ export function createGitHubTaskRetryBatchAuthority<T extends GitHubRetryBinding
const authorized = new Map<string, T>();
for (const action of actions) {
const delivery = byDelivery.get(action.deliveryId!);
if (!delivery || !linked.has(`${delivery.id}:${action.payload.commentId}`)) throw deny();
if (!delivery || !linked.has(`${delivery.id}:${action.payload.commentId}`)) throw deny("batch_source_link");
// Reuse only the same live grant within this transaction. Automatic review
// policies with different contexts still receive their own full check.
const grant = JSON.stringify(delivery.normalizedEvent.githubAutomatic ?? delivery.normalizedEvent.githubIssue ?? null);
let current = groups.get(grant);
if (!current) {
current = await authorize(tx, action, notice);
if (current.endpoint.provider !== "github") throw deny();
if (current.endpoint.provider !== "github") throw deny("app_binding");
notice.taskRetry.runtimeFence ??= current.retryRuntimeFence;
groups.set(grant, current);
}
if (delivery.state !== "processed" || delivery.endpointId !== current.endpoint.id ||
delivery.conversationId !== current.conversation.id || delivery.principalId !== action.principalId ||
!githubTaskRetryAppMatches(current.endpoint, delivery, legacyByDelivery.get(delivery.id)) ||
!githubTaskRetryDestinationMatches(delivery, current.conversation, current.resource)) throw deny();
!(await githubTaskRetryAppAuthorized(tx, current.endpoint, delivery, legacyByDelivery.get(delivery.id))) ||
!githubTaskRetryDestinationMatches(delivery, current.conversation, current.resource)) throw deny("destination_binding");
authorized.set(action.id, { ...current, delivery });
}
return authorized;
@@ -0,0 +1,16 @@
import { describe, expect, it } from "vitest";
import { forbidden } from "../../../errors.js";
import { chatWakeAuthorityDenied, safeChatWakeAuthorityReason } from "./wakeup-authorization-error.js";
describe("safe chat wake authority reason", () => {
it("retains only the stable category from a known authority refusal", () => {
expect(safeChatWakeAuthorityReason(chatWakeAuthorityDenied("source_receipt"))).toBe("source_receipt");
});
it.each([
forbidden("private provider response", { code: "chat_action_authorization_changed", authorityReason: "private-source-payload" }),
forbidden("private provider response", { code: "another_error", authorityReason: "source_receipt" }),
{ details: { code: "chat_action_authorization_changed", authorityReason: "source_receipt" } },
])("does not copy arbitrary error fields or untrusted error shapes", error => {
expect(safeChatWakeAuthorityReason(error)).toBeUndefined();
});
});
@@ -0,0 +1,19 @@
import { forbidden, HttpError } from "../../../errors.js";
// Stable categories only. Never surface stored provider payloads, identifiers,
// credential fingerprints, or arbitrary downstream error text to the board.
const reasons = ["source_shape", "task_assignment", "delivery_binding", "runtime_fence",
"conversation_binding", "destination_binding", "automatic_policy", "task_privacy",
"principal_access", "source_comment", "retry_intent", "source_receipt", "app_binding",
"connection_access", "runtime_generation", "batch_scope", "batch_source_link"] as const;
export type ChatWakeAuthorityReason = typeof reasons[number];
export function chatWakeAuthorityDenied(authorityReason: ChatWakeAuthorityReason) {
return forbidden("This accepted chat message is no longer authorized to start work",
{ code: "chat_action_authorization_changed", authorityReason });
}
export function safeChatWakeAuthorityReason(error: unknown): ChatWakeAuthorityReason | undefined {
if (!(error instanceof HttpError) || !error.details || typeof error.details !== "object") return undefined;
const details = error.details as Record<string, unknown>;
return details.code === "chat_action_authorization_changed" && reasons.includes(details.authorityReason as ChatWakeAuthorityReason)
? details.authorityReason as ChatWakeAuthorityReason : undefined;
}
@@ -1,3 +1,4 @@
import { chatWakeAuthorityDenied } from "./wakeup-authorization-error.js";
import { nonDirectDestinationAllowed } from "./surfaces.js";
import { lifecycleRuntimeFence } from "./delivery-ledger.js";
import type { DbTransaction, DbOrTransaction } from "../runtime-types.js";
@@ -45,11 +46,7 @@ export function createInboundWakeAuthority(db: Db, options: WakeAuthorityOptions
notice?: { nonblocking: true; terminal: boolean; taskRetry?: TaskRetryWakeAuthority },
) {
const payload = action.payload;
const deny = () =>
forbidden(
"This accepted chat message is no longer authorized to start work",
{ code: "chat_action_authorization_changed" },
);
const deny = chatWakeAuthorityDenied;
if (
payload.version !== 1 ||
typeof payload.issueId !== "string" ||
@@ -61,7 +58,7 @@ export function createInboundWakeAuthority(db: Db, options: WakeAuthorityOptions
!["user", "system"].includes(String(payload.requestedByActorType)) ||
typeof payload.requestedByActorId !== "string"
)
throw deny();
throw deny("source_shape");
const issue = await tx
.select()
.from(issues)
@@ -80,7 +77,7 @@ export function createInboundWakeAuthority(db: Db, options: WakeAuthorityOptions
(!notice?.terminal &&
["backlog", "done", "cancelled"].includes(issue.status))
)
throw deny();
throw deny("task_assignment");
// The scheduler already owns the issue lock. Do not wait in the opposite
// order behind an ingress transaction which owns the endpoint first.
const endpoint = await tx
@@ -117,13 +114,11 @@ export function createInboundWakeAuthority(db: Db, options: WakeAuthorityOptions
delivery.endpointId !== endpoint.id ||
delivery.conversationId !== action.conversationId ||
delivery.principalId !== action.principalId ||
!currentFence ||
!(await runtimeCallbackEndpoint(tx as unknown as DbTransaction, endpoint.id, currentFence, [
"verifying",
"active",
]))
!currentFence
)
throw deny();
throw deny("delivery_binding");
if (!(await runtimeCallbackEndpoint(tx as unknown as DbTransaction, endpoint.id, currentFence, ["verifying", "active"])))
throw deny("runtime_fence");
const conversation = await tx
.select()
.from(chatConversations)
@@ -143,7 +138,7 @@ export function createInboundWakeAuthority(db: Db, options: WakeAuthorityOptions
conversation.sessionGeneration !== payload.sessionGeneration ||
!["active", "waiting"].includes(conversation.state)
)
throw deny();
throw deny("conversation_binding");
const resource = conversation.resourceId
? await tx
.select()
@@ -163,15 +158,15 @@ export function createInboundWakeAuthority(db: Db, options: WakeAuthorityOptions
endpoint,
action.principalId,
);
if (notice?.taskRetry && !githubTaskRetryDestinationMatches(delivery, conversation, resource)) throw deny();
if (notice?.taskRetry && !githubTaskRetryDestinationMatches(delivery, conversation, resource)) throw deny("destination_binding");
if (endpoint.provider === "github") {
const automatic = await resolveGitHubWakeAuthority(tx, endpoint, delivery);
if (automatic.kind === "denied") throw deny();
if (automatic.kind === "denied") throw deny("automatic_policy");
if (automatic.kind === "allowed") authorization.userId = automatic.userId;
}
if (!(await canActorReadIssuePrivacy(tx, authorization.userId
? { type: "board", userId: authorization.userId }
: { type: "none" }, issue))) throw deny();
: { type: "none" }, issue))) throw deny("task_privacy");
const expectedUserId =
payload.requestedByActorType === "user"
? payload.requestedByActorId
@@ -185,7 +180,7 @@ export function createInboundWakeAuthority(db: Db, options: WakeAuthorityOptions
(payload.requestedByActorType === "system" &&
payload.requestedByActorId !== action.principalId)
)
throw deny();
throw deny("principal_access");
const source = await tx
.select({
authorUserId: issueComments.authorUserId,
@@ -217,7 +212,7 @@ export function createInboundWakeAuthority(db: Db, options: WakeAuthorityOptions
(source.deletedAt && !notice?.terminal) ||
source.authorUserId !== expectedUserId
)
throw deny();
throw deny("source_comment");
return { issue, delivery, endpoint, conversation, resource,
...(notice?.taskRetry && currentFence ? { retryRuntimeFence: currentFence } : {}) };
}
@@ -5,13 +5,13 @@ import { enqueueFastResponse } from "../../fast-responses.js";
import { and, eq, sql } from "drizzle-orm";
import { retryChatControlAdmission } from "../../chat-control-admission-retry.js";
import type { Db } from "@paperclipai/db";
import { createDurableChatWakeupRequest, assertDurableChatWakeupReceipt } from "../../durable-chat-wakeup.js";
import { createDurableChatWakeupRequest, assertDurableChatWakeupReceipt, registerDeferredChatWakeOwner } from "../../durable-chat-wakeup.js";
import { agentWakeupRequests, chatActions, chatConversations, chatDeliveries, chatEndpoints } from "@paperclipai/db";
import { forbidden } from "../../../errors.js";
import { logger } from "../../../middleware/logger.js";
import { queueIssueAssignmentWakeup } from "../../issue-assignment-wakeup.js";
import { isGitHubAutomaticDelivery, acknowledgeGitHubWakeup } from "../github/wake-authority.js";
import type { createInboundWakeAuthority } from "./wakeup-authorization.js";
import { inboundWakeScope, type createInboundWakeAuthority } from "./wakeup-authorization.js";
import type { createInboundAttachments } from "../inbound-attachments.js";
import type { IssueAssignmentWakeupDeps } from "../../issue-assignment-wakeup.js";
type InboundAttachmentResult = Awaited<ReturnType<ReturnType<typeof createInboundAttachments>["ingestAttachments"]>>;
@@ -425,5 +425,46 @@ export function createInboundWakeups(db: Db, options: WakeupOptions) {
return denied;
}
}
return { stageInboundWakeup, acceptInboundWakeup, settleRejectedInboundWakeups, processInboundWakeup };
const unregisterDeferredWakeOwner = registerDeferredChatWakeOwner(db, async (scope) => {
const action = await db.select().from(chatActions).where(and(
eq(chatActions.id, scope.requestId), eq(chatActions.companyId, scope.companyId),
eq(chatActions.kind, "inbound_wakeup"), eq(chatActions.status, "processed"),
)).then(rows => rows[0] ?? null);
if (!action || action.payload.agentId !== scope.agentId || action.payload.issueId !== scope.issueId) return;
const [receipt] = await db.select().from(agentWakeupRequests).where(and(
eq(agentWakeupRequests.id, action.id), eq(agentWakeupRequests.companyId, scope.companyId),
eq(agentWakeupRequests.agentId, scope.agentId), eq(agentWakeupRequests.status, "deferred_issue_execution"),
));
if (!receipt || receipt.runId) return;
const authorize = async (tx: Db) => {
const [source] = await tx.select().from(chatActions).where(and(
eq(chatActions.id, action.id), eq(chatActions.companyId, scope.companyId),
eq(chatActions.kind, "inbound_wakeup"), eq(chatActions.status, "processed"),
));
if (!source || inboundWakeScope(source) !== inboundWakeScope(action))
throw forbidden("The saved chat source changed", { code: "chat_action_authorization_changed" });
const current = await authorizeInboundWorkStart(tx, source);
if (current.delivery.state !== "processed") throw new Error("chat_inbound_wakeup_acceptance_not_committed");
return current;
};
// The same authority used at ingress checks the live endpoint, principal,
// immutable action source, conversation generation and original comment.
const context = await db.transaction(tx => authorize(tx as unknown as Db));
const request = createDurableChatWakeupRequest({
id: action.id, companyId: scope.companyId, agentId: scope.agentId, issueId: scope.issueId,
commentId: String(action.payload.commentId),
requestedByActorType: action.payload.requestedByActorType as "user" | "system",
requestedByActorId: String(action.payload.requestedByActorId), requestedAt: action.createdAt,
resumeDeferred: true, authorize: async tx => { await authorize(tx); },
});
assertDurableChatWakeupReceipt(request, receipt);
await queueIssueAssignmentWakeup({ heartbeat: options.heartbeat, issue: context.issue,
reason: "External chat message received", mutation: "chat_message_received",
contextSource: `chat:${context.endpoint.provider}`, taskKey: context.issue.identifier,
requestedByActorType: request.requestedByActorType, requestedByActorId: request.requestedByActorId,
wakeCommentId: request.commentId, chatConversationId: context.conversation.id,
attachmentOmissionReasons: action.payload.attachmentOmissionReasons as Record<string, number> | undefined,
durableChatRequest: request, rethrowOnError: true });
});
return { stageInboundWakeup, acceptInboundWakeup, settleRejectedInboundWakeups, processInboundWakeup, unregisterDeferredWakeOwner };
}
@@ -1,5 +1,6 @@
import { and, eq, sql } from "drizzle-orm";
import { agentWakeupRequests, environmentLeases, heartbeatRuns, issueRecoveryActions, nativeRunFinalizations, type Db } from "@paperclipai/db";
import { agentWakeupRequests, environmentLeases, heartbeatRuns, issueRecoveryActions, nativeRunFinalizations, nativeRunResults, issues, type Db } from "@paperclipai/db";
import { buildExecutionContinuation } from "../execution-continuation.js";
import { readTaskRetryIntent } from "../task-retry.js";
import { hasNativeLocalProcessStop, hasHistoricalSuspendedNativeSession, recordedLocalExecutionStopped } from "../native-local-process-stop.js";
import { hasRemoteTerminationReceipt } from "../remote-execution-termination.js";
@@ -30,13 +31,29 @@ export async function readTaskChatRetryIntent(db: Db, input: {
/** An unusable checkpoint does not prevent an isolated attempt. The old
* executor must still be contained; a terminal database row is insufficient. */
export async function taskChatRetryExecutionStopped(db: Db, run: typeof heartbeatRuns.$inferSelect) {
return taskChatRetryExecutionContained(db, run, false);
}
async function taskChatRetryExecutionContained(db: Db, run: typeof heartbeatRuns.$inferSelect, admittedFailure: boolean) {
if (adapterExecutionControls.has(run.id) ||
(run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date())) return false;
const [coordinator] = await db.select().from(nativeRunFinalizations).where(and(
eq(nativeRunFinalizations.companyId, run.companyId), eq(nativeRunFinalizations.runId, run.id),
)).for("share", { noWait: true });
if (coordinator && (coordinator.leaseOwner || coordinator.resultId || coordinator.failureDetail?.successorRunId ||
if (coordinator && (coordinator.leaseOwner || coordinator.failureDetail?.successorRunId ||
!["terminal_failure", "committed"].includes(coordinator.phase))) return false;
if (coordinator?.resultId) {
if (!admittedFailure || run.runtimeMode !== "native" || run.status !== "failed" ||
run.nativePhase !== "committed" || !run.completionContractId || coordinator.phase !== "committed" ||
coordinator.issueId !== run.nativeIssueId) return false;
const [failedResult] = await db.select({ id: nativeRunResults.id }).from(nativeRunResults).where(and(
eq(nativeRunResults.companyId, run.companyId), eq(nativeRunResults.runId, run.id),
eq(nativeRunResults.issueId, run.nativeIssueId!), eq(nativeRunResults.id, coordinator.resultId),
eq(nativeRunResults.schemaStatus, "accepted"), eq(nativeRunResults.completionContractId, run.completionContractId),
sql`${nativeRunResults.resultJson}#>>'{terminal,runTerminalState}' = 'failed'`,
)).limit(1);
if (!failedResult) return false;
}
const leases = await db.select().from(environmentLeases).where(and(
eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, run.id),
)).for("share", { noWait: true });
@@ -46,6 +63,42 @@ export async function taskChatRetryExecutionStopped(db: Db, run: typeof heartbea
await hasHistoricalSuspendedNativeSession(db, run);
}
/** Dispatch revalidates the canonical admission receipt, not an admission which
* has already resolved its recovery holds. This exception certifies only the
* exact current successor; it never makes the failed result replayable. */
export async function taskChatRetryAdmittedContinuationStopped(db: Db, run: typeof heartbeatRuns.$inferSelect,
input: { issueId: string; intentId: string; successorRunId: string; commentId: string }) {
if (run.nativeIssueId !== input.issueId) return false;
const retry = await readTaskChatRetryIntent(db, { companyId: run.companyId, issueId: input.issueId,
agentId: run.agentId, sourceRunId: run.id, intentId: input.intentId });
if (!retry?.intent.chatActionId) return false;
const [task] = await db.select({ assignee: issues.assigneeAgentId, executionRunId: issues.executionRunId })
.from(issues).where(and(eq(issues.companyId, run.companyId), eq(issues.id, input.issueId)));
const [successor] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, run.companyId),
eq(heartbeatRuns.id, input.successorRunId), eq(heartbeatRuns.agentId, run.agentId))).for("share", { noWait: true });
const [receipt] = await db.select({ runId: agentWakeupRequests.runId, status: agentWakeupRequests.status })
.from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, run.companyId),
eq(agentWakeupRequests.id, retry.intent.chatActionId), eq(agentWakeupRequests.agentId, run.agentId)));
const explicit = successor?.contextSnapshot?.explicitUserContinuation as Record<string, unknown> | undefined;
if (!successor || task?.assignee !== run.agentId || task.executionRunId !== successor.id ||
successor.contextSnapshot?.issueId !== input.issueId ||
(successor.nativeIssueId !== null && successor.nativeIssueId !== input.issueId) ||
successor.status !== "running" || successor.wakeupRequestId !== retry.intent.chatActionId ||
successor.retryOfRunId !== run.id || receipt?.runId !== successor.id || receipt.status !== "claimed" ||
successor.contextSnapshot?.taskRetryRequestId !== input.intentId ||
explicit?.previousRunId !== run.id || explicit.commentId !== input.commentId ||
explicit.taskRetryRequestId !== input.intentId || await getExecutionBlocker(db, run.companyId, input.issueId)) return false;
try {
await buildExecutionContinuation({ db, companyId: run.companyId, issueId: input.issueId,
agentId: run.agentId, runId: successor.id, context: successor.contextSnapshot!, summary: null, exposeLowTrustRaw: false });
} catch (error) {
if (error instanceof Error && ["continuation_user_authorization_missing", "continuation_source_context_missing",
"continuation_task_ownership_changed"].includes(error.message)) return false;
throw error;
}
return taskChatRetryExecutionContained(db, run, true);
}
/** Admission may persist a wait for the exact recovery this user requested.
* This grants no execution authority: promotion and execution still require
* containment, and the queue retains the source's current execution blocker. */
@@ -1,5 +1,5 @@
import { z } from "zod";
import { and, asc, eq, inArray, isNull, sql } from "drizzle-orm";
import { and, asc, eq, gt, inArray, isNull, or, sql } from "drizzle-orm";
import { agentWakeupRequests, chatActions, chatConversations, chatEndpoints, heartbeatRuns, issues, type Db } from "@paperclipai/db";
import type { DbOrTransaction } from "./runtime-types.js";
@@ -8,15 +8,19 @@ export const taskRetryInputSchema = z.object({
// Truncating it strands older requests or makes the newer-input guard reject
// every Retry. Dispatch already carries the full queue with bounded inline text.
sourceActionIds: z.array(z.string().uuid()).refine(ids => new Set(ids).size === ids.length),
skippedActionIds: z.array(z.string().uuid()).optional(),
runtimeFence: z.object({ generation: z.number().int().nonnegative(),
credentialFingerprint: z.string().regex(/^[a-f0-9]{64}$/) }).optional(),
});
}).refine(value => !value.skippedActionIds || (
new Set(value.skippedActionIds).size === value.skippedActionIds.length &&
value.skippedActionIds.every(id => value.sourceActionIds.includes(id))
));
export type TaskRetryInput = z.infer<typeof taskRetryInputSchema>;
export async function selectTaskRetryInput(tx: DbOrTransaction, input: {
companyId: string; issueId: string; agentId: string; failedRunId: string;
}) {
const [conversation] = await tx.select({ id: chatConversations.id }).from(chatConversations)
const [conversation] = await tx.select({ id: chatConversations.id, runCreatedAt: heartbeatRuns.createdAt }).from(chatConversations)
.innerJoin(chatEndpoints, eq(chatEndpoints.id, chatConversations.endpointId))
.innerJoin(chatActions, and(eq(chatActions.companyId, chatConversations.companyId),
eq(chatActions.conversationId, chatConversations.id)))
@@ -28,15 +32,20 @@ export async function selectTaskRetryInput(tx: DbOrTransaction, input: {
eq(chatEndpoints.externalExecutionPolicy, "restricted"),
)).limit(1);
if (!conversation) return undefined;
const pending = await tx.select({ id: chatActions.id }).from(chatActions)
const pending = await tx.select({ id: chatActions.id, status: agentWakeupRequests.status }).from(chatActions)
.innerJoin(agentWakeupRequests, and(eq(agentWakeupRequests.companyId, chatActions.companyId),
eq(agentWakeupRequests.id, chatActions.id))).where(and(
eq(chatActions.companyId, input.companyId), eq(chatActions.conversationId, conversation.id),
eq(chatActions.kind, "inbound_wakeup"), eq(chatActions.status, "processed"),
eq(agentWakeupRequests.agentId, input.agentId), eq(agentWakeupRequests.status, "deferred_issue_execution"),
eq(chatActions.kind, "inbound_wakeup"), eq(agentWakeupRequests.agentId, input.agentId),
or(and(eq(chatActions.status, "processed"), eq(agentWakeupRequests.status, "deferred_issue_execution")),
and(eq(chatActions.status, "failed"), eq(agentWakeupRequests.status, "skipped"),
inArray(agentWakeupRequests.reason, ["budget.blocked", "agent.not_invokable"]),
sql`${chatActions.payload}->>'requestedByActorType' = 'user'`,
gt(chatActions.createdAt, conversation.runCreatedAt))),
isNull(agentWakeupRequests.runId),
)).orderBy(asc(chatActions.createdAt), asc(chatActions.id)).for("update", { of: agentWakeupRequests });
return taskRetryInputSchema.parse({ sourceActionIds: pending.map(row => row.id) });
return taskRetryInputSchema.parse({ sourceActionIds: pending.map(row => row.id),
skippedActionIds: pending.filter(row => row.status === "skipped").map(row => row.id) });
}
export async function claimTaskRetryInput(tx: DbOrTransaction, input: {
@@ -35,6 +35,33 @@ const responseRunColumns = {
issueId: heartbeatRuns.issueId,
status: heartbeatRuns.status,
updatedAt: heartbeatRuns.updatedAt,
// Terminal execution can precede native presentation commit. Until its
// durable decision exists, missing output is undecided rather than failure.
nativePresentationPending: sql<boolean>`coalesce(
${heartbeatRuns.status} = 'succeeded'
and ${heartbeatRuns.runtimeMode} = 'native'
and (${heartbeatRuns.nativePhase} is distinct from 'committed'
or ${heartbeatRuns.resultJson}->'presentationDecision'->>'schema' is distinct from 'paperclip.run_presentation_decision.v1'
or coalesce(${heartbeatRuns.resultJson}->'presentationDecision'->>'commentAction', '') not in ('none', 'create', 'reuse')),
false
)`,
// Project only the server-committed no-publication decision, never the
// potentially large native result or model-authored summary.
passiveResponseWait: sql<boolean>`coalesce(
${heartbeatRuns.status} = 'succeeded'
and ${heartbeatRuns.runtimeMode} = 'native'
and ${heartbeatRuns.nativePhase} = 'committed'
and ${heartbeatRuns.resultJson}->>'finalizationPhase' = 'committed'
and ${heartbeatRuns.resultJson}->>'finalizationReasonCode' = 'external_chat_response_waiting'
and ${heartbeatRuns.resultJson}->'nativeResult'->>'schema' = 'paperclip.run_result.v1'
and ${heartbeatRuns.resultJson}->'nativeResult'->>'reportedWorkDisposition' = 'yielded'
and ${heartbeatRuns.resultJson}->'nativeResult'->'continuation'->>'kind' = 'response_wake'
and ${heartbeatRuns.resultJson}->'presentationDecision'->>'schema' = 'paperclip.run_presentation_decision.v1'
and ${heartbeatRuns.resultJson}->'presentationDecision'->>'chosenSource' = 'none'
and ${heartbeatRuns.resultJson}->'presentationDecision'->>'commentAction' = 'none'
and ${heartbeatRuns.resultJson}->'presentationDecision'->'reasonCodes' @> '["yielded_control_plane_wait"]'::jsonb,
false
)`,
contextSnapshot: sql<Record<string, unknown>>`jsonb_build_object(
'issueId', ${heartbeatRuns.contextSnapshot}->'issueId',
'taskId', ${heartbeatRuns.contextSnapshot}->'taskId',
@@ -130,7 +157,7 @@ export async function writeGitHubResponseComment(
const sameRequest = !shared || previous?.body?.includes(requestResponseMarker(source)) === true;
const alreadyFinal = sameRequest && previous?.body?.includes("<!-- paperclip-response-state:final -->") === true;
const body = `${projectSafeChatPublicationText(input.body)}\n\n${marker}${shared ? `\n${requestResponseMarker(source)}` : ""}\n<!-- paperclip-response-version:${versionAt.toISOString()} -->${input.final ? "\n<!-- paperclip-response-state:final -->" : ""}`;
const preserved = previous && (previous.body === body || (input.acknowledgement && sameRequest) || (alreadyFinal && !input.final) ||
const preserved = previous && (previous.body === body || (input.acknowledgement && (sameRequest || (shared && previous.body?.includes("<!-- paperclip-response-state:final -->")))) || (alreadyFinal && !input.final) ||
(input.preserveFinal && previous.body?.includes("<!-- paperclip-response-state:final -->"))) ? previous : null;
const posted = preserved && (!shared || preserved.body?.includes(marker)) ? preserved : await api.request<Comment>(
previous ? `${item}/${previous.id}` : source.replyId
@@ -145,7 +172,8 @@ export async function writeGitHubResponseComment(
const receipt = { id: String(posted.id), url: posted.html_url };
await lease.commit(async tx => {
if (shared) await tx.update(chatActions).set({ result: {
...receipt, final: input.final || alreadyFinal, versionAt: versionAt.toISOString(), deliveryId: source.delivery.id,
...receipt, final: input.final || alreadyFinal || Boolean(preserved?.body?.includes("<!-- paperclip-response-state:final -->")),
versionAt: versionAt.toISOString(), deliveryId: source.delivery.id,
}, updatedAt: new Date() }).where(eq(chatActions.id, target.id));
await tx.update(chatActions).set({ status: "processed", result: {
...receipt, final: input.final || alreadyFinal, versionAt: versionAt.toISOString(),
@@ -230,6 +258,20 @@ export function githubResponseCommentService(db: Db, fetchImpl = fetch) {
companyId: source.endpoint.companyId, endpointId: source.endpoint.id,
issueId: source.conversation.issueId!, runId: run.id }) : "none";
if (reply === "unsettled") throw conflict("GitHub reply is still being resolved");
// A confirmed reply for this exact run can retire its placeholder.
// Otherwise terminal execution is not yet a missing-response decision.
if (ownsLatestRequest && run.nativePresentationPending && reply === "none") return;
if (isMainPullResponse(source) && ownsLatestRequest && run.passiveResponseWait && reply === "none") {
// A committed passive turn intentionally has no new response.
// Settle this request's acknowledgement without editing the shared
// PR assessment or inventing a current-run publication receipt.
await lease.commit(async tx => { await tx.update(chatActions).set({
status: "cancelled", result: { ...existing.result, final: true, code: "passive_response_wait" },
updatedAt: new Date(),
}).where(and(eq(chatActions.id, existing.id), eq(chatActions.companyId, source.endpoint.companyId),
sql`coalesce(${chatActions.result}->>'final', 'false') <> 'true'`)); });
return;
}
if (existing.result?.final === true) return existing.result.id ? { id: String(existing.result.id), url: String(existing.result.url) } : undefined;
preserveFinal = reply === "confirmed";
onlyExisting = reply === "confirmed" && !existing.result?.id;
@@ -374,6 +416,8 @@ export function githubResponseCommentService(db: Db, fetchImpl = fetch) {
)).orderBy(desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id)).limit(1);
if (latest?.id !== run.id) throw forbidden("A newer GitHub run owns the response");
if ((await responseForRequest())?.result?.final === true) throw forbidden("GitHub request already has a final response");
if (current.nativePresentationPending) throw conflict("GitHub native response presentation is still being resolved");
if (isMainPullResponse(source) && current.passiveResponseWait) throw forbidden("GitHub run intentionally yielded without a new response");
if (await githubRunReplyState(db, input) !== "none") throw conflict("GitHub reply is still being resolved");
};
receipt = await acknowledge(link.deliveryId, input.body, assertRun);
+24 -8
View File
@@ -131,14 +131,18 @@ export async function resolveChatRunPresentationAuthorizationReason(
/** A missing receipt is not proof that a provider write never arrived. */
export async function githubRunReplyState(
db: Db,
input: { companyId: string; issueId: string; runId: string; endpointId: string },
input: { companyId: string; issueId: string; runId: string; endpointId: string; sourceCommentId?: string; requireSettled?: boolean },
): Promise<"none" | "unsettled" | "confirmed"> {
const actions = await db
.select({
status: chatActions.status,
operation: sql<string>`${chatActions.payload}->>'operation'`,
reviewId: sql<string | null>`${chatActions.payload}->>'reviewId'`,
result: chatActions.result,
result: sql<Record<string, unknown> | null>`case when ${chatActions.result} is null then null else jsonb_build_object(
'reviewId', ${chatActions.result}->'reviewId', 'id', ${chatActions.result}->'id', 'url', ${chatActions.result}->'url', 'summaryUrl', ${chatActions.result}->'summaryUrl',
'replyWriteStarted', ${chatActions.result}->'replyWriteStarted', 'retryable', ${chatActions.result}->'retryable',
'code', ${chatActions.result}->'code', 'attempts', ${chatActions.result}->'attempts',
'deliveryUnknown', ${chatActions.result}->'deliveryUnknown') end`,
})
.from(chatActions)
.innerJoin(chatConversations, and(
@@ -161,12 +165,19 @@ export async function githubRunReplyState(
sql`${chatActions.payload}->'session'->>'issueId' = ${input.issueId}`,
sql`${chatActions.payload}->'session'->>'runId' = ${input.runId}`,
sql`${chatActions.payload}->>'operation' in ('comment', 'formal_review', 'assessment')`,
input.sourceCommentId ? sql`exists (select 1 from chat_message_links source_link
where source_link.company_id = ${chatActions.companyId} and source_link.endpoint_id = ${chatActions.endpointId}
and source_link.conversation_id = ${chatActions.conversationId} and source_link.delivery_id = ${chatActions.deliveryId}
and source_link.direction = 'inbound' and source_link.comment_id = ${input.sourceCommentId}::uuid)` : undefined,
));
let unsettled = false;
let unsettled = false, confirmed = false;
for (const action of actions) {
if (input.requireSettled && (action.status !== "processed" || action.result?.deliveryUnknown === true)) {
unsettled = true;
}
// An assessment can publish findings before a later step fails or loses
// authority. Those durable receipts still prove a reply was delivered.
if (action.operation === "assessment") {
if (action.operation === "assessment" && !input.requireSettled) {
const [review] = await db
.select({ receipts: chatGitHubReviews.publicationReceipts })
.from(chatGitHubReviews)
@@ -181,11 +192,16 @@ export async function githubRunReplyState(
}
if (action.status === "processed") {
if (action.operation === "comment" || action.operation === "formal_review") {
if (action.result?.id && action.result?.url) return "confirmed";
unsettled = true;
if (action.result?.id && action.result?.url) {
if (!input.requireSettled) return "confirmed";
confirmed = true;
} else unsettled = true;
}
if (action.operation === "assessment") {
if (action.result?.summaryUrl) return "confirmed";
if (action.result?.summaryUrl) {
if (!input.requireSettled) return "confirmed";
confirmed = true;
} else if (input.requireSettled) unsettled = true;
}
} else if (action.result?.replyWriteStarted === true || ["received", "processing"].includes(action.status) ||
(action.status === "failed" && (action.result?.retryable === true || action.result?.code === "publication_failed")) ||
@@ -194,7 +210,7 @@ export async function githubRunReplyState(
unsettled = true;
}
}
return unsettled ? "unsettled" : "none";
return unsettled ? "unsettled" : confirmed ? "confirmed" : "none";
}
type ChatRunMilestoneCandidate = {
+4 -2
View File
@@ -601,7 +601,7 @@ function uniqueImportedSkillKey(companyId: string, baseSlug: string, usedKeys: S
return candidate;
}
function buildSkillRuntimeName(key: string, slug: string) {
export function buildSkillRuntimeName(key: string, slug: string) {
if (key.startsWith("paperclipai/paperclip/")) return slug;
return `${slug}--${hashSkillValue(key)}`;
}
@@ -6238,6 +6238,8 @@ export function companySkillService(db: Db, options: { actor?: AuthorizationActo
files: Record<string, string>,
options?: {
onConflict?: PackageSkillConflictStrategy;
/** Managed plugin namespaces may share a slug while retaining separate canonical records. */
allowSlugCollision?: boolean;
},
): Promise<ImportPackageSkillResult[]> {
await ensureSkillInventoryCurrent(companyId);
@@ -6286,7 +6288,7 @@ export function companySkillService(db: Db, options: { actor?: AuthorizationActo
const normalizedSlug = normalizeSkillSlug(importedSkill.slug) ?? importedSkill.slug;
const existingByIncomingKey = existingByKey.get(importedSkill.key) ?? null;
const existingByIncomingSlug = existingBySlug.get(normalizedSlug) ?? null;
const conflict = existingByIncomingKey ?? existingByIncomingSlug;
const conflict = existingByIncomingKey ?? (options?.allowSlugCollision ? null : existingByIncomingSlug);
if (!conflict || conflictStrategy === "replace") {
const skillToPersist = conflict && conflict.key !== importedSkill.key
+9 -4
View File
@@ -103,9 +103,10 @@ export function dashboardService(db: Db) {
const monthSpendCents = Number(monthSpend);
// Per-day run breakdown. A run is "recovered" when its retry chain later
// succeeded (recovered_runs = all ancestors of a succeeded retry), so a
// restart-killed run whose retry succeeded is pulled out of the headline
// failed count. error_code is carried through so a failure spike can be
// attributed to an error class (e.g. process_lost, provider_quota).
// restart-killed or shutdown-interrupted run whose retry succeeded is
// pulled out of the headline failure count. error_code is carried through
// so a failure spike can be attributed to an error class (e.g. process_lost,
// provider_quota).
// Both recursive arms are bounded to the chart window: a retry is always
// created after the run it retries, so ancestors of an out-of-window
// child are themselves out of window and invisible to the membership
@@ -166,7 +167,11 @@ export function dashboardService(db: Db) {
const recovered = row.recovered === true || row.recovered === "t" || row.recovered === "true";
if (status === "succeeded") {
bucket.succeeded += count;
} else if (status === "failed" || status === "timed_out") {
} else if (
status === "failed" ||
status === "timed_out" ||
(recovered && status === "interrupted")
) {
if (recovered) {
bucket.recovered += count;
} else {
@@ -181,6 +181,19 @@ export function unadmittedChatWakeupCondition(
and chat_admission.agent_id::text = chat_unadmitted.payload->>'agentId'
and chat_admission.status <> 'skipped'
)
and not exists (
select 1 from chat_actions chat_retry
join agent_wakeup_requests chat_retry_admission on chat_retry_admission.id = chat_retry.id
where chat_retry.company_id = chat_unadmitted.company_id
and chat_retry.endpoint_id = chat_unadmitted.endpoint_id
and chat_retry.conversation_id = chat_unadmitted.conversation_id
and chat_retry.kind = 'failed_run_retry'
and chat_retry.payload->'taskRetryInput'->'skippedActionIds' ? chat_unadmitted.id::text
and chat_retry.payload->>'issueId' = chat_unadmitted.payload->>'issueId'
and chat_retry_admission.company_id = chat_retry.company_id
and chat_retry_admission.agent_id::text = chat_retry.payload->>'agentId'
and chat_retry_admission.status <> 'skipped'
)
and (chat_unadmitted.status <> 'failed' or not exists (
select 1 from chat_actions chat_later
join agent_wakeup_requests chat_later_admission on chat_later_admission.id = chat_later.id
@@ -198,6 +211,23 @@ export function unadmittedChatWakeupCondition(
)`;
}
export interface DeferredChatWakeScope {
companyId: string;
agentId: string;
issueId: string;
requestId: string;
}
const deferredChatWakeOwners = new WeakMap<Db, (input: DeferredChatWakeScope) => Promise<void>>();
/** The live inbound owner reauthorizes the original source. Cleanup owns no chat authority. */
export function registerDeferredChatWakeOwner(db: Db, owner: (input: DeferredChatWakeScope) => Promise<void>) {
deferredChatWakeOwners.set(db, owner);
return () => { if (deferredChatWakeOwners.get(db) === owner) deferredChatWakeOwners.delete(db); };
}
export async function resumeDeferredChatWake(db: Db, input: DeferredChatWakeScope) {
await deferredChatWakeOwners.get(db)?.(input);
}
/** Internal authority: this object cannot be supplied through a JSON API. */
export interface DurableChatWakeupRequest {
readonly id: string;
@@ -210,6 +240,8 @@ export interface DurableChatWakeupRequest {
readonly requestedAt: Date;
readonly idempotencyKey: string;
readonly failedRunRetry?: { readonly failedRunId: string };
/** Only the current inbound owner may reconsider its already saved, unconsumed receipt. */
readonly resumeDeferred?: true;
readonly authorize: (tx: Db) => Promise<void>;
readonly onAdmitted?: (tx: Db, receipt: { runId: string | null }) => Promise<void>;
}
@@ -273,6 +273,7 @@ export function environmentRunOrchestrator(
adapterType: string;
adapterConfig?: Record<string, unknown>;
admittedLifecycleMode?: "warm" | "per_turn";
managedAiCredentialIdentity?: string;
issueId: string | null;
heartbeatRunId: string;
agentId: string;
@@ -292,7 +293,7 @@ export function environmentRunOrchestrator(
});
const environment = resolveRunnerEnvironmentForRun(
selectedEnvironment, input.adapterType, input.adapterConfig, input.admittedLifecycleMode,
selectedEnvironment, input.adapterType, input.adapterConfig, input.admittedLifecycleMode, input.managedAiCredentialIdentity,
);
if (input.recoverPluginTask && environment.driver === "plugin" && input.adapterType === "paperclip_runner") {
+1 -1
View File
@@ -1875,7 +1875,7 @@ function createSandboxEnvironmentDriver(
? qualifiedSandboxSnapshotId(configuredEnvironment, input.companyId, parsed.config, selectedTemplate.value) : null;
if (input.adapterType === "paperclip_runner" && !pinnedSnapshotId
&& hasSandboxSnapshotQualification(configuredEnvironment, input.companyId)) {
throw new Error("sandbox_snapshot_qualification_required: The snapshot qualification is missing or stale. Test this environment again before running Paperclip Runner.");
throw new Error("sandbox_snapshot_qualification_required: The snapshot qualification is missing or stale. Open the agent's Harness / Runtime page and select Run test before running Paperclip Runner.");
}
if (input.configuredEnvironment) parsed.config = { ...parsed.config, reuseLease: storedParsed.config.reuseLease, archiveOnRelease: storedParsed.config.archiveOnRelease };
if (pinnedSnapshotId) parsed.config = { ...parsed.config, snapshot: pinnedSnapshotId };
+64
View File
@@ -0,0 +1,64 @@
import { and, eq, inArray, or, sql } from "drizzle-orm";
import { companySkills, pluginCompanySettings, pluginManagedResources, plugins, type Db } from "@paperclipai/db";
import { readPaperclipSkillSyncPreference, resolvePaperclipDesiredSkillNames, writePaperclipSkillSyncPreference } from "@paperclipai/adapter-utils/server-utils";
import { unprocessable } from "../errors.js";
import { buildSkillRuntimeName } from "./company-skills.js";
import { pluginManagedSkillService } from "./plugin-managed-skills.js";
/** Environment capabilities join the normal authorized, versioned skill selection. */
export async function environmentSkillConfig(db: Db, companyId: string,
environment: { driver: string; config: Record<string, unknown> | null } | null | undefined,
config: Record<string, unknown>, installMissing = true): Promise<{ config: Record<string, unknown>; skillKeys: string[]; shadowedSkills?: Array<{ key: string; shadowedBy: string }> }> {
if (environment?.driver !== "plugin") return { config, skillKeys: [] };
const { pluginKey, driverKey } = environment.config ?? {};
if (typeof pluginKey !== "string" || typeof driverKey !== "string") return { config, skillKeys: [] };
const [plugin] = await db.select().from(plugins).where(eq(plugins.pluginKey, pluginKey));
const keys = plugin?.manifestJson.environmentDrivers?.find(driver => driver.driverKey === driverKey)?.skillKeys ?? [];
if (!plugin || !keys.length) return { config, skillKeys: [] };
const [settings] = await db.select().from(pluginCompanySettings).where(and(
eq(pluginCompanySettings.companyId, companyId), eq(pluginCompanySettings.pluginId, plugin.id)));
if (plugin.status !== "ready" || settings?.enabled === false || !plugin.manifestJson.capabilities.includes("skills.managed")) {
throw unprocessable("Environment skills require an enabled plugin with skills.managed capability");
}
// Existing bindings need only a bounded metadata query, not a file-by-file drift scan.
const installed = await db.select({ resourceKey: pluginManagedResources.resourceKey, key: companySkills.key })
.from(pluginManagedResources).innerJoin(companySkills, and(
eq(companySkills.id, pluginManagedResources.resourceId), eq(companySkills.companyId, companyId)))
.where(and(eq(pluginManagedResources.companyId, companyId), eq(pluginManagedResources.pluginId, plugin.id),
eq(pluginManagedResources.resourceKind, "skill"), inArray(pluginManagedResources.resourceKey, keys)));
const selected = new Map(installed.map(skill => [skill.resourceKey, skill.key]));
for (const key of keys) {
if (selected.has(key) || !installMissing) continue;
const result = await db.transaction(async tx => {
// Serialize first installation across concurrent agents in this company.
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`environment-skill:${companyId}:${plugin.id}:${key}`}, 0))`);
return pluginManagedSkillService(tx as unknown as Db, { pluginId: plugin.id, pluginKey, manifest: plugin.manifestJson }).reconcile(key, companyId);
});
if (!result.skill) throw unprocessable("Environment skill is unavailable");
selected.set(key, result.skill.key);
}
const preference = readPaperclipSkillSyncPreference(config);
const explicit = new Set(preference.desiredSkillEntries.map(entry => entry.key));
const skillKeys = keys.flatMap(key => selected.has(key) ? [selected.get(key)!] : []);
const candidates = await db.select({ key: companySkills.key, slug: companySkills.slug, name: companySkills.name })
.from(companySkills).where(and(eq(companySkills.companyId, companyId),
or(inArray(sql<string>`lower(${companySkills.key})`, [...new Set([...explicit, ...skillKeys])].map(key => key.toLowerCase())),
inArray(sql<string>`lower(${companySkills.slug})`, [...explicit].map(key => key.toLowerCase().split("/").at(-1)!.replace(/--[a-f0-9]{10}$/, ""))))));
const names = candidates.map(skill => ({ key: skill.key, runtimeName: buildSkillRuntimeName(skill.key, skill.slug) }));
const entries = preference.desiredSkillEntries.map(entry => ({ ...entry,
key: resolvePaperclipDesiredSkillNames(writePaperclipSkillSyncPreference({}, [entry]), names)[0] ?? entry.key,
}));
const selectedKeys = new Set(entries.map(entry => entry.key));
const required = candidates.filter(skill => skillKeys.includes(skill.key));
const shadowedSkills = candidates.flatMap(skill => {
if (skillKeys.includes(skill.key) || !selectedKeys.has(skill.key)) return [];
const winner = required.find(candidate => candidate.slug === skill.slug || candidate.name === skill.name);
return winner ? [{ key: skill.key, shadowedBy: winner.key }] : [];
});
const shadowed = new Set(shadowedSkills.map(skill => skill.key));
return { config: writePaperclipSkillSyncPreference(config, [
...entries.filter(entry => !shadowed.has(entry.key)),
...skillKeys.filter(key => !selectedKeys.has(key))]), skillKeys,
...(shadowedSkills.length ? { shadowedSkills } : {}),
};
}
@@ -85,10 +85,11 @@ export async function executeEnvironmentTask(db: Db, workers: PluginWorkerManage
throw new Error("Plugin-provided Runner execution identity mismatch");
}
if (runner && resumeFrom) {
const sources = await db.select({ runId: environmentLeases.heartbeatRunId, metadata: environmentLeases.metadata }).from(environmentLeases).where(and(
const inspectCheckpoint = operation.kind === "read_state";
const sources = await db.select({ id: environmentLeases.id, runId: environmentLeases.heartbeatRunId, metadata: environmentLeases.metadata }).from(environmentLeases).where(and(
eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.provider, lease.provider!),
eq(environmentLeases.providerLeaseId, resumeFrom),
sql`${environmentLeases.metadata}->>'runnerTaskSessionRetained' = 'true'`,
inspectCheckpoint ? undefined : sql`${environmentLeases.metadata}->>'runnerTaskSessionRetained' = 'true'`,
checkpointIdentity ? eq(environmentLeases.heartbeatRunId, checkpointIdentity.runId) : undefined,
)).limit(2);
const priorRunId = sources.length === 1 ? sources[0]!.runId : null;
@@ -98,7 +99,20 @@ export async function executeEnvironmentTask(db: Db, workers: PluginWorkerManage
companyId: input.companyId, leaseId: lease.id,
priorIdentity: { runnerInstanceId: runner.runnerId, environmentLeaseId: runner.leaseId,
runId: priorRunId, normalizedSessionId: runner.sessionId },
inspectCheckpoint,
})) throw new Error("Plugin Runner resume identity mismatch");
// Older providers misclassified suspended checkpoints. A fresh provider
// attestation may repair availability, but never supplies stop/owner authority.
if (inspectCheckpoint && sources[0]!.metadata?.runnerTaskSessionRetained !== true) {
const status = await executeEnvironmentTask(db, workers, { companyId: input.companyId,
leaseId: sources[0]!.id, operation: { kind: "status" } });
if (status.kind !== "status" || status.executionStopped !== true || status.sessionStateAvailable !== true ||
resumeFrom !== await resolvePluginTaskResume(db, { companyId: input.companyId, leaseId: lease.id,
priorIdentity: { runnerInstanceId: runner.runnerId, environmentLeaseId: runner.leaseId,
runId: priorRunId, normalizedSessionId: runner.sessionId } })) {
throw new Error("Plugin Runner retained session is not authorized");
}
}
}
if (metadata.driver !== "plugin" || typeof metadata.pluginId !== "string" || typeof metadata.driverKey !== "string") {
throw new Error("Plugin-provided Runner execution lease has no pinned plugin driver");
@@ -380,6 +394,8 @@ export async function settleDispatchedEnvironmentTask(db: Db, workers: PluginWor
export async function resolvePluginTaskResume(db: Db, input: {
companyId: string; leaseId: string;
priorIdentity: { runnerInstanceId: string; environmentLeaseId: string; runId: string; normalizedSessionId: string };
/** Read-only discovery; launching still requires an attested retained checkpoint. */
inspectCheckpoint?: boolean;
}): Promise<string> {
const rows = await db.select({ lease: environmentLeases, run: heartbeatRuns }).from(environmentLeases)
.innerJoin(heartbeatRuns, and(eq(heartbeatRuns.id, environmentLeases.heartbeatRunId), eq(heartbeatRuns.companyId, input.companyId)))
@@ -389,7 +405,8 @@ export async function resolvePluginTaskResume(db: Db, input: {
// A retained PRP lease is logical; later provider tasks have different physical lease IDs.
const candidates = rows.filter(row => {
const identity = row.lease.metadata?.runnerTaskIdentity as Record<string, unknown> | undefined;
return row.lease.id !== input.leaseId && row.run.id === input.priorIdentity.runId && row.lease.metadata?.runnerTaskSessionRetained === true &&
return row.lease.id !== input.leaseId && row.run.id === input.priorIdentity.runId &&
(input.inspectCheckpoint || row.lease.metadata?.runnerTaskSessionRetained === true) &&
identity?.runnerId === input.priorIdentity.runnerInstanceId && identity.leaseId === input.priorIdentity.environmentLeaseId &&
identity.sessionId === input.priorIdentity.normalizedSessionId && identity.runId === input.priorIdentity.runId &&
!rows.some(successor => successor.lease.id !== input.leaseId &&
@@ -98,11 +98,22 @@ const support = await getEmbeddedPostgresTestSupport();
expect(JSON.stringify(envelope)).not.toContain("Unrelated");
});
it.each(["retryOfRunId", "previousRunId", "interruptedRunId"])("rejects explicit %s history from another task", async (key) => {
it.each(["retryOfRunId", "previousRunId"])("rejects explicit %s history from another task", async (key) => {
const f = await fixture();
await expect(f.build({ [key]: f.producerRunId })).rejects.toThrow("continuation_source_context_missing");
});
it("degrades a stale interruptedRunId hint from another task and keeps producer attribution", async () => {
// interruptedRunId is a best-effort hint, not explicit user history: when
// it names another task's run the wake continues without that resume
// source, and an interaction wake falls back to its producer.
const f = await fixture();
const envelope = await f.build({ interruptedRunId: f.producerRunId });
expect(envelope.trigger.sourceRunId).toBe(f.producerRunId);
expect(envelope.completedWork).toBeNull();
expect(envelope).not.toHaveProperty("interruptedRunId");
});
it("retains the explicit user continuation authorization requirement", async () => {
const f = await fixture();
await expect(f.build({ explicitUserContinuation: { previousRunId: f.producerRunId } }))
@@ -193,14 +193,41 @@ const support = await getEmbeddedPostgresTestSupport();
}
});
it("rejects handoff history from a different task", async () => {
it("degrades a stale interrupted-run hint from a different task instead of failing the wake", async () => {
// Cross-issue reassigns can leave interruptedRunId pointing at another
// task's run. The hint is best-effort: the wake must continue without a
// resume source instead of throwing continuation_source_context_missing.
const [source] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: randomUUID() } }).where(eq(heartbeatRuns.id, runId));
try {
await expectMissingContinuationContext(
() => buildExecutionContinuation({ db, companyId, issueId, agentId,
context: { interruptedRunId: runId }, summary: null, exposeLowTrustRaw: false }),
);
const envelope = await buildExecutionContinuation({ db, companyId, issueId, agentId,
context: { interruptedRunId: runId, wakeReason: "issue_assigned" }, summary: null, exposeLowTrustRaw: false });
expect(envelope.trigger.sourceRunId).toBeNull();
expect(envelope).not.toHaveProperty("interruptedRunId");
expect(envelope.objective).toBe("Focus the Gmail summary on launch decisions.");
} finally {
await db.update(heartbeatRuns).set({ contextSnapshot: source.contextSnapshot }).where(eq(heartbeatRuns.id, runId));
}
});
it("degrades an interrupted-run hint whose run row no longer exists", async () => {
const missingRunId = randomUUID();
const envelope = await buildExecutionContinuation({ db, companyId, issueId, agentId,
context: { interruptedRunId: missingRunId, wakeReason: "issue_assigned" }, summary: null, exposeLowTrustRaw: false });
expect(envelope.trigger.sourceRunId).toBeNull();
expect(envelope).not.toHaveProperty("interruptedRunId");
});
it("still rejects an explicit user resume from a different task", async () => {
// Fail-closed stays in force for explicit user resume history; only the
// best-effort interruptedRunId hint degrades.
const [source] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: randomUUID() } }).where(eq(heartbeatRuns.id, runId));
try {
await expect(
buildExecutionContinuation({ db, companyId, issueId, agentId,
context: { explicitUserContinuation: { previousRunId: runId }, wakeReason: "user_resume" }, summary: null, exposeLowTrustRaw: false }),
).rejects.toThrow("continuation_user_authorization_missing");
} finally {
await db.update(heartbeatRuns).set({ contextSnapshot: source.contextSnapshot }).where(eq(heartbeatRuns.id, runId));
}
+25 -6
View File
@@ -197,25 +197,44 @@ export async function buildExecutionContinuation(input: {
);
const explicitContinuation = object(input.context.explicitUserContinuation);
const explicitUserSource = string(explicitContinuation.previousRunId);
const interruptedSource = string(input.context.interruptedRunId);
const resumeSourceRunId =
explicitUserSource ??
string(input.context.retryOfRunId) ??
string(input.context.previousRunId) ??
string(input.context.interruptedRunId);
interruptedSource;
const producerRunId = triggerInteraction?.sourceRunId ?? null;
const sourceRunId = resumeSourceRunId ?? producerRunId;
const requestedSourceRunId = resumeSourceRunId ?? producerRunId;
const loadRun = async (id: string) => (await db
.select({ context: heartbeatRuns.contextSnapshot, result: heartbeatRuns.resultJson })
.from(heartbeatRuns)
.where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, id)))
)[0];
const candidate = sourceRunId ? await loadRun(sourceRunId) : null;
const candidate = requestedSourceRunId ? await loadRun(requestedSourceRunId) : null;
// An interaction producer is provenance. Explicit resume history must still
// belong to this task, and only task-scoped content can enter the envelope.
const sourceRun = object(candidate?.context).issueId === issueId ? candidate : null;
if ((sourceRunId && !candidate) || (resumeSourceRunId && !sourceRun))
// interruptedRunId is a best-effort hint written when a run is interrupted.
// After a cross-issue reassign it can name another task's run or a deleted
// row. Unlike an explicit user resume or a retry chain, a hint that does
// not resolve to this task must not fail the whole wake: degrade to "no
// resume source" and continue.
const staleInterruptedSource =
interruptedSource !== null
&& resumeSourceRunId === interruptedSource
&& explicitUserSource === null
&& string(input.context.retryOfRunId) === null
&& string(input.context.previousRunId) === null
&& sourceRun === null;
// A degraded hint falls back to the interaction producer so interaction
// wakes keep their source attribution.
const sourceRunId = staleInterruptedSource ? (producerRunId ?? null) : requestedSourceRunId;
if (
!staleInterruptedSource
&& ((requestedSourceRunId && !candidate) || (resumeSourceRunId && !sourceRun))
)
throw new Error(explicitUserSource ? "continuation_user_authorization_missing" : "continuation_source_context_missing");
const producer = producerRunId === sourceRunId ? candidate
const producer = producerRunId === requestedSourceRunId ? candidate
: producerRunId ? await loadRun(producerRunId) : null;
if (producerRunId && !producer) throw new Error("continuation_source_context_missing");
const producerIssueId = string(object(producer?.context).issueId);
@@ -431,7 +450,7 @@ export async function buildExecutionContinuation(input: {
if (!predecessor || !authorization || explicitUserSource !== sourceRunId)
throw new Error("continuation_user_authorization_missing");
}
const interruptedRunId = explicitUserSource ?? string(input.context.interruptedRunId) ?? (lastTerminal && lastTerminal.status !== "succeeded" &&
const interruptedRunId = explicitUserSource ?? (staleInterruptedSource ? undefined : interruptedSource) ?? (lastTerminal && lastTerminal.status !== "succeeded" &&
(hasConversationContinuationPolicy(lastTerminal.result) ||
lastTerminal.status === "interrupted" || lastTerminal.errorCode === "process_lost")
? lastTerminal.id : undefined);
@@ -0,0 +1,39 @@
import { randomUUID } from "node:crypto";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { agents, companies, createDb, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations } from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js";
import { executionProjectionsForRuns } from "./execution-projection.js";
const support = await getEmbeddedPostgresTestSupport();
describe.skipIf(!support.supported)("persisted stopped-workspace projection", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("stopped-workspace-projection");
db = createDb(database.connectionString);
}, 60_000);
afterAll(async () => { await db?.$client.end(); await database?.cleanup(); });
it("reads recovered files on a cancelled run through the real batched query", async () => {
const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Stopped workspace", issuePrefix: "SWP" });
await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer", adapterType: "paperclip_runner" });
await db.insert(issues).values({ id: issueId, companyId, title: "Review current changes", assigneeAgentId: agentId });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: issueId,
runtimeMode: "native", status: "cancelled", finishedAt: new Date(),
contextSnapshot: { issueId }, resultJson: { workspaceRestoreFailure: "restore_failed" } });
await db.insert(nativeRunFinalizations).values({ companyId, issueId, runId, phase: "observed" });
await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: issueId, kind: "active_run_watchdog",
cause: "native_continuation_requires_reconciliation", fingerprint: `native-workspace:${runId}`,
ownerType: "system", status: "resolved", outcome: "blocked", resolvedAt: new Date(),
nextAction: "The original sandbox is retained for workspace repair.",
evidence: { runId, continuationDelivery: "invalidated",
automaticRecovery: { replay: "blocked", actionOutcome: "unknown", policy: "preserve_without_replay_v1" },
workspaceRecovery: { schema: "paperclip.workspace-recovery.v1", runId, status: "recovered",
stage: "saving_receipts", attempt: 1, attemptLimit: 6, retryable: true, requestIds: [] },
} });
const projections = await executionProjectionsForRuns(db, companyId, [runId]);
expect(projections.get(runId)).toMatchObject({ phase: "recovery_needed", label: "Stopped",
nextAction: "Saved work recovered. Send a message to continue.", permittedActions: ["inspect_run"] });
});
});
@@ -37,6 +37,39 @@ const project = (
) => projectExecution(r, c, pending, undefined, now);
describe("execution truth projection", () => {
it.each(["queued", "recovering", "blocked", "recovered"] as const)("shows the exact saved workspace recovery state instead of stale repair instructions: %s", status => {
const sourceRunId = "ec036e06-90a3-4b69-81db-a8eab7dbfbac";
const source = run({ id: sourceRunId, status: "failed", errorCode: "native_continuation_requires_reconciliation" });
const action = {
status: "resolved" as const,
cause: "native_continuation_requires_reconciliation",
nextAction: "The original sandbox is retained for workspace repair.",
evidence: {
runId: sourceRunId,
automaticRecovery: { policy: "preserve_without_replay_v1", actionOutcome: "unknown", replay: "blocked" },
continuationDelivery: "invalidated",
workspaceRecovery: {
schema: "paperclip.workspace-recovery.v1", runId: sourceRunId, status,
stage: "saving_receipts", attempt: 1, requestIds: [],
...(status === "blocked" ? { message: "The saved source cannot be read safely." } : {}),
},
},
};
const projected = projectExecution(source, coordinator({ phase: "terminal_failure" }), [], action, now);
expect(projected).toMatchObject({
phase: "recovery_needed", label: "Stopped", cause: action.cause,
nextAction: status === "recovered" ? "Saved work recovered. Send a message to continue."
: status === "blocked" ? "The saved source cannot be read safely." : "Recovering saved work…",
permittedActions: ["inspect_run"], successorRunId: null,
});
expect(source.status).toBe("failed");
expect(action.evidence.automaticRecovery.replay).toBe("blocked");
expect(projectExecution(source, undefined, [], { ...action,
evidence: { ...action.evidence, workspaceRecovery: { ...action.evidence.workspaceRecovery,
runId: "5f227d75-b314-4511-bf23-9c615277e69b" } },
}, now).nextAction).toBe(action.nextAction);
});
it("keeps cleanup quarantine visible without a coordinator or recovery row", () => {
const stopped = run({ id: "stopped", status: "failed", errorCode: "native_session_cleanup_quarantined" });
expect(projectExecution(stopped, undefined, [], undefined, now)).toMatchObject({
+3 -1
View File
@@ -14,6 +14,7 @@ import type { ExecutionProjection } from "@paperclipai/shared";
import { EXECUTION_CONTROL_DEADLINE_MS } from "./execution-control-deadline.js";
import { executionFailureRetryCount } from "./execution-recovery-attempt.js";
import { retryIdempotentDatabaseOperation } from "../database-retry.js";
import { workspaceRecoveryDisplay } from "./workspace-recovery-receipt.js";
const text = (v: unknown) => (typeof v === "string" ? v : null);
const executionRunColumns = {
id: heartbeatRuns.id,
@@ -245,7 +246,8 @@ export function projectExecution(
Object.assign(projection, { phase, label });
if (recoveryAction?.status === "resolved" && recoveryAction.evidence?.automaticRecovery) {
projection.cause = recoveryAction.cause;
projection.nextAction = recoveryAction.nextAction;
projection.nextAction = workspaceRecoveryDisplay(recoveryAction.evidence, run.id)?.message
?? recoveryAction.nextAction;
const continuation = recoveryAction.evidence.explicitUserContinuation as
{ previousRunId?: unknown; runId?: unknown } | undefined;
const explicitSuccessor = text(continuation?.runId);
@@ -7,7 +7,7 @@ import { claimedAdapterType, conversationRecoveryActionPredicate, getConversatio
import { persistActivity } from "./activity-log.js";
import { appendHeartbeatRunEvent } from "./heartbeat-run-events.js";
import { logger } from "../middleware/logger.js";
import { and, eq, inArray, isNull, not, or, sql } from "drizzle-orm";
import { and, eq, exists, inArray, isNull, not, or, sql } from "drizzle-orm";
import {
chatActions,
environmentLeases,
@@ -28,6 +28,7 @@ import { isSupersededConversationRun } from "./agent-conversations.js";
import { hasRequiredWorkspaceRecovery } from "./workspace-restore-recovery-state.js";
import { hasRemoteTerminationReceipt } from "./remote-execution-termination.js";
import { readSystemRecovery } from "./system-recovery-state.js";
import { alias } from "drizzle-orm/pg-core";
/** An operator records observed outcomes; this is not permission to blindly retry. */
export async function validateExecutionReconciliation(input: {
@@ -344,6 +345,24 @@ export async function deliverReconciledExecutions(
}
}
const supersedingWorkspaceHold = alias(issueRecoveryActions, "superseding_workspace_hold");
function supersedingNativeWorkspaceHold(db: Db, input: {
companyId: string | typeof heartbeatRuns.companyId;
issueId: string | typeof issueRecoveryActions.sourceIssueId;
runId: string | typeof heartbeatRuns.id;
}) {
return db.select({ id: supersedingWorkspaceHold.id }).from(supersedingWorkspaceHold).where(and(
eq(supersedingWorkspaceHold.companyId, input.companyId),
eq(supersedingWorkspaceHold.sourceIssueId, input.issueId),
eq(supersedingWorkspaceHold.status, "resolved"),
eq(supersedingWorkspaceHold.cause, "native_continuation_requires_reconciliation"),
sql`${supersedingWorkspaceHold.evidence}->>'runId' = ${input.runId}::text`,
sql`${supersedingWorkspaceHold.evidence}->'automaticRecovery'->>'replay' = 'blocked'`,
sql`${supersedingWorkspaceHold.evidence}->'workspaceRestoreRecovery'->>'schema' = 'paperclip.workspace-restore-recovery.v1'`,
));
}
export function unresolvedExecutionDispositions(db: Db, limit: number) {
return db
.select({ action: issueRecoveryActions })
@@ -372,9 +391,14 @@ export function unresolvedExecutionDispositions(db: Db, limit: number) {
sql`not (${issueRecoveryActions.evidence} ? 'systemRecovery')`,
inArray(issueRecoveryActions.status, ["active", "escalated"]),
eq(issueRecoveryActions.kind, "active_run_watchdog"),
inArray(issueRecoveryActions.cause, [
...EXECUTION_RECONCILIATION_CAUSES,
]),
or(inArray(issueRecoveryActions.cause, [...EXECUTION_RECONCILIATION_CAUSES]), and(
eq(heartbeatRuns.runtimeMode, "native"), eq(heartbeatRuns.nativePhase, "terminal_failure"),
eq(nativeRunFinalizations.phase, "terminal_failure"), isNull(nativeRunFinalizations.nextAttemptAt),
sql`${issueRecoveryActions.wakePolicy}->>'kind' = 'resume_native_run'`,
sql`${issueRecoveryActions.wakePolicy}->>'runId' = ${heartbeatRuns.id}::text`,
exists(supersedingNativeWorkspaceHold(db, { companyId: heartbeatRuns.companyId,
issueId: issueRecoveryActions.sourceIssueId, runId: heartbeatRuns.id })),
)),
inArray(heartbeatRuns.status, [
"failed",
"timed_out",
@@ -502,9 +526,6 @@ export async function settleUnrecoverableExecutions(
!run ||
!action ||
action.evidence.runId !== runId ||
!EXECUTION_RECONCILIATION_CAUSES.includes(
action.cause as (typeof EXECUTION_RECONCILIATION_CAUSES)[number],
) ||
!["active", "escalated"].includes(action.status) ||
(run.nativeIssueId ?? run.contextSnapshot?.issueId) !== task.id ||
!["failed", "timed_out", "interrupted", "cancelled"].includes(
@@ -512,6 +533,29 @@ export async function settleUnrecoverableExecutions(
)
)
return;
if (!EXECUTION_RECONCILIATION_CAUSES.includes(action.cause as (typeof EXECUTION_RECONCILIATION_CAUSES)[number])) {
if (run.runtimeMode !== "native" || run.nativePhase !== "terminal_failure"
|| coordinator?.phase !== "terminal_failure" || coordinator.leaseOwner || coordinator.resultId
|| coordinator.nextAttemptAt || coordinator.failureDetail?.successorRunId
|| action.wakePolicy?.kind !== "resume_native_run" || action.wakePolicy.runId !== run.id) return;
const [hold] = await supersedingNativeWorkspaceHold(tx as unknown as Db, {
companyId: run.companyId, issueId: task.id, runId: run.id,
}).limit(1).for("update");
if (!hold) return;
await notifyExecutionRunWork(tx);
const note = "Exact session recovery stopped. The recorded workspace recovery holds this execution without replaying its actions.";
await tx.update(issueRecoveryActions).set({ status: "cancelled", outcome: "cancelled",
resolvedAt: now, updatedAt: now, wakePolicy: null, monitorPolicy: null,
nextAction: note, resolutionNote: note,
evidence: { ...action.evidence, supersedingRecoveryActionId: hold.id },
}).where(eq(issueRecoveryActions.id, action.id));
await persistActivity(tx as unknown as Db, { companyId: run.companyId, actorType: "system",
actorId: "execution-recovery", action: "issue.execution_recovery_settled", entityType: "issue",
entityId: task.id, runId: run.id,
details: { recoveryActionId: action.id, outcome: "cancelled", supersedingRecoveryActionId: hold.id },
});
return;
}
// Adoption transfers maintenance to the retained-workspace owner.
// This compatibility resolver must not close its hold or relabel it
// as a user repair merely because old return-owner metadata is absent.
@@ -57,6 +57,67 @@ const support = await getEmbeddedPostgresTestSupport();
actorType: "user", actorId: "board", reason: "issue_commented" };
}
type Fixture = Awaited<ReturnType<typeof seed>>;
it.each(["new", "saved"])("delivers a reassignment's saved user question once after the native run stopped (%s)", async origin => {
const f = await seed();
await db.update(issues).set({ status: "in_review" }).where(eq(issues.id, f.issueId));
const [source] = await db.update(heartbeatRuns).set({ status: "cancelled", errorCode: "issue_reassigned",
processPid: null, processGroupId: null,
}).where(eq(heartbeatRuns.id, f.sourceRunId)).returning();
await db.update(issueRecoveryActions).set({ cause: "native_continuation_requires_reconciliation" })
.where(eq(issueRecoveryActions.sourceIssueId, f.issueId));
const lease = { id: randomUUID(), companyId: f.companyId, heartbeatRunId: source.id,
provider: "daytona", providerLeaseId: "reviewed-task-sandbox" };
await db.insert(environmentLeases).values({ ...lease, status: "expired", leasePolicy: "ephemeral",
releasedAt: new Date(), cleanupStatus: "success", metadata: {
remoteExecutionTermination: remoteTerminationReceipt(lease, { providerLeaseId: lease.providerLeaseId, state: "destroyed" }),
},
});
await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running" });
const heartbeat = heartbeatService(db);
if (origin === "new") {
await heartbeat.wakeup(f.agentId, { source: "assignment", triggerDetail: "system", reason: "issue_assigned",
requestedByActorType: "user", requestedByActorId: f.actorId,
payload: { issueId: f.issueId, commentId: f.commentId, mutation: "update" },
contextSnapshot: { source: "issue.update", issueId: f.issueId, wakeCommentId: f.commentId },
});
} else {
await db.insert(agentWakeupRequests).values({ companyId: f.companyId, agentId: f.agentId,
source: "assignment", triggerDetail: "system", reason: "issue_assigned", status: "deferred_issue_execution",
requestedByActorType: "user", requestedByActorId: f.actorId, payload: {
issueId: f.issueId, commentId: f.commentId, executionWait: { reason: "execution_recovery" },
_paperclipWakeContext: { source: "issue.update", issueId: f.issueId, wakeReason: "issue_assigned",
wakeCommentId: f.commentId, wakeCommentIds: [f.commentId] },
},
});
}
const [receipt] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId));
if (receipt.status === "deferred_issue_execution") {
await db.update(agentWakeupRequests).set({ updatedAt: new Date(0) }).where(eq(agentWakeupRequests.id, receipt.id));
await Promise.all([heartbeat.resumeExecutionWaitComments(), heartbeat.resumeExecutionWaitComments()]);
}
const [delivered] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, receipt.id));
expect(delivered).toMatchObject({ status: origin === "new" ? "queued" : "coalesced", runId: expect.any(String) });
const successors = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId),
eq(heartbeatRuns.status, "queued")));
expect(successors).toHaveLength(1);
expect(delivered.runId).toBe(successors[0].id);
expect(successors[0]).toMatchObject({ agentId: f.agentId, contextSnapshot: {
forceFreshSession: true, previousRunId: source.id, wakeCommentIds: [f.commentId],
} });
await heartbeat.resumeRemoteStopComments(source);
expect(await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId),
eq(heartbeatRuns.status, "queued")))).toHaveLength(1);
expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toBeNull();
const [original] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, source.id));
expect(original).toMatchObject({ status: "cancelled", errorCode: "issue_reassigned" });
});
it("keeps a bare human assignment behind the execution hold", async () => {
const f = await seed();
expect(await admitExplicitNativeContinuation({ ...f, db, reason: "issue_assigned", commentId: null })).toBeNull();
expect(await getExecutionBlocker(db, f.companyId, f.issueId)).not.toBeNull();
expect(await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId),
eq(heartbeatRuns.status, "queued")))).toHaveLength(0);
});
it("automatically admits a saved historical local message once after isolated fallback becomes eligible", async () => {
const f = await seed();
const processStartedAt = new Date();
@@ -1451,7 +1512,9 @@ const support = await getEmbeddedPostgresTestSupport();
{ runtime: "native", retry: false }, { runtime: "native", retry: true },
{ runtime: "legacy", retry: false }, { runtime: "legacy", retry: true },
{ runtime: "legacy_startup", retry: false }, { runtime: "legacy_startup", retry: true },
])("resumes a user message after confirmed cleanup: %j", async ({ runtime, retry }) => {
{ runtime: "native", retry: false, reason: "issue_assigned" },
{ runtime: "legacy", retry: false, reason: "issue_assigned" },
])("resumes a user message after confirmed cleanup: %j", async ({ runtime, retry, reason = "issue_commented" }) => {
const f = await seed();
if (runtime.startsWith("legacy")) {
await db.update(agents).set({ adapterType: "claude_local" }).where(eq(agents.id, f.agentId));
@@ -1474,7 +1537,7 @@ const support = await getEmbeddedPostgresTestSupport();
const heartbeat = heartbeatService(db, retry ? { environmentRuntime: {
retryPendingSandboxTeardown: async () => ({ providerLeaseId: identity.providerLeaseId, state: "destroyed" }),
} as unknown as HeartbeatEnvironmentRuntime } : {});
await heartbeat.wakeup(f.agentId, { source: "automation", triggerDetail: "system", reason: "issue_commented",
await heartbeat.wakeup(f.agentId, { source: "automation", triggerDetail: "system", reason,
requestedByActorType: "user", requestedByActorId: "board", payload: { issueId: f.issueId, commentId: f.commentId },
contextSnapshot: { issueId: f.issueId, wakeCommentId: f.commentId } });
const [source] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.sourceRunId));
@@ -1897,8 +1960,11 @@ const support = await getEmbeddedPostgresTestSupport();
expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toBeNull();
} else expect(await getExecutionBlocker(db, f.companyId, f.issueId)).not.toBeNull();
});
it.each(["live_process", "missing_process", "lease", "coordinator", "successor", "agent_message", "old_comment", "wrong_author", "run_authored", "reassigned", "automatic", "approval", "question", "malformed_comment", "legacy_owner"])("keeps the hold for %s", async kind => {
it.each(["issue_commented", "issue_assigned"].flatMap(reason =>
["live_process", "missing_process", "lease", "coordinator", "successor", "agent_message", "system_message", "old_comment", "wrong_author", "run_authored", "reassigned", "automatic", "mention", "approval", "question", "malformed_comment", "missing_comment", "foreign_comment", "legacy_owner"].map(kind => ({ reason, kind })),
))("keeps the hold for $kind ($reason)", async ({ reason, kind }) => {
const f = await seed();
f.reason = reason;
if (kind === "legacy_owner") await db.insert(heartbeatRuns).values({ companyId: f.companyId,
agentId: f.agentId, status: "failed", runtimeMode: "legacy", processPid: process.pid,
contextSnapshot: { issueId: f.issueId }, resultJson: { conversationContinuation: "continue_conversation_v1" } });
@@ -1920,8 +1986,12 @@ const support = await getEmbeddedPostgresTestSupport();
await db.insert(issueApprovals).values({ companyId: f.companyId, issueId: f.issueId, approvalId });
}
if (kind === "malformed_comment") f.commentId = "not-a-uuid";
if (kind === "missing_comment") f.commentId = randomUUID();
if (kind === "foreign_comment") f.commentId = (await seed()).commentId;
if (kind === "agent_message") f.actorType = "agent";
if (kind === "system_message") f.actorType = "system";
if (kind === "automatic") f.reason = "issue_continuation_needed";
if (kind === "mention") f.reason = "issue_comment_mentioned";
if (kind === "wrong_author") f.actorId = "someone-else";
if (kind === "run_authored") await db.update(issueComments).set({ createdByRunId: f.sourceRunId }).where(eq(issueComments.id, f.commentId));
if (kind === "old_comment") await db.update(issueComments).set({ createdAt: new Date("2026-09-11T09:00:00Z") }).where(eq(issueComments.id, f.commentId));
@@ -31,6 +31,10 @@ import { queuedCommentIdsFromWakePayload } from "./issue-queued-comment-queue.js
type Run = typeof heartbeatRuns.$inferSelect;
const terminal = ["failed", "interrupted", "timed_out", "cancelled"];
export function isUserCommentContinuationReason(reason: string | null | undefined): boolean {
return reason === "issue_commented" || reason === "issue_reopened_via_comment" || reason === "issue_assigned";
}
function processStopped(pid: number): boolean {
try { process.kill(pid, 0); return false; }
catch (error) { return (error as NodeJS.ErrnoException).code === "ESRCH"; }
@@ -96,7 +100,7 @@ export async function admitExplicitNativeContinuation(input: {
const retry = input.reason === "retry_failed_run" &&
z.string().guid().safeParse(input.failedRunId).success;
if (!retry && !input.taskRetryRequestId && !input.queuedCommentInterruptId && (!commentId || !z.string().guid().safeParse(commentId).success ||
!["issue_commented", "issue_reopened_via_comment"].includes(input.reason ?? ""))) return null;
!isUserCommentContinuationReason(input.reason))) return null;
const [task] = await db.select().from(issues).where(and(
eq(issues.companyId, companyId), eq(issues.id, issueId),
));
+2 -2
View File
@@ -72,7 +72,7 @@ export type ExternalObjectResolveResult =
| { ok: true; snapshot: ExternalObjectResolverSnapshot }
| {
ok: false;
liveness: Extract<ExternalObjectLivenessState, "auth_required" | "unreachable">;
liveness: Extract<ExternalObjectLivenessState, "auth_required" | "rate_limited" | "unreachable">;
errorCode: string;
errorMessage?: string | null;
retryAfterSeconds?: number;
@@ -676,7 +676,7 @@ export function externalObjectService(
byLiveness[object.liveness] = (byLiveness[object.liveness] ?? 0) + 1;
const livenessTone = object.liveness === "auth_required" || object.liveness === "unreachable"
? "danger"
: object.liveness === "stale"
: object.liveness === "rate_limited" || object.liveness === "stale"
? "warning"
: object.statusTone;
if (severityRank[livenessTone] > severityRank[highestSeverity]) highestSeverity = livenessTone;
+52
View File
@@ -200,6 +200,54 @@ type GitCredentialSecretsDeps = {
resolveUserSecretValue?: SecretServiceLike["resolveUserSecretValue"];
};
export type GitHubApiCredentialSource = "company_secret" | "server_env";
export type GitHubApiCredential = {
token: string;
source: GitHubApiCredentialSource;
/** The company-secret name the token came from; null for a server-environment token. */
secretName: string | null;
};
/**
* Resolve a GitHub API credential for company-scoped, non-run work (for example the
* external-object refresh sweep, which has no agent or responsible-user context).
*
* This is the background-safe subset of the git credential order: it reads a company
* secret by well-known name, then the server process environment (`GITHUB_TOKEN`/`GH_TOKEN`)
* that self-hosted operators already set for Git. It deliberately cannot resolve a managed
* GitHub connection, because every managed grant is scoped to one agent or one person and a
* background sweep has neither. Callers that have a run context must use
* `createGitRemoteAuthProvider`/`resolveManagedGitHubCredential` instead so the managed
* identity and its consent boundary are honored.
*
* The `source` matters to callers that show company data. A server-environment token is
* instance-wide, so it can see repositories the company cannot. A caller must treat a
* `server_env` token differently from a `company_secret` token and keep it away from
* private repositories. Without any credential a caller runs anonymous, and anonymous
* GitHub requests are capped at 60/hour, so a busy company is rate-limited into
* misleading failures.
*/
export async function resolveGitHubApiCredential(
db: Db,
companyId: string,
opts: { secretNames?: readonly string[]; env?: NodeJS.ProcessEnv; secrets?: GitCredentialSecretsDeps } = {},
): Promise<GitHubApiCredential | null> {
const secrets = opts.secrets ?? secretService(db);
for (const secretName of opts.secretNames ?? DEFAULT_GITHUB_TOKEN_SECRET_NAMES) {
const secret = await Promise.resolve(secrets.getByName(companyId, secretName)).catch(() => null);
if (!secret) continue;
const token = await secrets
.resolveSecretValue(companyId, secret.id, "latest")
.then((value) => value.trim())
.catch(() => "");
if (token) return { token, source: "company_secret", secretName };
}
const env = opts.env ?? process.env;
const envToken = env.GITHUB_TOKEN?.trim() || env.GH_TOKEN?.trim() || "";
return envToken ? { token: envToken, source: "server_env", secretName: null } : null;
}
/**
* Build the credential provider for one run. Resolution order: the managed GitHub identity
* resolver, then a company secret by well-known name, then the server process environment
@@ -315,6 +363,7 @@ export async function resolveManagedGitHubIdentitySelection(
agentId?: string | null;
allowStandingDelegation?: boolean;
excludeGrantId?: string;
explicitGrantId?: string;
},
): Promise<{
configured: boolean;
@@ -357,6 +406,7 @@ export async function resolveManagedGitHubIdentitySelection(
const grants = await db.select().from(connectionGrants).where(and(
eq(connectionGrants.companyId, companyId),
inArray(connectionGrants.connectionId, [...eligibleConnectionIds]),
context.explicitGrantId ? eq(connectionGrants.id, context.explicitGrantId) : undefined,
or(eq(connectionGrants.kind, "agent"), eq(connectionGrants.kind, "user")),
));
const dedicated = context.agentId
@@ -489,6 +539,7 @@ export async function resolveManagedGitHubCredential(
responsibleUserId?: string | null;
agentId?: string | null;
allowStandingDelegation?: boolean;
explicitGrantId?: string;
},
): Promise<{ configured: boolean; identitySource?: "personal" | "dedicated"; credential?: GitCredential; error?: string }> {
const selection = await resolveManagedGitHubIdentitySelection(db, companyId, context);
@@ -583,6 +634,7 @@ export async function resolveManagedGitHubCredential(
} catch {
failure = { configured: true, identitySource: selection.identitySource, error: "GitHub credentials are temporarily unavailable" };
}
if (context.explicitGrantId) return failure;
// Retry credential acquisition, never the GitHub operation. An alternate
// authorization must still belong to this exact principal and account.
const alternate = await resolveManagedGitHubIdentitySelection(db, companyId, {
+51 -15
View File
@@ -1,7 +1,10 @@
import type { Db } from "@paperclipai/db";
import { DEFAULT_GITHUB_TOKEN_SECRET_NAMES } from "./git-credentials.js";
import {
DEFAULT_GITHUB_TOKEN_SECRET_NAMES,
resolveGitHubApiCredential,
type GitHubApiCredential,
} from "./git-credentials.js";
import { ghFetch, gitHubApiBase } from "./github-fetch.js";
import { secretService } from "./secrets.js";
type FetchLike = (url: string, init?: RequestInit) => Promise<Response>;
@@ -26,6 +29,7 @@ export type GitHubCommitDiffDetailsResolver = (
export interface GitHubCommitDetailsResolverOptions {
fetch?: FetchLike;
tokenProvider?: (companyId: string) => Promise<string | null> | string | null;
credentialProvider?: (companyId: string) => Promise<GitHubApiCredential | null> | GitHubApiCredential | null;
secretNames?: readonly string[];
}
@@ -42,6 +46,12 @@ function record(value: unknown): Record<string, unknown> | null {
: null;
}
function normalizeCredential(credential: GitHubApiCredential | null | undefined): GitHubApiCredential | null {
const token = credential?.token?.trim();
if (!token) return null;
return { token, source: credential!.source, secretName: credential!.secretName ?? null };
}
export function extractGitHubCommitReference(values: readonly unknown[]): GitHubCommitReference | null {
for (const value of values) {
if (typeof value !== "string" || value.length === 0) continue;
@@ -57,16 +67,27 @@ export function extractGitHubCommitReference(values: readonly unknown[]): GitHub
return null;
}
async function defaultTokenProvider(db: Db, companyId: string, secretNames: readonly string[]) {
const secrets = secretService(db);
for (const secretName of secretNames) {
const secret = await secrets.getByName(companyId, secretName);
if (!secret) continue;
const token = await secrets.resolveSecretValue(companyId, secret.id, "latest");
const trimmed = token.trim();
if (trimmed) return trimmed;
async function defaultCredentialProvider(db: Db, companyId: string, secretNames: readonly string[]) {
return resolveGitHubApiCredential(db, companyId, { secretNames });
}
/** Return the repo's `private` flag, or null when the probe does not answer. */
async function probeRepoIsPrivate(
reference: GitHubCommitReference,
headers: Record<string, string>,
fetchImpl: FetchLike,
): Promise<boolean | null> {
try {
const response = await fetchImpl(
`${gitHubApiBase(reference.host)}/repos/${encodeURIComponent(reference.owner)}/${encodeURIComponent(reference.repo)}`,
{ headers },
);
if (!response.ok) return null;
const body = record(await response.json());
return typeof body?.private === "boolean" ? body.private : null;
} catch {
return null;
}
return null;
}
function hasNextPage(response: Response): boolean {
@@ -85,13 +106,21 @@ export function createGitHubCommitDiffDetailsResolver(
): GitHubCommitDiffDetailsResolver {
const fetchImpl = opts.fetch ?? ghFetch;
const secretNames = opts.secretNames ?? DEFAULT_GITHUB_TOKEN_SECRET_NAMES;
const tokenProvider = Object.prototype.hasOwnProperty.call(opts, "tokenProvider") && opts.tokenProvider !== undefined
? opts.tokenProvider
: ((companyId: string) => defaultTokenProvider(db, companyId, secretNames));
const credentialProvider: (companyId: string) => Promise<GitHubApiCredential | null> =
opts.credentialProvider
? async (companyId: string) => normalizeCredential(await opts.credentialProvider!(companyId))
: Object.prototype.hasOwnProperty.call(opts, "tokenProvider") && opts.tokenProvider !== undefined
? async (companyId: string) => {
const raw = typeof opts.tokenProvider === "function" ? await opts.tokenProvider(companyId) : opts.tokenProvider;
const token = raw?.trim();
return token ? { token, source: "company_secret", secretName: null } : null;
}
: (companyId: string) => defaultCredentialProvider(db, companyId, secretNames);
return async (companyId, reference) => {
try {
const token = (typeof tokenProvider === "function" ? await tokenProvider(companyId) : tokenProvider)?.trim() || null;
const credential = await credentialProvider(companyId);
const token = credential?.token?.trim() || null;
const headers: Record<string, string> = {
accept: "application/vnd.github+json",
"user-agent": "paperclip-work-product-resolver",
@@ -99,6 +128,13 @@ export function createGitHubCommitDiffDetailsResolver(
};
if (token) headers.authorization = `Bearer ${token}`;
// A server-environment token is instance-wide. Do not use it to read a private
// repository on behalf of one company; only a company-scoped credential may.
if (credential?.source === "server_env") {
const isPrivate = await probeRepoIsPrivate(reference, headers, fetchImpl);
if (isPrivate !== false) return null;
}
const commitUrl = `${gitHubApiBase(reference.host)}/repos/${encodeURIComponent(reference.owner)}/${encodeURIComponent(reference.repo)}/commits/${encodeURIComponent(reference.sha)}`;
let additions: number | null = null;
let deletions: number | null = null;
@@ -1,9 +1,8 @@
import { createHash } from "node:crypto";
import type { Db } from "@paperclipai/db";
import type { ExternalObjectCanonicalUrl } from "@paperclipai/shared";
import { DEFAULT_GITHUB_TOKEN_SECRET_NAMES } from "./git-credentials.js";
import { DEFAULT_GITHUB_TOKEN_SECRET_NAMES, resolveGitHubApiCredential, type GitHubApiCredential } from "./git-credentials.js";
import { ghFetch, gitHubApiBase } from "./github-fetch.js";
import { secretService } from "./secrets.js";
import type {
ExternalObjectDetection,
ExternalObjectDetector,
@@ -17,6 +16,11 @@ type FetchLike = (url: string, init?: RequestInit) => Promise<Response>;
export interface GitHubExternalObjectProviderOptions {
fetch?: FetchLike;
tokenProvider?: (companyId: string) => Promise<string | null> | string | null;
/**
* Resolve the credential and its source. Prefer this over `tokenProvider` when the
* caller must treat a server-environment token differently from a company credential.
*/
credentialProvider?: (companyId: string) => Promise<GitHubApiCredential | null> | GitHubApiCredential | null;
secretNames?: readonly string[];
}
@@ -57,6 +61,12 @@ function asNestedString(record: Record<string, unknown>, key: string, nestedKey:
return nested ? asString(nested[nestedKey]) : null;
}
function normalizeCredential(credential: GitHubApiCredential | null | undefined): GitHubApiCredential | null {
const token = credential?.token?.trim();
if (!token) return null;
return { token, source: credential!.source, secretName: credential!.secretName ?? null };
}
function parseGitHubCanonicalUrl(canonical: ExternalObjectCanonicalUrl): GitHubObjectIdentity | null {
if (canonical.canonicalIdentity.scheme !== "https") return null;
const host = canonical.canonicalIdentity.host.toLowerCase();
@@ -126,7 +136,19 @@ function retryAfterSeconds(response: Response) {
return 300;
}
function failureFromGitHubResponse(response: Response): ExternalObjectResolveResult | null {
function rateLimitedResult(authenticated: boolean, retryAfterSeconds: number): ExternalObjectResolveResult {
return {
ok: false,
liveness: "rate_limited",
errorCode: "github_rate_limited",
errorMessage: authenticated
? "GitHub rate limit reached while refreshing this object. It will retry after the limit resets."
: "GitHub rate limit reached while refreshing this object because no GitHub credential is configured, so requests are anonymous. Add a GitHub token to raise the limit.",
retryAfterSeconds,
};
}
function failureFromGitHubResponse(response: Response, authenticated: boolean): ExternalObjectResolveResult | null {
if (response.status === 401) {
return {
ok: false,
@@ -140,13 +162,7 @@ function failureFromGitHubResponse(response: Response): ExternalObjectResolveRes
if (response.status === 403) {
const rateLimitRemaining = response.headers.get("x-ratelimit-remaining");
if (rateLimitRemaining === "0") {
return {
ok: false,
liveness: "unreachable",
errorCode: "github_rate_limited",
errorMessage: "GitHub rate limit reached while refreshing this object.",
retryAfterSeconds: retryAfterSeconds(response),
};
return rateLimitedResult(authenticated, retryAfterSeconds(response));
}
return {
ok: false,
@@ -157,11 +173,15 @@ function failureFromGitHubResponse(response: Response): ExternalObjectResolveRes
};
}
if (response.status === 429 || response.status >= 500) {
if (response.status === 429) {
return rateLimitedResult(authenticated, retryAfterSeconds(response));
}
if (response.status >= 500) {
return {
ok: false,
liveness: "unreachable",
errorCode: response.status === 429 ? "github_rate_limited" : "github_unreachable",
errorCode: "github_unreachable",
errorMessage: `GitHub returned HTTP ${response.status} while refreshing this object.`,
retryAfterSeconds: retryAfterSeconds(response),
};
@@ -200,40 +220,53 @@ function notFoundSnapshot(identity: GitHubObjectIdentity, etag: string | null):
}
/**
* Probe `/repos/{owner}/{repo}` to classify a 404 on a pull request or issue.
* Probe `/repos/{owner}/{repo}` to classify a 404 on a pull request or issue, and to
* learn whether the repository is private.
*
* GitHub returns 404 both when the object does not exist and when the repository
* exists but the credentials cannot see it (private repos are deliberately hidden
* behind 404). This probes the repo metadata with the same credentials to tell the
* two apart:
*
* - "visible": the repo returns 2xx — the referenced object really is gone.
* - "visible": the repo returns 2xx — the referenced object really is gone. The
* response also carries the repo's `private` flag.
* - "hidden": the repo returns 404/403 — the credentials lack access to the repo,
* so the object status cannot be determined and should not be frozen as "Not found".
* - "uncertain": the probe itself failed (network/rate limit) — retry later.
* - "rate_limited": the probe was rejected by a GitHub rate limit — retry later, with a
* distinct state so a quota problem is not reported as a network failure.
* - "uncertain": the probe itself failed (network/other) — retry later.
*/
type RepoProbeOutcome = {
visibility: "visible" | "hidden" | "rate_limited" | "uncertain";
isPrivate: boolean | null;
};
async function probeRepoVisibility(
identity: GitHubObjectIdentity,
opts: { fetch: FetchLike; headers?: Record<string, string> | undefined },
): Promise<"visible" | "hidden" | "uncertain"> {
): Promise<RepoProbeOutcome> {
try {
const probe = await opts.fetch(
`${gitHubApiBase(identity.host)}/repos/${encodeURIComponent(identity.owner)}/${encodeURIComponent(identity.repo)}`,
{ headers: opts.headers },
);
if (probe.ok) return "visible";
if (probe.status === 404) return "hidden";
if (probe.ok) {
const body = await safeJson(probe);
return { visibility: "visible", isPrivate: typeof body?.private === "boolean" ? body.private : null };
}
if (probe.status === 404) return { visibility: "hidden", isPrivate: null };
if (probe.status === 429) return { visibility: "rate_limited", isPrivate: null };
if (probe.status === 403) {
// GitHub can return 403 for both "credentials lack access" and "rate limit
// reached". A rate-limited probe cannot tell the two apart, so treat it as
// uncertain (retry later) instead of implying missing access.
// a rate limit (retry later) instead of implying missing access.
const rateLimitRemaining = probe.headers.get("x-ratelimit-remaining");
if (rateLimitRemaining === "0") return "uncertain";
return "hidden";
if (rateLimitRemaining === "0") return { visibility: "rate_limited", isPrivate: null };
return { visibility: "hidden", isPrivate: null };
}
return "uncertain";
return { visibility: "uncertain", isPrivate: null };
} catch {
return "uncertain";
return { visibility: "uncertain", isPrivate: null };
}
}
@@ -362,27 +395,25 @@ async function safeJson(response: Response) {
}
}
async function defaultTokenProvider(db: Db, companyId: string, secretNames: readonly string[]) {
const secrets = secretService(db);
for (const secretName of secretNames) {
const secret = await secrets.getByName(companyId, secretName);
if (!secret) continue;
const token = await secrets.resolveSecretValue(companyId, secret.id, "latest");
const trimmed = token.trim();
if (trimmed) return trimmed;
}
return null;
}
export function createGitHubExternalObjectProvider(
db: Db,
opts: GitHubExternalObjectProviderOptions = {},
): { detector: ExternalObjectDetector; resolvers: ExternalObjectResolver[] } {
const fetchImpl = opts.fetch ?? ghFetch;
const secretNames = opts.secretNames ?? DEFAULT_GITHUB_TOKEN_SECRET_NAMES;
const tokenProvider = Object.prototype.hasOwnProperty.call(opts, "tokenProvider") && opts.tokenProvider !== undefined
? opts.tokenProvider
: ((companyId: string) => defaultTokenProvider(db, companyId, secretNames));
// `credentialProvider` is the preferred seam; `tokenProvider` stays for callers that
// only care about the token string. A token from `tokenProvider` is treated as
// company-scoped, because the caller supplied it explicitly.
const credentialProvider: (companyId: string) => Promise<GitHubApiCredential | null> =
opts.credentialProvider
? async (companyId: string) => normalizeCredential(await opts.credentialProvider!(companyId))
: Object.prototype.hasOwnProperty.call(opts, "tokenProvider") && opts.tokenProvider !== undefined
? async (companyId: string) => {
const raw = typeof opts.tokenProvider === "function" ? await opts.tokenProvider(companyId) : opts.tokenProvider;
const token = raw?.trim();
return token ? { token, source: "company_secret", secretName: null } : null;
}
: (companyId: string) => resolveGitHubApiCredential(db, companyId, { secretNames });
// Cache repository-visibility probe results so many objects in the same repo
// share a single probe instead of each issuing its own request every refresh
// cycle. Only determined outcomes ("visible"/"hidden") are cached; uncertain
@@ -391,21 +422,21 @@ export function createGitHubExternalObjectProvider(
// reused after the company rotates its credentials — that would freeze a
// reference as "probe-verified not-found" using an out-of-date result.
const probeCache = new Map<string, { result: "visible" | "hidden"; expiresAt: number }>();
const probeCache = new Map<string, { outcome: RepoProbeOutcome; expiresAt: number }>();
async function cachedProbeRepoVisibility(
companyId: string,
identity: GitHubObjectIdentity,
headers: Record<string, string>,
): Promise<"visible" | "hidden" | "uncertain"> {
): Promise<RepoProbeOutcome> {
const credentialFingerprint = createHash("sha256").update(headers.authorization ?? "anonymous").digest("hex");
const key = `${companyId}\u0000${credentialFingerprint}\u0000${identity.owner.toLowerCase()}\u0000${identity.repo.toLowerCase()}`;
const cached = probeCache.get(key);
if (cached && cached.expiresAt > Date.now()) return cached.result;
const result = await probeRepoVisibility(identity, { fetch: fetchImpl, headers });
if (result !== "uncertain") {
probeCache.set(key, { result, expiresAt: Date.now() + GITHUB_OBJECT_TTL_SECONDS * 1000 });
if (cached && cached.expiresAt > Date.now()) return cached.outcome;
const outcome = await probeRepoVisibility(identity, { fetch: fetchImpl, headers });
if (outcome.visibility === "visible" || outcome.visibility === "hidden") {
probeCache.set(key, { outcome, expiresAt: Date.now() + GITHUB_OBJECT_TTL_SECONDS * 1000 });
}
return result;
return outcome;
}
const detector: ExternalObjectDetector = {
@@ -445,9 +476,9 @@ export function createGitHubExternalObjectProvider(
};
}
let token: string | null = null;
let credential: GitHubApiCredential | null = null;
try {
token = typeof tokenProvider === "function" ? await tokenProvider(companyId) : tokenProvider;
credential = await credentialProvider(companyId);
} catch {
return {
ok: false,
@@ -457,7 +488,12 @@ export function createGitHubExternalObjectProvider(
retryAfterSeconds: GITHUB_OBJECT_TTL_SECONDS,
};
}
token = token?.trim() || null;
const token = credential?.token?.trim() || null;
const authenticated = Boolean(token);
// A server-environment token is instance-wide, so it can see repositories this
// company cannot. Only a company-scoped credential may resolve a private
// repository for company display; a server token is limited to public repos.
const companyScoped = credential?.source !== "server_env";
const headers: Record<string, string> = {
accept: "application/vnd.github+json",
"user-agent": "paperclip-external-object-resolver",
@@ -465,6 +501,54 @@ export function createGitHubExternalObjectProvider(
};
if (token) headers.authorization = `Bearer ${token}`;
if (!companyScoped) {
// A server-environment token is instance-wide, so it can read repositories
// this company cannot. Before reading with it, verify that the repository is
// public RIGHT NOW. Never serve this authorization decision from the probe
// cache: a repository can become private inside the cache TTL, and a cached
// "public" verdict must not authorize a later read of its private contents.
// The cache is still used below to classify a 404, where a stale verdict can
// only make the object look deleted — it can never expose private data.
const probe = await probeRepoVisibility(identity, { fetch: fetchImpl, headers });
if (probe.visibility === "hidden") {
return {
ok: false,
liveness: "auth_required",
errorCode: "github_repo_not_accessible",
errorMessage: `GitHub returned not-found for ${identity.owner}/${identity.repo}. The repository may be private, deleted, or the configured GitHub credentials may lack access to it.`,
retryAfterSeconds: GITHUB_OBJECT_TTL_SECONDS,
};
}
if (probe.visibility === "rate_limited") {
return rateLimitedResult(authenticated, GITHUB_OBJECT_TTL_SECONDS);
}
if (probe.visibility === "uncertain") {
return {
ok: false,
liveness: "unreachable",
errorCode: "github_repo_probe_failed",
errorMessage: "GitHub could not verify this repository while checking this object.",
retryAfterSeconds: GITHUB_OBJECT_TTL_SECONDS,
};
}
// Require positive proof that the repository is public before reading
// with the instance-wide server token. A private verdict and a probe
// response that does not confirm public visibility both fail closed, so
// the server token can never fetch private details for a company that
// did not authorize it.
if (probe.isPrivate !== false) {
return {
ok: false,
liveness: "auth_required",
errorCode: "github_repo_requires_company_token",
errorMessage: probe.isPrivate === true
? `The ${identity.owner}/${identity.repo} repository is private. Add a GitHub token for this company to refresh this object.`
: `The ${identity.owner}/${identity.repo} repository visibility could not be confirmed as public. Add a GitHub token for this company to refresh this object.`,
retryAfterSeconds: GITHUB_OBJECT_TTL_SECONDS,
};
}
}
const apiKind = objectType === "pull_request" ? "pulls" : "issues";
const url = `${gitHubApiBase(identity.host)}/repos/${encodeURIComponent(identity.owner)}/${encodeURIComponent(identity.repo)}/${apiKind}/${identity.number}`;
@@ -489,11 +573,11 @@ export function createGitHubExternalObjectProvider(
// Probe the repository metadata to classify: if the repo itself is visible
// the object truly is gone; if it is not, surface credentials-needed
// instead of permanently freezing a reference as "Not found".
const repoVisibility = await cachedProbeRepoVisibility(companyId, identity, headers);
if (repoVisibility === "visible") {
const probe = await cachedProbeRepoVisibility(companyId, identity, headers);
if (probe.visibility === "visible") {
return { ok: true, snapshot: notFoundSnapshot(identity, etag) };
}
if (repoVisibility === "hidden") {
if (probe.visibility === "hidden") {
return {
ok: false,
liveness: "auth_required",
@@ -502,6 +586,9 @@ export function createGitHubExternalObjectProvider(
retryAfterSeconds: GITHUB_OBJECT_TTL_SECONDS,
};
}
if (probe.visibility === "rate_limited") {
return rateLimitedResult(authenticated, GITHUB_OBJECT_TTL_SECONDS);
}
return {
ok: false,
liveness: "unreachable",
@@ -511,7 +598,7 @@ export function createGitHubExternalObjectProvider(
};
}
const failure = failureFromGitHubResponse(response);
const failure = failureFromGitHubResponse(response, authenticated);
if (failure) return failure;
if (!response.ok) {
return {
+2 -1
View File
@@ -2322,7 +2322,7 @@ export function heartbeatService(
interactionId: readNonEmptyString(context.interactionId),
issueId,
messageIds:
run.retryOfRunId || context.retryOfRunId
(run.retryOfRunId || context.retryOfRunId) && !isFailedChatRunRetry
? []
: queuedCommentIdsFromRunContext(context).length
? queuedCommentIdsFromRunContext(context)
@@ -2713,6 +2713,7 @@ export function heartbeatService(
mergedConfig,
configSnapshot,
secretManifest,
managedAiCredentialIdentity: managedAiRuntime?.identity,
},
reuse: {
requestedShouldReuseExisting,
@@ -26,6 +26,7 @@ import { resolveAssignedConnectionInstructionsForRun } from "../native-runtime/a
import { recordFailedSkillPreparation, type NativeRunHistoricalSpan } from "../native-runtime/native-run-trace.js";
import { collectRunFailureSecretValues } from "../run-failure-diagnostics.js";
import { skillVersionSelectionMap } from "../runtime-skill-selections.js";
import { environmentSkillConfig } from "../environment-skills.js";
import type { selectHeartbeatEnvironment } from "./environment-selection.js";
import type { createHeartbeatRetries } from "./retries.js";
import type { createHeartbeatLifecycle } from "./run-lifecycle.js";
@@ -231,18 +232,30 @@ export async function prepareHeartbeatExecutionConfiguration(db: Db, input: Hear
} else {
delete context.paperclipSecrets;
}
const effectiveResolvedConfig = applyRunScopedMentionedSkillKeys(
resolvedConfig,
runScopedSkillKeys,
);
const storedVersions = parseObject(run.contextSnapshot?.skillVersions);
const hasStoredVersions = Object.prototype.hasOwnProperty.call(run.contextSnapshot ?? {}, "skillVersions");
const savedShadowedSkills = Array.isArray(run.contextSnapshot?.shadowedSkills)
? run.contextSnapshot.shadowedSkills.flatMap(value => {
const saved = parseObject(value);
return typeof saved.key === "string" && typeof saved.shadowedBy === "string" && Object.hasOwn(storedVersions, saved.shadowedBy)
? [{ key: saved.key, shadowedBy: saved.shadowedBy }] : [];
}) : [];
const selectedConfig = applyRunScopedMentionedSkillKeys(resolvedConfig, runScopedSkillKeys);
const { config: effectiveResolvedConfig, skillKeys: environmentSkills, shadowedSkills } = hasStoredVersions
? { config: selectedConfig, skillKeys: [], shadowedSkills: savedShadowedSkills }
: await environmentSkillConfig(db, agent.companyId, selectedEnvironmentForConfig, selectedConfig);
if (shadowedSkills?.length) {
context.shadowedSkills = shadowedSkills;
if (!hasStoredVersions) await appendRunEvent(run, { eventType: "skills.shadowed", stream: "system", level: "warn",
message: shadowedSkills.map(({ key, shadowedBy }) => `Skill "${key}" was skipped because required plugin skill "${shadowedBy}" uses the same name.`).join("\n"),
payload: { shadowedSkills } });
}
const runtimeSkillPreference = readPaperclipSkillSyncPreference(
effectiveResolvedConfig,
);
const nativeRunnerPreparationSpans: NativeRunHistoricalSpan[] = [];
const skillsPrepareStartedAtMs = Date.now();
let skillDeliveryConfig = effectiveResolvedConfig;
const storedVersions = parseObject(run.contextSnapshot?.skillVersions);
const hasStoredVersions = Object.prototype.hasOwnProperty.call(run.contextSnapshot ?? {}, "skillVersions");
const prepareSkills = async () => {
try {
@@ -270,7 +283,7 @@ export async function prepareHeartbeatExecutionConfiguration(db: Db, input: Hear
// assignments from delivery; explicit task mentions remain errors below.
skillDeliveryConfig = writePaperclipSkillSyncPreference(effectiveResolvedConfig,
resolved.map(entry => ({ key: entry.key, versionId: entry.versionId ?? null })));
for (const key of runScopedMentionedSkillKeys) {
for (const key of [...runScopedMentionedSkillKeys.filter(key => !shadowedSkills?.some(skill => skill.key === key)), ...(hasStoredVersions ? [] : environmentSkills)]) {
const entry = resolved.find(candidate => candidate.key === key);
if (!entry || entry.sourceStatus === "missing") {
throw new ConfigurationIncompleteFailure("A referenced skill is unavailable. Restore its installed version or update the task's skill reference.", {
@@ -282,7 +295,7 @@ export async function prepareHeartbeatExecutionConfiguration(db: Db, input: Hear
const skillVersions = Object.fromEntries(resolved.map(entry => [entry.key, entry.versionId ?? entry.currentVersionId ?? null]));
context.skillVersions = skillVersions;
context.skillSelectionSnapshot = true;
await db.update(heartbeatRuns).set({ contextSnapshot: sql`coalesce(${heartbeatRuns.contextSnapshot}, '{}'::jsonb) || ${JSON.stringify({ skillVersions, skillSelectionSnapshot: true })}::jsonb` }).where(eq(heartbeatRuns.id, run.id));
await db.update(heartbeatRuns).set({ contextSnapshot: sql`coalesce(${heartbeatRuns.contextSnapshot}, '{}'::jsonb) || ${JSON.stringify({ skillVersions, skillSelectionSnapshot: true, ...(shadowedSkills?.length ? { shadowedSkills } : {}) })}::jsonb` }).where(eq(heartbeatRuns.id, run.id));
}
return resolved;
}));
+26 -8
View File
@@ -1,4 +1,4 @@
import { assertTaskRetryConversationAllowed, readTaskRetryIntent, retireSupersededTaskRetry, taskRetryMutationAllowed } from "../task-retry.js";
import { assertTaskRetryConversationAllowed, readTaskRetryIntent, readTaskRetryBoardMessageOrigin, retireSupersededTaskRetry, taskRetryMutationAllowed } from "../task-retry.js";
import { insertIssueComment } from "../issue-comment-writes.js";
import { withExternalAdmissionGuard, assertNoExternalOverlap } from "../../modules/external-agents/index.js";
import { isAgentAwaitingSetup } from "../../modules/agent-lifecycle/index.js";
@@ -47,6 +47,7 @@ import { adapterExecutionControls } from "../adapter-execution-control.js";
import { executionFailureRetryCount } from "../execution-recovery-attempt.js";
import {
slackMentionAllowsRunStart,
resumeDeferredChatWake,
assertDurableChatWakeupReceipt,
assertDurableChatWakeupRequest,
withDurableChatAdmission,
@@ -1857,6 +1858,13 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
));
if (!latest || !latest.finishedAt || !isHeartbeatRunTerminalStatus(latest.status)) continue;
if (latest.runtimeMode !== "legacy" && latest.runtimeMode !== "native") continue;
if (wake.idempotencyKey?.startsWith("chat-inbound:")) {
await resumeDeferredChatWake(db, { companyId: wake.companyId, agentId: wake.agentId,
issueId: String(wake.payload?.issueId), requestId: wake.id }).catch(() => {
logger.warn({ requestId: wake.id }, "saved chat source could not resume after recovery");
});
continue;
}
const releaseSource = `${latest.companyId}:${String(wake.payload?.issueId)}:${latest.id}:${latest.sourceVersion}`;
if (latest.runtimeMode === "native" && releasedNativeSources.has(releaseSource)) continue;
if (latest.runtimeMode === "legacy") {
@@ -2187,6 +2195,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
if (executionReconciliationWake && !issueId) return null;
const durableRequest = opts.durableChatRequest;
let taskRetryActorId: string | null = null;
delete enrichedContextSnapshot.boardMessageRetry;
if (opts.taskRetryRequestId) {
const [receipt] = await db.select().from(agentWakeupRequests).where(and(
eq(agentWakeupRequests.id, opts.taskRetryRequestId), eq(agentWakeupRequests.agentId, agentId),
@@ -2205,6 +2214,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
enrichedContextSnapshot.forceFreshSession = true;
enrichedContextSnapshot.previousRunId = retry.sourceRunId;
enrichedContextSnapshot.taskRetryRequestId = receipt.id;
if (retry.boardMessageOrigin) enrichedContextSnapshot.boardMessageRetry = true;
}
@@ -2373,10 +2383,13 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
receipt.payload?.museBindingGeneration !== museRequest.bindingGeneration || receipt.payload?.museRequestDigest !== museRequest.requestDigest)) {
throw conflict("Request ID reused with changed input.");
}
if (receipt && durableRequest?.failedRunRetry && opts.taskRetryRequestId &&
receipt.status === "deferred_issue_execution" && !receipt.runId &&
receipt.payload?.taskRetryRequestId === opts.taskRetryRequestId) {
// A bound ordinary Retry may reconsider its same deferred chat receipt.
if (receipt && durableRequest && receipt.status === "deferred_issue_execution" && !receipt.runId &&
((durableRequest.failedRunRetry && opts.taskRetryRequestId &&
receipt.payload?.taskRetryRequestId === opts.taskRetryRequestId) ||
(durableRequest.resumeDeferred && !durableRequest.failedRunRetry &&
receipt.payload?.issueId === durableRequest.issueId &&
queuedCommentIdsFromWakePayload(receipt.payload).includes(durableRequest.commentId)))) {
// The live inbound owner or a bound Retry may reconsider the same saved receipt.
// The issue lock, live chat authority and execution holds below still
// decide whether it can dispatch; this never creates another wake.
executionWaitRequestId = receipt.id;
@@ -2822,8 +2835,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
// system wake. Admission validates the saved user comment or board click.
(opts.queuedCommentInterruptId ?? opts.queuedCommentRequestId) === executionWaitRequestId
? undefined : eq(agentWakeupRequests.requestedByActorType,
durableRequest?.failedRunRetry && opts.taskRetryRequestId
? opts.requestedByActorType ?? "" : "user"),
durableRequest ? opts.requestedByActorType ?? "" : "user"),
opts.queuedCommentInterruptId === executionWaitRequestId
? sql`${agentWakeupRequests.payload}->'queuedCommentInterrupt'->>'actorId' = ${opts.requestedByActorId ?? ""}`
: opts.queuedCommentRequestId === executionWaitRequestId ? undefined
@@ -2849,6 +2861,12 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
return { kind: "deferred" as const };
if (!await taskRetryMutationAllowed(tx as unknown as Db, { companyId: agent.companyId, issueId,
actorId: retry.actorId, actorSource: retry.actorSource })) return { kind: "deferred" as const };
if (retry.boardMessageOrigin) {
const origin = await readTaskRetryBoardMessageOrigin(tx as unknown as Db, { companyId: agent.companyId,
issueId, agentId, sourceRunId: retry.sourceRunId, actorId: retry.actorId });
if (!origin || origin.commentId !== retry.boardMessageOrigin.commentId ||
origin.identityContextId !== retry.boardMessageOrigin.identityContextId) return { kind: "deferred" as const };
}
}
if (opts.queuedCommentRequestId) {
const ids = await undeliveredLegacyUserCommentIds(tx as unknown as Db,
@@ -4187,7 +4205,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
};
// A deferred durable chat wake already owns this ID and source.
// Promote that receipt in the same transaction as its successor.
const wakeupRequest = durableRequest?.failedRunRetry && executionWaitRequestId === durableRequest.id
const wakeupRequest = durableRequest && executionWaitRequestId === durableRequest.id
? await tx.update(agentWakeupRequests).set({
payload, status: "queued", error: null, finishedAt: null, updatedAt: new Date(),
}).where(and(eq(agentWakeupRequests.id, durableRequest.id),
+29 -1
View File
@@ -11,6 +11,7 @@ import { createHeartbeatRunState } from "./run-state.js";
import type { HotRestartIntent } from "../hot-restart.js";
import type { NativeRestartRecoveryClaim, NativeRestartRecoveryDisposition } from "../native-runtime/index.js";
import { NATIVE_OWNERSHIP_UNVERIFIED_ERROR_CODE } from "../native-runtime/native-runner-ownership.js";
import { claimNativeRestartRecoveries } from "../native-runtime/native-restart-recovery.js";
import { allowLegacyShutdownWorkspaceCleanup, beginLegacyShutdownWorkspaceSettlement, finishLegacyShutdownWorkspaceSettlement, maintainLegacyShutdownWorkspaceSettlement, legacyShutdownWorkspaceResourceProtected, sweepLegacyShutdownWorkspaceSettlements } from "../legacy-shutdown-workspace-settlement.js";
import { adapterExecutionControls, createAdapterExecutionControl } from "../adapter-execution-control.js";
import { logger } from "../../middleware/logger.js";
@@ -23,7 +24,7 @@ const native = vi.hoisted(() => ({
finalizations: vi.fn(async (_db: Db, _ids?: string[], _options?: unknown) => undefined),
cleanups: vi.fn(async () => undefined),
drainMaintenance: vi.fn<() => Promise<void>>(async () => undefined),
claims: vi.fn<() => Promise<NativeRestartRecoveryDisposition[]>>(async () => []),
claims: vi.fn<typeof claimNativeRestartRecoveries>(async () => []),
}));
const hotRestart = vi.hoisted(() => ({
read: vi.fn<() => Promise<HotRestartIntent | null>>(async () => null),
@@ -608,6 +609,33 @@ describePostgres("heartbeat recovery module ownership", () => {
await vi.waitFor(() => expect(deps.activeRunExecutionPromises.size).toBe(0));
});
it("does not dispatch recovery for a run still preparing in this heartbeat process", async () => {
const run = await seedRun();
await db.update(agents).set({ adapterType: "paperclip_runner" }).where(eq(agents.id, run.agentId));
await db.update(issues).set({ executionRunId: run.id }).where(eq(issues.id, run.issueId!));
await db.update(heartbeatRuns).set({ runtimeMode: "native", nativeIssueId: run.issueId }).where(eq(heartbeatRuns.id, run.id));
await db.insert(nativeRunFinalizations).values({ runId: run.id, companyId: run.companyId, issueId: run.issueId!, phase: "observed" });
const deps = callbacks(db);
deps.activeRunExecutions.add(run.id);
deps.getRun.mockImplementation(async id => (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, id)))[0] ?? null);
native.claims.mockImplementationOnce(claimNativeRestartRecoveries);
const before = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, run.id));
try {
const result = await createHeartbeatRecovery(db, deps).recoverNativeRunsAfterRestart();
expect(result.awaitingEvidenceRunIds).toEqual([run.id]);
expect(result.claims).toEqual([]);
expect(deps.executeRun).not.toHaveBeenCalled();
expect(await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, run.id))).toEqual(before);
expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, run.issueId!))).toHaveLength(0);
expect((await deps.getRun(run.id))?.status).toBe("running");
} finally {
deps.activeRunExecutions.delete(run.id);
await Promise.all([...deps.activeRunExecutionPromises]);
await db.delete(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, run.id));
await db.delete(heartbeatRuns).where(eq(heartbeatRuns.id, run.id));
}
});
it("does not claim or execute recovery when persisted finalization fails", async () => {
const deps = callbacks(db);
native.finalizations.mockRejectedValueOnce(new Error("result settlement failed"));
@@ -959,6 +959,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
}
const dispositions = await claimNativeRestartRecoveries({
db,
liveRunExecutions: activeRunExecutions,
restartKind,
recoveryRequestId: intent?.recoveryRequestId ?? null,
coordinatedPreviousController: intent
@@ -429,6 +429,38 @@ describe.skipIf(!runControlPostgresSupport.supported)("heartbeat run-control dat
.toMatchObject({ status: "done", phase: "done", completedAt: expect.any(Date) });
});
it.each(["confirmed", "missing", "wrong_allocation", "unacknowledged", "still_running", "wrong_intent"] as const)("publishes native Stop acknowledgement only after exact remote containment: %s", async proof => {
const { company, agent } = await fixture();
const [issue] = await db.insert(issues).values({ companyId: company.id, title: "Save work after Stop", assigneeAgentId: agent.id }).returning();
const runId = randomUUID(), leaseId = randomUUID(), providerLeaseId = randomUUID();
const [run] = await db.insert(heartbeatRuns).values({ id: runId, companyId: company.id, agentId: agent.id,
nativeIssueId: issue.id, runtimeMode: "native", status: proof === "still_running" ? "running" : "cancelled", finishedAt: proof === "still_running" ? null : new Date(),
resultJson: { executionCancellation: { state: "requested", requestedAt: new Date().toISOString() },
cancelledByActorType: "user", cancelledByUserId: "operator", nativeCancellation: {
schema: "paperclip.native-cancellation.v1", runId: proof === "wrong_intent" ? randomUUID() : runId, companyId: company.id, issueId: issue.id,
scope: "run", reasonCode: "cancellation_run_only", dispatchState: proof === "unacknowledged" ? "pending" : "acknowledged", dispatched: true,
intentAuditId: randomUUID(), acknowledgementAuditId: randomUUID(),
}, workspaceRestoreFailure: "restore_failed", workspaceRestoreRecovery: {
schema: "paperclip.workspace-restore-recovery.v1", leaseIds: [leaseId],
} },
}).returning();
const receipt = { schema: "paperclip.remote-termination.v1", companyId: company.id, runId, leaseId,
provider: "daytona", providerLeaseId: proof === "wrong_allocation" ? randomUUID() : providerLeaseId,
state: "stopped", confirmedAt: new Date().toISOString() };
await db.insert(environmentLeases).values({ id: leaseId, companyId: company.id, issueId: issue.id, heartbeatRunId: runId,
provider: "daytona", providerLeaseId, status: proof === "missing" ? "active" : "released", leasePolicy: "retain_on_failure",
releasedAt: proof === "missing" ? null : new Date(), cleanupStatus: proof === "missing" ? null : "success",
metadata: proof === "missing" ? {} : { remoteExecutionTermination: receipt } });
const control = createHeartbeatRunControl(db, callbacks(db));
await control.acknowledgeRemoteStop(run.id, company.id);
await control.acknowledgeRemoteStop(run.id, company.id);
const [stopped] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id));
expect(stopped.resultJson?.executionCancellation).toMatchObject({ state: proof === "confirmed" ? "acknowledged" : "requested" });
if (proof === "confirmed") expect(stopped.resultJson?.executionCancellation).toMatchObject({ proof: "provider_termination_receipt" });
expect(stopped.resultJson?.workspaceRestoreFailure).toBe("restore_failed");
expect(stopped.resultJson?.workspaceRestoreRecovery).toMatchObject({ leaseIds: [leaseId] });
});
it("keeps pre-Stop input pending until a later user message authorizes one continuation", async () => {
const { company, agent } = await fixture();
const [issue] = await db.insert(issues).values({ companyId: company.id, title: "Retain my direction after Stop",
+23 -8
View File
@@ -1,3 +1,4 @@
import { resumeDeferredChatWake } from "../durable-chat-wakeup.js";
import { notifyEnvironmentCleanup } from "../environment-cleanup-notifications.js";
import { readNativeStopExecutionEvidence } from "./native-stop-evidence-read.js";
import { readTaskRetryIntent, reconcileTaskChatRetryReceipts } from "../task-retry.js";
@@ -40,6 +41,7 @@ import {
} from "../remote-execution-termination.js";
import {
admitExplicitNativeContinuation,
isUserCommentContinuationReason,
undeliveredLegacyUserCommentIds,
} from "../explicit-native-continuation.js";
import { isCancelledNativeStartup } from "../cancelled-native-startup.js";
@@ -492,21 +494,27 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont
completeTerminatedRemoteNativeSessionCleanup({ companyId, runId, remoteCleanupScope });
}
}
const stopped = state?.runtimeMode === "legacy" && state.status === "cancelled" ? await getRun(runId) : null;
if (stopped?.runtimeMode === "legacy" && stopped.status === "cancelled" &&
const stopped = state?.status === "cancelled" ? await getRun(runId) : null;
// Native interrupt acknowledgement is not physical containment. Publish the
// shared Stop receipt only after every exact remote lease confirms teardown.
// Keep workspace preservation separate: a stopped provider can still owe files.
if (stopped?.status === "cancelled" &&
parseObject(stopped.resultJson?.executionCancellation).state === "requested" &&
await runUsedConversationAdapter(db, stopped) &&
(stopped.runtimeMode === "native" ? isAcknowledgedNativeStop(stopped)
: stopped.runtimeMode === "legacy" && await runUsedConversationAdapter(db, stopped)) &&
await remoteExecutionHasStopped(db, companyId, runId)) {
await db.update(heartbeatRuns).set({
resultJson: sql`coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb) || ${JSON.stringify({
executionCancellation: { ...parseObject(stopped.resultJson?.executionCancellation),
state: "acknowledged", acknowledgedAt: new Date().toISOString(),
proof: "provider_termination_receipt" },
conversationContinuation: CONVERSATION_CONTINUATION_POLICY,
...(stopped.runtimeMode === "legacy" ? { conversationContinuation: CONVERSATION_CONTINUATION_POLICY } : {}),
})}::jsonb`,
updatedAt: new Date(),
}).where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId),
eq(heartbeatRuns.status, "cancelled")));
eq(heartbeatRuns.status, "cancelled"),
sql`${heartbeatRuns.resultJson}->'executionCancellation'->>'state' = 'requested'`,
stopped.runtimeMode === "native" ? sql`${heartbeatRuns.resultJson}->'nativeCancellation' = ${JSON.stringify(stopped.resultJson?.nativeCancellation)}::jsonb` : undefined));
}
}
@@ -543,12 +551,19 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont
const pending = await db.select().from(agentWakeupRequests).where(and(
eq(agentWakeupRequests.companyId, run.companyId), eq(agentWakeupRequests.agentId, run.agentId),
eq(agentWakeupRequests.status, "deferred_issue_execution"),
eq(agentWakeupRequests.requestedByActorType, "user"),
inArray(agentWakeupRequests.requestedByActorType, ["user", "system"]),
requestId ? eq(agentWakeupRequests.id, requestId) : undefined,
sql`${agentWakeupRequests.payload}->>'issueId' = ${issueId}`,
)).orderBy(asc(agentWakeupRequests.requestedAt)).limit(50);
for (const wake of pending) {
if (wake.idempotencyKey?.startsWith("chat-inbound:")) continue;
if (wake.idempotencyKey?.startsWith("chat-inbound:")) {
await resumeDeferredChatWake(db, { companyId: run.companyId, agentId: run.agentId,
issueId, requestId: wake.id }).catch(() => {
logger.warn({ requestId: wake.id }, "saved chat source could not resume after cleanup");
});
continue;
}
if (wake.requestedByActorType !== "user") continue;
if (readTaskRetryIntent(wake.payload)) { await resumeTaskRetry(wake.companyId, wake.id); continue; }
let payload = parseObject(wake.payload);
if (payload.queuedCommentInterrupt) {
@@ -575,7 +590,7 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont
}
if (legacyContinuation || stoppedNativeContinuation) {
if (!commentId || !run.finishedAt || !requestedByActorId ||
!["issue_commented", "issue_reopened_via_comment"].includes(reason ?? "")) continue;
!isUserCommentContinuationReason(reason)) continue;
const [comment] = await db.select().from(issueComments).where(and(
eq(issueComments.companyId, run.companyId), eq(issueComments.issueId, issueId),
sql`${issueComments.id}::text = ${commentId}`, eq(issueComments.authorType, "user"),
@@ -11,6 +11,7 @@ import { buildNativeRuntimeContext } from "../native-runtime/runtime-context.js"
import { nativeRuntimeContextFixture } from "../native-runtime/runtime-context.test-fixture.js";
import { prepareNativeWorkspaceSync } from "../native-runtime/native-workspace-sync.js";
import { resolveHeartbeatNativeRuntimeMode } from "../native-runtime/runtime-mode.js";
import { claimNativeRestartRecoveries } from "../native-runtime/native-restart-recovery.js";
import { canonicalNativeRuntimeContextDigest } from "../../vendor/paperclip-runner/index.js";
import { selectHeartbeatRuntime, type HeartbeatRuntimeSelectionInput } from "./runtime-selection.js";
@@ -74,6 +75,31 @@ describe.skipIf(!support.supported)("heartbeat runtime selection boundary", () =
const coordinators = (id: string) => db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, id));
const sandbox = { kind: "remote" as const, transport: "sandbox" as const, remoteCwd: "/workspace", reusableLeaseConfigured: false };
it("keeps recovery out of live preparation before the workspace descriptor exists", async () => {
const { input, run, issue } = await fixture();
input.workspace.executionTarget = sandbox;
await db.update(issues).set({ executionRunId: run.id }).where(eq(issues.id, issue.id));
const liveRunExecutions = new Set([run.id]);
const recoveryInput = { db, restartKind: "hard" as const, runIds: [run.id], liveRunExecutions };
vi.mocked(prepareNativeWorkspaceSync).mockImplementationOnce(async () => {
const saved = await read(run.id);
expect(saved.runnerProfileJson).toHaveProperty("nativeExecutionInput");
expect(saved.runnerProfileJson).not.toHaveProperty("nativeWorkspaceSync");
const before = await coordinators(run.id);
expect(await claimNativeRestartRecoveries(recoveryInput)).toEqual([
{ kind: "awaiting_evidence", runId: run.id, reason: "current_controller_preparing" },
]);
expect(await coordinators(run.id)).toEqual(before);
expect((await read(run.id)).status).toBe("running");
return null;
});
expect((await selectHeartbeatRuntime(db, input)).selected).toBe(true);
liveRunExecutions.delete(run.id);
expect(await claimNativeRestartRecoveries(recoveryInput)).toEqual([
expect.objectContaining({ kind: "bootstrap_incomplete", runId: run.id, controllerGeneration: 1 }),
]);
});
it("persists the native input, completion contract, and coordinator before transferring cleanup ownership", async () => {
const { input, run } = await fixture();
input.workspace.onCheckpoint = vi.fn(async () => {});
@@ -311,6 +337,26 @@ describe.skipIf(!support.supported)("heartbeat runtime selection boundary", () =
expect(await coordinators(run.id)).toHaveLength(1);
});
it.each(["api_key", "subscription"] as const)("keeps managed Claude %s task execution warm", async method => {
const { input, run, issue } = await fixture();
const adapterConfig = { provider: "acpx", acpxAgent: "claude", model: "claude-sonnet-4-6", lifecycleMode: "warm" };
input.agent = { ...input.agent, adapterConfig };
await db.update(agents).set({ adapterConfig }).where(eq(agents.id, input.agent.id));
input.nativeRuntimeResolution = resolveHeartbeatNativeRuntimeMode({ persisted: input.run, enabled: true, runtimeConfig: {}, adapterConfig,
agent: input.agent, issue, target: null, workspaceId: null });
input.workspace.executionTarget = { ...sandbox, runnerTask: vi.fn(), reusableLeaseConfigured: true,
effectiveCapabilities: { reusableLeases: true } as never, runnerLifecyclePolicy: { mode: "warm", idleTimeoutMs: 300_000 } };
const attribution = { connectionId: randomUUID(), grantId: randomUUID(), provider: "anthropic" as const, method,
mode: "responsible_user" as const, responsibleUserId: "task-owner" };
input.config.managedAiRuntime = { sessionIdentity: "account:epoch-1", identity: "account:generation-1",
config: { env: {}, managedAiConnection: { ...attribution, identity: "account:generation-1", sessionIdentity: "account:epoch-1" } },
attribution, accountName: "Saved account", accountOwnerUserId: "task-owner", home: instructionRoot, cleanup: async () => {} };
const selected = await selectHeartbeatRuntime(db, input);
if (!selected.selected || !selected.nativeExecution) throw new Error("Expected native Claude selection");
expect(selected.nativeExecution.session.lifecyclePolicy).toEqual({ mode: "warm", idleTimeoutMs: 300_000 });
expect((await read(run.id)).runnerProfileJson).toMatchObject({ nativeExecutionInput: { session: { lifecyclePolicy: { mode: "warm" } } } });
});
it("preserves only server-owned admission and dispatch evidence when recording legacy selection", async () => {
const { input, run } = await fixture("process");
const admission = { version: 1, kind: "fixture" }, dispatch = { entered: true };
@@ -506,11 +506,10 @@ export async function selectHeartbeatRuntime(db: Db, input: HeartbeatRuntimeSele
executionTarget.transport === "sandbox"
? (executionTarget.runnerLifecyclePolicy ?? null)
: null;
// Codex refreshes its durable auth home; Copilot owns a fenced home
// and an explicitly bound token. Both retire on credential generation
// changes. Other managed harnesses require per-turn cleanup.
// Task providers own credential lifetime; process-backed managed homes retain their provider-specific cleanup policy.
const supportsManagedWarmSession = agent.adapterType === "paperclip_runner" &&
supportsManagedNativeWarmSession({ ...nativeRuntimeResolution.profile, acpxAgent: parseObject(agent.adapterConfig).acpxAgent }, managedAiRuntime?.attribution);
((executionTarget?.kind === "remote" && executionTarget.transport === "sandbox" && !!executionTarget.runnerTask) ||
supportsManagedNativeWarmSession({ ...nativeRuntimeResolution.profile, acpxAgent: parseObject(agent.adapterConfig).acpxAgent }, managedAiRuntime?.attribution));
const effectiveLifecyclePolicy = persistedNativeExecutionInput?.session.lifecyclePolicy ??
(["openai_dot_mcp", "grok_bot_mcp", "muse_external"].includes(nativeRuntimeResolution.profile.backend) || managedAiRuntime && !supportsManagedWarmSession
? { mode: "per_turn" as const, idleTimeoutMs: null }
@@ -320,6 +320,69 @@ describe.skipIf(!support.supported)("heartbeat workspace preparation boundary",
expect((await readIssue(issue.id)).executionWorkspaceId).toBe(prepared.persistedExecutionWorkspace!.id);
});
it("reuses a successful fresh task attempt for the next ordinary user turn", async () => {
const { input, issue } = await fixture();
input.policy.useIsolatedTaskDirectory = true;
input.policy.effectiveExecutionWorkspaceMode = "isolated_workspace";
input.policy.requestedExecutionWorkspaceMode = "isolated_workspace";
input.task.freshWorkspace = { mode: "fresh_isolated_workspace", retryIntentId: input.run.id,
sourceRunId: input.run.id, retainedSourceIds: [] };
const original = await prepareHeartbeatWorkspace(db, input);
const workspace = original.persistedExecutionWorkspace!;
await writeFile(join(workspace.cwd!, "saved-review.txt"), "completed review history\n");
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() })
.where(eq(heartbeatRuns.id, input.run.id));
await reuse(input, workspace);
input.task.freshWorkspace = null;
const next = await prepareHeartbeatWorkspace(db, input);
expect(next.persistedExecutionWorkspace!.id).toBe(workspace.id);
expect(next.executionWorkspace.cwd).toBe(workspace.cwd);
expect(await readFile(join(next.executionWorkspace.cwd, "saved-review.txt"), "utf8"))
.toBe("completed review history\n");
expect((await readIssue(issue.id)).executionWorkspaceId).toBe(workspace.id);
await reuse(input, workspace);
input.task.freshWorkspace = { mode: "fresh_isolated_workspace", retryIntentId: input.run.id,
sourceRunId: input.run.id, retainedSourceIds: [] };
input.reuse.existingExecutionWorkspace = null;
input.reuse.reusableExistingExecutionWorkspace = null;
input.reuse.requestedShouldReuseExisting = false;
input.reuse.workspaceReuseRequest = resolveExecutionWorkspaceReuseRequestForIssue({
issueExecutionWorkspaceId: null, issueExecutionWorkspacePreference: "create_new", existingExecutionWorkspaceStatus: null,
});
const replacement = await prepareHeartbeatWorkspace(db, input);
expect(replacement.executionWorkspace.cwd).not.toBe(workspace.cwd);
await expect(access(join(replacement.executionWorkspace.cwd, "saved-review.txt"))).rejects.toThrow();
expect(await readFile(join(workspace.cwd!, "saved-review.txt"), "utf8")).toBe("completed review history\n");
});
it.each(["task_binding", "workspace_row", "foreign_issue", "foreign_company", "closed_workspace"])(
"rejects a retained task attempt after its %s changes", async change => {
const { input, issue, source } = await fixture();
input.policy.useIsolatedTaskDirectory = true;
input.policy.effectiveExecutionWorkspaceMode = "isolated_workspace";
input.policy.requestedExecutionWorkspaceMode = "isolated_workspace";
input.task.freshWorkspace = { mode: "fresh_isolated_workspace", retryIntentId: input.run.id,
sourceRunId: input.run.id, retainedSourceIds: [] };
const original = await prepareHeartbeatWorkspace(db, input);
const workspace = original.persistedExecutionWorkspace!;
await writeFile(join(workspace.cwd!, "saved-review.txt"), "keep saved work\n");
await reuse(input, workspace);
input.task.freshWorkspace = null;
if (change === "task_binding") await db.update(issues).set({ executionWorkspaceId: null }).where(eq(issues.id, issue.id));
if (change === "workspace_row") await db.update(executionWorkspaces).set({ cwd: source }).where(eq(executionWorkspaces.id, workspace.id));
if (change === "foreign_issue") await db.update(executionWorkspaces).set({ sourceIssueId: null }).where(eq(executionWorkspaces.id, workspace.id));
if (change === "foreign_company") {
const [other] = await db.insert(companies).values({ name: "Other workspace company", issuePrefix: "OTH" }).returning();
await db.update(executionWorkspaces).set({ companyId: other.id }).where(eq(executionWorkspaces.id, workspace.id));
}
if (change === "closed_workspace") await db.update(executionWorkspaces).set({ status: "archived" }).where(eq(executionWorkspaces.id, workspace.id));
await expect(prepareHeartbeatWorkspace(db, input)).rejects.toMatchObject({
resultJson: { workspaceValidation: { reason: "isolated_task_directory_binding_mismatch", issueId: issue.id } },
});
expect(await readFile(join(workspace.cwd!, "saved-review.txt"), "utf8")).toBe("keep saved work\n");
},
);
async function reuse(input: HeartbeatWorkspacePreparationInput, workspace: NonNullable<Awaited<ReturnType<typeof prepareHeartbeatWorkspace>>["persistedExecutionWorkspace"]>) {
input.reuse.requestedShouldReuseExisting = true;
input.reuse.existingExecutionWorkspace = workspace;
@@ -393,10 +456,12 @@ describe.skipIf(!support.supported)("heartbeat workspace preparation boundary",
it("persists the workspace and issue binding before acquiring its environment", async () => {
const { input, source, issue, envOrchestrator } = await fixture();
input.config.managedAiCredentialIdentity = "account:generation";
const acquire = envOrchestrator.acquireForRun;
vi.spyOn(envOrchestrator, "acquireForRun").mockImplementation(async args => {
expect((await readIssue(issue.id)).executionWorkspaceId).toBe(args.persistedExecutionWorkspace?.id);
expect((await readRun(input.run.id)).contextSnapshot?.executionWorkspaceId).toBe(args.persistedExecutionWorkspace?.id);
expect(args.managedAiCredentialIdentity).toBe("account:generation");
return acquire(args);
});
const result = await prepareHeartbeatWorkspace(db, input);
@@ -129,6 +129,7 @@ export interface HeartbeatWorkspacePreparationInput {
mergedConfig: Record<string, unknown>;
configSnapshot: WorkspaceMetadataInput["configSnapshot"];
secretManifest: WorkspaceMetadataInput["secretManifest"];
managedAiCredentialIdentity?: string;
};
reuse: {
requestedShouldReuseExisting: boolean;
@@ -277,18 +278,33 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
workspaceHints: [], warnings: [], baseCwdFallback: false, materializationFailures: [], additionalWorkspaces: [], referencedProjectFailures: [] };
}
if (useIsolatedTaskDirectory && issueRef && !pluginTaskWorkspace) {
const cwd = await materializeIsolatedTaskDirectory({
companyId: agent.companyId,
issueId: issueRef.id,
...(input.task.freshWorkspace?.mode === "fresh_isolated_workspace" ? { attemptId: run.id } : {}),
});
if (reusableExistingExecutionWorkspace && (
reusableExistingExecutionWorkspace.companyId !== agent.companyId ||
reusableExistingExecutionWorkspace.sourceIssueId !== issueRef.id ||
reusableExistingExecutionWorkspace.mode !== "isolated_workspace" ||
reusableExistingExecutionWorkspace.strategyType !== "project_primary" ||
reusableExistingExecutionWorkspace.cwd !== cwd
)) {
// A completed fresh attempt becomes the current task directory. New
// input reuses that binding; only another fresh attempt changes roots.
let cwd: string;
try {
if (reusableExistingExecutionWorkspace) {
const [currentIssue] = await db.select({ workspaceId: issues.executionWorkspaceId }).from(issues)
.where(and(eq(issues.id, issueRef.id), eq(issues.companyId, agent.companyId)));
const stored = await executionWorkspacesSvc.getStoredById(agent.companyId, reusableExistingExecutionWorkspace.id);
if (fresh || currentIssue?.workspaceId !== reusableExistingExecutionWorkspace.id ||
reusableExistingExecutionWorkspace.companyId !== agent.companyId ||
reusableExistingExecutionWorkspace.sourceIssueId !== issueRef.id ||
reusableExistingExecutionWorkspace.mode !== "isolated_workspace" ||
reusableExistingExecutionWorkspace.strategyType !== "project_primary" || !stored ||
stored.companyId !== agent.companyId || stored.sourceIssueId !== issueRef.id ||
stored.mode !== "isolated_workspace" || stored.strategyType !== "project_primary" ||
stored.status !== "active" || stored.cwd !== reusableExistingExecutionWorkspace.cwd || !stored.cwd) {
throw new Error("The saved task directory binding changed");
}
}
cwd = await materializeIsolatedTaskDirectory({
companyId: agent.companyId,
issueId: issueRef.id,
...(fresh ? { attemptId: run.id } : {}),
...(reusableExistingExecutionWorkspace ? { reuseCwd: reusableExistingExecutionWorkspace.cwd! } : {}),
});
} catch (error) {
if (!reusableExistingExecutionWorkspace) throw error;
throw new WorkspaceValidationFailure("The existing execution workspace is not this task's isolated directory.", {
workspaceValidation: { reason: "isolated_task_directory_binding_mismatch", issueId: issueRef.id },
});
@@ -1106,6 +1122,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
adapterType: agent.adapterType,
adapterConfig: parseObject(agent.adapterConfig),
admittedLifecycleMode: persistedNativeExecutionInput?.session.lifecyclePolicy.mode,
managedAiCredentialIdentity: input.config.managedAiCredentialIdentity,
runnerTaskProjectIds:[...new Set([executionWorkspace.projectId,...resolvedWorkspace.runnerTaskProjectIds ?? [],
...(executionWorkspace.additionalWorkspaces ?? []).map(workspace=>workspace.projectId)]
.filter((id):id is string=>Boolean(id)))],
@@ -73,6 +73,37 @@ describe("isolated task directories", () => {
.rejects.toThrow("not a private directory");
});
it("reuses only the exact private task directory, including a prior fresh attempt", async () => {
const identity = await setup();
for (const attemptId of [undefined, "previous-attempt"]) {
const cwd = await materializeIsolatedTaskDirectory({ ...identity, attemptId });
await writeFile(path.join(cwd, "saved.txt"), "preserved");
expect(await materializeIsolatedTaskDirectory({ ...identity, reuseCwd: cwd })).toBe(cwd);
expect(await readFile(path.join(cwd, "saved.txt"), "utf8")).toBe("preserved");
}
});
it.each(["other-company", "other-issue", "outside", "traversal", "missing", "symlink"])(
"does not admit or recreate a reused task directory with %s binding", async change => {
const identity = await setup();
const cwd = await materializeIsolatedTaskDirectory({ ...identity, attemptId: "prior-attempt" });
await writeFile(path.join(cwd, "saved.txt"), "preserved");
let reuseCwd = cwd;
if (change === "other-company") reuseCwd = cwd.replace(identity.companyId, "other-company");
if (change === "other-issue") reuseCwd = cwd.replace(identity.issueId, "other-issue");
if (change === "outside") reuseCwd = path.dirname(path.dirname(cwd));
if (change === "traversal") reuseCwd = `${cwd}/../prior-attempt`;
if (change === "missing") reuseCwd = path.join(path.dirname(cwd), "missing-attempt");
if (change === "symlink") {
reuseCwd = path.join(path.dirname(cwd), "linked-attempt");
await symlink(cwd, reuseCwd);
}
await expect(materializeIsolatedTaskDirectory({ ...identity, reuseCwd })).rejects.toThrow();
if (change === "missing") await expect(readFile(path.join(reuseCwd, "saved.txt"))).rejects.toThrow();
expect(await readFile(path.join(cwd, "saved.txt"), "utf8")).toBe("preserved");
},
);
it("round-trips sandbox output into the task directory and stages it on the next turn", async () => {
const identity = await setup();
const cwd = await materializeIsolatedTaskDirectory(identity);
+18 -4
View File
@@ -26,20 +26,34 @@ export async function materializeIsolatedTaskDirectory(input: {
companyId: string;
issueId: string;
attemptId?: string;
/** Validate retained files in place; never recreate a missing directory. */
reuseCwd?: string;
}): Promise<string> {
// Files belong to the task, so reassignment preserves the same workspace.
const identities = [input.companyId, input.issueId, ...(input.attemptId ? [input.attemptId] : [])];
let identities = [input.companyId, input.issueId, ...(input.attemptId ? [input.attemptId] : [])];
if (identities.some((value) => !/^[a-zA-Z0-9_-]+$/.test(value))) {
throw new Error("Invalid isolated task workspace identity");
}
const root = resolvePaperclipInstanceRoot();
await mkdir(root, { recursive: true });
if (!input.reuseCwd) await mkdir(root, { recursive: true });
let cwd = await realpath(root);
let namespace = input.attemptId ? "isolated-workspace-attempts" : "isolated-workspaces";
if (input.reuseCwd) {
const segments = path.relative(cwd, input.reuseCwd).split(path.sep);
if (input.attemptId || path.resolve(input.reuseCwd) !== input.reuseCwd ||
segments[1] !== input.companyId || segments[2] !== input.issueId ||
!((segments[0] === "isolated-workspaces" && segments.length === 3) ||
(segments[0] === "isolated-workspace-attempts" && segments.length === 4 && /^[a-zA-Z0-9_-]+$/.test(segments[3])))) {
throw new Error("Isolated task workspace path is not this task's directory");
}
namespace = segments[0];
identities = segments.slice(1);
}
// A retry is a sibling namespace, never a descendant of the retained root.
// An old copyback operation must not be able to overwrite its replacement.
for (const segment of [input.attemptId ? "isolated-workspace-attempts" : "isolated-workspaces", ...identities]) {
for (const segment of [namespace, ...identities]) {
cwd = path.join(cwd, segment);
await mkdir(cwd, { mode: 0o700 }).catch((error: NodeJS.ErrnoException) => {
if (!input.reuseCwd) await mkdir(cwd, { mode: 0o700 }).catch((error: NodeJS.ErrnoException) => {
if (error.code !== "EEXIST") throw error;
});
const stat = await lstat(cwd);
@@ -19,6 +19,7 @@ import {
issueComments,
issues,
issueWorkProducts,
runIdentityContexts,
} from "@paperclipai/db";
import {
@@ -32,8 +33,33 @@ import { loadConfig } from "../../config.js";
import { HttpError } from "../../errors.js";
import { voiceSessionStore, type VoiceTransaction } from "../voice/voice-session-store.js";
import { issueService } from "../issues.js";
import { readInheritedGitHubReviewWait } from "../chat-channels/github/review-wait.js";
import { boundExternalChatProvider } from "./external-chat-provider.js";
import { resolveExternalChatQuestionResponse } from "./external-chat-question-response.js";
import { githubRunReplyState } from "../chat-run-publications.js";
// This boundary reads identity and wake authority, never launch renderings,
// saved provider profiles, or run output. Keep the nested wake proof narrow too.
const responseWaitContextKeys = ["source", "issueId", "wakeReason", "wakeCommentId", "wakeCommentIds",
"interactionId", "interactionKind", "interactionStatus", "sourceRunId", "sourceCommentId",
"externalChatContinuation", "paperclipExternalChatQuestionResponse", "paperclipHarnessCheckedOut",
"paperclipExternalChatExecutionBound"] as const;
const responseWaitRun = {
id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId,
nativeIssueId: heartbeatRuns.nativeIssueId, issueId: heartbeatRuns.issueId, status: heartbeatRuns.status,
responsibleUserId: heartbeatRuns.responsibleUserId, activeIdentityContextId: heartbeatRuns.activeIdentityContextId,
contextSnapshot: sql<Record<string, unknown> | null>`case when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object'
then (select coalesce(jsonb_object_agg(field.key, field.value), '{}'::jsonb)
from jsonb_each(${heartbeatRuns.contextSnapshot}) as field(key, value)
where field.key in (${sql.join(responseWaitContextKeys.map(key => sql`${key}`), sql`, `)}))
|| jsonb_build_object('paperclipWake', jsonb_build_object(
'checkedOutByHarness', ${heartbeatRuns.contextSnapshot}#>'{paperclipWake,checkedOutByHarness}',
'externalChatExecutionBound', ${heartbeatRuns.contextSnapshot}#>'{paperclipWake,externalChatExecutionBound}',
'externalChatProvider', ${heartbeatRuns.contextSnapshot}#>'{paperclipWake,externalChatProvider}',
'issue', jsonb_build_object('id', ${heartbeatRuns.contextSnapshot}#>'{paperclipWake,issue,id}'),
'commentIds', ${heartbeatRuns.contextSnapshot}#>'{paperclipWake,commentIds}'))
else null end`,
};
export const LIST_CHAT_ATTACHMENTS_TOOL_NAME = "list_chat_attachments";
export const REUSE_CHAT_ATTACHMENT_TOOL_NAME = "reuse_chat_attachment";
@@ -652,7 +678,7 @@ export async function resolveExternalChatResponseWaitAuthorizationInTransaction(
: issueQuery.for("update").limit(1));
const runQuery = tx
.select()
.select(responseWaitRun)
.from(heartbeatRuns)
.where(
and(
@@ -684,12 +710,12 @@ export async function resolveExternalChatResponseWaitAuthorizationInTransaction(
!answerContext
)
return "revoked";
const candidate = run
? externalChatWaitCandidate(
answerContext?.authorizationContext ?? run.contextSnapshot,
binding,
)
: null;
const directContext = answerContext?.authorizationContext ?? run?.contextSnapshot;
const inheritedReviewWait = run && !externalChatWaitCandidate(directContext, binding)
? await readInheritedGitHubReviewWait(tx, run) : null;
if (inheritedReviewWait?.kind === "revoked") return "revoked";
const authorizationContext = inheritedReviewWait?.context ?? directContext;
const candidate = run ? externalChatWaitCandidate(authorizationContext, binding) : null;
if (!candidate) return "not_applicable";
const actorQuery = tx
@@ -779,7 +805,7 @@ export async function resolveExternalChatResponseWaitAuthorizationInTransaction(
await authorizeChatConversationForBoundRun(
tx,
binding,
run.contextSnapshot,
authorizationContext,
lockMode,
);
return "authorized";
@@ -811,6 +837,49 @@ export async function resolveExternalChatResponseWaitAuthorization(input: {
);
}
const publishedGitHubReviewWaitKey = "github-review-response:";
export function isPublishedGitHubReviewCompletionContinuation(value: unknown): boolean {
const continuation = record(value);
return continuation.kind === "response_wake" && typeof continuation.idempotencyKey === "string" &&
continuation.idempotencyKey.startsWith(publishedGitHubReviewWaitKey);
}
/** Project a wait from the same saved publication and current authority used
* by finalization. Inherited waits need an accepted tree resume or a confirmed
* reply from this run to its exact current source. An arbitrary old review does
* not assign an unanswered new turn a wait. */
export async function readPublishedGitHubReviewCompletionContinuationInTransaction(
tx: Db, binding: ChatReuseBinding, lockMode: AuthorizationLockMode = "read",
) {
const [run] = await tx.select(responseWaitRun).from(heartbeatRuns).where(and(
eq(heartbeatRuns.id, binding.runId), eq(heartbeatRuns.companyId, binding.companyId),
eq(heartbeatRuns.agentId, binding.agentId), eq(heartbeatRuns.nativeIssueId, binding.issueId),
eq(heartbeatRuns.runtimeMode, "native"),
)).limit(1);
if (!run || run.status !== "running") return null;
const wait = await readInheritedGitHubReviewWait(tx, run);
if (wait?.kind !== "published") return null;
if (wait.reviewRunId !== run.id) {
const [identity] = await tx.select({ cause: runIdentityContexts.cause, parentContextId: runIdentityContexts.parentContextId })
.from(runIdentityContexts).where(and(eq(runIdentityContexts.id, run.activeIdentityContextId!),
eq(runIdentityContexts.companyId, run.companyId), eq(runIdentityContexts.runId, run.id),
eq(runIdentityContexts.status, "accepted"))).limit(1);
const resumed = run.contextSnapshot?.source === "issue.tree_resume" && identity?.cause === "issue_tree_resumed" &&
Boolean(identity.parentContextId);
if (!resumed && !(run.contextSnapshot?.source === "chat:github" &&
await githubRunReplyState(tx, { ...binding, endpointId: wait.endpointId,
sourceCommentId: wait.context.wakeCommentId, requireSettled: true }) === "confirmed")) return null;
}
if (await resolveExternalChatResponseWaitAuthorizationInTransaction(tx, binding, lockMode) !== "authorized") return null;
return { kind: "response_wake" as const, summary: "Wait for the next authorized GitHub response to the published review.",
idempotencyKey: `${publishedGitHubReviewWaitKey}${run.id}:${wait.reviewId}:${wait.headSha}` };
}
export async function readPublishedGitHubReviewCompletionContinuation(input: { db: Db; binding: ChatReuseBinding }) {
return input.db.transaction(tx => readPublishedGitHubReviewCompletionContinuationInTransaction(tx as unknown as Db, input.binding));
}
async function sourceLineageExists(
tx: Db,
binding: ChatReuseBinding,
@@ -1,3 +1,4 @@
import { initializeRunIdentity } from "../run-identity.js";
import { createHash, randomUUID } from "node:crypto";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
@@ -36,12 +37,14 @@ import {
issues,
nativeRunFinalizations,
nativeRunResults,
runIdentityContexts,
statusDecisions,
toolApplications,
toolConnections,
chatVoiceSessions, chatVoiceReplies, chatVoiceToolCalls,
workspaceOperations,
} from "@paperclipai/db";
import { validatePrpStructuredRunResult } from "../../vendor/paperclip-runner/index.js";
import type {
PrpStructuredRunResult,
PrpTerminalState,
@@ -50,7 +53,10 @@ import type {
import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
import { finalizeNativeRun } from "./native-run-finalizer.js";
import { nativeCompletionFeedback } from "./native-completion-feedback.js";
import { hasPublishedGitHubReview } from "../chat-channels/github/review-wait.js";
import { hasPublishedGitHubReview, readInheritedGitHubReviewWait } from "../chat-channels/github/review-wait.js";
import * as chatWaitAuthority from "./chat-attachment-reuse.js";
import * as publishedReviewAuthority from "../chat-channels/github/review-wait.js";
import { toolAccessService } from "../tool-access.js";
import { PaperclipControlPlanePort } from "./paperclip-control-plane-port.js";
import {
authorizeNativeChatReviewPresentation,
@@ -114,6 +120,8 @@ describe("native external-chat response wait", () => {
| "slack" = "telegram",
attentionRequests: PrpStructuredRunResult["attentionRequests"] = [],
resultOverrides: Partial<PrpStructuredRunResult> = {},
deferCompletion = false,
contractOverride?: { objective: string; criteria: Array<{ id: string; requirement: string }> },
) {
const companyId = randomUUID();
const agentId = randomUUID();
@@ -177,6 +185,7 @@ describe("native external-chat response wait", () => {
criteria: [
{ id: "response", requirement: "Return the requested photo" },
],
...contractOverride,
},
canonicalSha256: contractSha256,
createdByActorType: "system",
@@ -384,7 +393,7 @@ describe("native external-chat response wait", () => {
workAssessmentId: randomUUID(),
statusDecisionId: randomUUID(),
};
await port.completeRun({
if (!deferCompletion) await port.completeRun({
result,
terminal,
callerResultId: `wait-result-${runId}`,
@@ -401,6 +410,7 @@ describe("native external-chat response wait", () => {
.where(eq(heartbeatRuns.id, runId));
return {
port, result, terminal,
agentId,
companyId,
conversationId,
@@ -4385,7 +4395,14 @@ describe("native external-chat response wait", () => {
[5, "done", "done", null, false],
[3, "yielded", "in_review", "monitor", false],
[3, "yielded", "in_review", "response_wake", true],
] as const)("settles a published %s/5 review reporting %s in %s with %s, separate approval: %s", async (score, disposition, status, continuationKind, separateApproval) => {
[3, "yielded", "in_review", "response_wake", false, "tree_resume"],
[3, "yielded", "in_review", "response_wake", false, "continued_review"],
[3, "yielded", "in_review", "monitor", false, "continued_review"],
[3, "yielded", "in_progress", "response_wake", false, "new_head"],
] as const)("settles a published %s/5 review reporting %s in %s with %s, separate approval: %s, resume: %s", async (score, disposition, status, continuationKind, separateApproval, resumeMode?: "tree_resume" | "continued_review" | "new_head") => {
const resumed = resumeMode !== undefined;
const savedPublication = resumeMode === "continued_review" || resumeMode === "new_head";
const unreviewedHead = resumeMode === "new_head";
const fixture = await seedWaitTurn("github", [], {
reportedWorkDisposition: disposition,
summary: disposition === "done" ? "Review is 5/5 and required checks passed." : "Review published; waiting for the next PR update.",
@@ -4394,7 +4411,7 @@ describe("native external-chat response wait", () => {
});
await db.update(issues).set({ title: "Review the pull request", originKind: "chat_channel",
createdByUserId: fixture.userId, responsibleUserId: fixture.userId }).where(eq(issues.id, fixture.issueId));
const oldRequest = score === 3 ? await seedPriorCompletionReview(fixture) : null;
const oldRequest = score === 3 && !resumed ? await seedPriorCompletionReview(fixture) : null;
if (continuationKind === "monitor") {
await new PaperclipRunnerToolAuthority(db, fixture).execute({ tool: "set_task_monitor", callId: randomUUID(),
arguments: { idempotencyKey: "review-monitor", monitor: { nextCheckAt: new Date(Date.now() + 60_000).toISOString(), notes: "Check PR status." } } });
@@ -4417,7 +4434,7 @@ describe("native external-chat response wait", () => {
}).returning();
await expect(hasPublishedGitHubReview(db, fixture)).resolves.toBe(false);
// A completed but unpublished head must not hide another published head from this run.
const [published] = await db.insert(chatGitHubReviews).values({ ...review!, id: randomUUID(), deliveryId: randomUUID(), headSha: "c".repeat(40) }).returning();
const [published] = await db.insert(chatGitHubReviews).values({ ...review!, id: randomUUID(), deliveryId: randomUUID(), headSha: "c".repeat(40), assessment: { ...review!.assessment!, reviewedCommit: "c".repeat(40) }, createdAt: new Date(Date.now() + 10) }).returning();
await db.insert(chatActions).values({
companyId: fixture.companyId, endpointId: fixture.endpointId, kind: "github_review_publication",
providerActionId: `github_publication:${fixture.issueId}:assessment:${createHash("sha256").update(JSON.stringify(published!.id)).digest("hex")}`,
@@ -4433,8 +4450,76 @@ describe("native external-chat response wait", () => {
providerActionId: `github_publication:${fixture.issueId}:assessment:${createHash("sha256").update(JSON.stringify(older!.id)).digest("hex")}`,
});
}
let inheritedOriginalRunId: string | null = null;
if (resumed) {
await db.update(chatEndpointResources).set({ metadata: { providerRepositoryId: "1" } }).where(eq(chatEndpointResources.id, fixture.resourceId));
await db.update(chatConversations).set({ externalThreadId: "github:paperclip/test-repository:1" }).where(eq(chatConversations.id, fixture.conversationId));
// A tree resume inherits its requester through the accepted identity
// ledger, while its immediate wake correctly has no chat envelope.
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId));
const originalRunId = randomUUID();
inheritedOriginalRunId = originalRunId;
await db.insert(heartbeatRuns).values({ ...run!, id: originalRunId, activeIdentityContextId: null, status: "succeeded", finishedAt: new Date() });
const [origin] = await db.insert(runIdentityContexts).values({
companyId: fixture.companyId, runId: originalRunId, revision: 1,
messageId: fixture.commentId, responsibleUserId: fixture.userId,
cause: "chat_message", correlationId: "dispatch", status: "accepted",
}).returning();
const [continuation] = await db.insert(runIdentityContexts).values({
companyId: fixture.companyId, runId: fixture.runId, revision: 1,
parentContextId: origin!.id, responsibleUserId: fixture.userId,
cause: "issue_tree_resumed", correlationId: "dispatch", status: "accepted",
}).returning();
await db.update(heartbeatRuns).set({ activeIdentityContextId: continuation!.id,
responsibleUserId: fixture.userId, contextSnapshot: {
source: "issue.tree_resume", wakeReason: "issue_tree_resumed",
issueId: fixture.issueId, paperclipHarnessCheckedOut: true,
paperclipWake: { checkedOutByHarness: true, issue: { id: fixture.issueId }, commentIds: [] },
},
}).where(eq(heartbeatRuns.id, fixture.runId));
}
await expect(hasPublishedGitHubReview(db, fixture)).resolves.toBe(true);
await expect(hasPublishedGitHubReview(db, { ...fixture, runId: randomUUID() })).resolves.toBe(false);
if (resumed) {
const [inheritedRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId));
await expect(readInheritedGitHubReviewWait(db, inheritedRun!)).resolves.toMatchObject({ kind: "published" });
await expect(resolveExternalChatResponseWaitAuthorization({ db, binding: fixture })).resolves.toBe("authorized");
for (const binding of [
{ ...fixture, companyId: randomUUID() }, { ...fixture, issueId: randomUUID() },
{ ...fixture, agentId: randomUUID() },
]) await expect(resolveExternalChatResponseWaitAuthorization({ db, binding })).resolves.not.toBe("authorized");
await db.update(chatActions).set({ status: "pending" }).where(eq(chatActions.companyId, fixture.companyId));
await expect(resolveExternalChatResponseWaitAuthorization({ db, binding: fixture })).resolves.not.toBe("authorized");
await db.update(chatActions).set({ status: "processed" }).where(eq(chatActions.companyId, fixture.companyId));
await db.update(chatEndpointResources).set({ enabled: false }).where(eq(chatEndpointResources.endpointId, fixture.endpointId));
await expect(resolveExternalChatResponseWaitAuthorization({ db, binding: fixture })).resolves.toBe("revoked");
await db.update(chatEndpointResources).set({ enabled: true }).where(eq(chatEndpointResources.endpointId, fixture.endpointId));
await db.update(heartbeatRuns).set({ responsibleUserId: "different-requester" }).where(eq(heartbeatRuns.id, fixture.runId));
await expect(resolveExternalChatResponseWaitAuthorization({ db, binding: fixture })).resolves.not.toBe("authorized");
await db.update(heartbeatRuns).set({ responsibleUserId: fixture.userId }).where(eq(heartbeatRuns.id, fixture.runId));
await db.update(chatConversations).set({ externalThreadId: "github:paperclip/other-repository:1" }).where(eq(chatConversations.id, fixture.conversationId));
await expect(resolveExternalChatResponseWaitAuthorization({ db, binding: fixture })).resolves.not.toBe("authorized");
await db.update(chatConversations).set({ externalThreadId: "github:paperclip/test-repository:1" }).where(eq(chatConversations.id, fixture.conversationId));
await db.update(chatEndpointResources).set({ metadata: { providerRepositoryId: "2" } }).where(eq(chatEndpointResources.id, fixture.resourceId));
await expect(resolveExternalChatResponseWaitAuthorization({ db, binding: fixture })).resolves.not.toBe("authorized");
await db.update(chatEndpointResources).set({ metadata: { providerRepositoryId: "1" } }).where(eq(chatEndpointResources.id, fixture.resourceId));
const [newHead] = await db.insert(chatGitHubReviews).values({ ...review!, id: randomUUID(),
deliveryId: randomUUID(), runId: null, headSha: "d".repeat(40), state: "queued", createdAt: new Date(Date.now() + 1000),
}).returning();
await expect(resolveExternalChatResponseWaitAuthorization({ db, binding: fixture })).resolves.not.toBe("authorized");
await db.delete(chatGitHubReviews).where(eq(chatGitHubReviews.id, newHead!.id));
if (savedPublication) {
await db.update(chatGitHubReviews).set({ runId: inheritedOriginalRunId }).where(eq(chatGitHubReviews.issueId, fixture.issueId));
await expect(hasPublishedGitHubReview(db, fixture)).resolves.toBe(false);
await expect(resolveExternalChatResponseWaitAuthorization({ db, binding: fixture })).resolves.toBe("authorized");
}
}
if (unreviewedHead) {
await db.insert(chatGitHubReviews).values({ ...review!, id: randomUUID(), runId: null,
deliveryId: randomUUID(), headSha: "e".repeat(40), state: "queued", createdAt: new Date(Date.now() + 1000),
});
await expect(resolveExternalChatResponseWaitAuthorization({ db, binding: fixture })).resolves.toBe("revoked");
}
const [stored] = await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, fixture.runId));
await expect(nativeCompletionFeedback(db, fixture.runId, stored!.resultJson.result as PrpStructuredRunResult)).resolves.toContain("accepted");
if (oldRequest) {
@@ -4468,6 +4553,15 @@ describe("native external-chat response wait", () => {
if (oldRequest) expect(await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, oldRequest.id)))
.toEqual([expect.objectContaining({ status: "cancelled", result: expect.objectContaining({ outcome: "withdrawn" }) })]);
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, fixture.companyId))).toEqual([]);
if (resumed) {
await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, fixture.companyId))).toEqual([]);
expect(await db.select().from(chatActions).where(and(eq(chatActions.companyId, fixture.companyId), eq(chatActions.kind, "github_review_publication")))).toHaveLength(1);
if (unreviewedHead) {
expect((await db.select().from(statusDecisions).where(eq(statusDecisions.runId, fixture.runId)))[0])
.toMatchObject({ reasonCode: "external_chat_response_wait_authorization_lost" });
}
}
if (status === "in_review" && continuationKind === "response_wake") {
const attention = async () => (await issueService(db).listReviewAttention(fixture.companyId, [{ id: fixture.issueId, companyId: fixture.companyId, status }])).get(fixture.issueId)?.state;
await db.update(chatEndpointResources).set({ enabled: false }).where(eq(chatEndpointResources.endpointId, fixture.endpointId));
@@ -4483,6 +4577,397 @@ describe("native external-chat response wait", () => {
}
});
async function seedPublishedReviewCompletionTurn(contractOverride?: Parameters<typeof seedWaitTurn>[4]) {
const fixture = await seedWaitTurn("github", [], {}, true, contractOverride);
await db.update(chatEndpointResources).set({ metadata: { providerRepositoryId: "1" } })
.where(eq(chatEndpointResources.id, fixture.resourceId));
await db.update(chatConversations).set({ externalThreadId: "github:paperclip/test-repository:1" })
.where(eq(chatConversations.id, fixture.conversationId));
const [identity] = await db.insert(runIdentityContexts).values({ companyId: fixture.companyId,
runId: fixture.runId, revision: 1, messageId: fixture.commentId, responsibleUserId: fixture.userId,
cause: "chat_message", correlationId: "dispatch", status: "accepted" }).returning();
await db.update(heartbeatRuns).set({ activeIdentityContextId: identity!.id, responsibleUserId: fixture.userId })
.where(eq(heartbeatRuns.id, fixture.runId));
const [review] = await db.insert(chatGitHubReviews).values({ companyId: fixture.companyId,
endpointId: fixture.endpointId, issueId: fixture.issueId, runId: fixture.runId,
repositoryId: "1", repository: "paperclip/test-repository", pullNumber: 1, headSha: "a".repeat(40),
deliveryId: fixture.deliveryId, configurationRevision: 1, policySnapshot: defaultGitHubReviewPolicy(),
event: { event: "opened", deliveryId: fixture.deliveryId, repositoryId: "1", repository: "paperclip/test-repository",
pullNumber: 1, title: "Review", body: "", baseSha: "b".repeat(40), headSha: "a".repeat(40),
baseBranch: "master", author: { id: "1", login: "author", isBot: false }, sender: { id: "1", login: "author" }, draft: false, labels: [] },
state: "completed", assessment: { complete: true, score: 3, reviewedCommit: "a".repeat(40),
summary: "Quantity is ignored", rationale: "Review complete", findings: [],
coverage: { reviewedPaths: [], omittedPaths: [], limitations: [] } }, checkId: "123" }).returning();
await db.insert(chatActions).values({ companyId: fixture.companyId, endpointId: fixture.endpointId,
kind: "github_review_publication", status: "processed", payload: { operation: "assessment", reviewId: review!.id },
providerActionId: `github_publication:${fixture.issueId}:assessment:${createHash("sha256").update(JSON.stringify(review!.id)).digest("hex")}` });
return { ...fixture, review: review! };
}
it.each([false, true])("binds a low-score Retry wait to its accepted newer source after a predecessor failed before identity: %s", async acceptedSource => {
const objective = "Review the current head. A lower score stays In review with a passive response wake; only a merged PR or 5/5 with passing checks is Done.";
const fixture = await seedPublishedReviewCompletionTurn({ objective,
criteria: [{ id: "response", requirement: objective }] });
await db.update(chatGitHubReviews).set({ policySnapshot: { ...fixture.review.policySnapshot, ratingThreshold: 5 },
assessment: { ...fixture.review.assessment!, score: 2 } }).where(eq(chatGitHubReviews.id, fixture.review.id));
const previousRunId = randomUUID();
await db.insert(heartbeatRuns).values({ id: previousRunId, companyId: fixture.companyId, agentId: fixture.agentId,
issueId: fixture.issueId, status: "failed", errorCode: "chat_failed_run_retry_not_authorized",
finishedAt: new Date(), contextSnapshot: { issueId: fixture.issueId, source: "chat:github" } });
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId));
await db.update(heartbeatRuns).set({ activeIdentityContextId: null, retryOfRunId: previousRunId,
contextSnapshot: { ...run!.contextSnapshot, retryOfRunId: previousRunId, wakeReason: "retry_failed_run" } })
.where(eq(heartbeatRuns.id, fixture.runId));
await db.delete(runIdentityContexts).where(eq(runIdentityContexts.id, run!.activeIdentityContextId!));
await initializeRunIdentity(db, { companyId: fixture.companyId, issueId: fixture.issueId,
runId: fixture.runId, responsibleUserId: fixture.userId, parentRunId: previousRunId,
messageIds: acceptedSource ? [fixture.commentId] : [], cause: "retry_failed_run" });
const authority = new PaperclipRunnerToolAuthority(db, fixture);
const read = () => authority.execute({ tool: "get_task_context", callId: randomUUID(), arguments: {} });
const { resolveCompletionContinuation } = await import(new URL("../../../../packages/paperclip-runner/src/drivers/completion-continuation.ts", import.meta.url).href);
const report = { ...fixture.result, continuation: undefined, completionClaim: {
...fixture.result.completionClaim, objectiveSatisfied: false,
criteria: [{ criterionId: "response", status: "unknown" as const, evidenceRefs: [] }],
remainingWork: [{ description: "Author must fix the quantity defect before this review can reach the passing score.", blocksCompletion: true }],
} };
if (!acceptedSource) {
await expect(resolveCompletionContinuation(report, fixture.runId, read)).rejects.toThrow("no eligible saved monitor");
expect((await db.select().from(issues).where(eq(issues.id, fixture.issueId)))[0].status).not.toBe("done");
return;
}
const resolved = await resolveCompletionContinuation(report, fixture.runId, read) as PrpStructuredRunResult;
expect(resolved).toMatchObject({ reportedWorkDisposition: "yielded", continuation: { kind: "response_wake" } });
await expect(nativeCompletionFeedback(db, fixture.runId, resolved)).resolves.toContain("accepted");
await fixture.port.completeRun({ result: resolved, terminal: fixture.terminal, callerResultId: `retry-wait-${fixture.runId}` });
await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
expect((await db.select().from(issues).where(eq(issues.id, fixture.issueId)))[0]).toMatchObject({ status: "in_review" });
expect((await db.select().from(statusDecisions).where(eq(statusDecisions.runId, fixture.runId)))[0])
.toMatchObject({ reasonCode: "external_chat_response_waiting", toStatus: "in_review", decisionJson: { effects: [] } });
await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, fixture.companyId))).toHaveLength(0);
expect(await db.select().from(chatActions).where(and(eq(chatActions.companyId, fixture.companyId),
eq(chatActions.kind, "github_review_publication")))).toHaveLength(1);
});
async function seedInheritedReviewCompletionTurn(resume: boolean) {
const fixture = await seedPublishedReviewCompletionTurn();
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId));
const predecessorId = randomUUID();
await db.insert(heartbeatRuns).values({ ...run!, id: predecessorId, activeIdentityContextId: null,
status: "succeeded", finishedAt: new Date() });
await db.update(chatGitHubReviews).set({ runId: predecessorId }).where(eq(chatGitHubReviews.id, fixture.review.id));
if (resume) {
const [origin] = await db.insert(runIdentityContexts).values({ companyId: fixture.companyId,
runId: predecessorId, revision: 1, messageId: fixture.commentId, responsibleUserId: fixture.userId,
cause: "chat_message", correlationId: "dispatch", status: "accepted" }).returning();
await db.update(runIdentityContexts).set({ messageId: null, parentContextId: origin!.id,
cause: "issue_tree_resumed" }).where(eq(runIdentityContexts.id, run!.activeIdentityContextId!));
await db.update(heartbeatRuns).set({ contextSnapshot: { source: "issue.tree_resume", wakeReason: "issue_tree_resumed",
issueId: fixture.issueId, paperclipHarnessCheckedOut: true,
paperclipWake: { checkedOutByHarness: true, issue: { id: fixture.issueId }, commentIds: [] } },
}).where(eq(heartbeatRuns.id, fixture.runId));
}
return { ...fixture, predecessorId };
}
it.each([undefined, null, "malformed-first"] as const)("derives an omitted inherited GitHub review wait after normal tree resume: %s", async absent => {
const fixture = await seedInheritedReviewCompletionTurn(true);
const authority = new PaperclipRunnerToolAuthority(db, fixture);
const read = () => authority.execute({ tool: "get_task_context", callId: randomUUID(), arguments: {} });
const { resolveCompletionContinuation } = await import(new URL("../../../../packages/paperclip-runner/src/drivers/completion-continuation.ts", import.meta.url).href);
const report = { ...fixture.result, continuation: absent === "malformed-first" ? "response_wake" : absent };
if (absent === "malformed-first") {
expect(await resolveCompletionContinuation(report, fixture.runId, read)).toEqual(report);
expect(validatePrpStructuredRunResult(report).ok).toBe(false);
delete report.continuation;
}
const resolved = await resolveCompletionContinuation(report, fixture.runId, read) as PrpStructuredRunResult;
expect(resolved).toMatchObject({ reportedWorkDisposition: "yielded", continuation: { kind: "response_wake" } });
await expect(nativeCompletionFeedback(db, fixture.runId, resolved)).resolves.toContain("accepted");
await fixture.port.completeRun({ result: resolved, terminal: fixture.terminal, callerResultId: `wait-result-${fixture.runId}` });
await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
expect((await db.select().from(issues).where(eq(issues.id, fixture.issueId)))[0]).toMatchObject({ status: "in_review" });
expect((await db.select().from(statusDecisions).where(eq(statusDecisions.runId, fixture.runId)))[0])
.toMatchObject({ reasonCode: "external_chat_response_waiting", decisionJson: { effects: [] } });
await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, fixture.companyId))).toHaveLength(0);
expect(await db.select().from(chatActions).where(and(eq(chatActions.companyId, fixture.companyId),
eq(chatActions.kind, "github_review_publication")))).toHaveLength(1);
});
async function seedCurrentAuthorReply(fixture: Awaited<ReturnType<typeof seedInheritedReviewCompletionTurn>>) {
const [reply] = await db.insert(chatActions).values({ companyId: fixture.companyId,
endpointId: fixture.endpointId, conversationId: fixture.conversationId, deliveryId: fixture.deliveryId,
kind: "github_review_publication", status: "processed", providerActionId: `github_publication:${fixture.issueId}:comment:${randomUUID()}`,
payload: { operation: "comment", session: { companyId: fixture.companyId, issueId: fixture.issueId,
runId: fixture.runId, agentId: fixture.agentId }, body: "Quantity is ignored by the current total calculation." },
result: { id: "123", url: "https://github.com/paperclip/test-repository/pull/1#issuecomment-123" },
}).returning();
return reply!;
}
it.each([undefined, null] as const)("derives an omitted inherited review wait only after this author reply is delivered: %s", async continuation => {
const fixture = await seedInheritedReviewCompletionTurn(false);
await seedCurrentAuthorReply(fixture);
const authority = new PaperclipRunnerToolAuthority(db, fixture);
const { resolveCompletionContinuation } = await import(new URL("../../../../packages/paperclip-runner/src/drivers/completion-continuation.ts", import.meta.url).href);
const resolved = await resolveCompletionContinuation({ ...fixture.result, continuation }, fixture.runId,
() => authority.execute({ tool: "get_task_context", callId: randomUUID(), arguments: {} })) as PrpStructuredRunResult;
expect(resolved).toMatchObject({ continuation: { kind: "response_wake" } });
await expect(nativeCompletionFeedback(db, fixture.runId, resolved)).resolves.toContain("accepted");
await fixture.port.completeRun({ result: resolved, terminal: fixture.terminal, callerResultId: `wait-result-${fixture.runId}` });
await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
expect((await db.select().from(issues).where(eq(issues.id, fixture.issueId)))[0]).toMatchObject({ status: "in_review" });
expect((await db.select().from(statusDecisions).where(eq(statusDecisions.runId, fixture.runId)))[0])
.toMatchObject({ reasonCode: "external_chat_response_waiting", decisionJson: { effects: [] } });
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, fixture.companyId))).toHaveLength(0);
});
it.each(["missing_parent", "wrong_cause", "principal_revoked", "new_head", "pending_publication"] as const)(
"does not derive an inherited tree resume wait after %s", async gate => {
const fixture = await seedInheritedReviewCompletionTurn(true);
if (gate === "missing_parent" || gate === "wrong_cause") await db.update(runIdentityContexts)
.set(gate === "missing_parent" ? { parentContextId: null } : { cause: "chat_message" })
.where(eq(runIdentityContexts.runId, fixture.runId));
if (gate === "principal_revoked") await db.update(companyMemberships).set({ status: "suspended" })
.where(eq(companyMemberships.companyId, fixture.companyId));
if (gate === "new_head") await db.insert(chatGitHubReviews).values({ ...fixture.review, id: randomUUID(),
runId: null, deliveryId: randomUUID(), headSha: "c".repeat(40), state: "queued", assessment: null,
createdAt: new Date(Date.now() + 1000) });
if (gate === "pending_publication") await db.update(chatActions).set({ status: "received" })
.where(eq(chatActions.companyId, fixture.companyId));
const context = new PaperclipRunnerToolAuthority(db, fixture)
.execute({ tool: "get_task_context", callId: randomUUID(), arguments: {} });
if (gate === "principal_revoked") await expect(context).rejects.toThrow("task is no longer available");
else expect(await context).toMatchObject({ completionContinuation: null });
});
it.each(["missing", "pending", "unknown", "mixed_unknown", "mixed_missing_assessment", "other_run", "other_source", "ack_only", "partial_assessment", "new_head", "revoked"] as const)(
"does not derive an inherited author reply wait after %s", async gate => {
const fixture = await seedInheritedReviewCompletionTurn(false);
const reply = await seedCurrentAuthorReply(fixture);
if (gate === "missing") await db.delete(chatActions).where(eq(chatActions.id, reply.id));
if (gate === "pending" || gate === "unknown") await db.update(chatActions)
.set({ status: gate === "pending" ? "received" : "failed", result: { deliveryUnknown: true } })
.where(eq(chatActions.id, reply.id));
if (gate === "mixed_unknown") await db.insert(chatActions).values({ ...reply, id: randomUUID(),
providerActionId: `github_publication:${randomUUID()}`, status: "failed", result: { deliveryUnknown: true } });
if (gate === "mixed_missing_assessment") await db.insert(chatActions).values({ ...reply, id: randomUUID(),
providerActionId: `github_publication:${randomUUID()}`, payload: { ...reply.payload,
operation: "assessment", reviewId: fixture.review.id }, result: { published: 1, total: 2 } });
if (gate === "other_run") await db.update(chatActions).set({ payload: { ...reply.payload,
session: { companyId: fixture.companyId, issueId: fixture.issueId, runId: fixture.predecessorId, agentId: fixture.agentId } } })
.where(eq(chatActions.id, reply.id));
if (gate === "other_source") {
const [source] = await db.select().from(chatDeliveries).where(eq(chatDeliveries.id, fixture.deliveryId));
const [other] = await db.insert(chatDeliveries).values({ ...source!, id: randomUUID(), providerEventId: randomUUID(), deduplicationKey: randomUUID() }).returning();
await db.update(chatActions).set({ deliveryId: other!.id }).where(eq(chatActions.id, reply.id));
}
if (gate === "partial_assessment") {
const [partial] = await db.insert(chatGitHubReviews).values({ ...fixture.review, id: randomUUID(),
runId: fixture.runId, deliveryId: randomUUID(), createdAt: new Date(Date.now() - 86_400_000), publicationReceipts: {
partial: { id: "123", url: "https://github.com/paperclip/test-repository/pull/1#issuecomment-123", digest: "partial" },
} }).returning();
await db.update(chatActions).set({ status: "failed", payload: { ...reply.payload,
operation: "assessment", reviewId: partial!.id }, result: { code: "publication_failed" } })
.where(eq(chatActions.id, reply.id));
}
if (gate === "ack_only") await db.update(chatActions).set({ kind: "github_response_comment" })
.where(eq(chatActions.id, reply.id));
if (gate === "new_head") await db.insert(chatGitHubReviews).values({ ...fixture.review, id: randomUUID(),
runId: null, deliveryId: randomUUID(), headSha: "c".repeat(40), state: "queued", assessment: null,
createdAt: new Date(Date.now() + 1000) });
if (gate === "revoked") await db.update(toolConnections).set({ enabled: false })
.where(eq(toolConnections.companyId, fixture.companyId));
const context = await new PaperclipRunnerToolAuthority(db, fixture)
.execute({ tool: "get_task_context", callId: randomUUID(), arguments: {} });
expect(context).toMatchObject({ completionContinuation: null });
});
it.each(["current", "resume", "reply"] as const)("projects only bound authority while deriving a published GitHub completion wait: %s", async turn => {
const fixture = turn === "current" ? await seedPublishedReviewCompletionTurn() : await seedInheritedReviewCompletionTurn(turn === "resume");
const reply = turn === "reply" ? await seedCurrentAuthorReply(fixture as Awaited<ReturnType<typeof seedInheritedReviewCompletionTurn>>) : null;
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId));
const payload = "unused-saved-review-rendering".repeat(32768);
await db.update(heartbeatRuns).set({ runnerProfileJson: { retained: payload }, stdoutExcerpt: payload, stderrExcerpt: payload,
contextSnapshot: { ...run.contextSnapshot, executionContinuation: { savedInput: payload },
paperclipTaskMarkdown: payload, paperclipWake: { ...(run.contextSnapshot!.paperclipWake as object), retainedPayload: payload } },
}).where(eq(heartbeatRuns.id, fixture.runId));
if (reply) await db.update(chatActions).set({ result: { ...reply.result, savedProviderOutput: payload } }).where(eq(chatActions.id, reply.id));
const observed = createDb(temporary?.connectionString ?? externalTestDatabaseUrl!);
const events: Array<Record<string, unknown>> = [], now = Date.now();
const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event));
installDatabaseResponseCapture(observed, { heartbeatRuns, chatActions }, capture);
try {
const context = await new PaperclipRunnerToolAuthority(observed, fixture)
.execute({ tool: "get_task_context", callId: randomUUID(), arguments: {} });
expect(context).toMatchObject({ completionContinuation: { kind: "response_wake" } });
capture.flush();
const reads = events.filter(event => event.table === "heartbeat_runs" && event.operation === "select");
expect(reads.length).toBeGreaterThan(0);
expect(reads.reduce((bytes, event) => bytes + Number(event.responseValueBytes), 0)).toBeLessThan(16 * 1024);
const actionReads = events.filter(event => event.table === "chat_actions" && event.operation === "select");
expect(actionReads.reduce((bytes, event) => bytes + Number(event.responseValueBytes), 0)).toBeLessThan(16 * 1024);
expect(JSON.stringify(context)).not.toContain(payload);
} finally { capture.flush(); await observed.$client.end(); }
});
it.each([undefined, null, "malformed-first"] as const)("derives an omitted published GitHub review wait through current task context: %s", async absent => {
const fixture = await seedPublishedReviewCompletionTurn();
const authority = new PaperclipRunnerToolAuthority(db, fixture);
const read = () => authority.execute({ tool: "get_task_context", callId: randomUUID(), arguments: {} });
const { resolveCompletionContinuation } = await import(new URL("../../../../packages/paperclip-runner/src/drivers/completion-continuation.ts", import.meta.url).href);
const report = { ...fixture.result, continuation: absent === "malformed-first" ? "response_wake" : absent };
if (absent === "malformed-first") {
// Explicit malformed input remains invalid; the next omitted report can
// recover from authoritative state without changing its disposition.
expect(await resolveCompletionContinuation(report, fixture.runId, read)).toEqual(report);
expect(validatePrpStructuredRunResult(report).ok).toBe(false);
delete report.continuation;
}
const resolved = await resolveCompletionContinuation(report, fixture.runId, read) as PrpStructuredRunResult;
expect(resolved).toMatchObject({ reportedWorkDisposition: "yielded", continuation: { kind: "response_wake" } });
await expect(nativeCompletionFeedback(db, fixture.runId, resolved)).resolves.toContain("accepted");
await fixture.port.completeRun({ result: resolved, terminal: fixture.terminal, callerResultId: `wait-result-${fixture.runId}` });
await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
expect((await db.select().from(issues).where(eq(issues.id, fixture.issueId)))[0]).toMatchObject({ status: "in_review" });
expect((await db.select().from(statusDecisions).where(eq(statusDecisions.runId, fixture.runId)))[0])
.toMatchObject({ reasonCode: "external_chat_response_waiting", decisionJson: { effects: [] } });
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, fixture.companyId))).toHaveLength(0);
});
it.each(["missing_publication", "pending_publication", "unknown_publication", "new_head", "other_run", "review_mismatch", "principal_revoked", "connection_revoked", "endpoint_revoked", "ownership_changed"] as const)(
"does not derive a published GitHub completion wait after %s", async gate => {
const fixture = await seedPublishedReviewCompletionTurn();
if (gate === "missing_publication") await db.delete(chatActions).where(eq(chatActions.companyId, fixture.companyId));
if (gate === "pending_publication" || gate === "unknown_publication") await db.update(chatActions)
.set({ status: gate === "pending_publication" ? "received" : "failed", result: { deliveryUnknown: true } })
.where(eq(chatActions.companyId, fixture.companyId));
if (gate === "new_head") await db.insert(chatGitHubReviews).values({ ...fixture.review, id: randomUUID(),
runId: null, deliveryId: randomUUID(), headSha: "c".repeat(40), state: "queued", assessment: null,
createdAt: new Date(Date.now() + 1000) });
if (gate === "other_run") {
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId));
const previousId = randomUUID();
await db.insert(heartbeatRuns).values({ ...run!, id: previousId, activeIdentityContextId: null,
status: "succeeded", finishedAt: new Date() });
await db.update(chatGitHubReviews).set({ runId: previousId }).where(eq(chatGitHubReviews.id, fixture.review.id));
}
if (gate === "review_mismatch") await db.update(chatGitHubReviews).set({ assessment: {
...fixture.review.assessment!, reviewedCommit: "f".repeat(40),
} }).where(eq(chatGitHubReviews.id, fixture.review.id));
if (gate === "principal_revoked") await db.update(companyMemberships).set({ status: "suspended" })
.where(eq(companyMemberships.companyId, fixture.companyId));
if (gate === "connection_revoked") await db.update(toolConnections).set({ enabled: false })
.where(eq(toolConnections.companyId, fixture.companyId));
if (gate === "endpoint_revoked") await db.update(chatEndpoints).set({ status: "revoked" })
.where(eq(chatEndpoints.id, fixture.endpointId));
if (gate === "ownership_changed") await db.update(issues).set({ executionRunId: null })
.where(eq(issues.id, fixture.issueId));
const authority = new PaperclipRunnerToolAuthority(db, fixture);
const { resolveCompletionContinuation } = await import(new URL("../../../../packages/paperclip-runner/src/drivers/completion-continuation.ts", import.meta.url).href);
await expect(resolveCompletionContinuation({ ...fixture.result, continuation: undefined }, fixture.runId,
() => authority.execute({ tool: "get_task_context", callId: randomUUID(), arguments: {} }))).rejects.toThrow();
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, fixture.companyId))).toHaveLength(0);
},
);
it("serializes an actual connection disable against the final status committer proof", async () => {
const fixture = await seedPublishedReviewCompletionTurn();
const authority = new PaperclipRunnerToolAuthority(db, fixture);
const { resolveCompletionContinuation } = await import(new URL("../../../../packages/paperclip-runner/src/drivers/completion-continuation.ts", import.meta.url).href);
const result = await resolveCompletionContinuation({ ...fixture.result, continuation: null }, fixture.runId,
() => authority.execute({ tool: "get_task_context", callId: randomUUID(), arguments: {} })) as PrpStructuredRunResult;
await nativeCompletionFeedback(db, fixture.runId, result);
await fixture.port.completeRun({ result, terminal: fixture.terminal, callerResultId: `wait-result-${fixture.runId}` });
const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.companyId, fixture.companyId));
const applicationName = `review-wait-race-${fixture.runId}`;
const writerDb = createDb(externalTestDatabaseUrl ?? temporary!.connectionString, { applicationName });
let writer: Promise<unknown> | undefined;
let writerFinished = false, serialized = false;
const readProof = publishedReviewAuthority.readInheritedGitHubReviewWait;
const readForCommit = chatWaitAuthority.readPublishedGitHubReviewCompletionContinuationInTransaction;
const commitGuard = vi.spyOn(chatWaitAuthority, "readPublishedGitHubReviewCompletionContinuationInTransaction")
.mockImplementationOnce(async (...args) => {
const [committer] = await args[0].execute(sql`select pg_backend_pid() as pid`);
const proofGuard = vi.spyOn(publishedReviewAuthority, "readInheritedGitHubReviewWait")
.mockImplementationOnce(async (...proofArgs) => {
const proof = await readProof(...proofArgs);
// This is the same maintained writer used by PATCH tool-connections.
// It does not borrow the task's issue lock to disable a chat connection.
writer = toolAccessService(writerDb).updateConnection(connection!.id, { enabled: false })
.finally(() => { writerFinished = true; });
await vi.waitFor(async () => {
const waiting = await db.execute(sql`select query from pg_stat_activity
where application_name = ${applicationName} and wait_event_type = 'Lock'`);
expect(writerFinished || waiting.length > 0).toBe(true);
if (waiting.length) expect(String(waiting[0]!.query)).toContain('update "tool_connections"');
serialized = !writerFinished && waiting.length > 0;
if (serialized) {
const blockers = await db.execute(sql`select pg_blocking_pids(pid) as blockers from pg_stat_activity where application_name = ${applicationName} and wait_event_type = 'Lock'`);
expect(blockers[0]!.blockers).toContain(Number(committer!.pid));
}
});
return proof;
});
try { return await readForCommit(...args); }
finally { proofGuard.mockRestore(); }
});
try {
await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
await writer;
expect(serialized).toBe(true);
expect((await db.select().from(issues).where(eq(issues.id, fixture.issueId)))[0]).toMatchObject({ status: "in_review" });
expect((await db.select().from(toolConnections).where(eq(toolConnections.id, connection!.id)))[0]).toMatchObject({ enabled: false });
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, fixture.companyId))).toHaveLength(0);
} finally { commitGuard.mockRestore(); await Promise.allSettled(writer ? [writer] : []); await writerDb.$client.end({ timeout: 1 }); }
});
it.each((["current", "resume", "reply"] as const).flatMap(turn =>
(["before_feedback", "before_finalization", "during_commit"] as const).map(phase => ({ turn, phase }))))(
"rechecks a projected GitHub completion wait $turn $phase", async ({ turn, phase }) => {
const fixture = turn === "current" ? await seedPublishedReviewCompletionTurn() : await seedInheritedReviewCompletionTurn(turn === "resume");
const reply = turn === "reply" ? await seedCurrentAuthorReply(fixture as Awaited<ReturnType<typeof seedInheritedReviewCompletionTurn>>) : null;
const authority = new PaperclipRunnerToolAuthority(db, fixture);
const { resolveCompletionContinuation } = await import(new URL("../../../../packages/paperclip-runner/src/drivers/completion-continuation.ts", import.meta.url).href);
const result = await resolveCompletionContinuation({ ...fixture.result, continuation: null }, fixture.runId,
() => authority.execute({ tool: "get_task_context", callId: randomUUID(), arguments: {} })) as PrpStructuredRunResult;
const revoke = () => reply
? db.update(chatActions).set({ status: "failed", result: { deliveryUnknown: true } }).where(eq(chatActions.id, reply.id))
: turn === "resume" ? db.update(chatActions).set({ status: "received" }).where(eq(chatActions.companyId, fixture.companyId))
: db.update(toolConnections).set({ enabled: false }).where(eq(toolConnections.companyId, fixture.companyId));
if (phase === "before_feedback") {
await revoke();
await expect(nativeCompletionFeedback(db, fixture.runId, result)).rejects.toThrow("no longer authorized");
return;
}
await nativeCompletionFeedback(db, fixture.runId, result);
await fixture.port.completeRun({ result, terminal: fixture.terminal, callerResultId: `wait-result-${fixture.runId}` });
let guard: ReturnType<typeof vi.spyOn> | undefined;
if (phase === "before_finalization") await revoke();
if (phase === "during_commit") {
const read = chatWaitAuthority.readPublishedGitHubReviewCompletionContinuationInTransaction;
guard = vi.spyOn(chatWaitAuthority, "readPublishedGitHubReviewCompletionContinuationInTransaction")
.mockImplementation(async (...args) => {
if (reply) await args[0].update(chatActions).set({ status: "failed", result: { deliveryUnknown: true } }).where(eq(chatActions.id, reply.id));
else if (turn === "resume") await args[0].update(chatActions).set({ status: "received" }).where(eq(chatActions.companyId, fixture.companyId));
else await args[0].update(toolConnections).set({ enabled: false }).where(eq(toolConnections.companyId, fixture.companyId));
return read(...args);
});
}
try {
const finalized = await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
expect((await db.select().from(issues).where(eq(issues.id, fixture.issueId)))[0]).toMatchObject({ status: "in_progress" });
const decisions = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, fixture.runId));
if (phase === "during_commit") {
expect(finalized).toMatchObject({ phase: "retryable_failure" });
expect(decisions).toHaveLength(0);
} else expect(decisions.at(-1)).toMatchObject({ reasonCode: "external_chat_response_wait_authorization_lost" });
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, fixture.companyId))).toHaveLength(0);
} finally { guard?.mockRestore(); }
},
);
it("admits a real repository-access request to Mine until it is resolved", async () => {
const fixture = await seedWaitTurn("github", [{ kind: "approval", ownerClass: "human", summary: "Grant repository access so I can read the diff." }], {
reportedWorkDisposition: "needs_review", continuation: undefined,
@@ -1,5 +1,6 @@
import { and, eq, inArray, sql } from "drizzle-orm";
import { chatConversations, chatEndpoints, heartbeatRuns, issues, statusDecisions, type Db } from "@paperclipai/db";
import { readInheritedGitHubReviewWait } from "../chat-channels/github/review-wait.js";
import { authorizeChatConversationForBoundRun } from "./chat-attachment-reuse.js";
import { EXTERNAL_CHAT_QUESTION_RESPONSE_KEY } from "./external-chat-question-response.js";
@@ -30,6 +31,8 @@ export async function listExternalReviewWaits(db: Db, companyId: string, issueId
runId: heartbeatRuns.id,
agentId: heartbeatRuns.agentId,
contextSnapshot: authorizationContext,
responsibleUserId: heartbeatRuns.responsibleUserId,
activeIdentityContextId: heartbeatRuns.activeIdentityContextId,
}).from(issues)
.innerJoin(statusDecisions, and(
eq(statusDecisions.id, issues.lastStatusDecisionId),
@@ -58,9 +61,14 @@ export async function listExternalReviewWaits(db: Db, companyId: string, issueId
eq(chatEndpoints.status, "active"),
))
.where(and(eq(issues.companyId, companyId), inArray(issues.id, issueIds), eq(issues.status, "in_review")));
const waits = await Promise.all(candidates.map(async ({ runId, agentId, contextSnapshot, ...wait }) => {
const waits = await Promise.all(candidates.map(async ({ runId, agentId, contextSnapshot, responsibleUserId, activeIdentityContextId, ...wait }) => {
try {
await authorizeChatConversationForBoundRun(db, { companyId, issueId: wait.issueId, runId, agentId }, contextSnapshot, "read");
const inheritedWait = await readInheritedGitHubReviewWait(db, {
id: runId, companyId, agentId, responsibleUserId, activeIdentityContextId,
nativeIssueId: wait.issueId, issueId: wait.issueId, contextSnapshot,
});
if (inheritedWait?.kind === "revoked") return null;
await authorizeChatConversationForBoundRun(db, { companyId, issueId: wait.issueId, runId, agentId }, inheritedWait?.context ?? contextSnapshot, "read");
return wait;
} catch (error) {
if (error instanceof Error && ["paperclip_runner_chat_attachment_binding_denied",
@@ -9,7 +9,7 @@ import { evaluateAgentInvokabilityFromDb } from "../agent-invokability.js";
import { issueService } from "../issues.js";
import { isConversation } from "../agent-conversations.js";
import { issueTreeControlService } from "../issue-tree-control.js";
import { resolveExternalChatResponseWaitAuthorization } from "./chat-attachment-reuse.js";
import { isPublishedGitHubReviewCompletionContinuation, readPublishedGitHubReviewCompletionContinuation, resolveExternalChatResponseWaitAuthorization } from "./chat-attachment-reuse.js";
import { getNativeReviewAssignment, readNativeReviewAssignmentContext } from "./native-review-participant.js";
import { and, eq, inArray, notInArray } from "drizzle-orm";
import {
@@ -68,6 +68,12 @@ export async function nativeCompletionFeedback(
)
.then((rows) => rows[0]);
if (!issue) throw new Error("Completion task no longer exists.");
if (result.reportedWorkDisposition === "yielded" && isPublishedGitHubReviewCompletionContinuation(result.continuation)) {
const current = await readPublishedGitHubReviewCompletionContinuation({ db,
binding: { companyId: run.companyId, issueId: issue.id, runId, agentId: run.agentId } });
if (!current || current.idempotencyKey !== result.continuation!.idempotencyKey)
throw new Error("The published GitHub review wait is no longer authorized for this run. Reassess current task state without repeating the published review.");
}
const acceptedHandoff = await assertNativeCaseHandoffResult(db, runId, issue.id, result);
if (acceptedHandoff) return "The persisted case handoff controls this turn. End the turn; the task remains open for its next agent.";
const reviewContext = readNativeReviewAssignmentContext(run.contextSnapshot);
@@ -4,7 +4,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { activityLog, agents, companies, createDb, environmentLeases, environments, externalAgentHolds, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations } from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
import { getExecutionBlocker } from "../execution-blocker.js";
import { markExecutionReconciliation, validateExecutionReconciliation } from "../execution-recovery-resolution.js";
import { markExecutionReconciliation, settleUnrecoverableExecutions, validateExecutionReconciliation } from "../execution-recovery-resolution.js";
import { prepareSandboxStopAndRetain, settleStopOnlyCleanup } from "../sandbox-stop-and-retain.js";
import { preserveCancelledNativeWorkspaces, preserveNativeFailedWorkspace } from "./native-failed-workspace-recovery.js";
import type { NativeRestartRecoveryClaim } from "./native-restart-recovery.js";
@@ -51,6 +51,44 @@ const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTes
const readLease = async (id: string) => (await db.select().from(environmentLeases).where(eq(environmentLeases.id, id)))[0]!;
const actions = async (issueId: string) => db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId));
it.each(["settled", "historical", "live_owner", "retry", "nonterminal", "wrong_wake", "wrong_hold_run", "no_hold"])("retires only an exact superseded native resume obligation: %s", async scenario => {
const f = await seed(), actionId = randomUUID();
await db.insert(issueRecoveryActions).values({ id: actionId, companyId: f.companyId, sourceIssueId: f.issueId,
kind: "active_run_watchdog", status: "active", ownerType: "agent", ownerAgentId: f.agentId,
returnOwnerAgentId: f.agentId, cause: "native_session_interrupted", fingerprint: randomUUID(),
evidence: { runId: f.runId }, nextAction: "Resume the exact persisted session.",
wakePolicy: { kind: "resume_native_run", runId: f.runId }, attemptCount: 1, maxAttempts: 3 });
await preserveNativeFailedWorkspace(db, f.run);
const hold = (await actions(f.issueId)).find(action => action.id !== actionId)!;
expect(hold.evidence.automaticRecovery).toMatchObject({ replay: "blocked", actionOutcome: "unknown" });
if (scenario === "live_owner") await db.update(nativeRunFinalizations).set({ leaseOwner: "live-controller" }).where(eq(nativeRunFinalizations.runId, f.runId));
if (scenario === "retry") await db.update(nativeRunFinalizations).set({ nextAttemptAt: new Date(Date.now() + 60_000) }).where(eq(nativeRunFinalizations.runId, f.runId));
if (scenario === "nonterminal") await db.update(nativeRunFinalizations).set({ phase: "observed" }).where(eq(nativeRunFinalizations.runId, f.runId));
if (scenario === "wrong_wake") await db.update(issueRecoveryActions).set({ wakePolicy: { kind: "resume_native_run", runId: randomUUID() } }).where(eq(issueRecoveryActions.id, actionId));
if (scenario === "wrong_hold_run") await db.update(issueRecoveryActions).set({ evidence: { ...hold.evidence, runId: randomUUID() } }).where(eq(issueRecoveryActions.id, hold.id));
if (scenario === "no_hold") await db.delete(issueRecoveryActions).where(eq(issueRecoveryActions.id, hold.id));
const beforeRun = await readRun(f.runId), beforeLease = await readLease(f.lease.id);
const beforeBlocker = await getExecutionBlocker(db, f.companyId, f.issueId);
const [beforeTask] = await db.select().from(issues).where(eq(issues.id, f.issueId));
await settleUnrecoverableExecutions(db);
if (scenario === "historical") await settleUnrecoverableExecutions(db);
const retired = (await actions(f.issueId)).find(action => action.id === actionId)!;
const shouldRetire = scenario === "settled" || scenario === "historical";
expect(retired.status).toBe(shouldRetire ? "cancelled" : "active");
if (shouldRetire) {
expect(retired).toMatchObject({ outcome: "cancelled", wakePolicy: null,
evidence: { runId: f.runId, supersedingRecoveryActionId: hold.id } });
expect((await actions(f.issueId)).find(action => action.id === hold.id)).toEqual(hold);
expect(await db.select().from(activityLog).where(and(eq(activityLog.entityId, f.issueId),
eq(activityLog.action, "issue.execution_recovery_settled")))).toHaveLength(1);
}
expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toEqual(beforeBlocker);
expect(await readRun(f.runId)).toEqual(beforeRun);
expect(await readLease(f.lease.id)).toEqual(beforeLease);
expect((await db.select().from(issues).where(eq(issues.id, f.issueId)))[0]).toEqual(beforeTask);
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, f.companyId))).toHaveLength(1);
});
it.each(["acknowledged", "warm", "pending", "foreign", "owned"])("pins historical cancelled work only after an exact Stop acknowledgement: %s", async kind => {
const f = await seed();
if (kind === "warm") await db.update(environmentLeases).set({ leasePolicy: "reuse_by_environment" }).where(eq(environmentLeases.id, f.lease.id));
Loaded 100 of 355 files, more files were not shown because too many files have changed in this diff. Show more