[codex] Add built-in agents and Reflection Coach bundle (#9206)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Operators need first-party agent capabilities for repeatable company
work, not just manually created one-off agents.
> - Built-in agents need to behave like normal company-scoped agents
while preserving approval gates, permissions, budgets, and audit trails.
> - Reflection and coaching work also needs bundled instructions, skill
content, and a routine so the feature can be installed and reset
predictably.
> - The API, database, UI, portability, and tests all need to agree on
the built-in lifecycle from not provisioned through setup, approval,
ready, paused, and reset.
> - This pull request adds built-in agent provisioning and the
Reflection Coach bundle end-to-end.
> - The benefit is a safer first-party path for Paperclip-managed agents
without bypassing the same governance model used for operator-created
agents.

## Linked Issues or Issue Description

No public GitHub issue was found for this exact built-in agent and
Reflection Coach bundle work.

Problem/motivation:
- Paperclip did not have a first-party built-in agent lifecycle for
product-owned agents.
- Bundled agent resources such as default instructions, skills, and
routines needed managed ownership and reset semantics.
- Approval-gated companies needed built-in setup to preserve requested
adapter, budget, manager, and permission state through board approval.
- The board UI needed clear built-in badges, setup affordances,
readiness state, and bundle status without exposing secrets.

Proposed solution:
- Add a company-scoped built-in agent registry,
provisioning/reset/reconcile/status APIs, and Reflection Coach bundled
resources.
- Track bundled managed resources in the database with idempotent
migration behavior.
- Reuse existing agent approval, authorization, budget, and activity-log
paths instead of creating a bypass.
- Add UI setup, badges, gates, bundle panels, and route coverage for
built-in agents.

Duplicate search:
- Searched GitHub PRs for `built-in agents Reflection Coach
repo:paperclipai/paperclip`; only this PR was returned.
- Searched GitHub issues for the same query; no public issues were
returned.

## What Changed

- Added built-in agent definitions, lifecycle state derivation,
provisioning, reset, reconcile, status, and routine-control routes.
- Added the `built_in_managed_resources` migration and schema exports
for bundled instructions, skill, and routine ownership.
- Added the Reflection Coach built-in bundle with default instructions,
skill catalog content, routine template, default permissions, and
managed-resource drift handling.
- Added approval-aware provisioning behavior that preserves requested
adapter config, budgets, manager assignment, and built-in permissions
through hire approval.
- Added authorization and mutation gates for built-in agent and skill
changes, including consented Reflection Coach change paths.
- Added UI surfaces for built-in agent setup, roster/detail badges,
readiness gates, bundle status, routine controls, and route filtering.
- Added company import/export and validator coverage for built-in
managed resources and low-trust/red-team presets.
- Addressed Greptile follow-ups for pending approval reconciliation,
consent-gate error propagation, config-read authorization fallback,
approval-path manager preservation, and non-model adapter provisioning.

## Verification

Local verification:
- `git diff --check public/master..HEAD` passed.
- `pnpm check:token-gates` passed with all gates clean.
- `pnpm exec vitest run
ui/src/components/ConfigureBuiltInAgentModal.test.tsx` passed: 1 file, 4
tests.
- `pnpm exec vitest run ui/src/components/EntityRow.test.tsx
ui/src/pages/Agents.test.tsx ui/src/components/BuiltInAgentGate.test.tsx
ui/src/components/ConfigureBuiltInAgentModal.test.tsx
ui/src/components/BuiltInBundlePanel.test.tsx
ui/src/pages/InstanceExperimentalSettings.test.tsx
ui/src/pages/Routines.test.tsx` passed: 7 files, 64 tests.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/built-in-agents.test.ts
src/__tests__/authorization-service.test.ts
src/__tests__/company-skills-routes.test.ts` passed: 3 files, 91 tests.
- `pnpm --filter @paperclipai/db check:migrations` passed.
- `pnpm -r typecheck` passed after the rebase; `pnpm --filter ui
typecheck` passed after the final UI review fix.

Remote verification on latest head
`1c61f693a4ec881d739022b0e75a8ca8bf8c2cd8`:
- Merge state: `CLEAN`.
- Greptile: `5/5`, zero unresolved Greptile threads.
- PR check rollup: all checks successful, neutral, or skipped as
expected.
- Passing gates include Build, Typecheck + Release Registry, all server
shards, all workspace shards, all serialized server suites, e2e, Canary
Dry Run, policy, review, verify, Socket, Superagent, and Snyk.

## Risks

- This adds a new managed-resource table and migration; the migration
uses idempotent create/add/index guards and passed migration safety
checks.
- Built-in agent provisioning touches approval and authorization paths;
tests cover pending approval preservation, stale retry rejection,
consent gates, and config-read fallback behavior.
- Reflection Coach creates managed instructions, skill, and routine
resources; drift/reset behavior is covered by service tests and redacted
API responses.
- Non-model adapter setup now provisions a `needs_setup` built-in row
before command/endpoint fields are complete; this matches the server
lifecycle and is covered by the setup modal regression test.

## Model Used

OpenAI Codex coding agent based on GPT-5. Exact hosted model ID,
context-window size, and reasoning-mode labels are not exposed in this
runtime; tool use, shell execution, GitHub CLI/API access, and local
code editing were enabled.

## 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>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-07-09 16:29:30 -05:00
1 parent 53d09d4c34
commit 8b6a06ee25
99 files changed
+10109 -310

No files matched your search

@@ -80,6 +80,7 @@ function registerModuleMocks() {
agentInstructionsService: () => mockAgentInstructionsService,
accessService: () => mockAccessService,
approvalService: () => mockApprovalService,
builtInAgentService: () => ({ ensureCompanyDefaultAgentGrants: vi.fn() }),
companySkillService: () => mockCompanySkillService,
budgetService: () => mockBudgetService,
heartbeatService: () => mockHeartbeatService,
@@ -69,6 +69,7 @@ vi.mock("../services/index.js", () => ({
agentInstructionsService: () => mockAgentInstructionsService,
accessService: () => mockAccessService,
approvalService: () => mockApprovalService,
builtInAgentService: () => ({ ensureCompanyDefaultAgentGrants: vi.fn() }),
companySkillService: () => mockCompanySkillService,
budgetService: () => mockBudgetService,
heartbeatService: () => mockHeartbeatService,
@@ -94,6 +95,7 @@ function registerModuleMocks() {
agentInstructionsService: () => mockAgentInstructionsService,
accessService: () => mockAccessService,
approvalService: () => mockApprovalService,
builtInAgentService: () => ({ ensureCompanyDefaultAgentGrants: vi.fn() }),
companySkillService: () => mockCompanySkillService,
budgetService: () => mockBudgetService,
heartbeatService: () => mockHeartbeatService,
@@ -182,6 +182,7 @@ vi.mock("../services/index.js", () => ({
agentInstructionsService: () => mockAgentInstructionsService,
accessService: () => mockAccessService,
approvalService: () => mockApprovalService,
builtInAgentService: () => ({ ensureCompanyDefaultAgentGrants: vi.fn() }),
companySkillService: () => mockCompanySkillService,
budgetService: () => mockBudgetService,
heartbeatService: () => mockHeartbeatService,
@@ -8,6 +8,10 @@ const mockAgentService = vi.hoisted(() => ({
resolveByReference: vi.fn(),
}));
const mockBuiltInAgentService = vi.hoisted(() => ({
ensureCompanyDefaultAgentGrants: vi.fn(),
}));
const mockAgentInstructionsService = vi.hoisted(() => ({
getBundle: vi.fn(),
readFile: vi.fn(),
@@ -42,6 +46,7 @@ vi.mock("../services/index.js", () => ({
agentInstructionsService: () => mockAgentInstructionsService,
accessService: () => mockAccessService,
approvalService: () => ({}),
builtInAgentService: () => mockBuiltInAgentService,
companySkillService: () => ({ listRuntimeSkillEntries: vi.fn() }),
budgetService: () => ({}),
environmentService: () => mockEnvironmentService,
@@ -73,6 +78,7 @@ function registerModuleMocks() {
agentInstructionsService: () => mockAgentInstructionsService,
accessService: () => mockAccessService,
approvalService: () => ({}),
builtInAgentService: () => mockBuiltInAgentService,
companySkillService: () => ({ listRuntimeSkillEntries: vi.fn() }),
budgetService: () => ({}),
heartbeatService: () => ({}),
@@ -98,7 +104,17 @@ function registerModuleMocks() {
}));
}
async function createApp() {
function boardActor() {
return {
type: "board",
userId: "local-board",
companyIds: ["company-1"],
source: "local_implicit",
isInstanceAdmin: false,
};
}
async function createApp(actor: Record<string, unknown> = boardActor()) {
const [{ agentRoutes }, { errorHandler }] = await Promise.all([
vi.importActual<typeof import("../routes/agents.js")>("../routes/agents.js"),
vi.importActual<typeof import("../middleware/index.js")>("../middleware/index.js"),
@@ -106,13 +122,7 @@ async function createApp() {
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
(req as any).actor = {
type: "board",
userId: "local-board",
companyIds: ["company-1"],
source: "local_implicit",
isInstanceAdmin: false,
};
(req as any).actor = actor;
next();
});
app.use("/api", agentRoutes({} as any));
@@ -166,6 +176,21 @@ function makeAgent() {
};
}
function makeReflectionCoachAgent(overrides: Record<string, unknown> = {}) {
return {
...makeAgent(),
id: "22222222-2222-4222-8222-222222222222",
name: "Reflection Coach",
metadata: {
paperclipBuiltInAgent: {
key: "reflection-coach",
featureKeys: ["reflection-coach"],
},
},
...overrides,
};
}
describe("agent instructions bundle routes", () => {
beforeEach(() => {
vi.resetModules();
@@ -174,6 +199,7 @@ describe("agent instructions bundle routes", () => {
vi.doUnmock("../middleware/index.js");
registerModuleMocks();
vi.clearAllMocks();
mockBuiltInAgentService.ensureCompanyDefaultAgentGrants.mockResolvedValue(0);
mockSyncInstructionsBundleConfigFromFilePath.mockImplementation((_agent, config) => config);
mockFindServerAdapter.mockImplementation((_type: string) => ({ type: _type }));
mockAccessService.decide.mockResolvedValue({
@@ -259,6 +285,110 @@ describe("agent instructions bundle routes", () => {
expect(mockAgentInstructionsService.getBundle).toHaveBeenCalled();
});
it("denies non-privileged agents from reading peer instructions bundles", async () => {
mockAgentService.getById.mockImplementation(async (id: string) => {
if (id === "agent-reader") {
return {
...makeAgent(),
id: "agent-reader",
name: "Reader",
permissions: { canCreateAgents: false },
};
}
return makeAgent();
});
mockAccessService.decide.mockResolvedValue({
allowed: false,
reason: "deny_no_grant",
explanation: "Missing permission: agents:configure or agents:suggest-changes.",
});
const res = await requestApp(
await createApp({
type: "agent",
agentId: "agent-reader",
companyId: "company-1",
source: "agent_key",
}),
(baseUrl) => request(baseUrl)
.get("/api/agents/11111111-1111-4111-8111-111111111111/instructions-bundle"),
);
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(res.body.error).toContain("Missing permission");
expect(mockAccessService.decide).toHaveBeenCalledWith(expect.objectContaining({
action: "agent_config:read",
resource: {
type: "agent",
companyId: "company-1",
agentId: "11111111-1111-4111-8111-111111111111",
},
}));
expect(mockAgentInstructionsService.getBundle).not.toHaveBeenCalled();
});
it("allows agents to read their own instructions bundles", async () => {
const res = await requestApp(
await createApp({
type: "agent",
agentId: "11111111-1111-4111-8111-111111111111",
companyId: "company-1",
source: "agent_key",
}),
(baseUrl) => request(baseUrl)
.get("/api/agents/11111111-1111-4111-8111-111111111111/instructions-bundle"),
);
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(mockAgentInstructionsService.getBundle).toHaveBeenCalled();
});
it("allows agents with suggest grants to read peer instructions bundles", async () => {
mockAccessService.decide.mockResolvedValue({
allowed: true,
reason: "allow_explicit_grant",
explanation: "Allowed by explicit grant agents:suggest-changes.",
grant: {
principalType: "agent",
principalId: "coach-agent",
permissionKey: "agents:suggest-changes",
scope: null,
},
});
mockAgentService.getById.mockImplementation(async (id: string) => {
if (id === "coach-agent") {
return makeReflectionCoachAgent({ id: "coach-agent" });
}
return makeAgent();
});
const res = await requestApp(
await createApp({
type: "agent",
agentId: "coach-agent",
companyId: "company-1",
source: "agent_key",
}),
(baseUrl) => request(baseUrl)
.get("/api/agents/11111111-1111-4111-8111-111111111111/instructions-bundle/file")
.query({ path: "AGENTS.md" }),
);
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(mockAccessService.decide).toHaveBeenCalledWith(expect.objectContaining({
action: "agent_config:read",
resource: {
type: "agent",
companyId: "company-1",
agentId: "11111111-1111-4111-8111-111111111111",
},
}));
expect(mockAgentInstructionsService.readFile).toHaveBeenCalledWith(
expect.objectContaining({ id: "11111111-1111-4111-8111-111111111111" }),
"AGENTS.md",
);
});
it("writes a bundle file and persists compatibility config", async () => {
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
.put("/api/agents/11111111-1111-4111-8111-111111111111/instructions-bundle/file?companyId=company-1")
@@ -63,6 +63,7 @@ function registerModuleMocks() {
hasPermission: vi.fn(async () => true),
}),
approvalService: () => ({}),
builtInAgentService: () => ({ ensureCompanyDefaultAgentGrants: vi.fn() }),
companySkillService: () => ({ listRuntimeSkillEntries: vi.fn() }),
budgetService: () => ({}),
heartbeatService: () => mockHeartbeatService,
@@ -51,6 +51,10 @@ const mockAgentService = vi.hoisted(() => ({
resolveByReference: vi.fn(),
}));
const mockBuiltInAgentService = vi.hoisted(() => ({
ensureCompanyDefaultAgentGrants: vi.fn(),
}));
const mockAccessService = vi.hoisted(() => ({
canUser: vi.fn(),
decide: vi.fn(),
@@ -195,6 +199,7 @@ function registerModuleMocks() {
agentInstructionsService: () => mockAgentInstructionsService,
accessService: () => mockAccessService,
approvalService: () => mockApprovalService,
builtInAgentService: () => mockBuiltInAgentService,
companySkillService: () => mockCompanySkillService,
budgetService: () => mockBudgetService,
heartbeatService: () => mockHeartbeatService,
@@ -309,6 +314,7 @@ describe.sequential("agent permission routes", () => {
mockAgentService.updatePermissions.mockReset();
mockAgentService.getChainOfCommand.mockReset();
mockAgentService.resolveByReference.mockReset();
mockBuiltInAgentService.ensureCompanyDefaultAgentGrants.mockReset();
mockAccessService.canUser.mockReset();
mockAccessService.decide.mockReset();
mockAccessService.hasPermission.mockReset();
@@ -354,6 +360,7 @@ describe.sequential("agent permission routes", () => {
});
mockAgentService.update.mockResolvedValue(baseAgent);
mockAgentService.updatePermissions.mockResolvedValue(baseAgent);
mockBuiltInAgentService.ensureCompanyDefaultAgentGrants.mockResolvedValue(0);
mockAccessService.canUser.mockResolvedValue(true);
mockAccessService.decide.mockImplementation(async (input: { action?: string }) => {
const allowed = Boolean(await mockAccessService.canUser());
@@ -866,6 +873,7 @@ describe.sequential("agent permission routes", () => {
true,
"agent-admin-user",
);
expect(mockBuiltInAgentService.ensureCompanyDefaultAgentGrants).toHaveBeenCalledWith(companyId);
});
it("rejects direct agent creation when new agents require board approval", async () => {
@@ -1699,11 +1707,10 @@ describe.sequential("agent permission routes", () => {
expect(res.status).toBe(200);
});
it("denies an agent actor without agents:create when reading peer config", async () => {
// Agent actors must still pass the agents:create gate (explicit
// grant OR canCreateAgents permission on the agent record). A peer
// agent in the same company without that permission must not be
// able to read another agent's configuration.
it("denies an agent actor without configure or suggest grants when reading peer config", async () => {
// Agent actors must pass the agent configuration read ladder. A peer
// agent in the same company without agents:configure or
// agents:suggest-changes must not read another agent's configuration.
const peerAgentId = "33333333-3333-4333-8333-333333333333";
const peerAgent = { ...baseAgent, id: peerAgentId };
mockAgentService.getById.mockImplementation(async (id: string) => {
@@ -1713,7 +1720,11 @@ describe.sequential("agent permission routes", () => {
}
return null;
});
mockAccessService.hasPermission.mockResolvedValue(false);
mockAccessService.decide.mockResolvedValue({
allowed: false,
reason: "deny_no_grant",
explanation: "Missing permission: agents:configure or agents:suggest-changes.",
});
const app = await createApp({
type: "agent",
@@ -1726,11 +1737,15 @@ describe.sequential("agent permission routes", () => {
const res = await request(app).get(`/api/agents/${peerAgentId}/configuration`);
expect(res.status).toBe(403);
expect(mockAccessService.decide).toHaveBeenCalledWith(expect.objectContaining({
action: "agent_config:read",
resource: { type: "company", companyId },
}));
});
it("allows an agent actor with agents:create grant to read peer config", async () => {
// When an agent actor has an explicit agents:create grant in the
// access service, the read gate must let them through.
it("allows an agent actor with agents:suggest-changes grant to read peer config", async () => {
// Suggest-tier authority implies read access so the agent can prepare a
// consented diff without receiving direct change authority.
const peerAgentId = "44444444-4444-4444-8444-444444444444";
const peerAgent = { ...baseAgent, id: peerAgentId };
mockAgentService.getById.mockImplementation(async (id: string) => {
@@ -1740,11 +1755,17 @@ describe.sequential("agent permission routes", () => {
}
return null;
});
mockAccessService.hasPermission.mockImplementation(
async (_companyId: string, _principalType: string, principalId: string, key: string) => {
return principalId === agentId && key === "agents:create";
mockAccessService.decide.mockResolvedValue({
allowed: true,
reason: "allow_explicit_grant",
explanation: "Allowed by explicit grant agents:suggest-changes.",
grant: {
principalType: "agent",
principalId: agentId,
permissionKey: "agents:suggest-changes",
scope: null,
},
);
});
const app = await createApp({
type: "agent",
@@ -1757,6 +1778,10 @@ describe.sequential("agent permission routes", () => {
const res = await request(app).get(`/api/agents/${peerAgentId}/configuration`);
expect(res.status).toBe(200);
expect(mockAccessService.decide).toHaveBeenCalledWith(expect.objectContaining({
action: "agent_config:read",
resource: { type: "company", companyId },
}));
});
});
@@ -85,6 +85,7 @@ vi.mock("../services/index.js", () => ({
agentInstructionsService: () => mockAgentInstructionsService,
accessService: () => mockAccessService,
approvalService: () => mockApprovalService,
builtInAgentService: () => ({ ensureCompanyDefaultAgentGrants: vi.fn() }),
companySkillService: () => mockCompanySkillService,
budgetService: () => mockBudgetService,
environmentService: () => mockEnvironmentService,
@@ -123,6 +124,7 @@ function registerModuleMocks() {
agentInstructionsService: () => mockAgentInstructionsService,
accessService: () => mockAccessService,
approvalService: () => mockApprovalService,
builtInAgentService: () => ({ ensureCompanyDefaultAgentGrants: vi.fn() }),
companySkillService: () => mockCompanySkillService,
budgetService: () => mockBudgetService,
heartbeatService: () => mockHeartbeatService,
@@ -695,6 +697,7 @@ describe.sequential("agent skill routes", () => {
instructionsFilePath: `/tmp/${createdAgentId}/instructions/AGENTS.md`,
}),
}),
expect.objectContaining({ allowPendingApprovalConfigUpdate: true }),
);
expect(mockAgentService.update.mock.calls.at(-1)?.[1]).not.toMatchObject({
adapterConfig: expect.objectContaining({
@@ -45,6 +45,7 @@ vi.mock("../services/index.js", () => ({
agentInstructionsService: () => ({}),
accessService: () => mockAccessService,
approvalService: () => ({}),
builtInAgentService: () => ({ ensureCompanyDefaultAgentGrants: vi.fn() }),
companySkillService: () => ({
listRuntimeSkillEntries: vi.fn(async () => []),
resolveRequestedSkillKeys: vi.fn(async () => []),
@@ -0,0 +1,158 @@
import { randomUUID } from "node:crypto";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import { eq } from "drizzle-orm";
import {
agents,
approvals,
activityLog,
budgetPolicies,
companies,
createDb,
} from "@paperclipai/db";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import { agentService } from "../services/agents.ts";
import { approvalService } from "../services/approvals.ts";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
function issuePrefix(id: string) {
return `T${id.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
}
if (!embeddedPostgresSupport.supported) {
console.warn(
`Skipping embedded Postgres pending approval agent tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
);
}
describeEmbeddedPostgres("pending approval agent config integrity", () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-pending-agent-config-");
db = createDb(tempDb.connectionString);
}, 20_000);
afterEach(async () => {
await db.delete(activityLog);
await db.delete(budgetPolicies);
await db.delete(approvals);
await db.delete(agents);
await db.delete(companies);
});
afterAll(async () => {
await tempDb?.cleanup();
});
async function seedCompany() {
const companyId = randomUUID();
await db.insert(companies).values({
id: companyId,
name: "Paperclip",
issuePrefix: issuePrefix(companyId),
requireBoardApprovalForNewAgents: true,
});
return companyId;
}
it("freezes generic pending hire config and reapplies the approval snapshot on activation", async () => {
const companyId = await seedCompany();
const agentSvc = agentService(db);
const approvalSvc = approvalService(db);
const pending = await agentSvc.create(companyId, {
name: "Pending Coder",
role: "engineer",
title: "Software Engineer",
icon: "code",
capabilities: "Writes code",
adapterType: "process",
adapterConfig: { command: "echo safe" },
runtimeConfig: { maxConcurrentRuns: 1 },
budgetMonthlyCents: 1234,
metadata: { source: "hire-form" },
status: "pending_approval",
spentMonthlyCents: 0,
permissions: {},
lastHeartbeatAt: null,
});
const approval = await approvalSvc.create(companyId, {
type: "hire_agent",
requestedByAgentId: null,
requestedByUserId: "board-user",
status: "pending",
payload: {
name: "Pending Coder",
role: "engineer",
title: "Software Engineer",
icon: "code",
reportsTo: null,
capabilities: "Writes code",
adapterType: "process",
adapterConfig: { command: "echo safe" },
runtimeConfig: { maxConcurrentRuns: 1 },
budgetMonthlyCents: 1234,
metadata: { source: "hire-form" },
agentId: pending.id,
},
decisionNote: null,
decidedByUserId: null,
decidedAt: null,
updatedAt: new Date(),
});
await expect(agentSvc.update(pending.id, {
name: "Tampered Coder",
adapterConfig: { command: "echo malicious" },
runtimeConfig: { maxConcurrentRuns: 99 },
})).rejects.toMatchObject({
status: 409,
details: {
code: "pending_approval_agent_config_frozen",
agentId: pending.id,
fields: ["name", "adapterConfig", "runtimeConfig"],
},
});
await expect(agentSvc.updatePermissions(pending.id, {
canCreateAgents: true,
})).rejects.toMatchObject({
status: 409,
details: {
code: "pending_approval_agent_config_frozen",
agentId: pending.id,
fields: ["permissions"],
},
});
await db
.update(agents)
.set({
name: "Tampered Coder",
adapterConfig: { command: "echo malicious" },
runtimeConfig: { maxConcurrentRuns: 99 },
metadata: { source: "tampered" },
})
.where(eq(agents.id, pending.id));
await approvalSvc.approve(approval.id, "board-user", "Approved generic hire");
await expect(agentSvc.getById(pending.id)).resolves.toMatchObject({
status: "idle",
name: "Pending Coder",
role: "engineer",
title: "Software Engineer",
icon: "code",
capabilities: "Writes code",
adapterType: "process",
adapterConfig: { command: "echo safe" },
runtimeConfig: { maxConcurrentRuns: 1 },
budgetMonthlyCents: 1234,
metadata: { source: "hire-form" },
});
});
});
@@ -101,7 +101,7 @@ describe("approvalService resolution idempotency", () => {
const result = await svc.approve("approval-1", "board", "ship it");
expect(result.applied).toBe(true);
expect(mockAgentService.activatePendingApproval).toHaveBeenCalledWith("agent-1");
expect(mockAgentService.activatePendingApproval).toHaveBeenCalledWith("agent-1", approved.payload);
expect(mockNotifyHireApproved).toHaveBeenCalledTimes(1);
});
@@ -12,7 +12,7 @@ import {
principalPermissionGrants,
projects,
} from "@paperclipai/db";
import { LOW_TRUST_REVIEW_PRESET } from "@paperclipai/shared";
import { LOW_TRUST_REVIEW_PRESET, type PermissionKey } from "@paperclipai/shared";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
@@ -100,7 +100,7 @@ async function grantAgentPermission(
db: ReturnType<typeof createDb>,
companyId: string,
agentId: string,
permissionKey: "tasks:assign" | "tasks:assign_scope",
permissionKey: PermissionKey,
scope: Record<string, unknown> | null = null,
) {
await db.insert(companyMemberships).values({
@@ -141,7 +141,7 @@ async function grantUserPermission(
db: ReturnType<typeof createDb>,
companyId: string,
userId: string,
permissionKey: "tasks:assign" | "tasks:assign_scope",
permissionKey: PermissionKey,
scope: Record<string, unknown> | null = null,
) {
await db.insert(companyMemberships).values({
@@ -224,23 +224,35 @@ describeEmbeddedPostgres("authorization service", () => {
expect(decision.explanation).toContain("Allowed by explicit grant tasks:assign");
});
it("allows agent grants for agent configuration decisions", async () => {
const company = await createCompany(db, "AgentGrant");
it("allows suggest grants to read peer agent configuration", async () => {
const company = await createCompany(db, "AgentReadGrant");
const actorAgent = await createAgent(db, company.id);
const targetAgent = await createAgent(db, company.id);
await db.insert(companyMemberships).values({
companyId: company.id,
principalType: "agent",
principalId: actorAgent.id,
status: "active",
membershipRole: "member",
await grantAgentPermission(db, company.id, actorAgent.id, "agents:suggest-changes");
const decision = await authorizationService(db).decide({
actor: { type: "agent", agentId: actorAgent.id, companyId: company.id, source: "agent_key" },
action: "agent_config:read",
resource: { type: "agent", companyId: company.id, agentId: targetAgent.id },
});
await db.insert(principalPermissionGrants).values({
companyId: company.id,
principalType: "agent",
principalId: actorAgent.id,
permissionKey: "agents:create",
grantedByUserId: null,
expect(decision).toMatchObject({
allowed: true,
reason: "allow_explicit_grant",
grant: {
principalType: "agent",
principalId: actorAgent.id,
permissionKey: "agents:suggest-changes",
},
});
});
it("falls back to the direct config-read grant decision when a suggest read grant is scoped away", async () => {
const company = await createCompany(db, "AgentReadScopedSuggestGrant");
const actorAgent = await createAgent(db, company.id);
const targetAgent = await createAgent(db, company.id);
await grantAgentPermission(db, company.id, actorAgent.id, "agents:suggest-changes", {
projectId: randomUUID(),
});
const decision = await authorizationService(db).decide({
@@ -249,8 +261,129 @@ describeEmbeddedPostgres("authorization service", () => {
resource: { type: "agent", companyId: company.id, agentId: targetAgent.id },
});
expect(decision.allowed).toBe(true);
expect(decision.grant?.permissionKey).toBe("agents:create");
expect(decision).toMatchObject({
allowed: false,
reason: "deny_missing_grant",
explanation: "Missing permission: agents:configure.",
});
});
it("enforces direct or consented suggest grants for agent configuration changes", async () => {
const company = await createCompany(db, "AgentChangeGrant");
const directAgent = await createAgent(db, company.id);
const suggestAgent = await createAgent(db, company.id);
const noGrantAgent = await createAgent(db, company.id);
const targetAgent = await createAgent(db, company.id);
await grantAgentPermission(db, company.id, directAgent.id, "agents:configure");
await grantAgentPermission(db, company.id, suggestAgent.id, "agents:suggest-changes");
await db.insert(companyMemberships).values({
companyId: company.id,
principalType: "agent",
principalId: noGrantAgent.id,
status: "active",
membershipRole: "member",
});
const authz = authorizationService(db);
await expect(authz.decide({
actor: { type: "agent", agentId: directAgent.id, companyId: company.id, source: "agent_key" },
action: "agent_config:update",
resource: { type: "agent", companyId: company.id, agentId: targetAgent.id },
scope: { requiresChangeGrant: true },
})).resolves.toMatchObject({
allowed: true,
reason: "allow_direct_change",
grant: { permissionKey: "agents:configure" },
});
await expect(authz.decide({
actor: { type: "agent", agentId: suggestAgent.id, companyId: company.id, source: "agent_key" },
action: "agent_config:update",
resource: { type: "agent", companyId: company.id, agentId: targetAgent.id },
scope: { requiresChangeGrant: true },
})).resolves.toMatchObject({
allowed: false,
reason: "deny_missing_consent",
grant: { permissionKey: "agents:suggest-changes" },
});
await expect(authz.decide({
actor: { type: "agent", agentId: suggestAgent.id, companyId: company.id, source: "agent_key" },
action: "agent_config:update",
resource: { type: "agent", companyId: company.id, agentId: targetAgent.id },
scope: { requiresChangeGrant: true, consentedChange: true },
})).resolves.toMatchObject({
allowed: true,
reason: "allow_consented_change",
grant: { permissionKey: "agents:suggest-changes" },
});
await expect(authz.decide({
actor: { type: "agent", agentId: noGrantAgent.id, companyId: company.id, source: "agent_key" },
action: "agent_config:update",
resource: { type: "agent", companyId: company.id, agentId: targetAgent.id },
scope: { requiresChangeGrant: true },
})).resolves.toMatchObject({
allowed: false,
reason: "deny_no_grant",
});
});
it("enforces direct or consented suggest grants for skill configuration changes", async () => {
const company = await createCompany(db, "SkillChangeGrant");
const directAgent = await createAgent(db, company.id);
const suggestAgent = await createAgent(db, company.id);
const noGrantAgent = await createAgent(db, company.id);
await grantAgentPermission(db, company.id, directAgent.id, "skills:create");
await grantAgentPermission(db, company.id, suggestAgent.id, "skills:suggest-changes");
await db.insert(companyMemberships).values({
companyId: company.id,
principalType: "agent",
principalId: noGrantAgent.id,
status: "active",
membershipRole: "member",
});
const authz = authorizationService(db);
await expect(authz.decide({
actor: { type: "agent", agentId: directAgent.id, companyId: company.id, source: "agent_key" },
action: "skill_config:update",
resource: { type: "company", companyId: company.id },
})).resolves.toMatchObject({
allowed: true,
reason: "allow_direct_change",
grant: { permissionKey: "skills:create" },
});
await expect(authz.decide({
actor: { type: "agent", agentId: suggestAgent.id, companyId: company.id, source: "agent_key" },
action: "skill_config:update",
resource: { type: "company", companyId: company.id },
})).resolves.toMatchObject({
allowed: false,
reason: "deny_missing_consent",
grant: { permissionKey: "skills:suggest-changes" },
});
await expect(authz.decide({
actor: { type: "agent", agentId: suggestAgent.id, companyId: company.id, source: "agent_key" },
action: "skill_config:update",
resource: { type: "company", companyId: company.id },
scope: { consentedChange: true },
})).resolves.toMatchObject({
allowed: true,
reason: "allow_consented_change",
grant: { permissionKey: "skills:suggest-changes" },
});
await expect(authz.decide({
actor: { type: "agent", agentId: noGrantAgent.id, companyId: company.id, source: "agent_key" },
action: "skill_config:update",
resource: { type: "company", companyId: company.id },
})).resolves.toMatchObject({
allowed: false,
reason: "deny_no_grant",
});
});
it("denies cross-company agent decisions before grant evaluation", async () => {
@@ -605,6 +738,69 @@ describeEmbeddedPostgres("authorization service", () => {
})).resolves.toMatchObject({ allowed: false, reason: "deny_low_trust_boundary" });
});
it("blocks low-trust configuration actions before evaluating explicit change grants", async () => {
const company = await createCompany(db, "LowTrustConfigGrants");
const project = await createProject(db, company.id, "Allowed");
const targetAgent = await createAgent(db, company.id);
const actorAgent = await createAgent(db, company.id, {
role: "ceo",
permissions: {
trustPreset: LOW_TRUST_REVIEW_PRESET,
authorizationPolicy: {
trustBoundary: {
mode: LOW_TRUST_REVIEW_PRESET,
companyId: company.id,
projectIds: [project.id],
allowedAgentIds: [targetAgent.id],
},
},
},
});
await grantAgentPermission(db, company.id, actorAgent.id, "agents:configure");
await db.insert(principalPermissionGrants).values({
companyId: company.id,
principalType: "agent",
principalId: actorAgent.id,
permissionKey: "skills:create",
grantedByUserId: null,
});
const authz = authorizationService(db);
const actor = { type: "agent" as const, agentId: actorAgent.id, companyId: company.id, source: "agent_key" as const };
await expect(authz.decide({
actor,
action: "agent:read",
resource: { type: "agent", companyId: company.id, agentId: targetAgent.id },
})).resolves.toMatchObject({ allowed: true, reason: "allow_low_trust_boundary" });
await expect(authz.decide({
actor,
action: "agent_config:read",
resource: { type: "agent", companyId: company.id, agentId: targetAgent.id },
})).resolves.toMatchObject({ allowed: false, reason: "deny_low_trust_boundary" });
await expect(authz.decide({
actor,
action: "agent_config:read",
resource: { type: "agent", companyId: company.id, agentId: actorAgent.id },
})).resolves.toMatchObject({ allowed: false, reason: "deny_low_trust_boundary" });
await expect(authz.decide({
actor,
action: "agent_config:update",
resource: { type: "agent", companyId: company.id, agentId: targetAgent.id },
scope: { requiresChangeGrant: true, consentedChange: true },
})).resolves.toMatchObject({ allowed: false, reason: "deny_low_trust_boundary" });
await expect(authz.decide({
actor,
action: "skill_config:update",
resource: { type: "company", companyId: company.id },
scope: { consentedChange: true },
})).resolves.toMatchObject({ allowed: false, reason: "deny_low_trust_boundary" });
});
it("denies simple-mode assignment when the target agent requires protected-assignment approval", async () => {
const company = await createCompany(db, "ProtectedAssignment");
const actorAgent = await createAgent(db, company.id, { role: "engineer" });
@@ -0,0 +1,442 @@
import express from "express";
import request from "supertest";
import { beforeEach, describe, expect, it, vi } from "vitest";
const companyId = "22222222-2222-4222-8222-222222222222";
const agentId = "11111111-1111-4111-8111-111111111111";
const mockAccessService = vi.hoisted(() => ({
decide: vi.fn(),
canUser: vi.fn(),
}));
const mockInstanceSettingsService = vi.hoisted(() => ({
getExperimental: vi.fn(),
}));
const mockBuiltInAgentService = vi.hoisted(() => ({
list: vi.fn(),
get: vi.fn(),
ensure: vi.fn(),
provision: vi.fn(),
reset: vi.fn(),
enableRoutineSchedule: vi.fn(),
disableRoutineSchedule: vi.fn(),
runRoutine: vi.fn(),
}));
const mockLogActivity = vi.hoisted(() => vi.fn());
function allowDecision() {
return {
allowed: true,
action: "agents:create",
reason: "allow_explicit_grant",
explanation: "Allowed.",
};
}
function denyDecision() {
return {
allowed: false,
action: "agents:create",
reason: "deny_missing_grant",
explanation: "Missing permission: agents:create.",
};
}
function builtInState(overrides: Record<string, unknown> = {}) {
return {
definition: {
key: "briefs",
displayName: "Briefs Agent",
featureKeys: ["briefs"],
shortPurpose: "Prepares concise operational briefs.",
defaultInstructions: "Write briefs.",
defaultRole: "general",
allowedAdapterTypes: ["codex_local"],
},
status: "ready",
agentId,
agent: {
id: agentId,
companyId,
name: "Briefs Agent",
role: "general",
status: "idle",
adapterType: "codex_local",
adapterConfig: { model: "gpt-5.4" },
},
pauseReason: null,
...overrides,
};
}
function registerModuleMocks() {
vi.doMock("../services/index.js", () => ({
accessService: () => mockAccessService,
instanceSettingsService: () => mockInstanceSettingsService,
logActivity: mockLogActivity,
}));
vi.doMock("../services/built-in-agents.js", () => ({
builtInAgentService: () => mockBuiltInAgentService,
}));
}
async function createApp(actor: Record<string, unknown>) {
const [{ builtInAgentRoutes }, { errorHandler }] = await Promise.all([
vi.importActual<typeof import("../routes/built-in-agents.js")>("../routes/built-in-agents.js"),
vi.importActual<typeof import("../middleware/index.js")>("../middleware/index.js"),
]);
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
(req as any).actor = actor;
next();
});
app.use("/api", builtInAgentRoutes({} as any));
app.use(errorHandler);
return app;
}
describe("built-in agent routes", () => {
beforeEach(() => {
vi.resetModules();
registerModuleMocks();
vi.clearAllMocks();
mockAccessService.decide.mockResolvedValue(allowDecision());
mockAccessService.canUser.mockResolvedValue(true);
mockInstanceSettingsService.getExperimental.mockResolvedValue({ enableBuiltInAgents: true });
mockBuiltInAgentService.list.mockResolvedValue([builtInState()]);
mockBuiltInAgentService.get.mockResolvedValue(builtInState());
mockBuiltInAgentService.ensure.mockResolvedValue(builtInState());
mockBuiltInAgentService.provision.mockResolvedValue({ state: builtInState(), approval: null });
mockBuiltInAgentService.reset.mockResolvedValue(builtInState());
mockBuiltInAgentService.enableRoutineSchedule.mockResolvedValue(builtInState());
mockBuiltInAgentService.disableRoutineSchedule.mockResolvedValue(builtInState());
mockBuiltInAgentService.runRoutine.mockResolvedValue({ id: "routine-run-1", source: "manual", status: "queued" });
});
it("lists built-in agent state for actors with company access", async () => {
const app = await createApp({
type: "board",
userId: "board-user",
companyIds: [companyId],
source: "session",
isInstanceAdmin: false,
});
const res = await request(app).get(`/api/companies/${companyId}/built-in-agents`);
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(mockBuiltInAgentService.list).toHaveBeenCalledWith(companyId);
expect(res.body).toEqual([expect.objectContaining({ status: "ready", agentId })]);
expect(res.body[0].agent.adapterConfig).toEqual({});
});
it("denies list requests outside the actor company boundary", async () => {
const app = await createApp({
type: "board",
userId: "board-user",
companyIds: ["33333333-3333-4333-8333-333333333333"],
source: "session",
isInstanceAdmin: false,
});
const res = await request(app).get(`/api/companies/${companyId}/built-in-agents`);
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(mockBuiltInAgentService.list).not.toHaveBeenCalled();
});
it("returns 404 and does not load built-in state when the experimental flag is disabled", async () => {
mockInstanceSettingsService.getExperimental.mockResolvedValue({ enableBuiltInAgents: false });
const app = await createApp({
type: "board",
userId: "board-user",
companyIds: [companyId],
source: "session",
isInstanceAdmin: false,
});
const res = await request(app).get(`/api/companies/${companyId}/built-in-agents`);
expect(res.status, JSON.stringify(res.body)).toBe(404);
expect(res.body.error).toContain("Built-in agents are not enabled");
expect(mockBuiltInAgentService.list).not.toHaveBeenCalled();
});
it("provisions through the agents:create gate and passes optional adapter overrides", async () => {
const app = await createApp({
type: "board",
userId: "board-user",
companyIds: [companyId],
source: "session",
isInstanceAdmin: false,
});
const res = await request(app)
.post(`/api/companies/${companyId}/built-in-agents/briefs/provision`)
.send({ adapterType: "codex_local", adapterConfig: { model: "gpt-5.4" }, budgetMonthlyCents: 5000 });
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(mockAccessService.decide).toHaveBeenCalledWith({
actor: expect.objectContaining({ type: "board" }),
action: "agents:create",
resource: { type: "company", companyId },
});
expect(mockBuiltInAgentService.provision).toHaveBeenCalledWith(
companyId,
"briefs",
{
adapterType: "codex_local",
adapterConfig: { model: "gpt-5.4" },
budgetMonthlyCents: 5000,
},
{ requestedByAgentId: null, requestedByUserId: "board-user" },
);
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
companyId,
actorType: "user",
actorId: "board-user",
action: "built_in_agent.provision_requested",
entityId: agentId,
}));
});
it("denies provision when agents:create is not allowed", async () => {
mockAccessService.decide.mockResolvedValue(denyDecision());
const app = await createApp({
type: "board",
userId: "board-user",
companyIds: [companyId],
source: "session",
isInstanceAdmin: false,
});
const res = await request(app)
.post(`/api/companies/${companyId}/built-in-agents/briefs/provision`)
.send({ adapterType: "codex_local" });
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(res.body.details).toMatchObject({ reason: "deny_missing_grant" });
expect(mockBuiltInAgentService.ensure).not.toHaveBeenCalled();
expect(mockBuiltInAgentService.provision).not.toHaveBeenCalled();
});
it("rejects provision bodies with unknown fields", async () => {
const app = await createApp({
type: "board",
userId: "board-user",
companyIds: [companyId],
source: "session",
isInstanceAdmin: false,
});
const res = await request(app)
.post(`/api/companies/${companyId}/built-in-agents/briefs/provision`)
.send({ adapterType: "codex_local", unexpected: true });
expect(res.status, JSON.stringify(res.body)).toBe(400);
expect(mockBuiltInAgentService.ensure).not.toHaveBeenCalled();
expect(mockBuiltInAgentService.provision).not.toHaveBeenCalled();
});
it("enables a built-in routine schedule through the board tasks:assign gate", async () => {
const app = await createApp({
type: "board",
userId: "board-user",
companyIds: [companyId],
source: "session",
isInstanceAdmin: false,
});
const res = await request(app)
.post(`/api/companies/${companyId}/built-in-agents/reflection-coach/routines/recent-agent-reflection/enable`)
.send({});
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(mockAccessService.canUser).toHaveBeenCalledWith(companyId, "board-user", "tasks:assign");
expect(mockBuiltInAgentService.enableRoutineSchedule).toHaveBeenCalledWith(
companyId,
"reflection-coach",
"recent-agent-reflection",
{ agentId: null, userId: "board-user", runId: null },
);
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
action: "built_in_agent.routine_schedule_enabled",
entityId: agentId,
details: expect.objectContaining({ routineKey: "recent-agent-reflection" }),
}));
});
it("disables a built-in routine schedule", async () => {
const app = await createApp({
type: "board",
userId: "board-user",
companyIds: [companyId],
source: "session",
isInstanceAdmin: false,
});
const res = await request(app)
.post(`/api/companies/${companyId}/built-in-agents/reflection-coach/routines/recent-agent-reflection/disable`)
.send({});
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(mockBuiltInAgentService.disableRoutineSchedule).toHaveBeenCalledWith(
companyId,
"reflection-coach",
"recent-agent-reflection",
{ agentId: null, userId: "board-user", runId: null },
);
});
it("triggers a built-in routine manual run", async () => {
const app = await createApp({
type: "board",
userId: "board-user",
companyIds: [companyId],
source: "session",
isInstanceAdmin: false,
});
const res = await request(app)
.post(`/api/companies/${companyId}/built-in-agents/reflection-coach/routines/recent-agent-reflection/run`)
.send({});
expect(res.status, JSON.stringify(res.body)).toBe(202);
expect(res.body).toMatchObject({ id: "routine-run-1", source: "manual" });
expect(mockBuiltInAgentService.runRoutine).toHaveBeenCalledWith(
companyId,
"reflection-coach",
"recent-agent-reflection",
{ agentId: null, userId: "board-user", runId: null },
);
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
action: "built_in_agent.routine_run_triggered",
details: expect.objectContaining({ routineRunId: "routine-run-1" }),
}));
});
it("denies built-in routine controls when tasks:assign is not allowed", async () => {
mockAccessService.canUser.mockResolvedValue(false);
const app = await createApp({
type: "board",
userId: "board-user",
companyIds: [companyId],
source: "session",
isInstanceAdmin: false,
});
const res = await request(app)
.post(`/api/companies/${companyId}/built-in-agents/reflection-coach/routines/recent-agent-reflection/run`)
.send({});
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(mockBuiltInAgentService.runRoutine).not.toHaveBeenCalled();
});
it("denies agent actors from controlling built-in routines", async () => {
const app = await createApp({
type: "agent",
agentId: "manager-agent",
companyId,
source: "agent_key",
runId: "55555555-5555-4555-8555-555555555555",
});
const res = await request(app)
.post(`/api/companies/${companyId}/built-in-agents/reflection-coach/routines/recent-agent-reflection/run`)
.send({});
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(res.body.error).toContain("Only board operators can control built-in routines.");
expect(mockAccessService.canUser).not.toHaveBeenCalled();
expect(mockBuiltInAgentService.runRoutine).not.toHaveBeenCalled();
});
it("returns pending hire approvals instead of provisioning immediately when company policy requires it", async () => {
const approval = {
id: "approval-1",
status: "pending",
type: "hire_agent",
};
mockBuiltInAgentService.provision.mockResolvedValue({
state: builtInState({
status: "pending_approval",
agent: { ...builtInState().agent, status: "pending_approval" },
}),
approval,
});
const app = await createApp({
type: "agent",
agentId: "manager-agent",
companyId,
source: "agent_key",
});
const res = await request(app)
.post(`/api/companies/${companyId}/built-in-agents/briefs/provision`)
.send({ adapterType: "codex_local", adapterConfig: { model: "gpt-5.4" } });
expect(res.status, JSON.stringify(res.body)).toBe(202);
expect(res.body.status).toBe("pending_approval");
expect(res.body.approval).toMatchObject({ id: "approval-1", status: "pending", type: "hire_agent" });
expect(mockBuiltInAgentService.ensure).not.toHaveBeenCalled();
expect(mockBuiltInAgentService.provision).toHaveBeenCalledWith(
companyId,
"briefs",
{ adapterType: "codex_local", adapterConfig: { model: "gpt-5.4" } },
{ requestedByAgentId: "manager-agent", requestedByUserId: null },
);
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
companyId,
actorType: "agent",
actorId: "manager-agent",
action: "approval.created",
entityId: "approval-1",
}));
});
it("resets registry defaults through the same agents:create gate", async () => {
const app = await createApp({
type: "agent",
agentId: "manager-agent",
companyId,
source: "agent_key",
});
const res = await request(app)
.post(`/api/companies/${companyId}/built-in-agents/briefs/reset`)
.send({});
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(mockBuiltInAgentService.reset).toHaveBeenCalledWith(companyId, "briefs", {});
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
companyId,
actorType: "agent",
actorId: "manager-agent",
agentId: "manager-agent",
action: "built_in_agent.reset",
entityId: agentId,
}));
});
it("denies agent actors from provisioning across company boundaries", async () => {
const app = await createApp({
type: "agent",
agentId: "manager-agent",
companyId: "33333333-3333-4333-8333-333333333333",
source: "agent_key",
});
const res = await request(app)
.post(`/api/companies/${companyId}/built-in-agents/briefs/reset`)
.send({});
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(mockAccessService.decide).not.toHaveBeenCalled();
expect(mockBuiltInAgentService.reset).not.toHaveBeenCalled();
});
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,249 @@
import { randomUUID } from "node:crypto";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import { eq } from "drizzle-orm";
import {
agents,
companies,
createDb,
heartbeatRuns,
issueThreadInteractions,
issues,
} from "@paperclipai/db";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import {
changeConsentGateService,
skillChangeTargetKey,
} from "../services/change-consent-gate.js";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
describeEmbeddedPostgres("changeConsentGateService", () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-reflection-coach-gate-");
db = createDb(tempDb.connectionString);
}, 20_000);
afterEach(async () => {
await db.delete(issueThreadInteractions);
await db.delete(issues);
await db.delete(heartbeatRuns);
await db.delete(agents);
await db.delete(companies);
});
afterAll(async () => {
await tempDb?.cleanup();
});
async function seedGateFixture() {
const companyId = randomUUID();
const coachId = randomUUID();
const sourceRunId = randomUUID();
const proposalIssueId = randomUUID();
const skillId = randomUUID();
const targetKey = skillChangeTargetKey(skillId);
await db.insert(companies).values({
id: companyId,
name: "Paperclip",
issuePrefix: "PAP",
defaultResponsibleUserId: "board-user",
});
await db.insert(agents).values({
id: coachId,
companyId,
name: "Reflection Coach",
role: "general",
adapterType: "codex_local",
adapterConfig: {},
runtimeConfig: {},
permissions: { canCreateSkills: true },
});
await db.insert(heartbeatRuns).values({
id: sourceRunId,
companyId,
agentId: coachId,
status: "succeeded",
});
await db.insert(issues).values({
id: proposalIssueId,
companyId,
title: "Review Reflection Coach proposal",
status: "in_review",
priority: "medium",
identifier: "PAP-1",
issueNumber: 1,
createdByAgentId: coachId,
});
return { companyId, coachId, sourceRunId, proposalIssueId, skillId, targetKey };
}
it("rejects Reflection Coach skill mutation without an accepted bound interaction", async () => {
const { companyId, coachId, targetKey } = await seedGateFixture();
await expect(changeConsentGateService(db).assertConsented({
companyId,
actorAgentId: coachId,
actorRunId: randomUUID(),
targetKeys: [targetKey],
})).rejects.toMatchObject({
status: 403,
details: { code: "reflection_coach_mutation_gate_required" },
});
});
it("rejects accepted interactions from the same run as the apply mutation", async () => {
const { companyId, coachId, sourceRunId, proposalIssueId, targetKey } = await seedGateFixture();
await db.insert(issueThreadInteractions).values({
id: randomUUID(),
companyId,
issueId: proposalIssueId,
kind: "request_confirmation",
status: "accepted",
continuationPolicy: "wake_assignee_on_accept",
sourceRunId,
createdByAgentId: coachId,
payload: {
version: 1,
prompt: "Apply this Reflection Coach skill diff?",
detailsMarkdown: "```diff\n+Tighten the workflow.\n```",
target: { type: "custom", key: targetKey, revisionId: "proposal-v1" },
},
result: { version: 1, outcome: "accepted" },
resolvedByUserId: "board-user",
resolvedAt: new Date(),
});
await expect(changeConsentGateService(db).assertConsented({
companyId,
actorAgentId: coachId,
actorRunId: sourceRunId,
targetKeys: [targetKey],
})).rejects.toMatchObject({
status: 403,
details: { code: "reflection_coach_mutation_gate_required" },
});
});
it("allows a previous-run accepted interaction with a displayed diff for the bound target", async () => {
const { companyId, coachId, sourceRunId, proposalIssueId, targetKey } = await seedGateFixture();
const interactionId = randomUUID();
await db.insert(issueThreadInteractions).values({
id: interactionId,
companyId,
issueId: proposalIssueId,
kind: "request_confirmation",
status: "accepted",
continuationPolicy: "wake_assignee_on_accept",
sourceRunId,
createdByAgentId: coachId,
payload: {
version: 1,
prompt: "Apply this Reflection Coach skill diff?",
detailsMarkdown: "```diff\n+Tighten the workflow.\n```",
target: { type: "custom", key: targetKey, revisionId: "proposal-v1" },
},
result: { version: 1, outcome: "accepted" },
resolvedByUserId: "board-user",
resolvedAt: new Date(),
});
const actorRunId = randomUUID();
await expect(changeConsentGateService(db).assertConsented({
companyId,
actorAgentId: coachId,
actorRunId,
targetKeys: [targetKey],
})).resolves.toBe(true);
const [stored] = await db
.select({ result: issueThreadInteractions.result })
.from(issueThreadInteractions)
.where(eq(issueThreadInteractions.id, interactionId));
expect(stored?.result).toMatchObject({
consumedByRunId: actorRunId,
outcome: "accepted",
version: 1,
});
expect((stored?.result as { consumedAt?: unknown } | undefined)?.consumedAt).toEqual(expect.any(String));
});
it("rejects reusing an accepted interaction after it is consumed by a mutation", async () => {
const { companyId, coachId, sourceRunId, proposalIssueId, targetKey } = await seedGateFixture();
await db.insert(issueThreadInteractions).values({
id: randomUUID(),
companyId,
issueId: proposalIssueId,
kind: "request_confirmation",
status: "accepted",
continuationPolicy: "wake_assignee_on_accept",
sourceRunId,
createdByAgentId: coachId,
payload: {
version: 1,
prompt: "Apply this Reflection Coach skill diff?",
detailsMarkdown: "```diff\n+Tighten the workflow.\n```",
target: { type: "custom", key: targetKey, revisionId: "proposal-v1" },
},
result: { version: 1, outcome: "accepted" },
resolvedByUserId: "board-user",
resolvedAt: new Date(),
});
await expect(changeConsentGateService(db).assertConsented({
companyId,
actorAgentId: coachId,
actorRunId: randomUUID(),
targetKeys: [targetKey],
})).resolves.toBe(true);
await expect(changeConsentGateService(db).assertConsented({
companyId,
actorAgentId: coachId,
actorRunId: randomUUID(),
targetKeys: [targetKey],
})).rejects.toMatchObject({
status: 403,
details: { code: "reflection_coach_mutation_gate_required" },
});
});
it("allows legacy Reflection Coach target keys for durable accepted interactions", async () => {
const { companyId, coachId, sourceRunId, proposalIssueId, skillId, targetKey } = await seedGateFixture();
await db.insert(issueThreadInteractions).values({
id: randomUUID(),
companyId,
issueId: proposalIssueId,
kind: "request_confirmation",
status: "accepted",
continuationPolicy: "wake_assignee_on_accept",
sourceRunId,
createdByAgentId: coachId,
payload: {
version: 1,
prompt: "Apply this Reflection Coach skill diff?",
detailsMarkdown: "```diff\n+Tighten the workflow.\n```",
target: { type: "custom", key: `reflection-coach:company-skill:${skillId}`, revisionId: "proposal-v1" },
},
result: { version: 1, outcome: "accepted" },
resolvedByUserId: "board-user",
resolvedAt: new Date(),
});
await expect(changeConsentGateService(db).assertConsented({
companyId,
actorAgentId: coachId,
actorRunId: randomUUID(),
targetKeys: [targetKey],
})).resolves.toBe(true);
});
});
@@ -3,18 +3,28 @@ import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import { and, eq } from "drizzle-orm";
import {
activityLog,
agentConfigRevisions,
agents,
agentWakeupRequests,
builtInManagedResources,
companies,
companySkillVersions,
companySkills,
companyMemberships,
createDb,
heartbeatRunEvents,
heartbeatRuns,
principalPermissionGrants,
routines,
routineTriggers,
} from "@paperclipai/db";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import { companyService } from "../services/companies.js";
import { readBuiltInAgentMarker } from "../services/built-in-agent-metadata.js";
import { reconcileBuiltInAgentsOnStartup } from "../services/built-in-agents.js";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
@@ -35,11 +45,19 @@ describeEmbeddedPostgres("companyService", () => {
}, 20_000);
afterEach(async () => {
await db.delete(routineTriggers);
await db.delete(routines);
await db.delete(builtInManagedResources);
await db.delete(companySkillVersions);
await db.delete(companySkills);
await db.delete(heartbeatRunEvents);
await db.delete(heartbeatRuns);
await db.delete(agentWakeupRequests);
await db.delete(agentConfigRevisions);
await db.delete(activityLog);
await db.delete(agents);
await db.delete(principalPermissionGrants);
await db.delete(companyMemberships);
await db.delete(companies);
});
@@ -63,6 +81,50 @@ describeEmbeddedPostgres("companyService", () => {
expect(rows.map((row) => row.issuePrefix).sort()).toEqual(["ARO", "AROA"]);
});
it("auto-provisions one paused Reflection Coach bundle for a freshly created company", async () => {
const created = await companyService(db).create({
name: "Fresh Company",
});
const agentRows = await db.select().from(agents).where(eq(agents.companyId, created.id));
const reflectionRows = agentRows.filter((row) => readBuiltInAgentMarker(row.metadata)?.key === "reflection-coach");
expect(reflectionRows).toHaveLength(1);
expect(reflectionRows[0]).toMatchObject({
name: "Reflection Coach",
status: "paused",
budgetMonthlyCents: 0,
spentMonthlyCents: 0,
});
const [skill] = await db
.select()
.from(companySkills)
.where(and(
eq(companySkills.companyId, created.id),
eq(companySkills.key, "paperclipai/bundled/paperclip-operations/reflection-coach"),
));
expect(skill).toMatchObject({
slug: "reflection-coach",
});
const [routine] = await db.select().from(routines).where(eq(routines.companyId, created.id));
expect(routine).toMatchObject({
status: "paused",
assigneeAgentId: reflectionRows[0]!.id,
originKind: "built_in_agent_bundle",
originId: "reflection-coach:recent-agent-reflection",
});
const [trigger] = await db.select().from(routineTriggers).where(eq(routineTriggers.routineId, routine!.id));
expect(trigger).toMatchObject({
kind: "schedule",
enabled: false,
});
await reconcileBuiltInAgentsOnStartup(db);
const afterReconcileRows = await db.select().from(agents).where(eq(agents.companyId, created.id));
expect(afterReconcileRows.filter((row) => readBuiltInAgentMarker(row.metadata)?.key === "reflection-coach")).toHaveLength(1);
});
it("archives companies by pausing runnable agents and cancelling active runs", async () => {
const companyId = randomUUID();
const runningAgentId = randomUUID();
@@ -480,6 +480,55 @@ describe("company portability", () => {
expect(exported.warnings).toContain("Agent claudecoder PATH override was omitted from export because it is system-dependent.");
});
it("exports agent permission grants through the Paperclip extension and manifest", async () => {
const db = {
select: vi.fn((selection: Record<string, unknown>) => ({
from: vi.fn(() => ({
where: vi.fn(async () => {
if (!selection.permissionKey) return [];
return [
{
principalId: "agent-1",
permissionKey: "agents:suggest-changes",
scope: null,
},
{
principalId: "agent-1",
permissionKey: "skills:create",
scope: { targetAgentIds: ["agent-1"] },
},
];
}),
})),
})),
};
const portability = companyPortabilityService(db as any);
const exported = await portability.exportBundle("company-1", {
include: {
company: true,
agents: true,
projects: false,
issues: false,
},
});
const extension = asTextFile(exported.files[".paperclip.yaml"]);
expect(extension).toContain("permissionGrants:");
expect(extension).toContain('permissionKey: "agents:suggest-changes"');
expect(extension).toContain('permissionKey: "skills:create"');
expect(exported.manifest.agents.find((agent) => agent.slug === "claudecoder")?.permissionGrants).toEqual([
{
permissionKey: "agents:suggest-changes",
scope: null,
},
{
permissionKey: "skills:create",
scope: { targetAgentIds: ["agent-1"] },
},
]);
});
it("exports hire approval policy only when approval is required", async () => {
const portability = companyPortabilityService({} as any);
@@ -1559,6 +1608,90 @@ describe("company portability", () => {
);
});
it("imports agent permission grants from package metadata", async () => {
const portability = companyPortabilityService({} as any);
agentSvc.list.mockResolvedValue([]);
agentSvc.create.mockImplementation(async (_companyId: string, input: Record<string, unknown>) => ({
id: "agent-imported",
name: input.name,
adapterType: input.adapterType,
adapterConfig: input.adapterConfig,
runtimeConfig: input.runtimeConfig,
status: input.status,
}));
await portability.importBundle({
source: {
type: "inline",
files: {
"COMPANY.md": [
"---",
"name: Import",
"includes:",
" - agents/coder/AGENTS.md",
"---",
"",
].join("\n"),
"agents/coder/AGENTS.md": [
"---",
"name: Coder",
"slug: coder",
"kind: agent",
"---",
"",
"# Coder",
"",
].join("\n"),
".paperclip.yaml": [
"schema: paperclip/v1",
"agents:",
" coder:",
" adapter:",
" type: process",
" config: {}",
" permissionGrants:",
" - permissionKey: agents:suggest-changes",
" - permissionKey: skills:create",
" scope:",
" targetAgentIds:",
" - agent-imported",
"",
].join("\n"),
},
},
include: {
company: false,
agents: true,
projects: false,
issues: false,
},
target: {
mode: "existing_company",
companyId: "company-1",
},
collisionStrategy: "rename",
}, "user-1");
expect(accessSvc.setPrincipalPermission).toHaveBeenCalledWith(
"company-1",
"agent",
"agent-imported",
"agents:suggest-changes",
true,
"user-1",
null,
);
expect(accessSvc.setPrincipalPermission).toHaveBeenCalledWith(
"company-1",
"agent",
"agent-imported",
"skills:create",
true,
"user-1",
{ targetAgentIds: ["agent-imported"] },
);
});
it("removes import secrets created before a later import failure", async () => {
const portability = companyPortabilityService({} as any);
agentSvc.list.mockResolvedValue([]);
@@ -1959,6 +2092,123 @@ describe("company portability", () => {
]);
});
it("skips built-in managed agents and routines during export", async () => {
const portability = companyPortabilityService({} as any);
agentSvc.list.mockResolvedValue([
{
id: "agent-1",
name: "ClaudeCoder",
status: "idle",
role: "engineer",
title: "Software Engineer",
icon: "code",
reportsTo: null,
capabilities: "Writes code",
adapterType: "claude_local",
adapterConfig: { promptTemplate: "You are ClaudeCoder." },
runtimeConfig: { heartbeat: { intervalSec: 3600 } },
budgetMonthlyCents: 0,
permissions: { canCreateAgents: false },
metadata: null,
},
{
id: "agent-built-in",
name: "Reflection Coach",
status: "paused",
role: "coach",
title: "Reflection Coach",
icon: "sparkles",
reportsTo: null,
capabilities: "Reviews trajectories",
adapterType: "codex_local",
adapterConfig: { promptTemplate: "You coach agents." },
runtimeConfig: {},
budgetMonthlyCents: 0,
permissions: {},
metadata: {
paperclipBuiltInAgent: {
key: "reflection-coach",
featureKeys: ["recent-agent-reflection"],
},
},
},
]);
routineSvc.list.mockResolvedValue([
{
id: "routine-built-in",
companyId: "company-1",
projectId: null,
goalId: null,
parentIssueId: null,
title: "Review recent agent trajectories for coaching proposals",
description: "Review recent agent work and propose coaching follow-ups.",
assigneeAgentId: "agent-built-in",
priority: "medium",
status: "paused",
concurrencyPolicy: "coalesce_if_active",
catchUpPolicy: "skip_missed",
createdByAgentId: null,
createdByUserId: null,
updatedByAgentId: null,
updatedByUserId: null,
lastTriggeredAt: null,
lastEnqueuedAt: null,
createdAt: new Date(),
updatedAt: new Date(),
originKind: "built_in_agent_bundle",
originId: "reflection-coach:recent-agent-reflection",
originFingerprint: null,
triggers: [
{
id: "trigger-built-in",
companyId: "company-1",
routineId: "routine-built-in",
kind: "schedule",
label: "Weekly review",
enabled: false,
cronExpression: "0 9 * * 1",
timezone: "UTC",
nextRunAt: null,
lastFiredAt: null,
publicId: "public-built-in",
secretId: "secret-built-in",
signingMode: null,
replayWindowSec: null,
lastRotatedAt: null,
lastResult: null,
createdByAgentId: null,
createdByUserId: null,
updatedByAgentId: null,
updatedByUserId: null,
createdAt: new Date(),
updatedAt: new Date(),
},
],
lastRun: null,
activeIssue: null,
},
]);
const exported = await portability.exportBundle("company-1", {
include: {
company: true,
agents: true,
projects: true,
issues: true,
skills: false,
},
});
expect(exported.files["agents/claudecoder/AGENTS.md"]).toBeDefined();
expect(exported.files["agents/reflection-coach/AGENTS.md"]).toBeUndefined();
expect(exported.files["tasks/review-recent-agent-trajectories-for-coaching-proposals/TASK.md"]).toBeUndefined();
expect(exported.manifest.agents.map((agent) => agent.slug)).toEqual(["claudecoder"]);
expect(exported.manifest.issues).toEqual([]);
expect(exported.warnings).toContain("Skipped 1 built-in managed agent from export.");
expect(exported.warnings).toContain("Skipped 1 built-in managed routine from export.");
});
it("imports recurring task packages as routines instead of one-time issues", async () => {
const portability = companyPortabilityService({} as any);
@@ -8,6 +8,7 @@ const mockAgentService = vi.hoisted(() => ({
const mockAccessService = vi.hoisted(() => ({
canUser: vi.fn(),
decide: vi.fn(),
hasPermission: vi.fn(),
}));
@@ -74,6 +75,33 @@ const mockCatalogService = vi.hoisted(() => ({
const mockLogActivity = vi.hoisted(() => vi.fn());
const mockTrackSkillImported = vi.hoisted(() => vi.fn());
const mockGetTelemetryClient = vi.hoisted(() => vi.fn());
const mockReflectionCoachMutationGate = vi.hoisted(() => ({
assertConsented: vi.fn(),
}));
function allowSkillChangeDecision(reason = "allow_direct_change") {
return {
allowed: true,
action: "skill_config:update",
reason,
explanation: "Allowed.",
grant: {
principalType: "agent",
principalId: "agent-1",
permissionKey: reason === "allow_consented_change" ? "skills:suggest-changes" : "skills:create",
scope: null,
},
};
}
function denySkillChangeDecision(reason = "deny_no_grant", explanation = "Missing permission: skills:create or skills:suggest-changes.") {
return {
allowed: false,
action: "skill_config:update",
reason,
explanation,
};
}
function registerModuleMocks() {
vi.doMock("../routes/authz.js", async () => vi.importActual("../routes/authz.js"));
@@ -105,6 +133,16 @@ function registerModuleMocks() {
vi.doMock("../services/skills-catalog.js", () => mockCatalogService);
vi.doMock("../services/change-consent-gate.js", async () => {
const actual = await vi.importActual<typeof import("../services/change-consent-gate.js")>(
"../services/change-consent-gate.js",
);
return {
...actual,
changeConsentGateService: () => mockReflectionCoachMutationGate,
};
});
vi.doMock("../services/index.js", () => ({
accessService: () => mockAccessService,
agentService: () => mockAgentService,
@@ -141,6 +179,7 @@ describe("company skill mutation permissions", () => {
vi.doUnmock("../services/agents.js");
vi.doUnmock("../services/company-skills.js");
vi.doUnmock("../services/skills-catalog.js");
vi.doUnmock("../services/change-consent-gate.js");
vi.doUnmock("../services/index.js");
vi.doUnmock("../routes/company-skills.js");
vi.doUnmock("../routes/authz.js");
@@ -589,7 +628,9 @@ describe("company skill mutation permissions", () => {
});
mockLogActivity.mockResolvedValue(undefined);
mockAccessService.canUser.mockResolvedValue(true);
mockAccessService.decide.mockResolvedValue(allowSkillChangeDecision());
mockAccessService.hasPermission.mockResolvedValue(false);
mockReflectionCoachMutationGate.assertConsented.mockResolvedValue(undefined);
});
it("allows local board operators to mutate company skills", async () => {
@@ -647,7 +688,10 @@ describe("company skill mutation permissions", () => {
.send({})
.expect(200);
expect(mockAccessService.canUser).toHaveBeenCalledWith("company-1", "board-user", "skills:create");
expect(mockAccessService.decide).toHaveBeenCalledWith(expect.objectContaining({
action: "skill_config:update",
resource: { type: "company", companyId: "company-1" },
}));
expect(mockAccessService.canUser).not.toHaveBeenCalledWith("company-1", "board-user", "agents:create");
expect(mockCompanySkillService.createLocalSkill).toHaveBeenCalled();
expect(mockCompanySkillService.importFromSource).toHaveBeenCalled();
@@ -659,7 +703,7 @@ describe("company skill mutation permissions", () => {
});
it("blocks board users without skills:create from mutating company skills", async () => {
mockAccessService.canUser.mockResolvedValue(false);
mockAccessService.decide.mockResolvedValue(denySkillChangeDecision());
const res = await request(await createApp({
type: "board",
@@ -672,8 +716,11 @@ describe("company skill mutation permissions", () => {
.send({ source: "https://github.com/vercel-labs/agent-browser" });
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(res.body.error).toBe("Missing permission: skills:create");
expect(mockAccessService.canUser).toHaveBeenCalledWith("company-1", "board-user", "skills:create");
expect(res.body.error).toBe("Missing permission: skills:create or skills:suggest-changes.");
expect(mockAccessService.decide).toHaveBeenCalledWith(expect.objectContaining({
action: "skill_config:update",
resource: { type: "company", companyId: "company-1" },
}));
expect(mockAccessService.canUser).not.toHaveBeenCalledWith("company-1", "board-user", "agents:create");
expect(mockCompanySkillService.importFromSource).not.toHaveBeenCalled();
});
@@ -919,7 +966,8 @@ describe("company skill mutation permissions", () => {
});
});
it("blocks same-company agents with skill creation disabled from mutating company skills", async () => {
it("blocks same-company agents without skill change grants from mutating company skills", async () => {
mockAccessService.decide.mockResolvedValue(denySkillChangeDecision());
mockAgentService.getById.mockResolvedValue({
id: "55555555-5555-4555-8555-555555555555",
companyId: "company-1",
@@ -936,8 +984,11 @@ describe("company skill mutation permissions", () => {
.send({ source: "https://github.com/vercel-labs/agent-browser" });
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(res.body.error).toBe("Missing permission: skills:create");
expect(mockAccessService.hasPermission).toHaveBeenCalledWith("company-1", "agent", "55555555-5555-4555-8555-555555555555", "skills:create");
expect(res.body.error).toBe("Missing permission: skills:create or skills:suggest-changes.");
expect(mockAccessService.decide).toHaveBeenCalledWith(expect.objectContaining({
action: "skill_config:update",
resource: { type: "company", companyId: "company-1" },
}));
expect(mockAccessService.hasPermission).not.toHaveBeenCalledWith("company-1", "agent", "55555555-5555-4555-8555-555555555555", "agents:create");
expect(mockCompanySkillService.importFromSource).not.toHaveBeenCalled();
});
@@ -1124,11 +1175,12 @@ describe("company skill mutation permissions", () => {
});
});
it("allows agents with canCreateSkills to mutate company skills", async () => {
it("allows agents with direct skills:create grants to mutate company skills", async () => {
mockAccessService.decide.mockResolvedValue(allowSkillChangeDecision("allow_direct_change"));
mockAgentService.getById.mockResolvedValue({
id: "55555555-5555-4555-8555-555555555555",
companyId: "company-1",
permissions: { canCreateSkills: true },
permissions: { canCreateSkills: false },
});
const res = await request(await createApp({
@@ -1141,13 +1193,81 @@ describe("company skill mutation permissions", () => {
.send({ source: "https://github.com/vercel-labs/agent-browser" });
expect(res.status, JSON.stringify(res.body)).toBe(201);
expect(mockAccessService.decide).toHaveBeenCalledWith(expect.objectContaining({
action: "skill_config:update",
resource: { type: "company", companyId: "company-1" },
}));
expect(mockReflectionCoachMutationGate.assertConsented).not.toHaveBeenCalled();
expect(mockCompanySkillService.importFromSource).toHaveBeenCalledWith(
"company-1",
"https://github.com/vercel-labs/agent-browser",
);
});
it("allows same-company agents with missing skill creation permission to mutate company skills", async () => {
it("rejects suggest-tier skill mutations when the consent gate is not satisfied", async () => {
const { forbidden } = await import("../errors.js");
mockAccessService.decide.mockResolvedValue(denySkillChangeDecision(
"deny_missing_consent",
"Permission skills:suggest-changes requires accepted change consent before applying this mutation.",
));
mockReflectionCoachMutationGate.assertConsented.mockRejectedValue(forbidden("gate required", {
code: "reflection_coach_mutation_gate_required",
}));
const res = await request(await createApp({
type: "agent",
agentId: "reflection-coach",
companyId: "company-1",
runId: "run-apply",
}))
.post("/api/companies/company-1/skills")
.send({ name: "Reflection Draft", slug: "reflection-draft", markdown: "# Draft" });
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(res.body.error).toBe("Permission skills:suggest-changes requires accepted change consent before applying this mutation.");
expect(mockReflectionCoachMutationGate.assertConsented).toHaveBeenCalledWith({
companyId: "company-1",
actorAgentId: "reflection-coach",
actorRunId: "run-apply",
targetKeys: ["skill-slug:reflection-draft"],
});
expect(mockCompanySkillService.createLocalSkill).not.toHaveBeenCalled();
});
it("does not convert consent gate service failures into authorization denials", async () => {
mockAccessService.decide.mockResolvedValue(denySkillChangeDecision(
"deny_missing_consent",
"Permission skills:suggest-changes requires accepted change consent before applying this mutation.",
));
mockReflectionCoachMutationGate.assertConsented.mockRejectedValue(new Error("database unavailable"));
const res = await request(await createApp({
type: "agent",
agentId: "reflection-coach",
companyId: "company-1",
runId: "run-apply",
}))
.post("/api/companies/company-1/skills")
.send({ name: "Reflection Draft", slug: "reflection-draft", markdown: "# Draft" });
expect(res.status, JSON.stringify(res.body)).toBe(500);
expect(res.body.error).toBe("Internal server error");
expect(mockReflectionCoachMutationGate.assertConsented).toHaveBeenCalledWith({
companyId: "company-1",
actorAgentId: "reflection-coach",
actorRunId: "run-apply",
targetKeys: ["skill-slug:reflection-draft"],
});
expect(mockCompanySkillService.createLocalSkill).not.toHaveBeenCalled();
});
it("allows suggest-tier skill mutations after accepted change consent", async () => {
mockAccessService.decide
.mockResolvedValueOnce(denySkillChangeDecision(
"deny_missing_consent",
"Permission skills:suggest-changes requires accepted change consent before applying this mutation.",
))
.mockResolvedValueOnce(allowSkillChangeDecision("allow_consented_change"));
mockAgentService.getById.mockResolvedValue({
id: "55555555-5555-4555-8555-555555555555",
companyId: "company-1",
@@ -1164,57 +1284,29 @@ describe("company skill mutation permissions", () => {
.send({ source: "https://github.com/vercel-labs/agent-browser" });
expect(res.status, JSON.stringify(res.body)).toBe(201);
expect(mockReflectionCoachMutationGate.assertConsented).toHaveBeenCalledWith({
companyId: "company-1",
actorAgentId: "55555555-5555-4555-8555-555555555555",
actorRunId: "run-1",
targetKeys: ["skill-import:https://github.com/vercel-labs/agent-browser"],
});
expect(mockAccessService.decide).toHaveBeenLastCalledWith(expect.objectContaining({
action: "skill_config:update",
resource: { type: "company", companyId: "company-1" },
scope: { consentedChange: true },
}));
expect(mockCompanySkillService.importFromSource).toHaveBeenCalledWith(
"company-1",
"https://github.com/vercel-labs/agent-browser",
);
});
it("allows agents with explicit skills:create grants to mutate company skills", async () => {
it("blocks same-company agents without skill change or suggest grants", async () => {
mockAccessService.decide.mockResolvedValue(denySkillChangeDecision());
mockAgentService.getById.mockResolvedValue({
id: "55555555-5555-4555-8555-555555555555",
companyId: "company-1",
permissions: { canCreateSkills: false },
});
mockAccessService.hasPermission.mockImplementation(async (
_companyId: string,
_principalType: string,
_principalId: string,
key: string,
) => {
return key === "skills:create";
});
const res = await request(await createApp({
type: "agent",
agentId: "55555555-5555-4555-8555-555555555555",
companyId: "company-1",
runId: "run-1",
}))
.post("/api/companies/company-1/skills/import")
.send({ source: "https://github.com/vercel-labs/agent-browser" });
expect(res.status, JSON.stringify(res.body)).toBe(201);
expect(mockAccessService.hasPermission).toHaveBeenCalledWith("company-1", "agent", "55555555-5555-4555-8555-555555555555", "skills:create");
expect(mockCompanySkillService.importFromSource).toHaveBeenCalledWith(
"company-1",
"https://github.com/vercel-labs/agent-browser",
);
});
it("does not allow explicit agents:create grants to mutate company skills", async () => {
mockAgentService.getById.mockResolvedValue({
id: "55555555-5555-4555-8555-555555555555",
companyId: "company-1",
permissions: { canCreateSkills: false },
});
mockAccessService.hasPermission.mockImplementation(async (
_companyId: string,
_principalType: string,
_principalId: string,
key: string,
) => {
return key === "agents:create";
permissions: {},
});
const res = await request(await createApp({
@@ -1227,8 +1319,44 @@ describe("company skill mutation permissions", () => {
.send({ source: "https://github.com/vercel-labs/agent-browser" });
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(res.body.error).toBe("Missing permission: skills:create");
expect(mockAccessService.hasPermission).toHaveBeenCalledWith("company-1", "agent", "55555555-5555-4555-8555-555555555555", "skills:create");
expect(res.body.error).toBe("Missing permission: skills:create or skills:suggest-changes.");
expect(mockAccessService.decide).toHaveBeenCalledWith(expect.objectContaining({
action: "skill_config:update",
resource: { type: "company", companyId: "company-1" },
}));
expect(mockCompanySkillService.importFromSource).not.toHaveBeenCalled();
});
it("does not allow explicit agents:create grants to mutate company skills", async () => {
mockAccessService.decide.mockResolvedValue(denySkillChangeDecision());
mockAgentService.getById.mockResolvedValue({
id: "agent-1",
companyId: "company-1",
permissions: { canCreateSkills: false },
});
mockAccessService.hasPermission.mockImplementation(async (
_companyId: string,
_principalType: string,
_principalId: string,
key: string,
) => key === "agents:create");
const res = await request(await createApp({
type: "agent",
agentId: "agent-1",
companyId: "company-1",
runId: "run-1",
}))
.post("/api/companies/company-1/skills/import")
.send({ source: "https://github.com/vercel-labs/agent-browser" });
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(res.body.error).toBe("Missing permission: skills:create or skills:suggest-changes.");
expect(mockAccessService.decide).toHaveBeenCalledWith(expect.objectContaining({
action: "skill_config:update",
resource: { type: "company", companyId: "company-1" },
}));
expect(mockAccessService.hasPermission).not.toHaveBeenCalledWith("company-1", "agent", "agent-1", "agents:create");
expect(mockCompanySkillService.importFromSource).not.toHaveBeenCalled();
});
@@ -93,6 +93,7 @@ describeEmbeddedPostgres("heartbeat bounded retry scheduling", () => {
await db.delete(issueRelations);
await db.delete(issues);
await db.delete(activityLog);
await db.delete(heartbeatRunEvents);
await db.delete(heartbeatRuns);
await db.delete(agentWakeupRequests);
await db.delete(agentRuntimeState);
@@ -38,19 +38,23 @@ describeEmbeddedPostgres("heartbeat worktree suppression", () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
function isHeartbeatRunEventFkError(error: unknown) {
function isHeartbeatRunDependentFkError(error: unknown) {
const message = error instanceof Error ? `${error.message} ${String(error.cause ?? "")}` : String(error);
return message.includes("heartbeat_run_events_run_id_heartbeat_runs_id_fk");
return (
message.includes("heartbeat_run_events_run_id_heartbeat_runs_id_fk") ||
message.includes("activity_log_run_id_heartbeat_runs_id_fk")
);
}
async function deleteHeartbeatRunsWithEvents() {
async function deleteHeartbeatRunsWithDependents() {
for (let attempt = 0; attempt < 5; attempt += 1) {
await db.delete(heartbeatRunEvents);
await db.delete(activityLog);
try {
await db.delete(heartbeatRuns);
return;
} catch (error) {
if (!isHeartbeatRunEventFkError(error) || attempt === 4) throw error;
if (!isHeartbeatRunDependentFkError(error) || attempt === 4) throw error;
await new Promise((resolve) => setTimeout(resolve, 25));
}
}
@@ -67,7 +71,7 @@ describeEmbeddedPostgres("heartbeat worktree suppression", () => {
await db.delete(documentRevisions);
await db.delete(documents);
await db.delete(activityLog);
await deleteHeartbeatRunsWithEvents();
await deleteHeartbeatRunsWithDependents();
await db.delete(agentWakeupRequests);
await db.delete(issues);
await db.delete(agentRuntimeState);
@@ -82,6 +82,7 @@ describe("instance settings routes", () => {
enableExperimentalFileViewer: false,
enableCloudSync: false,
enableExternalObjects: false,
enableBuiltInAgents: false,
enableGoalsSidebarLink: false,
enableServerInfoDebugView: false,
autoRestartDevServerWhenIdle: false,
@@ -105,6 +106,7 @@ describe("instance settings routes", () => {
enableTaskWatchdogs: false,
enableCloudSync: false,
enableExternalObjects: false,
enableBuiltInAgents: false,
enableGoalsSidebarLink: false,
enableServerInfoDebugView: false,
autoRestartDevServerWhenIdle: false,
@@ -127,6 +129,7 @@ describe("instance settings routes", () => {
enableExperimentalFileViewer: true,
enableCloudSync: true,
enableExternalObjects: false,
enableBuiltInAgents: false,
enableGoalsSidebarLink: false,
enableServerInfoDebugView: false,
autoRestartDevServerWhenIdle: false,
@@ -155,6 +158,7 @@ describe("instance settings routes", () => {
enableTaskWatchdogs: true,
enableCloudSync: true,
enableExternalObjects: false,
enableBuiltInAgents: true,
enableGoalsSidebarLink: false,
enableServerInfoDebugView: true,
autoRestartDevServerWhenIdle: false,
@@ -211,6 +215,7 @@ describe("instance settings routes", () => {
enableTaskWatchdogs: false,
enableCloudSync: false,
enableExternalObjects: false,
enableBuiltInAgents: false,
enableGoalsSidebarLink: false,
enableServerInfoDebugView: false,
autoRestartDevServerWhenIdle: false,
@@ -309,6 +314,24 @@ describe("instance settings routes", () => {
});
});
it("allows local board users to update built-in agents", async () => {
const app = await createApp({
type: "board",
userId: "local-board",
source: "local_implicit",
isInstanceAdmin: true,
});
await request(app)
.patch("/api/instance/settings/experimental")
.send({ enableBuiltInAgents: true })
.expect(200);
expect(mockInstanceSettingsService.updateExperimental).toHaveBeenCalledWith({
enableBuiltInAgents: true,
});
});
it("allows local board users to update the goals sidebar link", async () => {
const app = await createApp({
type: "board",
@@ -10,6 +10,7 @@ describe("instance settings service", () => {
enableExperimentalFileViewer: true,
enableTaskWatchdogs: true,
enableCloudSync: true,
enableBuiltInAgents: true,
enableGoalsSidebarLink: true,
enableServerInfoDebugView: true,
autoRestartDevServerWhenIdle: true,
@@ -28,6 +29,7 @@ describe("instance settings service", () => {
enableExperimentalFileViewer: true,
enableTaskWatchdogs: true,
enableCloudSync: true,
enableBuiltInAgents: true,
enableGoalsSidebarLink: true,
enableServerInfoDebugView: true,
autoRestartDevServerWhenIdle: true,
@@ -98,4 +100,10 @@ describe("instance settings service", () => {
normalizeExperimentalSettings({ enableConferenceRoomChat: "yes" }).enableConferenceRoomChat,
).toBe(false);
});
it("defaults enableBuiltInAgents to false for empty and legacy stored settings", () => {
expect(normalizeExperimentalSettings(undefined).enableBuiltInAgents).toBe(false);
expect(normalizeExperimentalSettings({}).enableBuiltInAgents).toBe(false);
expect(normalizeExperimentalSettings({ enableExternalObjects: true }).enableBuiltInAgents).toBe(false);
});
});
@@ -68,6 +68,7 @@ describe("human invite roles", () => {
it("maps owner to the full management grant set", () => {
expect(grantsForHumanRole("owner")).toEqual([
{ permissionKey: "agents:create", scope: null },
{ permissionKey: "agents:configure", scope: null },
{ permissionKey: "skills:create", scope: null },
{ permissionKey: "environments:manage", scope: null },
{ permissionKey: "users:invite", scope: null },
@@ -80,6 +81,7 @@ describe("human invite roles", () => {
it("maps admin to management grants including environment management", () => {
expect(grantsForHumanRole("admin")).toEqual([
{ permissionKey: "agents:create", scope: null },
{ permissionKey: "agents:configure", scope: null },
{ permissionKey: "skills:create", scope: null },
{ permissionKey: "environments:manage", scope: null },
{ permissionKey: "users:invite", scope: null },
@@ -13,6 +13,7 @@ import {
approvals,
assets,
companies,
companyMemberships,
companySkills,
createDb,
documentAnnotationComments,
@@ -31,6 +32,7 @@ import {
issues,
issueThreadInteractions,
issueWorkProducts,
principalPermissionGrants,
projects,
} from "@paperclipai/db";
import { ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY, LOW_TRUST_REVIEW_PRESET } from "@paperclipai/shared";
@@ -68,22 +70,31 @@ async function waitFor(condition: () => boolean | Promise<boolean>, timeoutMs =
throw new Error("Timed out waiting for condition");
}
function isHeartbeatCleanupFkError(error: unknown) {
const message = error instanceof Error ? `${error.message} ${String(error.cause ?? "")}` : String(error);
return (
message.includes("heartbeat_run_events_run_id_heartbeat_runs_id_fk") ||
message.includes("activity_log_run_id_heartbeat_runs_id_fk") ||
message.includes("heartbeat_runs_wakeup_request_id_agent_wakeup_requests_id_fk")
);
}
async function deleteHeartbeatRunsAndWakeupsAfterActivityLogDrains(db: Db) {
let lastError: unknown = null;
for (let attempt = 0; attempt < 10; attempt += 1) {
await db.delete(activityLog);
await db.delete(heartbeatRunEvents);
await db.delete(activityLog);
try {
await db.delete(heartbeatRunEvents);
await db.delete(heartbeatRuns);
await db.delete(agentWakeupRequests);
return;
} catch (error) {
lastError = error;
if (!isHeartbeatCleanupFkError(error) || attempt === 9) {
throw error;
}
await new Promise((resolve) => setTimeout(resolve, 25));
}
}
throw lastError;
}
function expectNoCanary(value: unknown, ...markers: string[]) {
@@ -645,6 +656,8 @@ describeEmbeddedPostgres("low-trust red-team HTTP route regression suite", () =>
await deleteHeartbeatRunsAndWakeupsAfterActivityLogDrains(db);
await db.delete(issues);
await db.delete(agentRuntimeState);
await db.delete(principalPermissionGrants);
await db.delete(companyMemberships);
await db.delete(agents);
await db.delete(projects);
await db.delete(companySkills);
@@ -774,6 +787,29 @@ describeEmbeddedPostgres("low-trust red-team HTTP route regression suite", () =>
it("restricts low-trust self inspection without changing standard-agent visibility", async () => {
const fixture = await seedLowTrustFixture(db);
await db.insert(companyMemberships).values({
companyId: fixture.company.id,
principalType: "agent",
principalId: fixture.agents.lowTrust.id,
status: "active",
membershipRole: "member",
});
await db.insert(principalPermissionGrants).values([
{
companyId: fixture.company.id,
principalType: "agent",
principalId: fixture.agents.lowTrust.id,
permissionKey: "agents:configure",
grantedByUserId: null,
},
{
companyId: fixture.company.id,
principalType: "agent",
principalId: fixture.agents.lowTrust.id,
permissionKey: "skills:create",
grantedByUserId: null,
},
]);
const lowTrustRes = await request(createApp(db, agentActor(fixture))).get("/api/agents/me");
expect(lowTrustRes.status, JSON.stringify(lowTrustRes.body)).toBe(200);
@@ -802,6 +838,16 @@ describeEmbeddedPostgres("low-trust red-team HTTP route regression suite", () =>
expect(lowTrustSelfByIdRes.body).not.toHaveProperty("access");
expectNoCanary(lowTrustSelfByIdRes.body, fixture.canaries.agentConfig);
const lowTrustPeerConfigRes = await request(createApp(db, agentActor(fixture)))
.get(`/api/agents/${fixture.agents.collaborator.id}/configuration`);
expect(lowTrustPeerConfigRes.status, JSON.stringify(lowTrustPeerConfigRes.body)).toBe(403);
expectNoCanary(lowTrustPeerConfigRes.body, fixture.canaries.agentConfig);
const lowTrustSelfBundleRes = await request(createApp(db, agentActor(fixture)))
.get(`/api/agents/${fixture.agents.lowTrust.id}/instructions-bundle`);
expect(lowTrustSelfBundleRes.status, JSON.stringify(lowTrustSelfBundleRes.body)).toBe(403);
expectNoCanary(lowTrustSelfBundleRes.body, fixture.canaries.agentConfig);
const standardActor = agentActor(fixture, fixture.agents.standard.id);
const standardRes = await request(createApp(db, { ...standardActor, runId: null })).get("/api/agents/me");
expect(standardRes.status, JSON.stringify(standardRes.body)).toBe(200);
@@ -19,6 +19,7 @@ const apiPrefixes: Record<string, string> = {
"assets.ts": "/api",
"auth.ts": "/api/auth",
"board-chat.ts": "/api",
"built-in-agents.ts": "/api",
"cloud-upstreams.ts": "/api",
"companies.ts": "/api/companies",
"company-skills.ts": "/api",
@@ -218,6 +218,12 @@ vi.mock("../services/index.js", () => ({
failed: 0,
seededAgentIds: [],
})),
reconcileBuiltInAgentsOnStartup: vi.fn(async () => ({
scanned: 0,
reconciled: 0,
unknown: 0,
duplicates: 0,
})),
reconcilePersistedRuntimeServicesOnStartup: vi.fn(async () => ({ reconciled: 0 })),
resolveHeartbeatSchedulingSuppression: resolveHeartbeatSchedulingSuppressionMock,
routineService: routineServiceFactoryMock,
+2
View File
@@ -14,6 +14,7 @@ import { applyTrustProxy, parseTrustProxyEnv } from "./middleware/trust-proxy.js
import { healthRoutes } from "./routes/health.js";
import { companyRoutes } from "./routes/companies.js";
import { companySkillRoutes } from "./routes/company-skills.js";
import { builtInAgentRoutes } from "./routes/built-in-agents.js";
import { teamsCatalogRoutes } from "./routes/teams-catalog.js";
import { agentRoutes } from "./routes/agents.js";
import { projectRoutes } from "./routes/projects.js";
@@ -226,6 +227,7 @@ export async function createApp(
api.use("/companies", companyRoutes(db, opts.storageService));
api.use(llmRoutes(db));
api.use(companySkillRoutes(db));
api.use(builtInAgentRoutes(db));
api.use(teamsCatalogRoutes(db));
api.use(agentRoutes(db, { pluginWorkerManager: workerManager }));
api.use(assetRoutes(db, opts.storageService));
@@ -0,0 +1,47 @@
You are Reflection Coach, a built-in operational coach at Paperclip.
When you wake up, follow the Paperclip heartbeat procedure. Work only on issues assigned to you. Always leave a task comment before exiting a heartbeat.
Your job is to run reflection loops on other agents and propose the smallest durable improvement to how they operate. When an issue asks you to reflect on a target agent, use the `reflection-coach` skill as your operating procedure.
## Core responsibilities
- Read the target agent's recent completed, in-review, and blocked issue trajectories, including comments, status changes, reviewer feedback, approvals, and blockers.
- Read the target agent's current AGENTS.md and assigned skills before proposing anything.
- Cluster repeated failure or improvement patterns only when they are backed by concrete issue/comment evidence.
- Propose the smallest durable change: an AGENTS.md diff, a reusable skill draft/update, a tool-description change, or a combination.
- Publish a proposal document with evidence, minimal diffs, and replay cases, and request acceptance before any change to another agent's surfaces is applied.
## Hard boundaries
- Never reflect on yourself. If the target agent id equals your own `PAPERCLIP_AGENT_ID`, refuse and ask for another coach.
- Never hot-swap production instructions or edit another agent's live configuration in the same run that discovers the pattern. Discovery and application are always separate runs.
- Do not score agents without trajectory evidence. Every proposed rule needs linked issue/comment evidence or it is dropped.
- Keep proposals small: AGENTS.md growth at most +20% per proposal, skills at most 15KB, tool descriptions at most 500 characters. Split larger ideas into multiple proposals.
- Do not rewrite product code or shared infrastructure as part of a reflection task. Your output is the coaching proposal, the diff, and the approval path.
## Applying changes (permission is gated, not automatic)
You may be granted permission to create and update skills, update agent AGENTS.md/instruction files, or assign follow-up proposal issues. Permission is not enough by itself; every actual mutation is gated:
- Show the exact proposed diff before you change anything. Instructions, skills, and tool descriptions are only ever changed from a reviewed diff, never from a verbal summary.
- Gate every instruction, skill, or tool-description change behind a `request_confirmation` interaction so the user or board explicitly accepts or rejects it first. The interaction must show the diff in `payload.detailsMarkdown`, use `continuationPolicy: wake_assignee_on_accept`, and bind `payload.target.key` to the exact resource you will mutate.
- Apply an accepted change only in a separate follow-up run after the interaction resolves. Never propose and apply in the same run.
- If asked to "just apply it" without a reviewed diff and an accepted interaction, refuse politely and name this gate. No-same-run-apply is a load-bearing property of this loop.
Server-enforced target keys:
- `agent:<agentId>:instructions`
- `agent:<agentId>:profile`
- `skill:<skillId>`
- `skill-slug:<slug>`
- `skill-import:<source>`
- `skills:scan-projects`
## Execution contract
- Start concrete work in the same heartbeat when the issue is actionable; do not stop at a plan unless planning was requested.
- Leave durable progress in comments, issue documents, or draft files, with a clear next action owner.
- Use child issues for long or parallel delegated work instead of polling.
- If blocked, mark the issue blocked and name the unblock owner and exact action needed.
- Respect budget, pause/cancel, approval gates, execution policy stages, and company boundaries.
@@ -0,0 +1,77 @@
---
routineKey: recent-agent-reflection
title: Review recent agent trajectories for coaching proposals
description: Bounded reflection sweep over recently active agents that produces evidence-backed coaching proposals only. Never mutates another agent's live instructions, skills, or tool descriptions without an accepted task interaction.
assigneeRef:
resourceKind: agent
resourceKey: reflection-coach
status: paused
priority: medium
concurrencyPolicy: coalesce_if_active
catchUpPolicy: skip_missed
variables:
- name: lookbackDays
label: Lookback window (days)
type: number
defaultValue: 7
required: false
options: []
- name: maxTargetAgents
label: Max target agents per run
type: number
defaultValue: 8
required: false
options: []
- name: targetAgentMode
label: Target selection mode
type: select
defaultValue: recent_active
required: false
options:
- recent_active
- all
- explicit
- name: excludeAgentIds
label: Agent ids to exclude (comma-separated)
type: string
defaultValue: null
required: false
options: []
triggers:
- kind: schedule
label: Weekly reflection sweep
enabled: false
cronExpression: "0 9 * * 1"
timezone: UTC
signingMode: none
replayWindowSec: 0
issueTemplate:
surfaceVisibility: normal
---
# Recent agent reflection sweep
This routine is **paused by default** and spends no tokens until an operator enables its schedule or triggers a manual run. When it runs, it produces coaching proposals only.
## What this run must do
1. Select target agents using `{{targetAgentMode}}`:
- `recent_active` — agents with completed/in-review/blocked issue activity within the last `{{lookbackDays}}` days.
- `all` — every non-terminated agent in the company.
- `explicit` — only agents named in the run inputs.
Cap the set at `{{maxTargetAgents}}`. Drop any agent id listed in `{{excludeAgentIds}}`, and always drop your own `PAPERCLIP_AGENT_ID` (no self-reflection).
2. For each selected target, run the `reflection-coach` skill as the operating procedure: pull recent trajectories, read current AGENTS.md and assigned skills, cluster evidence-backed patterns, and draft the smallest durable change.
3. Produce, per target agent, a proposal document with clustered patterns, linked issue/comment evidence, minimal diffs, and replay cases. Create a follow-up proposal issue when a change is worth carrying forward.
## Hard limits for this routine
- Proposal-only. This routine must not edit any agent's live AGENTS.md, skill assignments, or tool descriptions directly.
- Any actual instruction/skill/tool-description change requires a displayed diff and an **accepted** `request_confirmation` task interaction, applied only in a separate follow-up run.
- Mutation confirmations must bind the exact resource key they will apply, using `agent:<agentId>:instructions`, `agent:<agentId>:profile`, `skill:<skillId>`, `skill-slug:<slug>`, `skill-import:<source>`, or `skills:scan-projects`.
- Keep every read company-scoped. Do not cross company boundaries.
- Every proposed rule needs linked issue/comment evidence or it is dropped. No scoring without trajectories.
- Respect the size caps: AGENTS.md +20% max per proposal, skills 15KB max, tool descriptions 500 chars max.
## Output
A single bounded routine issue that links one proposal document (or follow-up proposal issue) per reviewed target agent, plus a summary comment listing: agents reviewed, window, clusters found, surfaces proposed, and the next-step owner for each accepted-or-pending change.
+14
View File
@@ -42,6 +42,7 @@ import {
environmentCustomImageService,
heartbeatService,
instanceSettingsService,
reconcileBuiltInAgentsOnStartup,
reconcileCloudUpstreamRunsOnStartup,
reconcileCodexLocalManagedHomesOnStartup,
reconcilePersistedRuntimeServicesOnStartup,
@@ -779,6 +780,19 @@ export async function startServer(): Promise<StartedServer> {
logger.error({ err }, "startup reconciliation of codex_local managed homes failed");
});
void reconcileBuiltInAgentsOnStartup(db as any)
.then((result) => {
if (result.reconciled > 0 || result.unknown > 0 || result.duplicates > 0 || result.autoEnsured > 0) {
logger.warn(
result,
"startup reconciliation of built-in agents complete",
);
}
})
.catch((err) => {
logger.error({ err }, "startup reconciliation of built-in agents failed");
});
// Force the instance onto the Kubernetes sandbox provider when configured via
// env (PAPERCLIP_EXECUTION_MODE=kubernetes). Runs BEFORE the heartbeat resumes
// queued runs so the policy + managed k8s environments are in place. A bad
+118 -45
View File
@@ -41,6 +41,7 @@ import {
agentInstructionsService,
accessService,
approvalService,
builtInAgentService,
companySkillService,
budgetService,
heartbeatService,
@@ -52,7 +53,7 @@ import {
syncInstructionsBundleConfigFromFilePath,
workspaceOperationService,
} from "../services/index.js";
import { conflict, forbidden, notFound, unprocessable } from "../errors.js";
import { conflict, forbidden, HttpError, notFound, unprocessable } from "../errors.js";
import { assertBoard, assertCompanyAccess, assertInstanceAdmin, getActorInfo } from "./authz.js";
import {
assertNoAgentHostWorkspaceCommandMutation,
@@ -99,6 +100,13 @@ import { recoveryService } from "../services/recovery/service.js";
import { resolveCoreTrustPreset } from "../services/trust-preset-resolver.js";
import { readObject } from "../lib/objects.js";
import { listInvalidOrgChainDescendantIds } from "../services/agent-invokability.js";
import {
AGENT_PROFILE_CHANGE_CONSENT_FIELDS,
agentInstructionsChangeTargetKey,
agentProfileChangeTargetKey,
changeConsentGateService,
touchesAgentProfileChangeConsentFields,
} from "../services/change-consent-gate.js";
const RUN_LOG_DEFAULT_LIMIT_BYTES = 256_000;
const RUN_LOG_MAX_LIMIT_BYTES = 1024 * 1024;
@@ -689,30 +697,22 @@ export function agentRoutes(
// read-only operation available to any board (human) member of the
// company. Responses go through `redactAgentConfiguration` so secrets
// are never exposed. Mutations and environment probes still gate on
// agents:create via assertCanCreateAgentsForCompany / assertCanUpdateAgent.
// agents:create or agents:configure via the mutating route helpers.
//
// For AGENT actors we keep the previous, stricter gate: an agent must
// either have an explicit `agents:create` grant or the legacy
// `canCreateAgents` permission on its own record. Agents are
// non-human principals — they should not be able to introspect peer
// agents' configurations just by virtue of being in the same company.
// For AGENT actors we keep a stricter gate: an agent must have either
// agents:configure or agents:suggest-changes before it can inspect peer
// agent configuration for a proposed diff.
assertCompanyAccess(req, companyId);
if (req.actor.type === "agent") {
if (!req.actor.agentId) throw forbidden("Agent authentication required");
const actorAgent = await svc.getById(req.actor.agentId);
if (!actorAgent || actorAgent.companyId !== companyId) {
throw forbidden("Agent key cannot access another company");
const decision = await access.decide({
actor: req.actor,
action: "agent_config:read",
resource: { type: "company", companyId },
});
if (!decision.allowed) {
throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
}
const allowedByGrant = await access.hasPermission(
companyId,
"agent",
actorAgent.id,
"agents:create",
);
if (!allowedByGrant && !canCreateAgents(actorAgent)) {
throw forbidden("Missing permission: can create agents");
}
return actorAgent;
return req.actor.agentId ? await svc.getById(req.actor.agentId) : null;
}
return null;
}
@@ -732,26 +732,21 @@ export function agentRoutes(
async function actorCanReadConfigurationsForCompany(req: Request, companyId: string) {
// Mirrors assertCanReadConfigurations but returns a boolean instead of
// throwing. Board actors only need company access; agent actors must
// still pass the agents:create gate (explicit grant or canCreateAgents
// on their own record) so peer agents cannot snoop each others'
// configurations.
// throwing. Board actors only need company access; agent actors must pass
// the agent configuration read grant ladder so peer agents cannot snoop
// each others' configurations.
try {
assertCompanyAccess(req, companyId);
} catch {
return false;
}
if (req.actor.type === "board") return true;
if (!req.actor.agentId) return false;
const actorAgent = await svc.getById(req.actor.agentId);
if (!actorAgent || actorAgent.companyId !== companyId) return false;
const allowedByGrant = await access.hasPermission(
companyId,
"agent",
actorAgent.id,
"agents:create",
);
return allowedByGrant || canCreateAgents(actorAgent);
const decision = await access.decide({
actor: req.actor,
action: "agent_config:read",
resource: { type: "company", companyId },
});
return decision.allowed;
}
async function buildSkippedWakeupResponse(
@@ -832,7 +827,7 @@ export function agentRoutes(
throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
}
async function assertCanReadAgent(req: Request, targetAgent: { companyId: string }) {
async function assertCanReadAgent(req: Request, targetAgent: { id: string; companyId: string }) {
assertCompanyAccess(req, targetAgent.companyId);
if (req.actor.type === "board") {
await assertCanReadConfigurations(req, targetAgent.companyId);
@@ -844,6 +839,14 @@ export function agentRoutes(
if (!actorAgent || actorAgent.companyId !== targetAgent.companyId) {
throw forbidden("Agent key cannot access another company");
}
const decision = await access.decide({
actor: req.actor,
action: "agent_config:read",
resource: { type: "agent", companyId: targetAgent.companyId, agentId: targetAgent.id },
});
if (decision.allowed) return;
throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
}
function assertKnownAdapterType(type: string | null | undefined): string {
@@ -1271,7 +1274,9 @@ export function agentRoutes(
delete nextAdapterConfig.bootstrapPromptTemplate;
if (!hadLegacyPrompt) return agent;
const updated = await svc.update(agent.id, { adapterConfig: nextAdapterConfig });
const updated = await svc.update(agent.id, { adapterConfig: nextAdapterConfig }, {
allowPendingApprovalConfigUpdate: true,
});
return (updated as T | null) ?? { ...agent, adapterConfig: nextAdapterConfig };
}
@@ -1286,7 +1291,9 @@ export function agentRoutes(
delete nextAdapterConfig.promptTemplate;
delete nextAdapterConfig.bootstrapPromptTemplate;
const updated = await svc.update(agent.id, { adapterConfig: nextAdapterConfig });
const updated = await svc.update(agent.id, { adapterConfig: nextAdapterConfig }, {
allowPendingApprovalConfigUpdate: true,
});
return (updated as T | null) ?? { ...agent, adapterConfig: nextAdapterConfig };
}
@@ -1302,14 +1309,70 @@ export function agentRoutes(
}
}
async function assertCanManageInstructionsPath(req: Request, targetAgent: { id: string; companyId: string }) {
async function assertCanApplyProtectedAgentChange(
req: Request,
targetAgent: { id: string; companyId: string },
targetKeys: string[],
) {
assertCompanyAccess(req, targetAgent.companyId);
if (req.actor.type !== "board") {
throw forbidden(
"Only board-authenticated callers can manage instructions path or bundle configuration",
);
const changeScope = { requiresChangeGrant: true };
const decision = await access.decide({
actor: req.actor,
action: "agent_config:update",
resource: { type: "agent", companyId: targetAgent.companyId, agentId: targetAgent.id },
scope: changeScope,
});
if (decision.allowed) {
return;
}
await assertBoardCanManageAgentsForCompany(req, targetAgent.companyId);
if (decision.reason === "deny_missing_consent" && req.actor.type === "agent" && targetKeys.length > 0) {
try {
await changeConsentGateService(db).assertConsented({
companyId: targetAgent.companyId,
actorAgentId: req.actor.agentId,
actorRunId: req.actor.runId ?? null,
targetKeys,
});
} catch (err) {
if (err instanceof HttpError && err.status === 403) {
throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
}
throw err;
}
const consentedDecision = await access.decide({
actor: req.actor,
action: "agent_config:update",
resource: { type: "agent", companyId: targetAgent.companyId, agentId: targetAgent.id },
scope: { ...changeScope, consentedChange: true },
});
if (consentedDecision.allowed) {
return;
}
throw forbidden(consentedDecision.explanation, authorizationDeniedDetails(consentedDecision));
}
throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
}
async function assertCanManageInstructionsPath(req: Request, targetAgent: { id: string; companyId: string }) {
await assertCanApplyProtectedAgentChange(
req,
targetAgent,
[agentInstructionsChangeTargetKey(targetAgent.id)],
);
}
async function assertCanApplyAgentProfileChange(
req: Request,
targetAgent: { id: string; companyId: string },
) {
await assertCanApplyProtectedAgentChange(
req,
targetAgent,
[agentProfileChangeTargetKey(targetAgent.id)],
);
}
function assertNoAgentInstructionsConfigMutation(
@@ -2472,6 +2535,7 @@ export function agentRoutes(
agent.id,
req.actor.type === "board" ? (req.actor.userId ?? null) : null,
);
await builtInAgentService(db).ensureCompanyDefaultAgentGrants(companyId);
if (agent.budgetMonthlyCents > 0) {
await budgets.upsertPolicy(
@@ -2800,7 +2864,7 @@ export function agentRoutes(
res.status(404).json({ error: "Agent not found" });
return;
}
await assertCanUpdateAgent(req, existing);
assertCompanyAccess(req, existing.companyId);
if (hasOwn(req.body as object, "permissions")) {
res.status(422).json({ error: "Use /api/agents/:id/permissions for permission changes" });
@@ -2912,6 +2976,15 @@ export function agentRoutes(
},
);
}
const touchesProfileFields = touchesAgentProfileChangeConsentFields(patchData);
const profileOnlyChange = touchesProfileFields && Object.keys(patchData).every((key) =>
(AGENT_PROFILE_CHANGE_CONSENT_FIELDS as readonly string[]).includes(key),
);
if (profileOnlyChange) {
await assertCanApplyAgentProfileChange(req, existing);
} else {
await assertCanUpdateAgent(req, existing);
}
const actor = getActorInfo(req);
const agent = await svc.update(id, patchData, {
+318
View File
@@ -0,0 +1,318 @@
import { Router, type Request } from "express";
import type { Db } from "@paperclipai/db";
import { builtInAgentEmptyMutationSchema, builtInAgentProvisionSchema, builtInAgentResetSchema } from "@paperclipai/shared";
import { validate } from "../middleware/validate.js";
import { forbidden, notFound } from "../errors.js";
import { accessService, instanceSettingsService, logActivity } from "../services/index.js";
import { builtInAgentService } from "../services/built-in-agents.js";
import { authorizationDeniedDetails } from "../services/authorization.js";
import { assertCompanyAccess, getActorInfo } from "./authz.js";
import type { BuiltInAgentState } from "../services/built-in-agents.js";
const WEEKDAY_LABELS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
function formatScheduleLabel(trigger: { cronExpression: string; timezone: string } | undefined) {
if (!trigger) return "Weekly schedule";
const parts = trigger.cronExpression.trim().split(/\s+/);
const [minute, hour, , , dayOfWeek] = parts;
const weekdayIndex = dayOfWeek ? Number(dayOfWeek) : Number.NaN;
if (
parts.length === 5
&& /^\d+$/.test(minute ?? "")
&& /^\d+$/.test(hour ?? "")
&& Number.isInteger(weekdayIndex)
&& weekdayIndex >= 0
&& weekdayIndex < WEEKDAY_LABELS.length
) {
return `Weekly · ${WEEKDAY_LABELS[weekdayIndex]} ${String(hour).padStart(2, "0")}:${String(minute).padStart(2, "0")} ${trigger.timezone}`;
}
return `Weekly · ${trigger.timezone}`;
}
function redactBuiltInAgentListState(state: BuiltInAgentState): BuiltInAgentState {
const definition = {
...state.definition,
defaultInstructions: state.definition.defaultInstructions ? "[file-backed]" : "",
bundle: state.definition.bundle
? {
stockVersion: state.definition.bundle.stockVersion,
instructions: {
entryFile: state.definition.bundle.instructions.entryFile,
files: Object.keys(state.definition.bundle.instructions.files),
},
skill: {
skillKey: state.definition.bundle.skill.skillKey,
displayName: state.definition.bundle.skill.displayName,
slug: state.definition.bundle.skill.slug,
canonicalKey: state.definition.bundle.skill.canonicalKey,
files: Object.keys(state.definition.bundle.skill.files),
},
routine: {
routineKey: state.definition.bundle.routine.routineKey,
title: state.definition.bundle.routine.title,
status: state.definition.bundle.routine.status,
triggerCount: state.definition.bundle.routine.triggers.length,
scheduleLabel: formatScheduleLabel(state.definition.bundle.routine.triggers[0]),
},
}
: undefined,
} as BuiltInAgentState["definition"];
if (!state.agent) return { ...state, definition };
return {
...state,
definition,
agent: {
...state.agent,
adapterConfig: {},
runtimeConfig: {},
},
};
}
export function builtInAgentRoutes(db: Db) {
const router = Router();
const access = accessService(db);
const svc = builtInAgentService(db);
const settings = instanceSettingsService(db);
async function assertBuiltInAgentsEnabled() {
const experimental = await settings.getExperimental();
if (experimental.enableBuiltInAgents !== true) {
throw notFound("Built-in agents are not enabled");
}
}
async function assertCanProvisionBuiltInAgents(req: Request, companyId: string) {
assertCompanyAccess(req, companyId);
const decision = await access.decide({
actor: req.actor,
action: "agents:create",
resource: { type: "company", companyId },
});
if (decision.allowed) return;
throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
}
async function assertCanControlBuiltInRoutine(req: Request, companyId: string) {
assertCompanyAccess(req, companyId);
if (req.actor.type !== "board") {
throw forbidden("Only board operators can control built-in routines.");
}
if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return;
const allowed = await access.canUser(companyId, req.actor.userId, "tasks:assign");
if (!allowed) {
throw forbidden("Missing permission: tasks:assign");
}
}
async function logBuiltInAgentMutation(
req: Request,
input: {
companyId: string;
action:
| "built_in_agent.provision_requested"
| "built_in_agent.reconcile"
| "built_in_agent.reset"
| "built_in_agent.routine_schedule_enabled"
| "built_in_agent.routine_schedule_disabled"
| "built_in_agent.routine_run_triggered"
| "approval.created";
key: string;
agentId: string | null;
status: string;
approvalId?: string | null;
routineKey?: string | null;
routineRunId?: string | null;
},
) {
const actor = getActorInfo(req);
await logActivity(db, {
companyId: input.companyId,
actorType: actor.actorType,
actorId: actor.actorId,
action: input.action,
entityType: input.action === "approval.created" ? "approval" : "agent",
entityId: input.action === "approval.created" ? input.approvalId ?? input.key : input.agentId ?? input.key,
...(actor.agentId ? { agentId: actor.agentId } : {}),
...(actor.runId ? { runId: actor.runId } : {}),
details: {
key: input.key,
status: input.status,
approvalId: input.approvalId ?? null,
routineKey: input.routineKey ?? null,
routineRunId: input.routineRunId ?? null,
},
});
}
router.get("/companies/:companyId/built-in-agents", async (req, res) => {
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
await assertBuiltInAgentsEnabled();
const states = await svc.list(companyId);
res.json(states.map(redactBuiltInAgentListState));
});
router.get("/companies/:companyId/built-in-agents/:key/status", async (req, res) => {
const companyId = req.params.companyId as string;
const key = req.params.key as string;
assertCompanyAccess(req, companyId);
await assertBuiltInAgentsEnabled();
res.json(redactBuiltInAgentListState(await svc.get(companyId, key)));
});
router.post("/companies/:companyId/built-in-agents/:key/reconcile", validate(builtInAgentEmptyMutationSchema), async (req, res) => {
const companyId = req.params.companyId as string;
const key = req.params.key as string;
await assertBuiltInAgentsEnabled();
await assertCanProvisionBuiltInAgents(req, companyId);
const state = await svc.ensure(companyId, key);
await logBuiltInAgentMutation(req, {
companyId,
action: "built_in_agent.reconcile",
key,
agentId: state.agentId,
status: state.status,
});
res.json(redactBuiltInAgentListState(state));
});
router.post(
"/companies/:companyId/built-in-agents/:key/provision",
validate(builtInAgentProvisionSchema),
async (req, res) => {
const companyId = req.params.companyId as string;
const key = req.params.key as string;
await assertBuiltInAgentsEnabled();
await assertCanProvisionBuiltInAgents(req, companyId);
const actor = getActorInfo(req);
const result = await svc.provision(companyId, key, req.body, {
requestedByAgentId: actor.actorType === "agent" ? actor.actorId : null,
requestedByUserId: actor.actorType === "user" ? actor.actorId : null,
});
const { state, approval } = result;
await logBuiltInAgentMutation(req, {
companyId,
action: "built_in_agent.provision_requested",
key,
agentId: state.agentId,
status: state.status,
});
if (approval) {
await logBuiltInAgentMutation(req, {
companyId,
action: "approval.created",
key,
agentId: state.agentId,
status: approval.status,
approvalId: approval.id,
});
}
res.status(approval ? 202 : 200).json(redactBuiltInAgentListState({ ...state, approval }));
},
);
router.post("/companies/:companyId/built-in-agents/:key/reset", validate(builtInAgentResetSchema), async (req, res) => {
const companyId = req.params.companyId as string;
const key = req.params.key as string;
await assertBuiltInAgentsEnabled();
await assertCanProvisionBuiltInAgents(req, companyId);
const state = await svc.reset(companyId, key, req.body);
await logBuiltInAgentMutation(req, {
companyId,
action: "built_in_agent.reset",
key,
agentId: state.agentId,
status: state.status,
});
res.json(redactBuiltInAgentListState(state));
});
router.post(
"/companies/:companyId/built-in-agents/:key/routines/:routineKey/enable",
validate(builtInAgentEmptyMutationSchema),
async (req, res) => {
const companyId = req.params.companyId as string;
const key = req.params.key as string;
const routineKey = req.params.routineKey as string;
await assertBuiltInAgentsEnabled();
assertCompanyAccess(req, companyId);
await assertCanControlBuiltInRoutine(req, companyId);
const actor = getActorInfo(req);
const state = await svc.enableRoutineSchedule(companyId, key, routineKey, {
agentId: actor.actorType === "agent" ? actor.actorId : null,
userId: actor.actorType === "user" ? actor.actorId : null,
runId: actor.runId ?? null,
});
await logBuiltInAgentMutation(req, {
companyId,
action: "built_in_agent.routine_schedule_enabled",
key,
agentId: state.agentId,
status: state.status,
routineKey,
});
res.json(redactBuiltInAgentListState(state));
},
);
router.post(
"/companies/:companyId/built-in-agents/:key/routines/:routineKey/disable",
validate(builtInAgentEmptyMutationSchema),
async (req, res) => {
const companyId = req.params.companyId as string;
const key = req.params.key as string;
const routineKey = req.params.routineKey as string;
await assertBuiltInAgentsEnabled();
assertCompanyAccess(req, companyId);
await assertCanControlBuiltInRoutine(req, companyId);
const actor = getActorInfo(req);
const state = await svc.disableRoutineSchedule(companyId, key, routineKey, {
agentId: actor.actorType === "agent" ? actor.actorId : null,
userId: actor.actorType === "user" ? actor.actorId : null,
runId: actor.runId ?? null,
});
await logBuiltInAgentMutation(req, {
companyId,
action: "built_in_agent.routine_schedule_disabled",
key,
agentId: state.agentId,
status: state.status,
routineKey,
});
res.json(redactBuiltInAgentListState(state));
},
);
router.post(
"/companies/:companyId/built-in-agents/:key/routines/:routineKey/run",
validate(builtInAgentEmptyMutationSchema),
async (req, res) => {
const companyId = req.params.companyId as string;
const key = req.params.key as string;
const routineKey = req.params.routineKey as string;
await assertBuiltInAgentsEnabled();
assertCompanyAccess(req, companyId);
const current = await svc.get(companyId, key);
await assertCanControlBuiltInRoutine(req, companyId);
const actor = getActorInfo(req);
const run = await svc.runRoutine(companyId, key, routineKey, {
agentId: actor.actorType === "agent" ? actor.actorId : null,
userId: actor.actorType === "user" ? actor.actorId : null,
runId: actor.runId ?? null,
});
await logBuiltInAgentMutation(req, {
companyId,
action: "built_in_agent.routine_run_triggered",
key,
agentId: current.agentId,
status: current.status,
routineKey,
routineRunId: run.id,
});
res.status(202).json(run);
},
);
return router;
}
+83 -44
View File
@@ -31,9 +31,17 @@ import {
listCatalogSkillsOrEmpty,
readCatalogSkillFile,
} from "../services/skills-catalog.js";
import { forbidden } from "../errors.js";
import { forbidden, HttpError } from "../errors.js";
import { assertAuthenticated, assertCompanyAccess, getActorInfo } from "./authz.js";
import { getTelemetryClient } from "../telemetry.js";
import { authorizationDeniedDetails } from "../services/authorization.js";
import {
changeConsentGateService,
skillChangeTargetKey,
skillImportChangeTargetKey,
skillSlugChangeTargetKey,
skillsScanProjectsChangeTargetKey,
} from "../services/change-consent-gate.js";
type SkillTelemetryInput = {
key: string;
@@ -51,11 +59,6 @@ export function companySkillRoutes(db: Db) {
const issues = issueService(db);
const heartbeat = heartbeatService(db);
function canCreateSkills(agent: { permissions: Record<string, unknown> | null | undefined }) {
if (!agent.permissions || typeof agent.permissions !== "object") return true;
return (agent.permissions as Record<string, unknown>).canCreateSkills !== false;
}
function asString(value: unknown): string | null {
if (typeof value !== "string") return null;
const trimmed = value.trim();
@@ -98,37 +101,65 @@ export function companySkillRoutes(db: Db) {
return { type: "system" as const };
}
async function assertCanMutateCompanySkills(req: Request, companyId: string) {
function skillMutationTargets(input: {
skillId?: string | null;
slug?: unknown;
source?: unknown;
catalogSkillId?: unknown;
scanProjects?: boolean;
}) {
const targetKeys: string[] = [];
const skillId = asString(input.skillId);
const slug = asString(input.slug);
const source = asString(input.source);
const catalogSkillId = asString(input.catalogSkillId);
if (skillId) targetKeys.push(skillChangeTargetKey(skillId));
if (slug) targetKeys.push(skillSlugChangeTargetKey(slug));
if (source) targetKeys.push(skillImportChangeTargetKey(source));
if (catalogSkillId) targetKeys.push(skillImportChangeTargetKey(catalogSkillId));
if (input.scanProjects) targetKeys.push(skillsScanProjectsChangeTargetKey());
return targetKeys;
}
async function assertCanMutateCompanySkills(req: Request, companyId: string, targetKeys: string[] = []) {
assertCompanyAccess(req, companyId);
const decision = await access.decide({
actor: req.actor,
action: "skill_config:update",
resource: { type: "company", companyId },
});
if (decision.allowed) {
return;
}
if (req.actor.type === "board") {
if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return;
const allowed = await access.canUser(companyId, req.actor.userId, "skills:create");
if (!allowed) {
throw forbidden("Missing permission: skills:create");
if (decision.reason === "deny_missing_consent" && req.actor.type === "agent" && targetKeys.length > 0) {
try {
await changeConsentGateService(db).assertConsented({
companyId,
actorAgentId: req.actor.agentId,
actorRunId: req.actor.runId ?? null,
targetKeys,
});
} catch (err) {
if (err instanceof HttpError && err.status === 403) {
throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
}
throw err;
}
return;
const consentedDecision = await access.decide({
actor: req.actor,
action: "skill_config:update",
resource: { type: "company", companyId },
scope: { consentedChange: true },
});
if (consentedDecision.allowed) {
return;
}
throw forbidden(consentedDecision.explanation, { reason: consentedDecision.reason });
}
if (!req.actor.agentId) {
throw forbidden("Agent authentication required");
}
const actorAgent = await agents.getById(req.actor.agentId);
if (!actorAgent || actorAgent.companyId !== companyId) {
throw forbidden("Agent key cannot access another company");
}
if (canCreateSkills(actorAgent)) {
return;
}
const allowedByGrant = await access.hasPermission(companyId, "agent", actorAgent.id, "skills:create");
if (allowedByGrant) {
return;
}
throw forbidden("Missing permission: skills:create");
throw forbidden(decision.explanation, { reason: decision.reason });
}
async function assertCanStartSkillTestRuns(req: Request, companyId: string) {
@@ -608,7 +639,7 @@ export function companySkillRoutes(db: Db) {
async (req, res) => {
const companyId = req.params.companyId as string;
const skillId = req.params.skillId as string;
await assertCanMutateCompanySkills(req, companyId);
await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({ skillId }));
const result = await svc.createVersion(companyId, skillId, req.body, skillActor(req));
const actor = getActorInfo(req);
await logActivity(db, {
@@ -676,7 +707,10 @@ export function companySkillRoutes(db: Db) {
async (req, res) => {
const companyId = req.params.companyId as string;
const skillId = req.params.skillId as string;
await assertCanMutateCompanySkills(req, companyId);
await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({
skillId,
slug: req.body.slug,
}));
const result = await svc.forkSkill(companyId, skillId, req.body, skillActor(req));
const actor = getActorInfo(req);
await logActivity(db, {
@@ -806,7 +840,9 @@ export function companySkillRoutes(db: Db) {
validate(companySkillCreateSchema),
async (req, res) => {
const companyId = req.params.companyId as string;
await assertCanMutateCompanySkills(req, companyId);
await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({
slug: req.body.slug,
}));
const result = await svc.createLocalSkill(companyId, req.body, skillActor(req));
const actor = getActorInfo(req);
@@ -835,7 +871,7 @@ export function companySkillRoutes(db: Db) {
async (req, res) => {
const companyId = req.params.companyId as string;
const skillId = req.params.skillId as string;
await assertCanMutateCompanySkills(req, companyId);
await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({ skillId }));
const result = await svc.updateSkill(companyId, skillId, req.body);
const actor = getActorInfo(req);
@@ -865,7 +901,7 @@ export function companySkillRoutes(db: Db) {
async (req, res) => {
const companyId = req.params.companyId as string;
const skillId = req.params.skillId as string;
await assertCanMutateCompanySkills(req, companyId);
await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({ skillId }));
const result = await svc.updateFile(
companyId,
skillId,
@@ -929,8 +965,8 @@ export function companySkillRoutes(db: Db) {
validate(companySkillImportSchema),
async (req, res) => {
const companyId = req.params.companyId as string;
await assertCanMutateCompanySkills(req, companyId);
const source = String(req.body.source ?? "");
await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({ source }));
const result = await svc.importFromSource(companyId, source);
const actor = getActorInfo(req);
@@ -969,7 +1005,10 @@ export function companySkillRoutes(db: Db) {
validate(companySkillInstallCatalogSchema),
async (req, res) => {
const companyId = req.params.companyId as string;
await assertCanMutateCompanySkills(req, companyId);
await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({
catalogSkillId: req.body.catalogSkillId,
slug: req.body.slug,
}));
const result = await svc.installFromCatalog(companyId, req.body);
const actor = getActorInfo(req);
@@ -1001,7 +1040,7 @@ export function companySkillRoutes(db: Db) {
validate(companySkillProjectScanRequestSchema),
async (req, res) => {
const companyId = req.params.companyId as string;
await assertCanMutateCompanySkills(req, companyId);
await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({ scanProjects: true }));
const result = await svc.scanProjectWorkspaces(companyId, req.body);
const actor = getActorInfo(req);
@@ -1032,7 +1071,7 @@ export function companySkillRoutes(db: Db) {
router.delete("/companies/:companyId/skills/:skillId", async (req, res) => {
const companyId = req.params.companyId as string;
const skillId = req.params.skillId as string;
await assertCanMutateCompanySkills(req, companyId);
await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({ skillId }));
const result = await svc.deleteSkill(companyId, skillId);
if (!result) {
res.status(404).json({ error: "Skill not found" });
@@ -1063,7 +1102,7 @@ export function companySkillRoutes(db: Db) {
async (req, res) => {
const companyId = req.params.companyId as string;
const skillId = req.params.skillId as string;
await assertCanMutateCompanySkills(req, companyId);
await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({ skillId }));
const result = await svc.auditSkill(companyId, skillId);
if (!result) {
res.status(404).json({ error: "Skill not found" });
@@ -1099,7 +1138,7 @@ export function companySkillRoutes(db: Db) {
async (req, res) => {
const companyId = req.params.companyId as string;
const skillId = req.params.skillId as string;
await assertCanMutateCompanySkills(req, companyId);
await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({ skillId }));
const before = await svc.getById(companyId, skillId);
const result = await svc.installUpdate(companyId, skillId, req.body);
if (!result) {
@@ -1139,7 +1178,7 @@ export function companySkillRoutes(db: Db) {
async (req, res) => {
const companyId = req.params.companyId as string;
const skillId = req.params.skillId as string;
await assertCanMutateCompanySkills(req, companyId);
await assertCanMutateCompanySkills(req, companyId, skillMutationTargets({ skillId }));
const before = await svc.getById(companyId, skillId);
const result = await svc.resetSkill(companyId, skillId, req.body);
if (!result) {
+1
View File
@@ -1,6 +1,7 @@
export { healthRoutes } from "./health.js";
export { companyRoutes } from "./companies.js";
export { companySkillRoutes } from "./company-skills.js";
export { builtInAgentRoutes } from "./built-in-agents.js";
export { teamsCatalogRoutes } from "./teams-catalog.js";
export { agentRoutes } from "./agents.js";
export { projectRoutes } from "./projects.js";
+101
View File
@@ -10,6 +10,8 @@ import {
updateAgentInstructionsBundleSchema,
upsertAgentInstructionsFileSchema,
createAgentKeySchema,
builtInAgentEmptyMutationSchema,
builtInAgentProvisionSchema,
wakeAgentSchema,
resetAgentSessionSchema,
agentSkillSyncSchema,
@@ -1144,6 +1146,105 @@ for (const route of [
// ─── Agents ──────────────────────────────────────────────────────────────────
registry.registerPath({
method: "get",
path: "/api/companies/{companyId}/built-in-agents",
tags: ["agents"],
summary: "List built-in agent provisioning state",
request: { params: z.object({ companyId: z.string() }) },
responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden, 404: r.notFound },
});
registry.registerPath({
method: "get",
path: "/api/companies/{companyId}/built-in-agents/{key}/status",
tags: ["agents"],
summary: "Get built-in agent bundle status",
request: { params: z.object({ companyId: z.string(), key: z.string() }) },
responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden, 404: r.notFound },
});
registry.registerPath({
method: "post",
path: "/api/companies/{companyId}/built-in-agents/{key}/reconcile",
tags: ["agents"],
summary: "Reconcile built-in agent managed resources",
request: {
params: z.object({ companyId: z.string(), key: z.string() }),
body: jsonBody(builtInAgentEmptyMutationSchema),
},
responses: {
200: 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}/built-in-agents/{key}/provision",
tags: ["agents"],
summary: "Provision a built-in agent",
request: {
params: z.object({ companyId: z.string(), key: z.string() }),
body: jsonBody(builtInAgentProvisionSchema),
},
responses: {
200: r.ok(),
202: r.ok(),
400: r.badRequest,
401: r.unauthorized,
403: r.forbidden,
404: r.notFound,
409: r.conflict,
},
});
registry.registerPath({
method: "post",
path: "/api/companies/{companyId}/built-in-agents/{key}/reset",
tags: ["agents"],
summary: "Reset a built-in agent",
request: { params: z.object({ companyId: z.string(), key: z.string() }) },
responses: {
200: r.ok(),
401: r.unauthorized,
403: r.forbidden,
404: r.notFound,
409: r.conflict,
},
});
for (const route of [
["enable", "Enable a built-in routine schedule", 200],
["disable", "Disable a built-in routine schedule", 200],
["run", "Run a built-in routine once", 202],
] as const) {
registry.registerPath({
method: "post",
path: `/api/companies/{companyId}/built-in-agents/{key}/routines/{routineKey}/${route[0]}`,
tags: ["agents"],
summary: route[1],
request: {
params: z.object({ companyId: z.string(), key: z.string(), routineKey: z.string() }),
body: jsonBody(builtInAgentEmptyMutationSchema),
},
responses: {
[route[2]]: r.ok(),
400: r.badRequest,
401: r.unauthorized,
403: r.forbidden,
404: r.notFound,
409: r.conflict,
422: r.unprocessable,
},
});
}
registry.registerPath({
method: "get",
path: "/api/companies/{companyId}/agents",
+124 -3
View File
@@ -30,6 +30,10 @@ import { syncAgentAdapterEnvBindings } from "./agent-secret-bindings.js";
import { normalizeAgentPermissions } from "./agent-permissions.js";
import { REDACTED_EVENT_VALUE, sanitizeRecord } from "../redaction.js";
import { secretService } from "./secrets.js";
import {
builtInAgentMarkersEqual,
readBuiltInAgentMarker,
} from "./built-in-agent-metadata.js";
function hashToken(token: string) {
return createHash("sha256").update(token).digest("hex");
@@ -43,6 +47,7 @@ const CONFIG_REVISION_FIELDS = [
"name",
"role",
"title",
"icon",
"reportsTo",
"capabilities",
"adapterType",
@@ -65,6 +70,12 @@ interface RevisionMetadata {
interface UpdateAgentOptions {
recordRevision?: RevisionMetadata;
allowBuiltInAgentMetadata?: boolean;
allowPendingApprovalConfigUpdate?: boolean;
}
interface CreateAgentOptions {
allowBuiltInAgentMetadata?: boolean;
}
interface AgentShortnameRow {
@@ -104,6 +115,7 @@ function buildConfigSnapshot(
name: row.name,
role: row.role,
title: row.title,
icon: row.icon,
reportsTo: row.reportsTo,
capabilities: row.capabilities,
adapterType: row.adapterType,
@@ -126,6 +138,50 @@ function hasConfigPatchFields(data: Partial<typeof agents.$inferInsert>) {
return CONFIG_REVISION_FIELDS.some((field) => Object.prototype.hasOwnProperty.call(data, field));
}
function changedPendingApprovalConfigFields(
existing: typeof agents.$inferSelect,
data: Partial<typeof agents.$inferInsert>,
) {
return CONFIG_REVISION_FIELDS.filter((field) =>
Object.prototype.hasOwnProperty.call(data, field) && !jsonEqual(data[field], existing[field]),
);
}
function configPatchFromApprovalPayload(payload: Record<string, unknown>) {
const patch: Partial<typeof agents.$inferInsert> = {};
if (typeof payload.name === "string") patch.name = payload.name;
if (typeof payload.role === "string") patch.role = payload.role;
if (Object.prototype.hasOwnProperty.call(payload, "title")) {
patch.title = typeof payload.title === "string" ? payload.title : null;
}
if (Object.prototype.hasOwnProperty.call(payload, "icon")) {
patch.icon = typeof payload.icon === "string" ? payload.icon : null;
}
if (Object.prototype.hasOwnProperty.call(payload, "reportsTo")) {
patch.reportsTo = typeof payload.reportsTo === "string" ? payload.reportsTo : null;
}
if (Object.prototype.hasOwnProperty.call(payload, "capabilities")) {
patch.capabilities = typeof payload.capabilities === "string" ? payload.capabilities : null;
}
if (typeof payload.adapterType === "string") patch.adapterType = payload.adapterType;
if (isPlainRecord(payload.adapterConfig)) patch.adapterConfig = payload.adapterConfig;
if (isPlainRecord(payload.runtimeConfig)) patch.runtimeConfig = payload.runtimeConfig;
if (Object.prototype.hasOwnProperty.call(payload, "defaultEnvironmentId")) {
patch.defaultEnvironmentId =
typeof payload.defaultEnvironmentId === "string" ? payload.defaultEnvironmentId : null;
}
if (typeof payload.budgetMonthlyCents === "number") {
patch.budgetMonthlyCents = payload.budgetMonthlyCents;
}
if (Object.prototype.hasOwnProperty.call(payload, "metadata")) {
patch.metadata = isPlainRecord(payload.metadata) ? payload.metadata : null;
}
if (isPlainRecord(payload.permissions)) {
patch.permissions = payload.permissions;
}
return patch;
}
function parseFiniteNumberLike(value: unknown): number | null {
if (typeof value === "number" && Number.isFinite(value)) return value;
if (typeof value !== "string") return null;
@@ -390,6 +446,21 @@ export function agentService(db: Db) {
});
}
function assertBuiltInAgentMetadataMutationAllowed(
beforeMetadata: unknown,
afterMetadata: unknown,
options?: { allowBuiltInAgentMetadata?: boolean },
) {
if (options?.allowBuiltInAgentMetadata) return;
const beforeMarker = readBuiltInAgentMarker(beforeMetadata);
const afterMarker = readBuiltInAgentMarker(afterMetadata);
if (builtInAgentMarkersEqual(beforeMarker, afterMarker)) return;
throw conflict("Built-in agent marker is managed by Paperclip and cannot be edited directly", {
code: "built_in_agent_marker_readonly",
key: beforeMarker?.key ?? afterMarker?.key ?? null,
});
}
async function updateAgent(
id: string,
data: Partial<typeof agents.$inferInsert>,
@@ -409,6 +480,16 @@ export function agentService(db: Db) {
) {
throw conflict("Pending approval agents cannot be activated directly");
}
if (existing.status === "pending_approval" && !options?.allowPendingApprovalConfigUpdate) {
const changedFields = changedPendingApprovalConfigFields(existing as typeof agents.$inferSelect, data);
if (changedFields.length > 0) {
throw conflict("Pending approval agent configuration cannot be changed before board approval", {
code: "pending_approval_agent_config_frozen",
agentId: id,
fields: changedFields,
});
}
}
if (data.reportsTo !== undefined) {
if (data.reportsTo) {
@@ -425,6 +506,10 @@ export function agentService(db: Db) {
}
}
if (Object.prototype.hasOwnProperty.call(data, "metadata")) {
assertBuiltInAgentMetadataMutationAllowed(existing.metadata, data.metadata, options);
}
const normalizedPatch = { ...data } as Partial<typeof agents.$inferInsert>;
if (data.permissions !== undefined) {
const role = (data.role ?? existing.role) as string;
@@ -501,7 +586,8 @@ export function agentService(db: Db) {
getById,
create: async (companyId: string, data: Omit<typeof agents.$inferInsert, "companyId">) => {
create: async (companyId: string, data: Omit<typeof agents.$inferInsert, "companyId">, options?: CreateAgentOptions) => {
assertBuiltInAgentMetadataMutationAllowed(null, data.metadata, options);
if (data.reportsTo) {
await ensureManager(companyId, data.reportsTo);
}
@@ -645,6 +731,14 @@ export function agentService(db: Db) {
remove: async (id: string) => {
const existing = await getById(id);
if (!existing) return null;
const builtInMarker = readBuiltInAgentMarker(existing.metadata);
if (builtInMarker) {
throw conflict("Built-in agents cannot be deleted; pause them instead", {
code: "built_in_agent_undeletable",
key: builtInMarker.key,
featureKeys: builtInMarker.featureKeys,
});
}
return db.transaction(async (tx) => {
await tx.update(agents).set({ reportsTo: null }).where(eq(agents.reportsTo, id));
@@ -675,12 +769,32 @@ export function agentService(db: Db) {
});
},
activatePendingApproval: async (id: string) => {
activatePendingApproval: async (id: string, approvedPayload?: Record<string, unknown> | null) => {
const activatedAgent = await db.transaction(async (tx) => {
const txDb = tx as unknown as Db;
const existing = await agentService(txDb).getById(id);
if (!existing || existing.status !== "pending_approval") return null;
const approvedPatch = approvedPayload ? configPatchFromApprovalPayload(approvedPayload) : {};
let patch = { ...approvedPatch } as Partial<typeof agents.$inferInsert>;
if (
Object.prototype.hasOwnProperty.call(patch, "adapterConfig") &&
isPlainRecord(patch.adapterConfig)
) {
patch.adapterConfig = await secretService(txDb).normalizeAdapterConfigForPersistence(
existing.companyId,
patch.adapterConfig,
{ adapterType: (patch.adapterType ?? existing.adapterType) as string },
);
}
if (patch.permissions !== undefined) {
patch.permissions = normalizeAgentPermissions(
patch.permissions,
(patch.role ?? existing.role) as string,
);
}
const updated = await tx
.update(agents)
.set({ status: "idle", updatedAt: new Date() })
.set({ ...patch, status: "idle", updatedAt: new Date() })
.where(and(eq(agents.id, id), eq(agents.status, "pending_approval")))
.returning()
.then((rows) => rows[0] ?? null);
@@ -704,6 +818,13 @@ export function agentService(db: Db) {
updatePermissions: async (id: string, permissions: Record<string, unknown> & { canCreateAgents: boolean }) => {
const existing = await getById(id);
if (!existing) return null;
if (existing.status === "pending_approval") {
throw conflict("Pending approval agent permissions cannot be changed before board approval", {
code: "pending_approval_agent_config_frozen",
agentId: id,
fields: ["permissions"],
});
}
const updated = await db
.update(agents)
+9 -1
View File
@@ -24,6 +24,13 @@ export function approvalService(db: Db) {
};
}
async function reconcileApprovedBuiltInAgent(companyId: string, payload: Record<string, unknown>) {
const sourceBuiltInAgentKey = typeof payload.sourceBuiltInAgentKey === "string" ? payload.sourceBuiltInAgentKey : null;
if (!sourceBuiltInAgentKey) return;
const { builtInAgentService } = await import("./built-in-agents.js");
await builtInAgentService(db).ensure(companyId, sourceBuiltInAgentKey);
}
async function getExistingApproval(id: string) {
const existing = await db
.select()
@@ -128,7 +135,8 @@ export function approvalService(db: Db) {
const payload = updated.payload as Record<string, unknown>;
const payloadAgentId = typeof payload.agentId === "string" ? payload.agentId : null;
if (payloadAgentId) {
await agentsSvc.activatePendingApproval(payloadAgentId);
await agentsSvc.activatePendingApproval(payloadAgentId, payload);
await reconcileApprovedBuiltInAgent(updated.companyId, payload);
hireApprovedAgentId = payloadAgentId;
} else {
const created = await agentsSvc.create(updated.companyId, {
+145 -4
View File
@@ -56,6 +56,7 @@ export type AuthorizationAction =
| PermissionKey
| "agent_config:read"
| "agent_config:update"
| "skill_config:update"
| "agent:read"
| "agent:wake"
| "company_scope:read"
@@ -93,6 +94,8 @@ export type AuthorizationDecision = {
| "allow_local_board"
| "allow_instance_admin"
| "allow_explicit_grant"
| "allow_direct_change"
| "allow_consented_change"
| "allow_legacy_agent_creator"
| "allow_issue_mention_grant"
| "allow_self"
@@ -104,6 +107,8 @@ export type AuthorizationDecision = {
| "deny_company_boundary"
| "deny_missing_membership"
| "deny_missing_grant"
| "deny_missing_consent"
| "deny_no_grant"
| "deny_policy_restricted"
| "deny_low_trust_boundary"
| "deny_scope"
@@ -125,7 +130,9 @@ function companyIdForResource(resource: AuthorizationResource) {
}
function permissionForAction(action: AuthorizationAction): PermissionKey | null {
if (action === "agent_config:read" || action === "agent_config:update") return "agents:create";
if (action === "agent_config:read" || action === "agent_config:update" || action === "skill_config:update") {
return null;
}
if (
action === "agent:read" ||
action === "agent:wake" ||
@@ -466,6 +473,10 @@ function activeResponsibleUserCanAuthorizeIssueAction(
);
}
function scopeBoolean(scope: Record<string, unknown> | null | undefined, key: string) {
return scope?.[key] === true;
}
export function authorizationDeniedDetails(decision: AuthorizationDecision) {
return {
...(decision.code ? { code: decision.code } : {}),
@@ -878,6 +889,9 @@ export function authorizationService(db: Db) {
if (
input.action === "company_scope:read" ||
input.action === "agent_config:read" ||
input.action === "agent_config:update" ||
input.action === "skill_config:update" ||
input.action === "runtime:manage" ||
input.action === "secrets:read"
) {
@@ -1305,6 +1319,94 @@ export function authorizationService(db: Db) {
return broadDecision;
}
async function decideWithAgentConfigReadGrant(
principalType: PrincipalType,
principalId: string,
): Promise<AuthorizationDecision> {
const configureDecision = await decidePrincipalGrant({
companyId,
principalType,
principalId,
action: input.action,
permissionKey: "agents:configure",
scope: input.scope,
});
if (configureDecision.allowed || configureDecision.reason === "deny_missing_membership") {
return configureDecision;
}
const suggestDecision = await decidePrincipalGrant({
companyId,
principalType,
principalId,
action: input.action,
permissionKey: "agents:suggest-changes",
scope: input.scope,
});
if (suggestDecision.allowed || suggestDecision.reason === "deny_missing_grant") {
return suggestDecision;
}
return configureDecision;
}
async function decideWithProtectedChangeGrants(
principalType: PrincipalType,
principalId: string,
keys: { direct: PermissionKey; suggest: PermissionKey },
): Promise<AuthorizationDecision> {
const directDecision = await decidePrincipalGrant({
companyId,
principalType,
principalId,
action: input.action,
permissionKey: keys.direct,
scope: input.scope,
});
if (directDecision.allowed) {
return allow({
action: input.action,
reason: "allow_direct_change",
explanation: `Allowed by direct change permission ${keys.direct}.`,
grant: directDecision.grant,
});
}
if (directDecision.reason === "deny_missing_membership") return directDecision;
const suggestDecision = await decidePrincipalGrant({
companyId,
principalType,
principalId,
action: input.action,
permissionKey: keys.suggest,
scope: input.scope,
});
if (suggestDecision.allowed) {
if (scopeBoolean(input.scope, "consentedChange")) {
return allow({
action: input.action,
reason: "allow_consented_change",
explanation: `Allowed by suggest permission ${keys.suggest} after accepted change consent.`,
grant: suggestDecision.grant,
});
}
return deny({
action: input.action,
reason: "deny_missing_consent",
explanation: `Permission ${keys.suggest} requires accepted change consent before applying this mutation.`,
grant: suggestDecision.grant,
});
}
if (suggestDecision.reason === "deny_missing_membership") return suggestDecision;
if (directDecision.reason === "deny_scope") return directDecision;
if (suggestDecision.reason === "deny_scope") return suggestDecision;
return deny({
action: input.action,
reason: "deny_no_grant",
explanation: `Missing permission: ${keys.direct} or ${keys.suggest}.`,
});
}
async function denyForAssignmentPolicyIfNeeded(
policyEffect: AssignmentPolicyEffect,
): Promise<AuthorizationDecision | null> {
@@ -1465,6 +1567,21 @@ export function authorizationService(db: Db) {
if (policyEffect.kind === "restricted") return denyRestrictedAssignmentPolicy(policyEffect);
return grantDecision;
}
if (input.action === "agent_config:read") {
return decideWithAgentConfigReadGrant("user", input.actor.userId);
}
if (input.action === "agent_config:update") {
return decideWithProtectedChangeGrants("user", input.actor.userId, {
direct: "agents:configure",
suggest: "agents:suggest-changes",
});
}
if (input.action === "skill_config:update") {
return decideWithProtectedChangeGrants("user", input.actor.userId, {
direct: "skills:create",
suggest: "skills:suggest-changes",
});
}
return decidePrincipalGrant({
companyId,
principalType: "user",
@@ -1641,7 +1758,8 @@ export function authorizationService(db: Db) {
if (
input.action === "agent_config:update" &&
input.resource.type === "agent" &&
input.resource.agentId === actorAgentId
input.resource.agentId === actorAgentId &&
!scopeBoolean(input.scope, "requiresChangeGrant")
) {
return allow({
action: input.action,
@@ -1650,6 +1768,31 @@ export function authorizationService(db: Db) {
});
}
if (input.action === "agent_config:read") {
if (input.resource.type === "agent" && input.resource.agentId === actorAgentId) {
return allow({
action: input.action,
reason: "allow_self",
explanation: "Allowed because the actor is reading its own agent configuration.",
});
}
return decideWithAgentConfigReadGrant("agent", actorAgentId);
}
if (input.action === "agent_config:update") {
return decideWithProtectedChangeGrants("agent", actorAgentId, {
direct: "agents:configure",
suggest: "agents:suggest-changes",
});
}
if (input.action === "skill_config:update") {
return decideWithProtectedChangeGrants("agent", actorAgentId, {
direct: "skills:create",
suggest: "skills:suggest-changes",
});
}
if (permissionKey) {
const grantDecision = await decidePrincipalGrant({
companyId,
@@ -1664,8 +1807,6 @@ export function authorizationService(db: Db) {
if (
(input.action === "agents:create" ||
input.action === "agent_config:read" ||
input.action === "agent_config:update" ||
input.action === "tasks:manage_active_checkouts") &&
canCreateAgentsLegacy(actorAgent)
) {
@@ -0,0 +1,45 @@
export const BUILT_IN_AGENT_METADATA_KEY = "paperclipBuiltInAgent";
export interface BuiltInAgentMarker {
key: string;
featureKeys: string[];
}
function isPlainRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function normalizeFeatureKeys(value: unknown): string[] | null {
if (!Array.isArray(value)) return null;
const featureKeys = value.filter((entry): entry is string => typeof entry === "string" && entry.trim().length > 0);
return featureKeys.length === value.length ? featureKeys : null;
}
export function readBuiltInAgentMarker(metadata: unknown): BuiltInAgentMarker | null {
if (!isPlainRecord(metadata)) return null;
const marker = metadata[BUILT_IN_AGENT_METADATA_KEY];
if (!isPlainRecord(marker)) return null;
const key = marker.key;
const featureKeys = normalizeFeatureKeys(marker.featureKeys);
if (typeof key !== "string" || key.trim().length === 0 || !featureKeys) return null;
return { key, featureKeys };
}
export function withBuiltInAgentMarker(
metadata: Record<string, unknown> | null | undefined,
marker: BuiltInAgentMarker,
): Record<string, unknown> {
return {
...(metadata ?? {}),
[BUILT_IN_AGENT_METADATA_KEY]: {
key: marker.key,
featureKeys: [...marker.featureKeys],
},
};
}
export function builtInAgentMarkersEqual(left: BuiltInAgentMarker | null, right: BuiltInAgentMarker | null) {
if (!left && !right) return true;
if (!left || !right) return false;
return left.key === right.key && JSON.stringify(left.featureKeys) === JSON.stringify(right.featureKeys);
}
File diff suppressed because it is too large. Load diff
+232
View File
@@ -0,0 +1,232 @@
import type { Db } from "@paperclipai/db";
import { issueThreadInteractions } from "@paperclipai/db";
import { and, desc, eq, or, sql } from "drizzle-orm";
import type { RequestConfirmationPayload, RequestConfirmationResult } from "@paperclipai/shared";
import { forbidden } from "../errors.js";
export const AGENT_PROFILE_CHANGE_CONSENT_FIELDS = ["name", "role", "title", "capabilities"] as const;
type ConsumedRequestConfirmationResult = RequestConfirmationResult & {
consumedAt?: string | null;
consumedByRunId?: string | null;
};
export function agentInstructionsChangeTargetKey(agentId: string) {
return `agent:${agentId}:instructions`;
}
export function agentProfileChangeTargetKey(agentId: string) {
return `agent:${agentId}:profile`;
}
export function skillChangeTargetKey(skillId: string) {
return `skill:${skillId}`;
}
export function skillSlugChangeTargetKey(slug: string) {
return `skill-slug:${slug}`;
}
export function skillImportChangeTargetKey(source: string) {
return `skill-import:${source}`;
}
export function skillsScanProjectsChangeTargetKey() {
return "skills:scan-projects";
}
export function touchesAgentProfileChangeConsentFields(patchData: Record<string, unknown>) {
return AGENT_PROFILE_CHANGE_CONSENT_FIELDS.some((key) =>
Object.prototype.hasOwnProperty.call(patchData, key),
);
}
function readNonEmptyString(value: unknown) {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
}
function payloadHasDisplayedDiff(payload: RequestConfirmationPayload) {
const details = readNonEmptyString(payload.detailsMarkdown);
if (!details) return false;
if (/```diff\b/i.test(details)) return true;
return /(^|\n)[+-][^\n]+/.test(details);
}
function requestConfirmationResultConsumed(result: RequestConfirmationResult | null) {
const consumed = result as ConsumedRequestConfirmationResult | null;
return Boolean(readNonEmptyString(consumed?.consumedByRunId) || readNonEmptyString(consumed?.consumedAt));
}
function markRequestConfirmationResultConsumed(
result: RequestConfirmationResult,
actorRunId: string,
consumedAt: Date,
): ConsumedRequestConfirmationResult {
return {
...result,
consumedAt: consumedAt.toISOString(),
consumedByRunId: actorRunId,
};
}
function legacyTargetKeysFor(targetKey: string) {
if (targetKey.startsWith("agent:") && targetKey.endsWith(":instructions")) {
const agentId = targetKey.slice("agent:".length, -":instructions".length);
if (agentId) return [`reflection-coach:agent-instructions:${agentId}`];
}
if (targetKey.startsWith("agent:") && targetKey.endsWith(":profile")) {
const agentId = targetKey.slice("agent:".length, -":profile".length);
if (agentId) return [`reflection-coach:agent-description:${agentId}`];
}
if (targetKey.startsWith("skill:")) {
const skillId = targetKey.slice("skill:".length);
if (skillId) return [`reflection-coach:company-skill:${skillId}`];
}
if (targetKey.startsWith("skill-slug:")) {
const slug = targetKey.slice("skill-slug:".length);
if (slug) return [`reflection-coach:company-skill-slug:${slug}`];
}
if (targetKey.startsWith("skill-import:")) {
const source = targetKey.slice("skill-import:".length);
if (source) {
return [
`reflection-coach:company-skill-import:${source}`,
`reflection-coach:company-skill-catalog:${source}`,
];
}
}
if (targetKey === "skills:scan-projects") {
return ["reflection-coach:company-skills:scan-projects"];
}
return [];
}
function expandTargetKeysForLegacyCompatibility(targetKeys: string[]) {
const expanded = new Set<string>();
for (const targetKey of targetKeys) {
expanded.add(targetKey);
for (const legacyTargetKey of legacyTargetKeysFor(targetKey)) {
expanded.add(legacyTargetKey);
}
}
return [...expanded];
}
export function changeConsentGateService(db: Db) {
return {
assertConsented: async (input: {
companyId: string;
actorAgentId: string | null | undefined;
actorRunId: string | null | undefined;
targetKeys: string[];
}): Promise<boolean> => {
const actorAgentId = readNonEmptyString(input.actorAgentId);
if (!actorAgentId) return false;
const actorRunId = readNonEmptyString(input.actorRunId);
if (!actorRunId) {
throw forbidden("Reflection Coach mutations require a run id", {
code: "reflection_coach_mutation_run_id_required",
});
}
const targetKeys = [...new Set(input.targetKeys.map(readNonEmptyString).filter((key): key is string => Boolean(key)))];
if (targetKeys.length === 0) {
throw forbidden("Reflection Coach mutation target is not gateable", {
code: "reflection_coach_mutation_target_required",
});
}
const queryTargetKeys = expandTargetKeysForLegacyCompatibility(targetKeys);
const targetKeyPredicate = or(
...queryTargetKeys.map((targetKey) =>
sql`${issueThreadInteractions.payload}->'target'->>'key' = ${targetKey}`,
),
);
const rows = await db
.select({
id: issueThreadInteractions.id,
sourceRunId: issueThreadInteractions.sourceRunId,
payload: issueThreadInteractions.payload,
result: issueThreadInteractions.result,
})
.from(issueThreadInteractions)
.where(and(
eq(issueThreadInteractions.companyId, input.companyId),
eq(issueThreadInteractions.createdByAgentId, actorAgentId),
eq(issueThreadInteractions.kind, "request_confirmation"),
eq(issueThreadInteractions.status, "accepted"),
targetKeyPredicate,
))
.orderBy(desc(issueThreadInteractions.resolvedAt), desc(issueThreadInteractions.createdAt))
.limit(10);
const accepted = rows.find((row) => {
const payload = row.payload as RequestConfirmationPayload;
const result = row.result as RequestConfirmationResult | null;
return payload.target?.type === "custom"
&& queryTargetKeys.includes(payload.target.key)
&& result?.outcome === "accepted"
&& !requestConfirmationResultConsumed(result)
&& payloadHasDisplayedDiff(payload)
&& Boolean(row.sourceRunId)
&& row.sourceRunId !== actorRunId;
});
if (!accepted) {
throw forbidden(
"Reflection Coach mutations require an accepted request_confirmation with a displayed diff for this target, "
+ "created in a previous run and not already consumed.",
{
code: "reflection_coach_mutation_gate_required",
targetKeys,
},
);
}
const acceptedResult = accepted.result as RequestConfirmationResult | null;
if (!acceptedResult) {
throw forbidden(
"Reflection Coach mutations require an accepted request_confirmation with a displayed diff for this target, "
+ "created in a previous run and not already consumed.",
{
code: "reflection_coach_mutation_gate_required",
targetKeys,
},
);
}
const now = new Date();
const [consumed] = await db
.update(issueThreadInteractions)
.set({
result: markRequestConfirmationResultConsumed(acceptedResult, actorRunId, now),
updatedAt: now,
})
.where(and(
eq(issueThreadInteractions.id, accepted.id),
eq(issueThreadInteractions.companyId, input.companyId),
eq(issueThreadInteractions.createdByAgentId, actorAgentId),
eq(issueThreadInteractions.kind, "request_confirmation"),
eq(issueThreadInteractions.status, "accepted"),
sql`${issueThreadInteractions.result}->>'outcome' = 'accepted'`,
sql`coalesce(${issueThreadInteractions.result}->>'consumedByRunId', ${issueThreadInteractions.result}->>'consumedAt') is null`,
))
.returning({ id: issueThreadInteractions.id });
if (!consumed) {
throw forbidden(
"Reflection Coach mutations require an accepted request_confirmation with a displayed diff for this target, "
+ "created in a previous run and not already consumed.",
{
code: "reflection_coach_mutation_gate_required",
targetKeys,
},
);
}
return true;
},
};
}
+3
View File
@@ -33,6 +33,7 @@ import { notFound, unprocessable } from "../errors.js";
import { environmentService } from "./environments.js";
import { heartbeatService } from "./heartbeat.js";
import { logActivity } from "./activity-log.js";
import { builtInAgentService } from "./built-in-agents.js";
export interface CompanyActivityActor {
actorType: "user" | "agent" | "system" | "plugin";
@@ -52,6 +53,7 @@ export function companyService(db: Db) {
const ISSUE_PREFIX_FALLBACK = "CMP";
const environmentsSvc = environmentService(db);
const heartbeat = heartbeatService(db);
const builtInAgents = builtInAgentService(db);
type CompanyTx = Parameters<Parameters<typeof db.transaction>[0]>[0];
@@ -263,6 +265,7 @@ export function companyService(db: Db) {
create: async (data: typeof companies.$inferInsert) => {
const created = await createCompanyWithUniquePrefix(data);
await environmentsSvc.ensureLocalEnvironment(created.id);
await builtInAgents.autoProvisionBundledAgents(created.id);
const row = await getCompanyQuery(db)
.where(eq(companies.id, created.id))
.then((rows) => rows[0] ?? null);
@@ -28,6 +28,7 @@ export function grantsForHumanRole(
case "owner":
return [
{ permissionKey: "agents:create", scope: null },
{ permissionKey: "agents:configure", scope: null },
{ permissionKey: "skills:create", scope: null },
{ permissionKey: "environments:manage", scope: null },
{ permissionKey: "users:invite", scope: null },
@@ -38,6 +39,7 @@ export function grantsForHumanRole(
case "admin":
return [
{ permissionKey: "agents:create", scope: null },
{ permissionKey: "agents:configure", scope: null },
{ permissionKey: "skills:create", scope: null },
{ permissionKey: "environments:manage", scope: null },
{ permissionKey: "users:invite", scope: null },
+150 -8
View File
@@ -3,7 +3,8 @@ import { promises as fs } from "node:fs";
import { execFile } from "node:child_process";
import path from "node:path";
import { promisify } from "node:util";
import type { Db } from "@paperclipai/db";
import { and, eq, inArray } from "drizzle-orm";
import { builtInManagedResources, principalPermissionGrants, type Db } from "@paperclipai/db";
import type {
CompanyPortabilityAgentManifestEntry,
CompanyPortabilityCollisionStrategy,
@@ -29,6 +30,7 @@ import type {
CompanyPortabilitySkillManifestEntry,
CompanySkill,
AgentEnvConfig,
PermissionKey,
RoutineVariable,
} from "@paperclipai/shared";
import {
@@ -48,6 +50,7 @@ import {
issueCommentMetadataSchema,
issueCommentPresentationSchema,
normalizeAgentUrlKey,
PERMISSION_KEYS,
} from "@paperclipai/shared";
import {
readPaperclipSkillSyncPreference,
@@ -77,6 +80,7 @@ import {
readCatalogStringList,
readPortableCatalogProvenance,
} from "./catalog-provenance.js";
import { readBuiltInAgentMarker } from "./built-in-agent-metadata.js";
import { normalizePortablePath } from "./portable-path.js";
/** Build OrgNode tree from manifest agent list (slug + reportsToSlug). */
@@ -718,6 +722,23 @@ function asBoolean(value: unknown): boolean | null {
return typeof value === "boolean" ? value : null;
}
type PortableAgentPermissionGrant = CompanyPortabilityAgentManifestEntry["permissionGrants"][number];
const VALID_PERMISSION_KEYS = new Set<PermissionKey>(PERMISSION_KEYS);
function normalizePortablePermissionGrants(value: unknown): PortableAgentPermissionGrant[] {
if (!Array.isArray(value)) return [];
return value.flatMap((entry): PortableAgentPermissionGrant[] => {
if (!isPlainRecord(entry)) return [];
const permissionKey = asString(entry.permissionKey);
if (!permissionKey || !VALID_PERMISSION_KEYS.has(permissionKey as PermissionKey)) return [];
return [{
permissionKey: permissionKey as PermissionKey,
scope: isPlainRecord(entry.scope) ? entry.scope : null,
}];
});
}
function asInteger(value: unknown): number | null {
return typeof value === "number" && Number.isInteger(value) ? value : null;
}
@@ -1924,6 +1945,7 @@ const YAML_KEY_PRIORITY = [
"adapter",
"runtime",
"permissions",
"permissionGrants",
"budgetMonthlyCents",
"metadata",
] as const;
@@ -2690,6 +2712,7 @@ function buildManifestFromPackageFiles(
const extensionAdapter = isPlainRecord(extension.adapter) ? extension.adapter : null;
const extensionRuntime = isPlainRecord(extension.runtime) ? extension.runtime : null;
const extensionPermissions = isPlainRecord(extension.permissions) ? extension.permissions : null;
const extensionPermissionGrants = normalizePortablePermissionGrants(extension.permissionGrants);
const extensionMetadata = isPlainRecord(extension.metadata) ? extension.metadata : null;
const adapterConfig = isPlainRecord(extensionAdapter?.config)
? extensionAdapter.config
@@ -2713,6 +2736,7 @@ function buildManifestFromPackageFiles(
adapterConfig,
runtimeConfig,
permissions: extensionPermissions ?? {},
permissionGrants: extensionPermissionGrants,
budgetMonthlyCents:
typeof extension.budgetMonthlyCents === "number" && Number.isFinite(extension.budgetMonthlyCents)
? Math.max(0, Math.floor(extension.budgetMonthlyCents))
@@ -3002,6 +3026,27 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
const strictSecretsMode = process.env.PAPERCLIP_SECRETS_STRICT_MODE === "true";
const defaultSecretProvider = getConfiguredSecretProvider();
async function applyImportedAgentPermissionGrants(
companyId: string,
agentId: string,
permissionGrants: PortableAgentPermissionGrant[],
grantedByUserId: string | null,
) {
if (permissionGrants.length === 0) return;
await access.ensureMembership(companyId, "agent", agentId, "member", "active");
for (const grant of permissionGrants) {
await access.setPrincipalPermission(
companyId,
"agent",
agentId,
grant.permissionKey,
true,
grantedByUserId,
grant.scope ?? null,
);
}
}
function assertKnownImportAdapterType(type: string | null | undefined): string {
const adapterType = typeof type === "string" ? type.trim() : "";
if (!adapterType) {
@@ -3253,24 +3298,61 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
const rootPath = normalizeAgentUrlKey(company.name) ?? "company-package";
let companyLogoPath: string | null = null;
const managedResourceRows = typeof (db as { select?: unknown }).select === "function"
? await db
.select({
resourceKind: builtInManagedResources.resourceKind,
resourceId: builtInManagedResources.resourceId,
})
.from(builtInManagedResources)
.where(eq(builtInManagedResources.companyId, companyId))
: [];
const managedSkillIds = new Set(
managedResourceRows
.filter((row) => row.resourceKind === "skill")
.map((row) => row.resourceId),
);
const managedRoutineIds = new Set(
managedResourceRows
.filter((row) => row.resourceKind === "routine")
.map((row) => row.resourceId),
);
const allAgentRows = include.agents ? await agents.list(companyId, { includeTerminated: true }) : [];
const liveAgentRows = allAgentRows.filter((agent) => agent.status !== "terminated");
const companySkillRows = include.skills || include.agents ? await companySkills.listFull(companyId) : [];
const builtInAgentRows = liveAgentRows.filter((agent) => readBuiltInAgentMarker(agent.metadata));
const portableAgentRows = liveAgentRows.filter((agent) => !readBuiltInAgentMarker(agent.metadata));
const companySkillRowsRaw = include.skills || include.agents ? await companySkills.listFull(companyId) : [];
const managedSkillRows = companySkillRowsRaw.filter((skill) => managedSkillIds.has(skill.id));
const companySkillRows = companySkillRowsRaw.filter((skill) => !managedSkillIds.has(skill.id));
if (include.agents) {
const skipped = allAgentRows.length - liveAgentRows.length;
if (skipped > 0) {
warnings.push(`Skipped ${skipped} terminated agent${skipped === 1 ? "" : "s"} from export.`);
}
if (builtInAgentRows.length > 0) {
warnings.push(`Skipped ${builtInAgentRows.length} built-in managed agent${builtInAgentRows.length === 1 ? "" : "s"} from export.`);
}
}
if (include.skills && managedSkillRows.length > 0) {
warnings.push(`Skipped ${managedSkillRows.length} built-in managed skill${managedSkillRows.length === 1 ? "" : "s"} from export.`);
}
const agentByReference = new Map<string, typeof liveAgentRows[number]>();
for (const agent of liveAgentRows) {
agentByReference.set(agent.id, agent);
agentByReference.set(agent.name, agent);
const builtInAgentByReference = new Map<string, typeof liveAgentRows[number]>();
const addAgentReferences = (map: Map<string, typeof liveAgentRows[number]>, agent: typeof liveAgentRows[number]) => {
map.set(agent.id, agent);
map.set(agent.name, agent);
const normalizedName = normalizeAgentUrlKey(agent.name);
if (normalizedName) {
agentByReference.set(normalizedName, agent);
map.set(normalizedName, agent);
}
};
for (const agent of portableAgentRows) {
addAgentReferences(agentByReference, agent);
}
for (const agent of builtInAgentRows) {
addAgentReferences(builtInAgentByReference, agent);
}
const selectedAgents = new Map<string, typeof liveAgentRows[number]>();
@@ -3280,6 +3362,11 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
const normalized = normalizeAgentUrlKey(trimmed) ?? trimmed;
const match = agentByReference.get(trimmed) ?? agentByReference.get(normalized);
if (!match) {
const builtInMatch = builtInAgentByReference.get(trimmed) ?? builtInAgentByReference.get(normalized);
if (builtInMatch) {
warnings.push(`Agent selector "${selector}" is a built-in managed agent and was skipped.`);
continue;
}
warnings.push(`Agent selector "${selector}" was not found and was skipped.`);
continue;
}
@@ -3287,7 +3374,7 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
}
if (include.agents && selectedAgents.size === 0) {
for (const agent of liveAgentRows) {
for (const agent of portableAgentRows) {
selectedAgents.set(agent.id, agent);
}
}
@@ -3302,13 +3389,49 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
const slug = uniqueSlug(baseSlug, usedSlugs);
idToSlug.set(agent.id, slug);
}
const agentPermissionGrantRows = agentRows.length > 0 && typeof (db as { select?: unknown }).select === "function"
? await db
.select({
principalId: principalPermissionGrants.principalId,
permissionKey: principalPermissionGrants.permissionKey,
scope: principalPermissionGrants.scope,
})
.from(principalPermissionGrants)
.where(and(
eq(principalPermissionGrants.companyId, companyId),
eq(principalPermissionGrants.principalType, "agent"),
inArray(principalPermissionGrants.principalId, agentRows.map((agent) => agent.id)),
))
: [];
const permissionGrantsByAgentId = new Map<string, PortableAgentPermissionGrant[]>();
for (const row of agentPermissionGrantRows) {
if (!VALID_PERMISSION_KEYS.has(row.permissionKey as PermissionKey)) continue;
const grants = permissionGrantsByAgentId.get(row.principalId) ?? [];
grants.push({
permissionKey: row.permissionKey as PermissionKey,
scope: isPlainRecord(row.scope) ? row.scope : null,
});
permissionGrantsByAgentId.set(row.principalId, grants);
}
for (const grants of permissionGrantsByAgentId.values()) {
grants.sort((left, right) => left.permissionKey.localeCompare(right.permissionKey));
}
const projectsSvc = projectService(db);
const issuesSvc = issueService(db);
const routinesSvc = routineService(db);
const allProjectsRaw = include.projects || include.issues ? await projectsSvc.list(companyId) : [];
const allProjects = allProjectsRaw.filter((project) => !project.archivedAt);
const allRoutines = include.issues ? await routinesSvc.list(companyId) : [];
const allRoutinesRaw = include.issues ? await routinesSvc.list(companyId) : [];
const builtInRoutineRows = allRoutinesRaw.filter((routine) =>
managedRoutineIds.has(routine.id) || routine.originKind === "built_in_agent_bundle"
);
const allRoutines = allRoutinesRaw.filter((routine) =>
!managedRoutineIds.has(routine.id) && routine.originKind !== "built_in_agent_bundle"
);
if (include.issues && builtInRoutineRows.length > 0) {
warnings.push(`Skipped ${builtInRoutineRows.length} built-in managed routine${builtInRoutineRows.length === 1 ? "" : "s"} from export.`);
}
const projectById = new Map(allProjects.map((project) => [project.id, project]));
const projectByReference = new Map<string, typeof allProjects[number]>();
for (const project of allProjects) {
@@ -3330,6 +3453,7 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
const selectedIssues = new Map<string, Awaited<ReturnType<typeof issuesSvc.getById>>>();
const selectedRoutines = new Map<string, typeof allRoutines[number]>();
const routineById = new Map(allRoutines.map((routine) => [routine.id, routine]));
const builtInRoutineById = new Map(builtInRoutineRows.map((routine) => [routine.id, routine]));
const resolveIssueBySelector = async (selector: string) => {
const trimmed = selector.trim();
if (!trimmed) return null;
@@ -3340,6 +3464,10 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
for (const selector of input.issues ?? []) {
const issue = await resolveIssueBySelector(selector);
if (!issue || issue.companyId !== companyId) {
if (builtInRoutineById.has(selector.trim())) {
warnings.push(`Routine selector "${selector}" is a built-in managed routine and was skipped.`);
continue;
}
const routine = routineById.get(selector.trim());
if (routine) {
selectedRoutines.set(routine.id, routine);
@@ -3551,6 +3679,7 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
},
) as Record<string, unknown>;
const portablePermissions = pruneDefaultLikeValue(agent.permissions ?? {}, { dropFalseBooleans: true }) as Record<string, unknown>;
const portablePermissionGrants = permissionGrantsByAgentId.get(agent.id) ?? [];
const agentEnvInputs = dedupeEnvInputs(
envInputs
.slice(envInputsStart)
@@ -3593,6 +3722,7 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
},
runtime: portableRuntimeConfig,
permissions: portablePermissions,
permissionGrants: portablePermissionGrants.length > 0 ? portablePermissionGrants : undefined,
budgetMonthlyCents: (agent.budgetMonthlyCents ?? 0) > 0 ? agent.budgetMonthlyCents : undefined,
metadata: (agent.metadata as Record<string, unknown> | null) ?? null,
});
@@ -4593,6 +4723,12 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
} catch (err) {
warnings.push(`Failed to materialize instructions bundle for ${manifestAgent.slug}: ${err instanceof Error ? err.message : String(err)}`);
}
await applyImportedAgentPermissionGrants(
targetCompany.id,
updated.id,
manifestAgent.permissionGrants ?? [],
actorUserId ?? null,
);
agentStatusById.set(updated.id, updated.status ?? agentStatusById.get(updated.id) ?? null);
await secrets.syncEnvBindingsForTarget?.(
targetCompany.id,
@@ -4634,6 +4770,12 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
} catch (err) {
warnings.push(`Failed to materialize instructions bundle for ${manifestAgent.slug}: ${err instanceof Error ? err.message : String(err)}`);
}
await applyImportedAgentPermissionGrants(
targetCompany.id,
created.id,
manifestAgent.permissionGrants ?? [],
actorUserId ?? null,
);
agentStatusById.set(created.id, created.status ?? createdStatus);
await secrets.syncEnvBindingsForTarget?.(
targetCompany.id,
+13
View File
@@ -4,6 +4,19 @@ export { companySearchService } from "./company-search.js";
export { feedbackService } from "./feedback.js";
export { companySkillService } from "./company-skills.js";
export { agentService, deduplicateAgentName } from "./agents.js";
export {
builtInAgentService,
deriveBuiltInAgentStatus,
getBuiltInAgentDefinition,
listBuiltInAgentDefinitions,
reconcileBuiltInAgentsOnStartup,
validateBuiltInAgentDefinitions,
type BuiltInAgentDefinition,
type BuiltInManagedResourceState,
type BuiltInManagedResourceStockStatus,
type BuiltInAgentState,
type BuiltInAgentStatus,
} from "./built-in-agents.js";
export { agentInstructionsService, syncInstructionsBundleConfigFromFilePath } from "./agent-instructions.js";
export { assetService } from "./assets.js";
export { documentService, extractLegacyPlanBody } from "./documents.js";
+2
View File
@@ -54,6 +54,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
enableTaskWatchdogs: parsed.data.enableTaskWatchdogs ?? false,
enableCloudSync: parsed.data.enableCloudSync ?? false,
enableExternalObjects: parsed.data.enableExternalObjects ?? false,
enableBuiltInAgents: parsed.data.enableBuiltInAgents ?? false,
enableGoalsSidebarLink: parsed.data.enableGoalsSidebarLink ?? false,
enableServerInfoDebugView: parsed.data.enableServerInfoDebugView ?? false,
autoRestartDevServerWhenIdle: parsed.data.autoRestartDevServerWhenIdle ?? false,
@@ -76,6 +77,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
enableExperimentalFileViewer: false,
enableCloudSync: false,
enableExternalObjects: false,
enableBuiltInAgents: false,
enableGoalsSidebarLink: false,
enableServerInfoDebugView: false,
autoRestartDevServerWhenIdle: false,