mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-13 04:02:28 +02:00
## Thinking Path > - Paperclip manages agent work as tasks and runs. > - GitHub chat brings repository conversations into those tasks. > - A review bot needs the assigned agent, its authority, and governed provider tools. > - The existing channel connection did not supply that review workflow or a complete setup journey. > - This pull request adds GitHub App setup, account access, event prompts, task-bound review tools, and exact-commit checks. > - Operators can inspect each review through the same task, run, and activity systems. ## Linked Issues or Issue Description **Subsystem affected** GitHub chat, governed connection tools, task execution, shared/database contracts, and connector setup UI. **Problem or motivation** Operators need a GitHub review bot that runs their assigned Paperclip agent. Mentions and PR events must preserve task ownership and requester authority. Provider publication must use the bot App identity and enforce the configured permissions. **Proposed solution** Extend the existing GitHub chat connector with resumable App onboarding, linked-member and sponsored-guest access, editable event prompts, and governed review operations. Validate structured assessments on the server and compute a stable Paperclip Review check for the exact head commit. **Alternatives considered** A separate review scheduler would duplicate Paperclip execution and permissions. Reusing personal GitHub credentials would change the bot identity and credential boundary. **Roadmap alignment** This extends the existing Connected Apps and governed-tool infrastructure. The project owner requested and approved this design. Related PR #8645 imports external Codex review feedback; this change runs an assigned Paperclip agent and publishes its results through the existing chat connector. ## What Changed - Include the current Paperclip instance origin in the copied setup prompt. Storybook uses its configured Paperclip origin; callback parameters and URL credentials are excluded. - Add a Claude/Codex copy button in the real setup and Storybook opening step. Its detailed prompt asks four setup questions and guides embedded-browser setup, verification, and optional required checks. Clipboard failure exposes selectable instructions. - Add a tutorial that explains why App installation, review scheduling, and required checks are separate choices. - Add manifest registration, an existing-App path, separate installation and repository selection, repository refresh, and explicit account confirmation. - Add low-trust agent guidance, effective capability verification, member selection, and explicit restricted guests with a sponsor. - Add configurable PR events, prompts, repository overrides, rating thresholds, and separate formal-review permissions. - Give the assigned agent governed App tools to read PRs, comment, begin an assessment, submit findings, and optionally submit a formal review. - Bind review history, root PR events, and inline replies to ordinary tasks. Deduplicate deliveries/findings and reject stale publication. - Link check Details to the underlying task on the current trusted hostname, or to Reviews before task creation. - Add schema migration 0283, API contracts, production UI, and 49 interactive Storybook states. - Repair local lease recovery. Keep the Cloud Dockerfile identical to master; no provider-pack layer or runtime-default environment variable is added. - Retry only rolled-back wake-admission transactions after transient endpoint-lock contention. A deterministic held-lock regression proves one accepted wake. ## Verification - Current head: `7ba761fe007bb798400d3e62346fa964f607f0f8`, rebased on master `d9b3a5653e41f2ee5a1345b97c86a238f7a5c8e9`. Dockerfile has zero diff against master. Final workspace typecheck and build passed. The new PostgreSQL migration regression passed and preserves existing relation and constraint identities after replay. - Greptile reviewed this exact head at 5/5. There are zero unresolved review threads and no merge conflicts. - All current-head checks are green: 54 passed and two conditional Storybook jobs skipped. This includes complete server/workspace test suites, build, typechecks, policy checks, Runner suites, browser suites, and security status. One timing-sensitive callback-ordering test passed in isolation and its CI shard passed one retry. The duplicate local full-suite run was stopped after CI completed; it is not counted as a local full-suite pass. - Before the final Slack rebase and migration renumbering, 186 focused GitHub tests, 14 native bootstrap cases, token gates, and Storybook build passed. The final rebase retained the new Slack communication guidance. - The embedded-browser setup test copied the full detailed prompt, including the configured Paperclip instance URL. Desktop and narrow layouts were checked. Component tests cover successful copying and clipboard failure with selectable text and retry. - Live local and hosted GitHub acceptance evidence refers to application revision `cb703ac959876a07ebf3d7a295847f9f351eb6fc`. Real agent tasks exercised issue mentions, automatic PR reviews, inline findings, repeated mentions, task continuation, and failing-to-passing checks after a push. The Storybook agent generated, built, and browser-rendered pages; missing acceptance text failed, matching text passed, and broken JSX produced an incomplete result. - Live cases also covered independently disabled push events, prompt injection, duplicate signed deliveries, rapid pushes, stale-result rejection, finding deduplication, and restart recovery. Formal reviews were denied while disabled and published only after explicit enablement. Check Details links pointed to the underlying task on the trusted hostname. - Those hosted native Claude runs used the provider-pack layer now removed from this PR. They do not prove native Claude works on the standard Cloud image. A replacement hosted native Codex run is not yet verified: the disposable QA tenant has only an Anthropic AI connection. No new staging or production deployment was made for the packaging removal. - Required-check merge enforcement could not be tested because the private disposable repository's GitHub plan rejected the rules configuration. Published success/failure/incomplete check states were verified directly. ## Risks - Latest master allocated migration 0282 to Slack. The GitHub migration is regenerated as 0283 with replay-safe table/index/constraint creation; a PostgreSQL regression verifies existing relations and constraints are preserved. Existing preview tenants remain subject to the fleet migration-history compatibility preflight; no bypass is introduced. - Migration 0283 adds company-scoped configuration, registration, review, and publication records. Existing connections retain their behavior until reviews/tools are enabled. - Signed webhooks and expiring registration state remain required. Hosted installations also need the companion narrow Cloud gateway exemptions. - Agent assessments can be incomplete or wrong. The server enforces coverage/result structure, current-head publication, rating policy, and separate formal-review permission; it does not replace code-review judgment. - No Cloud image packaging changes are included. Remote native ACPX/Claude and OpenCode retain their existing operator-supplied provider-pack prerequisite. Native Codex and Codex with managed MCP tools do not require that pack. Earlier staging deployment evidence refers to its stated revision, not this packaging-removal head. Production rollout and merging remain outside this change. ## Model Used OpenAI GPT-6 through Codex, with repository, code execution, API, and embedded-browser tools. The exact serving model ID and context-window size were not exposed by the environment. ## 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>
630 lines
22 KiB
TypeScript
630 lines
22 KiB
TypeScript
import { githubBotCredentials } from "./chat-github-client.js";
|
|
import { toolAccessPolicyService } from "./tool-access-policy.js";
|
|
import { agents, toolCatalogEntries } from "@paperclipai/db";
|
|
import { GITHUB_BOT_TOOLS, syncGitHubBotTools } from "./chat-github-tools.js";
|
|
import { and, desc, eq, sql } from "drizzle-orm";
|
|
import {
|
|
chatEndpoints,
|
|
chatEndpointResources,
|
|
chatExternalPrincipals,
|
|
chatIdentityLinks,
|
|
chatGitHubConfigurations,
|
|
chatGitHubReviews,
|
|
companyMemberships,
|
|
connectionGrants,
|
|
toolConnections,
|
|
type Db,
|
|
} from "@paperclipai/db";
|
|
import {
|
|
defaultGitHubReviewPolicy,
|
|
updateGitHubChatConfigurationSchema,
|
|
type GitHubChatConfiguration,
|
|
} from "@paperclipai/shared";
|
|
import { badRequest, conflict, forbidden, notFound } from "../errors.js";
|
|
import { toolAccessService } from "./tool-access.js";
|
|
import { logActivity } from "./activity-log.js";
|
|
import { githubBotRequest } from "./chat-github-client.js";
|
|
import { environmentService } from "./environments.js";
|
|
import { instanceSettingsService } from "./instance-settings.js";
|
|
import { resolveExecutionWorkspaceEnvironmentId } from "./execution-workspace-policy.js";
|
|
|
|
export function githubChatManagementService(db: Db, fetchImpl = fetch) {
|
|
async function endpoint(id: string) {
|
|
const [row] = await db
|
|
.select()
|
|
.from(chatEndpoints)
|
|
.where(
|
|
and(eq(chatEndpoints.id, id), eq(chatEndpoints.provider, "github")),
|
|
);
|
|
if (!row || row.status === "archived")
|
|
throw notFound("GitHub bot not found");
|
|
return row;
|
|
}
|
|
async function member(companyId: string, userId: string) {
|
|
const [row] = await db
|
|
.select()
|
|
.from(companyMemberships)
|
|
.where(
|
|
and(
|
|
eq(companyMemberships.companyId, companyId),
|
|
eq(companyMemberships.principalType, "user"),
|
|
eq(companyMemberships.principalId, userId),
|
|
eq(companyMemberships.status, "active"),
|
|
),
|
|
);
|
|
if (!row || row.membershipRole === "viewer")
|
|
throw forbidden(
|
|
"An active company member with permission to start work is required",
|
|
);
|
|
return row;
|
|
}
|
|
async function configuration(endpointId: string, userId: string) {
|
|
const bot = await endpoint(endpointId);
|
|
const [saved] = await db
|
|
.select()
|
|
.from(chatGitHubConfigurations)
|
|
.where(
|
|
and(
|
|
eq(chatGitHubConfigurations.companyId, bot.companyId),
|
|
eq(chatGitHubConfigurations.endpointId, endpointId),
|
|
),
|
|
);
|
|
return (
|
|
saved ?? {
|
|
endpointId,
|
|
companyId: bot.companyId,
|
|
revision: 0,
|
|
configuration: {
|
|
version: 1,
|
|
toolsEnabled: false,
|
|
responsibleUserId: userId,
|
|
memberAccess: "all_linked",
|
|
people: [],
|
|
defaults: defaultGitHubReviewPolicy(),
|
|
repositories: {},
|
|
} satisfies GitHubChatConfiguration,
|
|
}
|
|
);
|
|
}
|
|
async function saveConfiguration(
|
|
endpointId: string,
|
|
input: unknown,
|
|
userId: string,
|
|
) {
|
|
const bot = await endpoint(endpointId);
|
|
await member(bot.companyId, userId);
|
|
const parsed = updateGitHubChatConfigurationSchema.parse(input);
|
|
const config = parsed.configuration;
|
|
await member(bot.companyId, config.responsibleUserId);
|
|
for (const person of config.people) {
|
|
if (person.kind === "guest") {
|
|
await member(bot.companyId, person.sponsorUserId);
|
|
continue;
|
|
}
|
|
await member(bot.companyId, person.userId);
|
|
const [linked] = await db
|
|
.select({ externalId: chatExternalPrincipals.externalId })
|
|
.from(chatIdentityLinks)
|
|
.innerJoin(
|
|
chatExternalPrincipals,
|
|
eq(chatExternalPrincipals.id, chatIdentityLinks.principalId),
|
|
)
|
|
.where(
|
|
and(
|
|
eq(chatIdentityLinks.companyId, bot.companyId),
|
|
eq(chatIdentityLinks.endpointId, endpointId),
|
|
eq(chatIdentityLinks.paperclipUserId, person.userId),
|
|
eq(chatIdentityLinks.status, "linked"),
|
|
eq(chatExternalPrincipals.externalId, person.githubUserId),
|
|
),
|
|
);
|
|
if (!linked)
|
|
throw badRequest(
|
|
"Each member must connect and confirm their own GitHub account before being added",
|
|
);
|
|
}
|
|
const resources = await db
|
|
.select()
|
|
.from(chatEndpointResources)
|
|
.where(
|
|
and(
|
|
eq(chatEndpointResources.companyId, bot.companyId),
|
|
eq(chatEndpointResources.endpointId, endpointId),
|
|
),
|
|
);
|
|
const repositoryIds = new Set(
|
|
resources.map((resource) =>
|
|
String(resource.metadata?.providerRepositoryId ?? ""),
|
|
),
|
|
);
|
|
if (Object.keys(config.repositories).some((id) => !repositoryIds.has(id)))
|
|
throw badRequest(
|
|
"Repository overrides must refer to this App installation",
|
|
);
|
|
await db.transaction(async (tx) => {
|
|
await tx
|
|
.select({ id: chatEndpoints.id })
|
|
.from(chatEndpoints)
|
|
.where(eq(chatEndpoints.id, endpointId))
|
|
.for("update");
|
|
await tx.execute(
|
|
sql`select pg_advisory_xact_lock(hashtextextended(${`github-config:${endpointId}`}, 0))`,
|
|
);
|
|
const [current] = await tx
|
|
.select()
|
|
.from(chatGitHubConfigurations)
|
|
.where(eq(chatGitHubConfigurations.endpointId, endpointId))
|
|
.for("update");
|
|
if ((current?.revision ?? 0) !== parsed.expectedRevision)
|
|
throw conflict("This configuration changed. Refresh before saving.");
|
|
const values = {
|
|
companyId: bot.companyId,
|
|
endpointId,
|
|
revision: parsed.expectedRevision + 1,
|
|
configuration: config,
|
|
updatedByUserId: userId,
|
|
updatedAt: new Date(),
|
|
};
|
|
await tx
|
|
.insert(chatGitHubConfigurations)
|
|
.values(values)
|
|
.onConflictDoUpdate({
|
|
target: chatGitHubConfigurations.endpointId,
|
|
set: values,
|
|
});
|
|
// The list controls admission; this flag enables the existing restricted
|
|
// guest execution path only when an explicit guest is present.
|
|
await tx
|
|
.update(chatEndpoints)
|
|
.set({
|
|
allowUnlinkedPeople: config.people.some((p) => p.kind === "guest"),
|
|
sponsorUserId: config.responsibleUserId,
|
|
updatedAt: new Date(),
|
|
})
|
|
.where(eq(chatEndpoints.id, endpointId));
|
|
await syncGitHubBotTools(tx, bot, userId, config.toolsEnabled);
|
|
await logActivity(tx as unknown as Db, {
|
|
companyId: bot.companyId,
|
|
actorType: "user",
|
|
actorId: userId,
|
|
action: "chat_github.configuration_updated",
|
|
entityType: "tool_connection",
|
|
entityId: bot.connectionId,
|
|
details: { endpointId, revision: values.revision },
|
|
});
|
|
});
|
|
return configuration(endpointId, userId);
|
|
}
|
|
async function personalConnections(endpointId: string, userId: string) {
|
|
const bot = await endpoint(endpointId);
|
|
await member(bot.companyId, userId);
|
|
const rows = await db
|
|
.select({ connection: toolConnections, grant: connectionGrants })
|
|
.from(connectionGrants)
|
|
.innerJoin(
|
|
toolConnections,
|
|
and(
|
|
eq(toolConnections.id, connectionGrants.connectionId),
|
|
eq(toolConnections.companyId, bot.companyId),
|
|
),
|
|
)
|
|
.where(
|
|
and(
|
|
eq(connectionGrants.companyId, bot.companyId),
|
|
eq(connectionGrants.kind, "user"),
|
|
eq(connectionGrants.subjectUserId, userId),
|
|
),
|
|
);
|
|
return rows
|
|
.filter(
|
|
({ connection }) =>
|
|
connection.config.sourceTemplateKey === "github" ||
|
|
connection.transportConfig?.sourceTemplateKey === "github",
|
|
)
|
|
.map(({ connection, grant }) => ({
|
|
connectionId: connection.id,
|
|
name: connection.name,
|
|
status: grant.status,
|
|
login: grant.providerTenant?.github?.login ?? null,
|
|
enabled: connection.enabled,
|
|
}));
|
|
}
|
|
async function identity(
|
|
endpointId: string,
|
|
connectionId: string,
|
|
userId: string,
|
|
confirmedGithubUserId?: string,
|
|
) {
|
|
const bot = await endpoint(endpointId);
|
|
await member(bot.companyId, userId);
|
|
if (!bot.providerAccountId)
|
|
throw conflict("Verify the bot App installation first");
|
|
const verified = await toolAccessService(db).verifyPersonalGitHubIdentity(
|
|
bot.companyId,
|
|
connectionId,
|
|
userId,
|
|
);
|
|
if (confirmedGithubUserId === undefined) return verified;
|
|
if (confirmedGithubUserId !== verified.githubUserId)
|
|
throw conflict(
|
|
"The connected GitHub account changed. Check and confirm its identity again.",
|
|
);
|
|
await db.transaction(async (tx) => {
|
|
const [principal] = await tx
|
|
.insert(chatExternalPrincipals)
|
|
.values({
|
|
companyId: bot.companyId,
|
|
provider: "github",
|
|
providerAccountId: bot.providerAccountId!,
|
|
externalId: verified.githubUserId,
|
|
kind: "user",
|
|
handle: verified.login,
|
|
displayName: verified.login,
|
|
})
|
|
.onConflictDoUpdate({
|
|
target: [
|
|
chatExternalPrincipals.companyId,
|
|
chatExternalPrincipals.provider,
|
|
chatExternalPrincipals.providerAccountId,
|
|
chatExternalPrincipals.externalId,
|
|
],
|
|
set: { handle: verified.login, updatedAt: new Date() },
|
|
})
|
|
.returning();
|
|
await tx.execute(
|
|
sql`select pg_advisory_xact_lock(hashtextextended(${`chat-identity:${bot.companyId}:${principal!.id}`}, 0))`,
|
|
);
|
|
const [prior] = await tx
|
|
.select()
|
|
.from(chatIdentityLinks)
|
|
.where(
|
|
and(
|
|
eq(chatIdentityLinks.endpointId, endpointId),
|
|
eq(chatIdentityLinks.principalId, principal!.id),
|
|
),
|
|
)
|
|
.for("update");
|
|
if (prior?.status === "linked" && prior.paperclipUserId !== userId)
|
|
throw conflict(
|
|
"This GitHub account is already linked to another Paperclip member",
|
|
);
|
|
const [grant] = await tx
|
|
.select()
|
|
.from(connectionGrants)
|
|
.where(
|
|
and(
|
|
eq(connectionGrants.companyId, bot.companyId),
|
|
eq(connectionGrants.id, verified.grantId),
|
|
eq(connectionGrants.status, "active"),
|
|
eq(connectionGrants.subjectUserId, userId),
|
|
),
|
|
)
|
|
.for("update");
|
|
if (!grant)
|
|
throw forbidden("Your personal GitHub connection was revoked");
|
|
const values = {
|
|
companyId: bot.companyId,
|
|
endpointId,
|
|
principalId: principal!.id,
|
|
paperclipUserId: userId,
|
|
status: "linked" as const,
|
|
confirmedAt: new Date(),
|
|
revokedAt: null,
|
|
confirmationTokenHash: null,
|
|
expiresAt: null,
|
|
updatedAt: new Date(),
|
|
};
|
|
await tx
|
|
.insert(chatIdentityLinks)
|
|
.values(values)
|
|
.onConflictDoUpdate({
|
|
target: [chatIdentityLinks.endpointId, chatIdentityLinks.principalId],
|
|
set: values,
|
|
});
|
|
await logActivity(tx as unknown as Db, {
|
|
companyId: bot.companyId,
|
|
actorType: "user",
|
|
actorId: userId,
|
|
action: "chat_github.identity_confirmed",
|
|
entityType: "tool_connection",
|
|
entityId: bot.connectionId,
|
|
details: {
|
|
endpointId,
|
|
connectionId,
|
|
githubUserId: verified.githubUserId,
|
|
},
|
|
});
|
|
});
|
|
return verified;
|
|
}
|
|
return {
|
|
verification: async (endpointId: string) => {
|
|
const bot = await endpoint(endpointId);
|
|
const checks: Array<{
|
|
key: string;
|
|
label: string;
|
|
ok: boolean;
|
|
detail: string;
|
|
}> = [];
|
|
checks.push({
|
|
key: "delivery",
|
|
label: "Signed webhook delivery",
|
|
ok: !!bot.setup.webhookVerifiedAt,
|
|
detail: bot.setup.webhookVerifiedAt
|
|
? "GitHub delivered a signed webhook to this instance."
|
|
: "Send or redeliver a ping from your App's webhook settings.",
|
|
});
|
|
const credentials = await githubBotCredentials(
|
|
db,
|
|
bot.companyId,
|
|
endpointId,
|
|
);
|
|
const app = await githubBotRequest<{
|
|
id?: number;
|
|
permissions?: Record<string, string>;
|
|
events?: string[];
|
|
}>(fetchImpl, credentials.appJwt, "/app");
|
|
checks.push({
|
|
key: "app",
|
|
label: "GitHub App identity",
|
|
ok: String(app.id) === bot.botExternalId,
|
|
detail:
|
|
String(app.id) === bot.botExternalId
|
|
? "The vaulted credentials identify this bot's App."
|
|
: "The vaulted credentials identify a different GitHub App.",
|
|
});
|
|
const installation = credentials.credentials.installationId
|
|
? await githubBotRequest<{
|
|
permissions?: Record<string, string>;
|
|
suspended_at?: string | null;
|
|
}>(
|
|
fetchImpl,
|
|
credentials.appJwt,
|
|
`/app/installations/${credentials.credentials.installationId}`,
|
|
)
|
|
: null;
|
|
const permissions = installation?.permissions ?? {};
|
|
const permissionsOk =
|
|
!!installation &&
|
|
!installation.suspended_at &&
|
|
permissions.contents === "read" &&
|
|
permissions.pull_requests === "write" &&
|
|
permissions.checks === "write" &&
|
|
app.events?.includes("pull_request") === true;
|
|
checks.push({
|
|
key: "permissions",
|
|
label: "Review installation permissions",
|
|
ok: permissionsOk,
|
|
detail: permissionsOk
|
|
? "Contents read, Pull requests write, Checks write, and PR events are enabled."
|
|
: "Set Contents to read-only and Checks to write, subscribe to pull_request, and approve the permission upgrade on GitHub.",
|
|
});
|
|
const resources = await db
|
|
.select()
|
|
.from(chatEndpointResources)
|
|
.where(
|
|
and(
|
|
eq(chatEndpointResources.companyId, bot.companyId),
|
|
eq(chatEndpointResources.endpointId, endpointId),
|
|
eq(chatEndpointResources.enabled, true),
|
|
),
|
|
);
|
|
const inaccessible: string[] = [];
|
|
// Ask GitHub to authorize the selected repository IDs now. A cached
|
|
// inventory alone cannot prove access after an installation is changed.
|
|
for (let offset = 0; offset < resources.length; offset += 4) {
|
|
await Promise.all(
|
|
resources.slice(offset, offset + 4).map(async (resource) => {
|
|
const repositoryId = String(
|
|
resource.metadata?.providerRepositoryId ?? "",
|
|
);
|
|
try {
|
|
if (
|
|
!permissionsOk ||
|
|
resource.availability !== "available" ||
|
|
!/^[1-9][0-9]*$/.test(repositoryId) ||
|
|
!Number.isSafeInteger(Number(repositoryId))
|
|
)
|
|
throw new Error("Unavailable repository");
|
|
const issued = await githubBotRequest<{ token?: string }>(
|
|
fetchImpl,
|
|
credentials.appJwt,
|
|
`/app/installations/${credentials.credentials.installationId}/access_tokens`,
|
|
{
|
|
method: "POST",
|
|
body: {
|
|
repository_ids: [Number(repositoryId)],
|
|
permissions: {
|
|
contents: "read",
|
|
metadata: "read",
|
|
issues: "write",
|
|
pull_requests: "write",
|
|
checks: "write",
|
|
},
|
|
},
|
|
},
|
|
);
|
|
if (!issued.token) throw new Error("Missing installation token");
|
|
} catch {
|
|
inaccessible.push(resource.label ?? resource.providerResourceId);
|
|
}
|
|
}),
|
|
);
|
|
}
|
|
checks.push({
|
|
key: "repositories",
|
|
label: "Enabled repositories",
|
|
ok: resources.length > 0 && inaccessible.length === 0,
|
|
detail: inaccessible.length
|
|
? `Restore installation access and refresh: ${inaccessible.join(", ")}.`
|
|
: resources.length
|
|
? `GitHub confirmed review access to all ${resources.length} enabled repositories.`
|
|
: "Enable at least one repository from the App installation.",
|
|
});
|
|
const [agent] = await db
|
|
.select()
|
|
.from(agents)
|
|
.where(
|
|
and(
|
|
eq(agents.companyId, bot.companyId),
|
|
eq(agents.id, bot.assignedAgentId),
|
|
),
|
|
);
|
|
checks.push({
|
|
key: "runtime",
|
|
label: "Agent runtime supports bot tools",
|
|
ok:
|
|
!!agent &&
|
|
["paperclip_runner", "codex_local"].includes(agent.adapterType),
|
|
detail:
|
|
"Use Paperclip Runner or Codex with managed MCP tools. Low-trust execution also requires a valid scoped boundary and isolated sandbox; the test task proves runtime execution.",
|
|
});
|
|
const [savedConfig] = await db
|
|
.select()
|
|
.from(chatGitHubConfigurations)
|
|
.where(eq(chatGitHubConfigurations.endpointId, endpointId));
|
|
if (
|
|
agent &&
|
|
(agent.permissions.trustPreset === "low_trust_review" ||
|
|
savedConfig?.configuration.people.some(
|
|
(person) => person.kind === "guest",
|
|
))
|
|
) {
|
|
const settings = instanceSettingsService(db);
|
|
const experimental = await settings.getExperimental();
|
|
const environments = environmentService(db);
|
|
const local = await environments.ensureLocalEnvironment(bot.companyId);
|
|
const managed = experimental.enableManagedSandboxOnly
|
|
? await environments.findManagedSandboxEnvironment(bot.companyId)
|
|
: null;
|
|
const selected = resolveExecutionWorkspaceEnvironmentId({
|
|
agentDefaultEnvironmentId: agent.defaultEnvironmentId,
|
|
instanceDefaultEnvironmentId:
|
|
(await settings.get()).defaultEnvironmentId ?? null,
|
|
localDefaultEnvironmentId: local.id,
|
|
managedSandboxOnly: experimental.enableManagedSandboxOnly,
|
|
managedSandboxEnvironmentId: managed?.id,
|
|
});
|
|
const environment = await environments.getById(selected.environmentId);
|
|
const owners = environment
|
|
? await environments.listBoundCompanyIds(environment.id)
|
|
: [];
|
|
const sandboxOk =
|
|
experimental.enableIsolatedWorkspaces &&
|
|
environment?.driver === "sandbox" &&
|
|
environment.status === "active" &&
|
|
(!owners.length || owners.includes(bot.companyId));
|
|
checks.push({
|
|
key: "isolation",
|
|
label: "Low-trust and guest execution",
|
|
ok: !!sandboxOk,
|
|
detail: sandboxOk
|
|
? "An active sandbox environment is selected. Each task receives its own restricted trust boundary."
|
|
: "Enable isolated workspaces and select an active sandbox environment for this agent before running low-trust or guest tasks.",
|
|
});
|
|
}
|
|
const entries = await db
|
|
.select()
|
|
.from(toolCatalogEntries)
|
|
.where(
|
|
and(
|
|
eq(toolCatalogEntries.companyId, bot.companyId),
|
|
eq(toolCatalogEntries.connectionId, bot.connectionId),
|
|
eq(toolCatalogEntries.status, "active"),
|
|
),
|
|
);
|
|
const requiredTools = GITHUB_BOT_TOOLS.filter(
|
|
(tool) => tool.name !== "formal_review",
|
|
);
|
|
const denied: string[] = requiredTools
|
|
.filter(
|
|
(tool) =>
|
|
!entries.some(
|
|
(entry) =>
|
|
entry.toolName === tool.name &&
|
|
entry.name === `github_bot:${tool.name}`,
|
|
),
|
|
)
|
|
.map((tool) => tool.title);
|
|
let toolsOk = denied.length === 0;
|
|
for (const entry of entries) {
|
|
const decision = await toolAccessPolicyService(db).decide({
|
|
companyId: bot.companyId,
|
|
actor: {
|
|
actorType: "agent",
|
|
actorId: bot.assignedAgentId,
|
|
agentId: bot.assignedAgentId,
|
|
},
|
|
runContext: {},
|
|
request: {
|
|
toolName: `github-bot.${bot.id}:${entry.toolName}`,
|
|
applicationId: credentials.connection.applicationId,
|
|
applicationKey: "github-chat",
|
|
connectionId: bot.connectionId,
|
|
catalogEntryId: entry.id,
|
|
providerType: "paperclip_github_chat",
|
|
upstreamToolName: entry.toolName,
|
|
riskLevel: entry.riskLevel,
|
|
arguments: {},
|
|
sideEffecting: entry.riskLevel !== "read",
|
|
},
|
|
});
|
|
if (
|
|
entry.toolName !== "formal_review" &&
|
|
!decision.allowed &&
|
|
decision.decision !== "require_approval"
|
|
) {
|
|
toolsOk = false;
|
|
denied.push(entry.title ?? entry.toolName);
|
|
}
|
|
}
|
|
checks.push({
|
|
key: "tools",
|
|
label: "Assigned agent's effective GitHub tools",
|
|
ok: toolsOk,
|
|
detail: toolsOk
|
|
? "The bot App's task-scoped tools are assigned. Each run and publication rechecks access."
|
|
: denied.length
|
|
? `Repair tool policy for: ${denied.join(", ")}.`
|
|
: "Assign the bot's GitHub tools to this agent, then verify again.",
|
|
});
|
|
return { checks, ready: checks.every((check) => check.ok) };
|
|
},
|
|
configuration,
|
|
saveConfiguration,
|
|
personalConnections,
|
|
identity,
|
|
lookupPerson: async (login: string) => {
|
|
if (!/^[a-zA-Z0-9][a-zA-Z0-9-]{0,38}(?:\[bot\])?$/.test(login))
|
|
throw badRequest("Enter a GitHub username");
|
|
const user = await githubBotRequest<{
|
|
id?: number;
|
|
login?: string;
|
|
type?: string;
|
|
}>(fetchImpl, null, `/users/${encodeURIComponent(login)}`);
|
|
if (
|
|
!Number.isSafeInteger(user.id) ||
|
|
!user.id ||
|
|
!["User", "Bot"].includes(user.type ?? "") ||
|
|
!user.login
|
|
)
|
|
throw badRequest("Choose a GitHub person or bot account");
|
|
return { githubUserId: String(user.id), login: user.login };
|
|
},
|
|
reviews: async (endpointId: string) => {
|
|
const bot = await endpoint(endpointId);
|
|
return db
|
|
.select()
|
|
.from(chatGitHubReviews)
|
|
.where(
|
|
and(
|
|
eq(chatGitHubReviews.companyId, bot.companyId),
|
|
eq(chatGitHubReviews.endpointId, endpointId),
|
|
),
|
|
)
|
|
.orderBy(desc(chatGitHubReviews.createdAt))
|
|
.limit(100);
|
|
},
|
|
};
|
|
}
|