mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 19:08:33 +01:00
## Thinking Path > - Paperclip manages work for AI agents. > - Personal MCP connections should remain enabled while an idle tenant sleeps. > - Unfinished OAuth, transfer and delivery work must retain its owner and deadline. > - Cloud can receive bounded metadata and incoming work while the tenant remains the company-scoped authorizer. > - Current identity, revision and delivery acknowledgments establish when ownership has transferred. > - This change preserves useful wake, retries and revocation while making settled ownership inspectable without writes. ## Linked Issues or Issue Description Refs: #19377 and #19750. Hosted companion: [paperclip-cloud#1217](https://github.com/paperclipai/paperclip-cloud/pull/1217). **What happened?** Enabled personal MCP grants and subscriptions could keep an otherwise idle tenant awake. Ignoring those records would lose discovery, authorization, delivery and revocation obligations. **Expected behavior** Unconsumed authorization codes, device requests, file handoffs and delivery work retain their original deadlines. Settled connections remain enabled and become quiet after the current external owner acknowledges responsibility. Incoming useful work resumes normal authorization and delivery; revocation still takes effect for the current company. **Steps to reproduce** Complete normal PKCE/device consent and company selection, synchronize client/device and revocation state, retain the connection while idle, then exercise useful tools/events and revocation. Sleep eligibility requires current incoming/deadline ownership throughout. ## What Changed - Add bounded signed client/device metadata and revocation synchronization with exact revision, identity and ACK checks, startup recovery and finite legacy-device cutover. - Preserve company selection, authorization and operation identity. Register grant work before its INSERT in the same transaction; retain rollback, expiry and retry behavior. - Require current managed identity/resource before hosted publication. Receipt-cleared re-enable must obtain a fresh source ACK before device creation. - Reuse read-only settings and inspection budgets; connect MCP owners to normal startup, drain and shutdown. - Bound metadata pages and the actual signed request body while preserving the default limits of other operations. - Generate migration 0440 after the merged Legacy migration. Preserve all 438 existing executable migrations and the journal prefix; retain the normal five newest snapshots. - Preserve the merged transaction-owner forwarding and regression coverage from #19750 through normal ancestry integration. ## Verification - Current own Shared/SDK, database, eval-kernel and Runner builds passed, together with all seven normal application TypeScript programs. Missing generated package exports/workspace links were restored through normal setup; the original setup failures were retained. No source, compiler option, test assertion or timeout was weakened. - Normal migration generation changed only the five intended MCP tables; its SQL is byte-identical to the reviewed MCP delta. Fresh reference databases and both retained master/Muse histories upgraded through 0440, preserving historical hashes, row fields, schema and idempotence. Direct assertions cover the Legacy null default and MCP null/zero defaults. Two selected history cases passed; the other 21 database cases were unselected. - All six current MCP lifecycle cases passed with zero skips: normal PKCE approval intent, ACK recovery after outage, mutation during publication, disable/re-enable with original expiry, company-deletion rollback/commit and key rotation. - All 81 checks in five current whole files passed with zero skips: OpenAPI 34, read-only settings 2, diagnostic catalog 25, PostgreSQL diagnostics 7 and dependency scheduling 13. PostgreSQL fixtures ran normal migrations before test imports. - Earlier canonical proof at App `cd1c8c6` / Cloud `9f67531` includes real 60-second rate and three 15-second quiet windows, useful work and three revokes. Later paired proof at App `43af514` / Cloud `914eb0f` plus its reviewed candidate includes normal DCR, PostgreSQL metadata, a 144,017-byte signed publication, actual ACK, cap/default-413 controls and a real 15-second quiet window. The relevant producer/signing/wire inputs remain byte-identical in this integration; shared changes are qualified above. These remain source-scoped observations, not a fresh full canonical run on the integrated tree. - All known test owners, process groups and OS sockets closed; an independent final PostgreSQL audit found no remaining test sessions. One dependency-test trace recorded 46 opens and 45 close events. Its cause is unknown; this is not claimed as proof of graceful closure. - Fresh exact-head remote checks passed: 59 successful and 4 skipped contexts, with a complete current 5/5 Greptile review and all seven review threads resolved. Targeted local checks do not constitute a new whole-repository test run. ## Risks App and Cloud must agree on identity, revision, namespace, deadlines and revocation. Partial rollout, unavailable authority or missing ACK must retain awake debt. Shared startup/shutdown and settings changed since the earlier canonical profile, so historical observations carry only within their stated source scope. No deployed Railway/Neon suspension, Cloud alarm, savings or complete hosted Dot/Muse acceptance is claimed. ## Model Used OpenAI `gpt-6.1-sol` produced code and verification, with a Codex coordinator reviewing and integrating the changes. The coordinator's exact runtime model ID and context-window sizes were not exposed. ## 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> Co-authored-by: Codex <noreply@openai.com>
163 lines
8.7 KiB
TypeScript
163 lines
8.7 KiB
TypeScript
import { mcpCompanyDeletion } from "./public-mcp/company-deletion.js";
|
|
import { notifyStatusCardEvaluation } from "./status-card-notifications.js";
|
|
import { notifyExternalObjectRefresh } from "./external-object-refresh-notifications.js";
|
|
import { notifyIssueRecovery } from "./issue-recovery-notifications.js";
|
|
import { notifyUnsafeWorkspaceExportRecovery } from "./unsafe-workspace-export-notifications.js";
|
|
import { notifyCancelledWorkspacePreservation } from "./cancelled-workspace-preservation-notifications.js";
|
|
import { notifyInstructionCollection } from "./instruction-collection-notifications.js";
|
|
import { notifyDirectoryCleanup } from "./directory-cleanup-notifications.js";
|
|
import { notifyInstructionCommit } from "./instruction-commit-notifications.js";
|
|
import { notifyScheduledRetryCancellation } from "./scheduled-retry-cancellation-notifications.js";
|
|
import { notifyChatCompanyConfiguration } from "./chat-channels/configuration-work-notifications.js";
|
|
import { chatCompanyDeletion } from "./chat-channels/company-deletion.js";
|
|
import { notifyToolConnectionHealth } from "./tool-connection-health-notifications.js";
|
|
import { notifyCompanyRetentionWork } from "./retention-work-notifications.js";
|
|
import { notifyToolReviewChange } from "./tool-review-work-notifications.js";
|
|
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
|
|
import { agentObservabilityService } from "./agent-observability.js";
|
|
import { withAccountHomeSecretMutationLock } from "@paperclipai/adapter-codex-local/server";
|
|
import type { Db } from "@paperclipai/db";
|
|
import { eq, inArray } from "drizzle-orm";
|
|
import { createAgentLifecycle, processAgentLifecycle } from "./agent-lifecycle.js";
|
|
import { requestRestorePointDeletion } from "./git-restore-point-ledger.js";
|
|
import { agentLifecycleCompanyDeletion } from "../modules/agent-lifecycle/company-deletion.js";
|
|
import { executionAdmissionCompanyDeletion } from "../modules/execution-admission/company-deletion.js";
|
|
import {
|
|
companies,
|
|
agents,
|
|
companyLogos,
|
|
assets,
|
|
agentApiKeys,
|
|
agentRuntimeState,
|
|
agentTaskSessions,
|
|
agentWakeupRequests,
|
|
issues,
|
|
issueComments,
|
|
projects,
|
|
executionWorkspaces,
|
|
goals,
|
|
heartbeatRuns,
|
|
runIdentityContexts,
|
|
heartbeatRunEvents,
|
|
costEvents,
|
|
decisionInvocations,
|
|
financeEvents,
|
|
budgetPolicies,
|
|
budgetIncidents,
|
|
issueReadStates,
|
|
approvalComments,
|
|
approvals,
|
|
activityLog,
|
|
companySecrets,
|
|
joinRequests,
|
|
invites,
|
|
principalPermissionGrants,
|
|
companyMemberships,
|
|
companySkills,
|
|
cases,
|
|
documents,
|
|
routineRuns,
|
|
routineTriggers,
|
|
routineRevisions,
|
|
routines,
|
|
} from "@paperclipai/db";
|
|
|
|
export async function deleteCompany(db: Db, id: string) {
|
|
const lifecycle = createAgentLifecycle(db);
|
|
const companyAgents = await db.select({ id: agents.id }).from(agents).where(eq(agents.companyId, id));
|
|
for (const agent of companyAgents) {
|
|
await lifecycle.terminateAgent(agent.id);
|
|
await processAgentLifecycle(db, agent.id);
|
|
}
|
|
return withAccountHomeSecretMutationLock(undefined, id, () => db.transaction(async (tx) => {
|
|
// Exclude accounting writers before taking child locks. KEY SHARE must
|
|
// remain compatible: native writers can already hold a child row while
|
|
// saving a company-scoped result. FOR UPDATE would deadlock that save.
|
|
const [existing] = await tx.select({ id: companies.id }).from(companies)
|
|
.where(eq(companies.id, id)).for("no key update");
|
|
if (!existing) return null;
|
|
await mcpCompanyDeletion.deleteCompanyData(tx, id);
|
|
await notifyExternalObjectRefresh(tx, id);
|
|
await notifyIssueRecovery(tx, { companyId: id });
|
|
await notifyChatCompanyConfiguration(tx, id);
|
|
await chatCompanyDeletion.deleteCompanyData(tx, id);
|
|
await notifyDeliveryWork(tx, DELIVERY_QUEUES.skillSourceSync);
|
|
await notifyDeliveryWork(tx, DELIVERY_QUEUES.skillPackages);
|
|
await notifyDeliveryWork(tx, DELIVERY_QUEUES.routineSchedules);
|
|
await notifyDeliveryWork(tx, DELIVERY_QUEUES.issueMonitors);
|
|
await notifyStatusCardEvaluation(tx, id);
|
|
await notifyDeliveryWork(tx, DELIVERY_QUEUES.secretProposalExpiry, id);
|
|
await notifyToolReviewChange(tx, id);
|
|
await agentObservabilityService(tx as unknown as Db).removeForCompanyDeletion(id);
|
|
// Finance can reference costs and both can reference runs. Incidents
|
|
// reference policies and approvals; delete these dependents first.
|
|
await tx.delete(financeEvents).where(eq(financeEvents.companyId, id));
|
|
await tx.delete(decisionInvocations).where(eq(decisionInvocations.companyId, id));
|
|
await tx.delete(costEvents).where(eq(costEvents.companyId, id));
|
|
await tx.delete(budgetIncidents).where(eq(budgetIncidents.companyId, id));
|
|
await tx.delete(budgetPolicies).where(eq(budgetPolicies.companyId, id));
|
|
// Cases retain task and agent references. Their dependent handoffs and
|
|
// access sources cascade here before those task/agent records are removed.
|
|
await tx.delete(cases).where(eq(cases.companyId, id));
|
|
// Delete from child tables in dependency order
|
|
const companyRunIds = await tx
|
|
.select({ id: heartbeatRuns.id })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.companyId, id));
|
|
|
|
await tx.delete(heartbeatRunEvents).where(eq(heartbeatRunEvents.companyId, id));
|
|
if (companyRunIds.length > 0) {
|
|
await tx
|
|
.delete(heartbeatRunEvents)
|
|
.where(inArray(heartbeatRunEvents.runId, companyRunIds.map((run) => run.id)));
|
|
}
|
|
await tx.delete(agentTaskSessions).where(eq(agentTaskSessions.companyId, id));
|
|
await tx.delete(activityLog).where(eq(activityLog.companyId, id));
|
|
await tx.delete(runIdentityContexts).where(eq(runIdentityContexts.companyId, id));
|
|
await notifyScheduledRetryCancellation(tx, { companyId: id });
|
|
await notifyInstructionCommit(tx, { companyId: id });
|
|
await notifyDirectoryCleanup(tx, { companyId: id });
|
|
await notifyInstructionCollection(tx, { companyId: id });
|
|
await notifyCancelledWorkspacePreservation(tx, { companyId: id });
|
|
await notifyUnsafeWorkspaceExportRecovery(tx, { companyId: id });
|
|
await executionAdmissionCompanyDeletion.deleteCompanyData(tx, id);
|
|
await tx.delete(heartbeatRuns).where(eq(heartbeatRuns.companyId, id));
|
|
await tx.delete(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, id));
|
|
await tx.delete(agentApiKeys).where(eq(agentApiKeys.companyId, id));
|
|
await tx.delete(agentRuntimeState).where(eq(agentRuntimeState.companyId, id));
|
|
// Match receipt completion and comment deletion: task before comment.
|
|
await tx.select({ id: issues.id }).from(issues)
|
|
.where(eq(issues.companyId, id)).orderBy(issues.id).for("no key update");
|
|
await tx.delete(issueComments).where(eq(issueComments.companyId, id));
|
|
await tx.delete(approvalComments).where(eq(approvalComments.companyId, id));
|
|
await notifyCompanyRetentionWork(tx, id);
|
|
await tx.delete(approvals).where(eq(approvals.companyId, id));
|
|
await tx.delete(companySecrets).where(eq(companySecrets.companyId, id));
|
|
await tx.delete(joinRequests).where(eq(joinRequests.companyId, id));
|
|
await tx.delete(invites).where(eq(invites.companyId, id));
|
|
await tx.delete(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, id));
|
|
await tx.delete(companyMemberships).where(eq(companyMemberships.companyId, id));
|
|
await tx.delete(companySkills).where(eq(companySkills.companyId, id));
|
|
await tx.delete(routineRuns).where(eq(routineRuns.companyId, id));
|
|
await tx.delete(routineTriggers).where(eq(routineTriggers.companyId, id));
|
|
await tx.delete(routineRevisions).where(eq(routineRevisions.companyId, id));
|
|
await tx.delete(routines).where(eq(routines.companyId, id));
|
|
await tx.delete(issueReadStates).where(eq(issueReadStates.companyId, id));
|
|
await tx.delete(documents).where(eq(documents.companyId, id));
|
|
await tx.delete(issues).where(eq(issues.companyId, id));
|
|
await tx.delete(companyLogos).where(eq(companyLogos.companyId, id));
|
|
await tx.delete(assets).where(eq(assets.companyId, id));
|
|
await tx.delete(goals).where(eq(goals.companyId, id));
|
|
await requestRestorePointDeletion(tx, { companyId: id });
|
|
await tx.delete(executionWorkspaces).where(eq(executionWorkspaces.companyId, id));
|
|
await tx.delete(projects).where(eq(projects.companyId, id));
|
|
await agentLifecycleCompanyDeletion.deleteCompanyData(tx, id);
|
|
await notifyToolConnectionHealth(tx, id);
|
|
const rows = await tx
|
|
.delete(companies)
|
|
.where(eq(companies.id, id))
|
|
.returning();
|
|
return rows[0] ?? null;
|
|
}));
|
|
}
|