mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-03 09:37:19 +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>
205 lines
13 KiB
TypeScript
205 lines
13 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { and, eq, sql } from "drizzle-orm";
|
|
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { agentWakeupRequests, chatActions, chatExternalPrincipals, chatIdentityLinks, chatMessageLinks, chatPublications, companyMemberships, createDb, heartbeatRuns, issueComments, issues, subscribeDatabaseWork } from "@paperclipai/db";
|
|
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
|
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
|
|
import { createChatMilestoneFixtures } from "./helpers/chat-milestone-fixtures.js";
|
|
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
|
|
import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
|
|
import { chatRunMilestoneWork } from "../services/chat-run-milestone-work.js";
|
|
import { initializeRunIdentity, reserveSteeredIdentity, acceptSteeredIdentity } from "../services/run-identity.js";
|
|
import { idleWorkSnapshot } from "../services/task-admission.js";
|
|
import { accessService } from "../services/access.js";
|
|
|
|
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_MILESTONE_IDENTITY_TEST_DATABASE_URL");
|
|
const support = external ? { supported: true } : await getEmbeddedPostgresTestSupport();
|
|
(support.supported ? describe : describe.skip)("chat milestones after identity activation", () => {
|
|
let db: ReturnType<typeof createDb>;
|
|
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
|
|
let fixtures: ReturnType<typeof createChatMilestoneFixtures>;
|
|
let f: Awaited<ReturnType<typeof fixtures.create>>;
|
|
let coordinator: ReturnType<typeof createDeliveryWorkCoordinator> | undefined;
|
|
const errors: unknown[] = [];
|
|
beforeAll(async () => {
|
|
if (!external) temporary = await startEmbeddedPostgresTestDatabase("chat-identity-milestones-");
|
|
db = createDb(external ?? temporary!.connectionString, { idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 });
|
|
fixtures = createChatMilestoneFixtures(db);
|
|
}, 60_000);
|
|
beforeEach(async () => {
|
|
errors.length = 0; f = await fixtures.create();
|
|
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true });
|
|
});
|
|
afterEach(async () => {
|
|
await coordinator?.stop(); coordinator = undefined; vi.useRealTimers(); vi.restoreAllMocks();
|
|
await fixtures.cleanup(); expect(errors).toEqual([]);
|
|
});
|
|
afterAll(async () => { await db?.$client.end({ timeout: 1 }); await temporary?.cleanup(); });
|
|
async function flush() {
|
|
await vi.waitFor(async () => {
|
|
await vi.advanceTimersByTimeAsync(1000);
|
|
expect(idleWorkSnapshot().active).toBe(0); expect(coordinator!.nextWakeAt()).toBeNull();
|
|
}, { timeout: 10_000 });
|
|
}
|
|
async function quiet() {
|
|
const reads = vi.spyOn(db, "select"), writes = vi.spyOn(db, "transaction");
|
|
try { await vi.advanceTimersByTimeAsync(120_000); expect(reads).not.toHaveBeenCalled(); expect(writes).not.toHaveBeenCalled(); }
|
|
finally { reads.mockRestore(); writes.mockRestore(); }
|
|
}
|
|
const publications = () => db.select().from(chatPublications).where(eq(chatPublications.issueId, f.issueId));
|
|
|
|
it.each([false, true])("rechecks concurrent membership suspension before restoring notice access (rollback=%s)", async rollback => {
|
|
const membershipWhere = and(eq(companyMemberships.companyId, f.companyId), eq(companyMemberships.principalId, f.userId));
|
|
// A Board-origin reply uses the linked author and current membership.
|
|
// Remove the fixture's unrelated provider-ingress provenance.
|
|
await db.delete(chatMessageLinks).where(eq(chatMessageLinks.commentId, f.commentId));
|
|
await db.update(issueComments).set({ authorUserId: f.userId }).where(eq(issueComments.id, f.commentId));
|
|
const [principal] = await db.insert(chatExternalPrincipals).values({ companyId: f.companyId,
|
|
provider: "slack", providerAccountId: "", externalId: f.userId,
|
|
}).returning();
|
|
await db.insert(chatIdentityLinks).values({ companyId: f.companyId, endpointId: f.endpointId,
|
|
principalId: principal.id, paperclipUserId: f.userId, status: "linked",
|
|
});
|
|
await db.insert(chatActions).values({ companyId: f.companyId, endpointId: f.endpointId,
|
|
conversationId: f.conversationId, kind: "slack_board_message", status: "processed",
|
|
providerActionId: `board-comment:${f.commentId}`, payload: { issueId: f.issueId, commentId: f.commentId,
|
|
userId: f.userId, principalId: principal.id, agentId: f.agentId },
|
|
});
|
|
const runId = randomUUID(), sourceId = randomUUID();
|
|
const nextCheckAt = new Date(Date.now() - 1000).toISOString();
|
|
await db.insert(heartbeatRuns).values({ id: sourceId, companyId: f.companyId, agentId: f.agentId,
|
|
nativeIssueId: f.issueId, runtimeMode: "native", status: "succeeded", responsibleUserId: f.userId,
|
|
contextSnapshot: { issueId: f.issueId, source: "chat:slack", endpointId: f.endpointId, wakeCommentId: f.commentId },
|
|
resultJson: { semanticToolReceipts: { schedule: { operationId: "set_task_monitor",
|
|
result: { taskId: f.issueId, monitor: { status: "scheduled", nextCheckAt } } } } },
|
|
});
|
|
await db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId,
|
|
nativeIssueId: f.issueId, runtimeMode: "native", status: "running", responsibleUserId: f.userId,
|
|
contextSnapshot: { issueId: f.issueId, source: "issue.monitor" },
|
|
});
|
|
await db.insert(agentWakeupRequests).values({ companyId: f.companyId, agentId: f.agentId, runId,
|
|
source: "automation", reason: "issue_monitor_due", status: "claimed",
|
|
idempotencyKey: `issue-monitor:${f.issueId}:${nextCheckAt}`, payload: { issueId: f.issueId, nextCheckAt },
|
|
});
|
|
await initializeRunIdentity(db, { companyId: f.companyId, runId, issueId: f.issueId,
|
|
responsibleUserId: f.userId, cause: "dispatch" });
|
|
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, f.issueId));
|
|
let releaseSuspension!: () => void;
|
|
const suspensionHeld = new Promise<void>(resolve => { releaseSuspension = resolve; });
|
|
let markSuspended!: () => void;
|
|
const suspended = new Promise<void>(resolve => { markSuspended = resolve; });
|
|
let releaseRestoration!: () => void;
|
|
const restorationHeld = new Promise<void>(resolve => { releaseRestoration = resolve; });
|
|
let restored = false;
|
|
let restorationPid = 0;
|
|
const suspending = db.transaction(async tx => {
|
|
await tx.update(companyMemberships).set({ status: "suspended" }).where(membershipWhere);
|
|
markSuspended();
|
|
await suspensionHeld;
|
|
});
|
|
await suspended;
|
|
const restoring = db.transaction(async tx => {
|
|
const [backend] = await tx.execute<{ pid: number }>(sql`select pg_backend_pid() as pid`);
|
|
restorationPid = backend.pid;
|
|
await accessService(tx as unknown as typeof db).ensureMembership(f.companyId, "user", f.userId, "operator");
|
|
restored = true;
|
|
await restorationHeld;
|
|
if (rollback) throw new Error("outer membership rollback");
|
|
});
|
|
void restoring.catch(() => undefined);
|
|
try {
|
|
// The old read sees active membership, then its UPDATE waits. The fixed
|
|
// read waits first and observes the suspension after that writer commits.
|
|
await vi.waitFor(async () => {
|
|
expect(restorationPid).toBeGreaterThan(0);
|
|
const [state] = await db.execute<{ blocked: boolean }>(sql`select cardinality(pg_blocking_pids(${restorationPid})) > 0 as blocked`);
|
|
expect(state.blocked).toBe(true);
|
|
});
|
|
releaseSuspension();
|
|
await suspending;
|
|
await vi.waitFor(() => expect(restored).toBe(true));
|
|
coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, canReconcile: () => true, onError: error => errors.push(error) });
|
|
await chatRunMilestoneWork(db).register(coordinator, () => true).ready;
|
|
await vi.advanceTimersByTimeAsync(1000);
|
|
expect(await publications()).toEqual([]);
|
|
expect((await db.select().from(companyMemberships).where(membershipWhere))[0].status).toBe("suspended");
|
|
releaseRestoration();
|
|
if (rollback) await expect(restoring).rejects.toThrow("outer membership rollback");
|
|
else await restoring;
|
|
await flush();
|
|
expect((await db.select().from(companyMemberships).where(membershipWhere))[0].status)
|
|
.toBe(rollback ? "suspended" : "active");
|
|
expect(await publications()).toEqual(rollback ? [] : [expect.objectContaining({ idempotencyKey: `run:${runId}:working:${f.endpointId}` })]);
|
|
await quiet();
|
|
if (!rollback) {
|
|
const notices: string[] = [];
|
|
const unsubscribe = subscribeDatabaseWork(db, DELIVERY_QUEUES.chatRunMilestones, event => notices.push(event));
|
|
try {
|
|
await accessService(db).ensureMembership(f.companyId, "user", f.userId, "operator");
|
|
expect(notices).toEqual([]);
|
|
} finally { unsubscribe(); }
|
|
await quiet();
|
|
}
|
|
} finally {
|
|
releaseSuspension();
|
|
releaseRestoration();
|
|
await Promise.allSettled([suspending, restoring]);
|
|
}
|
|
});
|
|
|
|
it.each(["initialization", "steering"] as const)("wakes matching monitor lineage after %s commits, preserving rollback and replay", async kind => {
|
|
const nextCheckAt = new Date(Date.now() - 1000).toISOString();
|
|
const sourceId = randomUUID(), successorId = randomUUID();
|
|
await db.insert(heartbeatRuns).values({ id: sourceId, companyId: f.companyId, agentId: f.agentId,
|
|
nativeIssueId: f.issueId, runtimeMode: "native", status: "succeeded", responsibleUserId: f.userId,
|
|
contextSnapshot: { issueId: f.issueId, source: "chat:slack", endpointId: f.endpointId, wakeCommentId: f.commentId },
|
|
resultJson: { semanticToolReceipts: { schedule: { operationId: "set_task_monitor",
|
|
result: { taskId: f.issueId, monitor: { status: "scheduled", nextCheckAt } } } } },
|
|
});
|
|
await db.insert(heartbeatRuns).values({ id: successorId, companyId: f.companyId, agentId: f.agentId,
|
|
nativeIssueId: f.issueId, runtimeMode: "native", status: "running", responsibleUserId: null,
|
|
contextSnapshot: { issueId: f.issueId, source: "issue.monitor" },
|
|
});
|
|
await db.insert(agentWakeupRequests).values({ companyId: f.companyId, agentId: f.agentId, runId: successorId,
|
|
source: "automation", reason: "issue_monitor_due", status: "claimed",
|
|
idempotencyKey: `issue-monitor:${f.issueId}:${nextCheckAt}`, payload: { issueId: f.issueId, nextCheckAt },
|
|
});
|
|
const identityInput = { companyId: f.companyId, runId: successorId, issueId: f.issueId, responsibleUserId: f.userId, cause: "dispatch" };
|
|
if (kind === "steering") {
|
|
await initializeRunIdentity(db, { ...identityInput, responsibleUserId: null });
|
|
await db.update(issueComments).set({ authorUserId: f.userId }).where(eq(issueComments.id, f.commentId));
|
|
}
|
|
coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, canReconcile: () => true, onError: error => errors.push(error) });
|
|
await chatRunMilestoneWork(db).register(coordinator, () => true).ready;
|
|
await flush(); expect(await publications()).toEqual([]); await quiet();
|
|
const pending = kind === "steering" ? await reserveSteeredIdentity(db, {
|
|
companyId: f.companyId, runId: successorId, issueId: f.issueId, messageId: f.commentId,
|
|
}) : null;
|
|
// Reserving an unacknowledged message must not activate its identity.
|
|
if (kind === "steering") expect(pending?.status).toBe("pending");
|
|
await flush(); expect(await publications()).toEqual([]); await quiet();
|
|
const activate = (rollback: boolean) => db.transaction(async tx => {
|
|
if (kind === "steering") await acceptSteeredIdentity(tx, pending!);
|
|
else await initializeRunIdentity(tx as unknown as typeof db, identityInput);
|
|
await vi.advanceTimersByTimeAsync(1000);
|
|
expect(await publications()).toEqual([]);
|
|
if (rollback) throw new Error("outer rollback");
|
|
});
|
|
await expect(activate(true)).rejects.toThrow("outer rollback");
|
|
await flush(); expect(await publications()).toEqual([]); await quiet();
|
|
await activate(false); await flush();
|
|
expect(await publications()).toEqual([expect.objectContaining({ idempotencyKey: `run:${successorId}:working:${f.endpointId}` })]);
|
|
await quiet();
|
|
const notices: string[] = [];
|
|
const unsubscribe = subscribeDatabaseWork(db, DELIVERY_QUEUES.chatRunMilestones, event => notices.push(event));
|
|
try {
|
|
await db.transaction(async tx => {
|
|
if (kind === "steering") await acceptSteeredIdentity(tx, pending!);
|
|
else await initializeRunIdentity(tx as unknown as typeof db, identityInput);
|
|
});
|
|
expect(notices).toEqual([]);
|
|
} finally { unsubscribe(); }
|
|
await flush(); await quiet();
|
|
});
|
|
});
|