The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
perf(tools): scope connection readiness assignment reads (#17541)
Devin Foley2f637fe8c49b
diff --git a/doc/DATABASE.md b/doc/DATABASE.mdindex 17fbb47f40..aacf4f9f23 100644--- a/doc/DATABASE.md+++ b/doc/DATABASE.md@@ -471,6 +471,13 @@ bindings, selectors, exclusions, and installed connections on every call. Thepublic effective-profile response continues to include complete tool schemasand annotations.+Connection readiness checks use a scoped assignment reader. It applies the same+current profile precedence, selectors, and exclusions to the candidate connection+IDs. The reader selects rule match fields and catalog identities. It does not+load rule conditions, catalog schemas, profile summaries, or the company-agent+list. Installed connections and later identity and gateway checks remain fresh.+Full effective-profile and effective-tool responses keep their complete shape.+## Execution identity row locksIdentity initialization, credential acquisition, and steering reconciliation lockdiff --git a/server/src/__tests__/tool-effective-assignments.test.ts b/server/src/__tests__/tool-effective-assignments.test.tsindex 2f69d9e62d..13de5533fb 100644--- a/server/src/__tests__/tool-effective-assignments.test.ts+++ b/server/src/__tests__/tool-effective-assignments.test.ts@@ -1,10 +1,11 @@-import { randomUUID } from "node:crypto";+import { randomBytes, randomUUID } from "node:crypto";import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";import { eq, sql } from "drizzle-orm";import {agents, companies, createDb, toolApplications, toolCatalogEntries,toolConnections, toolProfileBindings, toolProfileEntries, toolProfiles, type Db,} from "@paperclipai/db";+import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture";import { toolAccessService } from "../services/tool-access.js";import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";@@ -49,6 +50,11 @@ describeDatabase("effective tool assignments", () => {expect(assignments).toEqual({ ...full, allowedTools: full.allowedTools.map(({ id, applicationId, connectionId, toolName }) => ({ id, applicationId, connectionId, toolName }),) });+ const connections = await service.getConnectionAssignmentsForAgent(f.company.id, f.agent.id, [f.connection.id]);+ expect(connections).toEqual({+ installedConnections: full.installedConnections,+ allowedConnectionIds: [...new Set(full.allowedTools.filter(tool => tool.connectionId === f.connection.id).map(tool => tool.connectionId))],+ });return { service, full, assignments };}@@ -130,4 +136,45 @@ describeDatabase("effective tool assignments", () => {expect(observed[1].bytes).toBeLessThan(observed[0].bytes / 100);expect(full.allowedTools[0].inputSchema).toEqual(f.read.inputSchema);});+ it("scopes catalog reads, omits rule payloads, and keeps current full definitions", async () => {+ const f = await fixture();+ const bulk = randomBytes(128 * 1024).toString("base64");+ const [rule] = await db.insert(toolProfileEntries).values({ companyId: f.company.id, profileId: f.profile.id,+ selectorType: "application", effect: "include", applicationId: f.application.id, conditions: { savedRuleMetadata: bulk } }).returning();+ const [unrelated] = await db.insert(toolConnections).values({ companyId: f.company.id, applicationId: f.application.id,+ name: "Other connection", uid: randomUUID(), transport: "mcp_remote", status: "active", enabled: true }).returning();+ await db.insert(toolCatalogEntries).values(Array.from({ length: 100 }, (_, index) => ({ companyId: f.company.id,+ applicationId: f.application.id, connectionId: unrelated.id, name: `other_${index}`, toolName: `other_${index}`, versionHash: `v${index}` })));+ const service = toolAccessService(db);+ const before = await service.getEffectiveToolAssignmentsForAgent(f.company.id, f.agent.id);+ expect(before.allowedTools).toHaveLength(102);+ const events: Array<Record<string, unknown>> = [], now = Date.now();+ const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event));+ installDatabaseResponseCapture(db, { toolCatalogEntries, toolProfileEntries }, capture);+ let scoped: Awaited<ReturnType<typeof service.getConnectionAssignmentsForAgent>>;+ try { scoped = await service.getConnectionAssignmentsForAgent(f.company.id, f.agent.id, [f.connection.id]); }+ finally { capture.flush(); }+ expect(Number(events.at(-1)?.completedQueries)).toBeGreaterThan(0);+ expect(Number(events.at(-1)?.responseValueBytes)).toBeLessThan(16 * 1024);+ const catalogQueries = events.filter(event => event.event === "paperclip.db_response_capture.entry.v1"+ && event.table === "tool_catalog_entries" && event.operation === "select");+ expect(catalogQueries).toHaveLength(1);+ expect(catalogQueries[0]).toMatchObject({ calls: 1, rows: 2 });+ expect(scoped!).toEqual({ allowedConnectionIds: [f.connection.id], installedConnections: before.installedConnections });+ expect(JSON.stringify(events)).not.toContain(bulk.slice(0, 64));+ expect((await db.select().from(toolProfileEntries).where(eq(toolProfileEntries.id, rule.id)))[0]).toEqual(rule);+ expect(await service.getEffectiveToolAssignmentsForAgent(f.company.id, f.agent.id)).toEqual(before);+ expect((await service.getConnectionAssignmentsForAgent(f.company.id, f.agent.id, [])).allowedConnectionIds).toEqual([]);+ await db.delete(toolProfileBindings).where(eq(toolProfileBindings.profileId, f.profile.id));+ expect((await service.getConnectionAssignmentsForAgent(f.company.id, f.agent.id, [f.connection.id])).allowedConnectionIds).toEqual([]);+ });++ it("keeps other companies' catalog rows out of scoped assignments", async () => {+ const f = await fixture();+ const other = await fixture();+ await db.update(toolProfiles).set({ defaultAction: "allow" }).where(eq(toolProfiles.id, f.profile.id));+ expect((await toolAccessService(db).getConnectionAssignmentsForAgent(f.company.id, f.agent.id, [other.connection.id])).allowedConnectionIds).toEqual([]);+ await expect(toolAccessService(db).getConnectionAssignmentsForAgent(f.company.id, other.agent.id, [f.connection.id])).rejects.toThrow("same company");+ });+});diff --git a/server/src/services/connection-intents.ts b/server/src/services/connection-intents.tsindex a6d07331c0..77dabac142 100644--- a/server/src/services/connection-intents.ts+++ b/server/src/services/connection-intents.ts@@ -291,9 +291,9 @@ export function connectionIntentService(db: Db) {&& connection.status !== "archived" && connection.connectionPurpose !== "ai");if (matching.length === 0) return null;- const effective = await access.getEffectiveToolAssignmentsForAgent(input.companyId, input.agentId);+ const effective = await access.getConnectionAssignmentsForAgent(input.companyId, input.agentId, matching.map(connection => connection.id));const installedIds = new Set(effective.installedConnections.map((connection) => connection.id));- const permittedIds = new Set(effective.allowedTools.map((tool) => tool.connectionId));+ const permittedIds = new Set(effective.allowedConnectionIds);const usable = (connection: ToolConnection | undefined) => connection&& installedIds.has(connection.id) && permittedIds.has(connection.id)&& connection.status === "active" && connection.enableddiff --git a/server/src/services/tool-access/profiles/projection.ts b/server/src/services/tool-access/profiles/projection.tsindex 50b77ae3a7..53b92ef182 100644--- a/server/src/services/tool-access/profiles/projection.ts+++ b/server/src/services/tool-access/profiles/projection.ts@@ -80,9 +80,15 @@ export type ProfileApplication = Pick<typeof toolApplications.$inferSelect, "id"export type ProfileConnection = Pick<typeof toolConnections.$inferSelect, "id" | "name">;+export type ProfileEntryMatch = Pick<typeof toolProfileEntries.$inferSelect,+ "selectorType" | "applicationId" | "connectionId" | "catalogEntryId" | "toolName" | "riskLevel">;++export type ProfileCatalogMatch = Pick<typeof toolCatalogEntries.$inferSelect,+ "id" | "applicationId" | "connectionId" | "toolName" | "riskLevel">;+export function profileEntryMatchesCatalog(- entry: typeof toolProfileEntries.$inferSelect,- catalogEntry: ProfileCatalogEntry,+ entry: ProfileEntryMatch,+ catalogEntry: ProfileCatalogMatch,): boolean {if (entry.selectorType === "application")return entry.applicationId === catalogEntry.applicationId;diff --git a/server/src/services/tool-access/profiles/resolution.ts b/server/src/services/tool-access/profiles/resolution.tsindex 80aa687068..3cc4d36df4 100644--- a/server/src/services/tool-access/profiles/resolution.ts+++ b/server/src/services/tool-access/profiles/resolution.ts@@ -3,20 +3,67 @@ import type { Db } from "@paperclipai/db";import { agents, toolCatalogEntries, toolProfileBindings, toolProfileEntries, toolProfiles } from "@paperclipai/db";import type { ToolCatalogEntry, ToolConnection, ToolProfileEffectiveSummary, ToolProfileWithDetails } from "@paperclipai/shared";import { effectiveToolProfileBindings, profileIdsInBindingOrder } from "../../tool-profile-binding-precedence.js";-import { buildProfileDetails, profileCatalogColumns, profileEntryMatchesCatalog, toProfileBinding, toProfileEntry, type ProfileCatalogEntry } from "./projection.js";+import { buildProfileDetails, profileCatalogColumns, profileEntryMatchesCatalog, toProfileBinding, toProfileEntry, type ProfileCatalogEntry, type ProfileEntryMatch, type ProfileCatalogMatch } from "./projection.js";type ProfileAssignmentDependencies = {assertOptionalAgent(companyId: string, agentId: string | null | undefined, label: string): Promise<void>;resolveInstalledConnectionsForAgent(companyId: string, agentId: string): Promise<ToolConnection[]>;toCatalogEntry(row: typeof toolCatalogEntries.$inferSelect): ToolCatalogEntry;};+function resolveCatalogAccess(+ profiles: Array<Pick<typeof toolProfiles.$inferSelect, "id" | "defaultAction">>,+ entries: Array<ProfileEntryMatch & { profileId: string; effect: string }>,+ catalog: ProfileCatalogMatch[],+) {+ const allowedCatalogIds = new Set<string>();+ const allowedToolNames = new Set<string>();+ const entriesByProfile = new Map<string, typeof entries>();+ for (const entry of entries) {+ const group = entriesByProfile.get(entry.profileId) ?? [];+ group.push(entry);+ entriesByProfile.set(entry.profileId, group);+ }+ for (const profile of profiles) {+ const profileEntries = entriesByProfile.get(profile.id) ?? [];+ const includes = profileEntries.filter(+ (entry) => entry.effect === "include",+ );+ const excludes = profileEntries.filter(+ (entry) => entry.effect === "exclude",+ );+ for (const catalogEntry of catalog) {+ if (+ excludes.some((entry) =>+ profileEntryMatchesCatalog(entry, catalogEntry),+ )+ )+ continue;+ if (+ profile.defaultAction === "allow" ||+ includes.some((entry) =>+ profileEntryMatchesCatalog(entry, catalogEntry),+ )+ ) {+ allowedCatalogIds.add(catalogEntry.id);+ allowedToolNames.add(catalogEntry.toolName);+ }+ }+ for (const entry of includes.filter(+ (item) => item.selectorType === "tool_name" && item.toolName,+ )) {+ const matchingExclude = excludes.some(+ (item) =>+ item.selectorType === "tool_name" &&+ item.toolName === entry.toolName,+ );+ if (!matchingExclude) allowedToolNames.add(entry.toolName!);+ }+ }+ return { allowedCatalogIds, allowedToolNames };+}+export function createToolProfileResolver(db: Db, { assertOptionalAgent, resolveInstalledConnectionsForAgent, toCatalogEntry }: ProfileAssignmentDependencies) {- async function resolveEffectiveProfiles<TEntry extends ProfileCatalogEntry, TAllowedTool>(- companyId: string,- agentId: string,- loadCatalog: () => PromiseLike<TEntry[]>,- toAllowedTool: (entry: TEntry) => TAllowedTool,- ): Promise<Omit<ToolProfileEffectiveSummary, "allowedTools"> & { allowedTools: TAllowedTool[] }> {+ async function readEffectiveProfileState(companyId: string, agentId: string) {await assertOptionalAgent(companyId,agentId,@@ -36,21 +83,8 @@ export function createToolProfileResolver(db: Db, { assertOptionalAgent, resolvebinding.targetId === companyId) ||(binding.targetType === "agent" && binding.targetId === agentId),);- if (matchingBindings.length === 0) {- return {- agentId,- profiles: [],- entries: [],- bindings: [],- allowedTools: [],- allowedToolNames: [],- installedConnections: await resolveInstalledConnectionsForAgent(- companyId,- agentId,- ),- };- }const candidateProfileIds = profileIdsInBindingOrder(matchingBindings);+ if (candidateProfileIds.length === 0) return { bindings: [], activeProfiles: [] };const candidateProfiles = await db.select().from(toolProfiles)@@ -73,6 +107,16 @@ export function createToolProfileResolver(db: Db, { assertOptionalAgent, resolve.filter((profile): profile is typeof toolProfiles.$inferSelect =>Boolean(profile && profile.status === "active"),);+ return { bindings, activeProfiles };+ }++ async function resolveEffectiveProfiles<TEntry extends ProfileCatalogEntry, TAllowedTool>(+ companyId: string,+ agentId: string,+ loadCatalog: () => PromiseLike<TEntry[]>,+ toAllowedTool: (entry: TEntry) => TAllowedTool,+ ): Promise<Omit<ToolProfileEffectiveSummary, "allowedTools"> & { allowedTools: TAllowedTool[] }> {+ const { bindings, activeProfiles } = await readEffectiveProfileState(companyId, agentId);if (activeProfiles.length === 0) {return {agentId,@@ -114,44 +158,7 @@ export function createToolProfileResolver(db: Db, { assertOptionalAgent, resolvelist.push(entry);entriesByProfile.set(entry.profileId, list);}- const allowedCatalogIds = new Set<string>();- const allowedToolNames = new Set<string>();- for (const profile of activeProfiles) {- const profileEntries = entriesByProfile.get(profile.id) ?? [];- const includes = profileEntries.filter(- (entry) => entry.effect === "include",- );- const excludes = profileEntries.filter(- (entry) => entry.effect === "exclude",- );- for (const catalogEntry of catalog) {- if (- excludes.some((entry) =>- profileEntryMatchesCatalog(entry, catalogEntry),- )- )- continue;- if (- profile.defaultAction === "allow" ||- includes.some((entry) =>- profileEntryMatchesCatalog(entry, catalogEntry),- )- ) {- allowedCatalogIds.add(catalogEntry.id);- allowedToolNames.add(catalogEntry.toolName);- }- }- for (const entry of includes.filter(- (item) => item.selectorType === "tool_name" && item.toolName,- )) {- const matchingExclude = excludes.some(- (item) =>- item.selectorType === "tool_name" &&- item.toolName === entry.toolName,- );- if (!matchingExclude) allowedToolNames.add(entry.toolName!);- }- }+ const { allowedCatalogIds, allowedToolNames } = resolveCatalogAccess(activeProfiles, entries, catalog);const agentIds = companyAgents.map((agent) => agent.id);const details: ToolProfileWithDetails[] = activeProfiles.map((profile) =>buildProfileDetails({@@ -182,7 +189,43 @@ export function createToolProfileResolver(db: Db, { assertOptionalAgent, resolve),};}+ async function getConnectionAssignmentsForAgent(companyId: string, agentId: string, connectionIds: string[]) {+ const { activeProfiles } = await readEffectiveProfileState(companyId, agentId);+ if (activeProfiles.length === 0 || connectionIds.length === 0) {+ return { allowedConnectionIds: [], installedConnections: await resolveInstalledConnectionsForAgent(companyId, agentId) };+ }+ const [entries, catalog] = await Promise.all([+ db.select({+ profileId: toolProfileEntries.profileId,+ effect: toolProfileEntries.effect,+ selectorType: toolProfileEntries.selectorType,+ applicationId: toolProfileEntries.applicationId,+ connectionId: toolProfileEntries.connectionId,+ catalogEntryId: toolProfileEntries.catalogEntryId,+ toolName: toolProfileEntries.toolName,+ riskLevel: toolProfileEntries.riskLevel,+ }).from(toolProfileEntries).where(and(+ eq(toolProfileEntries.companyId, companyId), inArray(toolProfileEntries.profileId, activeProfiles.map(profile => profile.id)),+ )),+ db.select({+ id: toolCatalogEntries.id,+ applicationId: toolCatalogEntries.applicationId,+ connectionId: toolCatalogEntries.connectionId,+ toolName: toolCatalogEntries.toolName,+ riskLevel: toolCatalogEntries.riskLevel,+ }).from(toolCatalogEntries).where(and(+ eq(toolCatalogEntries.companyId, companyId), eq(toolCatalogEntries.status, "active"), inArray(toolCatalogEntries.connectionId, connectionIds),+ )),+ ]);+ const { allowedCatalogIds } = resolveCatalogAccess(activeProfiles, entries, catalog);+ return {+ allowedConnectionIds: [...new Set(catalog.filter(entry => allowedCatalogIds.has(entry.id)).map(entry => entry.connectionId))],+ installedConnections: await resolveInstalledConnectionsForAgent(companyId, agentId),+ };+ }+return {+ getConnectionAssignmentsForAgent,getEffectiveProfilesForAgent: (companyId: string, agentId: string) =>resolveEffectiveProfiles(companyId,