Merge updated Dot base and current task authority into capabilities

Preserve private task filtering and task monitors, keep independent Dot opt-in, and regenerate the combined tool catalog and seeded protocol fixture.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-07 18:45:10 -05:00
commit 80e3534cf6
520 files changed
+96019 -4755

No files matched your search

@@ -42,6 +42,14 @@ vi.mock("../services/index.js", () => ({
heartbeatService: () => mockHeartbeatService,
}));
vi.mock("../services/authorization.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../services/authorization.js")>();
return {
...actual,
issueReadSqlCondition: vi.fn(async () => ({}) as any),
};
});
vi.mock("../services/agent-action-audit.js", () => ({
agentActionAuditService: () => mockAgentActionAuditService,
}));
@@ -219,6 +227,7 @@ describe("activity routes", () => {
entityType: undefined,
entityId: undefined,
limit: 100,
readCondition: expect.anything(),
});
});
@@ -237,6 +246,7 @@ describe("activity routes", () => {
entityType: "issue",
entityId: undefined,
limit: 500,
readCondition: expect.anything(),
});
});
@@ -19,6 +19,7 @@ import {
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import { activityService } from "../services/activity.ts";
import { issueReadSqlCondition } from "../services/authorization.ts";
import { issueService } from "../services/issues.ts";
import { documentService } from "../services/documents.ts";
@@ -150,6 +151,54 @@ describeEmbeddedPostgres("activity service", () => {
expect(result.map((event) => event.action)).toEqual(["test.newest", "test.middle"]);
});
it("filters company activity rows whose entity is a private issue", async () => {
const companyId = randomUUID();
const privateIssueId = randomUUID();
const openIssueId = randomUUID();
await db.insert(companies).values({
id: companyId,
name: "Private activity",
issuePrefix: `A${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
});
await db.insert(issues).values([
{
id: privateIssueId,
companyId,
title: "Confidential activity",
status: "todo",
priority: "medium",
visibility: "private",
privacyRootIssueId: privateIssueId,
responsibleUserId: "private-owner",
},
{
id: openIssueId,
companyId,
title: "Open activity",
status: "todo",
priority: "medium",
},
]);
await db.insert(activityLog).values([
{ companyId, actorType: "system", actorId: "system", action: "private.changed", entityType: "issue", entityId: privateIssueId },
{ companyId, actorType: "system", actorId: "system", action: "open.changed", entityType: "issue", entityId: openIssueId },
]);
const actor = {
type: "board" as const,
userId: "non-member",
companyIds: [companyId],
source: "session" as const,
isInstanceAdmin: false,
};
const rows = await activityService(db).list({
companyId,
readCondition: await issueReadSqlCondition(db, actor),
});
expect(rows.map((row) => row.action)).toContain("open.changed");
expect(rows.map((row) => row.action)).not.toContain("private.changed");
});
it.each([null, "native_provider_model_rejected", "adapter_failed"])("returns compact issue runs with bounded model rejection details: %s", async (errorCode) => {
const companyId = randomUUID();
const agentId = randomUUID();
@@ -175,10 +224,21 @@ describeEmbeddedPostgres("activity service", () => {
permissions: {},
});
await db.insert(issues).values({
id: issueId,
companyId,
title: "Summarize a completed run",
status: "done",
priority: "medium",
assigneeAgentId: agentId,
});
await db.insert(heartbeatRuns).values({
id: runId,
companyId,
agentId,
scopeKind: "issue",
issueId,
invocationSource: "assignment",
status: errorCode ? "failed" : "succeeded",
errorCode,
@@ -295,6 +355,8 @@ describeEmbeddedPostgres("activity service", () => {
id: runId,
companyId,
agentId,
scopeKind: "issue",
issueId,
invocationSource: "assignment",
status: "succeeded",
startedAt: new Date("2026-04-18T20:00:00.000Z"),
@@ -389,6 +451,8 @@ describeEmbeddedPostgres("activity service", () => {
id: runId,
companyId,
agentId,
scopeKind: "issue",
issueId,
invocationSource: "assignment",
status: "succeeded",
startedAt: new Date("2026-04-18T20:00:00.000Z"),
@@ -404,6 +468,8 @@ describeEmbeddedPostgres("activity service", () => {
id: otherRunId,
companyId,
agentId,
scopeKind: "issue",
issueId,
invocationSource: "assignment",
status: "succeeded",
startedAt: new Date("2026-04-18T20:05:00.000Z"),
@@ -511,6 +577,8 @@ describeEmbeddedPostgres("activity service", () => {
id: runId,
companyId,
agentId,
scopeKind: "issue",
issueId,
invocationSource: "assignment",
status: "succeeded",
startedAt: new Date("2026-04-18T20:10:00.000Z"),
@@ -29,6 +29,8 @@ const cases: Array<{ name: string; execute: () => Promise<Execute>; event: unkno
];
describe("CLI adapter accounting on timeout", () => {
// Keep OpenCode runtime config copies inside each fixture; host config may
// include plugins and large dependency trees unrelated to accounting.
const directories: string[] = [];
afterEach(async () => { vi.clearAllMocks(); for (const dir of directories.splice(0)) await rm(dir, { recursive: true, force: true }); });
it.each(cases.filter(f => ["codex", "cursor", "opencode"].includes(f.name)))("$name preserves malformed optional counters through the checkpoint wrapper", async fixture => {
@@ -49,7 +51,7 @@ describe("CLI adapter accounting on timeout", () => {
runId: "invalid-counter-run", agent: { id: "agent", companyId: "company", name: "Worker", adapterType: `${fixture.name}_local`, adapterConfig: {} },
runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: null },
config: { engine: "cli", command, cwd: dir, model: fixture.name === "opencode" ? "openai/test" : "gpt-6-astra", paperclipRuntimeSkills: [],
env: { OPENAI_API_KEY: "fixture", OPENCODE_ALLOW_ALL_MODELS: "1" } },
env: { XDG_CONFIG_HOME: dir, OPENAI_API_KEY: "fixture", OPENCODE_ALLOW_ALL_MODELS: "1" } },
context: {}, onLog: async () => {}, onUsage,
});
const valid = cached === 0 || cached === undefined;
@@ -77,7 +79,7 @@ describe("CLI adapter accounting on timeout", () => {
runId: "test-run", agent: { id: "test-agent", companyId: "test-company", name: "Accounting", adapterType: `${fixture.name}_local`, adapterConfig: {} },
runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: null },
config: { engine: "cli", command, cwd: dir, model: ["opencode", "pi"].includes(fixture.name) ? "openai/test" : fixture.name === "cursor" ? "gpt-5" : "test", paperclipRuntimeSkills: [],
env: { OPENAI_API_KEY: "test-placeholder", ANTHROPIC_API_KEY: "test-placeholder", GEMINI_API_KEY: "test-placeholder", OPENCODE_ALLOW_ALL_MODELS: "1", CLAUDE_CONFIG_DIR: dir } },
env: { XDG_CONFIG_HOME: dir, OPENAI_API_KEY: "test-placeholder", ANTHROPIC_API_KEY: "test-placeholder", GEMINI_API_KEY: "test-placeholder", OPENCODE_ALLOW_ALL_MODELS: "1", CLAUDE_CONFIG_DIR: dir } },
context: {}, onLog: async () => {}, onUsage,
};
const execute = await fixture.execute();
@@ -211,7 +213,7 @@ describe("CLI adapter accounting on timeout", () => {
const result = await execute({
runId: "tail-run", agent: { id: "test-agent", companyId: "test-company", name: "Accounting", adapterType: `${fixture.name}_local`, adapterConfig: {} },
runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: null },
config: { engine: "cli", command, cwd: dir, model: "anthropic/test", paperclipRuntimeSkills: [], env: { ANTHROPIC_API_KEY: "fixture", OPENAI_BASE_URL: "https://unrelated-proxy.example/v1", OPENROUTER_API_KEY: "unrelated-key", OPENCODE_ALLOW_ALL_MODELS: "1" } },
config: { engine: "cli", command, cwd: dir, model: "anthropic/test", paperclipRuntimeSkills: [], env: { XDG_CONFIG_HOME: dir, ANTHROPIC_API_KEY: "fixture", OPENAI_BASE_URL: "https://unrelated-proxy.example/v1", OPENROUTER_API_KEY: "unrelated-key", OPENCODE_ALLOW_ALL_MODELS: "1" } },
context: {}, onLog: async () => {}, onUsage,
});
expect(result.usage).toMatchObject({ inputTokens: 40, outputTokens: 20, cachedInputTokens: 200 });
@@ -231,7 +233,7 @@ describe("CLI adapter accounting on timeout", () => {
runId: "test-run", agent: { id: "test-agent", companyId: "test-company", name: "Accounting", adapterType: `${fixture.name}_local`, adapterConfig: {} },
runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: null },
config: { engine: "cli", command, cwd: dir, model: ["opencode", "pi"].includes(fixture.name) ? "openai/test" : fixture.name === "cursor" ? "gpt-5" : "test", paperclipRuntimeSkills: [],
env: { OPENAI_API_KEY: "test-placeholder", ANTHROPIC_API_KEY: "test-placeholder", GEMINI_API_KEY: "test-placeholder", MOONSHOT_API_KEY: "test-placeholder", OPENCODE_ALLOW_ALL_MODELS: "1", CLAUDE_CONFIG_DIR: dir } },
env: { XDG_CONFIG_HOME: dir, OPENAI_API_KEY: "test-placeholder", ANTHROPIC_API_KEY: "test-placeholder", GEMINI_API_KEY: "test-placeholder", MOONSHOT_API_KEY: "test-placeholder", OPENCODE_ALLOW_ALL_MODELS: "1", CLAUDE_CONFIG_DIR: dir } },
context: {}, onLog: async () => {},
});
expect(result.timedOut).toBe(true);
@@ -354,6 +354,8 @@ describe("agent live run routes", () => {
mockHeartbeatService.getRunLogAccess.mockResolvedValue({
id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
companyId: "company-1",
scopeKind: "company",
issueId: null,
logStore: "local_file",
logRef: "logs/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa.ndjson",
});
@@ -598,6 +600,8 @@ describe("agent live run routes", () => {
{
id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
companyId: "company-1",
scopeKind: "company",
issueId: null,
logStore: "local_file",
logRef: "logs/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa.ndjson",
},
@@ -687,7 +691,8 @@ describe("agent live run routes", () => {
lastOutputStream: null,
lastOutputBytes: 0,
processStartedAt: null,
issueId: "issue-1",
scopeKind: "company",
issueId: null,
}));
const { db, limit } = createLiveRunsDbStub(rows);
@@ -731,7 +736,8 @@ describe("agent live run routes", () => {
lastOutputStream: null,
lastOutputBytes: 0,
processStartedAt: null,
issueId: "issue-1",
scopeKind: "company",
issueId: null,
}));
const { db, limit } = createLiveRunsDbStub(rows);
@@ -774,7 +780,8 @@ describe("agent live run routes", () => {
lastOutputStream: null,
lastOutputBytes: 0,
processStartedAt: null,
issueId: "issue-1",
scopeKind: "company",
issueId: null,
}));
const selectCalls: Array<ReturnType<typeof vi.fn>> = [];
@@ -834,7 +841,8 @@ describe("agent live run routes", () => {
lastOutputStream: null,
lastOutputBytes: 0,
processStartedAt: null,
issueId: "issue-1",
scopeKind: "company",
issueId: null,
}));
const recentRows = Array.from({ length: 4 }, (_, index) => ({
id: `run-recent-${index}`,
@@ -861,7 +869,8 @@ describe("agent live run routes", () => {
lastOutputStream: null,
lastOutputBytes: 0,
processStartedAt: null,
issueId: "issue-1",
scopeKind: "company",
issueId: null,
}));
let selectCallCount = 0;
@@ -1251,7 +1251,7 @@ describe("agent permission routes", () => {
expect.objectContaining({
status: "idle",
}),
{ claudeLogin: { storedSessionId: null, ownerUserId: "agent-admin-user", applyExistingWithoutClaim: false } },
{ createdByUserId: "agent-admin-user", claudeLogin: { storedSessionId: null, ownerUserId: "agent-admin-user", applyExistingWithoutClaim: false } },
);
expect(mockAccessService.setPrincipalPermission).toHaveBeenCalledWith(
companyId,
@@ -1381,7 +1381,7 @@ describe("agent permission routes", () => {
},
},
}),
{ claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
{ createdByUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
);
});
@@ -1417,7 +1417,7 @@ describe("agent permission routes", () => {
model: DEFAULT_OPENCODE_LOCAL_MODEL,
}),
}),
{ claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
{ createdByUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
);
});
@@ -1455,7 +1455,7 @@ describe("agent permission routes", () => {
model: "anthropic/claude-sonnet-4-5",
}),
}),
{ claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
{ createdByUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
);
});
@@ -1495,6 +1495,7 @@ describe("agent permission routes", () => {
},
}),
{
createdByUserId: "board-user",
claudeLogin: {
storedSessionId: null,
ownerUserId: "board-user",
@@ -1725,7 +1726,7 @@ describe("agent permission routes", () => {
expect.objectContaining({
defaultEnvironmentId: environmentId,
}),
{ claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
{ createdByUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
);
});
@@ -1811,7 +1812,7 @@ describe("agent permission routes", () => {
adapterType: adapterCase.adapterType,
defaultEnvironmentId: environmentId,
}),
{ claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
{ createdByUserId: "board-user", claudeLogin: { storedSessionId: null, ownerUserId: "board-user", applyExistingWithoutClaim: false } },
);
});
}
@@ -1005,7 +1005,7 @@ describe("agent skill routes", () => {
}),
}),
}),
{ claudeLogin: { storedSessionId: null, ownerUserId: "local-board", applyExistingWithoutClaim: false } },
{ createdByUserId: "local-board", claudeLogin: { storedSessionId: null, ownerUserId: "local-board", applyExistingWithoutClaim: false } },
);
expect(mockTrackAgentCreated).toHaveBeenCalledWith(
expect.anything(),
@@ -1055,7 +1055,7 @@ describe("agent skill routes", () => {
expect.objectContaining({
role: "security",
}),
{ claudeLogin: { storedSessionId: null, ownerUserId: "local-board", applyExistingWithoutClaim: false } },
{ createdByUserId: "local-board", claudeLogin: { storedSessionId: null, ownerUserId: "local-board", applyExistingWithoutClaim: false } },
);
expect(mockTrackAgentCreated).toHaveBeenCalledWith(
expect.anything(),
@@ -1491,6 +1491,7 @@ describe("agent skill routes", () => {
}),
}),
{
createdByUserId: "local-board",
claudeLogin: {
storedSessionId: null,
ownerUserId: "local-board",
@@ -34,6 +34,10 @@ const mockAccessService = vi.hoisted(() => ({
}));
function registerModuleMocks() {
vi.doMock("../services/authorization.js", async (importActual) => ({
...await importActual<typeof import("../services/authorization.js")>(),
canActorReadApproval: async () => true,
}));
vi.doMock("../services/index.js", () => ({
accessService: () => mockAccessService,
approvalService: () => mockApprovalService,
+23 -4
View File
@@ -1,5 +1,11 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { approvalService } from "../services/approvals.ts";
import { companies } from "@paperclipai/db";
vi.mock("../services/budgets.js", () => ({
budgetService: () => ({ deliverPendingEnforcement: vi.fn(async () => {}) }),
budgetServiceInTransaction: () => ({ upsertPolicy: vi.fn(async () => {}) }),
}));
const mockAgentService = vi.hoisted(() => ({
activatePendingApproval: vi.fn(),
@@ -24,6 +30,7 @@ type ApprovalRecord = {
status: string;
payload: Record<string, unknown>;
requestedByAgentId: string | null;
requestedByUserId?: string | null;
};
function createApproval(status: string): ApprovalRecord {
@@ -39,8 +46,11 @@ function createApproval(status: string): ApprovalRecord {
function createDbStub(selectResults: ApprovalRecord[][], updateResults: ApprovalRecord[]) {
const pendingSelectResults = [...selectResults];
const selectWhere = vi.fn(async () => pendingSelectResults.shift() ?? []);
const from = vi.fn(() => ({ where: selectWhere }));
let inTransaction = false;
const selectWhere = vi.fn(async () => (inTransaction ? pendingSelectResults.shift() : pendingSelectResults[0]) ?? []);
const from = vi.fn((table) => table === companies
? { where: () => ({ for: async () => [{ id: "company-1" }] }) }
: { where: selectWhere });
const select = vi.fn(() => ({ from }));
const returning = vi.fn(async () => updateResults);
@@ -49,7 +59,10 @@ function createDbStub(selectResults: ApprovalRecord[][], updateResults: Approval
const update = vi.fn(() => ({ set }));
return {
db: { select, update, transaction: vi.fn(async (callback: (db: unknown) => Promise<unknown>) => callback({ select, update })) },
db: { select, update, transaction: vi.fn(async (callback: (db: unknown) => Promise<unknown>) => {
inTransaction = true;
try { return await callback({ select, update }); } finally { inTransaction = false; }
}) },
selectWhere,
returning,
};
@@ -116,9 +129,14 @@ describe("approvalService resolution idempotency", () => {
expect(mockNotifyHireApproved).not.toHaveBeenCalled();
});
it("creates the agent from payload when approval does not reference a pending agent", async () => {
it.each([
{ requestedByAgentId: "requester-1", requestedByUserId: "on-behalf-user", expectedCreator: null },
{ requestedByAgentId: null, requestedByUserId: "original-creator", expectedCreator: "original-creator" },
])("creates a legacy approved hire with its original human attribution ($expectedCreator)", async ({ requestedByAgentId, requestedByUserId, expectedCreator }) => {
const approved = {
...createApproval("approved"),
requestedByAgentId,
requestedByUserId,
payload: {
name: "New Agent",
adapterConfig: {
@@ -143,6 +161,7 @@ describe("approvalService resolution idempotency", () => {
expect.objectContaining({
adapterConfig: approved.payload.adapterConfig,
}),
{ createdByUserId: expectedCreator },
);
});
});
+1 -1
View File
@@ -103,7 +103,7 @@ async function createApp(storage: ReturnType<typeof createStorageService>) {
};
next();
});
app.use("/api", assetRoutes({} as any, storage));
app.use("/api", assetRoutes({ select: () => ({ from: () => ({ leftJoin: () => ({ where: async () => [] }), where: async () => [] }) }) } as any, storage));
return app;
}
@@ -172,6 +172,9 @@ describeEmbeddedPostgres("attention service", () => {
createdAt?: Date;
unblockDescriptor?: { owner: { userId: string } | "board"; action: string } | null;
blockedTransitionAt?: Date | null;
visibility?: "open" | "private";
privacyRootIssueId?: string | null;
responsibleUserId?: string | null;
harnessKind?: string | null;
reviewPolicy?: "anyone" | "not_creator" | "human_only" | null;
}) {
@@ -195,6 +198,9 @@ describeEmbeddedPostgres("attention service", () => {
executionState: input.executionState ?? null,
unblockDescriptor: input.unblockDescriptor ?? null,
blockedTransitionAt: input.blockedTransitionAt ?? null,
visibility: input.visibility ?? "open",
privacyRootIssueId: input.privacyRootIssueId ?? null,
responsibleUserId: input.responsibleUserId ?? null,
harnessKind: input.harnessKind ?? null,
createdAt: input.createdAt,
updatedAt: input.updatedAt,
@@ -2040,6 +2046,35 @@ describeEmbeddedPostgres("attention service", () => {
await request(app(agent)).get(`/api/companies/${companyId}/attention`).expect(403);
});
it("omits private issue review items for a non-member board user", async () => {
const { companyId } = await seedCompany("ATP");
const privateIssueId = randomUUID();
await insertIssue({
id: privateIssueId,
companyId,
identifier: "ATP-1",
title: "Confidential review",
status: "in_review",
assigneeUserId: "private-owner",
executionState: pendingUserExecutionState("private-owner"),
visibility: "private",
privacyRootIssueId: privateIssueId,
responsibleUserId: "private-owner",
});
const actor = {
type: "board" as const,
source: "session" as const,
userId: "non-member",
companyIds: [companyId],
isInstanceAdmin: false,
};
const feed = await attentionService(db).list(companyId, { userId: actor.userId, actor });
expect(feed.items.map((item) => item.subject.title)).not.toContain("Confidential review");
expect(JSON.stringify(feed)).not.toContain(privateIssueId);
});
it("computes the aging shelf uniformly across approval, interaction, and review sources", async () => {
const { companyId, workerId } = await seedCompany("AGE");
const now = Date.parse("2026-08-02T12:00:00.000Z");
@@ -1,6 +1,6 @@
import { randomUUID } from "node:crypto";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import { and, eq } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
agents,
authUsers,
@@ -8,9 +8,11 @@ import {
companyMemberships,
createDb,
instanceUserRoles,
issueAccessGrants,
issueComments,
issues,
principalPermissionGrants,
projectAccessMembers,
projects,
userInboxAgentPolicies,
} from "@paperclipai/db";
@@ -19,7 +21,13 @@ import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import { authorizationService } from "../services/authorization.js";
import {
authorizationService,
canActorReadIssuePrivacy,
issuePrivacyMode,
type AuthorizationActor,
} from "../services/authorization.js";
import { logger } from "../middleware/logger.js";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
@@ -56,12 +64,18 @@ async function createAgent(
.then((rows) => rows[0]!);
}
async function createProject(db: ReturnType<typeof createDb>, companyId: string, label: string) {
async function createProject(
db: ReturnType<typeof createDb>,
companyId: string,
label: string,
visibility: "open" | "private" = "open",
) {
return db
.insert(projects)
.values({
companyId,
name: `Project ${label} ${randomUUID()}`,
visibility,
})
.returning()
.then((rows) => rows[0]!);
@@ -76,6 +90,12 @@ async function createIssue(
projectId?: string | null;
parentId?: string | null;
assigneeAgentId?: string | null;
assigneeUserId?: string | null;
createdByUserId?: string | null;
responsibleUserId?: string | null;
visibility?: "open" | "private";
privacyRootIssueId?: string | null;
privacyParentIssueId?: string | null;
originKind?: string | null;
originId?: string | null;
} = {},
@@ -91,6 +111,12 @@ async function createIssue(
projectId: input.projectId ?? null,
parentId: input.parentId ?? null,
assigneeAgentId: input.assigneeAgentId ?? null,
assigneeUserId: input.assigneeUserId ?? null,
createdByUserId: input.createdByUserId ?? null,
responsibleUserId: input.responsibleUserId ?? null,
visibility: input.visibility ?? "open",
privacyRootIssueId: input.privacyRootIssueId ?? null,
privacyParentIssueId: input.privacyParentIssueId ?? null,
originKind: input.originKind ?? "manual",
originId: input.originId ?? null,
})
@@ -167,6 +193,21 @@ describeEmbeddedPostgres("authorization service", () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
it("defaults issue privacy to enforce while retaining explicit rollout overrides", () => {
const previousMode = process.env.PAPERCLIP_ISSUE_PRIVACY_MODE;
try {
delete process.env.PAPERCLIP_ISSUE_PRIVACY_MODE;
expect(issuePrivacyMode()).toBe("enforce");
process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = "shadow";
expect(issuePrivacyMode()).toBe("shadow");
process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = "off";
expect(issuePrivacyMode()).toBe("off");
} finally {
if (previousMode === undefined) delete process.env.PAPERCLIP_ISSUE_PRIVACY_MODE;
else process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = previousMode;
}
});
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-authorization-service-");
db = createDb(tempDb.connectionString);
@@ -178,6 +219,7 @@ describeEmbeddedPostgres("authorization service", () => {
await db.delete(principalPermissionGrants);
await db.delete(companyMemberships);
await db.delete(instanceUserRoles);
await db.delete(issueAccessGrants);
await db.delete(issues);
await db.delete(agents);
await db.delete(projects);
@@ -2744,6 +2786,199 @@ describeEmbeddedPostgres("authorization service", () => {
})).resolves.toMatchObject({ allowed: false, reason: "deny_low_trust_boundary" });
});
it("enforces private issue implicit principals, grants, revocation, and subtree inheritance", async () => {
const previousMode = process.env.PAPERCLIP_ISSUE_PRIVACY_MODE;
const previousTtl = process.env.PAPERCLIP_ISSUE_PRIVACY_CACHE_TTL_MS;
process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = "enforce";
process.env.PAPERCLIP_ISSUE_PRIVACY_CACHE_TTL_MS = "5000";
try {
const company = await createCompany(db, "IssuePrivacy");
const ownerId = await createUser(db);
const memberId = await createUser(db);
const granteeId = await createUser(db);
await db.insert(companyMemberships).values([ownerId, memberId, granteeId].map((principalId) => ({
companyId: company.id,
principalType: "user",
principalId,
status: "active",
membershipRole: "operator",
})));
const assignedAgent = await createAgent(db, company.id);
const otherAgent = await createAgent(db, company.id);
const authz = authorizationService(db);
const userActor = (userId: string): AuthorizationActor => ({ type: "board", userId, source: "session" });
const agentActor = (agentId: string): AuthorizationActor => ({
type: "agent",
agentId,
companyId: company.id,
source: "agent_key",
});
const decide = (actor: AuthorizationActor, issue: Awaited<ReturnType<typeof createIssue>>) => authz.decide({
actor,
action: "issue:read",
resource: { type: "issue", companyId: company.id, issueId: issue.id },
});
const openIssue = await createIssue(db, company.id);
await expect(decide(userActor(memberId), openIssue)).resolves.toMatchObject({ allowed: true });
const privateRootId = randomUUID();
const privateRoot = await createIssue(db, company.id, {
id: privateRootId,
visibility: "private",
privacyRootIssueId: privateRootId,
responsibleUserId: ownerId,
assigneeAgentId: assignedAgent.id,
});
await expect(decide(userActor(memberId), privateRoot)).resolves.toMatchObject({
allowed: false,
reason: "deny_issue_private",
});
await expect(decide(agentActor(otherAgent.id), privateRoot)).resolves.toMatchObject({
allowed: false,
reason: "deny_issue_private",
});
await expect(decide(userActor(ownerId), privateRoot)).resolves.toMatchObject({ allowed: true });
await expect(decide(agentActor(assignedAgent.id), privateRoot)).resolves.toMatchObject({ allowed: true });
const grant = await db.insert(issueAccessGrants).values({
issueId: privateRoot.id,
subjectType: "user",
subjectId: granteeId,
source: "explicit",
grantedByUserId: ownerId,
}).returning().then((rows) => rows[0]!);
await expect(decide(userActor(granteeId), privateRoot)).resolves.toMatchObject({ allowed: true });
const child = await createIssue(db, company.id, {
parentId: privateRoot.id,
privacyParentIssueId: privateRoot.id,
visibility: "private",
privacyRootIssueId: privateRoot.id,
});
await expect(decide(userActor(granteeId), child)).resolves.toMatchObject({ allowed: true });
await db.update(issueAccessGrants).set({ revokedAt: new Date() }).where(eq(issueAccessGrants.id, grant.id));
await expect(decide(userActor(granteeId), privateRoot)).resolves.toMatchObject({
allowed: false,
reason: "deny_issue_private",
});
process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = "shadow";
const warn = vi.spyOn(logger, "warn").mockImplementation(() => logger);
await expect(decide(userActor(memberId), privateRoot)).resolves.toMatchObject({ allowed: true });
expect(warn).toHaveBeenCalledWith(
expect.objectContaining({
authzMode: "shadow",
issueId: privateRoot.id,
reason: "deny_issue_private",
}),
"issue privacy would deny read",
);
warn.mockRestore();
} finally {
if (previousMode === undefined) delete process.env.PAPERCLIP_ISSUE_PRIVACY_MODE;
else process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = previousMode;
if (previousTtl === undefined) delete process.env.PAPERCLIP_ISSUE_PRIVACY_CACHE_TTL_MS;
else process.env.PAPERCLIP_ISSUE_PRIVACY_CACHE_TTL_MS = previousTtl;
}
});
it("uses private-project membership as the same issue-read predicate while preserving issue grants", async () => {
const previousMode = process.env.PAPERCLIP_ISSUE_PRIVACY_MODE;
process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = "enforce";
try {
const company = await createCompany(db, "ProjectPrivacy");
const memberId = await createUser(db);
const granteeId = await createUser(db);
const outsiderId = await createUser(db);
await db.insert(companyMemberships).values([memberId, granteeId, outsiderId].map((principalId) => ({
companyId: company.id,
principalType: "user" as const,
principalId,
status: "active",
membershipRole: "operator",
})));
const project = await createProject(db, company.id, "Private", "private");
const memberAgent = await createAgent(db, company.id);
const outsiderAgent = await createAgent(db, company.id);
await db.insert(companyMemberships).values([memberAgent.id, outsiderAgent.id].map((principalId) => ({
companyId: company.id,
principalType: "agent" as const,
principalId,
status: "active",
membershipRole: "member",
})));
await db.insert(projectAccessMembers).values({
companyId: company.id,
projectId: project.id,
subjectType: "user",
subjectId: memberId,
});
await db.insert(projectAccessMembers).values({
companyId: company.id,
projectId: project.id,
subjectType: "agent",
subjectId: memberAgent.id,
});
const issue = await createIssue(db, company.id, { projectId: project.id });
await db.insert(issueAccessGrants).values({
issueId: issue.id,
subjectType: "user",
subjectId: granteeId,
source: "explicit",
grantedByUserId: memberId,
});
const authz = authorizationService(db);
const decideProject = (userId: string) => authz.decide({
actor: { type: "board", userId, source: "session" },
action: "project:read",
resource: { type: "project", companyId: company.id, projectId: project.id },
});
const decideIssue = (userId: string) => authz.decide({
actor: { type: "board", userId, source: "session" },
action: "issue:read",
resource: { type: "issue", companyId: company.id, issueId: issue.id },
});
const decideProjectAsAgent = (agentId: string) => authz.decide({
actor: { type: "agent", agentId, companyId: company.id, source: "agent_key" },
action: "project:read",
resource: { type: "project", companyId: company.id, projectId: project.id },
});
const decideIssueAsAgent = (agentId: string) => authz.decide({
actor: { type: "agent", agentId, companyId: company.id, source: "agent_key" },
action: "issue:read",
resource: { type: "issue", companyId: company.id, issueId: issue.id },
});
await expect(decideProject(memberId)).resolves.toMatchObject({ allowed: true });
await expect(decideProject(outsiderId)).resolves.toMatchObject({
allowed: false,
reason: "deny_project_private",
});
await expect(decideIssue(memberId)).resolves.toMatchObject({ allowed: true });
await expect(decideIssue(granteeId)).resolves.toMatchObject({ allowed: true });
await expect(decideIssue(outsiderId)).resolves.toMatchObject({
allowed: false,
reason: "deny_issue_private",
});
await expect(decideProjectAsAgent(memberAgent.id)).resolves.toMatchObject({ allowed: true });
await expect(decideIssueAsAgent(memberAgent.id)).resolves.toMatchObject({ allowed: true });
await expect(decideProjectAsAgent(outsiderAgent.id)).resolves.toMatchObject({
allowed: false,
reason: "deny_project_private",
});
await expect(decideIssueAsAgent(outsiderAgent.id)).resolves.toMatchObject({
allowed: false,
reason: "deny_issue_private",
});
} finally {
if (previousMode === undefined) delete process.env.PAPERCLIP_ISSUE_PRIVACY_MODE;
else process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = previousMode;
}
});
it("denies secrets proposals for scoped tokens regardless of request source", async () => {
const company = await createCompany(db, "SecretProposalScopes");
const actorAgent = await createAgent(db, company.id);
+22 -309
View File
@@ -1,4 +1,5 @@
import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import {
agents,
@@ -22,313 +23,8 @@ vi.mock("../services/activity-log.js", () => ({
logActivity: mockLogActivity,
}));
type SelectResult = unknown[];
function createDbStub(selectResults: SelectResult[]) {
const pendingSelects = [...selectResults];
const selectWhere = vi.fn(() => {
const query = Promise.resolve(pendingSelects.shift() ?? []);
return Object.assign(query, { for: () => query });
});
const selectThen = vi.fn((resolve: (value: unknown[]) => unknown) => Promise.resolve(resolve(pendingSelects.shift() ?? [])));
const selectOrderBy = vi.fn(async () => pendingSelects.shift() ?? []);
const selectFrom = vi.fn(() => ({
where: selectWhere,
then: selectThen,
orderBy: selectOrderBy,
}));
const select = vi.fn(() => ({
from: selectFrom,
}));
const insertValues = vi.fn();
const insertReturning = vi.fn(async () => pendingInserts.shift() ?? []);
const insert = vi.fn(() => ({
values: insertValues.mockImplementation(() => ({
returning: insertReturning,
})),
}));
const updateSet = vi.fn();
const updateWhere = vi.fn(async () => pendingUpdates.shift() ?? []);
const update = vi.fn(() => ({
set: updateSet.mockImplementation(() => ({
where: updateWhere,
})),
}));
const pendingInserts: unknown[][] = [];
const pendingUpdates: unknown[][] = [];
return {
db: {
select,
insert,
update,
transaction: async (callback: (db: unknown) => Promise<unknown>) => callback({ select, insert, update }),
},
queueInsert: (rows: unknown[]) => {
pendingInserts.push(rows);
},
queueUpdate: (rows: unknown[] = []) => {
pendingUpdates.push(rows);
},
selectWhere,
insertValues,
updateSet,
};
}
describe("budgetService", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("creates a hard-stop incident and pauses an agent when spend exceeds a budget", async () => {
const policy = {
id: "policy-1",
companyId: "company-1",
scopeType: "agent",
scopeId: "agent-1",
metric: "billed_cents",
windowKind: "calendar_month_utc",
amount: 100,
warnPercent: 80,
hardStopEnabled: true,
notifyEnabled: false,
isActive: true,
};
const dbStub = createDbStub([
[policy],
[{ total: 150 }],
[],
[{
companyId: "company-1",
name: "Budget Agent",
status: "running",
pauseReason: null,
}],
[{ id: "agent-1", companyId: "company-1", status: "running" }],
]);
dbStub.queueInsert([{
id: "approval-1",
companyId: "company-1",
status: "pending",
}]);
dbStub.queueInsert([{
id: "incident-1",
companyId: "company-1",
policyId: "policy-1",
approvalId: "approval-1",
}]);
dbStub.queueUpdate([]);
const cancelWorkForScope = vi.fn().mockResolvedValue(undefined);
const service = budgetService(dbStub.db as any, { cancelWorkForScope });
await service.evaluateCostEvent({
companyId: "company-1",
agentId: "agent-1",
projectId: null,
} as any);
expect(dbStub.insertValues).toHaveBeenCalledWith(
expect.objectContaining({
companyId: "company-1",
type: "budget_override_required",
status: "pending",
}),
);
expect(dbStub.insertValues).toHaveBeenCalledWith(
expect.objectContaining({
companyId: "company-1",
policyId: "policy-1",
thresholdType: "hard",
amountLimit: 100,
amountObserved: 150,
approvalId: "approval-1",
}),
);
expect(dbStub.updateSet).toHaveBeenCalledWith(
expect.objectContaining({
status: "paused",
pauseReason: "budget",
pausedAt: expect.any(Date),
}),
);
expect(mockLogActivity).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
action: "budget.hard_threshold_crossed",
entityId: "incident-1",
}),
);
expect(cancelWorkForScope).toHaveBeenCalledWith({
companyId: "company-1",
scopeType: "agent",
scopeId: "agent-1",
});
});
it("blocks new work when an agent hard-stop remains exceeded even if the agent is not paused yet", async () => {
const agentPolicy = {
id: "policy-agent-1",
companyId: "company-1",
scopeType: "agent",
scopeId: "agent-1",
metric: "billed_cents",
windowKind: "calendar_month_utc",
amount: 100,
warnPercent: 80,
hardStopEnabled: true,
notifyEnabled: true,
isActive: true,
};
const dbStub = createDbStub([
[{
status: "running",
pauseReason: null,
companyId: "company-1",
name: "Budget Agent",
}],
[{
status: "active",
name: "Paperclip",
}],
[],
[agentPolicy],
[{ total: 120 }],
]);
const service = budgetService(dbStub.db as any);
const block = await service.getInvocationBlock("company-1", "agent-1");
expect(block).toEqual({
scopeType: "agent",
scopeId: "agent-1",
scopeName: "Budget Agent",
reason: "Agent cannot start because its budget hard-stop is still exceeded.",
});
});
it("surfaces a budget-owned company pause distinctly from a manual pause", async () => {
const dbStub = createDbStub([
[{
status: "idle",
pauseReason: null,
companyId: "company-1",
name: "Budget Agent",
}],
[{
status: "paused",
pauseReason: "budget",
name: "Paperclip",
}],
]);
const service = budgetService(dbStub.db as any);
const block = await service.getInvocationBlock("company-1", "agent-1");
expect(block).toEqual({
scopeType: "company",
scopeId: "company-1",
scopeName: "Paperclip",
reason: "Company is paused because its budget hard-stop was reached.",
});
});
it("uses live observed spend when raising a budget incident", async () => {
const dbStub = createDbStub([
[{
id: "incident-1",
companyId: "company-1",
policyId: "policy-1",
amountObserved: 120,
approvalId: "approval-1",
}],
[{
id: "policy-1",
companyId: "company-1",
scopeType: "company",
scopeId: "company-1",
metric: "billed_cents",
windowKind: "calendar_month_utc",
}],
[{ total: 150 }],
]);
const service = budgetService(dbStub.db as any);
await expect(
service.resolveIncident(
"company-1",
"incident-1",
{ action: "raise_budget_and_resume", amount: 140 },
"board-user",
),
).rejects.toThrow("New budget must exceed current observed spend");
});
it("syncs company monthly budget when raising and resuming a company incident", async () => {
const now = new Date();
const dbStub = createDbStub([
[{
id: "incident-1",
companyId: "company-1",
policyId: "policy-1",
scopeType: "company",
scopeId: "company-1",
metric: "billed_cents",
windowKind: "calendar_month_utc",
windowStart: now,
windowEnd: now,
thresholdType: "hard",
amountLimit: 100,
amountObserved: 120,
status: "open",
approvalId: "approval-1",
resolvedAt: null,
createdAt: now,
updatedAt: now,
}],
[{
id: "policy-1",
companyId: "company-1",
scopeType: "company",
scopeId: "company-1",
metric: "billed_cents",
windowKind: "calendar_month_utc",
amount: 100,
}],
[{ total: 120 }],
[{ id: "approval-1", status: "approved" }],
[{
companyId: "company-1",
name: "Paperclip",
status: "paused",
pauseReason: "budget",
pausedAt: now,
}],
]);
const service = budgetService(dbStub.db as any);
await service.resolveIncident(
"company-1",
"incident-1",
{ action: "raise_budget_and_resume", amount: 175 },
"board-user",
);
expect(dbStub.updateSet).toHaveBeenCalledWith(
expect.objectContaining({
budgetMonthlyCents: 175,
updatedAt: expect.any(Date),
}),
);
});
});
// Budget behavior is exercised against PostgreSQL below and in
// cost-accounting-reliability.test.ts, including transaction and retry paths.
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
@@ -493,7 +189,7 @@ describeEmbeddedPostgres("budgetService release gate enforcement", () => {
expect(agentAfterHardStop).toMatchObject({ status: "paused", pauseReason: "budget" });
expect(agentAfterHardStop?.pausedAt).toBeInstanceOf(Date);
expect(cancelWorkForScope).toHaveBeenCalledTimes(2);
expect(cancelWorkForScope).toHaveBeenCalledWith({ companyId, scopeType: "agent", scopeId: agentId });
expect(cancelWorkForScope).toHaveBeenCalledWith({ companyId, scopeType: "agent", scopeId: agentId, createdBefore: expect.any(Date), enforcement: { policyId: expect.any(String), version: expect.any(Number) } });
const block = await service.getInvocationBlock(companyId, agentId);
expect(block).toEqual({
@@ -538,6 +234,23 @@ describeEmbeddedPostgres("budgetService release gate enforcement", () => {
}
});
it("distinguishes a company budget pause from a manual company pause", async () => {
const { companyId, agentId } = await createBudgetFixture();
const service = budgetService(db);
await db.update(companies).set({ status: "paused", pauseReason: "budget" }).where(eq(companies.id, companyId));
expect(await service.getInvocationBlock(companyId, agentId)).toMatchObject({
scopeType: "company",
scopeId: companyId,
reason: "Budget pause requires a policy or an explicit operator resume.",
});
await db.update(companies).set({ pauseReason: null }).where(eq(companies.id, companyId));
expect(await service.getInvocationBlock(companyId, agentId)).toMatchObject({
scopeType: "company",
scopeId: companyId,
reason: "Company is paused and cannot start new work.",
});
});
it("hard-stops project work until a valid budget raise resumes it and overview reconciles ledger spend", async () => {
const { companyId, agentId, projectId } = await createBudgetFixture();
const cancelWorkForScope = vi.fn().mockResolvedValue(undefined);
@@ -578,7 +291,7 @@ describeEmbeddedPostgres("budgetService release gate enforcement", () => {
.from(projects);
expect(projectAfterHardStop?.pauseReason).toBe("budget");
expect(projectAfterHardStop?.pausedAt).toBeInstanceOf(Date);
expect(cancelWorkForScope).toHaveBeenCalledWith({ companyId, scopeType: "project", scopeId: projectId });
expect(cancelWorkForScope).toHaveBeenCalledWith({ companyId, scopeType: "project", scopeId: projectId, createdBefore: expect.any(Date), enforcement: { policyId: expect.any(String), version: expect.any(Number) } });
const overviewWhileBlocked = await service.overview(companyId);
expect(overviewWhileBlocked.pausedProjectCount).toBe(1);
@@ -16000,7 +16000,12 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
it("reorders rapid Slack callbacks by provider time before one conversation drain", async () => {
const fixture = await seedCompany();
const runtime = new FakeChatSdkRuntime();
const deferred: Array<() => void> = [];
const deferred: Array<() => void | Promise<void>> = [];
let releaseFirstDelivery!: () => void;
let signalFirstDelivery!: () => void;
const firstDeliveryEntered = new Promise<void>((resolve) => { signalFirstDelivery = resolve; });
const firstDeliveryReleased = new Promise<void>((resolve) => { releaseFirstDelivery = resolve; });
let firstDelivery = true;
const wakeup = vi.fn(async () => ({ accepted: true }));
const service = chatChannelService(db, {
deferWebhookProcessing: true,
@@ -16009,6 +16014,12 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
publicBaseUrl: "https://paperclip.example",
runtime: runtime as unknown as ChatSdkRuntime,
scheduleDeferredWork: (task) => deferred.push(task),
reachAuthorizationBarrier: async () => {
if (!firstDelivery) return;
firstDelivery = false;
signalFirstDelivery();
await firstDeliveryReleased;
},
});
const endpoint = await service.create(
fixture.companyId,
@@ -16127,69 +16138,54 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
publicBaseUrl: "https://paperclip.example",
runtime: new FakeChatSdkRuntime() as unknown as ChatSdkRuntime,
});
deferred.shift()?.();
// Simulate another server process reconciling the same durable rows at
// the same time as the webhook process's deferred drain.
await competingService.processPendingDeliveries();
await vi.waitFor(async () => {
const rows = await db
let drainSettled = false;
const draining = Promise.resolve(deferred.shift()?.()).then(() => { drainSettled = true; });
try {
// Hold the deferred owner after it acquires the conversation lease. The
// competing sweep must finish without overtaking that owner.
await firstDeliveryEntered;
await competingService.processPendingDeliveries();
expect(drainSettled).toBe(false);
expect(wakeup.mock.calls.filter((call) => call[0] === fixture.assignedAgentId)).toHaveLength(0);
releaseFirstDelivery();
await draining;
expect(drainSettled).toBe(true);
const conversations = await db
.select()
.from(chatConversations)
.where(eq(chatConversations.endpointId, endpoint.id));
expect(rows).toHaveLength(1);
});
const [conversation] = await db
.select()
.from(chatConversations)
.where(eq(chatConversations.endpointId, endpoint.id));
await vi.waitFor(async () => {
const rows = await db
.select({ id: issueComments.id })
expect(conversations).toHaveLength(1);
const [conversation] = conversations;
const comments = await db
.select({ id: issueComments.id, body: issueComments.body })
.from(issueComments)
.where(eq(issueComments.issueId, conversation.issueId));
expect(rows).toHaveLength(8);
});
const comments = await db
.select({ id: issueComments.id, body: issueComments.body })
.from(issueComments)
.where(eq(issueComments.issueId, conversation.issueId))
.orderBy(asc(issueComments.createdAt), asc(issueComments.id));
expect(comments.map((comment) => comment.body)).toEqual([
"@maya acknowledge quickly",
"follow-up 3",
"follow-up 4",
"follow-up 5",
"and include the rollback status",
"follow-up 6",
"follow-up 7",
"follow-up 8",
]);
// Comment admission commits before the durable wake. Wait for this
// company's last wake too, not merely its already-visible last comment.
// The competing sweep may legitimately reconcile another fixture company.
await vi.waitFor(() => {
const calls = wakeup.mock.calls.filter(
(call) => call[0] === fixture.assignedAgentId,
);
.where(eq(issueComments.issueId, conversation.issueId))
.orderBy(asc(issueComments.createdAt), asc(issueComments.id));
expect(comments.map((comment) => comment.body)).toEqual([
"@maya acknowledge quickly",
"follow-up 3",
"follow-up 4",
"follow-up 5",
"and include the rollback status",
"follow-up 6",
"follow-up 7",
"follow-up 8",
]);
// Joining the owner includes all comment admissions, durable wakeups and
// lease release. These assertions do not race a one-second polling budget.
expect(comments).toHaveLength(8);
const calls = wakeup.mock.calls.filter((call) => call[0] === fixture.assignedAgentId);
expect(calls).toHaveLength(8);
expect(calls.map((call) => call[1]?.payload?.wakeCommentId)).toEqual(
comments.map((comment) => comment.id),
);
});
// The last comment and wakeup commit inside the lease. Under full-suite
// load the assertions above can observe those effects one microtask before
// the deferred owner's `finally` deletes its lease. Require prompt eventual
// release; a real leak would remain for the much longer lease TTL.
await vi.waitFor(async () => {
expect(calls.map((call) => call[1]?.payload?.wakeCommentId)).toEqual(comments.map((comment) => comment.id));
expect(
await db
.select()
.from(chatEndpointLeases)
.where(eq(chatEndpointLeases.endpointId, endpoint.id)),
await db.select().from(chatEndpointLeases).where(eq(chatEndpointLeases.endpointId, endpoint.id)),
).toHaveLength(0);
});
await competingService.shutdown();
await service.shutdown();
} finally {
releaseFirstDelivery();
await draining;
await competingService.shutdown();
await service.shutdown();
}
});
it("stops a conversation drain after its lease renewal fails", async () => {
@@ -20832,6 +20828,10 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
trigger: "subscribed_message",
});
// Keep this ordering assertion independent of database/CI wall-clock speed.
// The next drain below explicitly makes both deliveries due.
await db.update(chatDeliveries).set({ nextAttemptAt: new Date(Date.now() + 60_000) })
.where(and(eq(chatDeliveries.endpointId, endpoint.id), inArray(chatDeliveries.state, ["received", "retry"])));
await service.processPendingDeliveries();
expect(wakeup).not.toHaveBeenCalled();
await db
@@ -61917,8 +61917,8 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
).resolves.toMatchObject({ ok: true });
expect(deferred).toHaveLength(1);
await drainDeferred();
await vi.waitFor(() => expect(deferred).toHaveLength(1));
await drainDeferred();
// Awaiting each callback also drains the lifecycle work it queues.
expect(deferred).toHaveLength(0);
await vi.waitFor(async () => {
await expect(
db
@@ -190,8 +190,9 @@ const support = await getEmbeddedPostgresTestSupport();
{ projectId: f.projectId, assigneeAgentId: null, assigneeUserId: "board-user" },
]) {
const result = await create(path, fields);
expect(result.status, JSON.stringify(result.body)).toBe(403);
expect(result.body.error).toMatch(/outside.*boundary|cannot assign work to board users|different company/i);
const hiddenProject = fields.projectId !== f.projectId && path.startsWith("/api/companies/");
expect(result.status, JSON.stringify(result.body)).toBe(hiddenProject ? 404 : 403);
expect(result.body.error).toMatch(hiddenProject ? /^Project not found$/ : /outside.*boundary|cannot assign work to board users|different company/i);
}
}
const after = await server.db.select({ id: issues.id }).from(issues).where(eq(issues.companyId, f.companyId));
@@ -232,7 +233,10 @@ const support = await getEmbeddedPostgresTestSupport();
body: JSON.stringify({ title: "Root cannot escape into another project", parentId: f.issueId,
projectId: outside.id, assigneeAgentId: f.agentId, status: "backlog" }),
});
expect(response.status, JSON.stringify(await response.json())).toBe(403);
const denied = await response.json();
const hiddenProject = path.startsWith("/api/companies/");
expect(response.status, JSON.stringify(denied)).toBe(hiddenProject ? 404 : 403);
expect(denied.error).toMatch(hiddenProject ? /^Project not found$/ : /outside.*boundary/i);
}
await expect(call(f, "create_task", { title: "Native root cannot escape", projectId: outside.id,
idempotencyKey: "root-outside", status: "backlog" })).rejects.toThrow(/outside.*boundary/);
@@ -685,8 +685,9 @@ describe("claude execute", () => {
expect(captured[1]?.appendedSystemPromptFilePath).toContain("agent-instructions.md");
expect(captured[1]?.appendedSystemPromptFilePath).not.toBe(instructionsFile);
expect(captured[1]?.appendedSystemPromptFileContents).toContain("# Agent instructions");
expect(captured[1]?.appendedSystemPromptFileContents).toContain(
`The above agent instructions were loaded from ${instructionsFile}. ` +
expect(captured[1]?.appendedSystemPromptFileContents).not.toContain(instructionsFile);
for (const prompt of prompts) expect(prompt).toContain(
`Agent instructions for this run were loaded from ${instructionsFile}. ` +
`Resolve any relative file references from ${path.dirname(instructionsFile)}/. ` +
`This base directory is authoritative for sibling instruction files such as ` +
`./HEARTBEAT.md, ./SOUL.md, and ./TOOLS.md; do not resolve those from the parent agent directory.`,
@@ -1338,7 +1339,9 @@ describe("claude execute", () => {
expect(capture1.addDir?.startsWith(expectedRoot)).toBe(true);
expect(capture1.instructionsFilePath?.startsWith(expectedRoot)).toBe(true);
expect(capture1.instructionsContents).toContain("You are managed instructions.");
expect(capture1.instructionsContents).toContain(`The above agent instructions were loaded from ${instructionsPath}.`);
expect(capture1.instructionsContents).not.toContain(instructionsPath);
expect(capture1.prompt).toContain(`Agent instructions for this run were loaded from ${instructionsPath}.`);
expect(capture2.prompt).toContain(`Agent instructions for this run were loaded from ${instructionsPath}.`);
expect(capture1.skillEntries).toContain("paperclip");
expect(capture2.argv).toContain("--resume");
expect(getFreshSessionHandoff).not.toHaveBeenCalled();
@@ -1362,6 +1365,81 @@ describe("claude execute", () => {
}
});
it("resumes across per-run instruction copies and refreshes their location", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-claude-working-copy-"));
const workspace = path.join(root, "workspace");
const commandPath = path.join(root, "claude");
const capturePath = path.join(root, "capture.json");
const skillDir = path.join(root, "skill");
await fs.mkdir(workspace, { recursive: true });
await fs.mkdir(skillDir);
await fs.writeFile(path.join(skillDir, "SKILL.md"), "First skill version.\n");
await writeFakeClaudeCommand(commandPath);
vi.stubEnv("PAPERCLIP_HOME", path.join(root, "paperclip-home"));
vi.stubEnv("PAPERCLIP_INSTANCE_ID", "default");
try {
let sessionParams: Record<string, unknown> | null = null;
let previousBundleKey: unknown;
let previousInstructionsPath = "";
for (const [index, change] of ["initial", "location", "instructions", "skill"].entries()) {
const runId = `run-${index}`;
const instructionsPath = path.join(root, "companies", "company-1", "agents", "agent-1",
"file-sync", "runs", runId, "live", "AGENTS.md");
await fs.mkdir(path.dirname(instructionsPath), { recursive: true });
await fs.writeFile(instructionsPath, index < 2 ? "First instructions.\n" : "Changed instructions.\n");
if (change === "skill") {
await fs.writeFile(path.join(skillDir, "SKILL.md"), "Changed skill version.\n");
}
const logs: string[] = [];
const result = await execute({
runId,
agent: { id: "agent-1", companyId: "company-1", name: "Test", adapterType: "claude_local", adapterConfig: { engine: "cli" } },
runtime: { sessionId: null, sessionParams, sessionDisplayId: null, taskKey: "issue-1" },
config: {
engine: "cli",
command: commandPath,
cwd: workspace,
instructionsFilePath: instructionsPath,
paperclipRuntimeSkills: [{ key: "test-skill", runtimeName: "test-skill", source: skillDir }],
paperclipSkillSync: { desiredSkills: ["test-skill"] },
env: { PAPERCLIP_TEST_CAPTURE_PATH: capturePath, CLAUDE_CONFIG_DIR: path.join(root, "claude-config") },
},
context: { issueId: "issue-1" },
onLog: async (_stream, chunk) => { logs.push(chunk); },
});
expect(result.exitCode).toBe(0);
const capture = JSON.parse(await fs.readFile(capturePath, "utf8")) as CapturePayload;
if (change === "location") {
expect(capture.argv).toContain("--resume");
expect(capture.argv).toContain("11111111-1111-4111-8111-111111111111");
expect(capture.instructionsFilePath).toBeNull();
expect(result.sessionParams?.promptBundleKey).toBe(previousBundleKey);
} else {
expect(capture.argv).not.toContain("--resume");
expect(capture.instructionsContents).toContain(index < 2 ? "First instructions." : "Changed instructions.");
expect(result.sessionParams?.promptBundleKey).not.toBe(previousBundleKey);
if (index > 0) {
expect(capture.instructionsContents).not.toContain(instructionsPath);
expect(logs.join("")).toContain("was saved for prompt bundle");
expect(logs.join("")).not.toContain("was saved for cwd");
}
}
if (index > 0) {
expect(capture.prompt).toContain(instructionsPath);
expect(capture.prompt).toContain(`Resolve any relative file references from ${path.dirname(instructionsPath)}/.`);
}
if (previousInstructionsPath) expect(capture.prompt).not.toContain(previousInstructionsPath);
sessionParams = sessionCodec.deserialize(sessionCodec.serialize(result.sessionParams ?? null));
previousBundleKey = result.sessionParams?.promptBundleKey;
previousInstructionsPath = instructionsPath;
}
} finally {
vi.unstubAllEnvs();
await fs.rm(root, { recursive: true, force: true });
}
});
it("starts a fresh Claude session when the stable prompt bundle changes", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-claude-execute-reset-"));
const workspace = path.join(root, "workspace");
@@ -1897,7 +1897,7 @@ describe("company portability", () => {
},
},
}),
}));
}), { createdByUserId: "user-1" });
expect(secretSvc.syncEnvBindingsForTarget).toHaveBeenCalledWith(
"company-1",
{ targetType: "agent", targetId: "agent-imported" },
@@ -2889,7 +2889,7 @@ describe("company portability", () => {
// a scoped resume; "system" stays for platform-managed pauses.
pauseReason: "import",
pausedAt: expect.any(Date),
}));
}), { createdByUserId: "user-1" });
expect(routineSvc.create).toHaveBeenCalledWith("company-imported", expect.objectContaining({
title: "Monday Review",
status: "paused",
@@ -3204,7 +3204,7 @@ describe("company portability", () => {
expect(agentSvc.create).toHaveBeenCalledWith("company-imported", expect.objectContaining({
name: "ClaudeCoder",
adapterType: "process",
}));
}), { createdByUserId: "user-1" });
});
it("preserves agent role from frontmatter when extension block omits it", async () => {
@@ -3383,7 +3383,7 @@ describe("company portability", () => {
desiredSkills: [paperclipKey],
},
}),
}));
}), { createdByUserId: "user-1" });
});
it("imports a packaged company logo and attaches it to the target company", async () => {
@@ -3677,7 +3677,7 @@ describe("company portability", () => {
maxConcurrentRuns: 20,
},
},
}));
}), { createdByUserId: "user-1" });
expect(result.company.action).toBe("unchanged");
expect(result.agents).toEqual([
{
@@ -3748,13 +3748,13 @@ describe("company portability", () => {
adapterConfig: expect.objectContaining({
dangerouslyBypassApprovalsAndSandbox: true,
}),
}));
}), { createdByUserId: "user-1" });
expect(agentSvc.create).toHaveBeenCalledWith("company-imported", expect.objectContaining({
adapterConfig: expect.not.objectContaining({
instructionsFilePath: expect.anything(),
promptTemplate: expect.anything(),
}),
}));
}), { createdByUserId: "user-1" });
expect(agentInstructionsSvc.materializeManagedBundle).toHaveBeenCalledWith(
expect.objectContaining({ name: "ClaudeCoder" }),
expect.objectContaining({
@@ -3856,7 +3856,7 @@ describe("company portability", () => {
extraArgs: ["--skip-git-repo-check"],
args: ["--legacy-arg"],
}),
}));
}), { createdByUserId: "user-1" });
const lastCreateInput = agentSvc.create.mock.calls.at(-1)?.[1] as Record<string, any>;
expect(lastCreateInput?.adapterConfig).toBeTruthy();
expect(lastCreateInput.adapterConfig?.dangerouslyBypassApprovalsAndSandbox).toBeUndefined();
@@ -5785,7 +5785,7 @@ describe("company portability", () => {
normalized: true,
}),
status: "idle",
}));
}), { createdByUserId: "user-1" });
expect(companySvc.create).toHaveBeenCalledWith(expect.objectContaining({
requireBoardApprovalForNewAgents: false,
}));
@@ -6107,13 +6107,13 @@ describe("company portability", () => {
expect(agentSvc.create).toHaveBeenCalledWith("company-1", expect.objectContaining({
adapterType: "paperclip_runner",
adapterConfig: expect.objectContaining({ provider: "opencode" }),
}));
}), { createdByUserId: "user-1" });
await portability.importBundle(request, "user-1");
expect(agentSvc.create).toHaveBeenCalledWith("company-1", expect.objectContaining({
adapterType: "paperclip_runner",
adapterConfig: expect.objectContaining({ provider: "codex" }),
}));
}), { createdByUserId: "user-1" });
await portability.importBundle({
...request,
@@ -67,13 +67,17 @@ describe("company extract-search route", () => {
})
.expect(200);
expect(extract).toHaveBeenCalledWith("company-1", expect.objectContaining({
expect(extract).toHaveBeenCalledWith(
"company-1",
expect.objectContaining({
contains: "github.com/example/repo/pull",
kind: "url",
scope: "comments",
limit: 200,
matchesPerIssue: 200,
}));
}),
expect.objectContaining({ issueReadCondition: expect.anything() }),
);
expect(response.body).toMatchObject({ kind: "url", scope: "comments", truncated: false });
});
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import {
companies,
companyMemberships,
createDb,
documents,
issueComments,
@@ -18,6 +19,7 @@ import {
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import { companySearchExtractService } from "../services/company-search-extract.js";
import { issueReadSqlCondition, type AuthorizationActor } from "../services/authorization.js";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
@@ -73,6 +75,7 @@ describeEmbeddedPostgres("companySearchExtractService", () => {
await db.delete(documents);
await db.delete(issueComments);
await db.delete(issues);
await db.delete(companyMemberships);
await db.delete(companies);
});
@@ -266,4 +269,44 @@ describeEmbeddedPostgres("companySearchExtractService", () => {
expect(result.results).toEqual([]);
});
it("does not extract content from a private issue for a non-member", async () => {
const companyId = await createCompany();
const viewerId = randomUUID();
await db.insert(companyMemberships).values({
companyId,
principalType: "user",
principalId: viewerId,
membershipRole: "operator",
status: "active",
});
const visibleIssueId = await createIssue(companyId, {
identifier: "EXT-PUBLIC",
description: "privacy-leak-needle",
});
const privateIssueId = randomUUID();
await createIssue(companyId, {
id: privateIssueId,
identifier: "EXT-PRIVATE",
description: "privacy-leak-needle private payload",
visibility: "private",
privacyRootIssueId: privateIssueId,
responsibleUserId: randomUUID(),
});
const actor: AuthorizationActor = {
type: "board",
userId: viewerId,
source: "session",
};
const result = await svc.extract(
companyId,
companySearchExtractQuerySchema.parse({ contains: "privacy-leak-needle" }),
{ issueReadCondition: await issueReadSqlCondition(db, actor) },
);
expect(result.results.map((row) => row.issueId)).toEqual([visibleIssueId]);
expect(JSON.stringify(result)).not.toContain(privateIssueId);
expect(JSON.stringify(result)).not.toContain("private payload");
});
});
@@ -8,9 +8,11 @@ import {
documents,
issueComments,
issueDocuments,
issueAccessGrants,
issueLabels,
issues,
labels,
projectAccessMembers,
projects,
} from "@paperclipai/db";
import { companySearchQuerySchema, COMPANY_SEARCH_MAX_QUERY_LENGTH } from "@paperclipai/shared";
@@ -23,6 +25,8 @@ import {
companySearchBranchFetchLimit,
companySearchService,
} from "../services/company-search.js";
import { issueReadSqlCondition, projectReadSqlCondition } from "../services/authorization.js";
import { issueService } from "../services/issues.js";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
@@ -87,6 +91,7 @@ describeEmbeddedPostgres("companySearchService", () => {
await db.delete(documents);
await db.delete(issueComments);
await db.delete(issueLabels);
await db.delete(issueAccessGrants);
await db.delete(issues);
await db.delete(labels);
await db.delete(projects);
@@ -814,4 +819,99 @@ describeEmbeddedPostgres("companySearchService", () => {
expect(ids, `query=${query} should not match unrelated issue`).not.toContain(rejected);
}
});
it("pushes private issue filtering into list, count, and company search queries", async () => {
const previousMode = process.env.PAPERCLIP_ISSUE_PRIVACY_MODE;
process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = "enforce";
try {
const companyId = await createCompany();
const ownerId = `owner-${randomUUID()}`;
const otherId = `other-${randomUUID()}`;
const granteeId = `grantee-${randomUUID()}`;
const openId = await createIssue(companyId, { title: "privacy needle open" });
const privateId = randomUUID();
await createIssue(companyId, {
id: privateId,
title: "privacy needle private",
visibility: "private",
privacyRootIssueId: privateId,
responsibleUserId: ownerId,
});
await db.insert(issueAccessGrants).values({
issueId: privateId,
subjectType: "user",
subjectId: granteeId,
source: "explicit",
grantedByUserId: ownerId,
});
const issuesSvc = issueService(db);
const conditionFor = (userId: string) => issueReadSqlCondition(db, {
type: "board",
userId,
source: "session",
});
const otherCondition = await conditionFor(otherId);
const ownerCondition = await conditionFor(ownerId);
const granteeCondition = await conditionFor(granteeId);
await expect(issuesSvc.list(companyId, { readCondition: otherCondition })).resolves.toMatchObject([
{ id: openId },
]);
await expect(issuesSvc.count(companyId, { readCondition: otherCondition })).resolves.toBe(1);
await expect(issuesSvc.count(companyId, { readCondition: ownerCondition })).resolves.toBe(2);
await expect(issuesSvc.count(companyId, { readCondition: granteeCondition })).resolves.toBe(2);
const result = await svc.search(
companyId,
companySearchQuerySchema.parse({ q: "privacy needle", scope: "issues" }),
{ issueReadCondition: otherCondition },
);
expect(result.results.map((row) => row.id)).toEqual([openId]);
} finally {
if (previousMode === undefined) delete process.env.PAPERCLIP_ISSUE_PRIVACY_MODE;
else process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = previousMode;
}
});
it("pushes private project filtering into project search and counts", async () => {
const previousMode = process.env.PAPERCLIP_ISSUE_PRIVACY_MODE;
process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = "enforce";
try {
const companyId = await createCompany();
const memberId = `member-${randomUUID()}`;
const outsiderId = `outsider-${randomUUID()}`;
const openId = await createProject(companyId, { name: "privacy project open" });
const privateId = await createProject(companyId, {
name: "privacy project private",
visibility: "private",
});
await db.insert(projectAccessMembers).values({
companyId,
projectId: privateId,
subjectType: "user",
subjectId: memberId,
});
const conditionFor = (userId: string) => projectReadSqlCondition(db, {
type: "board",
userId,
source: "session",
});
const query = companySearchQuerySchema.parse({ q: "privacy project", scope: "projects" });
const outsiderResult = await svc.search(companyId, query, {
projectReadCondition: await conditionFor(outsiderId),
});
expect(outsiderResult.results.map((row) => row.id)).toEqual([openId]);
expect(outsiderResult.countsByType.project).toBe(1);
const memberResult = await svc.search(companyId, query, {
projectReadCondition: await conditionFor(memberId),
});
expect(memberResult.results.map((row) => row.id)).toEqual(expect.arrayContaining([openId, privateId]));
expect(memberResult.countsByType.project).toBe(2);
} finally {
if (previousMode === undefined) delete process.env.PAPERCLIP_ISSUE_PRIVACY_MODE;
else process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = previousMode;
}
});
});
@@ -1,3 +1,6 @@
import Ajv2020 from "ajv/dist/2020.js";
import { requestHumanInputAction } from "../../../packages/paperclip-runner/src/protocol-actions/request-human-input.js";
import { questionSetToAskUserQuestionsPayload } from "@paperclipai/shared";
import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
@@ -314,9 +317,34 @@ const support = await getEmbeddedPostgresTestSupport();
expect(result.results.some(item => item.service === "google-sheets")).toBe(true);
expect(result.instruction).not.toContain("search its exact name");
});
it("keeps installed capability matches when a generic query resembles an external app name", async () => {
await resetQuestions();
const installed = await seedProvider("Studio library", "notion:list_pages");
await db.update(toolCatalogEntries).set({ description: "Read recent pages and return their titles and verification code" })
.where(eq(toolCatalogEntries.connectionId, installed.id));
const service = connectionIntentService(db);
const result = await service.search(claims,
"connected page service that can find or list recent pages and return page titles plus a verification code");
expect(result.results).toEqual(expect.arrayContaining([expect.objectContaining({
service: `connection:${installed.id}`, connectionId: installed.id, state: "ready",
})]));
expect(result.providerQuestion).toBeUndefined();
expect(result.instruction).not.toContain("Ask the responsible user with providerQuestion");
// A deliberate app name still reaches the existing governed provider choice.
const named = await service.search(claims, "Page X");
expect(named.providerQuestion?.id).toBe("connection-provider:page-x");
expect(named.results[0]?.service).toBe("via:composio:page-x");
});
it("keeps an external typo as a discovery suggestion until its app is selected", async () => {
await resetQuestions();
const result = await connectionIntentService(db).search(claims,
"Find Circlebak meeting transcripts and action items from yesterday");
expect(result.results.some(item => item.service === "via:composio:circleback-mcp")).toBe(true);
expect(result.providerQuestion).toBeUndefined();
expect(result.instruction).toContain("aggregator.targetService");
});
it.each([
["help me find tools for circle back", "circleback-mcp"],
["Find Circlebak meeting transcripts and action items from yesterday", "circleback-mcp"],
["Can you connect Circleback MCP to get all our meeting notes?", "circleback-mcp"],
["Find Attio tools to review all our customer contacts before next week's meeting", "attio"],
["Help me find a ClickUp connection to organize our team's projects", "clickup"],
@@ -385,6 +413,18 @@ const support = await getEmbeddedPostgresTestSupport();
"via:zapier:hubspot",
]);
expect(result.providerQuestion?.prompt).toContain("external service");
const ajv = new Ajv2020({ allErrors: true, allowUnionTypes: true, strict: false });
const input = { idempotencyKey: "provider-choice", interactionKind: "questions", title: "Choose a provider",
prompt: result.providerQuestion!.prompt, continuationPolicy: "wake_assignee" };
for (const payload of [{ version: 1, questionSet: result.providerQuestionSet }, { version: 1, questions: [result.providerQuestion] }]) {
expect(ajv.validate(requestHumanInputAction.live.descriptor.inputSchema, { ...input, payload }), JSON.stringify(ajv.errors)).toBe(true);
}
expect(questionSetToAskUserQuestionsPayload(result.providerQuestionSet!).questions).toEqual([result.providerQuestion]);
expect(result.instruction).toContain("questionSet:providerQuestionSet");
expect(result.instruction).not.toContain("do not add questionSet");
expect(ajv.validate(requestHumanInputAction.live.descriptor.inputSchema, { ...input, payload: { version: 1 } })).toBe(false);
expect(ajv.validate(requestHumanInputAction.live.descriptor.inputSchema, { ...input, payload: { version: 1,
questionSet: { ...result.providerQuestionSet, questions: [{ ...result.providerQuestionSet!.questions[0], answerMode: "text" }] } } })).toBe(false);
expect(result.results.every((item) => item.state !== "ready")).toBe(true);
expect(result.results.every((item) => item.aggregator?.evidenceUrl)).toBe(
true,
@@ -568,6 +608,51 @@ const support = await getEmbeddedPostgresTestSupport();
);
expect(result.instruction).toContain("Arcade");
});
it("returns exact eligible catalog names after a guessed tool without granting access", async () => {
await resetQuestions();
const connection = await seedProvider("arcade", "Hubspot_ListContacts", "responsible-user", false);
await db.delete(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, connection.id));
await seedProvider("composio", "Unrelated_PrivateTool", "other-user", false);
await db.insert(toolCatalogEntries).values({ companyId: claims.company_id, connectionId: connection.id,
toolName: "Hubspot_RemovedTool", name: "Removed", versionHash: "old", entryKind: "tool", status: "removed" });
const answer = await selectProvider("via:arcade:hubspot");
const service = connectionIntentService(db);
const error = await service.request(claims, "via:arcade:hubspot", {
selectionInteractionId: answer.id, toolNames: ["hubspot_list_contacts"],
}).catch(error => error);
expect(error).toMatchObject({ status: 422 });
expect(error.message).toContain('"Hubspot_ListContacts"');
expect(error.message).toContain("Request only the needed exact names");
expect(error.message).not.toMatch(/Unrelated_PrivateTool|Hubspot_RemovedTool/);
expect(await db.select().from(toolProfiles).where(eq(toolProfiles.companyId, claims.company_id))).toEqual([]);
const interactions = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.companyId, claims.company_id));
expect(interactions.map(row => [row.id, row.status])).toEqual([[answer.id, "answered"]]);
const requested = await service.request(claims, "via:arcade:hubspot", {
selectionInteractionId: answer.id, toolNames: ["Hubspot_ListContacts"],
});
expect(requested.state).toBe("needs_user_action");
const loaded = await service.loadIntent(requested.interactionId!);
expect(loaded.interaction.payload.accessRequest?.tools.map(tool => tool.toolName)).toEqual(["Hubspot_ListContacts"]);
expect(loaded.interaction.status).toBe("pending");
expect(await db.select().from(toolProfiles).where(eq(toolProfiles.companyId, claims.company_id))).toEqual([]);
});
it("bounds catalog-name recovery and does not disclose an ineligible connection", async () => {
await resetQuestions();
const connection = await seedProvider("arcade", "Read_00", "responsible-user", false);
await db.insert(toolCatalogEntries).values(Array.from({ length: 24 }, (_, index) => ({
companyId: claims.company_id, connectionId: connection.id, toolName: `Read_${String(index + 1).padStart(2, "0")}`,
name: `Read_${String(index + 1).padStart(2, "0")}`, versionHash: "v1", entryKind: "tool" as const, status: "active" as const,
})));
const service = connectionIntentService(db);
const error = await service.request(claims, "arcade", { connectionId: connection.id, toolNames: ["guessed"] }).catch(error => error);
expect(error).toMatchObject({ status: 422 });
expect(error.message).toContain("first 20 of 25");
expect(error.message.match(/Read_\d{2}/g)).toHaveLength(20);
await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.connectionId, connection.id));
const denied = await service.request(claims, "arcade", { connectionId: connection.id, toolNames: ["guessed"] }).catch(error => error);
expect(denied.message).not.toContain("Read_");
expect(denied.message).toContain("not eligible");
});
it("does not switch providers when the chosen route loses permission", async () => {
await resetQuestions();
const answer = await selectProvider("via:arcade:hubspot");
@@ -3,6 +3,7 @@ import { and, eq, sql } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import {
agents,
authUsers,
aiProviderDefaults,
agentWakeupRequests,
issueComments,
@@ -110,6 +111,7 @@ describeEmbeddedPostgres("connectionIntentService", () => {
issuePrefix: "CONN",
requireBoardApprovalForNewAgents: false,
});
await db.insert(authUsers).values({ id: "responsible-user", name: "Responsible user", email: "responsible@example.test", createdAt: new Date(), updatedAt: new Date() });
await db.insert(companyMemberships).values({
companyId,
principalType: "user",
+29 -18
View File
@@ -221,6 +221,21 @@ describe("cost routes", () => {
});
});
it("requires an explicit all-time request and rejects conflicting ranges", () => {
const { parseCostDateRange } = loadCostParsers();
expect(parseCostDateRange({})).toBeUndefined();
expect(parseCostDateRange({ period: "all" })).toEqual({ allTime: true });
for (const input of [
{ from: "2026-09-02", to: "2026-09-01" },
{ from: ["2026-09-01"] },
{ from: "2026-02-30" },
{ from: "" },
{ from: "09/01/2026" },
{ period: "all", from: "2026-09-01" },
{ period: "unknown" },
]) expect(() => parseCostDateRange(input)).toThrow();
});
it("returns 400 for an invalid 'from' date string", async () => {
const { parseCostDateRange } = loadCostParsers();
expect(() => parseCostDateRange({ from: "not-a-date" })).toThrow(/invalid 'from' date/i);
@@ -270,7 +285,7 @@ describe("cost routes", () => {
it("returns 400 for invalid finance event list limits", async () => {
const { parseCostLimit } = loadCostParsers();
expect(() => parseCostLimit({ limit: "0" })).toThrow(/invalid 'limit'/i);
for (const limit of ["0", "25garbage", "1.5", ["25"], "501"]) expect(() => parseCostLimit({ limit })).toThrow(/invalid 'limit'/i);
});
it("accepts valid finance event list limits", async () => {
@@ -352,7 +367,8 @@ describe("cost routes", () => {
});
it("allows authorized board users to update an agent budget and budget policy", async () => {
mockAgentService.update.mockResolvedValueOnce({
mockAgentService.getById.mockResolvedValueOnce({ id: "agent-1", companyId: "company-1", name: "Budget Agent", budgetMonthlyCents: 100, spentMonthlyCents: 0 });
mockAgentService.getById.mockResolvedValueOnce({
id: "agent-1",
companyId: "company-1",
name: "Budget Agent",
@@ -373,30 +389,22 @@ describe("cost routes", () => {
.send({ budgetMonthlyCents: 2500 });
expect(res.status).toBe(200);
expect(mockAgentService.update).toHaveBeenCalledWith("agent-1", { budgetMonthlyCents: 2500 });
expect(res.body.budgetMonthlyCents).toBe(2500);
expect(mockAgentService.update).not.toHaveBeenCalled();
expect(mockBudgetService.upsertPolicy).toHaveBeenCalledTimes(1);
expect(mockBudgetService.upsertPolicy).toHaveBeenCalledWith(
"company-1",
{
scopeType: "agent",
scopeId: "agent-1",
amount: 2500,
isActive: true,
windowKind: "calendar_month_utc",
},
"board-user",
);
expect(mockLogActivity).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
companyId: "company-1",
actorType: "user",
actorId: "board-user",
agentId: null,
action: "agent.budget_updated",
entityType: "agent",
entityId: "agent-1",
details: { budgetMonthlyCents: 2500 },
}),
);
// Policy mutation owns the atomic entity update and activity log.
expect(mockLogActivity).not.toHaveBeenCalled();
});
});
@@ -543,7 +551,9 @@ describeEmbeddedPostgres("cost and finance aggregate overflow handling", () => {
const [byAgentModelRow] = await costs.byAgentModel(companyId, range);
expect(byAgentRow?.costCents).toBe(4_000_000_000);
expect(byAgentRow?.inputTokens).toBe(4_000_000_000);
// Historical OpenAI input includes these ten cached tokens.
expect(byAgentRow?.inputTokens).toBe(3_999_999_990);
expect(byAgentRow!.inputTokens + byAgentRow!.cachedInputTokens).toBe(4_000_000_000);
expect(byProjectRow?.costCents).toBe(4_000_000_000);
expect(byAgentModelRow?.costCents).toBe(4_000_000_000);
});
@@ -692,7 +702,8 @@ describeEmbeddedPostgres("cost and finance aggregate overflow handling", () => {
issueCount: 3,
includeDescendants: true,
costCents: 600,
inputTokens: 60,
costCentsExact: "600.0000000",
inputTokens: 54,
cachedInputTokens: 6,
outputTokens: 12,
runCount: 0,
@@ -0,0 +1,70 @@
import { describe, expect, it, vi } from "vitest";
import { DECISION_MODELS, DECISION_TEST_REQUEST, decisionProviderForConnection } from "@paperclipai/shared";
import { decisionReceipt, runDecisionProvider } from "../services/decision-model-provider.js";
function openaiResponse() {
return { model: "gpt-6-luna", usage: { input_tokens: 123, output_tokens: 0 }, answers: [
{ type: "predicate", name: "billing", probability: 0.99 },
{ type: "choice", name: "team", choice: "billing", confidence: 0.9, probabilities: [{ value: "billing", probability: 0.9 }, { value: "technical", probability: 0.1 }] },
{ type: "score", name: "severity", score: 0.1, probabilities: [{ value: 0, probability: 0.9 }, { value: 1, probability: 0.1 }, { value: 2, probability: 0 }] },
] };
}
function openrouterResponse() {
return { id: "decision-fixture", model: "typesafe/jev-1.13", usage: { input_tokens: 123, output_tokens: 0, cost: 0.000005166 }, answers: {
billing: { type: "noul", noul: 0.99 }, team: { type: "choice", choice: "billing", confidence: 0.85, probabilities: { billing: 0.9, technical: 0.1 } },
severity: { type: "score", score: 0.1, probabilities: { "0": 0.9, "1": 0.1, "2": 0 } },
} };
}
describe("decision provider contract", () => {
it.each(["openai", "openrouter"] as const)("uses native %s decisions with the selected credential and preserves answers and fractional costs", async provider => {
const transport = vi.fn<typeof fetch>().mockResolvedValue(Response.json(provider === "openai" ? openaiResponse() : openrouterResponse()));
const result = await runDecisionProvider({ provider, model: DECISION_MODELS[provider].id, apiKey: "selected-credential", request: DECISION_TEST_REQUEST, signal: new AbortController().signal }, { fetch: transport });
expect(transport).toHaveBeenCalledTimes(1);
const [url, options] = transport.mock.calls[0];
expect(String(url)).toBe(provider === "openai" ? "https://api.openai.com/v1/decisions" : "https://openrouter.ai/api/alpha/decisions");
expect(new Headers(options?.headers).get("authorization")).toBe("Bearer selected-credential");
expect(result.answers).toMatchObject({ billing: { type: "boolean", probability: 0.99 }, team: { type: "choice", choice: "billing", confidence: provider === "openai" ? 0.9 : 0.85 }, severity: { type: "score", score: 0.1 } });
expect(result.receipt.costCents).toBe(provider === "openai" ? "0.0012300" : "0.0005166");
expect(JSON.stringify(result.receipt)).not.toContain("customer");
expect(JSON.parse(String(options?.body)).model).toBe(DECISION_MODELS[provider].id);
});
it("keeps usage for a charged refusal and never treats it as an answer", async () => {
const transport = vi.fn<typeof fetch>().mockResolvedValue(Response.json({ ...openaiResponse(), answers: [{ type: "refusal", name: null }] }));
const result = await runDecisionProvider({ provider: "openai", model: "gpt-6-luna", apiKey: "key", request: DECISION_TEST_REQUEST, signal: new AbortController().signal }, { fetch: transport });
expect(result.answers).toBeUndefined(); expect(result.errorCode).toBe("refused"); expect(result.receipt.inputTokens).toBe(123);
});
it.each([401, 429, 500])("does not retry HTTP %i or retain its response body", async status => {
const transport = vi.fn<typeof fetch>().mockResolvedValue(Response.json({ error: { message: "PRIVATE STATE AND KEY", type: "server_error" } }, { status }));
const result = await runDecisionProvider({ provider: "openai", model: "gpt-6-luna", apiKey: "key", request: DECISION_TEST_REQUEST, signal: new AbortController().signal }, { fetch: transport });
expect(transport).toHaveBeenCalledTimes(1); expect(result.receipt.costStatus).toBe(status === 500 ? "unpriced" : "estimated"); expect(result.noProviderWork).toBe(status !== 500); expect(JSON.stringify(result)).not.toContain("PRIVATE");
});
it("preserves usage when answer validation fails", async () => {
const response = openrouterResponse(); response.answers.team.choice = "invented";
const result = await runDecisionProvider({ provider: "openrouter", model: "typesafe/jev-1.13", apiKey: "key", request: DECISION_TEST_REQUEST, signal: new AbortController().signal }, { fetch: async () => Response.json(response) });
expect(result.answers).toBeUndefined(); expect(result.receipt.costStatus).toBe("reported");
});
it.each(["openai", "openrouter"] as const)("retains the %s receipt when the SDK rejects malformed wire answers", async provider => {
const wire = provider === "openai" ? { ...openaiResponse(), answers: [{ type: "predicate", name: "billing", probability: 2 }] }
: { ...openrouterResponse(), answers: { billing: { type: "noul", noul: "not-a-probability" } } };
const result = await runDecisionProvider({ provider, model: DECISION_MODELS[provider].id, apiKey: "key", request: DECISION_TEST_REQUEST, signal: new AbortController().signal }, { fetch: async () => Response.json(wire) });
expect(result.answers).toBeUndefined(); expect(result.receipt.inputTokens).toBe(123);
expect(result.receipt.costStatus).toBe(provider === "openai" ? "estimated" : "reported");
});
it("fails closed on an OpenRouter refusal while retaining any reported charge", async () => {
const result = await runDecisionProvider({ provider: "openrouter", model: DECISION_MODELS.openrouter.id, apiKey: "key", request: DECISION_TEST_REQUEST, signal: new AbortController().signal },
{ fetch: async () => Response.json({ ...openrouterResponse(), answers: { billing: { type: "refusal" } } }) });
expect(result.answers).toBeUndefined(); expect(result.errorCode).toBe("refused"); expect(result.receipt.costStatus).toBe("reported");
});
it("does not invent prices when usage or a supported rate is missing", () => {
expect(decisionReceipt("openai", {}).costCents).toBeNull();
expect(decisionReceipt("openai", { usage: { inputTokens: 100_000 } }).costStatus).toBe("unpriced");
expect(decisionReceipt("openrouter", { usage: { inputTokens: 1 } }).costCents).toBeNull();
expect(decisionReceipt("openrouter", { providerMetadata: { openrouter: { usage: { cost: 0 } } } }).costStatus).toBe("reported");
});
it("rejects subscription, personal endpoint routing and other provider capabilities", () => {
expect(decisionProviderForConnection({ provider: "openai", method: "subscription" })).toBeNull();
expect(decisionProviderForConnection({ provider: "openai", method: "api_key", routing: { kind: "gateway", baseUrl: "https://example.com" } })).toBeNull();
expect(decisionProviderForConnection({ provider: "anthropic", method: "api_key" })).toBeNull();
expect(decisionProviderForConnection({ provider: "openrouter", method: "api_key", routing: { kind: "openrouter" } })).toBe("openrouter");
});
});
@@ -0,0 +1,291 @@
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { randomUUID } from "node:crypto";
import { mkdtemp, realpath, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { and, eq, sql } from "drizzle-orm";
import {
createDb, companies, agents, companyMemberships, companyDecisionModels, costEvents, decisionInvocations,
connectionGrants, connectionGrantMembers, toolConnectionInstalls, budgetPolicies, budgetReservations,
heartbeatRuns, issues, projects, runIdentityContexts, secretAccessEvents, companySecrets,
} from "@paperclipai/db";
import { startEmbeddedPostgresTestDatabase } from "@paperclipai/db/test-embedded-postgres";
import { DECISION_TEST_REQUEST, updateDecisionModelSchema, createCostEventSchema } from "@paperclipai/shared";
import { aiConnectionService } from "../services/ai-connections.js";
import { agentService } from "../services/agents.js";
import { decisionModelService, settingsDecisionTest, defineDecisionFeature, type DecisionContext } from "../services/decision-models.js";
import { decisionReceipt, type DecisionProviderOutcome } from "../services/decision-model-provider.js";
import { costService } from "../services/costs.js";
import { billingReconciliationService } from "../services/billing-reconciliation.js";
import { withAccountingTransaction } from "../services/accounting-transaction.js";
import express from "express";
import request from "supertest";
import { decisionModelRoutes } from "../routes/decision-models.js";
import { errorHandler } from "../middleware/index.js";
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
let home: string;
const backgroundFeature = defineDecisionFeature("test.background", { background: true });
const outcome: DecisionProviderOutcome = { answers: { billing: { type: "boolean", probability: 0.9 } }, receipt: decisionReceipt("openai", { usage: { inputTokens: 100, outputTokens: 0 } }) };
beforeAll(async () => {
home = await realpath(await mkdtemp(path.join(os.tmpdir(), "paperclip-decisions-")));
vi.stubEnv("PAPERCLIP_HOME", home);
vi.stubEnv("PAPERCLIP_INSTANCE_ID", "decisions-fixture");
database = await startEmbeddedPostgresTestDatabase("paperclip-decisions-db-");
db = createDb(database.connectionString);
}, 90000);
afterAll(async () => { await database?.cleanup(); vi.unstubAllEnvs(); if (home) await rm(home, { recursive: true, force: true }); });
let sequence = 0;
async function fixture() {
const companyId = randomUUID(), agentId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Decision tests", issuePrefix: `DC${++sequence}` });
await db.insert(agents).values({ id: agentId, companyId, name: "Test agent", adapterType: "codex_local" });
await db.insert(companyMemberships).values(["alice", "bob"].map(principalId => ({ companyId, principalId, principalType: "user", status: "active", membershipRole: "owner" })));
const connections = aiConnectionService(db);
const binding = await connections.save(companyId, "alice", { provider: "openai", method: "api_key", name: "Decision key", ownership: "shared", apiKey: "fixture-key", agentIds: [], allAgents: true }, "fixture-key");
const provider = vi.fn().mockResolvedValue(structuredClone(outcome));
const service = decisionModelService(db, { provider });
const context: DecisionContext = { companyId, feature: settingsDecisionTest,
actor: { type: "board", userId: "alice", source: "session", companyIds: [companyId], memberships: [{ companyId, membershipRole: "owner", status: "active" }] } };
const config = { ...binding, enabled: true, allowBackground: true };
await service.configure(companyId, "alice", config);
return { companyId, agentId, binding, provider, service, context, config, connections };
}
describe("company decision service", () => {
it("starts unconfigured with background sponsorship on and makes availability free", async () => {
const f = await fixture();
await db.delete(companyDecisionModels).where(eq(companyDecisionModels.companyId, f.companyId));
expect(await f.service.settings(f.companyId)).toMatchObject({ enabled: false, allowBackground: true, connectionId: null });
expect(await f.service.availability(f.context)).toEqual({ available: false, reason: "not_configured" });
await f.service.configure(f.companyId, "alice", updateDecisionModelSchema.parse({ ...f.binding, enabled: true }));
const before = await db.select().from(secretAccessEvents).where(eq(secretAccessEvents.companyId, f.companyId));
const memo = f.service.availabilityForRequest();
expect(memo(f.context)).toBe(memo(f.context));
expect(await memo(f.context)).toEqual({ available: true });
expect(await db.select().from(secretAccessEvents).where(eq(secretAccessEvents.companyId, f.companyId))).toHaveLength(before.length);
expect(f.provider).not.toHaveBeenCalled();
});
it("records a human service charge without an agent, exact cost and no input or answer content", async () => {
const f = await fixture();
const result = await f.service.decide(f.context, { ...DECISION_TEST_REQUEST, state: "PRIVATE PAYLOAD" });
expect(result.status).toBe("succeeded");
expect(f.provider.mock.calls[0][0].apiKey).toBe("fixture-key");
const [event] = await db.select().from(costEvents).where(eq(costEvents.companyId, f.companyId));
expect(event).toMatchObject({ agentId: null, responsibleUserId: "alice", usageKind: "decision", costCents: 0.001, costStatus: "estimated", heartbeatRunId: null });
const rows = await db.select().from(decisionInvocations).where(eq(decisionInvocations.companyId, f.companyId));
expect(rows[0]).toMatchObject({ status: "succeeded", actorType: "user", responsibleUserId: "alice", costEventId: event.id });
expect(JSON.stringify(rows)).not.toContain("PRIVATE PAYLOAD"); expect(JSON.stringify(rows)).not.toContain("probability");
expect((await costService(db).byUser(f.companyId)).rows.find(r => r.userId === "alice")?.costCentsExact).toBe("0.0010000");
expect((await costService(db).byAgent(f.companyId))[0].agentId).toBeNull();
expect((await db.select().from(budgetReservations).where(eq(budgetReservations.companyId, f.companyId)))[0].state).toBe("settled");
});
it("allows real background use, preserves explicit off, and never sponsors a denied human", async () => {
const f = await fixture();
const context: DecisionContext = { companyId: f.companyId, feature: backgroundFeature, actor: { type: "system" } };
expect((await f.service.decide(context, DECISION_TEST_REQUEST)).status).toBe("succeeded");
expect((await db.select().from(decisionInvocations).where(eq(decisionInvocations.companyId, f.companyId)))[0]).toMatchObject({ actorType: "system", responsibleUserId: null });
await f.service.configure(f.companyId, "alice", { ...f.config, allowBackground: false });
expect(await f.service.availability(context)).toEqual({ available: false, reason: "background_disabled" });
const second = await f.connections.save(f.companyId, "alice", { provider: "openrouter", method: "api_key", name: "Other key", ownership: "shared", apiKey: "other", agentIds: [], allAgents: true }, "other");
await f.service.configure(f.companyId, "alice", { ...second, enabled: true, allowBackground: false });
expect((await f.service.settings(f.companyId)).allowBackground).toBe(false);
await f.service.configure(f.companyId, "alice", f.config);
await db.insert(connectionGrantMembers).values({ companyId: f.companyId, grantId: f.binding.grantId, subjectType: "user", subjectId: "bob" });
expect(await f.service.decide({ ...f.context, feature: backgroundFeature }, DECISION_TEST_REQUEST)).toMatchObject({ status: "unavailable", reason: "access_denied" });
expect(f.provider).toHaveBeenCalledTimes(1);
});
it("retains the charge and dispatch snapshot when the task is deleted during provider work", async () => {
const f = await fixture(), issueId = randomUUID();
await db.insert(issues).values({ id: issueId, companyId: f.companyId, title: "Temporary task" });
f.provider.mockImplementationOnce(async () => {
await db.delete(issues).where(eq(issues.id, issueId));
return structuredClone(outcome);
});
expect((await f.service.decide({ ...f.context, issueId }, DECISION_TEST_REQUEST)).status).toBe("succeeded");
const [event] = await db.select().from(costEvents).where(eq(costEvents.companyId, f.companyId));
expect(event).toMatchObject({ issueId: null, costCents: 0.001 });
const [invocation] = await db.select().from(decisionInvocations).where(eq(decisionInvocations.companyId, f.companyId));
expect(invocation).toMatchObject({ issueId, status: "succeeded", costEventId: event.id });
});
it("rechecks revoked grants after availability, and can disable a revoked connection", async () => {
const f = await fixture(); expect(await f.service.availability(f.context)).toEqual({ available: true });
await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, f.binding.grantId));
expect(await f.service.decide(f.context, DECISION_TEST_REQUEST)).toMatchObject({ status: "unavailable", reason: "connection_unavailable" });
await f.service.configure(f.companyId, "alice", { ...f.config, enabled: false });
expect(await f.service.availability(f.context)).toEqual({ available: false, reason: "disabled" }); expect(f.provider).not.toHaveBeenCalled();
});
it.each(["disabled", "rotated"])("rejects a secret %s while admission waits for accounting", async change => {
const f = await fixture();
const [secret] = await db.select().from(companySecrets).where(eq(companySecrets.companyId, f.companyId));
let release!: () => void, locked!: (pid: number) => void;
const gate = new Promise<void>(resolve => { release = resolve; });
const acquired = new Promise<number>(resolve => { locked = resolve; });
const holding = withAccountingTransaction(db, f.companyId, async tx => {
const [row] = await tx.execute<{ pid: number }>(sql`select pg_backend_pid() as pid`);
locked(row.pid); await gate;
});
const pid = await acquired;
const pending = f.service.decide(f.context, DECISION_TEST_REQUEST);
try {
await vi.waitFor(async () => {
const [row] = await db.execute<{ count: number }>(sql`select count(*)::int as count from pg_stat_activity where ${pid} = any(pg_blocking_pids(pid))`);
expect(row.count).toBeGreaterThan(0);
}, { timeout: 5000 });
await db.update(companySecrets).set(change === "disabled" ? { status: "disabled" } : { latestVersion: secret.latestVersion + 1 }).where(eq(companySecrets.id, secret.id));
} finally { release(); await holding; }
expect(await pending).toMatchObject({ status: "unavailable", reason: "connection_unavailable" });
expect(f.provider).not.toHaveBeenCalled();
expect(await db.select().from(decisionInvocations).where(eq(decisionInvocations.companyId, f.companyId))).toHaveLength(0);
});
it("preserves sponsorship off when a deleted grant is replaced", async () => {
const f = await fixture();
await f.service.configure(f.companyId, "alice", { ...f.config, allowBackground: false });
await db.delete(connectionGrants).where(eq(connectionGrants.id, f.binding.grantId));
expect(await f.service.availability(f.context)).toMatchObject({ available: false, reason: "connection_unavailable" });
expect((await f.service.settings(f.companyId)).allowBackground).toBe(false);
const next = await f.connections.save(f.companyId, "alice", { provider: "openrouter", method: "api_key", name: "Replacement", ownership: "shared", apiKey: "other", agentIds: [], allAgents: true }, "other");
await f.service.configure(f.companyId, "alice", { ...next, enabled: true });
expect((await f.service.settings(f.companyId)).allowBackground).toBe(false);
expect(f.provider).not.toHaveBeenCalled();
});
it("rejects foreign-company credentials, membership loss, and invented feature handles", async () => {
const f = await fixture(), other = await fixture();
await expect(f.service.configure(f.companyId, "alice", { ...other.config })).rejects.toThrow();
await db.update(companyMemberships).set({ status: "inactive" }).where(and(eq(companyMemberships.companyId, f.companyId), eq(companyMemberships.principalId, "alice")));
expect(await f.service.availability(f.context)).toMatchObject({ available: false, reason: "access_denied" });
expect(await f.service.decide({ ...f.context, feature: { id: "settings.test", background: true }, actor: { type: "system" } }, DECISION_TEST_REQUEST)).toMatchObject({ status: "unavailable", reason: "access_denied" });
});
it("captures the active run identity and checks both human and agent access", async () => {
const f = await fixture(), issueId = randomUUID(), runId = randomUUID();
await db.insert(issues).values({ id: issueId, companyId: f.companyId, title: "Decision task", status: "in_progress", assigneeAgentId: f.agentId });
await db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId, status: "running", invocationSource: "on_demand", responsibleUserId: "alice", contextSnapshot: { issueId } });
const [identity] = await db.insert(runIdentityContexts).values({ companyId: f.companyId, runId, revision: 1, responsibleUserId: "bob", cause: "steering", correlationId: "test", acceptedAt: new Date() }).returning();
await db.update(heartbeatRuns).set({ responsibleUserId: "bob", activeIdentityContextId: identity.id }).where(eq(heartbeatRuns.id, runId));
const context: DecisionContext = { companyId: f.companyId, feature: settingsDecisionTest, actor: { type: "agent", agentId: f.agentId, runId, companyId: f.companyId, source: "agent_jwt", onBehalfOfUserId: "alice" } };
expect((await f.service.decide(context, DECISION_TEST_REQUEST)).status).toBe("succeeded");
expect((await db.select().from(decisionInvocations).where(eq(decisionInvocations.companyId, f.companyId)))[0]).toMatchObject({ responsibleUserId: "bob", runId, issueId, identityContextId: identity.id });
await db.delete(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, f.binding.connectionId));
expect(await f.service.availability(context)).toMatchObject({ available: false, reason: "access_denied" });
await db.update(heartbeatRuns).set({ responsibleUserId: null }).where(eq(heartbeatRuns.id, runId));
expect(await f.service.availability(context)).toMatchObject({ available: false, reason: "responsible_user_missing" });
});
it("serializes budget admission against concurrent requests", async () => {
const f = await fixture();
await db.insert(budgetPolicies).values({ companyId: f.companyId, scopeType: "company", scopeId: f.companyId, windowKind: "calendar_month_utc", amount: 1, reservationCents: "1", notifyEnabled: false });
let release!: () => void; const gate = new Promise<void>(resolve => { release = resolve; });
let entered!: () => void; const started = new Promise<void>(resolve => { entered = resolve; });
f.provider.mockImplementationOnce(async () => { entered(); await gate; return structuredClone(outcome); });
const first = f.service.decide(f.context, DECISION_TEST_REQUEST);
await started;
try { expect(await f.service.decide(f.context, DECISION_TEST_REQUEST)).toMatchObject({ status: "unavailable", reason: "budget_blocked" }); }
finally { release(); }
expect((await first).status).toBe("succeeded"); expect(f.provider).toHaveBeenCalledTimes(1);
});
it("blocks agent deletion while an in-flight or unknown decision retains a budget hold", async () => {
const f = await fixture(), runId = randomUUID();
await db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId, status: "running", invocationSource: "on_demand", responsibleUserId: "alice" });
await db.insert(budgetPolicies).values({ companyId: f.companyId, scopeType: "company", scopeId: f.companyId, windowKind: "calendar_month_utc", amount: 1, reservationCents: "1", notifyEnabled: false });
const context: DecisionContext = { companyId: f.companyId, feature: settingsDecisionTest,
actor: { type: "agent", agentId: f.agentId, runId, companyId: f.companyId, source: "agent_jwt" } };
const remove = () => agentService(db).remove(f.agentId);
f.provider.mockImplementationOnce(async () => {
await expect(remove()).rejects.toMatchObject({ status: 409, details: { code: "agent_decision_accounting_pending" } });
expect(await f.service.decide(f.context, DECISION_TEST_REQUEST)).toMatchObject({ status: "unavailable", reason: "budget_blocked" });
return { errorCode: "timeout", receipt: decisionReceipt("openai", null) };
});
expect((await f.service.decide(context, DECISION_TEST_REQUEST)).status).toBe("failed");
await expect(remove()).rejects.toMatchObject({ status: 409, details: { code: "agent_decision_accounting_pending" } });
expect((await db.select().from(budgetReservations).where(eq(budgetReservations.companyId, f.companyId)))[0]).toMatchObject({ state: "held", amountCents: "1.0000000" });
});
it("holds unknown billing until an audited correction, without rerunning the provider", async () => {
const f = await fixture(); f.provider.mockResolvedValue({ errorCode: "timeout", receipt: decisionReceipt("openai", null) });
expect((await f.service.decide(f.context, DECISION_TEST_REQUEST)).status).toBe("failed");
const [event] = await db.select().from(costEvents).where(eq(costEvents.companyId, f.companyId));
expect(event.costStatus).toBe("unpriced");
expect((await db.select().from(budgetReservations).where(eq(budgetReservations.companyId, f.companyId)))[0].state).toBe("held");
await billingReconciliationService(db).adjust(f.companyId, event.id, { idempotencyKey: "correction", expectedCents: "0", correctedCents: "0.002", reason: "Verified provider invoice", pricing: { source: "operator" } }, "alice");
expect((await db.select().from(budgetReservations).where(eq(budgetReservations.companyId, f.companyId)))[0].state).toBe("settled");
expect(f.provider).toHaveBeenCalledTimes(1);
});
it("recovers an interrupted dispatch once without paying for a retry", async () => {
const f = await fixture();
const [invocation] = await db.insert(decisionInvocations).values({ companyId: f.companyId, feature: "test.background", actorType: "system", actorId: "paperclip-decisions",
...f.binding, provider: "openai", model: "gpt-6-luna", questionTypes: ["boolean"], startedAt: new Date(Date.now() - 180_000) }).returning();
await db.insert(budgetReservations).values({ companyId: f.companyId, decisionInvocationId: invocation.id, amountCents: "0.01", providerStartedAt: invocation.startedAt });
await Promise.all([f.service.recoverInterrupted(), f.service.recoverInterrupted()]);
const events = await db.select().from(costEvents).where(eq(costEvents.companyId, f.companyId));
expect(events).toHaveLength(1); expect(events[0].costStatus).toBe("unpriced"); expect(f.provider).not.toHaveBeenCalled();
});
it("keeps public cost reporting agent-scoped and bounds decision input before payment", async () => {
expect(createCostEventSchema.safeParse({ agentId: null, provider: "openai", model: "gpt-6-luna", costCents: 1, occurredAt: new Date().toISOString() }).success).toBe(false);
const f = await fixture(); await expect(f.service.decide(f.context, { ...DECISION_TEST_REQUEST, state: "x".repeat(32_001) })).rejects.toThrow(); expect(f.provider).not.toHaveBeenCalled();
});
it("preserves an explicit sponsorship opt-out when a subsequent edit omits the field", async () => {
const f = await fixture();
await f.service.configure(f.companyId, "alice", { ...f.config, allowBackground: false });
const second = await f.connections.save(f.companyId, "alice", { provider: "openrouter", method: "api_key", name: "Other", ownership: "shared", apiKey: "other", agentIds: [], allAgents: true }, "other");
await f.service.configure(f.companyId, "alice", { ...second, enabled: true });
expect((await f.service.settings(f.companyId)).allowBackground).toBe(false);
});
it("rejects revoked secrets without provider work and returns usage on successful calls", async () => {
const f = await fixture();
expect(await f.service.decide(f.context, DECISION_TEST_REQUEST)).toMatchObject({ status: "succeeded", usage: { costCents: "0.0010000", costStatus: "estimated", inputTokens: 100 } });
await db.update(companySecrets).set({ status: "revoked" }).where(eq(companySecrets.companyId, f.companyId));
expect(await f.service.decide(f.context, DECISION_TEST_REQUEST)).toMatchObject({ status: "unavailable" });
expect(f.provider).toHaveBeenCalledTimes(1);
});
it.each(["agent", "project"] as const)("reserves and enforces applicable %s budgets", async scopeType => {
const f = await fixture(), projectId = randomUUID(), issueId = randomUUID(), runId = randomUUID();
await db.insert(projects).values({ id: projectId, companyId: f.companyId, name: "Decisions project" });
await db.insert(issues).values({ id: issueId, companyId: f.companyId, projectId, title: "Budgeted task", assigneeAgentId: f.agentId });
await db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId, status: "running", invocationSource: "on_demand", responsibleUserId: "alice", contextSnapshot: { issueId } });
const context: DecisionContext = { companyId: f.companyId, feature: settingsDecisionTest, actor: { type: "agent", agentId: f.agentId, runId, companyId: f.companyId, source: "agent_jwt" } };
const [policy] = await db.insert(budgetPolicies).values({ companyId: f.companyId, scopeType, scopeId: scopeType === "agent" ? f.agentId : projectId, windowKind: "calendar_month_utc", amount: 1, reservationCents: "2", notifyEnabled: false }).returning();
expect(await f.service.availability(context)).toEqual({ available: true });
expect(await f.service.decide(context, DECISION_TEST_REQUEST)).toMatchObject({ status: "unavailable", reason: "budget_blocked" });
expect(f.provider).not.toHaveBeenCalled();
await db.update(budgetPolicies).set({ amount: 5 }).where(eq(budgetPolicies.id, policy.id));
expect((await f.service.decide(context, DECISION_TEST_REQUEST)).status).toBe("succeeded");
expect((await db.select().from(budgetReservations).where(eq(budgetReservations.companyId, f.companyId)))[0]).toMatchObject({ agentId: f.agentId, projectId, amountCents: "2.0000000", state: "settled" });
});
it("releases reservations when the provider rejects a request before model work", async () => {
const f = await fixture();
f.provider.mockResolvedValue({ noProviderWork: true, errorCode: "provider_auth_failed", receipt: { ...outcome.receipt, inputTokens: 0, costCents: "0", pricingProvenance: { source: "unknown", evidence: "HTTP 401" } } });
expect((await f.service.decide(f.context, DECISION_TEST_REQUEST)).status).toBe("failed");
expect((await db.select().from(budgetReservations).where(eq(budgetReservations.companyId, f.companyId)))[0].state).toBe("released");
expect((await db.select().from(costEvents).where(eq(costEvents.companyId, f.companyId)))[0].costCents).toBe(0);
});
it("enforces manager-only configuration and tests, company isolation, and fixed sample execution", async () => {
const f = await fixture(), other = await fixture();
const app = express(); app.use(express.json());
let actor = f.context.actor;
app.use((req, _res, next) => { req.actor = actor as typeof req.actor; next(); });
app.use("/api", decisionModelRoutes(db)); app.use(errorHandler);
const url = `/api/companies/${f.companyId}/decision-model`;
expect((await request(app).get(url)).body.canManage).toBe(true);
expect((await request(app).get(`/api/companies/${other.companyId}/decision-model`)).status).toBe(403);
actor = { type: "board", userId: "alice", source: "session", companyIds: [f.companyId], memberships: [{ companyId: f.companyId, status: "active", membershipRole: "viewer" }] };
expect((await request(app).get(url)).body).toEqual({ canManage: false, settings: null, choices: [] });
expect((await request(app).put(url).send(f.config)).status).toBe(403);
expect((await request(app).post(`${url}/test`).send({ actor: { type: "system" } })).status).toBe(403);
actor = f.context.actor;
await f.service.configure(f.companyId, "alice", { ...f.config, enabled: false });
expect((await request(app).post(`${url}/test`).send({ state: "untrusted", actor: { type: "system" }, model: "untrusted" })).body).toEqual({ status: "unavailable", reason: "disabled" });
expect((await request(app).post(`${url}/decide`).send(DECISION_TEST_REQUEST)).status).toBe(404);
expect((await request(app).get(`${url}/history?limit=501`)).status).toBe(400);
expect((await request(app).get(`${url}/history?from=2026-10-01T00:00:00.000Z&to=2026-10-31T23:59:59.000Z`)).status).toBe(200);
});
it("keeps private task links out of company cost history for unauthorized readers", async () => {
const f = await fixture(), projectId = randomUUID(), issueId = randomUUID();
await db.insert(projects).values({ id: projectId, companyId: f.companyId, name: "Private project", visibility: "private", privacyOwnerUserId: "bob" });
await db.insert(issues).values({ id: issueId, companyId: f.companyId, projectId, title: "PRIVATE TITLE", identifier: "SECRET-1" });
await f.service.decide({ companyId: f.companyId, feature: backgroundFeature, actor: { type: "system" }, issueId }, DECISION_TEST_REQUEST);
await db.update(companyMemberships).set({ membershipRole: "member" }).where(and(eq(companyMemberships.companyId, f.companyId), eq(companyMemberships.principalId, "alice")));
const actor = { type: "board" as const, userId: "alice", source: "session" as const, companyIds: [f.companyId], memberships: [{ companyId: f.companyId, status: "active", membershipRole: "member" }] };
expect(await f.service.availability({ ...f.context, actor, issueId })).toMatchObject({ available: false, reason: "access_denied" });
const history = await f.service.history(f.companyId, actor);
expect(history[0]).toMatchObject({ issueId: null, issueIdentifier: null, runId: null });
expect(JSON.stringify(history)).not.toContain("SECRET");
});
});
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { eq } from "drizzle-orm";
import { eq, inArray } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import {
activityLog,
@@ -87,7 +87,6 @@ describePg("decisionService", () => {
options: [{ id: "yes", label: "Yes", effects: [{ type: "comment_on_issue", targetIssueId, staleness, bodyMarkdown: "hello" }] }],
...extra,
});
// Make an existing decision TTL-expired for the next sweep. Creating a
// decision that is already expired is impossible (create rejects a past
// expiresAt), and creating one that expires a few milliseconds later races
+1 -1
View File
@@ -162,7 +162,7 @@ describe("durable Dot Runner integration", () => {
}
it("reapplies the Dot-only migration after the merged gateway schema", async () => {
const migration = await readFile(new URL("../../../packages/db/src/migrations/0312_broken_sentinels.sql", import.meta.url), "utf8");
const migration = await readFile(new URL("../../../packages/db/src/migrations/0317_messy_famine.sql", import.meta.url), "utf8");
for (const statement of migration.split("--> statement-breakpoint")) {
if (statement.trim()) await db.execute(sql.raw(statement));
}
@@ -3,6 +3,7 @@ import {
canonicalizeEffectiveRunConfigCategory,
createEffectiveRunConfigFingerprints,
diffEffectiveRunConfigFingerprints,
type EffectiveRunConfigSecretManifestEntry,
} from "../services/effective-run-config-fingerprints.ts";
describe("effective run config fingerprints", () => {
@@ -301,3 +302,29 @@ describe("effective run config fingerprints", () => {
});
});
});
describe("configured Paperclip environment freshness", () => {
const fingerprint = (env: Record<string, unknown>, secretManifest?: EffectiveRunConfigSecretManifestEntry[]) =>
createEffectiveRunConfigFingerprints({ session: { env }, secretManifest }).sessionFingerprint;
it("detects additions, changes, and removals without recording values", () => {
const absent = fingerprint({});
const first = fingerprint({ PAPERCLIP_PAGE_BUCKET: "first-bucket" });
const changed = fingerprint({ PAPERCLIP_PAGE_BUCKET: "second-bucket" });
expect(first.fingerprint).not.toBe(absent.fingerprint);
expect(changed.fingerprint).not.toBe(first.fingerprint);
expect(fingerprint({}).fingerprint).toBe(absent.fingerprint);
expect(first.canonicalJson).not.toContain("first-bucket");
for (const key of ["PAPERCLIP_RUN_ID", "PAPERCLIP_RUNNER_EXTERNAL_SANDBOX", "PAPERCLIP_NORMALIZED_SESSION_ID"]) {
expect(fingerprint({ [key]: "first" }).fingerprint).toBe(fingerprint({ [key]: "second" }).fingerprint);
}
});
it("detects custom namespaced secret version changes", () => {
const env = { PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY: { type: "secret_ref", secretId: "pages-key" } };
const manifest = (version: number) => [{ configPath: "env.PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY", envKey: "PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY", secretId: "pages-key", version }];
expect(fingerprint(env, manifest(1)).fingerprint).not.toBe(fingerprint(env, manifest(2)).fingerprint);
expect(fingerprint(env, manifest(1)).canonicalJson).toContain("pages-key");
});
});
@@ -62,6 +62,12 @@ vi.mock("../services/index.js", () => ({
workspaceOperationService: () => ({}),
accessService: () => ({
canUser: vi.fn(),
decide: vi.fn(async (input: { action: string }) => ({
allowed: ["project:read", "issue:read"].includes(input.action),
action: input.action,
reason: ["project:read", "issue:read"].includes(input.action) ? "allow_explicit_grant" : "deny_missing_grant",
explanation: ["project:read", "issue:read"].includes(input.action) ? "Allowed by test default." : "Missing permission.",
})),
hasPermission: vi.fn(),
}),
agentService: () => ({
@@ -0,0 +1,78 @@
import { createInterface } from "node:readline";
import { PassThrough } from "node:stream";
import { describe, expect, it } from "vitest";
import {
createRequest, definePlugin, isJsonRpcResponse, JsonRpcCallError, parseMessage,
PLUGIN_RPC_ERROR_CODES, serializeMessage, startWorkerRpcHost, type JsonRpcResponse,
} from "@paperclipai/plugin-sdk";
import {
getWorkspaceRestoreDiagnostic, withWorkspaceRestoreDiagnostics, withWorkspaceRestoreStep,
} from "@paperclipai/adapter-utils/workspace-restore-diagnostics";
import { preserveEnvironmentSyncOutErrorDiagnostic } from "../services/environment-sync-out-error.js";
async function roundTrip(method: string, error: unknown): Promise<{ error: JsonRpcCallError; wire: string }> {
const stdin = new PassThrough();
const stdout = new PassThrough();
const lines = createInterface({ input: stdout });
const worker = startWorkerRpcHost({ stdin, stdout, plugin: definePlugin({
async setup() {},
async onEnvironmentSyncOut() { throw error; },
async onEnvironmentSyncIn() { throw error; },
async onEnvironmentExecute() { throw error; },
}) });
try {
const response = new Promise<{ message: JsonRpcResponse; wire: string }>((resolve) => {
lines.on("line", (wire) => {
const message = parseMessage(wire);
if (isJsonRpcResponse(message)) resolve({ message, wire });
});
});
stdin.write(serializeMessage(createRequest(method, {}, "sync-out-test")));
const { message, wire } = await response;
if (!("error" in message) || !message.error) throw new Error("Expected RPC failure");
return { error: new JsonRpcCallError(message.error), wire };
} finally {
worker.stop(); lines.close(); stdin.destroy(); stdout.destroy();
}
}
describe("environment sync-out restore diagnostics", () => {
it("retains bounded evidence through the real worker RPC roundtrip and host restore classifier", async () => {
const failure = Object.assign(new Error("Workspace export failed"), {
name: "private-provider-class", code: "ETIMEDOUT", statusCode: 504,
response: { data: { apiKey: "private-token" } }, path: "/private-path",
cause: new Error("private-cause"), data: { credentials: "private-credentials" },
});
const { error, wire } = await roundTrip("environmentSyncOut", failure);
expect(wire).not.toContain("private-");
expect(wire.length).toBeLessThan(400);
expect(error.code).toBe(PLUGIN_RPC_ERROR_CODES.WORKER_ERROR);
expect(error.message).toBe(failure.message);
const before = structuredClone({ message: error.message, code: error.code, data: error.data });
const logs: string[] = [];
await expect(withWorkspaceRestoreDiagnostics("workspace", () => withWorkspaceRestoreStep("workspace_transfer", async () => {
throw preserveEnvironmentSyncOutErrorDiagnostic(error);
}), async (line) => { logs.push(line); })).rejects.toBe(error);
expect(getWorkspaceRestoreDiagnostic(error)).toEqual({ phase: "workspace", step: "workspace_transfer", errorCode: "ETIMEDOUT", httpStatus: 504 });
expect(logs).toEqual(['[paperclip] Workspace restore diagnostic: {"phase":"workspace","step":"workspace_transfer","errorCode":"ETIMEDOUT","httpStatus":504}\n']);
expect({ message: error.message, code: error.code, data: error.data }).toEqual(before);
expect(error).not.toHaveProperty("cause");
});
it.each(["environmentSyncIn", "environmentExecute"])("does not add the sync-out envelope to %s", async (method) => {
const { error } = await roundTrip(method, Object.assign(new Error("Provider failure"), { code: "EACCES", status: 503 }));
expect(error.data).toBeUndefined();
expect(preserveEnvironmentSyncOutErrorDiagnostic(error)).toBe(error);
expect(getWorkspaceRestoreDiagnostic(error)).toBeUndefined();
});
it("keeps old workers and unknown diagnostics compatible without changing policy fields", async () => {
const { error } = await roundTrip("environmentSyncOut", new Error("daytona_sandbox_not_found"));
expect(error.data).toBeUndefined();
expect(preserveEnvironmentSyncOutErrorDiagnostic(error)).toBe(error);
expect(error.message).toBe("daytona_sandbox_not_found");
const original = Object.freeze(new JsonRpcCallError({ code: -32001, message: "Existing worker failure" }));
expect(preserveEnvironmentSyncOutErrorDiagnostic(original)).toBe(original);
expect(preserveEnvironmentSyncOutErrorDiagnostic(null)).toBeNull();
});
});
@@ -1,3 +1,4 @@
import { sql } from "drizzle-orm";
import { EventEmitter } from "node:events";
import fs from "node:fs";
import os from "node:os";
@@ -7,6 +8,14 @@ import express from "express";
import request from "supertest";
import { beforeEach, describe, expect, it, vi } from "vitest";
// This unit suite isolates runtime lifecycle behavior; privacy is covered with a
// real database by privacy-production-review.test.ts.
vi.mock("../services/authorization.js", async () => ({
...(await vi.importActual<typeof import("../services/authorization.js")>("../services/authorization.js")),
executionWorkspaceReadSqlCondition: async () => sql<boolean>`true`,
canActorReadExecutionWorkspace: async () => true,
}));
const mockExecutionWorkspaceService = vi.hoisted(() => ({
getById: vi.fn(),
update: vi.fn(),
@@ -157,8 +166,8 @@ function createRegisteredRepairFixture(
prefix: string,
options: { targetInstanceId?: string; withCli?: boolean } = {},
) {
const workspaceCwd = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
const baseCwd = fs.mkdtempSync(path.join(os.tmpdir(), `${prefix}base-`));
const workspaceCwd = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), prefix)));
const baseCwd = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), `${prefix}base-`)));
const configDir = path.join(workspaceCwd, ".paperclip");
const sourceConfigPath = path.join(baseCwd, ".paperclip", "config.json");
const targetInstanceId = options.targetInstanceId ?? "repair-target";
@@ -300,7 +309,7 @@ describe("execution workspace runtime control conflict and failure reconciliatio
.post(`/api/execution-workspaces/${executionWorkspaceId}/runtime-services/stop`)
.send({});
expect(res.status).toBe(409);
expect(res.status, JSON.stringify(res.body)).toBe(409);
expect(res.body.details ?? res.body).toMatchObject({
code: "workspace_runtime_control_in_progress",
activeAction: "start",
@@ -322,7 +331,7 @@ describe("execution workspace runtime control conflict and failure reconciliatio
.post(`/api/execution-workspaces/${executionWorkspaceId}/runtime-services/start`)
.send({});
expect(res.status).toBe(403);
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(mockWorkspaceOperationService.assertRuntimeControlAvailable).not.toHaveBeenCalled();
});
@@ -367,7 +376,7 @@ describe("execution workspace runtime control conflict and failure reconciliatio
.post(`/api/execution-workspaces/${executionWorkspaceId}/runtime-commands/repair`)
.send({});
expect(res.status).toBe(422);
expect(res.status, JSON.stringify(res.body)).toBe(422);
expect(res.body).toMatchObject({
code: "workspace_repair_precondition_failed",
reason: "seed_manifest_malformed",
@@ -415,7 +424,7 @@ describe("execution workspace runtime control conflict and failure reconciliatio
.post(`/api/execution-workspaces/${executionWorkspaceId}/runtime-commands/repair`)
.send({});
expect(res.status).toBe(422);
expect(res.status, JSON.stringify(res.body)).toBe(422);
expect(res.body).toMatchObject({
code: "workspace_repair_precondition_failed",
reason: "source_registration_invalid",
@@ -450,7 +459,7 @@ describe("execution workspace runtime control conflict and failure reconciliatio
.post(`/api/execution-workspaces/${executionWorkspaceId}/runtime-commands/repair`)
.send({});
expect(res.status).toBe(422);
expect(res.status, JSON.stringify(res.body)).toBe(422);
expect(res.body).toMatchObject({
code: "workspace_repair_precondition_failed",
reason: "source_registration_invalid",
@@ -471,7 +480,7 @@ describe("execution workspace runtime control conflict and failure reconciliatio
.post(`/api/execution-workspaces/${executionWorkspaceId}/runtime-commands/repair`)
.send({});
expect(res.status).toBe(422);
expect(res.status, JSON.stringify(res.body)).toBe(422);
expect(res.body).toMatchObject({
code: "workspace_repair_precondition_failed",
reason: "source_registration_invalid",
@@ -493,7 +502,7 @@ describe("execution workspace runtime control conflict and failure reconciliatio
.post(`/api/execution-workspaces/${executionWorkspaceId}/runtime-commands/repair`)
.send({});
expect(res.status).toBe(422);
expect(res.status, JSON.stringify(res.body)).toBe(422);
expect(res.body).toMatchObject({
code: "workspace_repair_precondition_failed",
reason: "seed_manifest_instance_mismatch",
@@ -573,7 +582,7 @@ describe("execution workspace runtime control conflict and failure reconciliatio
.post(`/api/execution-workspaces/${executionWorkspaceId}/runtime-commands/repair`)
.send({});
expect(res.status).toBe(200);
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(mockStopRuntimeServicesForExecutionWorkspace).toHaveBeenCalledWith(
expect.objectContaining({ executionWorkspaceId, workspaceCwd: fixture.workspaceCwd }),
);
@@ -604,7 +613,7 @@ describe("execution workspace runtime control conflict and failure reconciliatio
.post(`/api/execution-workspaces/${executionWorkspaceId}/runtime-commands/repair`)
.send({});
expect(res.status).toBe(200);
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(mockStopRuntimeServicesForExecutionWorkspace).toHaveBeenCalledTimes(1);
expect(mockStartRuntimeServices).not.toHaveBeenCalled();
expect(mockBuildWorkspaceRuntimeDesiredStatePatch).toHaveBeenCalledWith(
@@ -656,7 +665,7 @@ describe("execution workspace runtime control conflict and failure reconciliatio
.post(`/api/execution-workspaces/${executionWorkspaceId}/runtime-commands/repair`)
.send({});
expect(res.status).toBe(500);
expect(res.status, JSON.stringify(res.body)).toBe(500);
expect(res.body).toEqual({ error: "Internal server error" });
expect(progress).toEqual(expect.arrayContaining([
expect.objectContaining({ metadata: { seedFailurePhase: "restore" } }),
@@ -1,9 +1,16 @@
import { sql } from "drizzle-orm";
import express from "express";
import request from "supertest";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { errorHandler } from "../middleware/index.js";
import { executionWorkspaceRoutes } from "../routes/execution-workspaces.js";
vi.mock("../services/authorization.js", async (importActual) => ({
...await importActual<typeof import("../services/authorization.js")>(),
executionWorkspaceReadSqlCondition: async () => sql<boolean>`true`,
canActorReadExecutionWorkspace: async () => true,
}));
const mockExecutionWorkspaceService = vi.hoisted(() => ({
list: vi.fn(),
listOverview: vi.fn(),
@@ -133,6 +140,7 @@ describe("execution workspace routes", () => {
},
]);
expect(mockExecutionWorkspaceService.listSummaries).toHaveBeenCalledWith("company-1", {
readCondition: expect.anything(),
projectId: undefined,
projectWorkspaceId: undefined,
issueId: undefined,
@@ -159,7 +167,7 @@ describe("execution workspace routes", () => {
status: ["active", "idle"],
limit: 25,
offset: 10,
});
}, expect.anything());
});
it("rejects invalid workspace overview pagination", async () => {
@@ -224,11 +224,13 @@ describe("external object routes", () => {
const app = await createApp(ownerActor());
const summary = await request(app).get(`/api/issues/${issueId}/external-object-summary`);
expect(summary.status).toBe(403);
expect(summary.status).toBe(404);
expect(summary.body.error).toBe("Issue not found");
expect(mockExternalObjectsService.getIssueSummary).not.toHaveBeenCalled();
const list = await request(app).get(`/api/issues/${issueId}/external-objects`);
expect(list.status).toBe(403);
expect(list.status).toBe(404);
expect(list.body.error).toBe("Issue not found");
expect(mockExternalObjectsService.listForIssue).not.toHaveBeenCalled();
});
+29 -2
View File
@@ -208,6 +208,20 @@ describeEmbeddedPostgres("workspace file resources", () => {
await tempDb?.cleanup();
});
it("withholds private task files and private cross-project targets", async () => {
const { projectRoot, executionRoot, targetProjectRoot } = await makeWorkspace();
const graph = await seedGraph(db, { projectRoot, executionRoot, targetProjectRoot });
await fs.writeFile(path.join(projectRoot, "secret.txt"), "PRIVATE_FILE", "utf8");
await fs.writeFile(path.join(targetProjectRoot, "secret.txt"), "PRIVATE_TARGET", "utf8");
const app = createApp(db, { type: "board", userId: "board-user", companyIds: [graph.companyId], source: "session", isInstanceAdmin: false });
await db.update(issues).set({ visibility: "private", responsibleUserId: "owner" }).where(eq(issues.id, graph.issueId));
await request(app).get(`/api/issues/${graph.issueId}/file-resources/content`).query({ workspace: "project", path: "secret.txt" }).expect(404);
await db.update(issues).set({ visibility: "open" }).where(eq(issues.id, graph.issueId));
await request(app).get(`/api/issues/${graph.issueId}/file-resources/content`).query({ workspace: "project", path: "secret.txt" }).expect(200);
await db.update(projects).set({ visibility: "private" }).where(eq(projects.id, graph.targetProjectId));
await request(app).get(`/api/issues/${graph.issueId}/file-resources/content`).query({ projectId: graph.targetProjectId, workspaceId: graph.targetProjectWorkspaceId, path: "secret.txt" }).expect(404);
});
it("resolves and reads a project file without exposing absolute paths", async () => {
const { root, projectRoot, executionRoot } = await makeWorkspace();
const graph = await seedGraph(db, { projectRoot, executionRoot });
@@ -981,7 +995,7 @@ describeEmbeddedPostgres("workspace file resources", () => {
expect(linkedSecret.status).toBe(403);
});
it("rejects denied paths, non-regular files, oversized text, binary, and HTML while previewing SVG as source", async () => {
it("rejects denied paths, non-regular files, oversized text and binary while returning HTML and SVG as text", async () => {
const { projectRoot, executionRoot } = await makeWorkspace();
const graph = await seedGraph(db, { projectRoot, executionRoot });
await fs.mkdir(path.join(projectRoot, ".git"), { recursive: true });
@@ -1000,7 +1014,7 @@ describeEmbeddedPostgres("workspace file resources", () => {
isInstanceAdmin: false,
});
for (const filePath of [".git/config", "folder", "big.txt", "blob.bin", "index.html"]) {
for (const filePath of [".git/config", "folder", "big.txt", "blob.bin"]) {
const res = await request(app)
.get(`/api/issues/${graph.issueId}/file-resources/content`)
.query({ workspace: "project", path: filePath });
@@ -1012,6 +1026,19 @@ describeEmbeddedPostgres("workspace file resources", () => {
expect(svg.status).toBe(200);
expect(svg.body.resource.previewKind).toBe("text");
expect(svg.body.content.data).toContain("<svg");
const html = await request(app)
.get(`/api/issues/${graph.issueId}/file-resources/content`)
.query({ workspace: "project", path: "index.html" });
expect(html.status).toBe(200);
expect(html.headers["content-type"]).toContain("application/json");
expect(html.headers["x-content-type-options"]).toBe("nosniff");
expect(html.body.resource).toMatchObject({ contentType: "text/html", previewKind: "text", capabilities: { preview: true } });
expect(html.body.content).toEqual({ encoding: "utf8", data: "<script>alert(1)</script>" });
const downloaded = await request(app)
.get(`/api/issues/${graph.issueId}/file-resources/content`)
.query({ workspace: "project", path: "index.html", download: "1" });
expect(downloaded.status).toBe(200);
expect(downloaded.headers["content-disposition"]).toBe('attachment; filename="index.html"');
});
it("rejects remote workspaces without fetching provider resources", async () => {
+2 -1
View File
@@ -1,6 +1,6 @@
import { randomUUID } from "node:crypto";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import { agents, companies, createDb, heartbeatRuns } from "@paperclipai/db";
import { costEvents, agents, companies, createDb, heartbeatRuns } from "@paperclipai/db";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
@@ -26,6 +26,7 @@ describeEmbeddedPostgres("heartbeat list", () => {
}, 20_000);
afterEach(async () => {
await db.delete(costEvents);
await db.delete(heartbeatRuns);
await db.delete(agents);
await db.delete(companies);
@@ -5,9 +5,10 @@ import { legacyDispositionFingerprint, LEGACY_DISPOSITION_REPAIR_INSTRUCTION } f
import * as controllerLeases from "../services/legacy-controller-lease.js";
import * as instructionWorkingCopies from "../services/agent-instruction-working-copies.js";
import * as runEvents from "../services/heartbeat-run-events.js";
import { waitForPendingRunFailureReports } from "../services/run-failure-report.js";
import { instanceSettingsService } from "../services/instance-settings.js";
import { createHash, randomUUID } from "node:crypto";
import { terminalizeLegacyExecution } from "../services/legacy-execution-recovery.js";
import { recordLegacyWorkspaceRestoreFailure, terminalizeLegacyExecution } from "../services/legacy-execution-recovery.js";
import { issueService } from "../services/issues.js";
import { getExecutionBlocker } from "../services/execution-blocker.js";
import { adapterExecutionControls, createAdapterExecutionControl } from "../services/adapter-execution-control.js";
@@ -33,7 +34,9 @@ import {
agentWakeupRequests,
approvals,
authUsers,
budgetIncidents,
budgetPolicies,
budgetReservations,
chatActions,
chatConversations,
chatDeliveries,
@@ -601,6 +604,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
await db.delete(issueTreeHolds);
await db.delete(agentTaskSessions);
await db.delete(issueApprovals);
await db.delete(budgetIncidents);
await db.delete(approvals);
await db.update(issues).set({ lastStatusDecisionId: null });
await db.delete(statusDecisionEffects);
@@ -748,6 +752,20 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
claimedAt: now,
});
if (input?.includeIssue !== false) {
await db.insert(issues).values({
id: issueId,
companyId,
title: "Recover local adapter after lost process",
status: "in_progress",
priority: "medium",
assigneeAgentId: agentId,
responsibleUserId: "responsible-user",
issueNumber: 1,
identifier: `${issuePrefix}-1`,
});
}
await db.insert(heartbeatRuns).values({
id: runId,
companyId,
@@ -775,19 +793,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
seq: 1, eventType: "adapter.invoke", payload: { adapterType: input?.adapterType ?? "codex_local" } });
if (input?.includeIssue !== false) {
await db.insert(issues).values({
id: issueId,
companyId,
title: "Recover local adapter after lost process",
status: "in_progress",
priority: "medium",
assigneeAgentId: agentId,
checkoutRunId: runId,
executionRunId: runId,
responsibleUserId: "responsible-user",
issueNumber: 1,
identifier: `${issuePrefix}-1`,
});
await db.update(issues).set({ checkoutRunId: runId, executionRunId: runId }).where(eq(issues.id, issueId));
}
return { companyId, agentId, runId, wakeupRequestId, issueId };
@@ -1508,6 +1514,11 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
startedAt: now,
});
// Complete the circular issue/run fixture after both FK targets exist.
await db.update(heartbeatRuns)
.set({ scopeKind: "issue", issueId })
.where(eq(heartbeatRuns.id, runId));
return { companyId, agentId, runId, wakeupRequestId, issueId };
}
@@ -2706,6 +2717,10 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
stopReason: "process_lost",
timeoutConfigured: false,
timeoutFired: false,
processLossDiagnostic: {
pidRecorded: true, groupRecorded: false, localCheck: "not_observed_alive", retryEligible: true,
observerUptimeMs: expect.any(Number), runPredatesObserver: true,
},
});
// The legacy engine writes this terminal status through the same
// guarded emitter that reports a genuine failed transition to Sentry.
@@ -2715,6 +2730,10 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
runId,
errorCode: "process_lost",
runStatus: "failed",
diagnostics: expect.objectContaining({ execution: expect.objectContaining({
processLossPidRecorded: true, processLossGroupRecorded: false, processLossLocalCheck: "not_observed_alive",
processLossRetryEligible: true, processLossRunPredatesObserver: true,
}) }),
}),
);
const [action] = await db
@@ -5678,6 +5697,9 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
);
});
expect(configurationComment).toBeTruthy();
await heartbeat.waitForRunExecutionDrain(runId);
await waitForPendingRunFailureReports();
expect(mockCaptureRunFailure.mock.calls.filter(([event]) => event.runId === runId)).toEqual([]);
});
it("queues one finish-handoff wake when a successful run leaves in-progress work without a next action", async () => {
@@ -7462,6 +7484,34 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
}
});
it("persists a failed capture before heartbeat failure finalization settles an older receipt", async () => {
const { companyId, agentId, runId } = await seedRunFixture({ runtimeMode: "legacy", agentStatus: "idle", runStatus: "queued" });
await db.insert(budgetPolicies).values({ companyId, scopeType: "company", scopeId: companyId,
metric: "billed_cents", windowKind: "calendar_month_utc", amount: 100, reservationCents: "10.0000000", isActive: true });
mockAdapterExecute.mockImplementationOnce(async (raw?: unknown) => {
const input = raw as { onUsage: (receipt: import("@paperclipai/adapter-utils").AdapterUsageCheckpoint) => Promise<void> };
await input.onUsage({ costUsd: 0, complete: true });
const transaction = vi.spyOn(db, "transaction").mockRejectedValueOnce(new Error("Database temporarily unavailable"));
const rename = vi.spyOn(fs, "rename").mockRejectedValueOnce(new Error("Receipt disk full"));
try {
// A paid capture and the first database fence write both fail. The
// heartbeat catch must retry the fence before terminalizing.
await input.onUsage({ costUsd: 0.25, usage: { inputTokens: 10, outputTokens: 2 }, complete: true });
throw new Error("Expected capture to reject");
} finally { transaction.mockRestore(); rename.mockRestore(); }
});
const heartbeat = heartbeatService(db);
await heartbeat.resumeQueuedRuns();
await heartbeat.drainActiveRunExecutions();
expect(mockAdapterExecute).toHaveBeenCalledTimes(1);
expect(await heartbeat.getRun(runId)).toMatchObject({ status: "failed", costAccountedAt: null,
costAccountingPending: true, accountingLastError: "usage_capture_failed",
usageJson: { accountingReceiptReady: false, accountingCaptureFailed: true } });
expect(await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, runId))).toEqual([]);
expect((await db.select().from(budgetReservations).where(eq(budgetReservations.runId, runId)))[0]?.state).toBe("held");
expect(Number((await db.select().from(agentRuntimeState).where(eq(agentRuntimeState.agentId, agentId)))[0]?.totalCostCents ?? 0)).toBe(0);
});
it("stops controller renewal and releases execution controls when teardown deadline cleanup throws", async () => {
const { runId, issueId } = await seedRunFixture({ runtimeMode: "legacy", agentStatus: "idle", runStatus: "queued" });
mockAdapterExecute.mockImplementationOnce(async () => {
@@ -7798,6 +7848,36 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
},
);
it.each([{}, { command: "/nonexistent-paperclip-bootstrap-command" }])("releases holds for real process bootstrap failures: %j", async (config) => {
const { execute } = await import("../adapters/process/execute.js");
mockAdapterExecute.mockImplementationOnce(execute);
const { runId, agentId } = await seedRunFixture({ runtimeMode: "legacy", agentStatus: "idle", runStatus: "queued", includeIssue: false });
await db.update(agents).set({ adapterType: "process", adapterConfig: config }).where(eq(agents.id, agentId));
const heartbeat = heartbeatService(db);
await heartbeat.resumeQueuedRuns();
await heartbeat.drainActiveRunExecutions();
expect(await heartbeat.getRun(runId)).toMatchObject({ status: "failed", costAccountingPending: false, costAccountedAt: expect.any(Date) });
expect((await db.select().from(budgetReservations).where(eq(budgetReservations.runId, runId)))[0]?.state).toBe("released");
expect(await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, runId))).toEqual([]);
});
it("releases the dispatch reservation after a proven pre-provider adapter failure", async () => {
mockAdapterExecute.mockResolvedValueOnce({
exitCode: 1, signal: null, timedOut: false,
errorMessage: "Provider startup failed", provider: "test", model: "test-model",
executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
});
const { runId } = await seedRunFixture({ runtimeMode: "legacy", agentStatus: "idle", runStatus: "queued", includeIssue: false });
const heartbeat = heartbeatService(db);
await heartbeat.resumeQueuedRuns();
await heartbeat.drainActiveRunExecutions();
const run = await heartbeat.getRun(runId);
expect(run).toMatchObject({ status: "failed", costAccountingPending: false });
expect(run?.costAccountedAt).not.toBeNull();
expect((await db.select().from(budgetReservations).where(eq(budgetReservations.runId, runId)))[0]).toMatchObject({ state: "released" });
expect(await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, runId))).toEqual([]);
});
it.each(["single Stop", "agent pause"] as const)(
"fences adapter registration while an earlier no-owner %s waits to commit",
async (operation) => {
@@ -7897,9 +7977,11 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
try {
await vi.waitFor(async () => {
const [row] = await db.execute<{ count: number }>(sql`
select count(*)::int as count from pg_stat_activity
where datname = current_database() and ${pid} = any(pg_blocking_pids(pid))
and query ilike '%update%heartbeat_runs%'
select count(*)::int as count from pg_stat_activity activity
where datname = current_database() and ${pid} = any(pg_blocking_pids(activity.pid))
and wait_event_type = 'Lock'
and exists (select 1 from pg_locks locks where locks.pid = activity.pid
and locks.relation = 'heartbeat_runs'::regclass)
`);
expect(row!.count).toBeGreaterThan(0);
});
@@ -7922,6 +8004,10 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
releaseAdapter();
await heartbeat.drainActiveRunExecutions();
const settledRun = await heartbeat.getRun(runId);
expect(settledRun?.costAccountingPending).toBe(false);
expect(settledRun?.costAccountedAt).not.toBeNull();
expect((await db.select().from(budgetReservations).where(eq(budgetReservations.runId, runId)))[0]).toMatchObject({ state: "released" });
expect(await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, runId))).toEqual([]);
expect({
status: settledRun?.status,
errorCode: settledRun?.errorCode,
@@ -7970,6 +8056,63 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
}
});
it("preserves a copy-back obligation recorded after Stop reads the running adapter", async () => {
const { runId, companyId, issueId } = await seedRunFixture({ runtimeMode: "legacy", adapterType: "codex_local" });
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
const [environment] = await db.insert(environments).values({ name: `Stop restore race ${runId}`, driver: "sandbox" }).returning();
const [lease] = await db.insert(environmentLeases).values({ companyId, issueId, heartbeatRunId: runId,
environmentId: environment.id, provider: "daytona", providerLeaseId: randomUUID(), status: "active",
leasePolicy: "ephemeral", metadata: { driver: "sandbox" },
}).returning();
const control = createAdapterExecutionControl();
adapterExecutionControls.set(runId, control);
let releaseWrite!: () => void;
const writeGate = new Promise<void>(resolve => { releaseWrite = resolve; });
let reportWrite!: () => void;
const writeCaptured = new Promise<void>(resolve => { reportWrite = resolve; });
const originalUpdate = db.update.bind(db);
const writeSpy = vi.spyOn(db, "update").mockImplementationOnce((table) => {
const update = originalUpdate(table);
const originalSet = update.set.bind(update);
vi.spyOn(update, "set").mockImplementationOnce((value) => {
const query = originalSet(value);
const originalWhere = query.where.bind(query);
vi.spyOn(query, "where").mockImplementationOnce((condition) => {
reportWrite();
return writeGate.then(() => originalWhere(condition)) as unknown as ReturnType<typeof query.where>;
});
return query;
});
return update;
});
const heartbeat = heartbeatService(db);
const stopping = heartbeat.cancelRun(runId);
try {
await writeCaptured;
// This commits after Stop captured its old result, before Stop's write.
await recordLegacyWorkspaceRestoreFailure(db, run, { workspaceRestoreFailure: "restore_failed" });
releaseWrite();
await vi.waitFor(() => expect(control.controller.signal.aborted).toBe(true));
const [requested] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
expect(requested.resultJson).toMatchObject({ workspaceRestoreFailure: "restore_failed",
workspaceRestoreRecovery: { leaseIds: [lease.id] }, executionCancellation: { state: "requested" } });
expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, lease.id)))[0])
.toMatchObject({ leasePolicy: "retain_on_failure", status: "pending_cleanup" });
const cancelled = await terminalizeLegacyExecution({ db, run: requested, status: "cancelled", reconcileIfNeeded: true,
patch: { resultJson: { executionCancellation: { state: "acknowledged" } } } });
control.finish();
await expect(stopping).resolves.toMatchObject({ status: "cancelled" });
expect(cancelled?.resultJson).toMatchObject({ workspaceRestoreFailure: "restore_failed", workspaceRestoreRecovery: { leaseIds: [lease.id] } });
expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId!))).toHaveLength(1);
} finally {
releaseWrite();
writeSpy.mockRestore();
control.finish();
adapterExecutionControls.delete(runId);
await stopping.catch(() => undefined);
}
});
it("clears the detached warning when the run reports activity again", async () => {
const { runId } = await seedRunFixture({
includeIssue: false,
@@ -8170,9 +8313,9 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
expect(duplicateSettled).toBe(false);
if (failure === "write") {
const error = new Error("owned cancellation write unavailable");
writeSpy = adapterType === "codex_local"
? vi.spyOn(db, "update").mockImplementationOnce(() => { throw error; })
: vi.spyOn(db, "transaction").mockRejectedValueOnce(error);
// Both conversation and process cancellation now finalize under the
// task/run transaction. Fail that write before either owner resolves.
writeSpy = vi.spyOn(db, "transaction").mockRejectedValueOnce(error);
}
} finally {
releaseTermination();
@@ -8213,6 +8356,86 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
},
);
it("preserves exact restore sources through late process Stop metadata with an oversized result", async () => {
const actualProcess = await vi.importActual<typeof import("../adapters/process/execute.js")>("../adapters/process/execute.js");
const actualSupervisor = await vi.importActual<typeof import("../services/local-service-supervisor.js")>("../services/local-service-supervisor.js");
let reportReady!: () => void;
const ready = new Promise<void>(resolve => { reportReady = resolve; });
let releaseTermination!: () => void;
const terminationGate = new Promise<void>(resolve => { releaseTermination = resolve; });
mockAdapterExecute.mockImplementationOnce((async (input: unknown) => {
const context = input as Parameters<typeof actualProcess.execute>[0];
const result = await actualProcess.execute({ ...context, onLog: async (stream, text) => {
await context.onLog(stream, text);
if (text.includes("restore stop ready")) reportReady();
} });
return { ...result, resultJson: { ...result.resultJson, lateAdapterReceipt: true } };
}) as typeof mockAdapterExecute);
mockTerminateLocalService.mockImplementationOnce(async (...args) => {
await actualSupervisor.terminateLocalService(...args);
await terminationGate;
});
const { runId, agentId, companyId, issueId } = await seedRunFixture({
adapterType: "process", runtimeMode: "legacy", agentStatus: "idle", runStatus: "queued",
});
await db.update(agents).set({ adapterConfig: { command: process.execPath,
args: ["-e", "console.log('restore stop ready'); setInterval(() => {}, 1000)"], graceSec: 1,
} }).where(eq(agents.id, agentId));
const originalFactory = instructionWorkingCopies.agentInstructionWorkingCopyService;
let completionReached = false;
const factory = vi.spyOn(instructionWorkingCopies, "agentInstructionWorkingCopyService").mockImplementation((...args) => {
const service = originalFactory(...args);
return { ...service, release: async (...releaseArgs) => {
await service.release(...releaseArgs);
if (releaseArgs[1] === runId && !completionReached) {
completionReached = true;
// Host completion reaches its owned-Stop await in microtasks after
// instruction cleanup. Settle Stop on the next turn, without a delay.
setImmediate(releaseTermination);
}
} };
});
const heartbeat = heartbeatService(db);
let stopping: ReturnType<typeof heartbeat.cancelRun> | undefined;
try {
await heartbeat.resumeQueuedRuns();
await ready;
expect(runningProcesses.get(runId)?.child.pid).toBeTruthy();
expect(adapterExecutionControls.has(runId)).toBe(false);
const [environment] = await db.insert(environments).values({ name: `Late restore Stop ${runId}`, driver: "sandbox" }).returning();
const [lease] = await db.insert(environmentLeases).values({ companyId, issueId, heartbeatRunId: runId,
environmentId: environment.id, provider: "daytona", providerLeaseId: randomUUID(), status: "active",
leasePolicy: "ephemeral", metadata: { driver: "sandbox" },
}).returning();
// Incompressible fixture data exercises the database-size projection,
// which keeps the recovery schema but omits its internal source IDs.
const payload = Array.from({ length: 8192 }, () => randomUUID()).join("");
const [run] = await db.update(heartbeatRuns).set({ resultJson: { payload } }).where(eq(heartbeatRuns.id, runId)).returning();
await recordLegacyWorkspaceRestoreFailure(db, run, { workspaceRestoreFailure: "restore_failed" });
expect((await heartbeat.getRun(runId))?.resultJson?.workspaceRestoreRecovery).toEqual({ schema: "paperclip.workspace-restore-recovery.v1" });
stopping = heartbeat.cancelRun(runId, "Stopped by test operator");
await expect(stopping).resolves.toMatchObject({ status: "cancelled" });
await heartbeat.waitForRunExecutionDrain(runId);
const [finished] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
expect(completionReached).toBe(true);
expect(finished).toMatchObject({ status: "cancelled", resultJson: {
lateAdapterReceipt: true,
workspaceRestoreFailure: "restore_failed",
workspaceRestoreRecovery: { schema: "paperclip.workspace-restore-recovery.v1", leaseIds: [lease.id] },
cancellation: { expected: true },
} });
expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, lease.id)))[0])
.toMatchObject({ leasePolicy: "retain_on_failure", status: "pending_cleanup" });
expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId))).toHaveLength(1);
} finally {
releaseTermination();
await stopping?.catch(() => undefined);
if (runningProcesses.has(runId)) await heartbeat.cancelRun(runId).catch(() => undefined);
await heartbeat.waitForRunExecutionDrain(runId);
factory.mockRestore();
}
});
it.each([
{
mode: "clean exit",
@@ -11313,6 +11536,9 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
await waitForRunToSettle(heartbeat, sourceRun.id, 5_000);
}
expect(sourceRun?.id).not.toBe(runId);
// Durable accounting is bookkeeping, not evidence that the agent acted
// on its plan. A receipt must not suppress plan-only recovery.
expect(await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, String(sourceRunId)))).toHaveLength(1);
expect(sourceRun?.livenessState).toBe("plan_only");
if (withLegacyReview) {
expect(await db.select().from(issues).where(eq(issues.id, legacyReviewId))).toEqual(legacyReviewBefore);
@@ -21,6 +21,45 @@ import type { AuthorizationActor, AuthorizationDecision } from "../services/auth
import { resolveManagedProjectWorkspaceDir } from "../home-paths.ts";
describe("resolveExecutionRunAdapterConfig", () => {
it.each(["many variables", "large value"])("keeps legacy adapter configuration compatible with %s", async kind => {
const env = kind === "many variables"
? Object.fromEntries(Array.from({ length: 129 }, (_, index) => [`CUSTOM_${index}`, "value"]))
: { CUSTOM_VALUE: "x".repeat(65_536) };
const result = await resolveExecutionRunAdapterConfig({ companyId: "company-1", adapterType: "process", executionRunConfig: { env }, secretsSvc: {
resolveAdapterConfigForRuntime: vi.fn(async (_companyId, config) => ({ config, secretKeys: new Set(), manifest: [] })),
} as any });
expect(result.resolvedConfig.env).toEqual(env);
});
it("captures scoped resolved task values and rejects configured markers", async () => {
const key = "PAPERCLIP_CONFIGURED_ENV_KEYS";
const secret = { type: "secret_ref", secretId: "pages-secret" };
const result = await resolveExecutionRunAdapterConfig({
companyId: "company-1", agentId: "agent-1", environmentId: "environment-1", projectId: "project-1", routineId: "routine-1",
executionRunConfig: { env: { PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY: secret, SHARED: "agent", [key]: '["HOST_SECRET"]' } },
environmentEnv: { SHARED: "environment", [key]: '["HOST_SECRET"]' },
projectEnv: { SHARED: "project", [key]: '["HOST_SECRET"]' },
routineEnv: { SHARED: "routine", [key]: '["HOST_SECRET"]' },
secretsSvc: {
resolveAdapterConfigForRuntime: vi.fn(async (companyId, config) => {
expect(companyId).toBe("company-1");
expect(config.env[key]).toBeUndefined();
return { config: { ...config, env: { ...config.env, PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY: "resolved-task-secret" } }, secretKeys: new Set(["PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY"]), manifest: [] };
}),
resolveEnvBindings: vi.fn(async (companyId, env) => {
expect(companyId).toBe("company-1");
expect(env[key]).toBeUndefined();
return { env, secretKeys: new Set(), manifest: [] };
}),
} as any,
});
expect(result.configuredTaskEnvironment).toEqual({
PAPERCLIP_PAGE_AWS_SECRET_ACCESS_KEY: "resolved-task-secret", SHARED: "routine",
});
expect(result.resolvedConfig.env).not.toHaveProperty(key);
expect(result.configuredTaskEnvironment).not.toHaveProperty(key);
});
it("does not preflight or resolve legacy GitHub token bindings for managed executions", async () => {
const assertNoGitHubBinding = (env: Record<string, unknown>) => {
for (const key of Object.keys(env)) if (/^(GH_TOKEN|GITHUB_TOKEN|GH_ENTERPRISE_TOKEN|GITHUB_ENTERPRISE_TOKEN|PAPERCLIP_GIT_TOKEN)$/.test(key)) {
@@ -486,6 +486,11 @@ describeEmbeddedPostgres("heartbeat bounded retry scheduling", () => {
identifier: `${issuePrefix}-1`,
});
// Complete the circular issue/run fixture after both FK targets exist.
await db.update(heartbeatRuns)
.set({ scopeKind: "issue", issueId })
.where(eq(heartbeatRuns.id, runId));
return { companyId, agentId, issueId, runId, now };
}
@@ -1262,8 +1267,8 @@ describeEmbeddedPostgres("heartbeat bounded retry scheduling", () => {
.from(executionWorkspaces)
.where(inArray(executionWorkspaces.id, [currentWorkspaceId, foreignWorkspaceId]));
expect(workspaces).toEqual(expect.arrayContaining([
expect.objectContaining({ id: currentWorkspaceId, status: "active", metadata: { current: true } }),
expect.objectContaining({ id: foreignWorkspaceId, status: "active", metadata: { foreign: true } }),
expect.objectContaining({ id: currentWorkspaceId, status: "active", metadata: expect.objectContaining({ current: true }) }),
expect.objectContaining({ id: foreignWorkspaceId, status: "active", metadata: expect.objectContaining({ foreign: true }) }),
]));
const activity = await db
@@ -1390,8 +1395,8 @@ describeEmbeddedPostgres("heartbeat bounded retry scheduling", () => {
.from(executionWorkspaces)
.where(inArray(executionWorkspaces.id, [staleWorkspaceId, currentWorkspaceId]));
expect(workspaces).toEqual(expect.arrayContaining([
expect.objectContaining({ id: staleWorkspaceId, status: "active", metadata: { stale: true } }),
expect.objectContaining({ id: currentWorkspaceId, status: "active", metadata: { current: true } }),
expect.objectContaining({ id: staleWorkspaceId, status: "active", metadata: expect.objectContaining({ stale: true }) }),
expect.objectContaining({ id: currentWorkspaceId, status: "active", metadata: expect.objectContaining({ current: true }) }),
]));
const activity = await db
@@ -0,0 +1,395 @@
import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import express from "express";
import request from "supertest";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import {
agents,
agentRuntimeState,
activityLog,
authUsers,
companies,
companyMemberships,
createDb,
heartbeatRunEvents,
heartbeatRuns,
issueAccessGrants,
issues,
workspaceOperations,
} from "@paperclipai/db";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import { errorHandler } from "../middleware/index.js";
import { activityRoutes } from "../routes/activity.js";
import { agentRoutes } from "../routes/agents.js";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
describeEmbeddedPostgres("heartbeat run privacy routes", { concurrent: false }, () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
const previousPrivacyMode = process.env.PAPERCLIP_ISSUE_PRIVACY_MODE;
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-run-privacy-routes-");
db = createDb(tempDb.connectionString);
process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = "enforce";
}, 120_000);
afterEach(async () => {
await db.delete(activityLog);
await db.delete(workspaceOperations);
await db.delete(heartbeatRunEvents);
await db.delete(issueAccessGrants);
await db.delete(agentRuntimeState);
await db.delete(heartbeatRuns);
await db.delete(issues);
await db.delete(agents);
await db.delete(companyMemberships);
await db.delete(companies);
await db.delete(authUsers);
});
afterAll(async () => {
if (previousPrivacyMode === undefined) delete process.env.PAPERCLIP_ISSUE_PRIVACY_MODE;
else process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = previousPrivacyMode;
await tempDb?.cleanup();
});
async function seedFixture() {
const companyId = randomUUID();
const ownerAgentId = randomUUID();
const grantedAgentId = randomUUID();
const otherAgentId = randomUUID();
const ownerUserId = `owner-${randomUUID()}`;
const otherUserId = `other-${randomUUID()}`;
const issueId = randomUUID();
const privateRunId = randomUUID();
const maintenanceRunId = randomUUID();
const operationId = randomUUID();
await db.insert(companies).values({
id: companyId,
name: "Run Privacy",
issuePrefix: "RPR",
requireBoardApprovalForNewAgents: false,
});
await db.insert(authUsers).values([ownerUserId, otherUserId].map((id) => ({
id,
name: id === ownerUserId ? "Owner user" : "Other user",
email: `${id}@example.test`,
emailVerified: true,
createdAt: new Date(),
updatedAt: new Date(),
})));
await db.insert(companyMemberships).values([ownerUserId, otherUserId].map((principalId) => ({
companyId,
principalType: "user",
principalId,
status: "active",
membershipRole: "operator",
})));
await db.insert(agents).values([
{
id: ownerAgentId,
companyId,
name: "Owner",
role: "engineer",
adapterType: "process",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
},
{
id: grantedAgentId,
companyId,
name: "Granted reviewer",
role: "security",
adapterType: "process",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
},
{
id: otherAgentId,
companyId,
name: "Other agent",
role: "engineer",
adapterType: "process",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
},
]);
await db.insert(issues).values({
id: issueId,
companyId,
identifier: "RPR-1",
title: "Confidential email triage",
description: "private@example.test",
visibility: "private",
privacyRootIssueId: issueId,
status: "in_progress",
responsibleUserId: ownerUserId,
assigneeAgentId: ownerAgentId,
});
await db.insert(issueAccessGrants).values({
issueId,
subjectType: "agent",
subjectId: grantedAgentId,
source: "explicit",
grantedByAgentId: ownerAgentId,
});
const startedAt = new Date("2026-07-31T12:00:00.000Z");
const finishedAt = new Date("2026-07-31T12:01:00.000Z");
await db.insert(heartbeatRuns).values([
{
id: privateRunId,
companyId,
agentId: ownerAgentId,
scopeKind: "issue",
issueId,
invocationSource: "assignment",
status: "running",
startedAt,
finishedAt,
usageJson: { inputTokens: 11, cachedInputTokens: 2, outputTokens: 7 },
resultJson: { summary: "Read the confidential email", costUsd: 0.42 },
contextSnapshot: { issueId, title: "Confidential email triage" },
logStore: "local_file",
logRef: "missing-private-run-log.ndjson",
},
{
id: maintenanceRunId,
companyId,
agentId: ownerAgentId,
scopeKind: "company",
issueId: null,
invocationSource: "timer",
status: "succeeded",
startedAt,
finishedAt,
resultJson: { summary: "Maintenance complete", costUsd: 0.01 },
contextSnapshot: { wakeReason: "heartbeat_timer" },
},
]);
await db.insert(heartbeatRunEvents).values({
companyId,
runId: privateRunId,
agentId: ownerAgentId,
seq: 1,
eventType: "output",
stream: "stdout",
message: "private@example.test",
});
await db.insert(workspaceOperations).values({
id: operationId,
companyId,
heartbeatRunId: privateRunId,
issueId: null,
phase: "provision",
status: "succeeded",
command: "read private email",
stdoutExcerpt: "private@example.test",
logStore: "local_file",
logRef: "missing-private-operation-log.ndjson",
});
return {
companyId,
ownerAgentId,
grantedAgentId,
otherAgentId,
ownerUserId,
otherUserId,
issueId,
privateRunId,
maintenanceRunId,
operationId,
};
}
function createApp(companyId: string, agentId: string) {
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
req.actor = {
type: "agent",
agentId,
companyId,
source: "agent_jwt",
};
next();
});
app.use("/api", agentRoutes(db));
app.use("/api", activityRoutes(db));
app.use(errorHandler);
return app;
}
function createBoardApp(companyId: string, userId: string) {
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
req.actor = {
type: "board",
userId,
companyIds: [companyId],
source: "session",
isInstanceAdmin: false,
};
next();
});
app.use("/api", agentRoutes(db));
app.use(errorHandler);
return app;
}
it("returns 404 for direct private-run content and metadata-only list stubs to a non-member", async () => {
const fixture = await seedFixture();
const app = createApp(fixture.companyId, fixture.otherAgentId);
for (const path of [
`/api/heartbeat-runs/${fixture.privateRunId}`,
`/api/heartbeat-runs/${fixture.privateRunId}/events`,
`/api/heartbeat-runs/${fixture.privateRunId}/log`,
`/api/heartbeat-runs/${fixture.privateRunId}/workspace-operations`,
`/api/workspace-operations/${fixture.operationId}/log`,
]) {
const response = await request(app).get(path);
expect(response.status, path).toBe(404);
expect(JSON.stringify(response.body)).not.toContain("private@example.test");
}
const history = await request(app).get(`/api/companies/${fixture.companyId}/heartbeat-runs`);
expect(history.status).toBe(200);
const privateStub = history.body.find((run: { id: string }) => run.id === fixture.privateRunId);
expect(privateStub).toMatchObject({
redacted: true,
durationMs: 60_000,
costUsd: 0.42,
usageJson: { inputTokens: 11, cachedInputTokens: 2, outputTokens: 7 },
});
expect(privateStub).not.toHaveProperty("issueId");
expect(privateStub).not.toHaveProperty("contextSnapshot");
expect(privateStub).not.toHaveProperty("resultJson");
expect(JSON.stringify(privateStub)).not.toContain("Confidential email triage");
expect(JSON.stringify(privateStub)).not.toContain("summary");
const summarizedHistory = await request(app)
.get(`/api/companies/${fixture.companyId}/heartbeat-runs?summary=true`);
const summarizedStub = summarizedHistory.body.find((run: { id: string }) => run.id === fixture.privateRunId);
expect(summarizedStub).toMatchObject({ redacted: true, durationMs: 60_000, costUsd: 0.42 });
expect(summarizedStub.usageJson).toMatchObject({ inputTokens: 11, outputTokens: 7 });
const live = await request(app).get(`/api/companies/${fixture.companyId}/live-runs`);
expect(live.status).toBe(200);
expect(live.body[0]).toMatchObject({ id: fixture.privateRunId, redacted: true, costUsd: 0.42 });
expect(live.body[0]).not.toHaveProperty("issueId");
const maintenance = await request(app).get(`/api/heartbeat-runs/${fixture.maintenanceRunId}`);
expect(maintenance.status).toBe(200);
expect(maintenance.body.resultJson.summary).toBe("Maintenance complete");
});
it("returns full private-run content to the owner and an explicitly granted agent", async () => {
const fixture = await seedFixture();
for (const agentId of [fixture.ownerAgentId, fixture.grantedAgentId]) {
const app = createApp(fixture.companyId, agentId);
const detail = await request(app).get(`/api/heartbeat-runs/${fixture.privateRunId}`);
expect(detail.status).toBe(200);
expect(detail.body).toMatchObject({ issueId: fixture.issueId });
expect(detail.body.resultJson.summary).toBe("Read the confidential email");
const events = await request(app).get(`/api/heartbeat-runs/${fixture.privateRunId}/events`);
expect(events.status).toBe(200);
expect(events.body[0].message).toBe("private@example.test");
const linkedIssues = await request(app).get(`/api/heartbeat-runs/${fixture.privateRunId}/issues`);
expect(linkedIssues.status).toBe(200);
expect(linkedIssues.body[0]).toMatchObject({ issueId: fixture.issueId, title: "Confidential email triage" });
}
});
it("returns no linked issue metadata to a non-member", async () => {
const fixture = await seedFixture();
const response = await request(createApp(fixture.companyId, fixture.otherAgentId))
.get(`/api/heartbeat-runs/${fixture.privateRunId}/issues`);
expect(response.status).toBe(200);
expect(response.body).toEqual([]);
});
it("conceals private runs from unauthorized cancellation and watchdog mutations", async () => {
const fixture = await seedFixture();
const deniedCancel = await request(createBoardApp(fixture.companyId, fixture.otherUserId))
.post(`/api/heartbeat-runs/${fixture.privateRunId}/cancel`);
expect(deniedCancel.status).toBe(404);
const deniedWatchdog = await request(createApp(fixture.companyId, fixture.otherAgentId))
.post(`/api/heartbeat-runs/${fixture.privateRunId}/watchdog-decisions`)
.send({ decision: "continue" });
expect(deniedWatchdog.status).toBe(404);
const allowedWatchdog = await request(createBoardApp(fixture.companyId, fixture.ownerUserId))
.post(`/api/heartbeat-runs/${fixture.privateRunId}/watchdog-decisions`)
.send({ decision: "continue" });
expect(allowedWatchdog.status).toBe(200);
await db.update(heartbeatRuns)
.set({ status: "succeeded" })
.where(eq(heartbeatRuns.id, fixture.privateRunId));
const allowedCancel = await request(createBoardApp(fixture.companyId, fixture.ownerUserId))
.post(`/api/heartbeat-runs/${fixture.privateRunId}/cancel`);
expect(allowedCancel.status).toBe(200);
expect(allowedCancel.body.id).toBe(fixture.privateRunId);
});
it("keeps deleted-issue runs and operation history bound to a fail-closed tombstone", async () => {
const fixture = await seedFixture();
await db.delete(issues).where(eq(issues.id, fixture.issueId));
const missingDetail = await request(createApp(fixture.companyId, fixture.ownerAgentId))
.get(`/api/heartbeat-runs/${fixture.privateRunId}`);
expect(missingDetail.status).toBe(404);
const [tombstonedRun] = await db.select({
scopeKind: heartbeatRuns.scopeKind,
issueId: heartbeatRuns.issueId,
})
.from(heartbeatRuns)
.where(eq(heartbeatRuns.id, fixture.privateRunId));
expect(tombstonedRun).toEqual({ scopeKind: "issue", issueId: null });
const [operation] = await db.select({
heartbeatRunId: workspaceOperations.heartbeatRunId,
issueId: workspaceOperations.issueId,
})
.from(workspaceOperations)
.where(eq(workspaceOperations.id, fixture.operationId));
expect(operation).toEqual({ heartbeatRunId: fixture.privateRunId, issueId: null });
const missingOperationLog = await request(createApp(fixture.companyId, fixture.ownerAgentId))
.get(`/api/workspace-operations/${fixture.operationId}/log`);
expect(missingOperationLog.status).toBe(404);
});
it("logs would-deny decisions without enforcing them in shadow mode", async () => {
const fixture = await seedFixture();
process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = "shadow";
try {
const response = await request(createApp(fixture.companyId, fixture.otherAgentId))
.get(`/api/heartbeat-runs/${fixture.privateRunId}`);
expect(response.status).toBe(200);
expect(response.body.resultJson.summary).toBe("Read the confidential email");
} finally {
process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = "enforce";
}
});
});
@@ -0,0 +1,462 @@
import { randomUUID } from "node:crypto";
import express from "express";
import request from "supertest";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
activityLog,
agents,
agentWakeupRequests,
authUsers,
companies,
companyMemberships,
createDb,
heartbeatRuns,
issueAccessGrants,
issueComments,
issueReferenceMentions,
issueRelations,
issues,
projectAccessMembers,
projects,
} from "@paperclipai/db";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
vi.mock("../services/issue-assignment-wakeup.js", () => ({
queueIssueAssignmentWakeup: vi.fn(),
}));
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
type Db = ReturnType<typeof createDb>;
function boardActor(companyId: string, userId: string): Express.Request["actor"] {
return {
type: "board",
userId,
companyIds: [companyId],
source: "session",
isInstanceAdmin: false,
};
}
function agentActor(companyId: string, agentId: string): Express.Request["actor"] {
return { type: "agent", agentId, companyId, runId: null, source: "agent_jwt" };
}
async function createApp(db: Db, actor: Express.Request["actor"]) {
const { issueRoutes } = await import("../routes/issues.js");
const { projectRoutes } = await import("../routes/projects.js");
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
req.actor = actor;
next();
});
app.use("/api", issueRoutes(db, {} as any));
app.use("/api", projectRoutes(db));
app.use((err: any, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
res.status(err.status ?? 500).json({ error: err.message ?? "Internal server error" });
});
return app;
}
describeEmbeddedPostgres("issue access grant and locked edge routes", { concurrent: false }, () => {
let db!: Db;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
const previousPrivacyMode = process.env.PAPERCLIP_ISSUE_PRIVACY_MODE;
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-issue-access-grants-");
db = createDb(tempDb.connectionString);
process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = "enforce";
// Load the current route dependency graph during setup, outside assertion timeouts.
await Promise.all([import("../routes/issues.js"), import("../routes/projects.js")]);
}, 120_000);
afterEach(async () => {
await db.delete(issueReferenceMentions);
await db.delete(issueComments);
await db.delete(issueRelations);
await db.delete(activityLog);
await db.delete(issueAccessGrants);
await db.delete(heartbeatRuns);
await db.delete(issues);
await db.delete(projectAccessMembers);
await db.delete(projects);
await db.delete(agentWakeupRequests);
await db.delete(agents);
await db.delete(companyMemberships);
await db.delete(authUsers);
await db.delete(companies);
});
afterAll(async () => {
if (previousPrivacyMode === undefined) delete process.env.PAPERCLIP_ISSUE_PRIVACY_MODE;
else process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = previousPrivacyMode;
await tempDb?.cleanup();
});
async function seedFixture() {
const companyId = randomUUID();
const ownerId = `owner-${randomUUID()}`;
const adminId = `admin-${randomUUID()}`;
const memberId = `member-${randomUUID()}`;
const sharedUserId = `shared-${randomUUID()}`;
const now = new Date();
await db.insert(companies).values({
id: companyId,
name: "Private issue grants",
issuePrefix: `P${randomUUID().replace(/-/g, "").slice(0, 5).toUpperCase()}`,
requireBoardApprovalForNewAgents: false,
});
await db.insert(authUsers).values([
{ id: ownerId, name: "Olivia Owner", email: `${ownerId}@example.test`, createdAt: now, updatedAt: now },
{ id: adminId, name: "Ada Admin", email: `${adminId}@example.test`, createdAt: now, updatedAt: now },
{ id: memberId, name: "Nora Nonreader", email: `${memberId}@example.test`, createdAt: now, updatedAt: now },
{
id: sharedUserId,
name: "Uma User",
email: `${sharedUserId}@example.test`,
image: "https://example.test/uma.png",
createdAt: now,
updatedAt: now,
},
]);
await db.insert(companyMemberships).values([ownerId, adminId, memberId, sharedUserId].map((principalId) => ({
companyId,
principalType: "user",
principalId,
status: "active",
membershipRole: principalId === ownerId ? "owner" : principalId === adminId ? "admin" : "operator",
})));
const [assignedAgent, sharedAgent] = await db.insert(agents).values([
{
companyId,
name: "Assigned Agent",
role: "engineer",
status: "active",
adapterType: "process",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
},
{
companyId,
name: "Private Helper",
role: "engineer",
status: "active",
adapterType: "process",
adapterConfig: {},
runtimeConfig: {},
permissions: {
authorizationPolicy: {
agentVisibility: { mode: "private", hiddenFromDefaultDirectory: true },
},
},
},
]).returning();
const privateProject = await db.insert(projects).values({
companyId,
name: "Secret launch project",
visibility: "private",
status: "planned",
}).returning().then((rows) => rows[0]!);
const privateIssueId = randomUUID();
await db.insert(issues).values({
id: privateIssueId,
companyId,
identifier: "PRV-1",
title: "Confidential root",
status: "backlog",
priority: "medium",
projectId: privateProject.id,
visibility: "private",
privacyRootIssueId: privateIssueId,
responsibleUserId: ownerId,
createdByUserId: ownerId,
});
const privateChild = await db.insert(issues).values({
companyId,
parentId: privateIssueId,
identifier: "PRV-1A",
title: "Confidential child",
status: "backlog",
priority: "medium",
projectId: privateProject.id,
visibility: "private",
privacyRootIssueId: privateIssueId,
responsibleUserId: ownerId,
createdByUserId: ownerId,
}).returning().then((rows) => rows[0]!);
const openIssue = await db.insert(issues).values({
companyId,
identifier: "PRV-2",
title: "Open issue",
status: "todo",
priority: "medium",
createdByUserId: ownerId,
}).returning().then((rows) => rows[0]!);
return {
companyId,
ownerId,
adminId,
memberId,
sharedUserId,
assignedAgent: assignedAgent!,
sharedAgent: sharedAgent!,
privateProject,
privateIssueId,
privateChild,
openIssue,
};
}
it("requires explicit owner/admin break-glass and records both audit evidence and an owner-visible notice", async () => {
const fixture = await seedFixture();
const adminApp = await createApp(db, boardActor(fixture.companyId, fixture.adminId));
const memberApp = await createApp(db, boardActor(fixture.companyId, fixture.memberId));
await request(adminApp).get(`/api/issues/${fixture.privateIssueId}`).expect(404);
await request(memberApp).get(`/api/issues/${fixture.privateIssueId}?breakGlass=true`).expect(404);
const accessed = await request(adminApp)
.get(`/api/issues/${fixture.privateIssueId}?breakGlass=true`);
expect(accessed.status, JSON.stringify(accessed.body)).toBe(200);
expect(accessed.body.id).toBe(fixture.privateIssueId);
const auditRows = await db.select().from(activityLog);
expect(auditRows).toEqual(expect.arrayContaining([
expect.objectContaining({
action: "issue.break_glass_read",
actorType: "user",
actorId: fixture.adminId,
entityType: "issue",
entityId: fixture.privateIssueId,
}),
]));
const notices = await db.select().from(issueComments);
expect(notices).toEqual([
expect.objectContaining({
issueId: fixture.privateIssueId,
authorType: "system",
presentation: expect.objectContaining({
kind: "system_notice",
title: "Break-glass access used",
tone: "warning",
}),
}),
]);
}, 20_000);
it("auto-grants child-subtree access on assignment and keeps it sticky until revoke", async () => {
const fixture = await seedFixture();
const ownerApp = await createApp(db, boardActor(fixture.companyId, fixture.ownerId));
const assigned = await request(ownerApp)
.patch(`/api/issues/${fixture.privateChild.id}`)
.send({ assigneeAgentId: fixture.assignedAgent.id });
expect(assigned.status, JSON.stringify(assigned.body)).toBe(200);
await request(ownerApp)
.patch(`/api/issues/${fixture.privateChild.id}`)
.send({ assigneeAgentId: fixture.assignedAgent.id })
.expect(200);
await request(ownerApp)
.patch(`/api/issues/${fixture.privateChild.id}`)
.send({ assigneeAgentId: null })
.expect(200);
const unassignedIssue = await db.select().from(issues).then((rows) => rows.find((row) => row.id === fixture.privateChild.id));
expect(unassignedIssue?.assigneeAgentId).toBeNull();
const grants = await db.select().from(issueAccessGrants);
expect(grants).toHaveLength(1);
expect(grants[0]).toMatchObject({
issueId: fixture.privateChild.id,
subjectType: "agent",
subjectId: fixture.assignedAgent.id,
source: "assignment",
grantedByUserId: fixture.ownerId,
revokedAt: null,
});
const readableBeforeRevoke = await request(await createApp(
db,
agentActor(fixture.companyId, fixture.assignedAgent.id),
)).get(`/api/issues/${fixture.privateChild.id}`);
expect(readableBeforeRevoke.status).toBe(200);
await request(ownerApp)
.post(`/api/issues/${fixture.privateChild.id}/access-grants/${grants[0]!.id}/revoke`)
.send({})
.expect(200);
const deniedAfterRevoke = await request(await createApp(
db,
agentActor(fixture.companyId, fixture.assignedAgent.id),
)).get(`/api/issues/${fixture.privateChild.id}`);
expect(deniedAfterRevoke.status).toBe(404);
expect(deniedAfterRevoke.body.error).toBe("Issue not found");
}, 20_000);
it("creates and enriches explicit grants idempotently while rejecting unauthorized and open shares", async () => {
const fixture = await seedFixture();
const ownerApp = await createApp(db, boardActor(fixture.companyId, fixture.ownerId));
const nonreaderApp = await createApp(db, boardActor(fixture.companyId, fixture.memberId));
await request(nonreaderApp)
.post(`/api/issues/${fixture.privateIssueId}/access-grants`)
.send({ subjectType: "agent", subjectId: fixture.sharedAgent.id })
.expect(404);
await request(nonreaderApp)
.patch(`/api/issues/${fixture.privateIssueId}`)
.send({ assigneeAgentId: fixture.assignedAgent.id })
.expect(404);
const openShare = await request(ownerApp)
.post(`/api/issues/${fixture.openIssue.id}/access-grants`)
.send({ subjectType: "agent", subjectId: fixture.sharedAgent.id });
expect(openShare.status).toBe(409);
expect(openShare.body.error).toContain("Open issues");
const first = await request(ownerApp)
.post(`/api/issues/${fixture.privateIssueId}/access-grants`)
.send({ subjectType: "agent", subjectId: fixture.sharedAgent.id });
expect(first.status, JSON.stringify(first.body)).toBe(201);
expect(first.body).toMatchObject({
issueId: fixture.privateIssueId,
source: "explicit",
subjectDisplayName: "Private Helper",
subjectInitials: "PH",
subjectAvatarUrl: null,
agentVisibility: "private",
});
const duplicate = await request(ownerApp)
.post(`/api/issues/${fixture.privateIssueId}/access-grants`)
.send({ subjectType: "agent", subjectId: fixture.sharedAgent.id });
expect(duplicate.status).toBe(200);
expect(duplicate.body.id).toBe(first.body.id);
await request(ownerApp)
.post(`/api/issues/${fixture.privateIssueId}/access-grants`)
.send({ subjectType: "user", subjectId: fixture.sharedUserId })
.expect(201);
const listed = await request(ownerApp).get(`/api/issues/${fixture.privateIssueId}/access-grants`);
expect(listed.status, JSON.stringify(listed.body)).toBe(200);
expect(listed.body).toEqual(expect.arrayContaining([
expect.objectContaining({
subjectId: fixture.sharedUserId,
subjectDisplayName: "Uma User",
subjectAvatarUrl: "https://example.test/uma.png",
subjectInitials: "UU",
agentVisibility: null,
}),
]));
expect(await db.select().from(issueAccessGrants)).toHaveLength(2);
const createdActivities = await db.select().from(activityLog);
expect(createdActivities.filter((row) => row.action === "issue_access_grant.created")).toHaveLength(2);
}, 20_000);
it("keeps private project metadata hidden from user and agent issue grantees", async () => {
const fixture = await seedFixture();
await db.insert(issueAccessGrants).values([
{
issueId: fixture.privateIssueId,
subjectType: "user",
subjectId: fixture.sharedUserId,
source: "explicit",
grantedByUserId: fixture.ownerId,
},
{
issueId: fixture.privateIssueId,
subjectType: "agent",
subjectId: fixture.sharedAgent.id,
source: "explicit",
grantedByUserId: fixture.ownerId,
},
]);
const granteeApps = [
await createApp(db, boardActor(fixture.companyId, fixture.sharedUserId)),
await createApp(db, agentActor(fixture.companyId, fixture.sharedAgent.id)),
];
for (const app of granteeApps) {
const detail = await request(app).get(`/api/issues/${fixture.privateIssueId}`);
expect(detail.status, JSON.stringify(detail.body)).toBe(200);
expect(detail.body.projectId).toBe(fixture.privateProject.id);
expect(detail.body.project).toBeNull();
const heartbeatContext = await request(app)
.get(`/api/issues/${fixture.privateIssueId}/heartbeat-context`);
expect(heartbeatContext.status, JSON.stringify(heartbeatContext.body)).toBe(200);
expect(heartbeatContext.body.issue.projectId).toBe(fixture.privateProject.id);
expect(heartbeatContext.body.project).toBeNull();
await request(app).get(`/api/projects/${fixture.privateProject.id}`).expect(404);
const projectList = await request(app)
.get(`/api/companies/${fixture.companyId}/projects`);
expect(projectList.status, JSON.stringify(projectList.body)).toBe(200);
expect(projectList.body.map((project: { id: string }) => project.id))
.not.toContain(fixture.privateProject.id);
const projectSearch = await request(app)
.get(`/api/companies/${fixture.companyId}/search?q=Secret%20launch&scope=projects`);
expect(projectSearch.status, JSON.stringify(projectSearch.body)).toBe(200);
expect(projectSearch.body.results.map((project: { id: string }) => project.id))
.not.toContain(fixture.privateProject.id);
}
}, 20_000);
it("returns exact locked stubs only through visible blocker and mention edges", async () => {
const fixture = await seedFixture();
const visibleIssue = await db.insert(issues).values({
companyId: fixture.companyId,
identifier: "PRV-3",
title: "Visible coordination issue",
description: "Depends on PRV-1",
status: "blocked",
priority: "medium",
createdByUserId: fixture.memberId,
}).returning().then((rows) => rows[0]!);
await db.insert(issueRelations).values({
companyId: fixture.companyId,
issueId: fixture.privateIssueId,
relatedIssueId: visibleIssue.id,
type: "blocks",
});
await db.insert(issueReferenceMentions).values({
companyId: fixture.companyId,
sourceIssueId: visibleIssue.id,
targetIssueId: fixture.privateIssueId,
sourceKind: "description",
sourceRecordId: null,
documentKey: null,
matchedText: "PRV-1",
});
const app = await createApp(db, boardActor(fixture.companyId, fixture.memberId));
const detail = await request(app).get(`/api/issues/${visibleIssue.id}`);
expect(detail.status, JSON.stringify(detail.body)).toBe(200);
const expectedStub = { id: fixture.privateIssueId, identifier: "PRV-1", locked: true };
expect(detail.body.blockedBy).toEqual([expectedStub]);
expect(detail.body.relatedWork.outbound[0].issue).toEqual(expectedStub);
expect(JSON.stringify(detail.body)).not.toContain("Confidential root");
const direct = await request(app).get(`/api/issues/${fixture.privateIssueId}`);
expect(direct.status).toBe(404);
const list = await request(app)
.get(`/api/companies/${fixture.companyId}/issues?includeBlockedBy=true`);
expect(list.status, JSON.stringify(list.body)).toBe(200);
expect(list.body.map((row: { id: string }) => row.id)).not.toContain(fixture.privateIssueId);
const visibleRow = list.body.find((row: { id: string }) => row.id === visibleIssue.id);
expect(visibleRow.blockedBy).toEqual([expectedStub]);
const search = await request(app)
.get(`/api/companies/${fixture.companyId}/search?q=Confidential%20root&scope=issues`);
expect(search.status).toBe(200);
expect(search.body.results.map((row: { id: string }) => row.id)).not.toContain(fixture.privateIssueId);
}, 20_000);
});
@@ -19,6 +19,9 @@ const mockIssueService = vi.hoisted(() => ({
const mockLogActivity = vi.hoisted(() => vi.fn(async () => undefined));
const mockAccessService = vi.hoisted(() => ({
decide: vi.fn(async ({ action }: { action: string }) => ({
action, allowed: action === "issue:read", reason: "allow_default", explanation: "Fixture task is readable",
})),
canUser: vi.fn(async () => false),
hasPermission: vi.fn(async () => false),
}));
@@ -136,7 +139,17 @@ function registerModuleMocks() {
}));
}
async function createApp(db: unknown = {}) {
function createEmptyRelationReadDb() {
const query = {
from: vi.fn().mockReturnThis(),
where: vi.fn(async () => []),
};
return {
select: vi.fn().mockReturnValue(query),
};
}
async function createApp(db: unknown = createEmptyRelationReadDb()) {
const [{ issueRoutes }, { errorHandler }] = await Promise.all([
vi.importActual<typeof import("../routes/issues.js")>("../routes/issues.js"),
vi.importActual<typeof import("../middleware/index.js")>("../middleware/index.js"),
@@ -359,6 +359,9 @@ function createRunContextDb(
orderBy: vi.fn(async () => []),
limit: vi.fn(() => ({
then: async (resolve: (limitedRows: unknown[]) => unknown) => resolve(await rowsForSelection(selection, chatBindingQuery, settledRecoveryQuery)),
for: vi.fn(() => ({
then: async (resolve: (lockedRows: unknown[]) => unknown) => resolve(await rowsForSelection(selection, chatBindingQuery, settledRecoveryQuery)),
})),
})),
for: vi.fn(() => ({
then: async (resolve: (selectedRows: unknown[]) => unknown) => resolve(await rowsForSelection(selection, chatBindingQuery, settledRecoveryQuery)),
@@ -471,14 +474,16 @@ describe("agent issue mutation checkout ownership", () => {
input.action === "issue:comment" ||
input.action === "issue:read" ||
input.action === "issue:mutate" ||
input.action === "company_scope:read",
input.action === "company_scope:read" ||
input.action === "project:read",
action: input.action,
reason:
input.action === "tasks:assign" ||
input.action === "issue:comment" ||
input.action === "issue:read" ||
input.action === "issue:mutate" ||
input.action === "company_scope:read"
input.action === "company_scope:read" ||
input.action === "project:read"
? "allow_explicit_grant"
: "deny_missing_grant",
explanation:
@@ -486,7 +491,8 @@ describe("agent issue mutation checkout ownership", () => {
input.action === "issue:comment" ||
input.action === "issue:read" ||
input.action === "issue:mutate" ||
input.action === "company_scope:read"
input.action === "company_scope:read" ||
input.action === "project:read"
? "Allowed by test default."
: "Missing permission.",
}));
@@ -880,7 +886,7 @@ describe("agent issue mutation checkout ownership", () => {
it("allows mentioned peer agents to post comments without ownership of an active checkout", async () => {
mockAccessService.decide.mockImplementation(async (input: { action: string }) => ({
allowed: input.action === "issue:comment",
allowed: input.action === "issue:comment" || input.action === "issue:read",
action: input.action,
reason: input.action === "issue:comment" ? "allow_issue_mention_grant" : "deny_missing_grant",
explanation:
@@ -963,8 +969,8 @@ describe("agent issue mutation checkout ownership", () => {
const res = await request(await createApp(peerActor()))
.get(`/api/issues/${issueId}/comments`);
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(res.body.error).toBe("Issue is outside this actor's authorization boundary");
expect(res.status, JSON.stringify(res.body)).toBe(404);
expect(res.body.error).toBe("Issue not found");
expect(mockAccessService.decide).toHaveBeenCalledWith(expect.objectContaining({ action: "issue:read" }));
});
@@ -979,8 +985,8 @@ describe("agent issue mutation checkout ownership", () => {
const res = await request(await createApp(peerActor()))
.get(`/api/issues/${issueId}/interactions`);
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(res.body.error).toBe("Issue is outside this actor's authorization boundary");
expect(res.status, JSON.stringify(res.body)).toBe(404);
expect(res.body.error).toBe("Issue not found");
expect(mockAccessService.decide).toHaveBeenCalledWith(expect.objectContaining({ action: "issue:read" }));
expect(mockIssueThreadInteractionService.listForIssue).not.toHaveBeenCalled();
});
@@ -1025,8 +1031,8 @@ describe("agent issue mutation checkout ownership", () => {
const res = await request(await createApp(peerActor()))
.get(`/api/issues/${issueId}/comments/comment-1`);
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(res.body.error).toBe("Issue is outside this actor's authorization boundary");
expect(res.status, JSON.stringify(res.body)).toBe(404);
expect(res.body.error).toBe("Issue not found");
expect(mockAccessService.decide).toHaveBeenCalledWith(expect.objectContaining({ action: "issue:read" }));
expect(mockIssueService.getComment).not.toHaveBeenCalled();
});
@@ -1034,7 +1040,7 @@ describe("agent issue mutation checkout ownership", () => {
it("allows visible issue field updates for peer agents", async () => {
mockIssueService.getById.mockResolvedValue(makeIssue({ status: "todo", assigneeAgentId: ownerAgentId }));
mockAccessService.decide.mockImplementation(async (input: { action: string }) => ({
allowed: input.action === "issue:comment" || input.action === "issue:mutate",
allowed: input.action === "issue:comment" || input.action === "issue:mutate" || input.action === "issue:read",
action: input.action,
reason:
input.action === "issue:comment"
@@ -1333,6 +1339,9 @@ describe("agent issue mutation checkout ownership", () => {
});
it("defaults agent-created root follow-up issues to inherit the current run workspace", async () => {
mockProjectService.getById.mockResolvedValue({
id: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", companyId, visibility: "open",
} as never);
const app = await createApp(
ownerActor(),
createRunContextDb({
@@ -1633,7 +1642,7 @@ describe("agent issue mutation checkout ownership", () => {
it("allows agents with the active-checkout management grant to mutate active checkouts", async () => {
mockAccessService.decide.mockImplementation(async (input: { action: string }) => ({
allowed: input.action === "issue:mutate" || input.action === "tasks:manage_active_checkouts",
allowed: input.action === "issue:mutate" || input.action === "tasks:manage_active_checkouts" || input.action === "issue:read",
action: input.action,
reason:
input.action === "issue:mutate" || input.action === "tasks:manage_active_checkouts"
@@ -2008,7 +2017,9 @@ describe("agent issue mutation checkout ownership", () => {
});
it.each(["agent", "viewer"])("rejects %s export-only retries before admission", async kind => {
mockAccessService.decide.mockResolvedValue({ allowed: false, explanation: "No runtime access" });
mockAccessService.decide.mockImplementation(async (input: { action: string }) => ({
allowed: input.action === "issue:read", explanation: "The viewer can read but has no runtime access",
}));
const res = await request(await createApp(kind === "agent" ? ownerActor() : boardActor()))
.post(`/api/issues/${issueId}/recovery-actions/retry-workspace-export`)
.send({ actionId: recoveryActionId, runId: ownerRunId, repairNote: "Restored provider connectivity and preserved all saved files." });
@@ -2575,11 +2586,14 @@ describe("agent issue mutation checkout ownership", () => {
explanation: "Target agent requires approval before task assignment.",
}));
decide.mockImplementation(async (input: { action: string }) => ({
allowed: input.action === "issue:mutate",
allowed: input.action === "issue:read" || input.action === "issue:mutate",
action: input.action,
reason: input.action === "issue:mutate" ? "allow_self" : "deny_policy_restricted",
reason:
input.action === "issue:read" || input.action === "issue:mutate"
? "allow_self"
: "deny_policy_restricted",
explanation:
input.action === "issue:mutate"
input.action === "issue:read" || input.action === "issue:mutate"
? "Allowed because the actor owns the assigned issue."
: "Target agent requires approval before task assignment.",
}));
@@ -724,7 +724,8 @@ describe("issue attachment routes", () => {
const app = await createApp(storage);
const res = await request(app).get("/api/attachments/attachment-1/content");
expect(res.status).toBe(403);
expect(res.status).toBe(404);
expect(res.body.error).toBe("Issue not found");
expect(storage.getObject).not.toHaveBeenCalled();
});
@@ -29,6 +29,12 @@ const mockExecutionWorkspaceService = vi.hoisted(() => ({
const mockAccessService = vi.hoisted(() => ({
canUser: vi.fn(),
decide: vi.fn(async (input: { action: string }) => ({
allowed: input.action === "issue:read" || input.action === "project:read",
action: input.action,
reason: "allow_test_read",
explanation: "The fixture actor can read the task.",
})),
hasPermission: vi.fn(),
}));
@@ -12,6 +12,9 @@ const mockIssueService = vi.hoisted(() => ({
}));
const mockAccessService = vi.hoisted(() => ({
decide: vi.fn(async ({ action }: { action: string }) => ({
action, allowed: action === "issue:read", reason: "allow_default", explanation: "Fixture task is readable",
})),
canUser: vi.fn(),
hasPermission: vi.fn(),
}));
@@ -821,7 +821,7 @@ describe("issue comment reopen routes", () => {
});
mockAccessService.decide.mockImplementation(
async (input: { action?: string }) => {
const allowed = input.action === "issue:comment";
const allowed = input.action === "issue:read" || input.action === "issue:comment";
return {
allowed,
action: input.action,
@@ -869,7 +869,7 @@ describe("issue comment reopen routes", () => {
});
mockAccessService.decide.mockImplementation(
async (input: { action?: string }) => {
const allowed = input.action === "issue:comment";
const allowed = input.action === "issue:read" || input.action === "issue:comment";
return {
allowed,
action: input.action,
@@ -39,6 +39,12 @@ vi.mock("../services/index.js", () => ({
}),
accessService: () => ({
canUser: vi.fn(),
decide: vi.fn(async (input: { action: string }) => ({
allowed: input.action === "issue:read" || input.action === "project:read",
action: input.action,
reason: "allow_test_read",
explanation: "The fixture actor can read the task.",
})),
hasPermission: vi.fn(),
}),
agentService: () => ({
@@ -253,6 +253,9 @@ describeEmbeddedPostgres("issue monitor scheduler", () => {
const { issueId, agentId } = await seedFixture();
const heartbeat = heartbeatService(db);
const tickAt = new Date("2026-04-11T12:31:00.000Z");
const [before] = await db.select().from(issues).where(eq(issues.id, issueId));
const unrelatedPolicy = { commentRequired: false, futureAuthorization: { preserve: true } };
await db.update(issues).set({ executionPolicy: { ...before.executionPolicy, ...unrelatedPolicy } }).where(eq(issues.id, issueId));
const result = await heartbeat.tickTimers(tickAt);
@@ -260,6 +263,7 @@ describeEmbeddedPostgres("issue monitor scheduler", () => {
const issue = await db.select().from(issues).where(eq(issues.id, issueId)).then((rows) => rows[0]!);
expect(issue.monitorNextCheckAt).toBeNull();
expect(issue.executionPolicy).toMatchObject(unrelatedPolicy);
expect(issue.monitorAttemptCount).toBe(1);
expect(issue.monitorLastTriggeredAt?.toISOString()).toBe(tickAt.toISOString());
expect(normalizeIssueExecutionPolicy(issue.executionPolicy ?? null)?.monitor ?? null).toBeNull();
@@ -284,6 +288,89 @@ describeEmbeddedPostgres("issue monitor scheduler", () => {
expect(activity).toContain("issue.monitor_triggered");
});
it("preserves a due monitor through native execution and dispatches once after release", async () => {
const { companyId, issueId, agentId, nextCheckAt } = await seedFixture();
const runId = randomUUID();
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: issueId,
runtimeMode: "native", status: "running", contextSnapshot: { issueId } });
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));
const heartbeat = heartbeatService(db);
expect((await heartbeat.tickTimers(new Date("2026-04-11T12:31:00.000Z"))).enqueued).toBe(0);
const [waiting] = await db.select().from(issues).where(eq(issues.id, issueId));
expect(waiting.monitorNextCheckAt).toEqual(nextCheckAt);
expect(waiting.monitorWakeRequestedAt).toBeNull();
expect(await db.select().from(agentWakeupRequests)).toHaveLength(0);
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, runId));
await db.update(issues).set({ executionRunId: null }).where(eq(issues.id, issueId));
expect((await heartbeat.tickTimers(new Date("2026-04-11T12:32:00.000Z"))).enqueued).toBe(1);
expect((await heartbeat.tickTimers(new Date("2026-04-11T12:33:00.000Z"))).enqueued).toBe(0);
const [triggered] = await db.select().from(issues).where(eq(issues.id, issueId));
expect(triggered.monitorNextCheckAt).toBeNull();
expect(triggered.monitorAttemptCount).toBe(1);
expect((await db.select().from(agentWakeupRequests)).filter(wake => wake.reason === "issue_monitor_due")).toHaveLength(1);
});
it.each(["replaced", "cleared", "reassigned", "completed"] as const)("fences a monitor %s after claim but before wake admission", async (change) => {
const { companyId, issueId, agentId } = await seedFixture();
const replacementAt = new Date("2026-04-11T13:30:00.000Z");
let raced = false;
const racingDb = new Proxy(db, {
get(target, property, receiver) {
if (property !== "transaction") return Reflect.get(target, property, receiver);
return async (callback: Parameters<typeof db.transaction>[0]) => {
const result = await db.transaction(callback);
const claimed = result as { id?: string; monitorWakeRequestedAt?: Date } | undefined;
if (!raced && claimed?.id === issueId && claimed.monitorWakeRequestedAt) {
raced = true;
await db.update(issues).set(change === "replaced" ? {
monitorNextCheckAt: replacementAt, monitorWakeRequestedAt: null,
executionPolicy: { monitor: { nextCheckAt: replacementAt.toISOString(), notes: "Replacement check", scheduledBy: "assignee" } },
} : change === "cleared" ? { monitorNextCheckAt: null, monitorWakeRequestedAt: null, executionPolicy: null }
: change === "reassigned" ? { assigneeAgentId: null } : { status: "done" })
.where(eq(issues.id, issueId));
}
return result;
};
},
});
expect((await heartbeatService(racingDb).tickTimers(new Date("2026-04-11T12:31:00.000Z"))).enqueued).toBe(0);
expect(raced).toBe(true);
expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, companyId)))
.filter(wake => wake.reason === "issue_monitor_due")).toHaveLength(0);
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId))).toHaveLength(0);
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
if (change === "replaced") expect(issue.monitorNextCheckAt).toEqual(replacementAt);
if (change === "cleared") expect(issue.monitorNextCheckAt).toBeNull();
});
it("does not erase a replacement scheduled after wake admission", async () => {
const { companyId, issueId } = await seedFixture();
const nextCheckAt = new Date("2026-04-11T13:30:00.000Z");
let replaced = false;
const racingDb = new Proxy(db, {
get(target, property, receiver) {
if (property !== "transaction") return Reflect.get(target, property, receiver);
return async (callback: Parameters<typeof db.transaction>[0]) => {
const result = await db.transaction(callback);
if (!replaced && (result as { kind?: string } | undefined)?.kind === "queued") {
replaced = true;
await db.update(issues).set({ monitorNextCheckAt: nextCheckAt, monitorWakeRequestedAt: null,
executionPolicy: { monitor: { nextCheckAt: nextCheckAt.toISOString(), notes: "New check", scheduledBy: "assignee" } },
}).where(eq(issues.id, issueId));
}
return result;
};
},
});
await heartbeatService(racingDb).tickTimers(new Date("2026-04-11T12:31:00.000Z"));
expect(replaced).toBe(true);
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
expect(issue.monitorNextCheckAt).toEqual(nextCheckAt);
expect(issue.monitorWakeRequestedAt).toBeNull();
expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, companyId)))
.filter(wake => wake.reason === "issue_monitor_due")).toHaveLength(1);
});
it.each(["unknown", "exhausted"] as const)("does not replay a quota monitor with %s execution evidence", async (kind) => {
const sourceRunId = randomUUID();
const { companyId, issueId, agentId } = await seedFixture({
@@ -4,8 +4,9 @@ import os from "node:os";
import path from "node:path";
import express from "express";
import request from "supertest";
import { and, eq } from "drizzle-orm";
import { and, eq, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { renderPaperclipWakePrompt } from "@paperclipai/adapter-utils/server-utils";
import {
costEvents,
agents,
@@ -363,12 +364,16 @@ describeEmbeddedPostgres("issue recovery actions", () => {
it.each(["company", "issue", "legacy", "finished"])("rejects an apparently live run with the wrong %s authority", async (mismatch) => {
const { companyId, sourceIssueId, runId, svc } = await seedNativeFinalizationRecovery("running");
const other = await seedCompany();
await db.update(heartbeatRuns).set({
// Exercise service rejection of historical corruption behind the immutable binding trigger.
await db.transaction(async (tx) => {
await tx.execute(sql`set local session_replication_role = replica`);
await tx.update(heartbeatRuns).set({
...(mismatch === "company" ? { companyId: other.companyId, agentId: other.coderId } : {}),
...(mismatch === "issue" ? { nativeIssueId: other.sourceIssueId } : {}),
...(mismatch === "legacy" ? { runtimeMode: "legacy" } : {}),
...(mismatch === "finished" ? { finishedAt: new Date() } : {}),
}).where(eq(heartbeatRuns.id, runId));
});
expect((await svc.getActiveForIssue(companyId, sourceIssueId))?.nativeRunActivity).toBeNull();
});
@@ -1781,6 +1786,29 @@ describeEmbeddedPostgres("issue recovery actions", () => {
});
});
it.each(["resolved", "cancelled"])("omits %s recovery instructions when the original worker resumes", async (status) => {
const { companyId, coderId, sourceIssueId } = await seedCompany();
const action = await issueRecoveryActionService(db).upsertSourceScoped({
companyId, sourceIssueId, kind: "stranded_assigned_issue", ownerType: "board",
returnOwnerAgentId: coderId, cause: "stranded_assigned_issue", fingerprint: "finished-recovery",
evidence: { failureSummary: "Retry budget exhausted during cleanup." },
nextAction: "Repair the runtime, then retry the original owner.", wakePolicy: null,
});
await db.update(issueRecoveryActions).set({ status, outcome: "handed_back", resolvedAt: new Date() })
.where(eq(issueRecoveryActions.id, action.id));
const payload = await buildPaperclipWakePayload({ db, companyId, contextSnapshot: {
issueId: sourceIssueId, wakeReason: "issue_recovery_action_restored",
recoveryActionId: action.id, recoveryCause: action.cause,
} });
expect(payload?.issue?.id).toBe(sourceIssueId);
expect(payload?.recovery).toBeNull();
const prompt = renderPaperclipWakePrompt(payload);
expect(prompt).toContain("Implement backend recovery");
expect(prompt).not.toContain("Recovery contract:");
expect(prompt).not.toContain(action.nextAction);
expect(prompt).not.toContain("Do not produce the deliverable");
});
it("accepts new verified evidence after an automatic no-replay disposition without reopening on duplicate requests", async () => {
const { companyId, coderId, sourceIssueId } = await seedCompany();
const runId = randomUUID();
@@ -1,7 +1,7 @@
import { randomUUID } from "node:crypto";
import express from "express";
import request from "supertest";
import { and, eq } from "drizzle-orm";
import { and, eq, inArray } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import {
activityLog,
@@ -9,6 +9,7 @@ import {
agentWakeupRequests,
companies,
createDb,
environmentLeases,
heartbeatRunEvents,
heartbeatRuns,
issueComments,
@@ -44,6 +45,7 @@ describeEmbeddedPostgres("issue scheduled retry routes", () => {
}, 20_000);
afterEach(async () => {
await db.delete(environmentLeases);
await db.delete(issueComments);
await db.delete(issueRelations);
await db.delete(issueTreeHolds);
@@ -304,6 +306,37 @@ describeEmbeddedPostgres("issue scheduled retry routes", () => {
expect(retryRuns[0]).toMatchObject({ id: retryRunId, status: "queued" });
});
it("reports cleanup waits with the saved schedule and promotes the same retry after release", async () => {
const f = await seedIssueWithRetry();
await db.update(heartbeatRuns)
.set({ resultJson: { conversationContinuation: "continue_conversation_v1" } })
.where(inArray(heartbeatRuns.id, [f.sourceRunId, f.retryRunId]));
const [lease] = await db.insert(environmentLeases).values({
companyId: f.companyId, issueId: f.issueId, heartbeatRunId: f.sourceRunId,
status: "pending_cleanup", cleanupStatus: "failed",
}).returning();
const app = createApp(boardActor(f.companyId));
for (let click = 0; click < 2; click++) {
const before = Date.now();
const res = await request(app).post(`/api/issues/${f.issueId}/scheduled-retry/retry-now`).send({});
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(res.body).toMatchObject({ outcome: "waiting", scheduledRetry: {
runId: f.retryRunId, status: "scheduled_retry", scheduledRetryAttempt: 2,
} });
expect(res.body.message).toContain("Waiting for execution cleanup");
const [saved] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.retryRunId));
expect(res.body.scheduledRetry.scheduledRetryAt).toBe(saved!.scheduledRetryAt!.toISOString());
expect(saved!.scheduledRetryAt!.getTime()).toBeGreaterThanOrEqual(before + 30_000);
}
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, f.sourceRunId))).toHaveLength(1);
await db.update(environmentLeases).set({ status: "released", cleanupStatus: "success", releasedAt: new Date() })
.where(eq(environmentLeases.id, lease!.id));
const resumed = await request(app).post(`/api/issues/${f.issueId}/scheduled-retry/retry-now`).send({});
expect(resumed.body).toMatchObject({ outcome: "promoted", scheduledRetry: {
runId: f.retryRunId, status: "queued", scheduledRetryAttempt: 2,
} });
});
it("returns a clear no-op response when there is no scheduled retry", async () => {
const companyId = randomUUID();
const issueId = randomUUID();
@@ -4,6 +4,8 @@ import request from "supertest";
import { eq } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import {
authUsers,
companyMemberships,
activityLog,
agents,
companies,
@@ -47,7 +49,9 @@ describeEmbeddedPostgres("stale issue execution lock routes", () => {
await db.delete(issues);
await db.delete(heartbeatRuns);
await db.delete(agents);
await db.delete(companyMemberships);
await db.delete(companies);
await db.delete(authUsers);
});
afterAll(async () => {
@@ -78,6 +82,8 @@ describeEmbeddedPostgres("stale issue execution lock routes", () => {
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
requireBoardApprovalForNewAgents: false,
});
await db.insert(authUsers).values({ id: "board-user", name: "Board", email: "board@example.test", createdAt: new Date(), updatedAt: new Date() }).onConflictDoNothing();
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "board-user", status: "active", membershipRole: "admin" });
await db.insert(agents).values({
id: agentId,
companyId,
@@ -602,18 +602,21 @@ describeEmbeddedPostgres("issueThreadInteractionService", () => {
permissions: {},
});
await db.update(heartbeatRuns)
.set({ nativeIssueId: randomUUID() })
.where(eq(heartbeatRuns.id, fixture.runId));
// Simulate historical corruption to retain the service-level defense test.
await db.transaction(async (tx) => {
await tx.execute(sql`set local session_replication_role = replica`);
await tx.update(heartbeatRuns).set({ nativeIssueId: randomUUID() }).where(eq(heartbeatRuns.id, fixture.runId));
});
await expect(interactionsSvc.create(
{ id: fixture.issueId, companyId: fixture.companyId },
questionCreateInput(fixture.runId),
{ agentId: fixture.agentId, runId: fixture.runId },
)).rejects.toMatchObject({ status: 422, message: "sourceRunId must belong to the same issue" });
await db.update(heartbeatRuns)
.set({ nativeIssueId: null, contextSnapshot: { issueId: randomUUID(), paperclipWake: { comments: [] } } })
.where(eq(heartbeatRuns.id, fixture.runId));
await db.transaction(async (tx) => {
await tx.execute(sql`set local session_replication_role = replica`);
await tx.update(heartbeatRuns).set({ nativeIssueId: null, contextSnapshot: { issueId: randomUUID(), paperclipWake: { comments: [] } } }).where(eq(heartbeatRuns.id, fixture.runId));
});
await expect(interactionsSvc.create(
{ id: fixture.issueId, companyId: fixture.companyId },
questionCreateInput(fixture.runId),
@@ -28,10 +28,12 @@ const mockHeartbeatService = vi.hoisted(() => ({
cancelRun: vi.fn(),
wakeup: vi.fn(),
}));
const mockAccessService = vi.hoisted(() => ({ decide: vi.fn() }));
const mockHeartbeatFactory = vi.hoisted(() => vi.fn());
vi.mock("../services/index.js", () => ({
accessService: () => mockAccessService,
heartbeatService: mockHeartbeatFactory,
issueService: () => mockIssueService,
issueTreeControlService: () => mockTreeControlService,
@@ -87,6 +89,25 @@ describe("issue tree control routes", () => {
});
mockHeartbeatService.cancelRun.mockResolvedValue(null);
mockHeartbeatService.wakeup.mockResolvedValue(null);
mockAccessService.decide.mockResolvedValue({ allowed: true });
});
it("conceals private roots from non-members before exposing tree state", async () => {
const app = await createApp({
type: "board",
userId: "user-1",
companyIds: ["company-2"],
source: "session",
isInstanceAdmin: false,
});
mockAccessService.decide.mockResolvedValue({ allowed: false, reason: "deny_issue_private" });
const res = await request(app)
.post("/api/issues/11111111-1111-4111-8111-111111111111/tree-control/preview")
.send({ mode: "pause" });
expect(res.status).toBe(404);
expect(mockTreeControlService.preview).not.toHaveBeenCalled();
});
it.each([false, true])(
+118 -1
View File
@@ -18,6 +18,7 @@ import {
issueComments,
issueInboxArchives,
issueDocuments,
issueAccessGrants,
issuePlanDecompositions,
issueReadStates,
issueRelations,
@@ -25,6 +26,7 @@ import {
issueWorkProducts,
issues,
projectWorkspaces,
projectAccessMembers,
projects,
workspaceOperations,
toolApplications,
@@ -3280,6 +3282,121 @@ describeEmbeddedPostgres("issueService.create workspace inheritance", () => {
expect(child.responsibleUserId).toBe(responsibleUserId);
});
it("creates children under a private issue in the same private subtree", async () => {
const companyId = randomUUID();
const parentIssueId = randomUUID();
await db.insert(companies).values({
id: companyId,
name: "Private subtree company",
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
});
await db.insert(issues).values({
id: parentIssueId,
companyId,
title: "Private root",
visibility: "private",
privacyRootIssueId: parentIssueId,
});
const child = await svc.create(companyId, {
parentId: parentIssueId,
title: "Inherited private child",
visibility: "open",
});
expect(child.visibility).toBe("private");
expect(child.privacyRootIssueId).toBe(parentIssueId);
});
it("creates one personal private project and parks private tasks there", async () => {
const companyId = randomUUID();
const responsibleUserId = randomUUID();
await db.insert(companies).values({
id: companyId,
name: "Personal private tasks company",
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
});
const [first, second] = await Promise.all([
svc.create(companyId, {
title: "First personal private task",
visibility: "private",
createdByUserId: responsibleUserId,
}),
svc.create(companyId, {
title: "Second personal private task",
visibility: "private",
createdByUserId: responsibleUserId,
}),
]);
const personalProjects = await db.select().from(projects)
.where(eq(projects.personalOwnerUserId, responsibleUserId));
expect(personalProjects).toHaveLength(1);
expect(personalProjects[0]).toMatchObject({
companyId,
name: "My private tasks",
visibility: "private",
});
expect(first.projectId).toBe(personalProjects[0]!.id);
expect(second.projectId).toBe(personalProjects[0]!.id);
expect(first.privacyRootIssueId).toBe(first.id);
expect(second.privacyRootIssueId).toBe(second.id);
await expect(db.select().from(projectAccessMembers)
.where(eq(projectAccessMembers.projectId, personalProjects[0]!.id)))
.resolves.toEqual([
expect.objectContaining({ subjectType: "user", subjectId: responsibleUserId }),
]);
});
it("keeps a responsible human and grants an agent access to its explicitly private task", async () => {
const companyId = randomUUID();
const responsibleUserId = randomUUID();
const creatorAgentId = randomUUID();
await db.insert(companies).values({
id: companyId,
name: "Agent private task company",
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
});
await db.insert(agents).values({
id: creatorAgentId,
companyId,
name: "Private task creator",
role: "engineer",
adapterType: "process",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
});
const issue = await svc.create(companyId, {
title: "Agent email scratch task",
visibility: "private",
createdByAgentId: creatorAgentId,
actorResponsibleUserId: responsibleUserId,
});
expect(issue.responsibleUserId).toBe(responsibleUserId);
const personalProject = await db.select().from(projects)
.where(eq(projects.id, issue.projectId!))
.then((rows) => rows[0]!);
expect(personalProject.personalOwnerUserId).toBe(responsibleUserId);
await expect(db.select().from(projectAccessMembers)
.where(eq(projectAccessMembers.projectId, personalProject.id)))
.resolves.toEqual([
expect.objectContaining({ subjectType: "user", subjectId: responsibleUserId }),
]);
await expect(db.select().from(issueAccessGrants)
.where(eq(issueAccessGrants.issueId, issue.id)))
.resolves.toEqual([
expect.objectContaining({
subjectType: "agent",
subjectId: creatorAgentId,
source: "explicit",
}),
]);
});
it("only honors explicit responsibleUserId for trusted issue create callers", async () => {
const companyId = randomUUID();
const creatorUserId = randomUUID();
@@ -5668,7 +5785,7 @@ describeEmbeddedPostgres("issueService.create workspace inheritance", () => {
.where(eq(executionWorkspaces.id, executionWorkspaceId))
.then((rows) => rows[0] ?? null);
expect(workspace?.metadata).toEqual({
expect(workspace?.metadata).toMatchObject({
config: {
environmentId: null,
provisionCommand: "bash ./scripts/provision-new.sh",
@@ -0,0 +1,229 @@
import { randomUUID } from "node:crypto";
import { and, eq, sql } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { agents, companies, createDb, environmentLeases, environments, heartbeatRuns, issueRecoveryActions, issues } from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { recordLegacyWorkspaceRestoreFailure, legacyExecutionNeedsReconciliationWithEvidence, terminalizeLegacyExecution } from "../services/legacy-execution-recovery.js";
import { hasConversationContinuationPolicy, conversationRecoveryActionPredicate } from "../services/conversation-continuation.js";
import { preserveWorkspaceRestoreRecoveryMetadataSql } from "../services/legacy-workspace-restore-recovery.js";
import { settleStopOnlyCleanup } from "../services/sandbox-stop-and-retain.js";
import { hasRequiredWorkspaceRecovery } from "../services/workspace-restore-recovery-state.js";
const externalTestDatabaseUrl = process.env.PAPERCLIP_TEST_DATABASE_URL?.trim();
const support = externalTestDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport();
(support.supported ? describe : describe.skip)("legacy remote workspace recovery", () => {
let db: ReturnType<typeof createDb>;
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
beforeAll(async () => { if (externalTestDatabaseUrl) db = createDb(externalTestDatabaseUrl);
else { temporary = await startEmbeddedPostgresTestDatabase("legacy-workspace-recovery-"); db = createDb(temporary.connectionString); } }, 30_000);
afterAll(async () => { await db?.$client.end(); await temporary?.cleanup(); });
async function seed(options: { local?: boolean; taskDone?: boolean; reusable?: boolean } = {}) {
const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Workspace recovery", issuePrefix: companyId.slice(0, 8) });
await db.insert(agents).values({ id: agentId, companyId, name: "Engineer", role: "engineer", adapterType: "codex_local" });
await db.insert(issues).values({ id: issueId, companyId, title: "Restore files", status: options.taskDone ? "done" : "in_progress", assigneeAgentId: agentId });
const [run] = await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", runtimeMode: "legacy", contextSnapshot: { issueId } }).returning();
if (options.local) await db.insert(environments).values({ name: "Local", driver: "local" }).onConflictDoNothing();
const [environment] = options.local ? await db.select().from(environments).where(eq(environments.driver, "local"))
: await db.insert(environments).values({ name: `Isolated test sandbox ${runId}`, driver: "sandbox" }).returning();
const [lease] = await db.insert(environmentLeases).values({ companyId, issueId, heartbeatRunId: runId, environmentId: environment.id,
status: "active", leasePolicy: options.reusable ? "reuse_by_environment" : "ephemeral",
provider: options.local ? "local" : "daytona", providerLeaseId: randomUUID(),
metadata: { driver: options.local ? "local" : "sandbox", pluginId: randomUUID(), sandboxProviderPlugin: !options.local },
}).returning();
return { companyId, runId, issueId, run, lease };
}
const patch = { errorCode: "workspace_restore_failed", finishedAt: new Date(), resultJson: {
workspaceRestoreFailure: "restore_failed", conversationContinuation: "continue_conversation_v1",
} };
const readLease = async (id: string) => (await db.select().from(environmentLeases).where(eq(environmentLeases.id, id)))[0];
it.each([false, true])("persists terminal status, stop-only source and board action atomically (task done=%s)", async taskDone => {
const f = await seed({ taskDone, reusable: true });
expect(await legacyExecutionNeedsReconciliationWithEvidence(db, { ...f.run, status: "failed", ...patch })).toBe(true);
const failed = await terminalizeLegacyExecution({ db, run: f.run, status: "failed", patch });
expect(failed?.status).toBe("failed");
expect(failed?.resultJson?.workspaceRestoreRecovery).toMatchObject({ leaseIds: [f.lease.id] });
expect(hasConversationContinuationPolicy(failed?.resultJson)).toBe(false);
const lease = await readLease(f.lease.id);
expect(lease).toMatchObject({ status: "pending_cleanup", leasePolicy: "retain_on_failure", metadata: {
sandboxStopAndRetain: { companyId: f.companyId, runId: f.runId, leaseId: f.lease.id, providerLeaseId: f.lease.providerLeaseId },
pendingCleanupInFlight: false,
} });
const [action] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId));
expect(action).toMatchObject({ ownerType: "board", evidence: { workspaceRestoreRecovery: { leaseIds: [f.lease.id] } } });
expect(await db.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.id, action.id), conversationRecoveryActionPredicate()))).toEqual([]);
// A new controller uses the durable stop-only intent. It cannot turn a
// successful stop into proof that the workspace files were restored.
const receipt = { schema: "paperclip.remote-termination.v1", runId: f.runId, companyId: f.companyId,
leaseId: lease.id, provider: lease.provider, providerLeaseId: lease.providerLeaseId, state: "stopped", confirmedAt: new Date().toISOString() };
await settleStopOnlyCleanup(db, lease, { attemptId: String(lease.metadata?.pendingCleanupAttemptId), receipt });
expect(await readLease(lease.id)).toMatchObject({ status: "released", leasePolicy: "retain_on_failure", metadata: { remoteExecutionTermination: { state: "stopped" } } });
expect(hasRequiredWorkspaceRecovery(failed?.resultJson)).toBe(true);
expect(await legacyExecutionNeedsReconciliationWithEvidence(db, failed!)).toBe(true);
// A late adapter metadata write cannot erase the source pin when its
// in-memory result predates the terminal transaction.
expect(await legacyExecutionNeedsReconciliationWithEvidence(db, { ...failed!, resultJson: patch.resultJson })).toBe(true);
const repeated = await terminalizeLegacyExecution({ db, run: failed!, status: "failed", patch });
expect(repeated?.resultJson?.workspaceRestoreRecovery).toMatchObject({ leaseIds: [f.lease.id] });
expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId)))).toHaveLength(1);
});
it("leaves local lock retry and successful remote cleanup policy unchanged", async () => {
const local = await seed({ local: true });
const failure = { ...patch, resultJson: { ...patch.resultJson, workspaceRestoreFailure: "restore_lock_timeout" } };
expect(await legacyExecutionNeedsReconciliationWithEvidence(db, { ...local.run, status: "failed", ...failure })).toBe(false);
expect(await readLease(local.lease.id)).toMatchObject({ status: "active", leasePolicy: "ephemeral" });
const remote = await seed();
expect(await legacyExecutionNeedsReconciliationWithEvidence(db, { ...remote.run, status: "succeeded", resultJson: {} })).toBe(false);
expect(await readLease(remote.lease.id)).toMatchObject({ status: "active", leasePolicy: "ephemeral" });
});
it("does not retain another run's lease or revive an already released source", async () => {
const f = await seed(), other = await seed();
await db.update(environmentLeases).set({ status: "released", releasedAt: new Date() }).where(eq(environmentLeases.id, f.lease.id));
expect(await legacyExecutionNeedsReconciliationWithEvidence(db, { ...f.run, status: "failed", ...patch })).toBe(false);
await terminalizeLegacyExecution({ db, run: f.run, status: "failed", patch });
expect(await readLease(f.lease.id)).toMatchObject({ status: "released", leasePolicy: "ephemeral" });
expect(await readLease(other.lease.id)).toMatchObject({ status: "active", leasePolicy: "ephemeral" });
});
it("keeps a competing physical owner out of the stop receipt", async () => {
const f = await seed(), other = await seed();
await db.update(environmentLeases).set({ providerLeaseId: f.lease.providerLeaseId }).where(eq(environmentLeases.id, other.lease.id));
await terminalizeLegacyExecution({ db, run: f.run, status: "failed", patch });
expect(await readLease(f.lease.id)).toMatchObject({ status: "pending_cleanup", metadata: { sandboxStopAndRetain: { runId: f.runId } } });
expect(await readLease(other.lease.id)).toMatchObject({ status: "active", heartbeatRunId: other.runId });
});
it("keeps the original source if host finalization fails after adapter settlement", async () => {
const f = await seed();
await recordLegacyWorkspaceRestoreFailure(db, f.run, patch.resultJson);
const [current] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
expect(current.status).toBe("running");
expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId))).toHaveLength(1);
expect(hasRequiredWorkspaceRecovery(current.resultJson)).toBe(true);
expect(await readLease(f.lease.id)).toMatchObject({ status: "pending_cleanup", leasePolicy: "retain_on_failure" });
// A restart's process-loss finalization sees the durable obligation, even
// when its own result predates the restore failure.
const stale = { stopReason: "process_lost" };
const failed = await terminalizeLegacyExecution({ db, run: f.run, status: "failed", reconcileIfNeeded: true, patch: { errorCode: "process_lost", resultJson: stale } });
expect(hasRequiredWorkspaceRecovery(failed?.resultJson)).toBe(true);
expect(await readLease(f.lease.id)).toMatchObject({ status: "pending_cleanup", leasePolicy: "retain_on_failure" });
expect(hasConversationContinuationPolicy(failed?.resultJson)).toBe(false);
});
it("records a repair action when cancellation wins before adapter copy-back reports failure", async () => {
const f = await seed();
await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date(), resultJson: { executionCancellation: { state: "acknowledged", proof: "provider_termination_receipt" } } }).where(eq(heartbeatRuns.id, f.runId));
await recordLegacyWorkspaceRestoreFailure(db, f.run, patch.resultJson);
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
expect(run.status).toBe("cancelled");
expect(run.resultJson?.executionCancellation).toMatchObject({ state: "acknowledged", proof: "provider_termination_receipt" });
expect(hasRequiredWorkspaceRecovery(run.resultJson)).toBe(true);
expect(await readLease(f.lease.id)).toMatchObject({ status: "pending_cleanup", leasePolicy: "retain_on_failure" });
expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId))).toHaveLength(1);
});
it.each(["write_condition", "native_takeover"])("preserves the existing terminal-write fence for %s", async scenario => {
const f = await seed();
if (scenario === "native_takeover") await db.update(heartbeatRuns).set({ runtimeMode: "native" }).where(eq(heartbeatRuns.id, f.runId));
const failed = await terminalizeLegacyExecution({ db, run: f.run, status: "failed", patch,
reconcileIfNeeded: true, ...(scenario === "write_condition" ? { writeConditions: [sql`false`] } : {}),
});
expect(failed).toBeNull();
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)))[0].status).toBe("running");
expect(await readLease(f.lease.id)).toMatchObject({ status: "active", leasePolicy: "ephemeral" });
expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId))).toEqual([]);
});
it.each([false, true])("keeps exact retained source IDs through a projected metadata update (merge=%s)", async mergeCurrent => {
const f = await seed();
await recordLegacyWorkspaceRestoreFailure(db, f.run, patch.resultJson);
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
const projection = { workspaceRestoreFailure: "restore_failed", workspaceRestoreRecovery: { schema: "paperclip.workspace-restore-recovery.v1" }, presentationDecision: "updated" };
const [updated] = await db.update(heartbeatRuns).set({ resultJson: preserveWorkspaceRestoreRecoveryMetadataSql(projection, mergeCurrent) })
.where(eq(heartbeatRuns.id, f.runId)).returning();
expect(updated.resultJson).toMatchObject({ presentationDecision: "updated", workspaceRestoreRecovery: run.resultJson!.workspaceRestoreRecovery });
expect(updated.resultJson?.workspaceRestoreFailure).toBe("restore_failed");
});
it("keeps ordinary metadata replacement and null semantics without a repair marker", async () => {
const f = await seed();
await db.update(heartbeatRuns).set({ resultJson: { oldValue: true } }).where(eq(heartbeatRuns.id, f.runId));
const [replaced] = await db.update(heartbeatRuns).set({ resultJson: preserveWorkspaceRestoreRecoveryMetadataSql({ newValue: true }) })
.where(eq(heartbeatRuns.id, f.runId)).returning();
expect(replaced.resultJson).toEqual({ newValue: true });
const [cleared] = await db.update(heartbeatRuns).set({ resultJson: preserveWorkspaceRestoreRecoveryMetadataSql(null) })
.where(eq(heartbeatRuns.id, f.runId)).returning();
expect(cleared.resultJson).toBeNull();
});
it("rolls back terminal status and retention together on a failed transaction", async () => {
const f = await seed();
await expect(db.transaction(async tx => { await terminalizeLegacyExecution({ db: tx as unknown as typeof db, run: f.run, status: "failed", patch }); throw new Error("outer transaction failed"); })).rejects.toThrow("outer transaction failed");
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)))[0].status).toBe("running");
expect(await readLease(f.lease.id)).toMatchObject({ status: "active", leasePolicy: "ephemeral" });
expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId))).toEqual([]);
}); it.each(["conversation_reset", "new_owner"])("late restore remains repair-blocked after %s", async scenario => {
const f = await seed();
await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date(),
contextSnapshot: { issueId: f.issueId, conversationSessionGeneration: 0 },
resultJson: { executionCancellation: { state: "acknowledged" }, conversationContinuation: "continue_conversation_v1" },
}).where(eq(heartbeatRuns.id, f.runId));
if (scenario === "conversation_reset") await db.update(issues).set({ conversationAgentId: f.run.agentId, conversationUserId: "board-review-fixture", conversationState: "active",
conversationSessionGeneration: scenario === "conversation_reset" ? 1 : 0,
}).where(eq(issues.id, f.issueId));
if (scenario === "new_owner") {
const id = randomUUID();
await db.insert(agents).values({ id, companyId: f.companyId, name: "New owner", role: "engineer", adapterType: "codex_local" });
await db.update(issues).set({ assigneeAgentId: id }).where(eq(issues.id, f.issueId));
}
await recordLegacyWorkspaceRestoreFailure(db, f.run, patch.resultJson);
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
expect(hasRequiredWorkspaceRecovery(run.resultJson)).toBe(true);
const lease = await readLease(f.lease.id);
expect(lease).toMatchObject({ status: "pending_cleanup", leasePolicy: "retain_on_failure" });
await settleStopOnlyCleanup(db, lease, { attemptId: String(lease.metadata?.pendingCleanupAttemptId),
receipt: { providerLeaseId: lease.providerLeaseId, state: "stopped" } });
const { getExecutionBlocker } = await import("../services/execution-blocker.js");
expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toMatchObject({
recoveryActionId: expect.any(String), canRetry: false, canContinue: false,
});
expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId)))
.toHaveLength(1);
});
it("keeps a late source hold alongside a newer incident without replacing its execution", async () => {
const f = await seed(), newerRunId = randomUUID();
await db.insert(heartbeatRuns).values({ id: newerRunId, companyId: f.companyId, agentId: f.run.agentId,
status: "running", runtimeMode: "legacy", contextSnapshot: { issueId: f.issueId } });
await db.update(issues).set({ executionRunId: newerRunId, checkoutRunId: newerRunId }).where(eq(issues.id, f.issueId));
const [newerAction] = await db.insert(issueRecoveryActions).values({ companyId: f.companyId, sourceIssueId: f.issueId,
kind: "active_run_watchdog", status: "active", cause: "another_incident", fingerprint: `newer:${newerRunId}`,
evidence: { runId: newerRunId }, nextAction: "Inspect the current incident." }).returning();
const failed = await terminalizeLegacyExecution({ db, run: f.run, status: "failed", patch });
await terminalizeLegacyExecution({ db, run: failed!, status: "failed", patch });
const [task] = await db.select().from(issues).where(eq(issues.id, f.issueId));
expect(task).toMatchObject({ status: "in_progress", executionRunId: newerRunId, checkoutRunId: newerRunId });
const actions = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId));
expect(actions).toHaveLength(2);
expect(actions.find(a => a.id === newerAction.id)).toEqual(newerAction);
const source = actions.find(a => a.evidence.runId === f.runId)!;
expect(source).toMatchObject({ status: "resolved", outcome: "blocked", ownerType: "board",
returnOwnerAgentId: null, attemptCount: 1, evidence: { automaticRecovery: { replay: "blocked" } } });
const { markExecutionReconciliation } = await import("../services/execution-recovery-resolution.js");
await markExecutionReconciliation(db, source, { runId: f.runId, providerStopped: true, actionOutcome: "mixed",
outcomeEvidence: "The original provider's actions were inspected.",
workspaceRepairEvidence: "The exact retained workspace was recovered and verified.",
}, "board-test", undefined, { workspaceRepairOnly: true });
await terminalizeLegacyExecution({ db, run: failed!, status: "failed", patch });
const [repaired] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, source.id));
expect(repaired.evidence.automaticRecovery).toBeUndefined();
expect(repaired.evidence.continuationDelivery).toBe("not_requested");
expect(repaired.evidence.executionReconciliation).toMatchObject({ runId: f.runId });
});
});
@@ -1368,10 +1368,8 @@ describeEmbeddedPostgres(
expect(
unmentionedComment.status,
JSON.stringify(unmentionedComment.body),
).toBe(403);
expect(unmentionedComment.body.details.code).toBe(
"issue_write_actor_class_excluded",
);
).toBe(404);
expect(unmentionedComment.body).toEqual({ error: "Issue not found" });
});
it("propagates denied low-trust policy conflicts on control-plane guards", async () => {
@@ -1738,7 +1736,7 @@ describeEmbeddedPostgres(
const before = await snapshot(db);
const res = await attempt.req();
expect(res.status, `${attempt.id}: ${JSON.stringify(res.body)}`).toBe(
403,
["LT approvals", "LT-15/16", "LT-19", "LT-26 child", "LT-26 child with unauthorized assignee", "LT-26 company issue", "LT-26 interaction", "LT-06 resume", "LT-06 blocker mutation"].includes(attempt.id) ? 403 : 404,
);
expectNoCanary(res.body, ...forbiddenMarkers);
const after = await snapshot(db);
@@ -1881,7 +1879,7 @@ describeEmbeddedPostgres(
for (const attempt of attempts) {
const res = await attempt.req();
expect(res.status, `${attempt.id}: ${JSON.stringify(res.body)}`).toBe(
403,
404,
);
expectNoCanary(res.body, ...forbiddenMarkers);
}
@@ -0,0 +1,30 @@
import { randomUUID } from "node:crypto";
import { request } from "@playwright/test";
import { afterAll, beforeAll, expect, it, vi } from "vitest";
import { startRunnerApiTestServer } from "./helpers/runner-api-server.js";
import { RunnerApi } from "../../../tests/runner-e2e/api.js";
import { setupAggregatorFixture } from "../../../tests/runner-e2e/aggregator-fixture.js";
let server: Awaited<ReturnType<typeof startRunnerApiTestServer>>;
beforeAll(async () => {
vi.stubEnv("PAPERCLIP_AGENT_JWT_SECRET", randomUUID());
server = await startRunnerApiTestServer({ deploymentMode: "local_trusted" });
vi.stubEnv("PAPERCLIP_RUNNER_E2E_PORT", new URL(server.apiUrl).port);
}, 60_000);
afterAll(async () => { await server?.close(); vi.unstubAllEnvs(); });
it("sets up an indexed company gateway without granting the eval agent access", async () => {
const fixture = await server.fixture({ connectionScenario: "fresh", disableWakeOnDemand: true });
const context = await request.newContext({ baseURL: server.apiUrl, extraHTTPHeaders: { Origin: server.apiUrl } });
const api = new RunnerApi(context);
let gateway: Awaited<ReturnType<typeof setupAggregatorFixture>> | undefined;
try {
gateway = await setupAggregatorFixture(api, fixture.companyId, fixture.agentId, "CONTACTS_local_only", true);
expect(gateway.initialAccess).toEqual({ installed: false, allowedToolIds: [] });
expect(gateway.invocationCount()).toBe(0);
const discovery = await fixture.authority.execute({ tool: "connections_search", callId: randomUUID(), arguments: { query: "HubSpot" } });
expect(discovery).toMatchObject({ providerQuestion: { id: "connection-provider:hubspot" }, providerQuestionSet: { schema: "paperclip.question_set.v1" } });
await expect(fixture.authority.execute({ tool: "connection_request", callId: randomUUID(), arguments: { service: "via:arcade:hubspot" } })).rejects.toThrow();
expect(gateway.invocationCount()).toBe(0);
} finally { await gateway?.close(); await context.dispose(); }
}, 60_000);
@@ -2907,6 +2907,39 @@ describe("P6-31 Section 18.13 executable status-authority corpus", () => {
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey, key))).toHaveLength(1);
});
it.each(["scheduled", "cleared", "replaced", "reassigned"] as const)("revalidates a %s monitor under the final disposition lock", async (state) => {
const template = corpus.fixtures.find(candidate => candidate.mode === "native")!;
const fixture = { ...template, id: `monitor-commit-${state}`, given: { ...template.given, priorIssueStatus: "in_progress" } };
const seeded = await seedFixture(fixture);
const nextCheckAt = new Date(Date.now() + 60_000).toISOString();
const currentCheck = state === "replaced" ? new Date(Date.now() + 120_000).toISOString() : nextCheckAt;
await db.update(issues).set({
executionRunId: seeded.runId, checkoutRunId: seeded.runId,
assigneeAgentId: state === "reassigned" ? null : agentId,
monitorNextCheckAt: state === "cleared" ? null : new Date(currentCheck),
executionPolicy: state === "cleared" ? null : { monitor: { nextCheckAt: currentCheck, notes: "Check again" } },
}).where(eq(issues.id, seeded.issueId));
const decision: NativeStatusDecision = { policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
statusAction: "preserve", toStatus: "in_progress", reasonCode: "scheduled_monitor_waiting",
unblockDescriptor: null, effects: [{ kind: "release_checkout" }] };
const commit = () => commitNativeStatusDecision({ db, companyId, issueId: seeded.issueId, runId: seeded.runId,
assessmentId: seeded.assessmentId, priorStatus: "in_progress", priorStatusVersion: 0, priorDecisionId: null,
decision, requireMonitorWait: { agentId, nextCheckAt } });
if (state !== "scheduled") {
await expect(commit()).rejects.toThrow("native_status_race");
expect(await db.select().from(statusDecisions).where(eq(statusDecisions.issueId, seeded.issueId))).toHaveLength(0);
} else {
await commit();
expect((await commit()).replayed).toBe(true);
const [issue] = await db.select().from(issues).where(eq(issues.id, seeded.issueId));
expect(issue).toMatchObject({ status: "in_progress", checkoutRunId: null, executionRunId: null });
expect(issue.monitorNextCheckAt?.toISOString()).toBe(nextCheckAt);
const effects = await db.select().from(statusDecisionEffects).where(eq(statusDecisionEffects.issueId, seeded.issueId));
expect(effects.map(effect => effect.effectKind)).toEqual(["release_checkout"]);
expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.agentId, agentId))).filter(wake => wake.payload?.issueId === seeded.issueId)).toHaveLength(0);
}
});
it("fails the transaction closed for an unknown status effect", async () => {
const fixture = corpus.fixtures.find((candidate) => candidate.mode === "native");
if (!fixture) throw new Error("native corpus fixture missing");
@@ -23,6 +23,7 @@ const apiPrefixes: Record<string, string> = {
"agent-avatars.ts": "/api",
"announcements.ts": "/api",
"ai-connections.ts": "/api",
"decision-models.ts": "/api",
"attention.ts": "/api",
"approvals.ts": "/api",
"assets.ts": "/api",
@@ -64,6 +65,7 @@ const apiPrefixes: Record<string, string> = {
"plugin-ui-static.ts": "/api",
"plugins.ts": "/api",
"projects.ts": "/api",
"primary-agent.ts": "/api",
"public-mcp.ts": "/api",
"project-tools.ts": "/api",
"resource-memberships.ts": "/api",
@@ -273,6 +275,19 @@ function loadSpecRoutes() {
}
describe("openapi routes", () => {
it("documents manager-only task privacy hints without protected scope identity", () => {
const spec = buildOpenApiSpec() as any;
const operation = spec.paths["/api/issues/{id}/privacy-constraints"].get;
const schema = operation.responses["200"].content["application/json"].schema;
expect(schema.properties).toEqual({
publicBlockedBy: { type: "string", enum: ["parent", "project"], nullable: true },
leavesPersonalProject: { type: "boolean" },
});
expect(schema.required).toEqual(["publicBlockedBy", "leavesPersonalProject"]);
expect(operation.responses["403"]).toBeDefined();
expect(operation.responses["404"]).toBeDefined();
});
it("documents strict run-attributed feedback without a read endpoint", () => {
const { spec } = loadSpecRoutes();
const path = spec.paths["/api/companies/{companyId}/agent-commentary"];
@@ -825,6 +840,24 @@ describe("openapi routes", () => {
});
});
it("documents the authenticated personal primary-agent contract", () => {
const { spec } = loadSpecRoutes();
const path = spec.paths["/api/companies/{companyId}/primary-agent/me"];
for (const operation of [path.get, path.put]) {
expect(operation["x-paperclip-authorization"]).toEqual({ actor: "board" });
expect(operation.security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]);
expect(operation.responses["200"].content["application/json"].schema.required).toEqual([
"companyId", "userId", "primaryAgentId", "initialized",
]);
}
expect(path.put.requestBody.content["application/json"].schema).toMatchObject({
additionalProperties: false,
required: ["primaryAgentId"],
properties: { primaryAgentId: { type: "string", format: "uuid" } },
});
expect(path.put.responses["422"]).toBeDefined();
});
it("documents board-only repository discovery and selection", () => {
const { spec } = loadSpecRoutes();
const discovery = spec.paths["/api/companies/{companyId}/project-repositories"].get;
@@ -11,6 +11,7 @@ import {
agentInstructionHeads,
agents,
approvals,
budgetPolicies,
companies,
createDb,
pluginEntities,
@@ -107,6 +108,7 @@ describeEmbeddedPostgres("plugin-managed agents", () => {
await db.delete(pluginManagedResources);
await db.delete(pluginCompanySettings);
await db.delete(approvals);
await db.delete(budgetPolicies);
await db.delete(principalPermissionGrants);
await db.delete(agents);
await db.delete(plugins);
@@ -499,6 +501,7 @@ describeEmbeddedPostgres("plugin-managed agents", () => {
const relinked = await services.agents.managedReconcile({ companyId, agentKey: "wiki-maintainer" });
expect(relinked.status).toBe("relinked");
expect(relinked.agentId).toBe(agentId);
expect(relinked.agent?.urlKey).toBe("renamed-wiki-agent");
const [binding] = await db.select().from(pluginEntities);
expect(binding?.data).toMatchObject({ agentId });
@@ -3,7 +3,7 @@ import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import { and, eq } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
import {
activityLog,
agentWakeupRequests,
@@ -14,11 +14,13 @@ import {
companyMemberships,
costEvents,
createDb,
documents,
executionWorkspaces,
heartbeatRunEvents,
heartbeatRuns,
issueAttachments,
issueComments,
issueDocuments,
issueRelations,
issueThreadInteractions,
issues,
@@ -215,14 +217,6 @@ describeEmbeddedPostgres("plugin orchestration APIs", () => {
const { companyId, agentId } = await seedCompanyAndAgent();
const blockerIssueId = randomUUID();
const originRunId = randomUUID();
await db.insert(heartbeatRuns).values({
id: originRunId,
companyId,
agentId,
status: "running",
invocationSource: "assignment",
contextSnapshot: { issueId: blockerIssueId },
});
await db.insert(issues).values({
id: blockerIssueId,
companyId,
@@ -231,6 +225,15 @@ describeEmbeddedPostgres("plugin orchestration APIs", () => {
priority: "medium",
identifier: `${issuePrefix(companyId)}-blocker`,
});
await db.insert(heartbeatRuns).values({
id: originRunId,
companyId,
agentId,
status: "running",
invocationSource: "assignment",
contextSnapshot: { issueId: blockerIssueId },
});
const services = buildHostServices(db, "plugin-record-id", "paperclip.missions", createEventBusStub());
const issue = await services.issues.create({
@@ -1284,4 +1287,215 @@ describeEmbeddedPostgres("plugin orchestration APIs", () => {
services.issues.getAttachmentContent({ attachmentId, companyId, maxBytes: 1_000_000 }),
).rejects.toThrow("over the");
});
// PAP-16091 / PAP-16050: a plugin is a non-member principal. Every issue-read
// path the host exposes (which a Slack notifier/digest plugin would fan out
// to shared channels) must apply the canonical visibility predicate so private
// issue content and relationship metadata never reach non-members.
describe("non-member plugin issue-read privacy (PAP-16091)", () => {
let previousMode: string | undefined;
beforeEach(() => {
previousMode = process.env.PAPERCLIP_ISSUE_PRIVACY_MODE;
process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = "enforce";
});
afterEach(() => {
if (previousMode === undefined) delete process.env.PAPERCLIP_ISSUE_PRIVACY_MODE;
else process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = previousMode;
});
async function seedOpenAndPrivate() {
const { companyId, agentId } = await seedCompanyAndAgent();
const openIssueId = randomUUID();
const privateIssueId = randomUUID();
await db.insert(issues).values([
{ id: openIssueId, companyId, title: "Public status", status: "todo", priority: "medium", visibility: "open" },
{ id: privateIssueId, companyId, title: "Confidential HR matter", status: "todo", priority: "medium", visibility: "private" },
]);
return { companyId, agentId, openIssueId, privateIssueId };
}
it("omits private issues from issues.list", async () => {
const { companyId, openIssueId, privateIssueId } = await seedOpenAndPrivate();
const services = buildHostServices(db, "plugin-record-id", "paperclip.slack-digest", createEventBusStub());
const listed = await services.issues.list({ companyId });
const ids = listed.map((issue) => issue.id);
expect(ids).toContain(openIssueId);
expect(ids).not.toContain(privateIssueId);
});
it("returns null from issues.get for a private issue", async () => {
const { companyId, openIssueId, privateIssueId } = await seedOpenAndPrivate();
const services = buildHostServices(db, "plugin-record-id", "paperclip.slack-digest", createEventBusStub());
await expect(services.issues.get({ issueId: privateIssueId, companyId })).resolves.toBeNull();
// Sanity: the same path still returns readable (open) issues.
await expect(services.issues.get({ issueId: openIssueId, companyId })).resolves.toMatchObject({ id: openIssueId });
});
it("returns no comments from issues.listComments for a private issue", async () => {
const { companyId, privateIssueId } = await seedOpenAndPrivate();
await db.insert(issueComments).values({
id: randomUUID(), companyId, issueId: privateIssueId, body: "secret decision rationale",
});
const services = buildHostServices(db, "plugin-record-id", "paperclip.slack-digest", createEventBusStub());
await expect(services.issues.listComments({ issueId: privateIssueId, companyId })).resolves.toEqual([]);
});
it("returns no attachments from issues.listAttachments for a private issue", async () => {
const { companyId, privateIssueId } = await seedOpenAndPrivate();
const assetId = randomUUID();
await db.insert(assets).values({
id: assetId, companyId, provider: "local_disk", objectKey: "secret", contentType: "image/png", byteSize: 10, sha256: "z",
});
await db.insert(issueAttachments).values({ id: randomUUID(), companyId, issueId: privateIssueId, assetId });
const services = buildHostServices(db, "plugin-record-id", "paperclip.slack-digest", createEventBusStub());
await expect(services.issues.listAttachments({ issueId: privateIssueId, companyId })).resolves.toEqual([]);
});
it("returns null from issues.getAttachmentContent for a private issue's attachment", async () => {
const { companyId, privateIssueId } = await seedOpenAndPrivate();
const assetId = randomUUID();
await db.insert(assets).values({
id: assetId, companyId, provider: "local_disk", objectKey: "secret2", contentType: "text/plain", byteSize: 4, sha256: "y",
});
const attachmentId = randomUUID();
await db.insert(issueAttachments).values({ id: attachmentId, companyId, issueId: privateIssueId, assetId });
const services = buildHostServices(db, "plugin-record-id", "paperclip.slack-digest", createEventBusStub());
await expect(
services.issues.getAttachmentContent({ attachmentId, companyId, maxBytes: 1_000_000 }),
).resolves.toBeNull();
});
it("excludes a private descendant and redacts private blocker edges in getOrchestrationSummary", async () => {
const { companyId } = await seedCompanyAndAgent();
const rootId = randomUUID();
const publicChildId = randomUUID();
const privateChildId = randomUUID();
const privateBlockerId = randomUUID();
await db.insert(issues).values([
{ id: rootId, companyId, title: "Root", status: "todo", priority: "medium", visibility: "open" },
{ id: publicChildId, companyId, parentId: rootId, title: "Public child", status: "todo", priority: "medium", visibility: "open" },
{ id: privateChildId, companyId, parentId: rootId, title: "Private child", status: "todo", priority: "medium", visibility: "private" },
{ id: privateBlockerId, companyId, title: "Private blocker", status: "todo", priority: "medium", visibility: "private" },
]);
// privateBlocker blocks the public root -> root.blockedBy includes it pre-redaction.
await db.insert(issueRelations).values({
companyId, issueId: privateBlockerId, relatedIssueId: rootId, type: "blocks",
});
const services = buildHostServices(db, "plugin-record-id", "paperclip.slack-digest", createEventBusStub());
const summary = await services.issues.getOrchestrationSummary({ companyId, issueId: rootId, includeSubtree: true });
// Private descendant never enters the subtree.
expect(new Set(summary.subtreeIssueIds)).toEqual(new Set([rootId, publicChildId]));
// No relation edge anywhere references the private blocker or private child.
const edgeIds = new Set<string>();
for (const relation of Object.values(summary.relations)) {
for (const edge of [...relation.blockedBy, ...relation.blocks]) edgeIds.add(edge.id);
}
expect(edgeIds.has(privateBlockerId)).toBe(false);
expect(edgeIds.has(privateChildId)).toBe(false);
});
it("reports a private root issue as not-found from getOrchestrationSummary", async () => {
const { companyId, privateIssueId } = await seedOpenAndPrivate();
const services = buildHostServices(db, "plugin-record-id", "paperclip.slack-digest", createEventBusStub());
await expect(
services.issues.getOrchestrationSummary({ companyId, issueId: privateIssueId, includeSubtree: true }),
).rejects.toThrow("Issue not found");
});
async function seedIssueDocument(companyId: string, issueId: string, key: string, body: string) {
const documentId = randomUUID();
await db.insert(documents).values({ id: documentId, companyId, latestBody: body, format: "markdown" });
await db.insert(issueDocuments).values({ id: randomUUID(), companyId, issueId, documentId, key });
return documentId;
}
it("throws not-found from issues.getRelations for a private issue", async () => {
const { companyId, privateIssueId } = await seedOpenAndPrivate();
const services = buildHostServices(db, "plugin-record-id", "paperclip.slack-digest", createEventBusStub());
await expect(
services.issues.getRelations({ issueId: privateIssueId, companyId }),
).rejects.toThrow("Issue not found");
});
it("redacts a private blocker edge from issues.getRelations on a public issue", async () => {
const { companyId, openIssueId, privateIssueId } = await seedOpenAndPrivate();
// privateIssue blocks the open issue -> open.blockedBy would name it pre-redaction.
await db.insert(issueRelations).values({
companyId, issueId: privateIssueId, relatedIssueId: openIssueId, type: "blocks",
});
const services = buildHostServices(db, "plugin-record-id", "paperclip.slack-digest", createEventBusStub());
const relations = await services.issues.getRelations({ issueId: openIssueId, companyId });
const edgeIds = [...relations.blockedBy, ...relations.blocks].map((edge) => edge.id);
expect(edgeIds).not.toContain(privateIssueId);
});
it("reports a private root issue as not-found from issues.getSubtree", async () => {
const { companyId, privateIssueId } = await seedOpenAndPrivate();
const services = buildHostServices(db, "plugin-record-id", "paperclip.slack-digest", createEventBusStub());
await expect(
services.issues.getSubtree({ issueId: privateIssueId, companyId }),
).rejects.toThrow("Issue not found");
});
it("excludes a private child and its documents from issues.getSubtree on an open root", async () => {
const { companyId } = await seedCompanyAndAgent();
const rootId = randomUUID();
const publicChildId = randomUUID();
const privateChildId = randomUUID();
await db.insert(issues).values([
{ id: rootId, companyId, title: "Root", status: "todo", priority: "medium", visibility: "open" },
{ id: publicChildId, companyId, parentId: rootId, title: "Public child", status: "todo", priority: "medium", visibility: "open" },
{ id: privateChildId, companyId, parentId: rootId, title: "Private child", status: "todo", priority: "medium", visibility: "private" },
]);
// A document on the private child would surface in the subtree summary pre-fix.
await seedIssueDocument(companyId, privateChildId, "plan", "confidential subtree plan");
const services = buildHostServices(db, "plugin-record-id", "paperclip.slack-digest", createEventBusStub());
const subtree = await services.issues.getSubtree({
issueId: rootId, companyId, includeDocuments: true, includeRelations: true,
});
expect(new Set(subtree.issueIds)).toEqual(new Set([rootId, publicChildId]));
expect(subtree.issues.map((issue) => issue.id)).not.toContain(privateChildId);
expect(Object.keys(subtree.documents ?? {})).not.toContain(privateChildId);
});
it("returns no interactions from issues.listInteractions for a private issue", async () => {
const { companyId, privateIssueId } = await seedOpenAndPrivate();
await db.insert(issueThreadInteractions).values({
id: randomUUID(), companyId, issueId: privateIssueId, kind: "request_confirmation",
payload: { version: 1, prompt: "Confirm confidential action?" } as any,
});
const services = buildHostServices(db, "plugin-record-id", "paperclip.slack-digest", createEventBusStub());
await expect(services.issues.listInteractions({ issueId: privateIssueId, companyId })).resolves.toEqual([]);
});
it("throws not-found from issueDocuments.list for a private issue", async () => {
const { companyId, privateIssueId } = await seedOpenAndPrivate();
await seedIssueDocument(companyId, privateIssueId, "plan", "confidential plan body");
const services = buildHostServices(db, "plugin-record-id", "paperclip.slack-digest", createEventBusStub());
await expect(
services.issueDocuments.list({ issueId: privateIssueId, companyId }),
).rejects.toThrow("Issue not found");
});
it("throws not-found from issueDocuments.get for a private issue", async () => {
const { companyId, privateIssueId } = await seedOpenAndPrivate();
await seedIssueDocument(companyId, privateIssueId, "plan", "confidential plan body");
const services = buildHostServices(db, "plugin-record-id", "paperclip.slack-digest", createEventBusStub());
await expect(
services.issueDocuments.get({ issueId: privateIssueId, companyId, key: "plan" }),
).rejects.toThrow("Issue not found");
});
it("is pass-through when privacy mode is off (enforce flip is the single switch)", async () => {
process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = "off";
const { companyId, privateIssueId } = await seedOpenAndPrivate();
const services = buildHostServices(db, "plugin-record-id", "paperclip.slack-digest", createEventBusStub());
const ids = (await services.issues.list({ companyId })).map((issue) => issue.id);
expect(ids).toContain(privateIssueId);
await expect(services.issues.get({ issueId: privateIssueId, companyId })).resolves.toMatchObject({ id: privateIssueId });
});
});
});
+206
View File
@@ -0,0 +1,206 @@
import { randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises";
import express from "express";
import request from "supertest";
import { and, eq, sql } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { activityLog, agents, companies, companyMemberships, createDb, userCompanyPreferences } from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { errorHandler } from "../middleware/index.js";
import { primaryAgentRoutes } from "../routes/primary-agent.js";
import { agentService } from "../services/agents.js";
import { primaryAgentService } from "../services/primary-agent.js";
import { resourceMembershipService } from "../services/resource-memberships.js";
import { activityRoutes } from "../routes/activity.js";
const support = await getEmbeddedPostgresTestSupport();
if (!support.supported) console.warn(`Primary agent database tests unavailable: ${support.reason}`);
(support.supported ? describe : describe.skip)("personal primary agent", () => {
let db: ReturnType<typeof createDb>;
let temp: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
beforeAll(async () => {
temp = await startEmbeddedPostgresTestDatabase("paperclip-primary-agent-");
db = createDb(temp.connectionString);
}, 30_000);
afterAll(async () => { await temp?.cleanup(); });
const actor = (companyId: string, userId = "user-a"): Express.Request["actor"] => ({
type: "board", source: "session", userId, companyIds: [companyId],
memberships: [{ companyId, membershipRole: "admin", status: "active" }],
});
const app = (identity: Express.Request["actor"]) => {
const result = express(); result.use(express.json());
result.use((req, _res, next) => { req.actor = identity; next(); });
result.use("/api", primaryAgentRoutes(db));
result.use("/api", activityRoutes(db)); result.use(errorHandler);
return result;
};
async function company() {
const id = randomUUID();
await db.insert(companies).values({ id, name: "Primary test", issuePrefix: `P${id.slice(0, 7)}` });
await db.insert(companyMemberships).values(["user-a", "user-b", "explicit"].map(principalId => ({ companyId: id, principalType: "user", principalId, status: "active", membershipRole: "admin" })));
return id;
}
const create = (companyId: string, name: string, userId?: string) => agentService(db).create(companyId, {
name, adapterType: "process", status: "idle",
}, { createdByUserId: userId });
const get = (companyId: string, userId = "user-a") => primaryAgentService(db).get(companyId, userId);
const url = (companyId: string) => `/api/companies/${companyId}/primary-agent/me`;
it("automatically crowns the first human creation, ignoring provisioned and agent-authored creations", async () => {
const c = await company();
await create(c, "System"); await create(c, "Agent hire");
expect(await get(c)).toMatchObject({ primaryAgentId: null, initialized: false });
const first = await create(c, "Maia", "user-a");
await create(c, "Alex", "user-a");
expect(await get(c)).toMatchObject({ primaryAgentId: first.id, initialized: true });
});
it("arbitrates simultaneous human creations and cannot overwrite an explicit choice", async () => {
const c = await company();
const created = await Promise.all([create(c, "Maia", "user-a"), create(c, "Alex", "user-a")]);
const preference = await get(c);
expect(created.map(a => a.id)).toContain(preference.primaryAgentId);
expect(await db.select().from(userCompanyPreferences).where(and(eq(userCompanyPreferences.companyId, c), eq(userCompanyPreferences.userId, "user-a")))).toHaveLength(1);
const selected = created.find(a => a.id !== preference.primaryAgentId)!;
await request(app(actor(c))).put(url(c)).send({ primaryAgentId: selected.id }).expect(200);
await create(c, "Later", "user-a");
expect((await get(c)).primaryAgentId).toBe(selected.id);
});
it("isolates company/user preferences, including trusted local board, and rejects untrusted identity fields", async () => {
const c = await company(), other = await company();
const a = await create(c, "Maia", "user-a"), b = await create(c, "Alex", "user-b");
const elsewhere = await create(other, "Elsewhere", "user-a");
expect((await request(app(actor(c))).get(url(c)).expect(200)).body.primaryAgentId).toBe(a.id);
expect((await request(app(actor(c, "user-b"))).get(url(c)).expect(200)).body.primaryAgentId).toBe(b.id);
await request(app(actor(c))).put(url(c)).send({ primaryAgentId: elsewhere.id }).expect(404);
await request(app(actor(c))).get(url(other)).expect(403);
await request(app(actor(c))).put(url(c)).send({ primaryAgentId: b.id, userId: "user-b" }).expect(400);
await request(app({ type: "agent", source: "agent_key", agentId: a.id, companyId: c })).put(url(c)).send({ primaryAgentId: b.id }).expect(403);
const local: Express.Request["actor"] = { type: "board", source: "local_implicit", userId: "local-board", isInstanceAdmin: true };
await request(app(local)).put(url(c)).send({ primaryAgentId: b.id }).expect(200);
expect((await get(c, "local-board")).primaryAgentId).toBe(b.id);
expect((await get(other, "local-board")).primaryAgentId).toBeNull();
expect((await get(c)).primaryAgentId).toBe(a.id);
});
it("serializes competing explicit choices and leave races", async () => {
const c = await company();
await create(c, "Maia", "user-a");
const a = await create(c, "Alex"), b = await create(c, "River");
const service = primaryAgentService(db);
await Promise.all([service.set(c, "user-a", a.id, actor(c)), service.set(c, "user-a", b.id, actor(c))]);
const current = (await get(c)).primaryAgentId;
const updates = await db.select().from(activityLog).where(and(eq(activityLog.companyId, c), eq(activityLog.action, "primary_agent.updated")));
expect(updates).toHaveLength(2);
expect([a.id, b.id]).toContain(current);
await Promise.all([
service.set(c, "user-a", a.id, actor(c)),
resourceMembershipService(db).updateAgent({ companyId: c, userId: "user-a", agentId: a.id, state: "left", actor: actor(c) }),
]);
const memberships = await resourceMembershipService(db).listForUser(c, "user-a", actor(c));
expect((await get(c)).primaryAgentId).toBe(memberships.agentMemberships[a.id] === "left" ? null : a.id);
});
it("audits preference changes without exposing the selection through company activity", async () => {
const c = await company();
const first = await create(c, "Maia", "user-a"), next = await create(c, "Alex");
await primaryAgentService(db).set(c, "user-a", next.id, actor(c));
await resourceMembershipService(db).updateAgent({ companyId: c, userId: "user-a", agentId: next.id, state: "left", actor: actor(c) });
const response = await request(app(actor(c, "user-b"))).get(`/api/companies/${c}/activity`).expect(200);
const events = response.body.filter((event: { action: string }) => event.action.startsWith("primary_agent."));
expect(events.map((event: { action: string }) => event.action).sort()).toEqual([
"primary_agent.cleared", "primary_agent.initialized", "primary_agent.updated",
]);
for (const event of events) {
expect(event).toMatchObject({ entityType: "user_preference", entityId: "user-a", agentId: null, details: null });
expect(JSON.stringify(event)).not.toContain(first.id);
expect(JSON.stringify(event)).not.toContain(next.id);
}
});
it("retains paused/error primaries, clears on leave, rejoins when chosen, and preserves stars", async () => {
const c = await company(); const a = await create(c, "Maia", "user-a");
await agentService(db).pause(a.id);
expect((await get(c)).primaryAgentId).toBe(a.id);
await agentService(db).update(a.id, { status: "error" });
expect((await get(c)).primaryAgentId).toBe(a.id);
const memberships = resourceMembershipService(db);
await memberships.updateAgent({ companyId: c, userId: "user-a", agentId: a.id, state: "left", actor: actor(c) });
expect(await get(c)).toMatchObject({ primaryAgentId: null, initialized: true });
await create(c, "Later", "user-a");
expect((await get(c)).primaryAgentId).toBeNull();
await request(app(actor(c))).put(url(c)).send({ primaryAgentId: a.id }).expect(200);
expect((await memberships.listForUser(c, "user-a", actor(c))).agentMemberships[a.id]).toBe("joined");
await memberships.updateAgent({ companyId: c, userId: "user-a", agentId: a.id, starred: true, actor: actor(c) });
const b = await create(c, "Alex");
await request(app(actor(c))).put(url(c)).send({ primaryAgentId: b.id }).expect(200);
expect((await memberships.listForUser(c, "user-a", actor(c))).starredAgentIds).toContain(a.id);
});
it("allows viewers to choose their own primary without granting company write permissions", async () => {
const c = await company(); const a = await create(c, "Maia");
await db.update(companyMemberships).set({ membershipRole: "viewer" }).where(and(eq(companyMemberships.companyId, c), eq(companyMemberships.principalId, "user-a")));
const viewer = { ...actor(c), memberships: [{ companyId: c, membershipRole: "viewer" as const, status: "active" as const }] };
await request(app(viewer)).put(url(c)).send({ primaryAgentId: a.id }).expect(200);
expect((await get(c)).primaryAgentId).toBe(a.id);
const [membership] = await db.select().from(companyMemberships).where(and(eq(companyMemberships.companyId, c), eq(companyMemberships.principalId, "user-a")));
expect(membership.membershipRole).toBe("viewer");
await request(app({ ...viewer, memberships: [] })).get(url(c)).expect(403);
});
it("clears terminated/deleted primaries and rejects terminated targets and explicit removal", async () => {
const c = await company(); const a = await create(c, "Maia", "user-a");
await agentService(db).terminate(a.id);
expect(await get(c)).toMatchObject({ primaryAgentId: null, initialized: true });
await request(app(actor(c))).put(url(c)).send({ primaryAgentId: a.id }).expect(422);
await request(app(actor(c))).put(url(c)).send({ primaryAgentId: null }).expect(400);
const b = await create(c, "Alex", "user-a");
expect((await get(c)).primaryAgentId).toBeNull();
await request(app(actor(c))).put(url(c)).send({ primaryAgentId: b.id }).expect(200);
await agentService(db).remove(b.id);
expect(await get(c)).toMatchObject({ primaryAgentId: null, initialized: true });
});
it("rolls creation and initialization back together", async () => {
const c = await company();
await expect(db.transaction(async tx => {
await agentService(tx as unknown as typeof db).create(c, { name: "Rolled back", adapterType: "process" }, { createdByUserId: "user-a" });
throw new Error("rollback");
})).rejects.toThrow("rollback");
expect(await get(c)).toMatchObject({ primaryAgentId: null, initialized: false });
expect(await db.select().from(agents).where(eq(agents.companyId, c))).toHaveLength(0);
});
it("backfills the earliest human event, leaves gone/terminated originals empty, and preserves explicit preferences", async () => {
const c = await company(); const first = await create(c, "First"), later = await create(c, "Later");
const terminated = await create(c, "Terminated");
await agentService(db).terminate(terminated.id);
const events = [
["human", first.id, "user", 1], ["human", later.id, "user", 2],
["gone", randomUUID(), "user", 1], ["gone", later.id, "user", 2],
["retired", terminated.id, "user", 1], ["retired", later.id, "user", 2],
["system", later.id, "system", 0], [first.id, later.id, "agent", 0],
["board", later.id, "user", 0], ["explicit", first.id, "user", 0],
] as const;
for (const [actorId, entityId, actorType, day] of events) await db.insert(activityLog).values({
companyId: c, actorId, actorType, entityId, entityType: "agent", action: "agent.created", createdAt: new Date(2020, 0, day + 1),
});
await request(app(actor(c, "explicit"))).put(url(c)).send({ primaryAgentId: later.id }).expect(200);
const migration = await readFile(new URL("../../../packages/db/src/migrations/0315_rapid_emma_frost.sql", import.meta.url), "utf8");
// Replay the whole migration twice: an already migrated preview instance
// must retain its explicit preferences when upgrading to the merged build.
for (let replay = 0; replay < 2; replay++) {
for (const statement of migration.split("--> statement-breakpoint")) {
if (statement.trim()) await db.execute(sql.raw(statement));
}
}
expect((await get(c, "human")).primaryAgentId).toBe(first.id);
expect(await get(c, "gone")).toMatchObject({ primaryAgentId: null, initialized: true });
expect(await get(c, "retired")).toMatchObject({ primaryAgentId: null, initialized: true });
expect((await get(c, "explicit")).primaryAgentId).toBe(later.id);
for (const user of ["system", "board", first.id]) expect((await get(c, user)).initialized).toBe(false);
});
});
@@ -0,0 +1,487 @@
import { randomUUID } from "node:crypto";
import { createServer } from "node:http";
import { Readable } from "node:stream";
import { once } from "node:events";
import express from "express";
import request from "supertest";
import WebSocket from "ws";
import { and, eq } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { workspaceOperations, agents, approvals, assets, chatEndpoints, chatExternalPrincipals, chatConversations, chatIdentityLinks, chatDeliveries, toolApplications, toolConnections, executionWorkspaces, authUsers, companies, companyMemberships, createDb, heartbeatRuns, issueAccessGrants, issues, projectAccessMembers, projects, startEmbeddedPostgresTestDatabase } from "@paperclipai/db";
import { authorizationService, canPublishIssueToChatAudience, canActorReadIssuePrivacy, issueReadSqlCondition, canActorReadProjectPrivacy, projectReadSqlCondition, canActorReadApproval, approvalReadSqlCondition, canActorReadExecutionWorkspace, type AuthorizationActor } from "../services/authorization.js";
import { canActorReadWorkspaceOperation } from "../services/heartbeat-run-privacy.js";
// Production regressions and the approved downward-only sharing contract.
describe("private task production review", () => {
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
beforeAll(async () => {
process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = "enforce";
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-private-review-");
db = createDb(tempDb.connectionString);
// Load the current route dependency graph during setup, outside assertion timeouts.
await Promise.all([import("../routes/issues.js"), import("../routes/projects.js")]);
}, 120_000);
afterAll(async () => { await tempDb?.cleanup(); });
async function fixture() {
const [company] = await db.insert(companies).values({ name: randomUUID(), issuePrefix: `T${randomUUID().slice(0, 5)}` }).returning();
const owner = randomUUID(), outsider = randomUUID();
await db.insert(authUsers).values([owner, outsider].map(id => ({ id, name: id, email: `${id}@example.test`, createdAt: new Date(), updatedAt: new Date() })));
await db.insert(companyMemberships).values([owner, outsider].map(principalId => ({ companyId: company.id, principalType: "user", principalId, status: "active", membershipRole: "operator" })));
const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Shared agent", role: "engineer", adapterType: "process", adapterConfig: {}, runtimeConfig: {}, permissions: {} }).returning();
const actor = (userId: string): AuthorizationActor => ({ type: "board", userId, source: "session", companyIds: [company.id] });
return { company, owner, outsider, agent, actor };
}
it("lets only the project privacy owner or an admin change its audience", async () => {
const f = await fixture();
const { projectRoutes } = await import("../routes/projects.js");
const { errorHandler } = await import("../middleware/index.js");
let actor = f.actor(f.owner);
const app = express();
app.use(express.json());
app.use((req, _res, next) => { req.actor = actor; next(); });
app.use("/api", projectRoutes(db));
app.use(errorHandler);
const created = await request(app).post(`/api/companies/${f.company.id}/projects`).send({ name: "Private project", visibility: "private", privacyOwnerUserId: f.outsider });
expect(created.status).toBe(201);
expect(created.body.privacyOwnerUserId).toBe(f.owner);
const projectId = created.body.id;
const member = await request(app).post(`/api/projects/${projectId}/access-members`).send({ subjectType: "user", subjectId: f.outsider });
expect(member.status).toBe(201);
actor = f.actor(f.outsider);
expect((await request(app).get(`/api/projects/${projectId}`)).status).toBe(200);
expect((await request(app).patch(`/api/projects/${projectId}`).send({ visibility: "open" })).status).toBe(403);
expect((await request(app).post(`/api/projects/${projectId}/access-members`).send({ subjectType: "agent", subjectId: f.agent.id })).status).toBe(403);
expect((await request(app).delete(`/api/projects/${projectId}/access-members/${member.body.id}`)).status).toBe(403);
actor = f.actor(f.owner);
expect((await request(app).delete(`/api/projects/${projectId}/access-members/${member.body.id}`)).status).toBe(200);
expect((await request(app).patch(`/api/projects/${projectId}`).send({ visibility: "open" })).status).toBe(200);
await db.update(companyMemberships).set({ membershipRole: "admin" }).where(and(eq(companyMemberships.companyId, f.company.id), eq(companyMemberships.principalId, f.outsider)));
actor = f.actor(f.outsider);
expect((await request(app).patch(`/api/projects/${projectId}`).send({ visibility: "private" })).status).toBe(200);
});
it("publishes private chat content only to a currently authorized linked DM recipient", async () => {
const f = await fixture();
const [task] = await db.insert(issues).values({ companyId: f.company.id, title: "Private chat", visibility: "private", responsibleUserId: f.owner }).returning();
const [application] = await db.insert(toolApplications).values({ companyId: f.company.id, name: "Test chat", type: "native" }).returning();
const [connection] = await db.insert(toolConnections).values({ companyId: f.company.id, applicationId: application.id, name: "Test chat", uid: "test-chat", connectionPurpose: "channel", transport: "chat_sdk" }).returning();
const [endpoint] = await db.insert(chatEndpoints).values({ companyId: f.company.id, connectionId: connection.id, provider: "slack", publicId: randomUUID(), assignedAgentId: f.agent.id }).returning();
const [principal] = await db.insert(chatExternalPrincipals).values({ companyId: f.company.id, provider: "slack", providerAccountId: "test", externalId: "person", kind: "user" }).returning();
const [conversation] = await db.insert(chatConversations).values({ companyId: f.company.id, endpointId: endpoint.id, issueId: task.id, externalConversationId: "dm", externalLabel: "Test DM", isDirectMessage: true }).returning();
const publication = { companyId: f.company.id, issueId: task.id, endpointId: endpoint.id, conversationId: conversation.id };
expect(await canPublishIssueToChatAudience(db, publication)).toBe(false);
await db.insert(chatDeliveries).values({ companyId: f.company.id, endpointId: endpoint.id, conversationId: conversation.id, principalId: principal.id, providerEventId: randomUUID(), deduplicationKey: randomUUID(), eventKind: "message", normalizedEvent: {} as any });
const [link] = await db.insert(chatIdentityLinks).values({ companyId: f.company.id, endpointId: endpoint.id, principalId: principal.id, paperclipUserId: f.outsider, status: "linked" }).returning();
expect(await canPublishIssueToChatAudience(db, publication)).toBe(false);
const [grant] = await db.insert(issueAccessGrants).values({ issueId: task.id, subjectType: "user", subjectId: f.outsider, source: "explicit" }).returning();
expect(await canPublishIssueToChatAudience(db, publication)).toBe(true);
await db.update(chatConversations).set({ isDirectMessage: false }).where(eq(chatConversations.id, conversation.id));
expect(await canPublishIssueToChatAudience(db, publication)).toBe(false);
await db.update(chatConversations).set({ isDirectMessage: true }).where(eq(chatConversations.id, conversation.id));
await db.update(issueAccessGrants).set({ revokedAt: new Date() }).where(eq(issueAccessGrants.id, grant.id));
expect(await canPublishIssueToChatAudience(db, publication)).toBe(false);
await db.update(chatIdentityLinks).set({ paperclipUserId: f.owner }).where(eq(chatIdentityLinks.id, link.id));
expect(await canPublishIssueToChatAudience(db, publication)).toBe(true);
await db.update(chatIdentityLinks).set({ revokedAt: new Date() }).where(eq(chatIdentityLinks.id, link.id));
expect(await canPublishIssueToChatAudience(db, publication)).toBe(false);
});
it("a shared agent cannot read an owner's private task on behalf of an unauthorized coworker", async () => {
const f = await fixture();
const id = randomUUID();
const [issue] = await db.insert(issues).values({ id, companyId: f.company.id, title: "Private email", visibility: "private", privacyRootIssueId: id, responsibleUserId: f.owner, assigneeAgentId: f.agent.id }).returning();
const authz = authorizationService(db);
const resource = { type: "issue" as const, companyId: f.company.id, issueId: id };
expect((await authz.decide({ actor: f.actor(f.outsider), action: "issue:read", resource })).allowed).toBe(false);
expect((await authz.decide({ actor: { type: "agent", agentId: f.agent.id, companyId: f.company.id, source: "agent_jwt", onBehalfOfUserId: f.outsider }, action: "issue:read", resource })).allowed).toBe(false);
});
it("list SQL and direct checks agree after a project becomes open", async () => {
const f = await fixture();
const [project] = await db.insert(projects).values({ companyId: f.company.id, name: "Previously private", visibility: "open" }).returning();
await db.insert(projectAccessMembers).values({ companyId: f.company.id, projectId: project.id, subjectType: "user", subjectId: f.outsider });
const id = randomUUID();
const [issue] = await db.insert(issues).values({ id, companyId: f.company.id, title: "Still individually private", visibility: "private", privacyRootIssueId: id, responsibleUserId: f.owner, projectId: project.id }).returning();
expect(await canActorReadIssuePrivacy(db, f.actor(f.outsider), issue)).toBe(false);
const found = await db.select({ id: issues.id }).from(issues).where(and(eq(issues.id, id), await issueReadSqlCondition(db, f.actor(f.outsider))));
expect(found).toEqual([]);
});
it("making a parent private also protects existing descendants", async () => {
const f = await fixture();
const { issueService } = await import("../services/issues.js");
const svc = issueService(db);
const parent = await svc.create(f.company.id, { title: "Parent", createdByUserId: f.owner });
const child = await svc.create(f.company.id, { title: "Existing child", parentId: parent.id, createdByUserId: f.owner });
await svc.update(parent.id, { visibility: "private" });
const updated = await svc.getById(child.id);
expect(updated?.visibility).toBe("private");
});
it("restricting a project protects descendants outside it and preserves privacy when reopened", async () => {
const f = await fixture();
const { issueService } = await import("../services/issues.js");
const { projectService } = await import("../services/projects.js");
const svc = issueService(db);
const [project] = await db.insert(projects).values({ companyId: f.company.id, name: "Project", visibility: "open" }).returning();
const root = await svc.create(f.company.id, { title: "Root", projectId: project.id, createdByUserId: f.owner });
const child = await svc.create(f.company.id, { title: "Child", parentId: root.id, createdByUserId: f.owner });
const grandchild = await svc.create(f.company.id, { title: "Grandchild", parentId: child.id, createdByUserId: f.owner });
await projectService(db).update(project.id, { visibility: "private" });
expect(await canActorReadIssuePrivacy(db, f.actor(f.outsider), grandchild)).toBe(false);
await projectService(db).update(project.id, { visibility: "open" });
expect(await canActorReadIssuePrivacy(db, f.actor(f.outsider), grandchild)).toBe(false);
expect((await svc.getById(child.id))?.visibility).toBe("private");
});
it("publishing a personal task leaves its private project while keeping its children private", async () => {
const f = await fixture();
const { issueService } = await import("../services/issues.js");
const svc = issueService(db);
const root = await svc.create(f.company.id, { title: "Personal", visibility: "private", createdByUserId: f.owner });
const child = await svc.create(f.company.id, { title: "Child", parentId: root.id, createdByUserId: f.owner });
const published = await svc.update(root.id, { visibility: "open" });
expect(published?.projectId).toBeNull();
expect(await canActorReadIssuePrivacy(db, f.actor(f.outsider), published!)).toBe(true);
expect(await canActorReadIssuePrivacy(db, f.actor(f.outsider), child)).toBe(false);
});
it("reparenting an open issue under a private task inherits privacy", async () => {
const f = await fixture();
const { issueService } = await import("../services/issues.js");
const svc = issueService(db);
const parent = await svc.create(f.company.id, { title: "Parent", createdByUserId: f.owner, visibility: "private" });
const child = await svc.create(f.company.id, { title: "Moved child", createdByUserId: f.owner });
const updated = await svc.update(child.id, { parentId: parent.id });
expect(updated?.visibility).toBe("private");
});
it("allows task management hints in an unreadable personal project without disclosing its identity", async () => {
const f = await fixture();
const [project] = await db.insert(projects).values({ companyId: f.company.id, name: "Protected personal context", visibility: "private", personalOwnerUserId: f.outsider, privacyOwnerUserId: f.outsider }).returning();
const id = randomUUID();
const [task] = await db.insert(issues).values({ id, companyId: f.company.id, title: "Owned task", visibility: "private", privacyRootIssueId: id, responsibleUserId: f.owner, projectId: project.id }).returning();
const { issueRoutes } = await import("../routes/issues.js");
const { projectRoutes } = await import("../routes/projects.js");
const app = express(); app.use(express.json());
app.use((req, _res, next) => { req.actor = f.actor(f.owner) as Express.Request["actor"]; next(); });
app.use("/api", issueRoutes(db, {} as any)); app.use("/api", projectRoutes(db));
app.use((err: any, _req: express.Request, res: express.Response, _next: express.NextFunction) => { res.status(err.status ?? 500).json({ error: err.message }); });
await request(app).get(`/api/projects/${project.id}`).expect(404);
const response = await request(app).get(`/api/issues/${task.id}/privacy-constraints`).expect(200);
expect(response.body).toEqual({ publicBlockedBy: null, leavesPersonalProject: true });
const { issueService } = await import("../services/issues.js");
expect(await issueService(db).update(task.id, { visibility: "open" })).toMatchObject({ visibility: "open", projectId: null });
});
it("reports an inaccessible private parent as a move-first constraint without leaking it", async () => {
const f = await fixture();
const parentId = randomUUID(), childId = randomUUID();
await db.insert(issues).values({ id: parentId, companyId: f.company.id, title: "Hidden parent content", visibility: "private", privacyRootIssueId: parentId, responsibleUserId: f.outsider });
await db.insert(issues).values({ id: childId, companyId: f.company.id, title: "Owned child", visibility: "private", privacyRootIssueId: parentId, privacyParentIssueId: parentId, responsibleUserId: f.owner });
const { issueRoutes } = await import("../routes/issues.js");
const app = express(); app.use(express.json());
app.use((req, _res, next) => { req.actor = f.actor(f.owner) as Express.Request["actor"]; next(); });
app.use("/api", issueRoutes(db, {} as any));
await request(app).get(`/api/issues/${parentId}`).expect(404);
const response = await request(app).get(`/api/issues/${childId}/privacy-constraints`).expect(200);
expect(response.body).toEqual({ publicBlockedBy: "parent", leavesPersonalProject: false });
});
it("does not expose task management hints to a shared reader or unrelated company", async () => {
const f = await fixture(); const id = randomUUID();
await db.insert(issues).values({ id, companyId: f.company.id, title: "Private", visibility: "private", privacyRootIssueId: id, responsibleUserId: f.owner });
const { issueRoutes } = await import("../routes/issues.js");
let actor = f.actor(f.outsider);
const app = express(); app.use(express.json());
app.use((req, _res, next) => { req.actor = actor as Express.Request["actor"]; next(); });
app.use("/api", issueRoutes(db, {} as any));
app.use((err: any, _req: express.Request, res: express.Response, _next: express.NextFunction) => { res.status(err.status ?? 500).json({ error: err.message }); });
await request(app).get(`/api/issues/${id}/privacy-constraints`).expect(404);
await db.insert(issueAccessGrants).values({ issueId: id, subjectType: "user", subjectId: f.outsider, source: "explicit" });
await request(app).get(`/api/issues/${id}/privacy-constraints`).expect(403);
actor = { ...f.actor(f.owner), companyIds: [] };
await db.update(companyMemberships).set({ status: "archived" }).where(and(eq(companyMemberships.companyId, f.company.id), eq(companyMemberships.principalId, f.owner)));
const denied = await request(app).get(`/api/issues/${id}/privacy-constraints`).expect(404);
expect(denied.body.publicBlockedBy).toBeUndefined();
});
it("an unauthorized board user cannot fetch a private issue through PATCH", async () => {
const f = await fixture();
const id = randomUUID();
await db.insert(issues).values({ id, companyId: f.company.id, title: "Confidential acquisition", description: "Private email content", status: "backlog", visibility: "private", privacyRootIssueId: id, responsibleUserId: f.owner, createdByUserId: f.owner });
const { issueRoutes } = await import("../routes/issues.js");
const app = express();
app.use(express.json());
app.use((req, _res, next) => { req.actor = f.actor(f.outsider) as Express.Request["actor"]; next(); });
app.use("/api", issueRoutes(db, {} as any));
app.use((err: any, _req: express.Request, res: express.Response, _next: express.NextFunction) => { res.status(err.status ?? 500).json({ error: err.message }); });
await request(app).get(`/api/issues/${id}`).expect(404);
const response = await request(app).patch(`/api/issues/${id}`).send({ priority: "low" });
expect({ status: response.status, title: response.body.title }).toEqual({ status: 404, title: undefined });
});
it("sharing a child grants its descendants, never its parent or sibling, and revokes immediately", async () => {
const f = await fixture();
const { issueService } = await import("../services/issues.js");
const svc = issueService(db);
const root = await svc.create(f.company.id, { title: "Root", visibility: "private", createdByUserId: f.owner });
const child = await svc.create(f.company.id, { title: "Shared child", parentId: root.id, createdByUserId: f.owner });
const grandchild = await svc.create(f.company.id, { title: "Grandchild", parentId: child.id, createdByUserId: f.owner });
const sibling = await svc.create(f.company.id, { title: "Sibling", parentId: root.id, createdByUserId: f.owner });
const [grant] = await db.insert(issueAccessGrants).values({ issueId: child.id, subjectType: "user", subjectId: f.outsider, source: "explicit" }).returning();
for (const [task, expected] of [[root, false], [child, true], [grandchild, true], [sibling, false]] as const) {
expect(await canActorReadIssuePrivacy(db, f.actor(f.outsider), task)).toBe(expected);
const rows = await db.select({ id: issues.id }).from(issues).where(and(eq(issues.id, task.id), await issueReadSqlCondition(db, f.actor(f.outsider))));
expect(rows.length > 0).toBe(expected);
}
await db.update(issueAccessGrants).set({ revokedAt: new Date() }).where(eq(issueAccessGrants.id, grant.id));
expect(await canActorReadIssuePrivacy(db, f.actor(f.outsider), child)).toBe(false);
expect(await canActorReadIssuePrivacy(db, f.actor(f.outsider), grandchild)).toBe(false);
});
it("binds child-manager grant writes to the child and rejects ancestor or sibling grants", async () => {
const f = await fixture();
const { issueService } = await import("../services/issues.js");
const { issueRoutes } = await import("../routes/issues.js");
const { errorHandler } = await import("../middleware/index.js");
const svc = issueService(db);
const root = await svc.create(f.company.id, { title: "Ancestor", visibility: "private", createdByUserId: f.outsider });
const child = await svc.create(f.company.id, { title: "Managed child", parentId: root.id, createdByUserId: f.owner });
const grandchild = await svc.create(f.company.id, { title: "Descendant", parentId: child.id, createdByUserId: f.outsider });
const sibling = await svc.create(f.company.id, { title: "Sibling", parentId: root.id, createdByUserId: f.outsider });
const [rootGrant] = await db.insert(issueAccessGrants).values({ issueId: root.id, subjectType: "user", subjectId: f.owner, source: "explicit" }).returning();
const [siblingGrant] = await db.insert(issueAccessGrants).values({ issueId: sibling.id, subjectType: "user", subjectId: f.owner, source: "explicit" }).returning();
const app = express(); app.use(express.json());
app.use((req, _res, next) => { req.actor = f.actor(f.owner); next(); });
app.use("/api", issueRoutes(db, {} as any)); app.use(errorHandler);
const audience = await request(app).get(`/api/issues/${child.id}/access-grants`).expect(200);
expect(audience.body).toContainEqual(expect.objectContaining({ id: rootGrant.id, inherited: true }));
for (const grant of [rootGrant, siblingGrant]) {
await request(app).post(`/api/issues/${child.id}/access-grants/${grant.id}/revoke`).send({}).expect(404);
const [unchanged] = await db.select().from(issueAccessGrants).where(eq(issueAccessGrants.id, grant.id));
expect(unchanged.revokedAt).toBeNull();
}
for (const task of [root, sibling]) {
await request(app).post(`/api/issues/${task.id}/access-grants`).send({ subjectType: "agent", subjectId: f.agent.id }).expect(403);
}
const added = await request(app).post(`/api/issues/${child.id}/access-grants`).send({ subjectType: "agent", subjectId: f.agent.id }).expect(201);
expect(added.body.issueId).toBe(child.id);
const agent: AuthorizationActor = { type: "agent", companyId: f.company.id, agentId: f.agent.id };
for (const [task, expected] of [[root, false], [child, true], [grandchild, true], [sibling, false]] as const) {
expect(await canActorReadIssuePrivacy(db, agent, task)).toBe(expected);
}
await request(app).post(`/api/issues/${child.id}/access-grants/${added.body.id}/revoke`).send({}).expect(200);
expect(await canActorReadIssuePrivacy(db, agent, child)).toBe(false);
expect(await canActorReadIssuePrivacy(db, agent, grandchild)).toBe(false);
});
it("retains a child assignment grant after unassignment without granting the root", async () => {
const f = await fixture();
const { issueService } = await import("../services/issues.js");
const svc = issueService(db);
const root = await svc.create(f.company.id, { title: "Root", visibility: "private", createdByUserId: f.owner });
const child = await svc.create(f.company.id, { title: "Assigned child", parentId: root.id, createdByUserId: f.owner, assigneeAgentId: f.agent.id });
await svc.update(child.id, { assigneeAgentId: null });
const actor: AuthorizationActor = { type: "agent", agentId: f.agent.id, companyId: f.company.id };
expect(await canActorReadIssuePrivacy(db, actor, child)).toBe(true);
expect(await canActorReadIssuePrivacy(db, actor, root)).toBe(false);
await db.update(issueAccessGrants).set({ revokedAt: new Date() }).where(eq(issueAccessGrants.issueId, child.id));
expect(await canActorReadIssuePrivacy(db, actor, child)).toBe(false);
});
it("protects standalone tasks created from a private run", async () => {
const f = await fixture();
const { issueService } = await import("../services/issues.js");
const svc = issueService(db);
const source = await svc.create(f.company.id, { title: "Private conversation", visibility: "private", createdByUserId: f.owner });
const [run] = await db.insert(heartbeatRuns).values({ companyId: f.company.id, agentId: f.agent.id, invocationSource: "on_demand", status: "succeeded", nativeIssueId: source.id }).returning();
const handoff = await svc.create(f.company.id, { title: "Standalone handoff", createdByUserId: f.owner, originRunId: run.id });
expect(handoff).toMatchObject({ parentId: null, privacyParentIssueId: source.id, visibility: "private" });
expect(await canActorReadIssuePrivacy(db, f.actor(f.outsider), handoff)).toBe(false);
});
it("intersects agent and responsible-user access to private projects in direct and list reads", async () => {
const f = await fixture();
const [project] = await db.insert(projects).values({ companyId: f.company.id, name: "Private project", visibility: "private" }).returning();
await db.insert(projectAccessMembers).values({ companyId: f.company.id, projectId: project.id, subjectType: "agent", subjectId: f.agent.id });
const actor: AuthorizationActor = { type: "agent", agentId: f.agent.id, companyId: f.company.id, onBehalfOfUserId: f.outsider };
expect(await canActorReadProjectPrivacy(db, actor, project)).toBe(false);
expect(await db.select().from(projects).where(and(eq(projects.id, project.id), await projectReadSqlCondition(db, actor)))).toEqual([]);
await db.insert(projectAccessMembers).values({ companyId: f.company.id, projectId: project.id, subjectType: "user", subjectId: f.outsider });
expect(await canActorReadProjectPrivacy(db, actor, project)).toBe(true);
});
it("binds native runs and keeps missing-task history fail closed", async () => {
const f = await fixture();
const [task] = await db.insert(issues).values({ companyId: f.company.id, title: "Private", visibility: "private", responsibleUserId: f.owner }).returning();
const [run] = await db.insert(heartbeatRuns).values({ companyId: f.company.id, agentId: f.agent.id, invocationSource: "on_demand", status: "succeeded", nativeIssueId: task.id }).returning();
expect(run).toMatchObject({ scopeKind: "issue", issueId: task.id });
await db.update(heartbeatRuns).set({ contextSnapshot: {}, scopeKind: "company" }).where(eq(heartbeatRuns.id, run.id));
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id))).toMatchObject([{ scopeKind: "issue", issueId: task.id }]);
const [orphan] = await db.insert(heartbeatRuns).values({ companyId: f.company.id, agentId: f.agent.id, invocationSource: "on_demand", status: "succeeded", contextSnapshot: { issueId: randomUUID() } }).returning();
expect(orphan).toMatchObject({ scopeKind: "issue", issueId: null });
});
it("filters private and orphaned operation excerpts from a shared workspace listing", async () => {
const f = await fixture();
const [project] = await db.insert(projects).values({ companyId: f.company.id, name: "Shared" }).returning();
const [workspace] = await db.insert(executionWorkspaces).values({ companyId: f.company.id, projectId: project.id, mode: "isolated_workspace", strategyType: "git_worktree", name: "Shared workspace" }).returning();
const [task] = await db.insert(issues).values({ companyId: f.company.id, title: "Private", visibility: "private", responsibleUserId: f.owner }).returning();
await db.insert(workspaceOperations).values({ companyId: f.company.id, executionWorkspaceId: workspace.id, issueId: task.id, phase: "prepare", stdoutExcerpt: "PRIVATE_OPERATION" });
const [publicOperation] = await db.insert(workspaceOperations).values({ companyId: f.company.id, executionWorkspaceId: workspace.id, phase: "prepare", stdoutExcerpt: "PUBLIC_OPERATION" }).returning();
const { executionWorkspaceRoutes } = await import("../routes/execution-workspaces.js");
const { errorHandler } = await import("../middleware/index.js");
let actor = f.actor(f.outsider);
const app = express(); app.use(express.json());
app.use((req, _res, next) => { req.actor = actor; next(); });
app.use("/api", executionWorkspaceRoutes(db)); app.use(errorHandler);
const path = `/api/execution-workspaces/${workspace.id}/workspace-operations`;
const outside = await request(app).get(path);
expect(outside.status).toBe(200);
expect(outside.body.map((row: { id: string }) => row.id)).toEqual([publicOperation.id]);
actor = f.actor(f.owner);
expect((await request(app).get(path)).body).toHaveLength(2);
await db.delete(issues).where(eq(issues.id, task.id));
expect((await request(app).get(path)).body.map((row: { id: string }) => row.id)).toEqual([publicOperation.id]);
});
it("keeps operation history private even with a company run and after task or run deletion", async () => {
const f = await fixture();
const [task] = await db.insert(issues).values({ companyId: f.company.id, title: "Private", visibility: "private", responsibleUserId: f.owner }).returning();
const [run] = await db.insert(heartbeatRuns).values({ companyId: f.company.id, agentId: f.agent.id, invocationSource: "on_demand", status: "succeeded" }).returning();
expect(run.scopeKind).toBe("company");
const [operation] = await db.insert(workspaceOperations).values({ companyId: f.company.id, issueId: task.id, heartbeatRunId: run.id, phase: "prepare", stdoutExcerpt: "PRIVATE_LOG" }).returning();
const access = authorizationService(db);
expect(await canActorReadWorkspaceOperation(db, access, f.actor(f.owner), operation)).toBe(true);
expect(await canActorReadWorkspaceOperation(db, access, f.actor(f.outsider), operation)).toBe(false);
await db.delete(issues).where(eq(issues.id, task.id));
const [orphan] = await db.select().from(workspaceOperations).where(eq(workspaceOperations.id, operation.id));
expect(orphan).toMatchObject({ issueId: null, stdoutExcerpt: "PRIVATE_LOG", metadata: { _issuePrivacySources: { [task.id]: true } } });
expect(await canActorReadWorkspaceOperation(db, access, f.actor(f.owner), orphan)).toBe(false);
await db.delete(heartbeatRuns).where(eq(heartbeatRuns.id, run.id));
const [history] = await db.update(workspaceOperations).set({ metadata: {} }).where(eq(workspaceOperations.id, operation.id)).returning();
expect(history).toMatchObject({ heartbeatRunId: null, metadata: { _runPrivacySources: { [run.id]: true }, _issuePrivacySources: { [task.id]: true } } });
expect(await canActorReadWorkspaceOperation(db, access, f.actor(f.owner), history)).toBe(false);
});
it("delivers authorized live output, then stops delivery after revocation on the same socket", async () => {
const f = await fixture();
const [task] = await db.insert(issues).values({ companyId: f.company.id, title: "Private", visibility: "private", responsibleUserId: f.owner }).returning();
const [run] = await db.insert(heartbeatRuns).values({ companyId: f.company.id, agentId: f.agent.id, invocationSource: "on_demand", status: "succeeded", nativeIssueId: task.id }).returning();
const [grant] = await db.insert(issueAccessGrants).values({ issueId: task.id, subjectType: "user", subjectId: f.outsider, source: "explicit" }).returning();
const { setupLiveEventsWebSocketServer } = await import("../realtime/live-events-ws.js");
const { publishLiveEvent } = await import("../services/live-events.js");
const server = createServer();
const wss = setupLiveEventsWebSocketServer(server, db, { deploymentMode: "authenticated", resolveCloudActor: async () => ({ userId: f.outsider, companyIds: [f.company.id] }) });
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
const socket = new WebSocket(`ws://127.0.0.1:${(server.address() as { port: number }).port}/api/companies/${f.company.id}/events/ws`);
const messages: string[] = [];
socket.on("message", data => messages.push(data.toString()));
try {
await once(socket, "open");
const publish = (chunk: string) => publishLiveEvent({ companyId: f.company.id, type: "heartbeat.run.log", payload: { issueId: task.id, runId: run.id, agentId: f.agent.id, chunk } });
publish("AUTHORIZED_CANARY");
await expect.poll(() => messages.some(message => message.includes("AUTHORIZED_CANARY"))).toBe(true);
publishLiveEvent({ companyId: f.company.id, type: "activity.logged", payload: { action: "authorized_activity", entityType: "issue", entityId: task.id } });
await expect.poll(() => messages.some(message => message.includes("authorized_activity"))).toBe(true);
await db.update(issueAccessGrants).set({ revokedAt: new Date() }).where(eq(issueAccessGrants.id, grant.id));
publish("REVOKED_CANARY");
publishLiveEvent({ companyId: f.company.id, type: "activity.logged", payload: { action: "revoked_activity", entityType: "issue", entityId: task.id } });
publishLiveEvent({ companyId: f.company.id, type: "activity.logged", payload: { action: "queue_drained", entityType: "company", entityId: f.company.id } });
await expect.poll(() => messages.some(message => message.includes("queue_drained"))).toBe(true);
expect(messages.join(" ")).not.toContain("REVOKED_CANARY");
expect(messages.join(" ")).not.toContain("revoked_activity");
} finally {
socket.terminate();
await new Promise<void>(resolve => (wss as any).close(resolve));
await new Promise<void>(resolve => server.close(() => resolve()));
}
});
it("protects linked approval payloads and execution workspace details", async () => {
const f = await fixture();
const [project] = await db.insert(projects).values({ companyId: f.company.id, name: "Public project" }).returning();
const [task] = await db.insert(issues).values({ companyId: f.company.id, projectId: project.id, title: "Private", visibility: "private", responsibleUserId: f.owner }).returning();
const [approval] = await db.insert(approvals).values({ companyId: f.company.id, type: "hire_agent", payload: { sourceIssueId: task.id, instructions: "PRIVATE_PAYLOAD" } }).returning();
const [workspace] = await db.insert(executionWorkspaces).values({ companyId: f.company.id, projectId: project.id, sourceIssueId: task.id, mode: "isolated_workspace", strategyType: "git_worktree", name: "Private workspace" }).returning();
expect(await canActorReadApproval(db, f.actor(f.owner), approval.id)).toBe(true);
expect(await canActorReadApproval(db, f.actor(f.outsider), approval.id)).toBe(false);
expect(await db.select().from(approvals).where(and(eq(approvals.id, approval.id), await approvalReadSqlCondition(db, f.actor(f.outsider))))).toEqual([]);
expect(await canActorReadExecutionWorkspace(db, f.actor(f.owner), workspace.id)).toBe(true);
expect(await canActorReadExecutionWorkspace(db, f.actor(f.outsider), workspace.id)).toBe(false);
await db.update(executionWorkspaces).set({ sourceIssueId: null, metadata: {} }).where(eq(executionWorkspaces.id, workspace.id));
expect(await canActorReadExecutionWorkspace(db, f.actor(f.outsider), workspace.id)).toBe(false);
await db.delete(issues).where(eq(issues.id, task.id));
expect(await canActorReadExecutionWorkspace(db, f.actor(f.outsider), workspace.id)).toBe(false);
});
it("keeps inline draft images owner-only until publication then follows the task grant", async () => {
const f = await fixture();
const [asset] = await db.insert(assets).values({ companyId: f.company.id, provider: "local_disk", objectKey: `${f.company.id}/assets/issues/drafts/image.png`, contentType: "image/png", byteSize: 6, sha256: "test", createdByUserId: f.owner }).returning();
const { assetRoutes } = await import("../routes/assets.js");
const { issueService } = await import("../services/issues.js");
function appFor(userId: string) {
const app = express();
app.use((req, _res, next) => { req.actor = f.actor(userId) as any; next(); });
app.use("/api", assetRoutes(db, { getObject: async () => ({ stream: Readable.from("SECRET"), contentLength: 6 }) } as any));
return app;
}
const url = `/api/assets/${asset.id}/content`;
await request(appFor(f.owner)).get(url).expect(200);
await request(appFor(f.outsider)).get(url).expect(404);
const task = await issueService(db).create(f.company.id, { title: "Private draft", visibility: "private", createdByUserId: f.owner, description: `![image](${url})` });
const [grant] = await db.insert(issueAccessGrants).values({ issueId: task.id, subjectType: "user", subjectId: f.outsider, source: "explicit" }).returning();
await request(appFor(f.outsider)).get(url).expect(200);
await db.update(issueAccessGrants).set({ revokedAt: new Date() }).where(eq(issueAccessGrants.id, grant.id));
await request(appFor(f.outsider)).get(url).expect(404);
await db.delete(issues).where(eq(issues.id, task.id));
await request(appFor(f.outsider)).get(url).expect(404);
});
it("protects attachment assets even after their attachment or task is deleted", async () => {
const f = await fixture();
const [task] = await db.insert(issues).values({ companyId: f.company.id, title: "Private", visibility: "private", responsibleUserId: f.owner }).returning();
const [asset] = await db.insert(assets).values({ companyId: f.company.id, provider: "local_disk", objectKey: `${f.company.id}/issues/${task.id}/file.txt`, contentType: "text/plain", byteSize: 6, sha256: "test" }).returning();
const { assetRoutes } = await import("../routes/assets.js");
const appFor = (userId: string) => {
const app = express();
app.use((req, _res, next) => { req.actor = f.actor(userId) as Express.Request["actor"]; next(); });
app.use("/api", assetRoutes(db, { getObject: async () => ({ stream: Readable.from("SECRET"), contentLength: 6 }) } as any));
return app;
};
await request(appFor(f.owner)).get(`/api/assets/${asset.id}/content`).expect(200, "SECRET");
await request(appFor(f.outsider)).get(`/api/assets/${asset.id}/content`).expect(404);
await db.delete(issues).where(eq(issues.id, task.id));
await request(appFor(f.owner)).get(`/api/assets/${asset.id}/content`).expect(404);
});
it("live WebSocket delivery does not disclose a private run to an unauthorized member", async () => {
const f = await fixture();
const id = randomUUID();
await db.insert(issues).values({ id, companyId: f.company.id, title: "Private email", visibility: "private", privacyRootIssueId: id, responsibleUserId: f.owner });
expect((await authorizationService(db).decide({ actor: f.actor(f.outsider), action: "issue:read", resource: { type: "issue", companyId: f.company.id, issueId: id } })).allowed).toBe(false);
const { setupLiveEventsWebSocketServer } = await import("../realtime/live-events-ws.js");
const { publishLiveEvent } = await import("../services/live-events.js");
const server = createServer();
const wss = setupLiveEventsWebSocketServer(server, db, { deploymentMode: "authenticated", resolveCloudActor: async () => ({ userId: f.outsider, companyIds: [f.company.id] }) });
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
const address = server.address() as { port: number };
const socket = new WebSocket(`ws://127.0.0.1:${address.port}/api/companies/${f.company.id}/events/ws`);
try {
await once(socket, "open");
const message = once(socket, "message");
publishLiveEvent({ companyId: f.company.id, type: "heartbeat.run.log", payload: { issueId: id, runId: randomUUID(), agentId: f.agent.id, chunk: "PRIVATE_EMAIL_CANARY" } });
const result = await Promise.race([message.then(([data]) => data.toString()), new Promise<string>(resolve => setTimeout(() => resolve(""), 150))]);
expect(result).not.toContain("PRIVATE_EMAIL_CANARY");
} finally {
socket.terminate();
await new Promise<void>(resolve => (wss as any).close(resolve));
await new Promise<void>(resolve => server.close(() => resolve()));
}
});
});
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
import express from "express";
import request from "supertest";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import { companies, createDb, projects } from "@paperclipai/db";
import { companies, companyMemberships, createDb, projectAccessMembers, projects } from "@paperclipai/db";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
@@ -51,9 +51,10 @@ describeEmbeddedPostgres("project list archived route defaults", () => {
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-projects-list-archived-");
db = createDb(tempDb.connectionString);
}, 20_000);
}, 120_000);
afterEach(async () => {
await db.delete(companyMemberships);
await db.delete(projects);
await db.delete(companies);
});
@@ -108,3 +109,74 @@ describeEmbeddedPostgres("project list archived route defaults", () => {
expect(res.body.map((project: { id: string }) => project.id)).toEqual([activeProjectId, archivedProjectId]);
});
});
describeEmbeddedPostgres("private project route visibility", { concurrent: false }, () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
const previousPrivacyMode = process.env.PAPERCLIP_ISSUE_PRIVACY_MODE;
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-private-project-routes-");
db = createDb(tempDb.connectionString);
process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = "enforce";
}, 20_000);
afterEach(async () => {
await db.delete(companyMemberships);
await db.delete(projects);
await db.delete(companies);
});
afterAll(async () => {
if (previousPrivacyMode === undefined) delete process.env.PAPERCLIP_ISSUE_PRIVACY_MODE;
else process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = previousPrivacyMode;
await tempDb?.cleanup();
});
it("omits private projects from non-member lists and returns 404 on direct fetch", async () => {
const companyId = randomUUID();
const privateProjectId = randomUUID();
const memberUserId = "project-member";
await db.insert(companies).values({
id: companyId,
name: "Private projects",
issuePrefix: `P${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
});
await db.insert(projects).values([
{ companyId, name: "Open project", visibility: "open" },
{ id: privateProjectId, companyId, name: "Secret project", visibility: "private" },
]);
await db.insert(companyMemberships).values([memberUserId, "project-outsider"].map((principalId) => ({
companyId,
principalType: "user" as const,
principalId,
status: "active",
membershipRole: "admin",
})));
await db.insert(projectAccessMembers).values({
companyId,
projectId: privateProjectId,
subjectType: "user",
subjectId: memberUserId,
});
const actorFor = (userId: string): Express.Request["actor"] => ({
type: "board",
userId,
source: "session",
isInstanceAdmin: false,
companyIds: [companyId],
memberships: [{ companyId, membershipRole: "admin", status: "active" }],
});
const outsiderApp = createApp(db, actorFor("project-outsider"));
const outsiderList = await request(outsiderApp).get(`/api/companies/${companyId}/projects`);
expect(outsiderList.status).toBe(200);
expect(outsiderList.body.map((project: { id: string }) => project.id)).not.toContain(privateProjectId);
await request(outsiderApp).get(`/api/projects/${privateProjectId}`).expect(404);
const memberApp = createApp(db, actorFor(memberUserId));
const memberList = await request(memberApp).get(`/api/companies/${companyId}/projects`);
expect(memberList.body.map((project: { id: string }) => project.id)).toContain(privateProjectId);
await request(memberApp).get(`/api/projects/${privateProjectId}`).expect(200);
});
});
+47 -1
View File
@@ -6,7 +6,7 @@ import { projectRoutes } from "../routes/projects.js";
import { agentRoutes } from "../routes/agents.js";
import { companySkillRoutes } from "../routes/company-skills.js";
import { MAX_ATTACHMENT_BYTES } from "../attachment-types.js";
import { mcpAttachmentUploads, mcpFileTickets, principalPermissionGrants, heartbeatRuns } from "@paperclipai/db";
import { mcpAttachmentUploads, mcpFileTickets, principalPermissionGrants, heartbeatRuns, issueAccessGrants } from "@paperclipai/db";
import { createHmac, createHash, randomBytes, randomUUID } from "node:crypto";
import express, { type Request } from "express";
import request from "supertest";
@@ -660,6 +660,52 @@ describe.skipIf(!support.supported)("public MCP OAuth and tool boundary", () =>
return { ...f, issue: issue!, call, dispatch, transfers, storage, cleanup: () => rm(storageDir, { recursive: true, force: true }) };
}
async function makePrivate(f: Awaited<ReturnType<typeof expandedFixture>>) {
const owner = randomUUID();
await db.insert(authUsers).values({ id: owner, name: "Private owner", email: owner + "@example.com", createdAt: new Date(), updatedAt: new Date() });
await db.insert(companyMemberships).values({ companyId: f.company.id, principalType: "user", principalId: owner, membershipRole: "member", status: "active" });
await db.update(issues).set({ visibility: "private", privacyRootIssueId: f.issue.id, responsibleUserId: owner, createdByUserId: owner }).where(eq(issues.id, f.issue.id));
return owner;
}
it("hides private tasks from assistant search, reads, edits and file-link creation", async () => {
const f = await expandedFixture();
try {
await makePrivate(f);
expect(await f.call("paperclip_search_tasks")).toMatchObject({ tasks: [] });
for (const name of ["paperclip_read_task", "paperclip_list_deliverables", "paperclip_list_document_revisions"]) {
await expect(f.call(name, { taskId: f.issue.id, ...(name === "paperclip_list_document_revisions" ? { key: "plan" } : {}) })).rejects.toMatchObject({ status: 404 });
}
expect(await f.call("paperclip_update_task", { taskId: f.issue.id, requestId: randomUUID(), changes: { title: "Unauthorized edit" } })).toMatchObject({ outcome: "rejected", status: 404 });
await expect(f.call("paperclip_get_upload_url", { taskId: f.issue.id, requestId: randomUUID(), filename: "data.txt", contentType: "text/plain", byteSize: 2, sha256: createHash("sha256").update("hi").digest("hex") })).rejects.toThrow();
expect((await db.select().from(issues).where(eq(issues.id, f.issue.id)))[0]?.title).toBe("Work");
expect(await db.select().from(mcpAttachmentUploads).where(eq(mcpAttachmentUploads.taskId, f.issue.id))).toHaveLength(0);
} finally { await f.cleanup(); }
});
it("revokes existing assistant upload and download links when private task sharing is removed", async () => {
const f = await expandedFixture();
try {
const owner = await makePrivate(f);
const [grant] = await db.insert(issueAccessGrants).values({ issueId: f.issue.id, subjectType: "user", subjectId: f.actor.userId!, source: "explicit", grantedByUserId: owner }).returning();
const bytes = Buffer.from("Private attachment");
const args = { taskId: f.issue.id, filename: "private.txt", contentType: "text/plain", byteSize: bytes.length, sha256: createHash("sha256").update(bytes).digest("hex") };
const app = express(); app.use(f.transfers.router);
const uploadedUrl = new URL((await f.call("paperclip_get_upload_url", { ...args, requestId: randomUUID() })).url as string);
const uploaded = await request(app).put(uploadedUrl.pathname + uploadedUrl.search).set("Content-Type", args.contentType).send(bytes);
expect(uploaded.status).toBe(200);
const download = new URL((await f.call("paperclip_get_download_url", { attachmentId: uploaded.body.attachment.id })).url as string);
const pending = await f.call("paperclip_get_upload_url", { ...args, requestId: randomUUID() });
const pendingUrl = new URL(pending.url as string);
expect((await request(app).get(download.pathname + download.search)).status).toBe(200);
await db.update(issueAccessGrants).set({ revokedAt: new Date() }).where(eq(issueAccessGrants.id, grant!.id));
expect((await request(app).get(download.pathname + download.search)).status).not.toBe(200);
expect((await request(app).put(pendingUrl.pathname + pendingUrl.search).set("Content-Type", args.contentType).send(bytes)).status).toBe(403);
expect((await db.select().from(mcpAttachmentUploads).where(eq(mcpAttachmentUploads.id, pending.uploadId as string)))[0]?.attachmentId).toBeNull();
await expect(f.call("paperclip_get_download_url", { attachmentId: uploaded.body.attachment.id })).rejects.toThrow();
} finally { await f.cleanup(); }
});
it("edits, blocks and completes tasks through real routes and rejects review overrides", async () => {
const f = await expandedFixture();
try {
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from "vitest";
import { forgetMcpHttpSessions, getMcpHttpSession, initializeMcpHttpSession, McpHttpInitializationError, readMcpHttpResponse } from "../services/mcp-http.js";
import { forgetMcpHttpSession, forgetMcpHttpSessions, getMcpHttpSession, initializeMcpHttpSession, McpHttpInitializationError, readMcpHttpResponse } from "../services/mcp-http.js";
const encoder = new TextEncoder();
function stream(chunks: string[], close = true) {
@@ -60,6 +60,25 @@ describe("remote connector Streamable HTTP", () => {
expect((await getMcpHttpSession(input))["Mcp-Session-Id"]).toBe("session-5");
expect(count).toBe(5);
});
it("forgets only the failed session for one identity", async () => {
let count = 0;
const send = vi.fn(async (init: RequestInit) => {
const body = JSON.parse(String(init.body));
if (body.method === "initialize") { count++; return Response.json({ jsonrpc: "2.0", id: body.id, result: { protocolVersion: "2025-06-18", capabilities: {} } }, { headers: { "Mcp-Session-Id": `session-${count}` } }); }
return new Response(null, { status: 202 });
});
const agentA = { send, requestId: "a", scope: "narrow-connection:agent-a", headers: { Authorization: "Bearer shared" } };
const agentB = { ...agentA, scope: "narrow-connection:agent-b" };
expect((await getMcpHttpSession(agentA))["Mcp-Session-Id"]).toBe("session-1");
expect((await getMcpHttpSession(agentB))["Mcp-Session-Id"]).toBe("session-2");
forgetMcpHttpSession({ ...agentA, sessionId: "session-1" });
expect((await getMcpHttpSession(agentB))["Mcp-Session-Id"]).toBe("session-2");
expect((await getMcpHttpSession(agentA))["Mcp-Session-Id"]).toBe("session-3");
// A late failure from the old session must not drop the session that replaced it.
forgetMcpHttpSession({ ...agentA, sessionId: "session-1" });
expect((await getMcpHttpSession(agentA))["Mcp-Session-Id"]).toBe("session-3");
expect(count).toBe(3);
});
it("does not resurrect an in-flight session after disconnect", async () => {
let finish: (() => void) | undefined;
const gate = new Promise<void>((resolve) => { finish = resolve; });
+4 -4
View File
@@ -166,10 +166,10 @@ function registerModuleMocks() {
}
async function createApp(actor: Record<string, unknown>) {
const [{ errorHandler }, { routineRoutes }] = await Promise.all([
vi.importActual<typeof import("../middleware/index.js")>("../middleware/index.js"),
vi.importActual<typeof import("../routes/routines.js")>("../routes/routines.js"),
]);
// Load the route after its mocks are installed. Concurrent importActual
// calls through the middleware barrel can cache unmocked dependencies.
const { errorHandler } = await import("../middleware/error-handler.js");
const { routineRoutes } = await import("../routes/routines.js");
const app = express();
app.use(express.json({ verify: (req, _res, buf) => { (req as any).rawBody = buf; } }));
app.use((req, _res, next) => {
@@ -42,6 +42,49 @@ afterEach(async () => {
});
describe.skipIf(!sentryPackage)("run failure context with the real Sentry SDK", () => {
it("sends only bounded process-loss evidence without leaking it into another capture", async () => {
const Sentry = sentryPackage!;
const events: Array<Record<string, unknown>> = [];
vi.stubEnv("SENTRY_DSN_BACKEND", "https://public@example.invalid/1");
vi.doMock("../peer-version-check.js", () => ({ checkExactPeerVersions: () => ({ ok: true }) }));
vi.doMock("@sentry/node", () => ({
...Sentry,
init: (options: Record<string, unknown>) => Sentry.init({
...options,
transport: () => ({ send: async () => ({}), flush: async () => true }),
beforeSend: (event: Record<string, unknown>) => { events.push(event); return event; },
}),
}));
vi.resetModules();
const { sentryReady, captureRunFailure, captureException } = await import("../sentry.js");
await sentryReady;
const diagnostics = sanitizeRunFailureDiagnostics(collectRunFailureDiagnostics({
errorCode: "process_lost", resultJson: { processLossDiagnostic: {
pidRecorded: true, groupRecorded: false, localCheck: "not_observed_alive", retryEligible: true,
runPredatesObserver: true, observerUptimeMs: 30_000, lastOutputAgeMs: 120_000,
pid: "private-process-identity", path: "/private-process-path", prompt: "private-process-prompt",
} },
} as unknown as typeof heartbeatRuns.$inferSelect, {}));
captureRunFailure({
taskId: "11111111-1111-4111-8111-111111111111", runId: "22222222-2222-4222-8222-222222222222",
errorMessage: "Process lost -- server may have restarted", errorCode: "process_lost",
agentAdapter: "fixture-adapter", runStatus: "failed", exitCode: null, signal: null, diagnostics,
});
captureException(new Error("unrelated process-loss fixture"));
await Sentry.flush(2000);
expect(events).toHaveLength(2);
const failure = events.find(event => (event.tags as Record<string, unknown>)?.error_code === "process_lost");
expect(failure).toMatchObject({ contexts: { run_execution: {
processLossPidRecorded: true, processLossGroupRecorded: false, processLossLocalCheck: "not_observed_alive",
processLossRetryEligible: true, processLossRunPredatesObserver: true,
processLossObserverUptimeMs: 30_000, processLossLastOutputAgeMs: 120_000,
} } });
expect(JSON.stringify(events)).not.toContain("private-process-");
const unrelated = events.find(event => event !== failure);
expect(unrelated).not.toHaveProperty("contexts.run_execution");
expect(unrelated).not.toHaveProperty("contexts.run_failure");
});
it("keeps portfolio diagnostics bounded and isolated from unrelated captures", async () => {
const Sentry = sentryPackage!;
const events: Array<Record<string, unknown>> = [];
@@ -57,6 +57,7 @@ const {
reason: null,
}));
const heartbeatServiceMock = {
reconcileCostAccounting: vi.fn(async () => ({ scanned: 0, accounted: 0 })),
resolveSchedulingSuppression: resolveHeartbeatSchedulingSuppressionMock,
recoverNativeRunsAfterRestart: vi.fn(async () => ({
restartKind: "hard",
@@ -559,11 +560,13 @@ describe("startServer feedback export wiring", () => {
}) as typeof setInterval);
try {
await startServer();
expect(heartbeatServiceMock.reconcileCostAccounting).toHaveBeenCalledTimes(1);
expect(heartbeatServiceMock.sweepStaleIssueLocks).toHaveBeenCalledTimes(1);
expect(intervalCallback).not.toBeNull();
intervalCallback?.();
await new Promise<void>((resolve) => setImmediate(resolve));
expect(heartbeatServiceMock.sweepStaleIssueLocks).toHaveBeenCalledTimes(2);
expect(heartbeatServiceMock.reconcileCostAccounting).toHaveBeenCalledTimes(2);
expect(retiredDetector).not.toHaveBeenCalled();
} finally {
delete (runtime as Partial<typeof runtime>).reconcileProductivityReviews;
@@ -660,6 +663,7 @@ describe("startServer feedback export wiring", () => {
// reaped at startup and on the interval.
expect(heartbeatServiceFactoryMock).toHaveBeenCalledTimes(1);
expect(heartbeatServiceMock.sweepPendingCleanupLeases).toHaveBeenCalled();
expect(heartbeatServiceMock.reconcileCostAccounting).toHaveBeenCalledTimes(1);
expect(intervalCallback).not.toBeNull();
intervalCallback?.();
await Promise.resolve();
@@ -667,12 +671,33 @@ describe("startServer feedback export wiring", () => {
expect(externalObjectsServiceMock.refreshDueObjectsForActiveCompanies).toHaveBeenCalledTimes(1);
expect(routineServiceMock.tickScheduledTriggers).not.toHaveBeenCalled();
expect(heartbeatServiceMock.reconcileCostAccounting).toHaveBeenCalledTimes(2);
expect(environmentCustomImagesServiceMock.cleanupExpiredSetupSessions).not.toHaveBeenCalled();
} finally {
setIntervalSpy.mockRestore();
}
});
it.each([false, true])("retries failed accounting recovery with heartbeat scheduling enabled: %s", async (enabled) => {
loadConfigMock.mockReturnValue(buildTestConfig({ heartbeatSchedulerEnabled: enabled }));
heartbeatServiceMock.reconcileCostAccounting.mockRejectedValueOnce(new Error("temporary ledger outage"));
let tick: (() => void) | undefined;
const timer = vi.spyOn(globalThis, "setInterval").mockImplementation(((callback: () => void) => {
tick = callback;
return 1 as unknown as ReturnType<typeof setInterval>;
}) as typeof setInterval);
try {
expect((await startServer()).server).toBe(fakeServer);
expect(heartbeatServiceMock.reconcileCostAccounting).toHaveBeenCalledTimes(1);
expect(tick).toBeDefined();
tick?.();
await new Promise<void>((resolve) => setImmediate(resolve));
expect(heartbeatServiceMock.reconcileCostAccounting).toHaveBeenCalledTimes(2);
} finally {
timer.mockRestore();
}
});
it("does not replay hot-restart adoption when the orphan reaper retries", async () => {
loadConfigMock.mockReturnValue(buildTestConfig({
heartbeatSchedulerEnabled: true,
+59
View File
@@ -7,6 +7,7 @@ import {
activityLog,
agents,
companies,
companyMemberships,
costEvents,
createDb,
documentRevisions,
@@ -52,6 +53,7 @@ function unprivilegedBoardActor(companyId: string): Express.Request["actor"] {
source: "session",
sessionId: "session-1",
companyIds: [companyId],
memberships: [{ companyId, membershipRole: "operator", status: "active" }],
isInstanceAdmin: false,
};
}
@@ -93,6 +95,7 @@ describeEmbeddedPostgres("status card routes", () => {
await db.delete(heartbeatRuns);
await db.delete(instanceSettings);
await db.delete(agents);
await db.delete(companyMemberships);
await db.delete(companies);
});
@@ -322,6 +325,62 @@ describeEmbeddedPostgres("status card routes", () => {
expect(list.body[0]).not.toHaveProperty("watchedIssueCount");
});
it("redacts hydrated summaries and watched issues when a card includes a private task", async () => {
const company = await seedCompany();
await enableStatusCards();
const privateIssueId = randomUUID();
await db.insert(issues).values({
id: privateIssueId,
companyId: company.id,
title: "Confidential acquisition",
status: "blocked",
priority: "high",
visibility: "private",
privacyRootIssueId: privateIssueId,
responsibleUserId: "private-owner",
});
const document = await db.insert(documents).values({
companyId: company.id,
title: "Private status summary",
format: "markdown",
latestBody: "Confidential acquisition is blocked.",
latestRevisionNumber: 1,
}).returning().then((rows) => rows[0]!);
const card = await db.insert(statusCards).values({
companyId: company.id,
createdByUserId: "private-owner",
interestPrompt: "Acquisition status",
documentId: document.id,
queries: [{ scope: "issues", status: ["blocked"], updatedWithin: "7d", sort: "updated", limit: 20, offset: 0 }],
queryVersion: 1,
refreshPolicy: { mode: "manual" },
state: "active",
fingerprint: {},
}).returning().then((rows) => rows[0]!);
await db.insert(companyMemberships).values({
companyId: company.id,
principalType: "user",
principalId: "unprivileged-user",
membershipRole: "operator",
status: "active",
});
const app = createApp(db, unprivilegedBoardActor(company.id));
const detail = await request(app).get(`/api/status-cards/${card.id}`);
expect(detail.status).toBe(200);
expect(detail.body).toMatchObject({
watchedIssueCount: 0,
summaryBody: null,
privacyRedacted: true,
});
expect(JSON.stringify(detail.body)).not.toContain("Confidential acquisition");
const dryRun = await request(app).get(`/api/status-cards/${card.id}/dry-run`);
expect(dryRun.status).toBe(200);
expect(JSON.stringify(dryRun.body)).not.toContain("Confidential acquisition");
expect(JSON.stringify(dryRun.body)).not.toContain(privateIssueId);
});
it("refreshes a card whose watched issues carry human comments", async () => {
// Regression: the postgres-js driver returns `max(updated_at)` as a string,
// so `latestHumanCommentAt.toISOString()` threw and refresh 500'd whenever a
@@ -265,6 +265,7 @@ describeEmbeddedPostgres("gateway connector invocation telemetry", () => {
}, 30_000);
afterEach(async () => {
vi.useRealTimers();
track.mockClear();
failLogActivityForAction.current = null;
await db.delete(activityLog);
@@ -379,6 +380,9 @@ describeEmbeddedPostgres("gateway connector invocation telemetry", () => {
}, 30_000);
it("emits one denied event for a policy block and one rate_limited event past the limit", async () => {
// Both calls must land in the same policy window, even across a minute boundary.
vi.useFakeTimers({ toFake: ["Date"] });
vi.setSystemTime(new Date("2026-10-06T12:00:30Z"));
const f = await fixture();
await db.insert(toolPolicies).values({
companyId: f.company.id,
+188
View File
@@ -4413,6 +4413,194 @@ rl.on("line", (line) => {
});
}
function initializeFakeMcpSession(request: FakeMcpRequest, sessionId: string) {
return {
headers: { "mcp-session-id": sessionId },
body: {
jsonrpc: "2.0",
id: request.body?.id,
result: { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "fake", version: "1" } },
},
};
}
const perCallResponseFailures = [
{
name: "an oversized response",
reasonCode: "mcp_remote_response_too_large",
response: () => ({ headers: { "content-type": "application/json" }, rawBody: "x".repeat(1_200_000) }),
check: (error: ToolGatewayHttpError) => {
expect(error.message).toContain("smaller page size");
expect(error.details).toMatchObject({ maxBytes: 1_000_000 });
},
},
{
name: "an invalid JSON response",
reasonCode: "mcp_remote_invalid_json",
response: () => ({ headers: { "content-type": "application/json" }, rawBody: "not json" }),
},
{
name: "a response without the requested message ID",
reasonCode: "remote_mcp_malformed_response",
response: () => ({ body: { jsonrpc: "2.0", id: "someone-else", result: { content: [{ type: "text", text: "wrong id" }] } } }),
},
];
for (const scenario of perCallResponseFailures) {
it(`keeps a remote MCP connection healthy and starts a fresh MCP session after ${scenario.name}`, async () => {
const company = await createCompany(db);
const agent = await createAgent(db, company.id);
const { run } = await createIssueAndRun(db, company.id, agent.id);
let initializeCount = 0;
let toolCallCount = 0;
const fake = await startFakeRemoteMcpServer((request) => {
if (request.body?.method === "initialize") {
initializeCount += 1;
return initializeFakeMcpSession(request, `session-${initializeCount}`);
}
if (request.body?.method === "notifications/initialized") return { status: 202, rawBody: "" };
toolCallCount += 1;
if (toolCallCount === 1) return scenario.response();
return { body: { jsonrpc: "2.0", id: request.body?.id, result: { content: [{ type: "text", text: "small page" }] } } };
});
try {
const { connection } = await createRemoteMcpTool(db, company.id, {
applicationKey: `per-call-${scenario.reasonCode}`,
toolName: "kv_get",
url: fake.url,
connectionConfig: { mcpSessionRequired: true },
});
await allowAllToolsForAgent(db, company.id, agent.id);
const gateway = createTestToolGatewayService(db);
const session = await gateway.createSession({ companyId: company.id, agentId: agent.id, runId: run.id });
const connectedTool = (await gateway.listToolsForSession(session.token))
.find((tool) => tool.providerType === "mcp_remote_http");
expect(connectedTool).toBeTruthy();
await gateway.executeTool({
sessionToken: session.token,
tool: connectedTool!.name,
parameters: { key: "everything" },
}).then(
() => {
throw new Error("Expected the remote MCP call to fail");
},
(error) => {
expectGatewayError(error, 502, scenario.reasonCode);
scenario.check?.(error as ToolGatewayHttpError);
},
);
await expect(db.select({ healthStatus: toolConnections.healthStatus }).from(toolConnections).where(
eq(toolConnections.id, connection.id),
)).resolves.toEqual([{ healthStatus: "ok" }]);
const nextSession = await gateway.createSession({ companyId: company.id, agentId: agent.id, runId: run.id });
await expect(gateway.listToolsForSession(nextSession.token)).resolves.toEqual(
expect.arrayContaining([expect.objectContaining({ name: connectedTool!.name })]),
);
await expect(gateway.executeTool({
sessionToken: nextSession.token,
tool: connectedTool!.name,
parameters: { key: "page-1" },
})).resolves.toMatchObject({ status: "completed" });
const toolCallSessionIds = fake.requests
.filter((request) => request.body?.method === "tools/call")
.map((request) => request.headers["mcp-session-id"]);
expect(toolCallSessionIds).toEqual(["session-1", "session-2"]);
} finally {
await fake.close();
}
});
}
it("resets only the failing agent's MCP session when another agent is initializing on the same connection", async () => {
const company = await createCompany(db);
const agentA = await createAgent(db, company.id);
const agentB = await createAgent(db, company.id);
const { run: runA } = await createIssueAndRun(db, company.id, agentA.id);
const { run: runB } = await createIssueAndRun(db, company.id, agentB.id);
let initializeCount = 0;
let markOversizedCallStarted!: () => void;
const oversizedCallStarted = new Promise<void>((resolve) => { markOversizedCallStarted = resolve; });
let markSecondInitializeStarted!: () => void;
const secondInitializeStarted = new Promise<void>((resolve) => { markSecondInitializeStarted = resolve; });
let releaseSecondInitialize!: () => void;
const secondInitializeReleased = new Promise<void>((resolve) => { releaseSecondInitialize = resolve; });
const fake = await startFakeRemoteMcpServer(async (request) => {
if (request.body?.method === "initialize") {
initializeCount += 1;
const sessionId = `session-${initializeCount}`;
if (initializeCount === 2) {
markSecondInitializeStarted();
await secondInitializeReleased;
}
return initializeFakeMcpSession(request, sessionId);
}
if (request.body?.method === "notifications/initialized") return { status: 202, rawBody: "" };
if (request.headers["mcp-session-id"] === "session-1") {
markOversizedCallStarted();
// Fail agent A's call only while agent B's initialization is in flight.
await secondInitializeStarted;
return { headers: { "content-type": "application/json" }, rawBody: "x".repeat(1_200_000) };
}
return { body: { jsonrpc: "2.0", id: request.body?.id, result: { content: [{ type: "text", text: "ok" }] } } };
});
let callA: Promise<unknown> | undefined;
let callB: Promise<unknown> | undefined;
try {
const { connection } = await createRemoteMcpTool(db, company.id, {
applicationKey: "overlapping-sessions",
toolName: "kv_get",
url: fake.url,
connectionConfig: { mcpSessionRequired: true },
});
await allowAllToolsForAgent(db, company.id, agentA.id);
await allowAllToolsForAgent(db, company.id, agentB.id);
const gateway = createTestToolGatewayService(db);
const sessionA = await gateway.createSession({ companyId: company.id, agentId: agentA.id, runId: runA.id });
const sessionB = await gateway.createSession({ companyId: company.id, agentId: agentB.id, runId: runB.id });
const connectedTool = (await gateway.listToolsForSession(sessionA.token))
.find((tool) => tool.providerType === "mcp_remote_http");
expect(connectedTool).toBeTruthy();
callA = gateway.executeTool({
sessionToken: sessionA.token,
tool: connectedTool!.name,
parameters: { key: "everything" },
}).then(
() => {
throw new Error("Expected agent A's oversized remote MCP response to fail");
},
(error) => expectGatewayError(error, 502, "mcp_remote_response_too_large"),
);
await oversizedCallStarted;
callB = gateway.executeTool({
sessionToken: sessionB.token,
tool: connectedTool!.name,
parameters: { key: "page-1" },
});
await callA;
releaseSecondInitialize();
await expect(callB).resolves.toMatchObject({ status: "completed" });
await expect(db.select({ healthStatus: toolConnections.healthStatus }).from(toolConnections).where(
eq(toolConnections.id, connection.id),
)).resolves.toEqual([{ healthStatus: "ok" }]);
const toolCallSessionIds = fake.requests
.filter((request) => request.body?.method === "tools/call")
.map((request) => request.headers["mcp-session-id"]);
expect(toolCallSessionIds).toEqual(["session-1", "session-2"]);
} finally {
// Open both gates and settle both calls so a failed assertion can't leave a fake-server request hanging.
markSecondInitializeStarted();
releaseSecondInitialize();
await Promise.allSettled([callA, callB]);
await fake.close();
}
});
it("persists hashed sessions and accepts them across gateway service instances", async () => {
const company = await createCompany(db);
const agent = await createAgent(db, company.id);
@@ -0,0 +1,235 @@
import { randomUUID } from "node:crypto";
import express from "express";
import request from "supertest";
import { and, eq, inArray } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import {
activityLog, agents, agentWakeupRequests, companies, createDb,
environmentLeases, heartbeatRuns, issueRecoveryActions, issues,
} from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { errorHandler } from "../middleware/index.js";
import { issueRoutes } from "../routes/issues.js";
import { getExecutionBlocker } from "../services/execution-blocker.js";
import { remoteTerminationReceipt } from "../services/remote-execution-termination.js";
import { LEGACY_WORKSPACE_RECOVERY_SCHEMA } from "../services/workspace-restore-recovery-state.js";
const external = process.env.PAPERCLIP_TEST_DATABASE_URL?.trim();
const support = external ? { supported: true } : await getEmbeddedPostgresTestSupport();
(support.supported ? describe : describe.skip)("retained workspace repair route", () => {
let db: ReturnType<typeof createDb>;
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
beforeAll(async () => {
if (external) db = createDb(external);
else {
temporary = await startEmbeddedPostgresTestDatabase("workspace-restore-repair-route-");
db = createDb(temporary.connectionString);
}
}, 30_000);
afterAll(async () => { await db?.$client.end(); await temporary?.cleanup(); });
async function seed(options: { newerAction?: boolean; conversationReset?: boolean; noCurrentOwner?: boolean } = {}) {
const companyId = randomUUID(), originalAgentId = randomUUID(), currentAgentId = randomUUID();
const issueId = randomUUID(), sourceRunId = randomUUID(), currentRunId = randomUUID(), leaseId = randomUUID();
const actionId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Workspace repair API", issuePrefix: `W${companyId.slice(0, 7)}` });
await db.insert(agents).values([
{ id: originalAgentId, companyId, name: "Original worker", role: "engineer", adapterType: "codex_local" },
{ id: currentAgentId, companyId, name: "Current worker", role: "engineer", adapterType: "codex_local" },
]);
const ownerId = options.conversationReset ? originalAgentId : currentAgentId;
await db.insert(issues).values({ id: issueId, companyId, title: "Preserve changed task", status: "in_progress",
assigneeAgentId: options.noCurrentOwner ? null : ownerId,
...(options.conversationReset ? { conversationAgentId: originalAgentId, conversationUserId: "fixture-board",
conversationState: "active", conversationSessionGeneration: 2 } : {}),
});
const workspaceRestoreRecovery = { schema: LEGACY_WORKSPACE_RECOVERY_SCHEMA, leaseIds: [leaseId] };
await db.insert(heartbeatRuns).values([
{ id: sourceRunId, companyId, agentId: originalAgentId, runtimeMode: "legacy", status: "cancelled",
finishedAt: new Date("2000-01-01T00:00:00Z"), contextSnapshot: { issueId, conversationSessionGeneration: 1 },
runnerProfileJson: { adapterDispatch: { adapterType: "codex_local" } },
resultJson: { workspaceRestoreFailure: "restore_failed", workspaceRestoreRecovery,
conversationContinuation: "continue_conversation_v1" } },
{ id: currentRunId, companyId, agentId: ownerId, runtimeMode: "legacy", status: "running",
contextSnapshot: { issueId, conversationSessionGeneration: 2 } },
]);
await db.update(issues).set({ executionRunId: currentRunId, checkoutRunId: currentRunId,
executionLockedAt: new Date("2000-01-01T00:00:00Z"), executionAgentNameKey: "current-worker" })
.where(eq(issues.id, issueId));
const identity = { id: leaseId, companyId, heartbeatRunId: sourceRunId, provider: "daytona", providerLeaseId: `fixture-${leaseId}` };
await db.insert(environmentLeases).values({ ...identity, issueId, status: "released", leasePolicy: "retain_on_failure",
releasedAt: new Date(), cleanupStatus: "success", metadata: {
remoteExecutionTermination: remoteTerminationReceipt(identity, { providerLeaseId: identity.providerLeaseId, state: "stopped" }),
} });
await db.insert(issueRecoveryActions).values({ id: actionId, companyId, sourceIssueId: issueId,
kind: "active_run_watchdog", cause: "legacy_execution_requires_reconciliation", ownerType: "board",
returnOwnerAgentId: originalAgentId, fingerprint: `legacy-execution:${sourceRunId}`,
status: "resolved", outcome: "blocked", nextAction: "Repair the retained workspace before continuing.",
evidence: { runId: sourceRunId, workspaceRestoreFailure: "restore_failed", workspaceRestoreRecovery,
automaticRecovery: { replay: "blocked" } },
});
const newerId = options.newerAction ? randomUUID() : null;
if (newerId) await db.insert(issueRecoveryActions).values({ id: newerId, companyId, sourceIssueId: issueId,
kind: "configuration_validation", cause: "configuration_incomplete", ownerType: "board", status: "active",
fingerprint: `newer:${currentRunId}`, nextAction: "Review the current configuration.", evidence: { runId: currentRunId } });
const [issueBefore] = await db.select().from(issues).where(eq(issues.id, issueId));
const [leaseBefore] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId));
const body = { actionId, outcome: "restored", sourceIssueStatus: issueBefore.status,
executionReconciliation: { runId: sourceRunId, providerStopped: true, actionOutcome: "mixed",
outcomeEvidence: "Reviewed the original action receipts without replaying any previous work.",
workspaceRepairEvidence: "Recovered and verified the required files from the exact retained sandbox." } };
return { companyId, issueId, sourceRunId, currentRunId, originalAgentId, currentAgentId, ownerId,
leaseId, actionId, newerId, issueBefore, leaseBefore, body };
}
function appFor(actor: Record<string, unknown> = { type: "board", source: "local_implicit" }) {
const wake = vi.fn(async () => null);
const app = express();
app.use(express.json());
app.use((req, _res, next) => { (req as unknown as { actor: unknown }).actor = actor; next(); });
app.use("/api", issueRoutes(db, {} as Parameters<typeof issueRoutes>[1], { recoveryActionEnqueueWakeup: wake }));
app.use(errorHandler);
return { app, wake };
}
async function assertSourceUnchanged(f: Awaited<ReturnType<typeof seed>>) {
expect((await db.select().from(issues).where(eq(issues.id, f.issueId)))[0]).toEqual(f.issueBefore);
expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.leaseId)))[0]).toEqual(f.leaseBefore);
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId))).toEqual([]);
expect(await db.select().from(heartbeatRuns).where(inArray(heartbeatRuns.id, [f.sourceRunId, f.currentRunId]))).toHaveLength(2);
}
it.each(["reassigned", "conversation_reset", "unassigned"])("records board repair after %s without restarting or changing the current task", async scenario => {
const f = await seed({ conversationReset: scenario === "conversation_reset", noCurrentOwner: scenario === "unassigned" });
const { app, wake } = appFor();
expect(await getExecutionBlocker(db, f.companyId, f.issueId)).not.toBeNull();
await request(app).post(`/api/issues/${f.issueId}/recovery-actions/resolve`).send(f.body).expect(200);
await assertSourceUnchanged(f);
expect(wake).not.toHaveBeenCalled();
const [action] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId));
expect(action.evidence).toMatchObject({ workspaceRestoreRecovery: { leaseIds: [f.leaseId] },
executionReconciliation: { runId: f.sourceRunId, workspaceRepairEvidence: f.body.executionReconciliation.workspaceRepairEvidence } });
expect(action.evidence.automaticRecovery).toBeUndefined();
expect(action.evidence.continuationDelivery).not.toBe("pending");
expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toBeNull();
const auditBefore = await db.select().from(activityLog).where(eq(activityLog.companyId, f.companyId));
expect(auditBefore.length).toBeGreaterThan(0);
await request(app).post(`/api/issues/${f.issueId}/recovery-actions/resolve`).send(f.body).expect(200);
expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId)))[0]).toEqual(action);
expect(await db.select().from(activityLog).where(eq(activityLog.companyId, f.companyId))).toEqual(auditBefore);
await assertSourceUnchanged(f);
expect(wake).not.toHaveBeenCalled();
});
it.each(["blocked", "done", "cancelled", "backlog"])("records repair without changing the current %s task", async status => {
const f = await seed();
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, f.currentRunId));
const [before] = await db.update(issues).set({ status, executionRunId: null, checkoutRunId: null,
executionLockedAt: null, executionAgentNameKey: null }).where(eq(issues.id, f.issueId)).returning();
const { app, wake } = appFor();
await request(app).post(`/api/issues/${f.issueId}/recovery-actions/resolve`)
.send({ ...f.body, sourceIssueStatus: status }).expect(200);
await assertSourceUnchanged({ ...f, issueBefore: before });
expect(wake).not.toHaveBeenCalled();
});
it("repairs only the recorded source while a newer active recovery action remains unchanged", async () => {
const f = await seed({ newerAction: true });
const [newerBefore] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.newerId!));
const { app, wake } = appFor();
const before = await request(app).get(`/api/issues/${f.issueId}/recovery-actions`).expect(200);
expect(before.body.active).toMatchObject({ id: f.newerId });
expect(before.body.actions).toEqual(expect.arrayContaining([
expect.objectContaining({ id: f.actionId, evidence: expect.objectContaining({
workspaceRestoreRecovery: { schema: LEGACY_WORKSPACE_RECOVERY_SCHEMA, leaseIds: [f.leaseId] },
}) }), expect.objectContaining({ id: f.newerId }),
]));
const response = await request(app).post(`/api/issues/${f.issueId}/recovery-actions/resolve`).send(f.body).expect(200);
expect(response.body.issue.activeRecoveryAction).toMatchObject({ id: f.newerId });
expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.newerId!)))[0]).toEqual(newerBefore);
const repeated = await request(app).post(`/api/issues/${f.issueId}/recovery-actions/resolve`).send(f.body).expect(200);
expect(repeated.body.issue.activeRecoveryAction).toMatchObject({ id: f.newerId });
const after = await request(app).get(`/api/issues/${f.issueId}/recovery-actions`).expect(200);
expect(after.body.active).toMatchObject({ id: f.newerId });
expect(after.body.actions.map((action: { id: string }) => action.id)).toEqual([f.newerId]);
await assertSourceUnchanged(f);
expect(wake).not.toHaveBeenCalled();
});
it("rejects an agent even when it owns the current task and run", async () => {
const f = await seed();
const { app, wake } = appFor({ type: "agent", source: "agent_jwt", companyId: f.companyId,
agentId: f.ownerId, runId: f.currentRunId });
await request(app).post(`/api/issues/${f.issueId}/recovery-actions/resolve`).send(f.body).expect(403);
await assertSourceUnchanged(f);
expect(wake).not.toHaveBeenCalled();
expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId)))[0].evidence)
.not.toHaveProperty("executionReconciliation");
});
it("does not expose retained-source evidence to another company", async () => {
const f = await seed(), other = await seed();
const { app } = appFor({ type: "agent", source: "agent_jwt", companyId: other.companyId,
agentId: other.ownerId, runId: other.currentRunId });
const response = await request(app).get(`/api/issues/${f.issueId}/recovery-actions`).expect(404);
expect(JSON.stringify(response.body)).not.toContain(f.leaseId);
expect(JSON.stringify(response.body)).not.toContain(f.actionId);
});
it.each(["other_task", "other_company", "wrong_decision_run"])("rejects repair evidence for %s", async scenario => {
const f = await seed();
const other = await seed();
const foreignTaskId = scenario === "other_task" ? randomUUID() : other.issueId;
if (scenario === "other_task") await db.insert(issues).values({ id: foreignTaskId, companyId: f.companyId,
title: "Other task", status: "todo", assigneeAgentId: f.originalAgentId });
if (scenario !== "wrong_decision_run") await db.update(heartbeatRuns).set({
...(scenario === "other_company" ? { companyId: other.companyId, agentId: other.originalAgentId } : {}),
contextSnapshot: { issueId: foreignTaskId },
}).where(eq(heartbeatRuns.id, f.sourceRunId));
const { app, wake } = appFor();
const body = scenario === "wrong_decision_run" ? { ...f.body,
executionReconciliation: { ...f.body.executionReconciliation, runId: other.sourceRunId } } : f.body;
await request(app).post(`/api/issues/${f.issueId}/recovery-actions/resolve`).send(body).expect(409);
await assertSourceUnchanged(f);
expect(wake).not.toHaveBeenCalled();
});
it("does not authorize ordinary execution reconciliation through the repair-only request shape", async () => {
const f = await seed();
await db.update(heartbeatRuns).set({ resultJson: { conversationContinuation: "continue_conversation_v1" } })
.where(eq(heartbeatRuns.id, f.sourceRunId));
await db.update(issueRecoveryActions).set({ evidence: { runId: f.sourceRunId, automaticRecovery: { replay: "blocked" } } })
.where(eq(issueRecoveryActions.id, f.actionId));
const { app, wake } = appFor();
await request(app).post(`/api/issues/${f.issueId}/recovery-actions/resolve`).send(f.body).expect(409);
await assertSourceUnchanged(f);
expect(wake).not.toHaveBeenCalled();
});
it("rejects a client-supplied repair-only authority flag", async () => {
const f = await seed();
const { app, wake } = appFor();
await request(app).post(`/api/issues/${f.issueId}/recovery-actions/resolve`)
.send({ ...f.body, workspaceRepairOnly: true }).expect(400);
await assertSourceUnchanged(f);
expect(wake).not.toHaveBeenCalled();
});
it.each(["missing_repair_evidence", "unconfirmed_stop", "missing_source_marker", "status_change"])("rejects %s without resolving the hold", async scenario => {
const f = await seed();
if (scenario === "unconfirmed_stop") await db.update(environmentLeases).set({ metadata: {} }).where(eq(environmentLeases.id, f.leaseId));
if (scenario === "missing_source_marker") await db.update(heartbeatRuns).set({ resultJson: { workspaceRestoreFailure: "restore_failed" } })
.where(eq(heartbeatRuns.id, f.sourceRunId));
const { app, wake } = appFor();
const body = scenario === "missing_repair_evidence" ? { ...f.body,
executionReconciliation: { ...f.body.executionReconciliation, workspaceRepairEvidence: undefined } }
: scenario === "status_change" ? { ...f.body, sourceIssueStatus: "todo" } : f.body;
await request(app).post(`/api/issues/${f.issueId}/recovery-actions/resolve`).send(body)
.expect(scenario === "missing_repair_evidence" ? 400 : 409);
expect((await db.select().from(issues).where(eq(issues.id, f.issueId)))[0]).toEqual(f.issueBefore);
expect((await db.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.id, f.actionId),
eq(issueRecoveryActions.companyId, f.companyId))))[0].evidence).not.toHaveProperty("executionReconciliation");
expect(wake).not.toHaveBeenCalled();
});
});
@@ -1,7 +1,16 @@
import { sql } from "drizzle-orm";
import express from "express";
import request from "supertest";
import { beforeEach, describe, expect, it, vi } from "vitest";
// Isolate runtime-management guards; real database privacy is covered by
// privacy-production-review.test.ts.
vi.mock("../services/authorization.js", async () => ({
...(await vi.importActual<typeof import("../services/authorization.js")>("../services/authorization.js")),
executionWorkspaceReadSqlCondition: async () => sql<boolean>`true`,
canActorReadExecutionWorkspace: async () => true,
}));
const mockProjectService = vi.hoisted(() => ({
create: vi.fn(),
createWorkspace: vi.fn(),
+4
View File
@@ -12,6 +12,7 @@ import { createMcpApiDispatch, createPublicMcpExecutor } from "./services/public
import { createPublicMcpEvents, type PublicMcpEvents } from "./services/public-mcp/events.js";
import { publicMcpIngressRoutes, publicMcpManagementRoutes } from "./routes/public-mcp.js";
import { agentAvatarRoutes } from "./routes/agent-avatars.js";
import { decisionModelRoutes } from "./routes/decision-models.js";
import { aiConnectionRoutes } from "./routes/ai-connections.js";
import { projectToolRoutes } from "./routes/project-tools.js";
import { emailChannelService } from "./services/email-channels.js";
@@ -109,6 +110,7 @@ import { sidebarBadgeRoutes } from "./routes/sidebar-badges.js";
import { sidebarPreferenceRoutes } from "./routes/sidebar-preferences.js";
import { announcementRoutes } from "./routes/announcements.js";
import { serverVersion } from "./version.js";
import { primaryAgentRoutes } from "./routes/primary-agent.js";
import { resourceMembershipRoutes } from "./routes/resource-memberships.js";
import { inboxDismissalRoutes } from "./routes/inbox-dismissals.js";
import { instanceSettingsRoutes } from "./routes/instance-settings.js";
@@ -827,6 +829,7 @@ export async function createApp(
api.use(sidebarPreferenceRoutes(db));
api.use(announcementRoutes(db, { ...opts.announcements, version: opts.hostVersion ?? serverVersion }));
api.use(resourceMembershipRoutes(db));
api.use(primaryAgentRoutes(db));
api.use(inboxDismissalRoutes(db));
api.use(instanceSettingsRoutes(db));
if (opts.databaseBackupService) {
@@ -878,6 +881,7 @@ export async function createApp(
registerAssignedMcpGateway(db, toolGateway);
app.locals.toolActionDeliveries = toolActionDeliveries;
app.use(mcpGatewayProtocolRoutes(toolGateway));
api.use(decisionModelRoutes(db));
api.use(aiConnectionRoutes(db, { deploymentMode: opts.deploymentMode, deploymentExposure: opts.deploymentExposure, trustedLocalStdioRuntimeHost }));
api.use(
toolAccessRoutes(db, {
+9 -4
View File
@@ -879,6 +879,7 @@ async function startServerWithDatabaseTeardown(
const heartbeat = config.heartbeatSchedulerEnabled
? heartbeatService(db as any, { pluginWorkerManager })
: null;
const accountingHeartbeat = heartbeat ?? heartbeatService(db as any, { pluginWorkerManager });
const decisionServiceOptions = {
wakeOriginAgent: createDecisionWakeOriginAgent(heartbeat?.wakeup ?? null),
};
@@ -1230,8 +1231,7 @@ async function startServerWithDatabaseTeardown(
// so a just-failed lease does not draw a retry on every tick. The startup
// sweep passes zero, so a restart retries a stranded orphan at once.
const ENVIRONMENT_LEASE_CLEANUP_SWEEP_BACKOFF_MS = 5 * 60 * 1000;
const environmentLeaseCleanupHeartbeat =
heartbeat ?? heartbeatService(db as any, { pluginWorkerManager });
const environmentLeaseCleanupHeartbeat = accountingHeartbeat;
const chatCompletionDeliveries = chatCompletionDeliveryService(db as any, environmentLeaseCleanupHeartbeat);
// Activity publication happens after the status transaction commits. This is
// a best-effort fast path; the durable outbox and sweeps remain authoritative.
@@ -1449,6 +1449,7 @@ async function startServerWithDatabaseTeardown(
},
"worktree run-execution cutoff state",
);
await accountingHeartbeat.reconcileCostAccounting().catch((err) => logger.error({ err }, "Cost accounting recovery failed; pending receipts will retry"));
const heartbeatSchedulingSuppression = await heartbeat.resolveSchedulingSuppression();
// Reap orphaned runs before timer ticks start so wakeups cannot coalesce
@@ -1464,8 +1465,7 @@ async function startServerWithDatabaseTeardown(
// workers before cleanup or retry admission, including unmanaged installs.
await app.locals.bundledPluginsStartup;
try {
const nativeRecovery =
await heartbeat.recoverNativeRunsAfterRestart();
const nativeRecovery = await heartbeat.recoverNativeRunsAfterRestart();
if (nativeRecovery.dispositions.length > 0) {
logger.info(
{
@@ -1763,6 +1763,9 @@ async function startServerWithDatabaseTeardown(
}));
trackHeartbeatSchedulerWork(chatCompletionDeliveries.sweepPending().catch((err) => logger.error({ err }, "chat completion delivery failed")));
trackHeartbeatSchedulerWork(accountingHeartbeat.reconcileCostAccounting().catch((err) => logger.error({ err }, "Cost accounting recovery failed")));
trackHeartbeatSchedulerWork(connectionDeliveries.sweepPending().catch((err) => logger.error({ err }, "connection continuation delivery failed")));
trackHeartbeatSchedulerWork(app.locals.toolGateway.sweepActionReviews().catch((err: unknown) => logger.error({ err }, "tool review recovery failed")));
trackHeartbeatSchedulerWork(app.locals.toolGateway.cleanupExpiredSessions().catch((err: unknown) => logger.error({ err }, "gateway token cleanup failed")));
@@ -1839,8 +1842,10 @@ async function startServerWithDatabaseTeardown(
// is still required. A failed acquire can leak a paid provider sandbox, so
// this path retries the teardown at startup and on the interval, exactly as
// the enabled path does.
await accountingHeartbeat.reconcileCostAccounting().catch((err) => logger.error({ err }, "Cost accounting recovery failed; pending receipts will retry"));
await runEnvironmentLeaseCleanupSweep(0);
startHeartbeatSchedulerInterval(() => {
trackHeartbeatSchedulerWork(accountingHeartbeat.reconcileCostAccounting().catch((err) => logger.error({ err }, "Cost accounting recovery failed")));
scheduleExternalObjectRefreshSweep(new Date());
scheduleEnvironmentLeaseCleanupSweep();
scheduleGitHubConnectionEventPoll();
@@ -8,6 +8,7 @@ import {
createDb,
documentRevisions,
documents,
environmentLeases,
heartbeatRunEvents,
heartbeatRuns,
issueDocuments,
@@ -51,6 +52,7 @@ describeEmbeddedPostgres("run-dispatch postgres adapter", () => {
}, 20_000);
afterEach(async () => {
await db.delete(environmentLeases);
await db.delete(activityLog);
await db.delete(issueDocuments);
await db.delete(documentRevisions);
@@ -154,6 +156,115 @@ describeEmbeddedPostgres("run-dispatch postgres adapter", () => {
return runId;
}
async function seedCleanupRetry(status: "scheduled_retry" | "queued" = "scheduled_retry") {
const { companyId, agentId } = await seedCompanyAndAgent();
const issueId = randomUUID();
const now = new Date();
await seedIssue({ companyId, issueId, assigneeAgentId: agentId, status: "in_progress" });
const sourceId = await seedRun({ companyId, agentId, contextSnapshot: { issueId } });
await db.update(heartbeatRuns).set({ status: "failed", finishedAt: now,
resultJson: { conversationContinuation: "continue_conversation_v1", workspaceRestoreFailure: "restore_failed" },
}).where(eq(heartbeatRuns.id, sourceId));
const [lease] = await db.insert(environmentLeases).values({ companyId, issueId,
heartbeatRunId: sourceId, status: "pending_cleanup", cleanupStatus: "failed",
}).returning();
const runId = await seedRun({ companyId, agentId, status, now,
contextSnapshot: { issueId, retryOfRunId: sourceId, executionRetryAccounting: { version: 1, failureRetries: 1, maxTurnContinuations: 0 } },
scheduledRetryReason: "transient_failure",
});
await db.update(heartbeatRuns).set({ retryOfRunId: sourceId, scheduledRetryAttempt: 1,
resultJson: { conversationContinuation: "continue_conversation_v1" },
}).where(eq(heartbeatRuns.id, runId));
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));
return { companyId, agentId, issueId, sourceId, leaseId: lease!.id, runId, now };
}
it("keeps one scheduled retry through cleanup and promotes it once after release", async () => {
const f = await seedCleanupRetry();
let adapter = createPostgresRunDispatchAdapter(db);
for (let attempt = 0; attempt < 4; attempt++) {
expect(await adapter.promoteOrCancelDueRetry({ ...f, now: new Date(f.now.getTime() + attempt * 60_000) }))
.toMatchObject({ outcome: "not_promoted" });
// Reconstruct the service to prove the wait survives controller restart.
adapter = createPostgresRunDispatchAdapter(db);
}
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
expect(run).toMatchObject({ status: "scheduled_retry", startedAt: null, finishedAt: null,
retryOfRunId: f.sourceId, scheduledRetryAttempt: 1,
contextSnapshot: { executionRetryAccounting: { failureRetries: 1 } },
});
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, f.companyId))).toHaveLength(2);
expect(await db.select().from(issueRecoveryActions)).toHaveLength(0);
const events = await db.select().from(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, f.runId));
expect(events.filter(e => e.message?.includes("waiting for execution cleanup"))).toHaveLength(1);
await db.update(environmentLeases).set({ status: "released", cleanupStatus: "success", releasedAt: new Date() })
.where(eq(environmentLeases.id, f.leaseId));
const now = new Date(f.now.getTime() + 300_000);
const outcomes = await Promise.all([
adapter.promoteOrCancelDueRetry({ ...f, now }), adapter.promoteOrCancelDueRetry({ ...f, now }),
]);
expect(outcomes.filter(o => o.outcome === "promoted")).toHaveLength(1);
const [resumed] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
expect(resumed).toMatchObject({ status: "queued", scheduledRetryAttempt: 1 });
expect(resumed.resultJson).not.toHaveProperty("executionWait");
expect(await adapter.cancelStaleQueuedRun({ ...f, now, expectedStatus: "queued" }))
.toMatchObject({ outcome: "not_stale" });
});
it("parks the same unstarted retry if cleanup becomes pending after promotion", async () => {
const f = await seedCleanupRetry("queued");
const adapter = createPostgresRunDispatchAdapter(db);
expect(await adapter.cancelStaleQueuedRun({ ...f, expectedStatus: "queued" }))
.toMatchObject({ outcome: "deferred" });
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
expect(run).toMatchObject({ status: "scheduled_retry", scheduledRetryAttempt: 1, startedAt: null, finishedAt: null });
expect((await db.select().from(issues).where(eq(issues.id, f.issueId)))[0].executionRunId).toBe(f.runId);
});
it("still suppresses a cleanup-waiting retry when the task is cancelled", async () => {
const f = await seedCleanupRetry();
await db.update(issues).set({ status: "cancelled" }).where(eq(issues.id, f.issueId));
expect(await createPostgresRunDispatchAdapter(db).promoteOrCancelDueRetry(f))
.toMatchObject({ outcome: "gate_suppressed", errorCode: "issue_cancelled" });
});
it("still suppresses a cleanup-waiting retry after reassignment", async () => {
const f = await seedCleanupRetry();
const newOwnerId = randomUUID();
await seedAgent({ id: newOwnerId, companyId: f.companyId, name: "New owner" });
await db.update(issues).set({ assigneeAgentId: newOwnerId }).where(eq(issues.id, f.issueId));
expect(await createPostgresRunDispatchAdapter(db).promoteOrCancelDueRetry(f))
.toMatchObject({ outcome: "gate_suppressed", errorCode: "issue_reassigned" });
});
it("retains a no-replay hold after cleanup releases ownership", async () => {
const f = await seedCleanupRetry();
const adapter = createPostgresRunDispatchAdapter(db);
await db.insert(issueRecoveryActions).values({
companyId: f.companyId, sourceIssueId: f.issueId, kind: "active_run_watchdog",
ownerType: "board", cause: "uncertain_external_action", status: "resolved",
evidence: { automaticRecovery: { replay: "blocked" } }, fingerprint: f.sourceId,
nextAction: "Verify the external action before continuing.",
});
expect(await adapter.promoteOrCancelDueRetry(f)).toMatchObject({ outcome: "not_promoted" });
await db.update(environmentLeases).set({ status: "released", cleanupStatus: "success", releasedAt: new Date() })
.where(eq(environmentLeases.id, f.leaseId));
const now = new Date(f.now.getTime() + 60_000);
expect(await adapter.promoteOrCancelDueRetry({ ...f, now })).toMatchObject({ outcome: "promoted" });
expect(await adapter.cancelStaleQueuedRun({ ...f, now, expectedStatus: "queued" }))
.toMatchObject({ outcome: "cancelled", errorCode: "execution_reconciliation_required" });
expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toMatchObject({ cause: "uncertain_external_action" });
});
it.each(["native", "started", "non-conversation"])("does not park a %s run behind cleanup", async (mode) => {
const f = await seedCleanupRetry("queued");
await db.update(heartbeatRuns).set(mode === "native" ? { runtimeMode: "native" }
: mode === "started" ? { startedAt: f.now } : { resultJson: {} })
.where(eq(heartbeatRuns.id, f.runId));
expect(await createPostgresRunDispatchAdapter(db).cancelStaleQueuedRun({ ...f, expectedStatus: "queued" }))
.toMatchObject({ outcome: "cancelled", errorCode: "execution_reconciliation_required" });
});
async function seedContinuationSummary(input: {
companyId: string;
issueId: string;
@@ -15,9 +15,11 @@ import {
issues,
} from "@paperclipai/db";
import { ISSUE_DISPOSITION_REPAIR_RETRY_REASON } from "@paperclipai/shared";
import { withAccountingTransaction } from "../../../services/accounting-transaction.js";
import type { ActivityPublication } from "../../../services/activity-log.js";
import { parseObject } from "../../../adapters/utils.js";
import { evaluateAgentInvokabilityFromDb } from "../../../services/agent-invokability.js";
import { budgetService } from "../../../services/budgets.js";
import { budgetService, budgetServiceInTransaction } from "../../../services/budgets.js";
import { isCompletedOnboardingHandoffWake } from "../../../services/chat-completion-delivery.js";
import { isHeartbeatWakeOnDemandEnabled } from "../../../services/heartbeat-policy.js";
import { collectDispositionRepairSourceState } from "../../../services/recovery/disposition-repair.js";
@@ -190,7 +192,7 @@ export function createPostgresRunDispatchAdapter(
async function withIssueThenRunLocks<T>(
input: { runId: string; companyId: string },
onMissing: () => T,
operation: (tx: Db, run: HeartbeatRun) => Promise<T>,
operation: (tx: Db, run: HeartbeatRun, publications: ActivityPublication[]) => Promise<T>,
): Promise<T> {
// Queue editing and claiming already use issue -> wake -> run. Read the
// immutable issue reference without a lock first, then acquire issue ->
@@ -206,8 +208,9 @@ export function createPostgresRunDispatchAdapter(
const hintedIssueId = readNonEmptyString(parseObject(hint.contextSnapshot).issueId);
const result: { kind: "missing" | "retry" } | { kind: "value"; value: T } =
await db.transaction(async (tx) => {
const typedTx = tx as unknown as Db;
await withAccountingTransaction(db, input.companyId, async (typedTx, publications) => {
// Budget gates mutate policy state. Acquire company before issue/run,
// matching receipt writers (including their attribution FK locks).
if (hintedIssueId) {
await typedTx
.select({ id: issues.id })
@@ -231,7 +234,7 @@ export function createPostgresRunDispatchAdapter(
const lockedIssueId = readNonEmptyString(parseObject(run.contextSnapshot).issueId);
if (lockedIssueId !== hintedIssueId) return { kind: "retry" as const };
return { kind: "value" as const, value: await operation(typedTx, run) };
return { kind: "value" as const, value: await operation(typedTx, run, publications) };
});
if (result.kind === "missing") return onMissing();
@@ -247,12 +250,13 @@ export function createPostgresRunDispatchAdapter(
input: LoadGateFactsInput,
now: Date,
tx?: unknown,
publications?: ActivityPublication[],
): Promise<LoadGateFactsResult> {
// Semantic adapter operations pass their transaction here so the fact
// read and the state transition share one unit of work. This helper is
// deliberately not exposed through the module's public API.
const dbOrTx = (tx as Db | undefined) ?? db;
const budgetsForRead = tx ? budgetService(dbOrTx) : budgets;
const budgetsForRead = tx ? budgetServiceInTransaction(dbOrTx, publications) : budgets;
const treeControlForRead = tx ? issueTreeControlService(dbOrTx) : treeControlSvc;
const issuesSvcForRead = tx ? issueService(dbOrTx) : issuesSvc;
@@ -639,7 +643,12 @@ export function createPostgresRunDispatchAdapter(
> {
const [row] = await tx
.update(heartbeatRuns)
.set({ status: "queued", updatedAt: input.now })
.set({
status: "queued",
updatedAt: input.now,
resultJson: sql`case when ${heartbeatRuns.resultJson}->'executionWait'->>'cause' = 'execution_owner_active'
then ${heartbeatRuns.resultJson} - 'executionWait' else ${heartbeatRuns.resultJson} end`,
})
.where(
and(
eq(heartbeatRuns.id, input.runId),
@@ -747,7 +756,7 @@ export function createPostgresRunDispatchAdapter(
): Promise<PromoteScheduledRetryOutcome> {
const now = input.now;
const promoteLockedRun = async (tx: Db, run: HeartbeatRun) => {
const promoteLockedRun = async (tx: Db, run: HeartbeatRun, publications: ActivityPublication[]) => {
if (
run.status !== "scheduled_retry" ||
!run.scheduledRetryAt ||
@@ -768,6 +777,7 @@ export function createPostgresRunDispatchAdapter(
},
now,
tx,
publications,
);
if (!factsResult.agentFound) {
@@ -827,6 +837,11 @@ export function createPostgresRunDispatchAdapter(
: { outcome: { outcome: "not_promoted" as const }, telemetryRun: null };
}
const issueId = factsResult.facts.issueId;
if (issueId && (await deferRetryForCleanupInTx(tx, run, issueId, now))) {
return { outcome: { outcome: "not_promoted" as const }, telemetryRun: null };
}
const promoted = await promoteDueRetryInTx(tx as unknown as Db, {
runId: input.runId,
companyId: input.companyId,
@@ -950,9 +965,9 @@ export function createPostgresRunDispatchAdapter(
async function decideCurrentRunStaleness(tx: Db, run: HeartbeatRun, now: Date) {
const contextSnapshot = parseObject(run.contextSnapshot);
const issueId = readNonEmptyString(contextSnapshot.issueId);
if (!issueId) return { issueId: null, facts: null, decision: { stale: false as const } };
if (!issueId) return { issueId: null, facts: null, executionBlocker: null, decision: { stale: false as const } };
const recovery = await getExecutionBlocker(tx, run.companyId, issueId, { conversationResetCommentId: deriveCommentId(contextSnapshot) });
if (recovery) return { issueId, facts: null, decision: { stale: true as const,
if (recovery) return { issueId, facts: null, executionBlocker: recovery, decision: { stale: true as const,
errorCode: "execution_reconciliation_required" as const, reason: recovery.nextAction,
details: { issueId, recoveryActionId: recovery.recoveryActionId },
} };
@@ -968,7 +983,67 @@ export function createPostgresRunDispatchAdapter(
now,
tx,
);
return { issueId, facts, decision: decideQueuedRunStaleness(facts, now) };
return { issueId, facts, executionBlocker: null, decision: decideQueuedRunStaleness(facts, now) };
}
/**
* Keep the existing attempt durable while the previous execution releases
* ownership. Only an unstarted legacy conversation retry can wait here;
* reconciliation of uncertain actions and native execution retain their gates.
* Both callers hold the issue and run locks, in that order.
*/
async function deferRetryForCleanupInTx(
tx: Db,
run: HeartbeatRun,
issueId: string,
now: Date,
observedBlocker?: Awaited<ReturnType<typeof getExecutionBlocker>>,
) {
if (
run.runtimeMode !== "legacy" || !run.retryOfRunId || run.startedAt ||
run.processPid || run.processGroupId ||
!hasConversationContinuationPolicy(run.resultJson) ||
!["scheduled_retry", "queued"].includes(run.status)
) return null;
// Use the dispatch gate's observation when supplied. A second read could
// see cleanup finish and accidentally cancel the retry for the old hold.
const blocker = observedBlocker === undefined
? await getExecutionBlocker(tx, run.companyId, issueId)
: observedBlocker;
if (blocker?.cause !== "execution_owner_active") return null;
const previousWait = parseObject(run.resultJson?.executionWait);
const scheduledRetryAt = new Date(now.getTime() + 30_000);
const executionWait = { issueId, runId: blocker.runId, cause: blocker.cause };
const [waiting] = await tx.update(heartbeatRuns)
.set({
status: "scheduled_retry",
scheduledRetryAt,
updatedAt: now,
contextSnapshot: { ...parseObject(run.contextSnapshot), scheduledRetryAt: scheduledRetryAt.toISOString() },
resultJson: { ...parseObject(run.resultJson), executionWait },
})
.where(and(
eq(heartbeatRuns.id, run.id),
eq(heartbeatRuns.companyId, run.companyId),
eq(heartbeatRuns.status, run.status),
))
.returning();
if (!waiting) return null;
// Repeated sweeps retain one wait diagnostic, not a new attempt or event.
if (previousWait.cause !== blocker.cause || previousWait.runId !== blocker.runId) {
await appendHeartbeatRunEvent(tx, {
companyId: run.companyId,
runId: run.id,
agentId: run.agentId,
eventType: "lifecycle",
stream: "system",
level: "info",
message: "Scheduled retry is waiting for execution cleanup; the same attempt will continue after ownership is released",
payload: { ...executionWait, scheduledRetryAttempt: run.scheduledRetryAttempt },
});
}
return { outcome: "deferred" as const, postCommitEffects: [statusEffect(waiting, run.status)] };
}
async function cancelStaleQueuedRun(
@@ -976,7 +1051,7 @@ export function createPostgresRunDispatchAdapter(
): Promise<CancelStaleQueuedRunOutcome> {
const cancelLockedRun = async (tx: Db, run: HeartbeatRun) => {
if (run.status !== input.expectedStatus) return { outcome: "lost_race" as const };
const { issueId, facts, decision } = await decideCurrentRunStaleness(tx, run, input.now);
const { issueId, facts, decision, executionBlocker } = await decideCurrentRunStaleness(tx, run, input.now);
if (!decision.stale || !issueId) {
if (input.expectedStatus === "queued" && facts?.isInteractionWake) {
// Preserve the authority accepted under the issue/run locks. Later
@@ -991,6 +1066,10 @@ export function createPostgresRunDispatchAdapter(
}
return { outcome: "not_stale" as const };
}
if (input.expectedStatus === "queued" && decision.errorCode === "execution_reconciliation_required") {
const deferred = await deferRetryForCleanupInTx(tx, run, issueId, input.now, executionBlocker);
if (deferred) return deferred;
}
return cancelStaleRunInTx(tx, run, issueId, decision, input.expectedStatus, input.now);
};
@@ -1010,7 +1089,7 @@ export function createPostgresRunDispatchAdapter(
input: DispatchResolvedInteractionInput<T>,
): Promise<DispatchResolvedInteractionOutcome<T>> {
const dispatchLockedRun = async (tx: Db, run: HeartbeatRun) => {
if (run.status !== input.expectedStatus) {
if (run.status !== input.expectedStatus || run.resultJson?.cancellation || run.resultJson?.startupCancellation) {
return { dispatched: false as const, cancellation: { outcome: "lost_race" as const } };
}
const { issueId, decision: initialDecision } = await decideCurrentRunStaleness(
@@ -46,6 +46,7 @@ export type PromoteScheduledRetryOutcome =
export type CancelStaleQueuedRunOutcome =
| { outcome: "not_stale" }
| { outcome: "deferred"; postCommitEffects: PostCommitEffect[] }
/** The run's status no longer matched the phase the caller expected; a concurrent writer already won. */
| { outcome: "lost_race" }
| {
+72 -4
View File
@@ -4,8 +4,8 @@ import { createRequire } from "node:module";
import type { Duplex } from "node:stream";
import { and, eq, isNull } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { agentApiKeys, companyMemberships, instanceUserRoles } from "@paperclipai/db";
import type { DeploymentMode } from "@paperclipai/shared";
import { agentApiKeys, companyMemberships, instanceUserRoles, heartbeatRuns, issues, projects } from "@paperclipai/db";
import type { DeploymentMode, LiveEvent } from "@paperclipai/shared";
import type { BetterAuthSessionResult } from "../auth/better-auth.js";
import { logger } from "../middleware/logger.js";
import { subscribeCompanyLiveEvents } from "../services/live-events.js";
@@ -40,7 +40,12 @@ const { WebSocket, WebSocketServer } = require("ws") as {
WebSocketServer: new (opts: { noServer: boolean }) => WsServer;
};
import { authorizationService, type AuthorizationActor } from "../services/authorization.js";
import { canActorReadHeartbeatRun } from "../services/heartbeat-run-privacy.js";
interface UpgradeContext {
actor: AuthorizationActor;
apiKeyId?: string;
companyId: string;
actorType: "board" | "agent";
actorId: string;
@@ -143,6 +148,7 @@ async function authorizeUpgrade(
companyId,
actorType: "board",
actorId: "board",
actor: { type: "board", userId: "local-board", source: "local_implicit" },
};
}
@@ -161,6 +167,7 @@ async function authorizeUpgrade(
companyId,
actorType: "board",
actorId: cloudActor.userId,
actor: { type: "board", userId: cloudActor.userId, source: "cloud_tenant", companyIds: cloudActor.companyIds },
};
}
}
@@ -198,6 +205,7 @@ async function authorizeUpgrade(
companyId,
actorType: "board",
actorId: userId,
actor: { type: "board", userId, source: "session", companyIds: memberships.map(m => m.companyId) },
};
}
@@ -208,7 +216,7 @@ async function authorizeUpgrade(
.where(and(eq(agentApiKeys.keyHash, tokenHash), isNull(agentApiKeys.revokedAt)))
.then((rows) => rows[0] ?? null);
if (!key || key.companyId !== companyId) {
if (!key || key.companyId !== companyId || key.scopeConfig) {
return null;
}
@@ -221,6 +229,8 @@ async function authorizeUpgrade(
companyId,
actorType: "agent",
actorId: key.agentId,
apiKeyId: key.id,
actor: { type: "agent", agentId: key.agentId, companyId, source: "agent_key", onBehalfOfUserId: key.responsibleUserId },
};
}
@@ -260,9 +270,67 @@ export function setupLiveEventsWebSocketServer(
return;
}
const access = authorizationService(db);
async function visibleEvent(event: LiveEvent): Promise<LiveEvent | null> {
if (context!.actor.source === "local_implicit") return event;
if (context!.apiKeyId) {
const active = await db.select({ id: agentApiKeys.id }).from(agentApiKeys)
.where(and(eq(agentApiKeys.id, context!.apiKeyId), isNull(agentApiKeys.revokedAt))).limit(1);
if (!active.length) return null;
} else {
const membership = await db.select({ id: companyMemberships.id }).from(companyMemberships)
.where(and(eq(companyMemberships.companyId, context!.companyId), eq(companyMemberships.principalType, "user"),
eq(companyMemberships.principalId, context!.actorId), eq(companyMemberships.status, "active"))).limit(1);
const admin = context!.actor.source !== "cloud_tenant" && await db.select({ id: instanceUserRoles.id }).from(instanceUserRoles)
.where(and(eq(instanceUserRoles.userId, context!.actorId), eq(instanceUserRoles.role, "instance_admin"))).limit(1).then(rows => rows.length > 0);
if (!membership.length && !admin) return null;
}
const payload = event.payload;
const issueId = typeof payload.issueId === "string" ? payload.issueId
: payload.entityType === "issue" && typeof payload.entityId === "string" ? payload.entityId : null;
if (issueId) {
const [issue] = await db.select({ id: issues.id }).from(issues)
.where(and(eq(issues.id, issueId), eq(issues.companyId, event.companyId))).limit(1);
if (!issue || !(await access.decide({ actor: context!.actor, action: "issue:read",
resource: { type: "issue", companyId: event.companyId, issueId } })).allowed) return null;
}
if (payload.entityType === "project" && typeof payload.entityId === "string") {
const [project] = await db.select({ id: projects.id }).from(projects)
.where(and(eq(projects.id, payload.entityId), eq(projects.companyId, event.companyId))).limit(1);
if (!project || !(await access.decide({ actor: context!.actor, action: "project:read",
resource: { type: "project", companyId: event.companyId, projectId: project.id } })).allowed) return null;
}
const runId = typeof payload.runId === "string" ? payload.runId
: payload.entityType === "heartbeat_run" && typeof payload.entityId === "string" ? payload.entityId : null;
if (runId) {
const [run] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, event.companyId)));
if (!run || !(await canActorReadHeartbeatRun(db, access, context!.actor, run))) return null;
}
if (event.type.startsWith("heartbeat.run.")) return runId ? event : null;
if (event.type === "agent.session.goal.changed") return issueId ? event : null;
// Company-wide invalidations carry no task-derived content. Authorized
// clients obtain details through viewer-filtered HTTP reads.
if (event.type === "activity.logged") return { ...event, payload: {
action: payload.action, entityType: payload.entityType, entityId: payload.entityId,
} };
if (event.type === "agent.status") return { ...event, payload: { agentId: payload.agentId, status: payload.status } };
if (event.type === "external_object.updated") return { ...event, payload: { externalObjectId: payload.externalObjectId } };
if (event.type.startsWith("plugin.")) return event;
return null;
}
let delivery = Promise.resolve();
let pending = 0;
const unsubscribe = subscribeCompanyLiveEvents(context.companyId, (event) => {
if (socket.readyState !== WebSocket.OPEN) return;
socket.send(JSON.stringify(event));
if (++pending > 1000) { socket.close(1013, "event backlog"); return; }
delivery = delivery.then(async () => {
if (socket.readyState !== WebSocket.OPEN) return;
// Check at delivery time, including after a grant is revoked while the
// subscription remains open. Never cache successful privacy decisions.
const visible = await visibleEvent(event);
if (visible && socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify(visible));
}).catch(err => logger.warn({ err, companyId: context.companyId }, "live event authorization failed"))
.finally(() => { pending -= 1; });
});
cleanupByClient.set(socket, unsubscribe);
+7
View File
@@ -10,6 +10,8 @@ import { sanitizeRecord } from "../redaction.js";
import { badRequest, forbidden } from "../errors.js";
import { agentActionAuditService } from "../services/agent-action-audit.js";
import { logActivity } from "../services/activity-log.js";
import { canActorReadHeartbeatRun } from "../services/heartbeat-run-privacy.js";
import { issueReadSqlCondition } from "../services/authorization.js";
/** Max rows a single CSV export will stream (guards against runaway exports). */
const AUDIT_CSV_EXPORT_MAX_ROWS = 10_000;
@@ -230,6 +232,7 @@ export function activityRoutes(db: Db) {
entityType: req.query.entityType as string | undefined,
entityId: req.query.entityId as string | undefined,
limit: normalizeActivityLimit(Number(req.query.limit)),
readCondition: await issueReadSqlCondition(db, req.actor),
};
const result = await svc.list(filters);
res.json(result);
@@ -369,6 +372,10 @@ export function activityRoutes(db: Db) {
}
assertCompanyAccess(req, run.companyId);
if (!(await assertCompanyScopeReadAllowed(req, res, run.companyId))) return;
if (!(await canActorReadHeartbeatRun(db, access, req.actor, run))) {
res.json([]);
return;
}
const result = await svc.issuesForRun(runId);
res.json(result);
});
+64 -6
View File
@@ -263,6 +263,11 @@ import {
changeConsentGateService,
touchesAgentProfileChangeConsentFields,
} from "../services/change-consent-gate.js";
import {
canActorReadHeartbeatRun,
canActorReadWorkspaceOperation,
redactHeartbeatRunListRow,
} from "../services/heartbeat-run-privacy.js";
import {
PaperclipRunnerProviderProfileError,
resolvePaperclipRunnerProviderProfile,
@@ -303,6 +308,12 @@ function mergeDesiredSkillEntries(
const RUN_LOG_DEFAULT_LIMIT_BYTES = 256_000;
const RUN_LOG_MAX_LIMIT_BYTES = 1024 * 1024;
type RunReadBinding = {
companyId: string;
scopeKind?: "company" | "issue" | null;
issueId?: string | null;
};
function readRunLogLimitBytes(value: unknown) {
const parsed = Number(value ?? RUN_LOG_DEFAULT_LIMIT_BYTES);
if (!Number.isFinite(parsed)) return RUN_LOG_DEFAULT_LIMIT_BYTES;
@@ -549,7 +560,7 @@ export function agentRoutes(
const KNOWN_INSTRUCTIONS_BUNDLE_KEY_SET: ReadonlySet<string> = new Set(KNOWN_INSTRUCTIONS_BUNDLE_KEYS);
const router = Router();
const svc = agentService(db);
const svc = agentService(db, { cancelWorkForScope: scope => heartbeat.cancelBudgetScopeWork(scope) });
const access = accessService(db);
const approvalsSvc = approvalService(db);
const budgets = budgetService(db);
@@ -762,6 +773,27 @@ export function agentRoutes(
const instanceSettings = instanceSettingsService(db);
const strictSecretsMode = process.env.PAPERCLIP_SECRETS_STRICT_MODE === "true";
async function actorCanReadRun(req: Request, run: RunReadBinding) {
return canActorReadHeartbeatRun(db, access, req.actor, run);
}
async function assertRunReadAllowed(
req: Request,
res: Response,
run: RunReadBinding,
notFoundMessage = "Heartbeat run not found",
) {
if (await actorCanReadRun(req, run)) return true;
res.status(404).json({ error: notFoundMessage });
return false;
}
async function serializeRunListRow<
T extends Record<string, unknown> & RunReadBinding & { id: string },
>(req: Request, run: T) {
return await actorCanReadRun(req, run) ? run : redactHeartbeatRunListRow(run);
}
// The company-scoped adapter login-session service. It runs the device-login
// flow in a fresh trusted sandbox and holds the one-time prompt in memory. The
// process owns one instance, so the in-memory prompt and the cancellation
@@ -4812,6 +4844,7 @@ export function agentRoutes(
lastHeartbeatAt: null,
},
{
createdByUserId: req.actor.type === "board" ? req.actor.userId : null,
aiConnectionInstall: managedHireConnection ? { ...managedHireConnection, createdByUserId: responsibleUserForAiRequest(req) } : undefined,
claudeLogin: {
storedSessionId: hireStoredSessionId ?? null,
@@ -5067,6 +5100,7 @@ export function agentRoutes(
lastHeartbeatAt: null,
},
{
createdByUserId: req.actor.type === "board" ? req.actor.userId : null,
aiConnectionInstall: managedConnection ? { ...managedConnection, createdByUserId: responsibleUserForAiRequest(req) } : undefined,
claudeLogin: {
storedSessionId: createStoredSessionId ?? null,
@@ -7074,7 +7108,7 @@ export function agentRoutes(
const limit = limitParam ? Math.max(1, Math.min(1000, parseInt(limitParam, 10) || 200)) : undefined;
const summary = req.query.summary === "true" || req.query.summary === "1";
const runs = await heartbeat.list(companyId, agentId, limit, { summary });
res.json(await runRedactions.redactForRuns(companyId, runs));
res.json(await runRedactions.redactForRuns(companyId, await Promise.all(runs.map(run => serializeRunListRow(req, run)))));
});
router.get("/companies/:companyId/provider-traces", async (req, res) => {
@@ -7147,7 +7181,17 @@ export function agentRoutes(
lastOutputStream: heartbeatRuns.lastOutputStream,
lastOutputBytes: heartbeatRuns.lastOutputBytes,
processStartedAt: heartbeatRuns.processStartedAt,
issueId: sql<string | null>`${heartbeatRuns.contextSnapshot} ->> 'issueId'`.as("issueId"),
scopeKind: heartbeatRuns.scopeKind,
issueId: heartbeatRuns.issueId,
inputTokens: sql<number | null>`(${heartbeatRuns.usageJson} ->> 'inputTokens')::numeric`.as("inputTokens"),
cachedInputTokens: sql<number | null>`(${heartbeatRuns.usageJson} ->> 'cachedInputTokens')::numeric`.as("cachedInputTokens"),
outputTokens: sql<number | null>`(${heartbeatRuns.usageJson} ->> 'outputTokens')::numeric`.as("outputTokens"),
totalTokens: sql<number | null>`(${heartbeatRuns.usageJson} ->> 'totalTokens')::numeric`.as("totalTokens"),
costUsd: sql<number | null>`coalesce(
(${heartbeatRuns.resultJson} ->> 'costUsd')::numeric,
(${heartbeatRuns.resultJson} ->> 'cost_usd')::numeric,
(${heartbeatRuns.resultJson} ->> 'total_cost_usd')::numeric
)`.as("costUsd"),
};
const liveRunsQuery = db
@@ -7200,7 +7244,7 @@ export function agentRoutes(
}
const projections = await executionProjectionsForRuns(db, companyId, rows.map(run => run.id));
res.json(await runRedactions.redactForRuns(companyId, await Promise.all(rows.map(async (run) => ({
res.json(await runRedactions.redactForRuns(companyId, await Promise.all(rows.map(async (run) => !(await actorCanReadRun(req, run)) ? redactHeartbeatRunListRow(run) : ({
...heartbeat.decorateActiveRunStatus(run),
agentAppearance: resolveAgentAppearance(run.agentAppearance, run.agentId),
avatarUrl: agentAvatarUrl(resolveAgentAppearance(run.agentAppearance, run.agentId), 512),
@@ -7223,6 +7267,7 @@ export function agentRoutes(
const run = await getAccessibleResource(req, res, heartbeat.getRun(runId), "Heartbeat run not found");
if (!run) return;
if (!(await assertRunTelemetryReadAllowed(req, res, run.companyId))) return;
if (!(await assertRunReadAllowed(req, res, run))) return;
const retryExhaustedReason = await heartbeat.getRetryExhaustedReason(runId);
const decoratedRun = heartbeat.decorateActiveRunStatus(run);
res.json(await runRedactions.redactForRun(
@@ -7240,6 +7285,7 @@ export function agentRoutes(
const runId = readHeartbeatRunId(req);
const existing = await getAccessibleResource(req, res, heartbeat.getRun(runId), "Heartbeat run not found");
if (!existing) return;
if (!(await assertRunReadAllowed(req, res, existing))) return;
const requestId = cancellationRequestId(req.body?.cancellationRequestId);
// Stamp the cancellation as operator-initiated (this route is board-only).
// Recovery reads this to stand down instead of classifying the cancelled
@@ -7479,6 +7525,7 @@ export function agentRoutes(
const runId = readHeartbeatRunId(req);
const existing = await getAccessibleResource(req, res, heartbeat.getRun(runId), "Heartbeat run not found");
if (!existing) return;
if (!(await assertRunReadAllowed(req, res, existing))) return;
const decision = typeof req.body?.decision === "string" ? req.body.decision : "";
if (!["snooze", "continue", "dismissed_false_positive"].includes(decision)) {
res.status(400).json({ error: "Unsupported watchdog decision" });
@@ -7699,6 +7746,7 @@ export function agentRoutes(
const run = await getAccessibleResource(req, res, heartbeat.getRun(runId), "Heartbeat run not found");
if (!run) return;
if (!(await assertRunTelemetryReadAllowed(req, res, run.companyId))) return;
if (!(await assertRunReadAllowed(req, res, run))) return;
const afterSeq = Number(req.query.afterSeq ?? 0);
const limit = Number(req.query.limit ?? 200);
@@ -7718,6 +7766,7 @@ export function agentRoutes(
const run = await getAccessibleResource(req, res, heartbeat.getRunLogAccess(runId), "Heartbeat run not found");
if (!run) return;
if (!(await assertRunTelemetryReadAllowed(req, res, run.companyId))) return;
if (!(await assertRunReadAllowed(req, res, run))) return;
const offset = Number(req.query.offset ?? 0);
const limitBytes = readRunLogLimitBytes(req.query.limitBytes);
@@ -7735,11 +7784,16 @@ export function agentRoutes(
const run = await getAccessibleResource(req, res, heartbeat.getRun(runId), "Heartbeat run not found");
if (!run) return;
if (!(await assertRunTelemetryReadAllowed(req, res, run.companyId))) return;
if (!(await assertRunReadAllowed(req, res, run))) return;
const context = asRecord(run.contextSnapshot);
const executionWorkspaceId = asNonEmptyString(context?.executionWorkspaceId);
const operations = await workspaceOperations.listForRun(runId, executionWorkspaceId);
res.json(redactCurrentUserValue(operations, await getCurrentUserRedactionOptions()));
const visibleOperations = [];
for (const operation of operations) {
if (await canActorReadWorkspaceOperation(db, access, req.actor, operation)) visibleOperations.push(operation);
}
res.json(redactCurrentUserValue(visibleOperations, await getCurrentUserRedactionOptions()));
});
router.get("/workspace-operations/:operationId/log", async (req, res) => {
@@ -7747,6 +7801,10 @@ export function agentRoutes(
const operation = await getAccessibleResource(req, res, workspaceOperations.getById(operationId), "Workspace operation not found");
if (!operation) return;
if (!(await assertRunTelemetryReadAllowed(req, res, operation.companyId))) return;
if (!(await canActorReadWorkspaceOperation(db, access, req.actor, operation))) {
res.status(404).json({ error: "Workspace operation not found" });
return;
}
const offset = Number(req.query.offset ?? 0);
const limitBytes = readRunLogLimitBytes(req.query.limitBytes);
@@ -7805,7 +7863,7 @@ export function agentRoutes(
and(
eq(heartbeatRuns.companyId, issue.companyId),
inArray(heartbeatRuns.status, ["queued", "running"]),
sql`${heartbeatRuns.contextSnapshot} ->> 'issueId' = ${issue.id}`,
eq(heartbeatRuns.issueId, issue.id),
),
)
.orderBy(desc(heartbeatRuns.createdAt));
+1 -1
View File
@@ -39,7 +39,7 @@ export function responsibleUserForAiRequest(req: Request): string | null {
: getActorInfo(req).actorId;
}
async function canManageAiConnections(db: Db, req: Request, companyId: string): Promise<boolean> {
export async function canManageAiConnections(db: Db, req: Request, companyId: string): Promise<boolean> {
const membership = req.actor.memberships?.find((m) => m.companyId === companyId && m.status === "active");
if (membership?.membershipRole === "viewer") return false;
return req.actor.source === "local_implicit" || Boolean(req.actor.isInstanceAdmin)
+11 -1
View File
@@ -22,6 +22,7 @@ import { assertBoard, assertCompanyAccess, getAccessibleResource, getActorInfo,
import { redactEventPayload } from "../redaction.js";
import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";
import { issueService } from "../services/issues.js";
import { approvalReadSqlCondition, canActorReadApproval } from "../services/authorization.js";
import { REVIEW_PATH_RECOVERY_INSTRUCTION } from "../services/recovery/review-path-recovery.js";
function redactApprovalPayload<T extends { payload: Record<string, unknown> }>(approval: T): T {
@@ -45,6 +46,15 @@ export function approvalRoutes(
options: { pluginWorkerManager?: PluginWorkerManager } = {},
) {
const router = Router();
router.param("id", async (req, res, next, id) => {
try {
if (!(await canActorReadApproval(db, req.actor, id))) {
res.status(404).json({ error: "Approval not found" });
return;
}
next();
} catch (error) { next(error); }
});
const svc = approvalService(db);
const access = accessService(db);
const heartbeat = heartbeatService(db, {
@@ -207,7 +217,7 @@ export function approvalRoutes(
assertCompanyAccess(req, companyId);
if (!(await assertApprovalAccessAllowed(req, res, companyId))) return;
const status = req.query.status as string | undefined;
const result = await svc.list(companyId, status);
const result = await svc.list(companyId, status, await approvalReadSqlCondition(db, req.actor));
res.json(result.map((approval) => redactApprovalPayload(approval)));
});
+43 -4
View File
@@ -1,9 +1,13 @@
import { and, eq } from "drizzle-orm";
import { runnerApiResponseReservations, heartbeatRuns, issues, issueAttachments } from "@paperclipai/db";
import { authorizationService } from "../services/authorization.js";
import { canActorReadHeartbeatRun } from "../services/heartbeat-run-privacy.js";
import { Router, type Request, type Response } from "express";
import multer from "multer";
import createDOMPurify from "dompurify";
import { JSDOM } from "jsdom";
import type { Db } from "@paperclipai/db";
import { ASSET_NAMESPACE_RULE, createAssetImageMetadataSchema } from "@paperclipai/shared";
import { ASSET_NAMESPACE_RULE, isUuidLike, createAssetImageMetadataSchema } from "@paperclipai/shared";
import type { StorageService } from "../storage/types.js";
import { assetService, logActivity } from "../services/index.js";
import {
@@ -184,7 +188,7 @@ export function assetRoutes(db: Db, storage: StorageService) {
sha256: stored.sha256,
originalFilename: stored.originalFilename,
createdByAgentId: actor.agentId,
createdByUserId: actor.actorType === "user" ? actor.actorId : null,
createdByUserId: actor.actorType === "user" ? actor.actorId : req.actor.onBehalfOfUserId ?? null,
});
await logActivity(db, {
@@ -198,7 +202,7 @@ export function assetRoutes(db: Db, storage: StorageService) {
entityType: "asset",
entityId: asset.id,
details: {
originalFilename: asset.originalFilename,
...(namespaceSuffix.startsWith("issues/") ? {} : { originalFilename: asset.originalFilename }),
contentType: asset.contentType,
byteSize: asset.byteSize,
},
@@ -327,6 +331,41 @@ export function assetRoutes(db: Db, storage: StorageService) {
const assetId = req.params.assetId as string;
const asset = await getAccessibleResource(req, res, svc.getById(assetId), "Asset not found");
if (!asset) return;
const access = authorizationService(db);
// Persisted storage namespaces retain provenance after attachment rows are deleted.
const objectParts = asset.objectKey.split("/");
const isDraftImage = objectParts[1] === "assets" && objectParts[2] === "issues" && objectParts[3] === "drafts";
const namespace = objectParts[1] === "assets" ? objectParts[2] : objectParts[1];
const sourceIssueId = objectParts[1] === "assets" ? objectParts[3] : objectParts[2];
const sourceExists = namespace !== "issues" || isDraftImage || (sourceIssueId && isUuidLike(sourceIssueId) && await db.select({ id: issues.id }).from(issues)
.where(and(eq(issues.id, sourceIssueId), eq(issues.companyId, asset.companyId))).limit(1).then(rows => rows.length > 0));
if (namespace === "issues" && !isDraftImage && (!sourceExists || !(await access.decide({ actor: req.actor, action: "issue:read",
resource: { type: "issue", companyId: asset.companyId, issueId: sourceIssueId } })).allowed)) {
res.status(404).json({ error: "Asset not found" }); return;
}
const captures = await db.select({ run: heartbeatRuns }).from(runnerApiResponseReservations)
.leftJoin(heartbeatRuns, eq(heartbeatRuns.id, runnerApiResponseReservations.runId))
.where(and(eq(runnerApiResponseReservations.assetId, asset.id), eq(runnerApiResponseReservations.companyId, asset.companyId)));
if (namespace === "runner-api" && !captures.length) { res.status(404).json({ error: "Asset not found" }); return; }
for (const { run } of captures) {
if (!run || !(await canActorReadHeartbeatRun(db, access, req.actor, run))) {
res.status(404).json({ error: "Asset not found" }); return;
}
}
const attachments = await db.select({ issueId: issueAttachments.issueId }).from(issueAttachments)
.where(and(eq(issueAttachments.assetId, asset.id), eq(issueAttachments.companyId, asset.companyId)));
if (isDraftImage && !attachments.length && !(req.actor.type === "board"
? req.actor.source === "local_implicit" || req.actor.isInstanceAdmin || req.actor.userId === asset.createdByUserId
: req.actor.type === "agent" && req.actor.agentId === asset.createdByAgentId
&& (!asset.createdByUserId || req.actor.onBehalfOfUserId === asset.createdByUserId))) {
res.status(404).json({ error: "Asset not found" }); return;
}
for (const attachment of attachments) {
if (!(await access.decide({ actor: req.actor, action: "issue:read", resource: {
type: "issue", companyId: asset.companyId, issueId: attachment.issueId,
} })).allowed) { res.status(404).json({ error: "Asset not found" }); return; }
}
// Use the persisted size only after resource authorization. Single ranges
// keep saved API text pages bounded all the way to disk or object storage.
@@ -354,7 +393,7 @@ export function assetRoutes(db: Db, storage: StorageService) {
res.status(206);
res.setHeader("Content-Range", `bytes ${range.start}-${range.end}/${asset.byteSize}`);
}
res.setHeader("Cache-Control", "private, max-age=60");
res.setHeader("Cache-Control", "private, no-store");
res.setHeader("X-Content-Type-Options", "nosniff");
if (!inlineSafe) {
res.setHeader("Content-Security-Policy", "sandbox; default-src 'none'");
+1
View File
@@ -41,6 +41,7 @@ export function attentionRoutes(db: Db) {
const feed = await svc.list(companyId, {
userId: req.actor.userId,
includeDismissed,
actor: req.actor,
archived,
all,
allowUnscopedAll: all,
+4 -1
View File
@@ -55,6 +55,7 @@ import {
accessService,
agentService,
budgetService,
heartbeatService,
buildExportFidelityReport,
collectExportFidelityCounts,
companyArtifactsService,
@@ -278,7 +279,9 @@ export function companyRoutes(db: Db, storage?: StorageService, options?: Compan
const router = Router();
const importTransferSpoolRoot =
options?.importTransferSpoolRoot ?? resolveDefaultImportTransferSpoolRoot();
const svc = companyService(db);
const svc = companyService(db, {
cancelWorkForScope: (scope) => heartbeatService(db).cancelBudgetScopeWork(scope),
});
const agents = agentService(db);
const portability = companyPortabilityService(db, storage);
const access = accessService(db);
+82 -75
View File
@@ -1,4 +1,10 @@
import { importProviderDailyCosts } from "../services/provider-billing-import.js";
import { importProviderCostsSchema } from "@paperclipai/shared";
import { accountingIntegrityService } from "../services/accounting-integrity.js";
import { billingReconciliationService } from "../services/billing-reconciliation.js";
import { adjustCostSchema, importBillingInvoiceSchema, repairAccountingSchema, retryAccountingSchema } from "@paperclipai/shared";
import { Router } from "express";
import { z } from "zod";
import type { Db } from "@paperclipai/db";
import {
createCostEventSchema,
@@ -18,28 +24,37 @@ import {
issueService,
heartbeatService,
accessService,
logActivity,
} from "../services/index.js";
import { assertBoard, assertCompanyAccess, getAccessibleResource, getActorInfo } from "./authz.js";
import { fetchCompanyQuotaWindows } from "../services/quota-windows.js";
import { badRequest } from "../errors.js";
import { badRequest, forbidden } from "../errors.js";
import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";
const reportDateSchema = z.union([z.iso.datetime({ offset: true }), z.iso.date()]);
export function parseCostDateRange(query: Record<string, unknown>) {
if (query.period !== undefined && query.period !== "all" && query.period !== "month") throw badRequest("invalid 'period'");
if (query.period === "all") {
if (query.from !== undefined || query.to !== undefined) throw badRequest("all-time period cannot have date bounds");
return { allTime: true };
}
if (query.from !== undefined && !reportDateSchema.safeParse(query.from).success) throw badRequest("invalid 'from' date");
if (query.to !== undefined && !reportDateSchema.safeParse(query.to).success) throw badRequest("invalid 'to' date");
const fromRaw = query.from as string | undefined;
const toRaw = query.to as string | undefined;
const from = fromRaw ? new Date(fromRaw) : undefined;
const to = toRaw ? new Date(toRaw) : undefined;
if (from && isNaN(from.getTime())) throw badRequest("invalid 'from' date");
if (to && isNaN(to.getTime())) throw badRequest("invalid 'to' date");
if (from && to && from > to) throw badRequest("from must not be after to");
return (from || to) ? { from, to } : undefined;
}
export function parseCostLimit(query: Record<string, unknown>) {
const raw = Array.isArray(query.limit) ? query.limit[0] : query.limit;
const raw = query.limit;
if (raw == null || raw === "") return 100;
const limit = typeof raw === "number" ? raw : Number.parseInt(String(raw), 10);
if (!Number.isFinite(limit) || limit <= 0 || limit > 500) {
const limit = typeof raw === "number" || typeof raw === "string" ? Number(raw) : Number.NaN;
if (!Number.isInteger(limit) || limit <= 0 || limit > 500) {
throw badRequest("invalid 'limit' value");
}
return limit;
@@ -120,22 +135,11 @@ export function costRoutes(
return;
}
const actor = getActorInfo(req);
const event = await costs.createEvent(companyId, {
...req.body,
occurredAt: new Date(req.body.occurredAt),
});
const actor = getActorInfo(req);
await logActivity(db, {
companyId,
actorType: actor.actorType,
actorId: actor.actorId,
agentId: actor.agentId,
action: "cost.reported",
entityType: "cost_event",
entityId: event.id,
details: { costCents: event.costCents, model: event.model },
});
}, { actorType: actor.actorType, actorId: actor.actorId, agentId: actor.agentId });
res.status(201).json(event);
});
@@ -145,27 +149,11 @@ export function costRoutes(
assertCompanyAccess(req, companyId);
assertBoard(req);
const actor = getActorInfo(req);
const event = await finance.createEvent(companyId, {
...req.body,
occurredAt: new Date(req.body.occurredAt),
});
const actor = getActorInfo(req);
await logActivity(db, {
companyId,
actorType: actor.actorType,
actorId: actor.actorId,
agentId: actor.agentId,
action: "finance_event.reported",
entityType: "finance_event",
entityId: event.id,
details: {
amountCents: event.amountCents,
biller: event.biller,
eventKind: event.eventKind,
direction: event.direction,
},
});
}, { actorType: actor.actorType, actorId: actor.actorId, agentId: actor.agentId });
res.status(201).json(event);
});
@@ -189,6 +177,14 @@ export function costRoutes(
res.json(summary);
});
router.get("/companies/:companyId/costs/by-user", async (req, res) => {
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
if (!(await assertCompanyCostReadAllowed(req, res, companyId))) return;
const range = parseCostDateRange(req.query);
res.json(await costs.byUser(companyId, range));
});
router.get("/companies/:companyId/costs/by-agent", async (req, res) => {
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
@@ -331,34 +327,19 @@ export function costRoutes(
assertBoard(req);
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
const company = await companies.update(companyId, { budgetMonthlyCents: req.body.budgetMonthlyCents });
if (!company) {
res.status(404).json({ error: "Company not found" });
return;
}
await logActivity(db, {
companyId,
actorType: "user",
actorId: req.actor.userId ?? "board",
action: "company.budget_updated",
entityType: "company",
entityId: companyId,
details: { budgetMonthlyCents: req.body.budgetMonthlyCents },
});
await budgets.upsertPolicy(
companyId,
{
scopeType: "company",
scopeId: companyId,
amount: req.body.budgetMonthlyCents,
isActive: req.body.budgetMonthlyCents > 0,
windowKind: "calendar_month_utc",
},
req.actor.userId ?? "board",
);
res.json(company);
res.json(await companies.getById(companyId));
});
router.patch("/agents/:agentId/budgets", validate(updateBudgetSchema), async (req, res) => {
@@ -368,37 +349,63 @@ export function costRoutes(
assertBoard(req);
const updated = await agents.update(agentId, { budgetMonthlyCents: req.body.budgetMonthlyCents });
if (!updated) {
res.status(404).json({ error: "Agent not found" });
return;
}
const actor = getActorInfo(req);
await logActivity(db, {
companyId: updated.companyId,
actorType: actor.actorType,
actorId: actor.actorId,
agentId: actor.agentId,
action: "agent.budget_updated",
entityType: "agent",
entityId: updated.id,
details: { budgetMonthlyCents: updated.budgetMonthlyCents },
});
await budgets.upsertPolicy(
updated.companyId,
agent.companyId,
{
scopeType: "agent",
scopeId: updated.id,
amount: updated.budgetMonthlyCents,
scopeId: agent.id,
amount: req.body.budgetMonthlyCents,
isActive: req.body.budgetMonthlyCents > 0,
windowKind: "calendar_month_utc",
},
req.actor.type === "board" ? req.actor.userId ?? "board" : null,
);
res.json(updated);
res.json(await agents.getById(agentId));
});
const integrity = accountingIntegrityService(db, budgetHooks);
const billing = billingReconciliationService(db, budgetHooks);
// Operational accounting evidence and repairs are board-only. These payloads
// can contain company-wide billing identifiers even for an agent's own run.
router.use("/companies/:companyId/accounting", (req, _res, next) => {
assertCompanyAccess(req, req.params.companyId as string); assertBoard(req); next();
});
router.post("/companies/:companyId/accounting/provider-costs/import", (req, _res, next) => {
// Unlike ledger inspection, this operation discloses a stored credential
// to a provider. Ordinary company membership does not authorize that use.
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
assertBoard(req);
const membership = req.actor.memberships?.find((item) => item.companyId === companyId);
if (req.actor.source !== "local_implicit" && !req.actor.isInstanceAdmin
&& !(membership?.status === "active" && ["owner", "admin"].includes(String(membership.membershipRole)))) {
throw forbidden("Company admin access required to import provider billing.");
}
next();
}, validate(importProviderCostsSchema), async (req, res) => {
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
assertBoard(req);
const result = await importProviderDailyCosts(db, companyId, req.body, getActorInfo(req).actorId);
res.json(result);
});
router.get("/companies/:companyId/accounting/health", async (req, res) => res.json(await integrity.health(req.params.companyId as string)));
router.get("/companies/:companyId/accounting/inspect", async (req, res) => res.json(await integrity.inspect(req.params.companyId as string)));
router.post("/companies/:companyId/accounting/repair", validate(repairAccountingSchema), async (req, res) =>
res.json(await integrity.repair(req.params.companyId as string, req.body.fingerprint, req.body.reason, getActorInfo(req).actorId)));
router.post("/companies/:companyId/accounting/retry", validate(retryAccountingSchema), async (req, res) =>
res.json(await integrity.retry(req.params.companyId as string, req.body.runId, getActorInfo(req).actorId)));
router.get("/companies/:companyId/accounting/invoices", async (req, res) => res.json(await billing.list(req.params.companyId as string)));
router.post("/companies/:companyId/accounting/invoices", validate(importBillingInvoiceSchema), async (req, res) =>
res.status(201).json(await billing.importInvoice(req.params.companyId as string, req.body, getActorInfo(req).actorId)));
router.get("/companies/:companyId/accounting/invoices/:invoiceId", async (req, res) =>
res.json(await billing.reconcile(req.params.companyId as string, req.params.invoiceId as string)));
router.get("/companies/:companyId/accounting/events/:eventId/adjustments", async (req, res) =>
res.json(await billing.adjustments(req.params.companyId as string, req.params.eventId as string)));
router.post("/companies/:companyId/accounting/events/:eventId/adjustments", validate(adjustCostSchema), async (req, res) =>
res.status(201).json(await billing.adjust(req.params.companyId as string, req.params.eventId as string, req.body, getActorInfo(req).actorId)));
return router;
}
+46
View File
@@ -0,0 +1,46 @@
import { Router } from "express";
import type { Db } from "@paperclipai/db";
import { DECISION_TEST_REQUEST, updateDecisionModelSchema } from "@paperclipai/shared";
import { assertBoard, assertCompanyAccess, getActorInfo } from "./authz.js";
import { canManageAiConnections } from "./ai-connections.js";
import { forbidden } from "../errors.js";
import { validate } from "../middleware/validate.js";
import { decisionModelService, settingsDecisionTest } from "../services/decision-models.js";
import { heartbeatService } from "../services/heartbeat.js";
import { parseCostDateRange, parseCostLimit } from "./costs.js";
export function decisionModelRoutes(db: Db) {
const router = Router();
const service = decisionModelService(db, { budgetHooks: { cancelWorkForScope: heartbeatService(db).cancelBudgetScopeWork } });
router.get("/companies/:companyId/decision-model", async (req, res) => {
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId); assertBoard(req);
const canManage = await canManageAiConnections(db, req, companyId);
if (!canManage) { res.json({ canManage, settings: null, choices: [] }); return; }
res.json({ canManage, settings: await service.settings(companyId), choices: await service.choices(companyId, getActorInfo(req).actorId) });
});
router.put("/companies/:companyId/decision-model", validate(updateDecisionModelSchema), async (req, res) => {
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId); assertBoard(req);
if (!(await canManageAiConnections(db, req, companyId))) throw forbidden("Manage connections permission is required");
res.json(await service.configure(companyId, getActorInfo(req).actorId, req.body));
});
router.get("/companies/:companyId/decision-model/availability", async (req, res) => {
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
res.json(await service.availability({ companyId, actor: req.actor, feature: settingsDecisionTest }));
});
router.post("/companies/:companyId/decision-model/test", async (req, res) => {
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId); assertBoard(req);
if (!(await canManageAiConnections(db, req, companyId))) throw forbidden("Manage connections permission is required");
// The client cannot supply a prompt, model, identity, or background flag.
res.json(await service.decide({ companyId, actor: req.actor, feature: settingsDecisionTest }, DECISION_TEST_REQUEST));
});
router.get("/companies/:companyId/decision-model/history", async (req, res) => {
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
res.json(await service.history(companyId, req.actor, { ...parseCostDateRange(req.query), limit: parseCostLimit(req.query) }));
});
return router;
}
+14 -2
View File
@@ -1,6 +1,7 @@
import { Router, type Request, type Response } from "express";
import { z } from "zod";
import type { Db } from "@paperclipai/db";
import { authorizationService, issueReadSqlCondition } from "../services/authorization.js";
import { validate } from "../middleware/validate.js";
import { decisionTrainingService, logActivity } from "../services/index.js";
import { assertBoard, assertCompanyAccess, getActorInfo, hasCompanyAccess } from "./authz.js";
@@ -52,6 +53,14 @@ function requireExampleOwner(res: Response, userId: string, createdByUserId: str
export function decisionTrainingRoutes(db: Db) {
const router = Router();
const svc = decisionTrainingService(db);
async function canRead(req: Request, companyId: string, issueId: string) {
return (await authorizationService(db).decide({ actor: req.actor, action: "issue:read", resource: { type: "issue", companyId, issueId } })).allowed;
}
async function requireRead(req: Request, res: Response, companyId: string, issueId: string) {
if (await canRead(req, companyId, issueId)) return true;
res.status(404).json({ error: "Decision training source not found" });
return false;
}
router.post(
"/companies/:companyId/decision-training",
@@ -61,6 +70,7 @@ export function decisionTrainingRoutes(db: Db) {
assertCompanyAccess(req, companyId);
const userId = requireHumanUser(req, res);
if (!userId) return;
if (!(await requireRead(req, res, companyId, req.body.issueId))) return;
const example = await svc.create({
companyId,
@@ -97,6 +107,7 @@ export function decisionTrainingRoutes(db: Db) {
assertCompanyAccess(req, companyId);
const userId = requireHumanUser(req, res);
if (!userId) return;
if (!(await requireRead(req, res, companyId, req.body.issueId))) return;
const preview = await svc.preview({
companyId,
sourceKind: req.body.sourceKind,
@@ -126,6 +137,7 @@ export function decisionTrainingRoutes(db: Db) {
return;
}
res.json(await svc.list(companyId, {
readCondition: await issueReadSqlCondition(db, req.actor),
projectId: parsed.data.project,
kind: parsed.data.kind,
author: parsed.data.author,
@@ -137,7 +149,7 @@ export function decisionTrainingRoutes(db: Db) {
const companyId = req.params.companyId as string;
assertBoard(req);
assertCompanyAccess(req, companyId);
const rows = await svc.list(companyId);
const rows = await svc.list(companyId, { readCondition: await issueReadSqlCondition(db, req.actor) });
const body = rows
.map(({ example }) => JSON.stringify({
retentionPolicy: example.retentionPolicy,
@@ -165,7 +177,7 @@ export function decisionTrainingRoutes(db: Db) {
const exampleId = parseExampleId(req, res);
if (!exampleId) return;
const example = await svc.getById(exampleId);
if (!example || !hasCompanyAccess(req, example.companyId)) {
if (!example || !hasCompanyAccess(req, example.companyId) || !(await canRead(req, example.companyId, example.issueId))) {
res.status(404).json({ error: "Decision training example not found" });
return;
}
+22 -2
View File
@@ -1,3 +1,5 @@
import { canActorReadWorkspaceOperation } from "../services/heartbeat-run-privacy.js";
import { canActorReadExecutionWorkspace, executionWorkspaceReadSqlCondition } from "../services/authorization.js";
import { spawn } from "node:child_process";
import { accessSync, constants as fsConstants, existsSync, readFileSync } from "node:fs";
import path from "node:path";
@@ -96,6 +98,12 @@ export function executionWorkspaceRoutes(db: Db, opts: { pluginWorkerManager?: P
pluginWorkerManager: opts.pluginWorkerManager,
});
async function assertWorkspacePrivacy(req: Request, res: Response, id: string) {
if (await canActorReadExecutionWorkspace(db, req.actor, id)) return true;
res.status(404).json({ error: "Execution workspace not found" });
return false;
}
async function assertExecutionWorkspaceReadAllowed(req: Request, res: Response, companyId: string) {
const decision = await access.decide({
actor: req.actor,
@@ -123,6 +131,7 @@ export function executionWorkspaceRoutes(db: Db, opts: { pluginWorkerManager?: P
assertCompanyAccess(req, companyId);
if (!(await assertExecutionWorkspaceReadAllowed(req, res, companyId))) return;
const filters = {
readCondition: await executionWorkspaceReadSqlCondition(db, req.actor),
projectId: req.query.projectId as string | undefined,
projectWorkspaceId: req.query.projectWorkspaceId as string | undefined,
issueId: req.query.issueId as string | undefined,
@@ -149,7 +158,7 @@ export function executionWorkspaceRoutes(db: Db, opts: { pluginWorkerManager?: P
return;
}
const overview = await svc.listOverview(companyId, parsed.data);
const overview = await svc.listOverview(companyId, parsed.data, await executionWorkspaceReadSqlCondition(db, req.actor));
res.json(overview);
});
@@ -157,6 +166,7 @@ export function executionWorkspaceRoutes(db: Db, opts: { pluginWorkerManager?: P
const id = req.params.id as string;
const workspace = await getAccessibleResource(req, res, svc.getById(id), "Execution workspace not found");
if (!workspace) return;
if (!(await assertWorkspacePrivacy(req, res, workspace.id))) return;
if (!(await assertExecutionWorkspaceReadAllowed(req, res, workspace.companyId))) return;
res.json(workspace);
});
@@ -165,6 +175,7 @@ export function executionWorkspaceRoutes(db: Db, opts: { pluginWorkerManager?: P
const id = req.params.id as string;
const workspace = await getAccessibleResource(req, res, svc.getById(id), "Execution workspace not found");
if (!workspace) return;
if (!(await assertWorkspacePrivacy(req, res, workspace.id))) return;
if (!(await assertExecutionWorkspaceReadAllowed(req, res, workspace.companyId))) return;
const readiness = await svc.getCloseReadiness(id);
if (!readiness) {
@@ -187,6 +198,7 @@ export function executionWorkspaceRoutes(db: Db, opts: { pluginWorkerManager?: P
assertBoard(req);
const workspace = await getAccessibleResource(req, res, svc.getById(id), "Execution workspace not found");
if (!workspace) return;
if (!(await assertWorkspacePrivacy(req, res, workspace.id))) return;
// Opening a workspace board is a runtime-control-grade action: it hands the
// caller an authenticated session inside the cloned instance.
if (!(await assertRuntimeManageAllowed(req, res, workspace.companyId))) return;
@@ -259,9 +271,14 @@ export function executionWorkspaceRoutes(db: Db, opts: { pluginWorkerManager?: P
const id = req.params.id as string;
const workspace = await getAccessibleResource(req, res, svc.getById(id), "Execution workspace not found");
if (!workspace) return;
if (!(await assertWorkspacePrivacy(req, res, workspace.id))) return;
if (!(await assertExecutionWorkspaceReadAllowed(req, res, workspace.companyId))) return;
const operations = await workspaceOperationsSvc.listForExecutionWorkspace(id);
res.json(operations);
const visibleOperations = [];
for (const operation of operations) {
if (await canActorReadWorkspaceOperation(db, access, req.actor, operation)) visibleOperations.push(operation);
}
res.json(visibleOperations);
});
async function handleExecutionWorkspaceRuntimeCommand(req: Request, res: Response) {
@@ -274,6 +291,7 @@ export function executionWorkspaceRoutes(db: Db, opts: { pluginWorkerManager?: P
const existing = await getAccessibleResource(req, res, svc.getById(id), "Execution workspace not found");
if (!existing) return;
if (!(await assertWorkspacePrivacy(req, res, existing.id))) return;
if (!(await assertRuntimeManageAllowed(req, res, existing.companyId))) return;
const authorization = await assertCanManageExecutionWorkspaceRuntimeServices(db, req, {
@@ -1050,6 +1068,7 @@ export function executionWorkspaceRoutes(db: Db, opts: { pluginWorkerManager?: P
const id = req.params.id as string;
const existing = await getAccessibleResource(req, res, svc.getById(id), "Execution workspace not found");
if (!existing) return;
if (!(await assertWorkspacePrivacy(req, res, existing.id))) return;
assertBoard(req);
if (!(await assertRuntimeManageAllowed(req, res, existing.companyId))) return;
@@ -1139,6 +1158,7 @@ export function executionWorkspaceRoutes(db: Db, opts: { pluginWorkerManager?: P
const id = req.params.id as string;
const existing = await getAccessibleResource(req, res, svc.getById(id), "Execution workspace not found");
if (!existing) return;
if (!(await assertWorkspacePrivacy(req, res, existing.id))) return;
if (!(await assertRuntimeManageAllowed(req, res, existing.companyId))) return;
assertNoAgentHostWorkspaceCommandMutation(
req,
+10 -10
View File
@@ -355,7 +355,7 @@ export function fileResourceRoutes(db: Db, opts: {
availabilityLimiter?: FileResourceLimiter;
} = {}) {
const router = Router();
const svc = opts.service ?? workspaceFileResourceService(db);
const serviceFor = (req: Request) => opts.service ?? workspaceFileResourceService(db, req.actor);
const limiter = opts.limiter ?? createFileResourceLimiter();
const listLimiter = opts.listLimiter ?? createFileResourceListLimiter();
const availabilityLimiter = opts.availabilityLimiter ?? createFileResourceAvailabilityLimiter();
@@ -468,7 +468,7 @@ export function fileResourceRoutes(db: Db, opts: {
throw error;
}
const issue = await svc.getIssue(req.params.issueId);
const issue = await serviceFor(req).getIssue(req.params.issueId);
const actor = getActorInfo(req);
if (!hasCompanyAccess(req, issue.companyId)) {
const error = notFound("Issue not found");
@@ -501,7 +501,7 @@ export function fileResourceRoutes(db: Db, opts: {
let release: (() => void) | null = null;
try {
release = availabilityLimiter.acquire(limiterKey(issue.companyId, actor.actorId, req.params.issueId));
const result = await svc.availability(req.params.issueId, body, { issue });
const result = await serviceFor(req).availability(req.params.issueId, body, { issue });
await logAvailabilityAttempt({
companyId: issue.companyId,
actor,
@@ -544,7 +544,7 @@ export function fileResourceRoutes(db: Db, opts: {
}
throw error;
}
const issue = await svc.getIssue(req.params.issueId);
const issue = await serviceFor(req).getIssue(req.params.issueId);
const actor = getActorInfo(req);
try {
if (!hasCompanyAccess(req, issue.companyId)) {
@@ -595,7 +595,7 @@ export function fileResourceRoutes(db: Db, opts: {
const requestAbort = requestAbortController(req, res);
try {
const result = await svc.list(req.params.issueId, query, {
const result = await serviceFor(req).list(req.params.issueId, query, {
issue,
scanContext: {
signal: requestAbort.signal,
@@ -677,7 +677,7 @@ export function fileResourceRoutes(db: Db, opts: {
}
throw error;
}
const issue = await svc.getIssue(req.params.issueId);
const issue = await serviceFor(req).getIssue(req.params.issueId);
const actor = getActorInfo(req);
try {
if (!hasCompanyAccess(req, issue.companyId)) {
@@ -730,7 +730,7 @@ export function fileResourceRoutes(db: Db, opts: {
throw error;
}
try {
const result = await svc.resolve(req.params.issueId, query, { issue });
const result = await serviceFor(req).resolve(req.params.issueId, query, { issue });
await logActivity(db, {
companyId: issue.companyId,
actorType: actor.actorType,
@@ -789,7 +789,7 @@ export function fileResourceRoutes(db: Db, opts: {
}
throw error;
}
const issue = await svc.getIssue(req.params.issueId);
const issue = await serviceFor(req).getIssue(req.params.issueId);
const actor = getActorInfo(req);
try {
if (!hasCompanyAccess(req, issue.companyId)) {
@@ -842,7 +842,7 @@ export function fileResourceRoutes(db: Db, opts: {
if (parseBooleanQuery(req.query.download)) {
let result: Awaited<ReturnType<WorkspaceFileResourceService["prepareDownload"]>> | null = null;
try {
result = await svc.prepareDownload(req.params.issueId, query, { issue });
result = await serviceFor(req).prepareDownload(req.params.issueId, query, { issue });
} catch (error) {
await logDeniedAttempt({
companyId: issue.companyId,
@@ -892,7 +892,7 @@ export function fileResourceRoutes(db: Db, opts: {
let result: WorkspaceFileContent | null = null;
try {
result = await svc.readContent(req.params.issueId, query, { issue });
result = await serviceFor(req).readContent(req.params.issueId, query, { issue });
} catch (error) {
await logDeniedAttempt({
companyId: issue.companyId,
+37 -1
View File
@@ -1,5 +1,5 @@
import { Router } from "express";
import type { Request } from "express";
import type { Request, Response } from "express";
import {
issues as issueRows,
type Db,
@@ -15,6 +15,7 @@ import {
} from "@paperclipai/shared";
import { validate } from "../middleware/validate.js";
import {
accessService,
heartbeatService,
issueService,
issueTreeControlService,
@@ -55,6 +56,35 @@ export function issueTreeControlRoutes(
const heartbeat = heartbeatService(db, {
pluginWorkerManager: options.pluginWorkerManager,
});
const access = accessService(db);
async function assertIssueReadAllowed(req: Request, res: Response, issue: {
id: string;
companyId: string;
projectId?: string | null;
parentId?: string | null;
assigneeAgentId?: string | null;
assigneeUserId?: string | null;
status?: string;
}) {
const decision = await access.decide({
actor: req.actor,
action: "issue:read",
resource: {
type: "issue",
companyId: issue.companyId,
issueId: issue.id,
projectId: issue.projectId ?? null,
parentIssueId: issue.parentId ?? null,
assigneeAgentId: issue.assigneeAgentId ?? null,
assigneeUserId: issue.assigneeUserId ?? null,
status: issue.status ?? "backlog",
},
});
if (decision.allowed) return true;
res.status(404).json({ error: "Root issue not found" });
return false;
}
async function resolveRootIssue(req: Request) {
const rootIssueId = req.params.id as string;
@@ -66,6 +96,7 @@ export function issueTreeControlRoutes(
assertBoard(req);
const root = await getAccessibleResource(req, res, resolveRootIssue(req), "Root issue not found");
if (!root) return;
if (!(await assertIssueReadAllowed(req, res, root))) return;
const preview = await treeControlSvc.preview(root.companyId, root.id, req.body);
const actor = getActorInfo(req);
@@ -93,6 +124,7 @@ export function issueTreeControlRoutes(
assertBoard(req);
const root = await getAccessibleResource(req, res, resolveRootIssue(req), "Root issue not found");
if (!root) return;
if (!(await assertIssueReadAllowed(req, res, root))) return;
const actor = getActorInfo(req);
const actorInput = {
@@ -334,6 +366,7 @@ export function issueTreeControlRoutes(
const issueId = req.params.id as string;
const issue = await getAccessibleResource(req, res, issuesSvc.getById(issueId), "Issue not found");
if (!issue) return;
if (!(await assertIssueReadAllowed(req, res, issue))) return;
const activePauseHold = await treeControlSvc.getActivePauseHoldGate(issue.companyId, issue.id);
res.json({ activePauseHold });
});
@@ -342,6 +375,7 @@ export function issueTreeControlRoutes(
assertBoard(req);
const root = await getAccessibleResource(req, res, resolveRootIssue(req), "Root issue not found");
if (!root) return;
if (!(await assertIssueReadAllowed(req, res, root))) return;
const statusParam = typeof req.query.status === "string" ? req.query.status : null;
const modeParam = typeof req.query.mode === "string" ? req.query.mode : null;
const includeMembers = req.query.includeMembers === "true";
@@ -360,6 +394,7 @@ export function issueTreeControlRoutes(
assertBoard(req);
const root = await getAccessibleResource(req, res, resolveRootIssue(req), "Root issue not found");
if (!root) return;
if (!(await assertIssueReadAllowed(req, res, root))) return;
const holdId = req.params.holdId as string;
if (!isUuidLike(holdId)) {
@@ -387,6 +422,7 @@ export function issueTreeControlRoutes(
"Root issue not found",
);
if (!root) return;
if (!(await assertIssueReadAllowed(req, res, root))) return;
const holdId = req.params.holdId as string;
if (!isUuidLike(holdId)) {
File diff suppressed because it is too large. Load diff
+234 -3
View File
@@ -7,6 +7,7 @@ import { Router } from "express";
import { z } from "zod";
import {
createAiConnectionSchema,
updateDecisionModelSchema,
aiConnectionPoolConfigSchema,
aiConnectionLoginIntentSchema,
localAiConnectionSchema,
@@ -31,6 +32,7 @@ import {
createAgentSchema,
createAgentHireSchema,
updateAgentSchema,
updatePrimaryAgentSchema,
updateAgentPermissionsSchema,
updateAgentInstructionsPathSchema,
updateAgentInstructionsBundleSchema,
@@ -70,6 +72,7 @@ import {
// Project
createProjectSchema,
updateProjectSchema,
addProjectAccessMemberSchema,
createProjectWorkspaceSchema,
updateProjectWorkspaceSchema,
// Company
@@ -127,6 +130,11 @@ import {
updateBudgetSchema,
upsertBudgetPolicySchema,
resolveBudgetIncidentSchema,
repairAccountingSchema,
retryAccountingSchema,
importBillingInvoiceSchema,
importProviderCostsSchema,
adjustCostSchema,
// Sidebar
upsertSidebarOrderPreferenceSchema,
// Announcements
@@ -1327,6 +1335,7 @@ const PUBLIC_OPERATIONS = new Set([
]);
const BOARD_ONLY_PREFIXES = [
"/api/companies/{companyId}/accounting/",
"/api/announcements/",
"/api/auth/",
"/api/admin/",
@@ -1347,6 +1356,9 @@ const browserUseOperations = [
] as const;
const BOARD_ONLY_OPERATIONS = new Set([
"GET /api/companies/{companyId}/decision-model",
"PUT /api/companies/{companyId}/decision-model",
"POST /api/companies/{companyId}/decision-model/test",
...browserUseOperations.map(([method, path]) => `${method.toUpperCase()} ${path}`),
"GET /api/companies/{companyId}/ai-connections",
"POST /api/companies/{companyId}/ai-connections",
@@ -1399,9 +1411,13 @@ const BOARD_ONLY_OPERATIONS = new Set([
"DELETE /api/board-api-keys/{keyId}",
"POST /api/bootstrap/claim",
"GET /api/companies/{companyId}/resource-memberships/me",
"GET /api/companies/{companyId}/primary-agent/me",
"PUT /api/companies/{companyId}/primary-agent/me",
"PUT /api/companies/{companyId}/resource-memberships/me/agents/{agentId}",
"PUT /api/companies/{companyId}/resource-memberships/me/documents/{documentId}",
"PUT /api/companies/{companyId}/resource-memberships/me/projects/{projectId}",
"POST /api/projects/{id}/access-members",
"DELETE /api/projects/{id}/access-members/{memberId}",
"GET /api/companies/{companyId}/secret-provider-configs",
"POST /api/companies/{companyId}/secret-provider-configs",
"GET /api/companies/{companyId}/secret-providers/health",
@@ -1632,6 +1648,7 @@ const CREATED_OPERATIONS = new Set([
"POST /api/issues/{id}/comments",
"POST /api/companies/{companyId}/issues/{issueId}/attachments",
"POST /api/companies/{companyId}/projects",
"POST /api/projects/{id}/access-members",
"POST /api/projects/{id}/workspaces",
"POST /api/companies/{companyId}/routines",
"POST /api/companies/{companyId}/folders",
@@ -1953,6 +1970,28 @@ registry.registerPath({
},
});
registry.registerPath({
method: "post",
path: "/api/issues/{id}/access-grants",
tags: ["issues"],
summary: "Grant a user or agent access to a private issue subtree",
request: {
params: z.object({ id: z.string() }),
body: jsonBody(z.object({
subjectType: z.enum(["user", "agent"]),
subjectId: z.string().min(1),
}).strict()),
},
responses: {
200: r.ok(),
201: r.ok(),
401: r.unauthorized,
403: r.forbidden,
404: r.notFound,
409: r.conflict,
},
});
registry.registerPath({
method: "get",
path: "/api/openapi.json",
@@ -4302,6 +4341,52 @@ registry.registerPath({
responses: { 200: r.ok(), 401: r.unauthorized },
});
registry.registerPath({
method: "get",
path: "/api/issues/{id}/privacy-constraints",
tags: ["issues"],
summary: "Get task privacy action constraints for an authorized manager",
description: "Returns action hints without disclosing protected parent or project identity. Visibility writes recheck the current rules under the privacy-tree lock.",
request: { params: z.object({ id: z.string() }) },
responses: {
200: r.ok(z.object({
publicBlockedBy: z.enum(["parent", "project"]).nullable(),
leavesPersonalProject: z.boolean(),
}).strict()),
401: r.unauthorized,
403: r.forbidden,
404: r.notFound,
},
});
registry.registerPath({
method: "get",
path: "/api/issues/{id}/access-grants",
tags: ["issues"],
summary: "List issue access grants",
request: { params: z.object({ id: z.string() }) },
responses: {
200: r.ok(),
401: r.unauthorized,
403: r.forbidden,
404: r.notFound,
},
});
registry.registerPath({
method: "post",
path: "/api/issues/{id}/access-grants/{grantId}/revoke",
tags: ["issues"],
summary: "Revoke an issue access grant",
request: { params: z.object({ id: z.string(), grantId: z.string() }) },
responses: {
200: r.ok(),
401: r.unauthorized,
403: r.forbidden,
404: r.notFound,
},
});
registry.registerPath({
method: "get",
path: "/api/issues/{id}/approvals",
@@ -4673,6 +4758,49 @@ registry.registerPath({
responses: { 200: r.ok(), 401: r.unauthorized },
});
registry.registerPath({
method: "get",
path: "/api/projects/{id}/access-members",
tags: ["projects"],
summary: "List project access members",
request: { params: z.object({ id: z.string() }) },
responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden, 404: r.notFound },
});
registry.registerPath({
method: "post",
path: "/api/projects/{id}/access-members",
tags: ["projects"],
summary: "Add a project access member",
request: {
params: z.object({ id: z.string() }),
body: jsonBody(addProjectAccessMemberSchema),
},
responses: {
201: r.ok(),
400: r.badRequest,
401: r.unauthorized,
403: r.forbidden,
404: r.notFound,
422: r.unprocessable,
},
});
registry.registerPath({
method: "delete",
path: "/api/projects/{id}/access-members/{memberId}",
tags: ["projects"],
summary: "Remove a project access member",
request: { params: z.object({ id: z.string(), memberId: z.string() }) },
responses: {
200: r.ok(),
401: r.unauthorized,
403: r.forbidden,
404: r.notFound,
422: r.unprocessable,
},
});
registry.registerPath({
method: "get",
path: "/api/projects/{id}/workspaces",
@@ -5327,9 +5455,16 @@ registry.registerPath({
// ─── Costs ───────────────────────────────────────────────────────────────────
const costReportQuerySchema = z.object({
period: z.enum(["month", "all"]).optional().describe("Defaults to the current UTC month. All-time cannot be combined with date bounds."),
from: z.union([z.iso.datetime({ offset: true }), z.iso.date()]).optional().describe("Inclusive start bound."),
to: z.union([z.iso.datetime({ offset: true }), z.iso.date()]).optional().describe("Inclusive end bound; must not precede from."),
});
const costSummaryPaths = [
"summary",
"by-agent",
"by-user",
"by-agent-model",
"by-provider",
"by-biller",
@@ -5348,7 +5483,12 @@ for (const segment of costSummaryPaths) {
path: `/api/companies/{companyId}/costs/${segment}`,
tags: ["costs"],
summary: `Cost report: ${segment}`,
request: { params: z.object({ companyId: z.string() }) },
request: {
params: z.object({ companyId: z.string() }),
...(!["window-spend", "quota-windows"].includes(segment) ? {
query: segment === "finance-events" ? costReportQuerySchema.extend({ limit: z.coerce.number().int().min(1).max(500).optional() }) : costReportQuerySchema,
} : {}),
},
responses: { 200: r.ok(), 401: r.unauthorized },
});
}
@@ -5358,11 +5498,12 @@ registry.registerPath({
path: "/api/companies/{companyId}/cost-events",
tags: ["costs"],
summary: "Record a cost event",
description: "Amounts are USD cents, including fractional cents. Decimal strings preserve exact nanodollar precision. Reuse the idempotency key and original receipt on retries; conflicting reuse returns 409.",
request: {
params: z.object({ companyId: z.string() }),
body: jsonBody(createCostEventSchema),
},
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized },
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 409: r.conflict },
});
registry.registerPath({
@@ -5370,13 +5511,47 @@ registry.registerPath({
path: "/api/companies/{companyId}/finance-events",
tags: ["costs"],
summary: "Record a finance event",
description: "Amounts accept exact decimal cents in the recorded currency. Credits use a nonnegative amount with direction credit. No currency conversion is inferred. Receipt-key conflicts return 409.",
request: {
params: z.object({ companyId: z.string() }),
body: jsonBody(createFinanceEventSchema),
},
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized },
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 409: r.conflict },
});
for (const [suffix, summary] of [
["health", "Inspect pending receipts, unpriced charges, cancellation backlog, and held reservations"],
["inspect", "Independently compare ledger evidence and stored totals"],
["invoices", "List imported provider invoices"],
["invoices/{invoiceId}", "Review exact invoice matches and unresolved differences"],
["events/{eventId}/adjustments", "Read append-only correction history and prior pricing evidence"],
] as const) {
registry.registerPath({
method: "get", path: `/api/companies/{companyId}/accounting/${suffix}`, tags: ["costs"], summary,
description: "Company-scoped board access is required. Board viewers may inspect; agents cannot access operator accounting evidence.",
request: { params: z.object({ companyId: z.string(),
...(suffix.includes("invoiceId") ? { invoiceId: z.string() } : {}),
...(suffix.includes("eventId") ? { eventId: z.string() } : {}),
}) },
responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden, 404: r.notFound },
});
}
for (const operation of [
{ suffix: "repair", schema: repairAccountingSchema, status: 200, summary: "Repair reviewed ledger projections", description: "Requires an audit reason and the current inspection fingerprint. A stale inspection returns 409. Missing evidence is never invented." },
{ suffix: "retry", schema: retryAccountingSchema, status: 200, summary: "Retry accounting for a company-owned run", description: "Retries accounting only. Provider work is never re-executed; incomplete evidence remains pending." },
{ suffix: "provider-costs/import", schema: importProviderCostsSchema, status: 200, summary: "Import a scoped provider cost report", description: "Reads up to 31 completed UTC days from OpenAI or Anthropic with a company admin credential. Requires explicit provider account and project/workspace identifiers. All pages validate before writing. Reimports append only the difference; run costs are not repriced. Report totals remain separate from invoices." },
{ suffix: "invoices", schema: importBillingInvoiceSchema, status: 201, summary: "Import normalized invoice evidence", description: "Idempotent by company, biller, and external invoice ID. Conflicting reuse returns 409. Import atomically creates finance timeline events and does not reprice run costs." },
{ suffix: "events/{eventId}/adjustments", schema: adjustCostSchema, status: 201, summary: "Apply a reviewed cost correction", description: "Requires the expected exact cents, an idempotency key, reason, and pricing evidence. Original amounts and pricing revisions remain in history. Stale reviews return 409; ambiguous or contradictory invoice evidence returns 422." },
] as const) {
registry.registerPath({
method: "post", path: `/api/companies/{companyId}/accounting/${operation.suffix}`, tags: ["costs"],
summary: operation.summary, description: `${operation.description} Company-scoped board write access is required; viewers and agents cannot mutate accounting.`,
request: { params: z.object({ companyId: z.string(), ...(operation.suffix.includes("eventId") ? { eventId: z.string() } : {}) }), body: jsonBody(operation.schema) },
responses: { [operation.status]: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict, 422: r.unprocessable },
});
}
registry.registerPath({
method: "post",
path: "/api/companies/{companyId}/budgets/policies",
@@ -6197,6 +6372,35 @@ registry.registerPath({
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized },
});
const primaryAgentPreferenceResponse = z.object({
companyId: z.string().uuid(),
userId: z.string(),
primaryAgentId: z.string().uuid().nullable(),
initialized: z.boolean(),
});
for (const method of ["get", "put"] as const) {
registry.registerPath({
method,
path: "/api/companies/{companyId}/primary-agent/me",
tags: ["agents"],
summary: method === "get" ? "Get my primary agent" : "Set my primary agent",
description: "Uses the authenticated board user's personal company preference. Active company viewers may manage their own preference. Agent credentials cannot access it. Setting a primary requires a visible, approved, non-terminated agent and rejoins that agent under existing membership rules. A cleared preference retains its initialization state.",
request: {
params: z.object({ companyId: z.string().uuid() }),
...(method === "put" ? { body: jsonBody(updatePrimaryAgentSchema) } : {}),
},
responses: {
200: r.ok(primaryAgentPreferenceResponse),
400: r.badRequest,
401: r.unauthorized,
403: r.forbidden,
404: r.notFound,
...(method === "put" ? { 422: r.unprocessable } : {}),
},
});
}
// ─── Announcements ───────────────────────────────────────────────────────────
const announcementResponseHeaders = {
@@ -10538,6 +10742,33 @@ registerCurrentRoute({
// --- Tool access -------------------------------------------------------------
registerCurrentRoute({
method: "get", path: "/api/companies/{companyId}/decision-model", tags: ["decision-models"],
summary: "Get decision settings, compatible connections, and manager capability",
responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden },
});
registerCurrentRoute({
method: "put", path: "/api/companies/{companyId}/decision-model", tags: ["decision-models"],
summary: "Configure the company decision model as a connection manager", body: updateDecisionModelSchema,
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 422: r.unprocessable },
});
registerCurrentRoute({
method: "get", path: "/api/companies/{companyId}/decision-model/availability", tags: ["decision-models"],
summary: "Check local decision configuration and caller authorization without contacting a provider",
responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden },
});
registerCurrentRoute({
method: "post", path: "/api/companies/{companyId}/decision-model/test", tags: ["decision-models"],
summary: "Run the fixed billed three-question setup test as a connection manager",
responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden },
});
registerCurrentRoute({
method: "get", path: "/api/companies/{companyId}/decision-model/history", tags: ["decision-models"],
summary: "List decision metadata and charges with authorized task links",
query: costReportQuerySchema.extend({ limit: z.coerce.number().int().min(1).max(500).optional() }),
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden },
});
registerCurrentRoute({
method: "get",
path: "/api/companies/{companyId}/tools/gallery",
+51
View File
@@ -0,0 +1,51 @@
import { Router } from "express";
import { agents, companies, type Db } from "@paperclipai/db";
import { and, eq } from "drizzle-orm";
import { updatePrimaryAgentSchema } from "@paperclipai/shared";
import { forbidden, notFound } from "../errors.js";
import { validate } from "../middleware/validate.js";
import { accessService } from "../services/access.js";
import { primaryAgentService } from "../services/primary-agent.js";
import { assertBoard, hasCompanyAccess } from "./authz.js";
export function primaryAgentRoutes(db: Db) {
const router = Router();
const svc = primaryAgentService(db);
const access = accessService(db);
router.use("/companies/:companyId/primary-agent/me", async (req, _res, next) => {
assertBoard(req);
const companyId = req.params.companyId as string;
if (!hasCompanyAccess(req, companyId)) throw forbidden("User does not have access to this company");
if (!req.actor.userId) throw forbidden("Board user access required");
// Personal preferences follow the same self-service rules as stars and
// resource memberships: viewers may choose their own primary too.
if (req.actor.source !== "local_implicit" && !req.actor.isInstanceAdmin
&& !req.actor.memberships?.some(membership => membership.companyId === companyId && membership.status === "active")) {
throw forbidden("User does not have active company access");
}
if (!await db.query.companies.findFirst({ where: eq(companies.id, req.params.companyId as string) })) {
throw notFound("Company not found");
}
next();
});
router.get("/companies/:companyId/primary-agent/me", async (req, res) => {
const preference = await svc.get(req.params.companyId as string, req.actor.userId!);
if (preference.primaryAgentId) {
const decision = await access.decide({ actor: req.actor, action: "agent:read",
resource: { type: "agent", companyId: preference.companyId, agentId: preference.primaryAgentId } });
if (!decision.allowed) preference.primaryAgentId = null;
}
res.json(preference);
});
router.put("/companies/:companyId/primary-agent/me", validate(updatePrimaryAgentSchema), async (req, res) => {
const companyId = req.params.companyId as string;
const agentId = req.body.primaryAgentId as string;
const agent = await db.query.agents.findFirst({ where: and(eq(agents.companyId, companyId), eq(agents.id, agentId)) });
if (!agent) throw notFound("Agent not found");
const decision = await access.decide({ actor: req.actor, action: "agent:read",
resource: { type: "agent", companyId, agentId } });
if (!decision.allowed) throw forbidden("Agent is outside this actor's authorization boundary");
res.json(await svc.set(companyId, req.actor.userId!, agentId, req.actor));
});
return router;
}
+197 -4
View File
@@ -8,14 +8,19 @@ import { normalizeProjectRepositoryUrl, resolveProjectRepositorySelection } from
import { toolAccessService } from "../services/tool-access.js";
import { Router, type Request, type Response } from "express";
import type { Db } from "@paperclipai/db";
import { agents, authUsers, companyMemberships, instanceUserRoles, projectAccessMembers } from "@paperclipai/db";
import { inArray } from "drizzle-orm";
import {
addProjectAccessMemberSchema,
createProjectSchema,
projectDiscoverySchema,
type ProjectDiscoveryPage,
createProjectWorkspaceSchema,
deriveProjectUrlKey,
findWorkspaceCommandDefinition,
isUuidLike,
matchWorkspaceRuntimeServiceToCommand,
normalizeProjectUrlKey,
updateProjectSchema,
updateProjectWorkspaceSchema,
workspaceRuntimeControlTargetSchema,
@@ -28,6 +33,7 @@ import { conflict, forbidden, unprocessable } from "../errors.js";
import { externalObjectService } from "../services/external-objects.js";
import { instanceSettingsService } from "../services/instance-settings.js";
import { assertBoard, assertCompanyAccess, getAccessibleResource, getActorInfo } from "./authz.js";
import { ensureProjectAccessMember } from "../services/projects.js";
import {
buildWorkspaceRuntimeDesiredStatePatch,
listConfiguredRuntimeServiceEntries,
@@ -137,11 +143,17 @@ export function projectRoutes(db: Db) {
if (isUuidLike(rawId)) return rawId;
const companyId = await resolveCompanyIdForProjectReference(req);
if (!companyId) return rawId;
const resolved = await svc.resolveByReference(companyId, rawId);
if (resolved.ambiguous) {
const urlKey = normalizeProjectUrlKey(rawId);
if (!urlKey) return rawId;
const visibleProjects = await filterProjectsForActor(
req,
await svc.list(companyId, { includeArchived: true }),
);
const matches = visibleProjects.filter((project) => deriveProjectUrlKey(project.name, project.id) === urlKey);
if (matches.length > 1) {
throw conflict("Project shortname is ambiguous in this company. Use the project ID.");
}
return resolved.project?.id ?? rawId;
return matches[0]?.id ?? rawId;
}
async function assertProjectReadAllowed(req: Request, res: Response, project: { id: string; companyId: string }) {
@@ -151,10 +163,87 @@ export function projectRoutes(db: Db) {
resource: { type: "project", companyId: project.companyId, projectId: project.id },
});
if (decision.allowed) return true;
res.status(403).json({ error: "Project is outside this actor's authorization boundary" });
res.status(404).json({ error: "Project not found" });
return false;
}
async function assertCanManageProjectPrivacy(req: Request, res: Response, project: {
companyId: string; privacyOwnerUserId?: string | null; personalOwnerUserId?: string | null;
}) {
const actor = req.actor;
if (actor.type === "board" && actor.userId) {
if (actor.source === "local_implicit" || actor.isInstanceAdmin) return true;
if (actor.userId === project.privacyOwnerUserId || actor.userId === project.personalOwnerUserId) return true;
const instanceAdmin = actor.source !== "cloud_tenant" && await db.select({ id: instanceUserRoles.id }).from(instanceUserRoles)
.where(and(eq(instanceUserRoles.userId, actor.userId), eq(instanceUserRoles.role, "instance_admin"))).limit(1).then(rows => rows.length > 0);
if (instanceAdmin) return true;
const membership = await db.select({ role: companyMemberships.membershipRole }).from(companyMemberships)
.where(and(eq(companyMemberships.companyId, project.companyId), eq(companyMemberships.principalType, "user"),
eq(companyMemberships.principalId, actor.userId), eq(companyMemberships.status, "active"))).limit(1);
if (["owner", "admin"].includes(membership[0]?.role ?? "")) return true;
}
res.status(403).json({ error: "Only the project privacy owner or an administrator can change project access" });
return false;
}
async function addActorAsPrivateProjectPrincipal(req: Request, project: { id: string; companyId: string; privacyOwnerUserId?: string | null; personalOwnerUserId?: string | null }, dbOrTx: Db = db) {
const ownerUserId = project.privacyOwnerUserId ?? project.personalOwnerUserId;
if (ownerUserId) await ensureProjectAccessMember(dbOrTx, {
companyId: project.companyId, projectId: project.id, subjectType: "user", subjectId: ownerUserId,
});
if (req.actor.type === "board" && req.actor.userId) {
await ensureProjectAccessMember(dbOrTx, {
companyId: project.companyId,
projectId: project.id,
subjectType: "user",
subjectId: req.actor.userId,
});
return;
}
if (req.actor.type === "agent" && req.actor.agentId) {
if (req.actor.onBehalfOfUserId) {
await ensureProjectAccessMember(dbOrTx, {
companyId: project.companyId,
projectId: project.id,
subjectType: "user",
subjectId: req.actor.onBehalfOfUserId,
});
}
await ensureProjectAccessMember(dbOrTx, {
companyId: project.companyId,
projectId: project.id,
subjectType: "agent",
subjectId: req.actor.agentId,
});
}
}
async function enrichProjectAccessMembers(rows: Array<typeof projectAccessMembers.$inferSelect>) {
const agentIds = rows.filter((row) => row.subjectType === "agent").map((row) => row.subjectId);
const userIds = rows.filter((row) => row.subjectType === "user").map((row) => row.subjectId);
const [agentRows, userRows] = await Promise.all([
agentIds.length === 0
? Promise.resolve([])
: db.select({ id: agents.id, name: agents.name }).from(agents).where(inArray(agents.id, agentIds)),
userIds.length === 0
? Promise.resolve([])
: db.select({ id: authUsers.id, name: authUsers.name, email: authUsers.email, image: authUsers.image })
.from(authUsers)
.where(inArray(authUsers.id, userIds)),
]);
const agentsById = new Map(agentRows.map((row) => [row.id, row]));
const usersById = new Map(userRows.map((row) => [row.id, row]));
return rows.map((row) => {
const agent = row.subjectType === "agent" ? agentsById.get(row.subjectId) : null;
const user = row.subjectType === "user" ? usersById.get(row.subjectId) : null;
return {
...row,
subjectDisplayName: agent?.name ?? user?.name ?? user?.email ?? null,
subjectAvatarUrl: user?.image ?? null,
};
});
}
async function assertRuntimeManageAllowed(req: Request, res: Response, companyId: string) {
const decision = await access.decide({
actor: req.actor,
@@ -248,6 +337,7 @@ export function projectRoutes(db: Db) {
const id = req.params.id as string;
const project = await getAccessibleResource(req, res, svc.getById(id), "Project not found");
if (!project) return;
if (!(await assertProjectReadAllowed(req, res, project))) return;
const summary = await externalObjectsSvc.getProjectSummary(project.id);
res.json(summary);
});
@@ -261,6 +351,7 @@ export function projectRoutes(db: Db) {
};
const { workspace, repositoryIds, repositoryUrls, idempotencyKey, ...projectData } = req.body as CreateProjectPayload & { idempotencyKey?: string; repositoryUrls?: string[] };
projectData.privacyOwnerUserId = req.actor.type === "board" ? req.actor.userId ?? null : req.actor.type === "agent" ? req.actor.onBehalfOfUserId ?? null : null;
const runContext = req.actor.type === "agent" && req.actor.source === "agent_jwt" && req.actor.runId
? await projectToolContext(db, req.actor, true) : null;
await assertProjectEnvironmentSelection(
@@ -305,6 +396,7 @@ export function projectRoutes(db: Db) {
if (runContext) await projectToolContext(tx as unknown as Db, req.actor, true);
const service = projectService(tx as unknown as Db);
const project = repositories ? await service.createWithRepositories(companyId, projectData, repositories) : await service.create(companyId, projectData);
if (project.visibility === "private") await addActorAsPrivateProjectPrincipal(req, project, tx as unknown as Db);
const attachedUrls = new Set((repositories ?? []).map(repo => repo.url.toLowerCase()));
const registeredUrls: typeof urlRepositories = [];
for (const repo of urlRepositories) {
@@ -347,7 +439,12 @@ export function projectRoutes(db: Db) {
const id = req.params.id as string;
const existing = await getAccessibleResource(req, res, svc.getById(id), "Project not found");
if (!existing) return;
if (!(await assertProjectReadAllowed(req, res, existing))) return;
const body = { ...req.body };
if (body.visibility !== undefined) {
if (!(await assertCanManageProjectPrivacy(req, res, existing))) return;
}
if (body.visibility === "private") await addActorAsPrivateProjectPrincipal(req, existing);
assertNoAgentHostWorkspaceCommandMutation(
req,
collectProjectExecutionWorkspaceCommandPaths(body.executionWorkspacePolicy),
@@ -399,10 +496,101 @@ export function projectRoutes(db: Db) {
res.json(project);
});
router.get("/projects/:id/access-members", async (req, res) => {
const id = req.params.id as string;
const project = await getAccessibleResource(req, res, svc.getById(id), "Project not found");
if (!project || !(await assertProjectReadAllowed(req, res, project))) return;
const rows = await db
.select()
.from(projectAccessMembers)
.where(and(eq(projectAccessMembers.companyId, project.companyId), eq(projectAccessMembers.projectId, project.id)));
res.json(await enrichProjectAccessMembers(rows));
});
router.post("/projects/:id/access-members", validate(addProjectAccessMemberSchema), async (req, res) => {
assertBoard(req);
const id = req.params.id as string;
const project = await getAccessibleResource(req, res, svc.getById(id), "Project not found");
if (!project || !(await assertProjectReadAllowed(req, res, project))) return;
if (!(await assertCanManageProjectPrivacy(req, res, project))) return;
const subjectType = req.body.subjectType as "user" | "agent";
const subjectId = req.body.subjectId as string;
const subjectExists = subjectType === "agent"
? await db.select({ id: agents.id }).from(agents)
.where(and(eq(agents.id, subjectId), eq(agents.companyId, project.companyId)))
.then((rows) => rows.length > 0)
: await db.select({ id: companyMemberships.id }).from(companyMemberships)
.where(and(
eq(companyMemberships.principalType, "user"),
eq(companyMemberships.principalId, subjectId),
eq(companyMemberships.companyId, project.companyId),
eq(companyMemberships.status, "active"),
))
.then((rows) => rows.length > 0);
if (!subjectExists) {
res.status(422).json({ error: "Project access member must belong to this company" });
return;
}
await ensureProjectAccessMember(db, { companyId: project.companyId, projectId: project.id, subjectType, subjectId });
const rows = await db.select().from(projectAccessMembers).where(and(
eq(projectAccessMembers.projectId, project.id),
eq(projectAccessMembers.subjectType, subjectType),
eq(projectAccessMembers.subjectId, subjectId),
));
const [member] = await enrichProjectAccessMembers(rows);
const actor = getActorInfo(req);
await logActivity(db, {
companyId: project.companyId,
actorType: actor.actorType,
actorId: actor.actorId,
agentId: actor.agentId,
action: "project.access_member_added",
entityType: "project",
entityId: project.id,
details: { subjectType, subjectId },
});
res.status(201).json(member);
});
router.delete("/projects/:id/access-members/:memberId", async (req, res) => {
assertBoard(req);
const id = req.params.id as string;
const project = await getAccessibleResource(req, res, svc.getById(id), "Project not found");
if (!project || !(await assertProjectReadAllowed(req, res, project))) return;
if (!(await assertCanManageProjectPrivacy(req, res, project))) return;
const member = await db.select().from(projectAccessMembers).where(and(
eq(projectAccessMembers.id, req.params.memberId as string),
eq(projectAccessMembers.companyId, project.companyId),
eq(projectAccessMembers.projectId, project.id),
)).then((rows) => rows[0] ?? null);
if (!member) {
res.status(404).json({ error: "Project access member not found" });
return;
}
if (member.subjectType === "user" && [project.personalOwnerUserId, project.privacyOwnerUserId].includes(member.subjectId)) {
res.status(422).json({ error: "The project privacy owner cannot be removed" });
return;
}
await db.delete(projectAccessMembers).where(eq(projectAccessMembers.id, member.id));
const actor = getActorInfo(req);
await logActivity(db, {
companyId: project.companyId,
actorType: actor.actorType,
actorId: actor.actorId,
agentId: actor.agentId,
action: "project.access_member_removed",
entityType: "project",
entityId: project.id,
details: { subjectType: member.subjectType, subjectId: member.subjectId },
});
res.json(member);
});
router.get("/projects/:id/workspaces", async (req, res) => {
const id = req.params.id as string;
const existing = await getAccessibleResource(req, res, svc.getById(id), "Project not found");
if (!existing) return;
if (!(await assertProjectReadAllowed(req, res, existing))) return;
const workspaces = await svc.listWorkspaces(id);
res.json(workspaces);
});
@@ -411,6 +599,7 @@ export function projectRoutes(db: Db) {
const id = req.params.id as string;
const existing = await getAccessibleResource(req, res, svc.getById(id), "Project not found");
if (!existing) return;
if (!(await assertProjectReadAllowed(req, res, existing))) return;
assertNoAgentHostWorkspaceCommandMutation(
req,
collectProjectWorkspaceCommandPaths(req.body),
@@ -450,6 +639,7 @@ export function projectRoutes(db: Db) {
const workspaceId = req.params.workspaceId as string;
const existing = await getAccessibleResource(req, res, svc.getById(id), "Project not found");
if (!existing) return;
if (!(await assertProjectReadAllowed(req, res, existing))) return;
assertNoAgentHostWorkspaceCommandMutation(
req,
collectProjectWorkspaceCommandPaths(req.body),
@@ -496,6 +686,7 @@ export function projectRoutes(db: Db) {
const project = await getAccessibleResource(req, res, svc.getById(id), "Project not found");
if (!project) return;
if (!(await assertProjectReadAllowed(req, res, project))) return;
const workspace = project.workspaces.find((entry) => entry.id === workspaceId) ?? null;
if (!workspace) {
@@ -770,6 +961,7 @@ export function projectRoutes(db: Db) {
const workspaceId = req.params.workspaceId as string;
const existing = await getAccessibleResource(req, res, svc.getById(id), "Project not found");
if (!existing) return;
if (!(await assertProjectReadAllowed(req, res, existing))) return;
const workspace = await svc.removeWorkspace(id, workspaceId);
if (!workspace) {
res.status(404).json({ error: "Project workspace not found" });
@@ -798,6 +990,7 @@ export function projectRoutes(db: Db) {
const id = req.params.id as string;
const existing = await getAccessibleResource(req, res, svc.getById(id), "Project not found");
if (!existing) return;
if (!(await assertProjectReadAllowed(req, res, existing))) return;
const project = await svc.remove(id);
if (!project) {
res.status(404).json({ error: "Project not found" });
+10 -5
View File
@@ -11,7 +11,7 @@ import {
} from "@paperclipai/shared";
import { forbidden, notFound, unprocessable } from "../errors.js";
import { validate } from "../middleware/validate.js";
import { authorizationDeniedDetails } from "../services/authorization.js";
import { authorizationDeniedDetails, issueReadSqlCondition } from "../services/authorization.js";
import { accessService, heartbeatService, instanceSettingsService, issueService, logActivity, statusCardService } from "../services/index.js";
import { queueIssueAssignmentWakeup, type IssueAssignmentWakeupDeps } from "../services/issue-assignment-wakeup.js";
import { assertCompanyAccess, getAccessibleResource, getActorInfo, hasCompanyAccess } from "./authz.js";
@@ -144,7 +144,9 @@ export function statusCardRoutes(db: Db, opts: { heartbeat?: IssueAssignmentWake
assertCompanyAccess(req, companyId);
await assertStatusCardsEnabled();
const query = listStatusCardsQuerySchema.parse(req.query);
res.json(await service.list(companyId, query.archived));
res.json(await service.list(companyId, query.archived, {
issueReadCondition: await issueReadSqlCondition(db, req.actor),
}));
});
router.post("/companies/:companyId/status-cards", validate(createStatusCardSchema), async (req, res) => {
@@ -171,7 +173,9 @@ export function statusCardRoutes(db: Db, opts: { heartbeat?: IssueAssignmentWake
await assertStatusCardsEnabled();
const card = await getAccessibleResource(req, res, service.getById(req.params.id as string), "Status card not found");
if (!card) return;
res.json(await service.hydrate(card));
res.json(await service.hydrate(card, {
issueReadCondition: await issueReadSqlCondition(db, req.actor),
}));
});
router.patch("/status-cards/:id", validate(patchStatusCardSchema), async (req, res) => {
@@ -260,11 +264,12 @@ export function statusCardRoutes(db: Db, opts: { heartbeat?: IssueAssignmentWake
if (!decision.allowed) {
throw forbidden("Status-card dry-run is outside this actor's low-trust authorization boundary", authorizationDeniedDetails(decision));
}
const issueReadCondition = await issueReadSqlCondition(db, req.actor);
res.json({
cardId: card.id,
queryVersion: card.queryVersion,
queries: await service.dryRun(card),
mentionedIssues: await service.listMentionedIssues(card),
queries: await service.dryRun(card, { issueReadCondition }),
mentionedIssues: await service.listMentionedIssues(card, { issueReadCondition }),
});
});
@@ -0,0 +1,56 @@
import { describe, expect, it } from "vitest";
import { buildProcessLossDiagnostic, readProcessLossDiagnostic } from "../process-loss-diagnostics.js";
const nowMs = Date.UTC(2026, 0, 1, 12);
const run = {
startedAt: new Date(nowMs - 10 * 60_000), lastOutputAt: new Date(nowMs - 2 * 60_000),
processPid: 123, processGroupId: null,
};
const input = { run, nowMs, observerStartedAtMs: nowMs - 30_000,
checksPersistedChildLiveness: true, retryEligible: true };
describe("orphan process-loss evidence", () => {
it("distinguishes a run from the previous observer without inventing a restart cause", () => {
expect(buildProcessLossDiagnostic(input)).toEqual({
pidRecorded: true, groupRecorded: false, localCheck: "not_observed_alive", retryEligible: true,
runPredatesObserver: true, lastOutputAgeMs: 120_000, observerUptimeMs: 30_000,
});
const currentObserverRun = buildProcessLossDiagnostic({ ...input, observerStartedAtMs: nowMs - 20 * 60_000 });
expect(currentObserverRun.runPredatesObserver).toBe(false);
expect(currentObserverRun).not.toHaveProperty("restartCause");
});
it("does not describe missing or unchecked identifiers as confirmed child death", () => {
expect(buildProcessLossDiagnostic({ ...input, checksPersistedChildLiveness: false }).localCheck).toBe("not_checked");
expect(buildProcessLossDiagnostic({ ...input, run: { ...run, processPid: null }, retryEligible: false }))
.toMatchObject({ pidRecorded: false, groupRecorded: false, localCheck: "no_identifiers", retryEligible: false });
expect(buildProcessLossDiagnostic({ ...input, run: { ...run, processPid: null, processGroupId: 456 } }))
.toMatchObject({ pidRecorded: false, groupRecorded: true, localCheck: "not_observed_alive" });
});
it("omits unavailable, future and unbounded ages", () => {
for (const lastOutputAt of [null, new Date(NaN), new Date(nowMs + 1), new Date(nowMs - 604_800_001)]) {
expect(buildProcessLossDiagnostic({ ...input, run: { ...run, lastOutputAt } })).not.toHaveProperty("lastOutputAgeMs");
}
for (const observerStartedAtMs of [NaN, Infinity, nowMs + 1]) {
const diagnostic = buildProcessLossDiagnostic({ ...input, observerStartedAtMs });
expect(diagnostic).not.toHaveProperty("observerUptimeMs");
expect(diagnostic).not.toHaveProperty("runPredatesObserver");
}
expect(buildProcessLossDiagnostic({ ...input, run: { ...run, startedAt: new Date(nowMs + 1) } }))
.not.toHaveProperty("runPredatesObserver");
expect(buildProcessLossDiagnostic({ ...input, observerStartedAtMs: nowMs - 1.5 }).observerUptimeMs).toBe(2);
});
it("reads only bounded scalar evidence, including hostile persisted input", () => {
const diagnostic = buildProcessLossDiagnostic(input);
expect(readProcessLossDiagnostic({ ...diagnostic, pid: 123, prompt: "private-prompt", path: "/private/path" }))
.toEqual(diagnostic);
for (const value of [null, [], "private", { localCheck: "private", pidRecorded: 1,
groupRecorded: "false", retryEligible: "private", runPredatesObserver: null,
observerUptimeMs: 604_800_001, lastOutputAgeMs: -1 },
Object.defineProperty({}, "localCheck", { get() { throw new Error("private"); } })]) {
expect(readProcessLossDiagnostic(value)).toEqual({});
}
});
});
@@ -7,6 +7,19 @@ const run = (overrides: Partial<Run> = {}) => ({ resultJson: null, ...overrides
const collect = (error: unknown) => collectRunFailureDiagnostics(run(), { error });
describe("run failure diagnostics", () => {
it("exports bounded orphan evidence only for a process-loss failure", () => {
const processLossDiagnostic = { pidRecorded: false, groupRecorded: false, localCheck: "no_identifiers",
retryEligible: false, runPredatesObserver: true, observerUptimeMs: 30_000, lastOutputAgeMs: 120_000,
pid: 123, path: "/private-path", prompt: "private-prompt" };
const resultJson = { processLossDiagnostic };
expect(collectRunFailureDiagnostics(run({ errorCode: "process_lost", resultJson }), {}).execution).toEqual({
processLossPidRecorded: false, processLossGroupRecorded: false, processLossLocalCheck: "no_identifiers",
processLossRetryEligible: false, processLossRunPredatesObserver: true,
processLossObserverUptimeMs: 30_000, processLossLastOutputAgeMs: 120_000,
});
expect(collectRunFailureDiagnostics(run({ errorCode: "adapter_failed", resultJson }), {}).execution).toEqual({});
});
it("exports only the closed native model/auth rejection vocabulary", () => {
const diagnostic = { provider: "codex", category: "model_auth_incompatible", status: 400, authMode: "chatgpt" };
const result = sanitizeRunFailureDiagnostics(collectRunFailureDiagnostics(run({ resultJson: {
@@ -110,6 +110,99 @@ describeEmbeddedPostgres("reportRunFailure", () => {
} as unknown as typeof heartbeatRuns.$inferSelect;
}
function missingSecretRun(overrides: Partial<typeof heartbeatRuns.$inferSelect> = {}) {
return buildRun({
errorCode: "configuration_incomplete",
executionStage: "preparing",
resultJson: {
configurationIncomplete: {
reason: "secret_binding_missing",
missingBindings: [{ bindingType: "user_secret_ref", errorCode: "user_secret_missing" }],
},
executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
},
...overrides,
});
}
it.each([
{ bindingType: "secret_ref" },
{ bindingType: "secret_ref", errorCode: "binding_missing" },
...["binding_missing", "responsible_user_missing", "user_secret_missing", "secret_inactive", "user_secret_definition_inactive"]
.map((errorCode) => ({ bindingType: "user_secret_ref", errorCode })),
])("keeps the known pre-dispatch secret blocker local: %j", async (binding) => {
await seedCompanyAndAgent();
const run = missingSecretRun();
(run.resultJson!.configurationIncomplete as Record<string, unknown>).missingBindings = [binding];
const saved = structuredClone(run);
await reportRunFailure(db, run, { phase: "setup" });
expect(mockCaptureRunFailure).not.toHaveBeenCalled();
expect(run).toEqual(saved);
});
it.each([
{},
{ reason: "secret_binding_missing", missingBindings: [] },
{ reason: "secret_binding_missing", missingBindings: [null] },
{ reason: "secret_binding_missing", missingBindings: [{ errorCode: "user_secret_missing" }] },
{ reason: "secret_binding_missing", missingBindings: [{ bindingType: "user_secret_ref", errorCode: "provider_error" }] },
{ reason: "secret_binding_missing", missingBindings: [{ bindingType: "user_secret_ref", errorCode: "user_secret_definition_missing" }] },
{ reason: "secret_binding_missing", missingBindings: [{ bindingType: "user_secret_ref", errorCode: "new_unknown_reason" }] },
{ reason: "secret_binding_missing", missingBindings: [
{ bindingType: "user_secret_ref", errorCode: "user_secret_missing" },
{ bindingType: "secret_ref", errorCode: "provider_error" },
] },
{ reason: "ai_connection_unavailable" },
])("reports ambiguous, unknown, and provider failures: %j", async (configurationIncomplete) => {
await seedCompanyAndAgent();
const run = missingSecretRun();
run.resultJson!.configurationIncomplete = configurationIncomplete;
await reportRunFailure(db, run, { phase: "setup" });
expect(mockCaptureRunFailure).toHaveBeenCalledTimes(1);
});
it.each([
{ status: "timed_out" },
{ errorCode: "setup_failed" },
{ errorCode: "workspace_validation_failed" },
{ errorCode: "adapter_failed" },
{ executionStage: "executing" },
{ executionStage: null },
{ exitCode: 1 },
{ exitCode: 0 },
{ signal: "SIGTERM" },
])("reports missing-secret text without a proven pre-dispatch outcome: %j", async (overrides) => {
await seedCompanyAndAgent();
await reportRunFailure(db, missingSecretRun(overrides), { phase: "setup" });
expect(mockCaptureRunFailure).toHaveBeenCalledTimes(1);
});
it.each([undefined, { kind: "bootstrap" }, { kind: "bootstrap", providerWorkStarted: true }])(
"reports missing-secret failures without explicit bootstrap proof: %j", async (executionRecovery) => {
await seedCompanyAndAgent();
const run = missingSecretRun();
run.resultJson!.executionRecovery = executionRecovery;
await reportRunFailure(db, run, { phase: "setup" });
expect(mockCaptureRunFailure).toHaveBeenCalledTimes(1);
},
);
it.each([undefined, "execute"] as const)("reports configuration failures outside setup: %s", async (phase) => {
await seedCompanyAndAgent();
await reportRunFailure(db, missingSecretRun(), { phase });
expect(mockCaptureRunFailure).toHaveBeenCalledTimes(1);
});
it("captures once for the status failed", async () => {
await seedCompanyAndAgent();
const run = buildRun({ status: "failed" });
@@ -188,7 +281,10 @@ describeEmbeddedPostgres("reportRunFailure", () => {
exceptions: [{ message: "adapter threw" }, { message: "provider unreachable", code: "ECONNRESET", status: 503, requestId: "request-123" }],
});
expect(captured.diagnostics.exceptions[0].stack).toContain("run-failure-report.test.ts");
expect(JSON.stringify(captured)).not.toContain("private-");
// Match the sensitive fixture values, not a legitimate checkout name in the stack.
for (const value of ["private-response", "private-stderr", "private-stdout", "private-prompt", "private-provider-raw", "private-summary", "private-env", "private-adapter-response"]) {
expect(JSON.stringify(captured)).not.toContain(value);
}
expect(error.cause).toBe(cause);
});
Loaded 100 of 520 files, more files were not shown because too many files have changed in this diff. Show more