mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-04 02:32:07 +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>
255 lines
8.5 KiB
TypeScript
255 lines
8.5 KiB
TypeScript
import { notifyChatRunMilestones } from "./chat-run-milestone-notifications.js";
|
|
import { notifyToolReviewChange } from "./tool-review-work-notifications.js";
|
|
import { notifyDeliveryWork, DELIVERY_QUEUES } from "./delivery-work-notifications.js";
|
|
import { and, eq } from "drizzle-orm";
|
|
import {
|
|
issues,
|
|
issueThreadInteractions,
|
|
toolActionRequests,
|
|
toolInvocations,
|
|
toolActionDeliveries,
|
|
type Db,
|
|
} from "@paperclipai/db";
|
|
import { conflict, forbidden, notFound } from "../errors.js";
|
|
import { assertIssueThreadInteractionResolverAudience } from "./issue-thread-interaction-resolution.js";
|
|
import { emitConnectionInvoked } from "./connector-telemetry.js";
|
|
import { toolAccessPolicyService } from "./tool-access-policy.js";
|
|
import {
|
|
logActivity,
|
|
publishActivity,
|
|
type ActivityPublication,
|
|
} from "./activity-log.js";
|
|
|
|
/** The shared transaction for both task and Connections review decisions. */
|
|
export async function commitToolActionReview(
|
|
db: Db,
|
|
input: {
|
|
companyId: string;
|
|
actionRequestId: string;
|
|
issueId?: string;
|
|
interactionId?: string;
|
|
decision: "approved" | "rejected";
|
|
rememberAction?: boolean;
|
|
reason?: string;
|
|
actor: { agentId?: string | null; userId?: string | null };
|
|
},
|
|
) {
|
|
if (input.actor.agentId)
|
|
throw forbidden("Only a human can resolve a tool review");
|
|
const [source] = await db
|
|
.select()
|
|
.from(toolActionRequests)
|
|
.where(
|
|
and(
|
|
eq(toolActionRequests.id, input.actionRequestId),
|
|
eq(toolActionRequests.companyId, input.companyId),
|
|
),
|
|
)
|
|
.limit(1);
|
|
if (!source) throw notFound("Tool action request not found");
|
|
if ((input.issueId || input.interactionId) && (!input.issueId || !input.interactionId || source.issueId !== input.issueId || source.interactionId !== input.interactionId)) {
|
|
throw conflict("Tool action request does not belong to this interaction");
|
|
}
|
|
const publications: ActivityPublication[] = [];
|
|
const result = await db.transaction(async (tx) => {
|
|
const [issue] = source.issueId
|
|
? await tx
|
|
.select()
|
|
.from(issues)
|
|
.where(
|
|
and(
|
|
eq(issues.id, source.issueId),
|
|
eq(issues.companyId, input.companyId),
|
|
),
|
|
)
|
|
.for("update")
|
|
: [];
|
|
const [interaction] = source.interactionId
|
|
? await tx
|
|
.select()
|
|
.from(issueThreadInteractions)
|
|
.where(
|
|
and(
|
|
eq(issueThreadInteractions.id, source.interactionId),
|
|
eq(issueThreadInteractions.companyId, input.companyId),
|
|
),
|
|
)
|
|
.for("update")
|
|
: [];
|
|
const [current] = await tx
|
|
.select()
|
|
.from(toolActionRequests)
|
|
.where(
|
|
and(
|
|
eq(toolActionRequests.id, source.id),
|
|
eq(toolActionRequests.companyId, input.companyId),
|
|
),
|
|
)
|
|
.for("update");
|
|
if (!current) throw notFound("Tool action request not found");
|
|
if (current.status !== "pending") {
|
|
if (
|
|
(input.decision === "approved" &&
|
|
["approved", "executing", "executed", "failed"].includes(
|
|
current.status,
|
|
)) ||
|
|
current.status === input.decision
|
|
)
|
|
return current;
|
|
throw conflict("This review has already been resolved");
|
|
}
|
|
if (
|
|
source.issueId &&
|
|
(!issue || issue.status === "done" || issue.status === "cancelled")
|
|
)
|
|
throw conflict("This task is closed");
|
|
const [invocation] = await tx
|
|
.select()
|
|
.from(toolInvocations)
|
|
.where(
|
|
and(
|
|
eq(toolInvocations.id, current.invocationId),
|
|
eq(toolInvocations.companyId, input.companyId),
|
|
),
|
|
)
|
|
.limit(1);
|
|
if (
|
|
!invocation ||
|
|
invocation.issueId !== current.issueId ||
|
|
(current.requestedByAgentId &&
|
|
(invocation.actorType === "agent" ? invocation.actorId : invocation.agentId) !== current.requestedByAgentId)
|
|
)
|
|
throw conflict("Tool invocation context does not match");
|
|
if (current.expiresAt && current.expiresAt <= new Date())
|
|
throw conflict("This review has expired");
|
|
if (current.interactionId) {
|
|
const payload = interaction?.payload as {
|
|
toolAction?: { actionRequestId?: string; invocationId?: string };
|
|
} | null;
|
|
if (
|
|
!interaction ||
|
|
interaction.issueId !== current.issueId ||
|
|
payload?.toolAction?.actionRequestId !== current.id ||
|
|
payload.toolAction.invocationId !== current.invocationId
|
|
)
|
|
throw conflict("Tool review context does not match");
|
|
assertIssueThreadInteractionResolverAudience({
|
|
actor: { type: "user", userId: input.actor.userId ?? "board" },
|
|
interaction,
|
|
governedAction: true,
|
|
});
|
|
if (interaction.status !== "pending")
|
|
throw conflict("This review has already been resolved");
|
|
}
|
|
const now = new Date();
|
|
if (interaction && issue) await notifyChatRunMilestones(tx, interaction);
|
|
await notifyToolReviewChange(tx, current.companyId);
|
|
const [updated] = await tx
|
|
.update(toolActionRequests)
|
|
.set({
|
|
status: input.decision,
|
|
resolvedByUserId: input.actor.userId ?? "board",
|
|
decidedByUserId: input.actor.userId ?? "board",
|
|
decidedAt: now,
|
|
resolvedAt: now,
|
|
updatedAt: now,
|
|
})
|
|
.where(eq(toolActionRequests.id, current.id))
|
|
.returning();
|
|
if (input.rememberAction) {
|
|
if (input.decision !== "approved")
|
|
throw conflict("Only an approval can remember permission");
|
|
await toolAccessPolicyService(
|
|
tx as unknown as Db,
|
|
).createTrustRuleFromActionRequest({
|
|
companyId: input.companyId,
|
|
actionRequestId: current.id,
|
|
body: { approvalThreshold: 1, priority: 40, argumentMode: "action" },
|
|
actor: { userId: input.actor.userId ?? "board" },
|
|
});
|
|
}
|
|
await tx
|
|
.update(toolInvocations)
|
|
.set({
|
|
approvalState: input.decision,
|
|
...(input.decision === "rejected"
|
|
? {
|
|
status: "denied" as const,
|
|
completedAt: now,
|
|
errorCode: "action_declined",
|
|
errorMessage: "The human declined this action.",
|
|
}
|
|
: {}),
|
|
updatedAt: now,
|
|
})
|
|
.where(
|
|
and(
|
|
eq(toolInvocations.id, current.invocationId),
|
|
eq(toolInvocations.companyId, input.companyId),
|
|
),
|
|
);
|
|
if (interaction && issue) {
|
|
await tx
|
|
.update(issueThreadInteractions)
|
|
.set({
|
|
status: input.decision === "approved" ? "accepted" : "rejected",
|
|
resolvedByUserId: input.actor.userId ?? "board",
|
|
resolvedAt: now,
|
|
updatedAt: now,
|
|
result:
|
|
input.decision === "approved"
|
|
? {
|
|
version: 1,
|
|
outcome: "accepted",
|
|
toolAction: {
|
|
version: 1,
|
|
status: "approved",
|
|
rememberedAction: input.rememberAction === true,
|
|
updatedAt: now.toISOString(),
|
|
},
|
|
}
|
|
: { version: 1, outcome: "rejected", reason: input.reason },
|
|
})
|
|
.where(eq(issueThreadInteractions.id, interaction.id));
|
|
await notifyDeliveryWork(tx, DELIVERY_QUEUES.toolAction);
|
|
await tx
|
|
.insert(toolActionDeliveries)
|
|
.values({
|
|
companyId: input.companyId,
|
|
actionRequestId: current.id,
|
|
issueId: issue.id,
|
|
interactionId: interaction.id,
|
|
})
|
|
.onConflictDoNothing();
|
|
await logActivity(
|
|
tx as unknown as Db,
|
|
{
|
|
companyId: input.companyId,
|
|
actorType: "user",
|
|
actorId: input.actor.userId ?? "board",
|
|
action:
|
|
input.decision === "approved"
|
|
? "issue.thread_interaction_accepted"
|
|
: "issue.thread_interaction_rejected",
|
|
entityType: "issue",
|
|
entityId: issue.id,
|
|
details: {
|
|
interactionId: interaction.id,
|
|
actionRequestId: current.id,
|
|
rememberAction: input.rememberAction === true,
|
|
},
|
|
},
|
|
publications,
|
|
);
|
|
}
|
|
return updated;
|
|
});
|
|
// A rejection writes the invocation's terminal `denied` status inside the
|
|
// transaction above; emit only after that commit. Approvals stay in-flight
|
|
// and reach their terminal status in the gateway execution paths.
|
|
if (input.decision === "rejected")
|
|
void emitConnectionInvoked(db, source.invocationId);
|
|
for (const publication of publications) publishActivity(publication);
|
|
return result;
|
|
}
|