Files
PaperClipAI/server/src/__tests__/tool-effective-assignments.test.ts
T
Devin FoleyandPaperclip 24758b9da1 Avoid loading tool schemas for effective assignments (#16969)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Tool profiles define which tools an agent can use.
> - Run preparation and connection checks resolve these assignments from
the database.
> - These callers need tool IDs and names, but the existing lookup also
reads complete schemas and provider metadata.
> - Repeated lookups transfer data that these callers discard.
> - This pull request adds a small assignment projection through the
same permission resolver.
> - The benefit is less database transfer and JSON work with current
permission checks and the same public response.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

Effective tool assignment reads during run preparation, native runtime
setup, and connection policy checks.

**Subsystem affected**

server/ — tool access and orchestration services.

**Current behavior**

Internal callers use the public effective-profile lookup. Its catalog
query reads complete tool rows, including input schemas, output schemas,
annotations, and provider metadata. These callers only use catalog IDs
and names.

**Proposed behavior**

Internal callers use an assignment lookup that selects catalog identity
and selector fields. Both lookups share one resolver. The public
effective-profile endpoint keeps its complete definitions.

**Reason and benefit**

Large catalogs increase database transfer and JSON work for every
assignment lookup. The smaller query avoids that payload without caching
permissions or changing query frequency.

**Breaking changes**

None. No route, schema, migration, permission rule, or public response
changes.

Related: Refs #16761, Refs #16723. The former narrows profile summary
reads. The latter changes how the gateway presents tool definitions.
Neither narrows this internal effective-assignment lookup.

## What Changed

- Share effective-profile resolution between full definitions and
assignment records.
- Select the existing catalog identity and selector projection for
internal assignments.
- Use the assignment lookup in run preparation, native runtime setup,
and connection policy checks.
- Add real PostgreSQL tests for selectors, exclusions, current profile
and binding state, company boundaries, and returned payload size.
- Document the database read contract.

## Verification

- Five focused test files passed: 521 tests. They cover tool access,
connection intents, runtime preparation, native runtime context, and the
new assignment lookup.
- `pnpm -r typecheck` passed.
- `pnpm check:module-boundaries` passed.
- The PostgreSQL fixture compares the full authorization result with the
assignment result. It checks all selector types, excludes removed tools,
and observes catalog, profile, and binding changes on later calls.
- The payload test measures rows returned by PostgreSQL before
application mapping. With large schema and annotation fields, the
assignment result is less than 1% of the full catalog payload. This is a
synthetic fixture result, not a fleet savings estimate.
- `pnpm build` passed.
- The full local suite is in progress. It found two Git fixture failures
that also reproduce on unchanged master with `init.defaultBranch=main`.
Both pass with a process-only `init.defaultBranch=master` setting. The
global Git configuration was not changed. This earlier failure remains
recorded; it is not counted as a clean first pass.
- Apex review: 5/5, no actionable comments. All 54 CI checks passed; two
conditional jobs were skipped.
- The broader local run also reached two UI test timeouts and one
adapter test timeout. All three passed when rerun in isolation with
unchanged source. The exact cause of these timeouts is not established.
No UI or adapter implementation is changed by this PR. The CLI
import/export journey passes its assertions but its local teardown fails
with `ENOTEMPTY` while a runtime context asset is written. Its CI check
passed. The complete local suite is not reported as a clean pass.

## Risks

- Both lookups share permission resolution. Existing tool access tests
and result parity checks cover that extraction.
- Future assignment callers must use the fields in the smaller result.
Typechecking rejects attempts to read full schemas from it.
- The lookup still scans the active company catalog and resolves current
connections on every call. This change reduces returned bytes; it does
not reduce query count or introduce a cache.
- No database migration or operational configuration change is required.

## Model Used

- OpenAI GPT-6 through Codex, with tool-assisted source inspection,
implementation, and test execution. The exact model variant and context
window are not exposed in this session.

## Checklist

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

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-20 08:42:59 -07:00

134 lines
8.7 KiB
TypeScript

import { 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 { toolAccessService } from "../services/tool-access.js";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
const support = await getEmbeddedPostgresTestSupport();
const describeDatabase = support.supported ? describe : describe.skip;
describeDatabase("effective tool assignments", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("effective-tool-assignments-");
db = createDb(database.connectionString, { maxConnections: 1 });
});
afterEach(async () => { await db.execute(sql`TRUNCATE TABLE companies CASCADE`); });
afterAll(async () => { await db?.$client.end({ timeout: 1 }); await database?.cleanup(); });
async function fixture() {
const [company] = await db.insert(companies).values({ name: "Assignments", issuePrefix: `AT${randomUUID().slice(0, 6)}` }).returning();
const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Assigned agent" }).returning();
const [application] = await db.insert(toolApplications).values({ companyId: company.id, name: "Fixture app", type: "mcp_http" }).returning();
const [connection] = await db.insert(toolConnections).values({ companyId: company.id, applicationId: application.id,
name: "Fixture connection", uid: randomUUID(), transport: "mcp_remote", status: "active", enabled: true }).returning();
const payload = "schema payload ".repeat(4096);
const entries = await db.insert(toolCatalogEntries).values([
{ name: "read_item", riskLevel: "read" as const },
{ name: "write_item", riskLevel: "write" as const },
{ name: "removed_item", riskLevel: "read" as const, status: "removed" as const },
].map(entry => ({ companyId: company.id, applicationId: application.id, connectionId: connection.id,
...entry, toolName: entry.name, versionHash: entry.name, inputSchema: { type: "object", description: payload },
outputSchema: { description: payload }, annotations: { description: payload },
firstSeenAt: new Date(Date.now() - 86_400_000) }))).returning();
const [profile] = await db.insert(toolProfiles).values({ companyId: company.id, profileKey: "fixture", name: "Fixture", defaultAction: "deny" }).returning();
await db.insert(toolProfileBindings).values({ companyId: company.id, profileId: profile.id, targetType: "agent", targetId: agent.id });
const [read, write, removed] = entries;
return { company, agent, application, connection, profile, read, write, removed };
}
async function compare(f: Awaited<ReturnType<typeof fixture>>) {
const service = toolAccessService(db);
const full = await service.getEffectiveProfilesForAgent(f.company.id, f.agent.id);
const assignments = await service.getEffectiveToolAssignmentsForAgent(f.company.id, f.agent.id);
expect(assignments).toEqual({ ...full, allowedTools: full.allowedTools.map(
({ id, applicationId, connectionId, toolName }) => ({ id, applicationId, connectionId, toolName }),
) });
return { service, full, assignments };
}
it.each(["application", "connection", "catalog_entry", "tool_name", "risk_level"] as const)("preserves %s selectors and exclusions", async selectorType => {
const f = await fixture();
await db.insert(toolProfileEntries).values({ companyId: f.company.id, profileId: f.profile.id, selectorType, effect: "include",
...(selectorType === "application" ? { applicationId: f.application.id } : {}),
...(selectorType === "connection" ? { connectionId: f.connection.id } : {}),
...(selectorType === "catalog_entry" ? { catalogEntryId: f.read.id } : {}),
...(selectorType === "tool_name" ? { toolName: f.read.toolName } : {}),
...(selectorType === "risk_level" ? { riskLevel: "read" as const } : {}),
});
await db.insert(toolProfileEntries).values({ companyId: f.company.id, profileId: f.profile.id,
selectorType: "catalog_entry", effect: "exclude", catalogEntryId: f.write.id });
const { full, assignments } = await compare(f);
expect(assignments.allowedTools.map(tool => tool.id)).toEqual([f.read.id]);
expect(full.allowedTools[0].inputSchema).toEqual(f.read.inputSchema);
expect(full.allowedTools[0].outputSchema).toEqual(f.read.outputSchema);
expect(full.allowedTools[0].annotations).toEqual(f.read.annotations);
});
it("keeps unresolved exact names and observes changed catalog, profile and binding state", async () => {
const f = await fixture();
await db.insert(toolProfileEntries).values([
{ companyId: f.company.id, profileId: f.profile.id, selectorType: "risk_level", effect: "include", riskLevel: "read" },
{ companyId: f.company.id, profileId: f.profile.id, selectorType: "tool_name", effect: "include", toolName: "not_discovered_yet" },
]);
expect((await compare(f)).assignments.allowedToolNames).toEqual(["not_discovered_yet", "read_item"]);
await db.update(toolCatalogEntries).set({ riskLevel: "write" }).where(eq(toolCatalogEntries.id, f.read.id));
expect((await compare(f)).assignments.allowedTools).toEqual([]);
await db.update(toolProfiles).set({ status: "archived" }).where(eq(toolProfiles.id, f.profile.id));
expect((await compare(f)).assignments.profiles).toEqual([]);
await db.update(toolProfiles).set({ status: "active", defaultAction: "allow" }).where(eq(toolProfiles.id, f.profile.id));
expect((await compare(f)).assignments.allowedTools.map(tool => tool.id)).toEqual([f.read.id, f.write.id]);
await db.delete(toolProfileBindings).where(eq(toolProfileBindings.profileId, f.profile.id));
expect((await compare(f)).assignments.allowedTools).toEqual([]);
});
it("preserves company bindings and rejects an agent from another company", async () => {
const f = await fixture();
await db.update(toolProfileBindings).set({ targetType: "company", targetId: f.company.id }).where(eq(toolProfileBindings.profileId, f.profile.id));
await db.update(toolProfiles).set({ defaultAction: "allow" }).where(eq(toolProfiles.id, f.profile.id));
expect((await compare(f)).assignments.allowedToolNames).toEqual(["read_item", "write_item"]);
const [other] = await db.insert(companies).values({ name: "Other", issuePrefix: `OT${randomUUID().slice(0, 6)}` }).returning();
const [foreign] = await db.insert(agents).values({ companyId: other.id, name: "Foreign" }).returning();
await expect(toolAccessService(db).getEffectiveToolAssignmentsForAgent(f.company.id, foreign.id)).rejects.toThrow("same company");
expect((await toolAccessService(db).getEffectiveToolAssignmentsForAgent(other.id, foreign.id)).allowedTools).toEqual([]);
});
it("reads small catalog rows from real PostgreSQL while preserving complete public definitions", async () => {
const f = await fixture();
await db.update(toolProfiles).set({ defaultAction: "allow" }).where(eq(toolProfiles.id, f.profile.id));
const observed: Array<{ rows: number; bytes: number }> = [];
const measuredDb = new Proxy(db, { get(target, key) {
if (key !== "select") return Reflect.get(target, key);
return (...fields: Parameters<Db["select"]>) => {
const builder = target.select(...fields), from = builder.from.bind(builder);
builder.from = ((...args: Parameters<typeof from>) => {
const selection = from(...args);
if (args[0] === toolCatalogEntries) {
const execute = selection.execute.bind(selection);
selection.execute = async () => {
const rows = await execute();
observed.push({ rows: rows.length, bytes: Buffer.byteLength(JSON.stringify(rows)) });
return rows;
};
}
return selection;
}) as typeof builder.from;
return builder;
};
} });
const service = toolAccessService(measuredDb);
const full = await service.getEffectiveProfilesForAgent(f.company.id, f.agent.id);
const assignments = await service.getEffectiveToolAssignmentsForAgent(f.company.id, f.agent.id);
expect(assignments.allowedTools.map(tool => tool.id)).toEqual(full.allowedTools.map(tool => tool.id));
expect(observed).toHaveLength(2);
expect(observed[1].rows).toBe(observed[0].rows);
expect(observed[1].bytes).toBeLessThan(observed[0].bytes / 100);
expect(full.allowedTools[0].inputSchema).toEqual(f.read.inputSchema);
});
});