mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-31 14:16:39 +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>
359 lines
16 KiB
TypeScript
359 lines
16 KiB
TypeScript
import { notifyChatConnectionHealth } from "./connection-health-notifications.js";
|
|
import type { ConnectionManagementContext } from "../connection-management.js";
|
|
import type { EndpointRow, DbOrTransaction } from "./runtime-types.js";
|
|
|
|
import { notifyChatEndpointWork } from "../chat-work-notifications.js";
|
|
|
|
import { chatCredentialMutationLease } from "../chat-credential-mutation-lease.js";
|
|
|
|
import { githubChatManagementService } from "../chat-github-management.js";
|
|
|
|
import {
|
|
and,
|
|
asc,
|
|
desc,
|
|
eq,
|
|
gte,
|
|
inArray,
|
|
isNotNull,
|
|
or,
|
|
sql,
|
|
} from "drizzle-orm";
|
|
|
|
import type { Db } from "@paperclipai/db";
|
|
|
|
import {
|
|
chatActions,
|
|
chatConversations,
|
|
chatDeliveries,
|
|
chatEndpoints,
|
|
chatIdentityLinks,
|
|
chatMessageLinks,
|
|
chatPublications,
|
|
heartbeatRuns,
|
|
issueComments,
|
|
toolConnections,
|
|
} from "@paperclipai/db";
|
|
import type {
|
|
ChatEndpoint,
|
|
ChatEndpointSetupState,
|
|
} from "@paperclipai/shared";
|
|
|
|
import {
|
|
conflict,
|
|
forbidden,
|
|
notFound,
|
|
} from "../../errors.js";
|
|
|
|
import {
|
|
logActivity,
|
|
} from "../activity-log.js";
|
|
|
|
import {
|
|
githubRunReplyState,
|
|
} from "../chat-run-publications.js";
|
|
|
|
import type { EndpointRecord } from "./runtime-types.js";
|
|
|
|
type SetupProbesOptions = {
|
|
endpointRecord: (endpointId: string) => Promise<EndpointRecord | null>;
|
|
withCredentialMutationLease: ReturnType<typeof chatCredentialMutationLease>;
|
|
fetchImpl: typeof fetch;
|
|
findAuthorizedIdentityLink: (endpoint: EndpointRow, userId: string) => Promise<{ id: string } | null>;
|
|
runtimeGeneration: (setup: ChatEndpointSetupState) => number;
|
|
lockCurrentPrincipalAuthorization: (tx: DbOrTransaction, endpoint: EndpointRow, principalId: string) => Promise<{ allowed: boolean }>;
|
|
get: (endpointId: string) => Promise<ChatEndpoint>;
|
|
setupTestActivationBarrier?: () => Promise<void>;
|
|
};
|
|
|
|
export function createSetupProbes(db: Db, options: SetupProbesOptions) {
|
|
const { endpointRecord, withCredentialMutationLease, fetchImpl, findAuthorizedIdentityLink, runtimeGeneration, lockCurrentPrincipalAuthorization, get } = options;
|
|
|
|
|
|
async function setupTestStatus(endpointId: string, userId: string) {
|
|
const record = await endpointRecord(endpointId);
|
|
if (!record) throw notFound("Chat endpoint not found");
|
|
const startedAt = record.endpoint.setup.testStartedAt;
|
|
if (!startedAt) return { messageReceivedAt: null };
|
|
const links = await db.select({ principalId: chatIdentityLinks.principalId }).from(chatIdentityLinks).where(and(
|
|
eq(chatIdentityLinks.companyId, record.endpoint.companyId), eq(chatIdentityLinks.endpointId, endpointId),
|
|
eq(chatIdentityLinks.paperclipUserId, userId), eq(chatIdentityLinks.status, "linked"),
|
|
));
|
|
if (!links.length) return { messageReceivedAt: null };
|
|
const principalIds = links.map((link) => link.principalId);
|
|
const [delivery, command] = await Promise.all([
|
|
db.select({ at: chatDeliveries.createdAt }).from(chatDeliveries).where(and(
|
|
eq(chatDeliveries.companyId, record.endpoint.companyId), eq(chatDeliveries.endpointId, endpointId),
|
|
inArray(chatDeliveries.principalId, principalIds), gte(chatDeliveries.createdAt, new Date(startedAt)),
|
|
inArray(chatDeliveries.eventKind, ["message", "mention"]),
|
|
)).orderBy(asc(chatDeliveries.createdAt)).limit(1).then((rows) => rows[0]),
|
|
db.select({ at: chatActions.createdAt }).from(chatActions).where(and(
|
|
eq(chatActions.companyId, record.endpoint.companyId), eq(chatActions.endpointId, endpointId),
|
|
inArray(chatActions.principalId, principalIds), eq(chatActions.kind, "slash_task_start"), gte(chatActions.createdAt, new Date(startedAt)),
|
|
)).orderBy(asc(chatActions.createdAt)).limit(1).then((rows) => rows[0]),
|
|
]);
|
|
const at = [delivery?.at, command?.at].filter((value): value is Date => Boolean(value)).sort((a, b) => a.getTime() - b.getTime())[0];
|
|
return { messageReceivedAt: at?.toISOString() ?? null };
|
|
}
|
|
|
|
async function test(endpointId: string, finishOptions?: { optionalSlackTestForUser: string }, managementContext?: ConnectionManagementContext) {
|
|
await managementContext?.reauthorize();
|
|
const initial = await endpointRecord(endpointId);
|
|
if (!initial) throw notFound("Chat endpoint not found");
|
|
return withCredentialMutationLease(
|
|
initial.endpoint,
|
|
async (credentialLease) => {
|
|
// Reload only after owning the same lane as reconnect, pause, removal,
|
|
// and credential rotation. Qualification and activation must describe
|
|
// one exact provider runtime, never a setup snapshot that a concurrent
|
|
// reconnect has already superseded.
|
|
const record = await endpointRecord(endpointId);
|
|
if (!record) throw notFound("Chat endpoint not found");
|
|
const endpoint = record.endpoint;
|
|
if (endpoint.status !== "verifying" || endpoint.setup.step !== "test") {
|
|
throw conflict("This connection is not waiting for a setup test", {
|
|
code: "chat_endpoint_not_testing",
|
|
});
|
|
}
|
|
if (endpoint.provider === "github" && endpoint.setup.github) {
|
|
const verified = await githubChatManagementService(db, fetchImpl).verification(endpoint.id);
|
|
if (!verified.ready && !(finishOptions?.optionalSlackTestForUser && verified.connectionReady)) throw conflict("Finish verifying the App, repositories, and assigned agent's tools before activating this bot", { checks: verified.checks });
|
|
}
|
|
const testStartedAtValue = endpoint.setup.testStartedAt;
|
|
const testStartedAt = testStartedAtValue
|
|
? new Date(testStartedAtValue)
|
|
: null;
|
|
const optionalSlackTest = Boolean(finishOptions?.optionalSlackTestForUser);
|
|
if (optionalSlackTest) {
|
|
if (!["slack", "github"].includes(endpoint.provider) || !endpoint.setup.webhookVerifiedAt || !endpoint.providerAccountId) {
|
|
throw conflict("Verify the connection before finishing setup");
|
|
}
|
|
const linked = await findAuthorizedIdentityLink(endpoint, finishOptions!.optionalSlackTestForUser);
|
|
if (!linked) throw forbidden("Connect your account before finishing setup");
|
|
}
|
|
if (!optionalSlackTest) {
|
|
if (
|
|
!endpoint.lastEventAt ||
|
|
!testStartedAtValue ||
|
|
!testStartedAt ||
|
|
Number.isNaN(testStartedAt.getTime()) ||
|
|
endpoint.lastEventAt < testStartedAt
|
|
) {
|
|
throw conflict(
|
|
"Send the test message in the provider before completing setup",
|
|
{
|
|
code: "chat_test_message_missing",
|
|
},
|
|
);
|
|
}
|
|
const requiredTrigger =
|
|
["telegram", "imessage-photon"].includes(endpoint.provider)
|
|
? "direct_message"
|
|
: "subscribed_message";
|
|
const qualifyingDelivery = await db
|
|
.select({
|
|
id: chatDeliveries.id,
|
|
conversationId: chatDeliveries.conversationId,
|
|
processedAt: chatDeliveries.processedAt,
|
|
})
|
|
.from(chatDeliveries)
|
|
.where(
|
|
and(
|
|
eq(chatDeliveries.companyId, endpoint.companyId),
|
|
eq(chatDeliveries.endpointId, endpoint.id),
|
|
eq(chatDeliveries.state, "processed"),
|
|
gte(chatDeliveries.processedAt, testStartedAt),
|
|
sql`${chatDeliveries.normalizedEvent}->>'trigger' = ${requiredTrigger}`,
|
|
),
|
|
)
|
|
.orderBy(desc(chatDeliveries.processedAt))
|
|
.limit(1)
|
|
.then((rows) => rows[0] ?? null);
|
|
if (
|
|
!qualifyingDelivery?.conversationId ||
|
|
!qualifyingDelivery.processedAt
|
|
) {
|
|
throw conflict(
|
|
["telegram", "imessage-photon"].includes(endpoint.provider)
|
|
? "Send the test direct message before completing setup"
|
|
: "Reply once without mentioning the agent before completing setup",
|
|
{ code: "chat_test_follow_up_missing" },
|
|
);
|
|
}
|
|
const finalPublication = await db
|
|
.select({
|
|
commentId: chatPublications.commentId,
|
|
payload: chatPublications.payload,
|
|
})
|
|
.from(chatPublications)
|
|
.innerJoin(
|
|
issueComments,
|
|
and(
|
|
eq(issueComments.id, chatPublications.commentId),
|
|
eq(issueComments.companyId, chatPublications.companyId),
|
|
eq(issueComments.issueId, chatPublications.issueId),
|
|
eq(issueComments.authorType, "agent"),
|
|
eq(issueComments.authorAgentId, endpoint.assignedAgentId),
|
|
),
|
|
)
|
|
.innerJoin(
|
|
chatMessageLinks,
|
|
and(
|
|
eq(chatMessageLinks.companyId, chatPublications.companyId),
|
|
eq(chatMessageLinks.endpointId, chatPublications.endpointId),
|
|
eq(
|
|
chatMessageLinks.conversationId,
|
|
chatPublications.conversationId,
|
|
),
|
|
eq(chatMessageLinks.deliveryId, qualifyingDelivery.id),
|
|
eq(chatMessageLinks.direction, "inbound"),
|
|
isNotNull(chatMessageLinks.commentId),
|
|
),
|
|
)
|
|
.innerJoin(
|
|
heartbeatRuns,
|
|
and(
|
|
eq(heartbeatRuns.id, issueComments.createdByRunId),
|
|
eq(heartbeatRuns.companyId, chatPublications.companyId),
|
|
eq(heartbeatRuns.agentId, endpoint.assignedAgentId),
|
|
eq(heartbeatRuns.status, "succeeded"),
|
|
eq(
|
|
sql<string>`${heartbeatRuns.contextSnapshot} ->> 'issueId'`,
|
|
sql<string>`${chatPublications.issueId}::text`,
|
|
),
|
|
or(
|
|
sql`${chatMessageLinks.commentId}::text = ${heartbeatRuns.contextSnapshot} ->> 'wakeCommentId'`,
|
|
sql`${chatMessageLinks.commentId}::text = ${heartbeatRuns.contextSnapshot} ->> 'commentId'`,
|
|
sql`coalesce(${heartbeatRuns.contextSnapshot} -> 'wakeCommentIds', '[]'::jsonb) ? ${chatMessageLinks.commentId}::text`,
|
|
),
|
|
),
|
|
)
|
|
.where(
|
|
and(
|
|
eq(chatPublications.companyId, endpoint.companyId),
|
|
eq(chatPublications.endpointId, endpoint.id),
|
|
eq(
|
|
chatPublications.conversationId,
|
|
qualifyingDelivery.conversationId,
|
|
),
|
|
eq(chatPublications.state, "published"),
|
|
gte(chatPublications.publishedAt, qualifyingDelivery.processedAt),
|
|
),
|
|
)
|
|
.orderBy(desc(chatPublications.publishedAt))
|
|
.then((rows) =>
|
|
rows.find(
|
|
(row) =>
|
|
row.payload.interactionId === undefined &&
|
|
row.payload.progressState === undefined &&
|
|
row.commentId !== null,
|
|
),
|
|
);
|
|
let githubToolReply = false;
|
|
if (!finalPublication && endpoint.provider === "github") {
|
|
const setupRuns = await db.select({ id: heartbeatRuns.id, issueId: chatConversations.issueId })
|
|
.from(heartbeatRuns)
|
|
.innerJoin(chatMessageLinks, and(
|
|
eq(chatMessageLinks.companyId, endpoint.companyId),
|
|
eq(chatMessageLinks.endpointId, endpoint.id),
|
|
eq(chatMessageLinks.deliveryId, qualifyingDelivery.id),
|
|
eq(chatMessageLinks.direction, "inbound"),
|
|
or(
|
|
sql`${chatMessageLinks.commentId}::text = ${heartbeatRuns.contextSnapshot}->>'wakeCommentId'`,
|
|
sql`coalesce(${heartbeatRuns.contextSnapshot}->'wakeCommentIds', '[]'::jsonb) ? ${chatMessageLinks.commentId}::text`,
|
|
),
|
|
))
|
|
.innerJoin(chatConversations, and(
|
|
eq(chatConversations.id, qualifyingDelivery.conversationId),
|
|
eq(chatConversations.id, chatMessageLinks.conversationId),
|
|
eq(chatConversations.companyId, endpoint.companyId),
|
|
sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${chatConversations.issueId}::text`,
|
|
))
|
|
.where(and(eq(heartbeatRuns.companyId, endpoint.companyId),
|
|
eq(heartbeatRuns.agentId, endpoint.assignedAgentId), eq(heartbeatRuns.status, "succeeded")))
|
|
.orderBy(desc(heartbeatRuns.createdAt)).limit(20);
|
|
for (const run of setupRuns) {
|
|
if (await githubRunReplyState(db, { companyId: endpoint.companyId, endpointId: endpoint.id,
|
|
issueId: run.issueId, runId: run.id }) === "confirmed") {
|
|
githubToolReply = true;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if (!finalPublication && !githubToolReply) {
|
|
throw conflict(
|
|
"Wait for the Paperclip agent to reply to the setup turn before completing setup",
|
|
{
|
|
code: "chat_test_round_trip_incomplete",
|
|
},
|
|
);
|
|
}
|
|
}
|
|
await options.setupTestActivationBarrier?.();
|
|
await managementContext?.reauthorize();
|
|
const expectedGeneration = runtimeGeneration(endpoint.setup);
|
|
await db.transaction(async (tx) => {
|
|
await credentialLease.assertOwned(tx);
|
|
if (optionalSlackTest) {
|
|
const linked = await tx.select({ principalId: chatIdentityLinks.principalId }).from(chatIdentityLinks).where(and(
|
|
eq(chatIdentityLinks.endpointId, endpoint.id), eq(chatIdentityLinks.paperclipUserId, finishOptions!.optionalSlackTestForUser), eq(chatIdentityLinks.status, "linked"),
|
|
)).limit(1).then((rows) => rows[0]);
|
|
if (!linked || !(await lockCurrentPrincipalAuthorization(tx, endpoint, linked.principalId)).allowed) throw forbidden("Your connected account is no longer authorized");
|
|
}
|
|
await notifyChatEndpointWork(tx, endpoint.connectionId, endpoint.companyId);
|
|
const [activated] = await tx
|
|
.update(chatEndpoints)
|
|
.set({
|
|
status: "active",
|
|
setup: {
|
|
...endpoint.setup,
|
|
step: "complete",
|
|
testStartedAt: null,
|
|
testSkipped: optionalSlackTest,
|
|
},
|
|
healthMessage: optionalSlackTest ? "Connected; conversation test optional" : "Connected",
|
|
activatedAt: endpoint.activatedAt ?? new Date(),
|
|
updatedAt: new Date(),
|
|
})
|
|
.where(
|
|
and(
|
|
eq(chatEndpoints.id, endpointId),
|
|
eq(chatEndpoints.status, "verifying"),
|
|
sql`${chatEndpoints.setup}->>'step' = 'test'`,
|
|
sql`coalesce((${chatEndpoints.setup}->>'runtimeGeneration')::integer, 0) = ${expectedGeneration}`,
|
|
sql`${chatEndpoints.setup}->>'testStartedAt' = ${testStartedAtValue}`,
|
|
),
|
|
)
|
|
.returning({ id: chatEndpoints.id });
|
|
if (!activated) {
|
|
throw conflict("This setup test was superseded by a reconnect", {
|
|
code: "chat_endpoint_test_superseded",
|
|
});
|
|
}
|
|
await notifyChatConnectionHealth(tx, endpoint);
|
|
await tx
|
|
.update(toolConnections)
|
|
.set({
|
|
status: "active",
|
|
enabled: true,
|
|
healthStatus: "healthy",
|
|
healthMessage: optionalSlackTest ? "Connected; conversation test optional" : "Connected",
|
|
lastError: null,
|
|
healthCheckedAt: new Date(),
|
|
updatedAt: new Date(),
|
|
})
|
|
.where(eq(toolConnections.id, endpoint.connectionId));
|
|
if (optionalSlackTest) await logActivity(tx as unknown as Db, {
|
|
companyId: endpoint.companyId, ...(managementContext?.audit ?? { actorType: "user" as const, actorId: finishOptions!.optionalSlackTestForUser }),
|
|
action: "chat.setup_completed", entityType: "chat_endpoint", entityId: endpointId,
|
|
details: { conversationTestOptional: true },
|
|
});
|
|
await credentialLease.assertOwned(tx);
|
|
});
|
|
return get(endpointId);
|
|
},
|
|
);
|
|
}
|
|
return { setupTestStatus, test };
|
|
}
|