mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-29 21:07:40 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Connected chats show safe notices when a run starts, waits, finishes, or fails. > - A recurring scan projected these notices even when no eligible work existed. > - Eligibility depends on committed run state, conversation lineage, and current authority. > - Existing database rows can reconstruct that work after restart. > - This PR wakes a scoped worker from those writes and removes lifecycle polling. > - Native progress events keep their separate existing owner until the next migration. ## Linked Issues or Issue Description **What happened?** The chat maintenance timer repeatedly scanned run lifecycle state. Empty and settled instances still queried the database. A run-status event alone cannot replace the scan: prompt receipts, continuation receipts, identity changes, and restored authority can make a run eligible later. **What did you expect?** Committed changes wake projection. Startup reconstructs eligible work. A completed pass stops until another relevant change arrives. Failed work retains recovery without scanning settled history forever. **Steps to reproduce** Configure an automatic chat endpoint. Finish its work, or leave it unused. Observe recurring lifecycle projection queries from the chat maintenance callback. Stacked on #17592. Related foundation: #15625. This PR owns lifecycle milestones only. ## What Changed - Preserve upstream coalesced Cloud membership writes together with locked membership restoration and its committed chat notification. - Signal milestone eligibility from the real Slack account-link transaction. - Register the lifecycle worker with the existing delivery coordinator. Remove lifecycle projection from the periodic chat callback. Keep native progress in a separately named lane and preserve the explicit combined API. - Reconstruct company/issue scopes from the existing selector. Drain bounded batches with company fairness. Retry failures, retain writes through drain/resume, and disarm settled work. - Signal from supported run, presentation, interaction, receipt, lineage, conversation, recovery, and authority writers. Preserve their transaction ownership, including nested savepoints and uncertain settlement. No new table is added. - Preserve provider authorization, authored-final suppression, responsible-user continuity, deduplication, the 24-hour selection window, and raw-output restrictions. Keep provider interpretation in its owner. - Preserve PostgreSQL timestamp precision in lifecycle pagination. Rejected submillisecond candidates must not repeat the same page and starve later notices. - Document producer coverage and alternate-writer dispositions in `doc/plans/2026-10-25-chat-run-milestone-sleep-audit.md`. ## Verification Published head: `1d056f68c5b1005933b9e12de8745bf1c4cbeeca`, targeting master after #17592 merged at `7d75ae0569e41786640cf09647ae8849411d2f22`. A normal merge integrates the actual landed parent. The entire 77-path milestone patch is binary-identical to the locally verified preparation across that ancestry reconciliation; both unrelated master paths are preserved. The four earlier producer/test integration conflicts retain scoped milestone and voice notices, current onboarding completion admission, and expanded identity query/read-scope coverage. - **330 distinct selected cases pass on the verified unchanged patch:** 305 across 14 complete suites (all five milestone worker suites, run identity, board claim, Cloud provisioning, auth session routes, Cloud actor authentication, stale-lock recovery, GitHub credentials, project Git authorization, and app admission wiring), plus 25 selected real chat producer cases. The remaining 1,590 chat integration cases were skipped, not passed. - The real producer cases cover saved milestone discovery, GitHub and Slack identity changes, account-link rollback/reconfirmation, ordinary ingress reactivation, post-close action/delivery receipt settlement, all ten authority-restoration paths including Cloud synchronization, and changed native review metadata. - Worker coverage verifies outer commit, rollback, uncertain-write recovery, restart, bounded batching/fairness, timestamp precision, retries, drain/resume, and settled SQL quiet. Authorization and existing publication deduplication remain with their owning services. - Server production typechecking, build, and module-boundary checks pass. The tests above were executed separately. Production typechecking excludes `src/__tests__` and does not replace those runs. Each database owner uses its own newly created and app-migrated PostgreSQL fixture. - [Current-parent acceptance and preserved failure ledger](https://github.com/paperclipai/paperclip/blob/1d056f68c5b1005933b9e12de8745bf1c4cbeeca/doc/plans/2026-10-25-chat-run-milestone-sleep-audit.md#current-parent-integration-and-acceptance-october-28) records commands, counts, producer scope, conflict dispositions, and limits. Earlier combined-stack counts and failures keep their original revision scope; local acceptance does not erase old CI failures. - No new migration, queue table, dependency, workflow, or shared scheduler contract is introduced. Parent migration 0397, bounded consent recovery, voice cleanup/retention repairs, and runner checkpoint restoration remain present. - **Exact-head Greptile is 5/5 and all 55 current checks are clean.** No Ponytail review is present, which is an explicitly authorized nonblocker; no failing review is waived. Older reviews and parent checks are not current passes. Actual failing Ponytail findings must be fixed; an absent/stopped/paused turn without a verdict is an authorized nonblocker. Active unfinished Ponytail uses its original request/start timer, with a 25-minute monitor cutoff respecting the user's 30-minute maximum. - No complete local repository matrix, live provider tenant, external alarm, physical host/database suspension, or fleet savings claim is made. Native progress remains a separate following slice. ## Risks - A future eligibility writer must notify the existing projection boundary. Independent SQL writers or another active server process are outside this process-local signal contract. - Authority and lineage remain sensitive. The worker uses the existing selectors and publication policy; it does not grant execution or disclosure authority. - Native progress and other publication maintenance still have recurring work. This PR removes one reason, not the entire chat maintenance timer. - Worker quiet does not prove database suspension, host sleep, or external alarm coverage. Cloud sleep blockers remain unchanged. - Merge eligibility requires passing current-head CI and Greptile 5/5 after this actual-master reconciliation. Subsequent stack slices retain their own gates. ## Model Used OpenAI Codex, GPT-6 family. The exact serving model ID and context-window size are not exposed. Used repository inspection, reasoning, shell execution, PostgreSQL tests, browser E2Es and GitHub tools. ## 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 available in this session) - [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 the documented focused 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>
706 lines
27 KiB
TypeScript
706 lines
27 KiB
TypeScript
import type { ConnectionManagementContext } from "./connection-management.js";
|
|
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 { HttpError, badRequest, conflict, forbidden, notFound, unprocessable } from "../errors.js";
|
|
import { toolAccessService } from "./tool-access.js";
|
|
import { logActivity } from "./activity-log.js";
|
|
import { notifyChatRunMilestones } from "./chat-run-milestone-notifications.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,
|
|
managementContext?: ConnectionManagementContext,
|
|
) {
|
|
await managementContext?.reauthorize();
|
|
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) => {
|
|
const [currentEndpoint] = await tx
|
|
.select({ allowUnlinkedPeople: chatEndpoints.allowUnlinkedPeople, sponsorUserId: chatEndpoints.sponsorUserId })
|
|
.from(chatEndpoints)
|
|
.where(eq(chatEndpoints.id, endpointId))
|
|
.for("update");
|
|
if (!currentEndpoint) throw notFound("GitHub bot not found");
|
|
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 allowUnlinkedPeople = config.people.some((p) => p.kind === "guest");
|
|
if ((!currentEndpoint.allowUnlinkedPeople && allowUnlinkedPeople) ||
|
|
(allowUnlinkedPeople && currentEndpoint.sponsorUserId !== config.responsibleUserId)) {
|
|
await notifyChatRunMilestones(tx, { companyId: bot.companyId });
|
|
}
|
|
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,
|
|
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,
|
|
...(managementContext?.audit ?? { actorType: "user" as const, 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 linkObservedIdentity(endpointId, userId, verified);
|
|
return verified;
|
|
}
|
|
async function linkObservedIdentity(endpointId: string, userId: string, verified: { githubUserId: string; login: string; avatarUrl?: string | null; grantId?: string; connectionId?: string }) {
|
|
const bot = await endpoint(endpointId);
|
|
await member(bot.companyId, userId);
|
|
if (!bot.providerAccountId) throw conflict("Verify the App installation first");
|
|
await db.transaction(async (tx) => {
|
|
const [membership] = await tx.select().from(companyMemberships).where(and(eq(companyMemberships.companyId, bot.companyId), eq(companyMemberships.principalType, "user"), eq(companyMemberships.principalId, userId))).for("update");
|
|
if (!membership || membership.status !== "active" || membership.membershipRole === "viewer") throw forbidden("An active company manager is required");
|
|
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",
|
|
);
|
|
if (verified.grantId) {
|
|
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(),
|
|
};
|
|
if (prior?.status !== "linked") {
|
|
await notifyChatRunMilestones(tx, { companyId: bot.companyId });
|
|
}
|
|
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: verified.connectionId ?? bot.connectionId,
|
|
githubUserId: verified.githubUserId,
|
|
},
|
|
});
|
|
});
|
|
}
|
|
return {
|
|
linkObservedIdentity,
|
|
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.
|
|
const verifiable = resources.filter((resource) => {
|
|
const repositoryId = String(resource.metadata?.providerRepositoryId ?? "");
|
|
if (
|
|
!permissionsOk ||
|
|
resource.availability !== "available" ||
|
|
!/^[1-9][0-9]*$/.test(repositoryId) ||
|
|
!Number.isSafeInteger(Number(repositoryId))
|
|
) {
|
|
inaccessible.push(resource.label ?? resource.providerResourceId);
|
|
return false;
|
|
}
|
|
return true;
|
|
});
|
|
// GitHub authorizes up to 500 explicit IDs in one scoped token request.
|
|
// Keep these tokens inside verification; task credentials remain scoped
|
|
// separately. Never omit repository_ids, which would request all access.
|
|
for (let offset = 0; offset < verifiable.length; offset += 500) {
|
|
const batch = verifiable.slice(offset, offset + 500);
|
|
try {
|
|
const issued = await githubBotRequest<{ token?: string }>(
|
|
fetchImpl,
|
|
credentials.appJwt,
|
|
`/app/installations/${credentials.credentials.installationId}/access_tokens`,
|
|
{
|
|
method: "POST",
|
|
body: {
|
|
repository_ids: batch.map((resource) =>
|
|
Number(resource.metadata!.providerRepositoryId),
|
|
),
|
|
permissions: {
|
|
contents: "read",
|
|
metadata: "read",
|
|
issues: "write",
|
|
pull_requests: "write",
|
|
checks: "write",
|
|
},
|
|
},
|
|
},
|
|
);
|
|
if (!issued.token) throw new Error("Missing installation token");
|
|
} catch {
|
|
// A rejected batch is unverified; do not activate from cached access.
|
|
inaccessible.push(
|
|
...batch.map((resource) => 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), connectionReady: checks.filter(check => !["runtime", "isolation"].includes(check.key)).every(check => check.ok) };
|
|
},
|
|
configuration,
|
|
saveConfiguration,
|
|
personalConnections,
|
|
identity,
|
|
lookupPerson: async (endpointId: string, login: string) => {
|
|
if (!/^[a-zA-Z0-9][a-zA-Z0-9-]{0,38}(?:\[bot\])?$/.test(login))
|
|
throw badRequest("Enter a GitHub username");
|
|
const bot = await endpoint(endpointId);
|
|
const material = await githubBotCredentials(db, bot.companyId, endpointId);
|
|
if (
|
|
!material.connection.enabled ||
|
|
material.connection.status !== "active" ||
|
|
!["active", "verifying"].includes(material.endpoint.status)
|
|
)
|
|
throw conflict("GitHub bot connection is not active");
|
|
const installationId = material.credentials.installationId;
|
|
if (!installationId || !/^[1-9][0-9]*$/.test(installationId))
|
|
throw conflict("Verify the GitHub App installation before looking up people");
|
|
let lookingUpPerson = false;
|
|
try {
|
|
const issued = await githubBotRequest<{ token?: string }>(
|
|
fetchImpl,
|
|
material.appJwt,
|
|
`/app/installations/${installationId}/access_tokens`,
|
|
{ method: "POST", body: { permissions: { metadata: "read" } } },
|
|
);
|
|
if (!issued.token)
|
|
throw unprocessable("GitHub did not issue an installation token. Reconnect the bot and try again.");
|
|
lookingUpPerson = true;
|
|
const user = await githubBotRequest<{
|
|
id?: number;
|
|
login?: string;
|
|
type?: string;
|
|
}>(fetchImpl, issued.token, `/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 };
|
|
} catch (error) {
|
|
if (!(error instanceof HttpError)) throw error;
|
|
const details = error.details as { code?: string; providerStatus?: number } | undefined;
|
|
if (details?.code === "github_bot_rate_limited")
|
|
throw unprocessable("GitHub's rate limit was reached. Wait and try the lookup again.", details);
|
|
if (details?.providerStatus === 404 && lookingUpPerson)
|
|
throw badRequest("GitHub could not find this account. Check the username and the bot's access to the account.", details);
|
|
if (details?.providerStatus === 401 || details?.providerStatus === 404)
|
|
throw unprocessable("GitHub could not authenticate this bot installation. Reconnect the bot and try again.", details);
|
|
if (details?.providerStatus === 403)
|
|
throw unprocessable("GitHub denied this bot installation access. Check its installation on GitHub and try again.", details);
|
|
throw error;
|
|
}
|
|
},
|
|
review: async (endpointId: string, reviewId: string) => {
|
|
const bot = await endpoint(endpointId);
|
|
const [review] = await db.select().from(chatGitHubReviews).where(and(
|
|
eq(chatGitHubReviews.companyId, bot.companyId),
|
|
eq(chatGitHubReviews.endpointId, endpointId),
|
|
eq(chatGitHubReviews.id, reviewId),
|
|
));
|
|
if (!review) throw notFound("This review was not found in this connection");
|
|
return review;
|
|
},
|
|
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);
|
|
},
|
|
};
|
|
}
|