Merge current master into reviewed Speko runtime

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* origin/master:
  fix(recovery): surface exhausted review-path repair (#15764)
  fix(slack): link created tasks in default reply guidance (#15579)
  fix(slack): require result and review updates in conversation prompts (#15611)
  Fix idle sleep checks for finished login and wake history (#15761)
  ci: use a Docker Hub mirror for image builds (#15756)
  fix(release): retry incomplete canary dependency publications (#15743)
  fix(release): reuse publisher lockfile for canary smoke (#15712)

# Conflicts:
#	server/src/services/chat-communication-guidance.test.ts
This commit is contained in:
Dotta committed 2026-10-09 21:11:33 -05:00
commit 7f7ee611e8
27 files changed
+1157 -35

No files matched your search

@@ -301,6 +301,11 @@ describe("buildPaperclipTaskMarkdown", () => {
externalChatProvider: "slack", nativeRunner, includeDescription,
});
expect(markdown).toContain("Interactive questions in Slack:");
expect(markdown).toContain("When you have results, update the user in the originating Slack");
expect(markdown).toContain("When the user needs to review a plan, approve an action, or review a result");
expect(markdown).toContain("create the required human-input or approval interaction before you yield");
expect(markdown).toContain("Saving a plan or setting a task to in_review alone does not ask the user to review it");
expect(markdown).toContain("do not continue gated work until the required approval is recorded");
expect(markdown).toContain("ask_user_questions");
expect(markdown).toContain("single_select");
expect(markdown).toContain("resumes this task after the answer");
@@ -1,5 +1,5 @@
import { randomUUID } from "node:crypto";
import { and, eq } from "drizzle-orm";
import { and, eq, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
activityLog,
@@ -70,6 +70,7 @@ vi.mock("../adapters/index.ts", async () => {
import { heartbeatService } from "../services/heartbeat.ts";
import { attentionService } from "../services/attention.ts";
import { issueService } from "../services/issues.ts";
import { escalateExhaustedIssueReviewPathRecovery } from "../services/recovery/review-path-recovery-escalation.ts";
import { runningProcesses } from "../adapters/index.ts";
import {
buildIssueBlockersResolvedWakeStateKey,
@@ -342,7 +343,7 @@ describeEmbeddedPostgres("heartbeat resolved dependency wake reconciliation", ()
return { companyId, agentId, blockedIssueId, blockerIssueId, executionWorkspaceId };
}
it("runs exactly one bounded review-path recovery before surfacing a stalled decision", async () => {
it.each(["pathless", "monitor"] as const)("runs exactly one bounded review-path recovery with %s disposition", async (disposition) => {
const companyId = randomUUID();
const agentId = randomUUID();
const issueId = randomUUID();
@@ -368,7 +369,7 @@ describeEmbeddedPostgres("heartbeat resolved dependency wake reconciliation", ()
await db.insert(issues).values({
id: issueId,
companyId,
title: "PAP-14994 fingerprint",
title: "External build follow-up",
status: "in_review",
priority: "medium",
assigneeAgentId: agentId,
@@ -377,6 +378,16 @@ describeEmbeddedPostgres("heartbeat resolved dependency wake reconciliation", ()
identifier: `${issuePrefix}-1`,
});
if (disposition === "monitor") {
const execute = mockAdapterExecute.getMockImplementation()!;
mockAdapterExecute.mockImplementationOnce(execute).mockImplementationOnce(async () => {
await issueService(db).update(issueId, {
monitorNextCheckAt: new Date(Date.now() + 60_000), monitorNotes: "Check external build",
});
return execute();
});
}
const heartbeat = heartbeatService(db);
const followUpRun = await heartbeat.wakeup(agentId, {
source: "automation",
@@ -420,19 +431,195 @@ describeEmbeddedPostgres("heartbeat resolved dependency wake reconciliation", ()
}),
});
const attention = await issueService(db)
.listReviewAttention(companyId, [{ id: issueId, companyId, status: "in_review" }]);
expect(attention.get(issueId)).toMatchObject({ state: "stalled", paths: [] });
const issue = await db.select().from(issues).where(eq(issues.id, issueId)).then((rows) => rows[0]);
if (disposition === "monitor") {
expect(issue).toMatchObject({ status: "in_review", assigneeAgentId: agentId, monitorNextCheckAt: expect.any(Date) });
expect(await db.select().from(issueRecoveryActions)).toHaveLength(0);
expect(await db.select().from(issueComments)).toHaveLength(0);
const attention = await issueService(db).listReviewAttention(companyId, [issue]);
expect(attention.get(issueId)).toMatchObject({ state: "covered", paths: expect.arrayContaining([expect.objectContaining({ kind: "monitor" })]) });
return;
}
expect(issue).toMatchObject({ status: "blocked", assigneeAgentId: agentId });
const actions = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId));
expect(actions).toHaveLength(1);
expect(actions[0]).toMatchObject({
ownerType: "board", ownerAgentId: null, ownerUserId: null,
returnOwnerAgentId: agentId, cause: "issue_review_path_lost", attemptCount: 1, maxAttempts: 1,
});
const notices = await db.select().from(issueComments).where(eq(issueComments.issueId, issueId));
expect(notices).toHaveLength(1);
expect(notices[0]).toMatchObject({ authorType: "system", presentation: expect.objectContaining({ title: "No follow-up scheduled" }) });
const recoveryRun = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, recoveryWakes[0].runId!)).then((rows) => rows[0]);
// Replayed finalization must not duplicate the notice, action, or wake.
expect(await escalateExhaustedIssueReviewPathRecovery(db, { run: recoveryRun, issueId })).toBeNull();
expect(await db.select().from(issueRecoveryActions)).toHaveLength(1);
expect(await db.select().from(issueComments)).toHaveLength(1);
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.reason, "issue_review_path_lost"))).toHaveLength(1);
const feed = await attentionService(db).list(companyId, { userId: "responsible-user" });
expect(feed.items.find((item) => item.subject.id === issueId)).toMatchObject({
sourceKind: "review",
expect(feed.items.find((item) => item.subject.id === actions[0].id)).toMatchObject({
sourceKind: "recovery_action",
relatedIssue: expect.objectContaining({ id: issueId }),
decisionVerbs: expect.arrayContaining([
expect.objectContaining({ id: "choose_review_path", label: "Choose review path" }),
expect.objectContaining({ id: "resolve", label: "Resolve" }),
]),
});
});
it.each(["monitor", "completed", "reassigned", "newer_run", "other_company"] as const)(
"does not escalate a stale review recovery after %s",
async (change) => {
const companyId = randomUUID();
const agentId = randomUUID();
const issueId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Review Co", issuePrefix: `R${companyId.slice(0, 6)}` });
await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer", role: "engineer", adapterType: "codex_local" });
await db.insert(issues).values({ id: issueId, companyId, title: "Async review", status: "in_review", assigneeAgentId: agentId });
const [run] = await db.insert(heartbeatRuns).values({
companyId, agentId, status: "succeeded", issueId,
createdAt: new Date(Date.now() - 60_000),
contextSnapshot: { issueId, wakeReason: "issue_review_path_lost", reviewPathRecoveryAttempt: 1 },
}).returning();
if (change === "monitor") {
await issueService(db).update(issueId, { monitorNextCheckAt: new Date(Date.now() + 60_000), monitorNotes: "Check build" });
} else if (change === "completed") {
await issueService(db).update(issueId, { status: "done" });
} else if (change === "reassigned") {
const nextAgentId = randomUUID();
await db.insert(agents).values({ id: nextAgentId, companyId, name: "New reviewer", role: "engineer", adapterType: "codex_local" });
await issueService(db).update(issueId, { assigneeAgentId: nextAgentId });
} else if (change === "newer_run") {
await db.insert(heartbeatRuns).values({ companyId, agentId, issueId, status: "succeeded", contextSnapshot: { issueId } });
}
expect(await escalateExhaustedIssueReviewPathRecovery(db, {
run: change === "other_company" ? { ...run, companyId: randomUUID() } : run,
issueId,
})).toBeNull();
expect(await db.select().from(issueRecoveryActions)).toHaveLength(0);
expect(await db.select().from(issueComments)).toHaveLength(0);
const current = await db.select().from(issues).where(eq(issues.id, issueId)).then((rows) => rows[0]);
expect(current.status).toBe(change === "completed" ? "done" : "in_review");
if (change === "monitor") expect(current.monitorNextCheckAt).not.toBeNull();
},
);
it("serializes concurrent finalization of a failed review repair", async () => {
const companyId = randomUUID();
const agentId = randomUUID();
const issueId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Review Co", issuePrefix: `R${companyId.slice(0, 6)}` });
await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer", role: "engineer", adapterType: "codex_local" });
await db.insert(issues).values({ id: issueId, companyId, title: "Failed review repair", status: "in_review", assigneeAgentId: agentId });
const [run] = await db.insert(heartbeatRuns).values({
companyId, agentId, issueId, status: "failed",
contextSnapshot: { issueId, wakeReason: "issue_review_path_lost", reviewPathRecoveryAttempt: 1 },
}).returning();
const results = await Promise.all([
escalateExhaustedIssueReviewPathRecovery(db, { run, issueId }),
escalateExhaustedIssueReviewPathRecovery(db, { run, issueId }),
]);
expect(results.filter(Boolean)).toHaveLength(1);
expect(await db.select().from(issueRecoveryActions)).toHaveLength(1);
expect(await db.select().from(issueComments)).toHaveLength(1);
expect(await db.select().from(agentWakeupRequests)).toHaveLength(0);
expect(await db.select().from(activityLog).where(eq(activityLog.action, "issue.review_path_recovery_exhausted"))).toHaveLength(1);
});
it.each(["restart", "transaction_failure", "due_monitor", "claimed_monitor", "expired_monitor", "exhausted_monitor", "disabled_monitor"] as const)("reconciles a committed review repair after %s with a one-connection pool", async (gap) => {
const companyId = randomUUID();
const agentId = randomUUID();
const issueId = randomUUID();
const wakeId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Review Co", issuePrefix: `R${companyId.slice(0, 6)}`, defaultResponsibleUserId: "responsible-user" });
await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer", role: "engineer", adapterType: "codex_local", runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } } });
await db.insert(issues).values({ id: issueId, companyId, title: "Repair finalized before restart", status: "in_review", assigneeAgentId: agentId, responsibleUserId: "responsible-user" });
await db.insert(agentWakeupRequests).values({
id: wakeId, companyId, agentId, source: "automation", status: "completed",
reason: "issue_review_path_lost", payload: { issueId, reviewPathRecoveryAttempt: 1 },
});
const [repairRun] = await db.insert(heartbeatRuns).values({
companyId, agentId, issueId, status: "succeeded", wakeupRequestId: wakeId, finishedAt: new Date(),
contextSnapshot: { issueId, wakeReason: "issue_review_path_lost", reviewPathRecoveryAttempt: 1 },
}).returning();
const dueAt = new Date(Date.now() - 60_000);
if (gap.endsWith("monitor")) {
const monitored = await issueService(db).update(issueId, {
monitorNextCheckAt: dueAt, monitorNotes: "Check external build",
executionPolicy: { monitor: {
nextCheckAt: dueAt.toISOString(), notes: "Check external build", scheduledBy: "assignee",
kind: "external_service", serviceName: "github_checks",
...(gap === "disabled_monitor" ? {} : { timeoutAt: new Date(Date.now() + 60_000).toISOString(), maxAttempts: 3 }),
} },
});
if (gap === "disabled_monitor") {
// A policy change after saving an unbounded check must not hide the
// spent repair forever: dispatch cannot accept its on-demand wake.
await db.update(agents).set({ runtimeConfig: { heartbeat: { wakeOnDemand: false } } }).where(eq(agents.id, agentId));
} else if (gap === "claimed_monitor") {
await db.update(issues).set({ monitorWakeRequestedAt: new Date() }).where(eq(issues.id, issueId));
} else if (gap === "expired_monitor" || gap === "exhausted_monitor") {
const policy = monitored!.executionPolicy as { monitor: Record<string, unknown> };
await db.update(issues).set({
executionPolicy: { ...policy, monitor: { ...policy.monitor, ...(gap === "expired_monitor" ? { timeoutAt: new Date(Date.now() - 1_000).toISOString() } : { maxAttempts: 1 }) } },
...(gap === "exhausted_monitor" ? { monitorAttemptCount: 1 } : {}),
}).where(eq(issues.id, issueId));
}
}
// Only the terminal run and completed wake were persisted before the crash.
// A new service must restore the missing action without invoking the agent.
const singleConnectionDb = createDb(tempDb!.connectionString, { maxConnections: 1 });
try {
if (gap === "transaction_failure") {
await db.execute(sql`alter table issue_comments add constraint review_repair_notice_test check (false) not valid`);
try {
await expect(escalateExhaustedIssueReviewPathRecovery(singleConnectionDb, { run: repairRun, issueId })).rejects.toThrow();
} finally {
await db.execute(sql`alter table issue_comments drop constraint review_repair_notice_test`);
}
expect(await db.select().from(issueRecoveryActions)).toHaveLength(0);
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0].status).toBe("in_review");
}
const recovery = heartbeatService(singleConnectionDb);
const result = await recovery.reconcileStrandedAssignedIssues();
if (gap === "due_monitor" || gap === "claimed_monitor") {
expect(result.escalated).toBe(0);
expect(await db.select().from(issueRecoveryActions)).toHaveLength(0);
expect(await db.select().from(issueComments)).toHaveLength(0);
const current = (await db.select().from(issues).where(eq(issues.id, issueId)))[0];
expect(current).toMatchObject({ status: "in_review", monitorNextCheckAt: dueAt });
// A claim left by a crashed dispatcher can be reclaimed after its lease.
if (gap === "claimed_monitor") {
await db.update(issues).set({ monitorWakeRequestedAt: new Date(Date.now() - 6 * 60_000) }).where(eq(issues.id, issueId));
}
const execute = mockAdapterExecute.getMockImplementation()!;
mockAdapterExecute.mockImplementationOnce(async () => {
await issueService(db).update(issueId, { status: "done" });
return execute();
});
const dispatcher = heartbeatService(db, { runtimeEnv: {} });
await dispatcher.tickTimers();
await dispatcher.drainActiveRunExecutions();
const wakes = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.reason, "issue_monitor_due"));
expect(wakes).toHaveLength(1);
expect(mockAdapterExecute).toHaveBeenCalledOnce();
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]).toMatchObject({ status: "done", monitorNextCheckAt: null });
return;
}
expect(result).toMatchObject({ escalated: 1, issueIds: [issueId] });
expect(await db.select().from(issueRecoveryActions)).toHaveLength(1);
expect(await db.select().from(issueComments)).toHaveLength(1);
const second = await recovery.reconcileStrandedAssignedIssues();
expect(second.escalated).toBe(0);
expect(await db.select().from(agentWakeupRequests)).toHaveLength(1);
expect(mockAdapterExecute).not.toHaveBeenCalled();
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]).toMatchObject({ status: "blocked", assigneeAgentId: agentId });
} finally {
await singleConnectionDb.$client.end({ timeout: 1 });
}
});
it("keeps resolved dependency wake reconciliation active", async () => {
const { companyId, agentId, blockedIssueId, blockerIssueId } =
await seedResolvedDependencyBackstopFixture({ workspaceState: "none" });
+128 -1
View File
@@ -178,7 +178,7 @@ if (!support.supported) console.warn(`Skipping idle sleep Postgres tests: ${supp
const companyId = randomUUID();
const agentId = randomUUID();
const runId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Idle test", issuePrefix: "IDLE" });
await db.insert(companies).values({ id: companyId, name: "Idle test", issuePrefix: `T${companyId.slice(0, 6).toUpperCase()}` });
await db.insert(agents).values({ id: agentId, companyId, name: "On-demand agent", role: "engineer", status: "idle", adapterType: "process" });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "on_demand", status: "succeeded" });
return { companyId, agentId, runId };
@@ -246,6 +246,44 @@ if (!support.supported) console.warn(`Skipping idle sleep Postgres tests: ${supp
expect(await read()).toEqual(present);
});
it("allows consumed coalesced wakes only after their linked run finishes", async () => {
const { companyId, agentId, runId } = await seed();
await db.update(heartbeatRuns).set({ status: "running" }).where(eq(heartbeatRuns.id, runId));
await db.insert(agentWakeupRequests).values({
companyId, agentId, source: "assignment", status: "coalesced", runId, finishedAt: new Date(now),
});
expect(await read()).toEqual(present);
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date(now) })
.where(eq(heartbeatRuns.id, runId));
expect(await read()).toEqual(none);
});
it.each(["unfinished", "missing_run", "wrong_company", "wrong_agent", "unfinished_run", "retry", "accounting"])(
"keeps a coalesced wake awake with %s evidence", async kind => {
const { companyId, agentId, runId } = await seed();
await db.update(heartbeatRuns).set({ finishedAt: new Date(now) }).where(eq(heartbeatRuns.id, runId));
let linkedRunId = runId;
if (kind === "missing_run") linkedRunId = randomUUID();
if (kind === "wrong_company") {
linkedRunId = (await seed()).runId;
await db.update(heartbeatRuns).set({ finishedAt: new Date(now) }).where(eq(heartbeatRuns.id, linkedRunId));
}
if (kind === "wrong_agent") {
const otherAgentId = randomUUID();
await db.insert(agents).values({ id: otherAgentId, companyId, name: "Other agent", role: "engineer", status: "idle", adapterType: "process" });
await db.update(heartbeatRuns).set({ agentId: otherAgentId }).where(eq(heartbeatRuns.id, runId));
}
if (kind === "unfinished_run") await db.update(heartbeatRuns).set({ finishedAt: null }).where(eq(heartbeatRuns.id, runId));
if (kind === "retry") await db.update(heartbeatRuns).set({ scheduledRetryAt: new Date(now + 1000) }).where(eq(heartbeatRuns.id, runId));
if (kind === "accounting") await db.update(heartbeatRuns).set({ costAccountingPending: true }).where(eq(heartbeatRuns.id, runId));
await db.insert(agentWakeupRequests).values({
companyId, agentId, source: "assignment", status: "coalesced", runId: linkedRunId,
finishedAt: kind === "unfinished" ? null : new Date(now),
});
expect(await read()).toEqual(present);
},
);
it("blocks an active routine without waiting for its next due time", async () => {
const { companyId } = await seed();
await db.insert(routines).values({ companyId, title: "Tomorrow", status: "active" });
@@ -268,6 +306,95 @@ if (!support.supported) console.warn(`Skipping idle sleep Postgres tests: ${supp
expect(await read()).toEqual(present);
});
async function seedFinishedLogin() {
const { companyId } = await seed();
const [environment] = await db.insert(environments).values({ name: "Finished login fixture" }).returning();
const [lease] = await db.insert(environmentLeases).values({
companyId, environmentId: environment!.id, providerLeaseId: "fixture-login-resource",
status: "released", cleanupStatus: "success", releasedAt: new Date(now),
}).returning();
const [session] = await db.insert(adapterAuthSessions).values({
companyId, environmentId: environment!.id, adapterType: "codex_local",
startedByUserId: "fixture-user", publicSessionId: "finished-fixture-session",
status: "authenticated", finishedAt: new Date(now), providerLeaseId: lease!.providerLeaseId,
}).returning();
return { companyId, environment: environment!, lease: lease!, session: session! };
}
it.each(["authenticated", "completed", "failed", "timed_out", "cancelled"] as const)(
"permits finished %s login history after confirmed provider cleanup", async status => {
const { session } = await seedFinishedLogin();
await db.update(adapterAuthSessions).set({ status }).where(eq(adapterAuthSessions.id, session.id));
expect(await read()).toEqual(none);
},
);
it.each(["canonical", "uppercase"])("accepts a %s cleanup reference to the internal lease id", async format => {
const { session, lease } = await seedFinishedLogin();
await db.update(adapterAuthSessions).set({ providerLeaseId: format === "uppercase" ? lease.id.toUpperCase() : lease.id })
.where(eq(adapterAuthSessions.id, session.id));
expect(await read()).toEqual(none);
});
it.each(["fixture-provider-id", "00000000-0000-0000-0000-00000000000z", randomUUID()])(
"accepts cleaned external provider reference %s without an unsafe UUID cast", async providerLeaseId => {
const { session, lease } = await seedFinishedLogin();
await db.update(environmentLeases).set({ providerLeaseId }).where(eq(environmentLeases.id, lease.id));
await db.update(adapterAuthSessions).set({ providerLeaseId }).where(eq(adapterAuthSessions.id, session.id));
expect(await read()).toEqual(none);
},
);
it("keeps a UUID-shaped external reference awake when an internal lease conflicts", async () => {
const { companyId, environment, session, lease } = await seedFinishedLogin();
const conflictingId = randomUUID();
await db.update(environmentLeases).set({ providerLeaseId: conflictingId }).where(eq(environmentLeases.id, lease.id));
await db.update(adapterAuthSessions).set({ providerLeaseId: conflictingId }).where(eq(adapterAuthSessions.id, session.id));
await db.insert(environmentLeases).values({
id: conflictingId, companyId, environmentId: environment.id,
status: "released", cleanupStatus: "failed", releasedAt: new Date(now),
});
expect(await read()).toEqual(present);
await db.update(environmentLeases).set({ cleanupStatus: "success" }).where(eq(environmentLeases.id, conflictingId));
expect(await read()).toEqual(none);
});
it("permits terminal login history without a provider resource", async () => {
const { session } = await seedFinishedLogin();
await db.update(adapterAuthSessions).set({ providerLeaseId: null }).where(eq(adapterAuthSessions.id, session.id));
expect(await read()).toEqual(none);
});
it.each(["cleanup_pending", "starting", "promoting", "awaiting_code", "submitting", "stored"] as const)(
"retains %s login work even with an old successful cleanup receipt", async status => {
const { session } = await seedFinishedLogin();
await db.update(adapterAuthSessions).set({ status }).where(eq(adapterAuthSessions.id, session.id));
expect(await read()).toEqual(present);
},
);
it.each(["unfinished", "promotion_claim", "missing_lease", "wrong_company", "wrong_environment", "cleanup_failed", "cleanup_unknown", "unreleased", "conflicting_lease"])(
"retains terminal login history with %s cleanup evidence", async kind => {
const { companyId, session, lease, environment } = await seedFinishedLogin();
if (kind === "unfinished") await db.update(adapterAuthSessions).set({ finishedAt: null }).where(eq(adapterAuthSessions.id, session.id));
if (kind === "promotion_claim") await db.update(adapterAuthSessions).set({ promotionExpiresAt: new Date(now + 1000) }).where(eq(adapterAuthSessions.id, session.id));
if (kind === "missing_lease") await db.delete(environmentLeases).where(eq(environmentLeases.id, lease.id));
if (kind === "wrong_company") await db.update(environmentLeases).set({ companyId: (await seed()).companyId }).where(eq(environmentLeases.id, lease.id));
if (kind === "wrong_environment") {
const [other] = await db.insert(environments).values({ name: "Other environment", driver: "sandbox" }).returning();
await db.update(environmentLeases).set({ environmentId: other!.id }).where(eq(environmentLeases.id, lease.id));
}
if (kind === "cleanup_failed") await db.update(environmentLeases).set({ cleanupStatus: "failed" }).where(eq(environmentLeases.id, lease.id));
if (kind === "cleanup_unknown") await db.update(environmentLeases).set({ cleanupStatus: null }).where(eq(environmentLeases.id, lease.id));
if (kind === "unreleased") await db.update(environmentLeases).set({ releasedAt: null }).where(eq(environmentLeases.id, lease.id));
if (kind === "conflicting_lease") await db.insert(environmentLeases).values({
companyId, environmentId: environment.id, providerLeaseId: lease.providerLeaseId,
status: "released", cleanupStatus: "failed", releasedAt: new Date(now),
});
expect(await read()).toEqual(present);
},
);
it("reports a pending secret proposal with future expiry", async () => {
const { companyId, agentId, runId } = await seed();
await db.insert(companySecretProposals).values({
@@ -3,6 +3,15 @@ import { CHAT_PROVIDERS, updateChatEndpointSchema } from "@paperclipai/shared";
import { buildChatCommunicationGuidance } from "./chat-communication-guidance.js";
describe("initial medium communication guidance", () => {
it.each([true, false])("requires result and review updates in Slack (direct=%s)", (isDirectMessage) => {
const guidance = buildChatCommunicationGuidance({ provider: "slack", isDirectMessage });
expect(guidance).toContain("When you have results, update the user in the originating Slack");
expect(guidance).toContain("Put this update in your final response");
expect(guidance).toContain("When the user needs to review a plan, approve an action, or review a result");
expect(guidance).toContain("create the required human-input or approval interaction before you yield");
expect(guidance).toContain("do not continue gated work until the required approval is recorded");
});
it("guides Slack presentation while retaining ordinary agent tools and explicit output requests", () => {
const guidance = buildChatCommunicationGuidance({ provider: "slack", isDirectMessage: false, communicationInstructions: "Use customer-facing names." });
expect(guidance).toContain("shared channel thread");
@@ -24,6 +33,15 @@ describe("initial medium communication guidance", () => {
expect(guidance).toContain("Protected approvals must be completed in Paperclip");
});
it.each([false, true])("requires public links for created Slack tasks (DM: %s)", (isDirectMessage) => {
const guidance = buildChatCommunicationGuidance({ provider: "slack", isDirectMessage });
expect(guidance).toContain("include a clickable link to each created task");
expect(guidance).toContain("task identifier or title as the link text");
expect(guidance).toContain("public task URL returned by Paperclip tools or supplied in task context");
expect(guidance).toContain("never guess a URL");
expect(guidance).toContain("If no public task URL is available, say that the link is unavailable");
});
it.each(CHAT_PROVIDERS.filter((provider) => provider !== "slack" && provider !== "speko"))("leaves %s unchanged", (provider) => {
expect(buildChatCommunicationGuidance({ provider, isDirectMessage: false, communicationInstructions: "Ignored" })).toBeNull();
});
@@ -1,5 +1,6 @@
import { SPEKO_COMMUNICATION_GUIDANCE } from "./voice/speko-skill.js";
import type { ChatProvider } from "@paperclipai/shared";
import { slackTaskUpdateGuidance } from "./connectors/slack/task-update-guidance.js";
// Presentation guidance only. Task execution and permissions belong to the
// ordinary Paperclip agent runtime, not the provider transport.
@@ -7,8 +8,10 @@ const providerGuidance: Partial<Record<ChatProvider, string>> = {
speko: SPEKO_COMMUNICATION_GUIDANCE,
slack: [
"This task began in Slack. Write replies for the person talking with you there.",
...slackTaskUpdateGuidance,
"Lead with the answer or outcome. Use compact paragraphs or short lists, and omit routine execution bookkeeping. Honor requests for more detail or exact output over default brevity.",
"Put small answers directly in the message. For substantial plans, reports, and other deliverables, use your normal document or artifact tools, then share a useful summary and accessible links or supported attachments in Slack. Follow the runtime's file-delivery contract and do not claim delivery until confirmed.",
"When you create tasks, include a clickable link to each created task in your reply. Use the task identifier or title as the link text, not a bare task ID. Use the public task URL returned by Paperclip tools or supplied in task context; never guess a URL or use a localhost, API, or sandbox address. If no public task URL is available, say that the link is unavailable.",
"Ask useful questions through the existing human-input tools. Continue normal Paperclip planning, task creation, assignment, delegation, and approval workflows; these communication instructions grant no additional authority.",
].join("\n\n"),
};
@@ -1,4 +1,5 @@
import { slackAppConfigurationSchema } from "@paperclipai/shared";
import { slackTaskUpdateGuidance } from "./task-update-guidance.js";
// Per-turn routing guidance, including resumed CLI sessions. This describes
// existing capabilities; it never grants tools or overrides action policies.
@@ -7,6 +8,7 @@ export function slackChatAgentGuidance(nativeRunner: boolean, savedCommand?: str
return [
"",
"Slack replies and actions:",
...slackTaskUpdateGuidance,
"Paperclip delivers your final response to the originating Slack conversation. Use assigned Slack action tools for an explicitly requested post, edit, reaction, pin, bookmark, canvas, list, or channel operation. Do not post a second copy of your ordinary reply with slack_post_message.",
"For a requested file in this conversation, follow the external-chat file-delivery contract below. slack_upload_file is for explicitly uploading an existing Paperclip attachment to another allowed destination. Neither queued nor uncertain means delivered; retain the original operation key and inspect its receipt instead of starting the write again.",
"Use only the tools assigned to this run and honor their action policies. Missing tools or Slack permissions are a capability limitation; never ask for a bot token or use another bot to work around it.",
@@ -0,0 +1,5 @@
// Shared by initial conversation guidance and every later Slack turn.
export const slackTaskUpdateGuidance = [
"When you have results, update the user in the originating Slack channel thread or direct conversation. Include the outcome and accessible links or supported attachments. Do not leave results only in a Paperclip task, document, or work product. Put this update in your final response so Paperclip can deliver it; do not send a duplicate with slack_post_message.",
"When the user needs to review a plan, approve an action, or review a result, notify them in the same Slack conversation. State what needs review, include the saved review link when available, and explain the action they must take. Follow the normal workflow to save the artifact and create the required human-input or approval interaction before you yield. Saving a plan or setting a task to in_review alone does not ask the user to review it. Do not claim notification or delivery without a successful receipt, and do not continue gated work until the required approval is recorded.",
];
@@ -150,6 +150,7 @@ import {
reviewPathConsumedRefFromRun,
} from "../recovery/review-path-recovery.js";
import { resolveRequiredSuccessfulRunHandoffOnValidPath } from "../successful-run-handoff-state.js";
import { escalateExhaustedIssueReviewPathRecovery } from "../recovery/review-path-recovery-escalation.js";
import {
redactCurrentUserText,
redactCurrentUserValue,
@@ -1987,6 +1988,10 @@ export function createHeartbeatLifecycle(db: Db, dependencies: HeartbeatLifecycl
reviewAttention,
existingWake: Boolean(existingWake),
});
if (decision.kind === "exhausted") {
await escalateExhaustedIssueReviewPathRecovery(db, { run, issueId: issue.id });
return;
}
if (decision.kind !== "enqueue") return;
const recoveryRun = await enqueueWakeup(issue.assigneeAgentId, {
+34 -3
View File
@@ -45,8 +45,16 @@ const WORK_CHECKS = [
`SELECT 1 FROM agent_api_keys WHERE revoked_at IS NULL`,
`SELECT 1 FROM board_api_keys WHERE revoked_at IS NULL
AND (expires_at IS NULL OR expires_at > now())`,
`SELECT 1 FROM agent_wakeup_requests WHERE
status NOT IN ('completed', 'failed', 'cancelled', 'skipped', 'timed_out')`,
// Coalescing consumes a request into another run. Retain it as work until
// both the request and that exact company/agent's run have finished.
`SELECT 1 FROM agent_wakeup_requests w WHERE
w.status NOT IN ('completed', 'failed', 'cancelled', 'skipped', 'timed_out', 'coalesced')
OR (w.status = 'coalesced' AND (w.finished_at IS NULL OR NOT EXISTS (
SELECT 1 FROM heartbeat_runs r WHERE r.id = w.run_id
AND r.company_id = w.company_id AND r.agent_id = w.agent_id
AND r.status IN ('succeeded', 'failed', 'cancelled', 'timed_out', 'interrupted')
AND r.finished_at IS NOT NULL AND r.scheduled_retry_at IS NULL
AND r.cost_accounting_pending = false)))`,
`SELECT 1 FROM issues WHERE status NOT IN ('done', 'cancelled')`,
// A completed issue can still need its first watchdog review, including a
// retry after immediate evaluation failed before creating a review/run.
@@ -62,6 +70,29 @@ const WORK_CHECKS = [
`SELECT 1 FROM issue_recovery_actions WHERE status NOT IN ('resolved', 'cancelled')`,
`SELECT 1 FROM status_cards WHERE archived_at IS NULL`,
`SELECT 1 FROM external_objects WHERE NOT is_terminal OR next_refresh_at IS NOT NULL`,
// Login history keeps its provider reference after teardown. A terminal
// label alone is insufficient: require a finished, unclaimed session and
// positive cleanup evidence for its resource in the same company/environment.
// Cast only UUID-shaped session references, leaving both lease indexes usable.
`SELECT 1 FROM adapter_auth_sessions s WHERE
s.status NOT IN ('authenticated', 'completed', 'failed', 'timed_out', 'cancelled')
OR s.finished_at IS NULL OR s.promotion_expires_at IS NOT NULL
OR (s.provider_lease_id IS NOT NULL AND NOT EXISTS (
SELECT 1 FROM environment_leases l WHERE l.company_id = s.company_id
AND l.environment_id = s.environment_id
AND (l.provider_lease_id = s.provider_lease_id OR l.id = CASE
WHEN s.provider_lease_id ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
THEN s.provider_lease_id::uuid END)
AND l.status IN ('released', 'expired') AND l.cleanup_status = 'success'
AND l.released_at IS NOT NULL))
OR (s.provider_lease_id IS NOT NULL AND EXISTS (
SELECT 1 FROM environment_leases l WHERE l.company_id = s.company_id
AND l.environment_id = s.environment_id
AND (l.provider_lease_id = s.provider_lease_id OR l.id = CASE
WHEN s.provider_lease_id ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
THEN s.provider_lease_id::uuid END)
AND (l.status IN ('released', 'expired') AND l.cleanup_status = 'success'
AND l.released_at IS NOT NULL) IS NOT TRUE))`,
// These less common work sources fail closed on any retained state. Their
// terminal-state exceptions can be added with tests for the owning service.
...[
@@ -73,7 +104,7 @@ const WORK_CHECKS = [
"native_run_finalizations", "company_transfer_runs", "decisions", "decision_effect_executions",
"decision_archive_notification_outbox", "browser_use_sessions", "browser_use_runs",
"browser_use_browsers", "environment_custom_image_setup_sessions", "feedback_exports",
"adapter_auth_sessions", "company_secret_proposals", "execution_workspaces",
"company_secret_proposals", "execution_workspaces",
"mcp_oauth_grants", "mcp_mutation_receipts", "mcp_event_subscriptions",
"mcp_event_deliveries", "mcp_attachment_uploads", "dot_agent_bindings",
"dot_runner_assignments", "dot_runner_operations", "dot_mailbox_items",
@@ -194,10 +194,11 @@ function monitorFromIssue(issue: IssueLivenessIssueInput) {
return { policyMonitor, stateMonitor };
}
export function hasScheduledIssueMonitorPath(issue: IssueLivenessIssueInput, now: Date | string | number) {
/** A saved, unconsumed check remains dispatchable when its due time passes. */
export function hasUnconsumedIssueMonitorPath(issue: IssueLivenessIssueInput, now: Date | string | number) {
const nowMs = typeof now === "number" ? now : readDateMs(now) ?? Date.now();
const nextCheckAtMs = readDateMs(issue.monitorNextCheckAt);
if (nextCheckAtMs === null || nextCheckAtMs <= nowMs) return false;
if (nextCheckAtMs === null) return false;
const { policyMonitor, stateMonitor } = monitorFromIssue(issue);
const timeoutAtMs = readDateMs(policyMonitor?.timeoutAt ?? stateMonitor?.timeoutAt);
@@ -211,6 +212,12 @@ export function hasScheduledIssueMonitorPath(issue: IssueLivenessIssueInput, now
return true;
}
export function hasScheduledIssueMonitorPath(issue: IssueLivenessIssueInput, now: Date | string | number) {
const nowMs = typeof now === "number" ? now : readDateMs(now) ?? Date.now();
const nextCheckAtMs = readDateMs(issue.monitorNextCheckAt);
return nextCheckAtMs !== null && nextCheckAtMs > nowMs && hasUnconsumedIssueMonitorPath(issue, nowMs);
}
export function classifyIssueReviewPaths(
input: IssueGraphLivenessInput,
issue: IssueLivenessIssueInput,
@@ -0,0 +1,134 @@
import { and, desc, eq, getTableColumns, or, sql } from "drizzle-orm";
import { agents, heartbeatRuns, issues, type Db } from "@paperclipai/db";
import { isWaitingConversation } from "../agent-conversations.js";
import { logActivity, publishActivity, type ActivityPublication } from "../activity-log.js";
import { issueRecoveryActionService } from "../issue-recovery-actions.js";
import { externalConversationStateSql } from "../slack-conversation-state.js";
import { isHeartbeatWakeOnDemandEnabled } from "../heartbeat-policy.js";
import {
executeIssuePostCommitActions,
issueService,
TERMINAL_HEARTBEAT_RUN_STATUSES,
type IssuePostCommitAction,
} from "../issues.js";
import {
buildIssueReviewPathLostIdempotencyKey,
decideIssueReviewPathRecovery,
ISSUE_REVIEW_PATH_LOST_WAKE_REASON,
reviewPathConsumedRefFromRun,
} from "./review-path-recovery.js";
import { buildStrandedRecoveryEscalationNotice } from "./stranded-notice.js";
import { hasUnconsumedIssueMonitorPath } from "./issue-graph-liveness.js";
/** A spent repair wake must leave an operator action, never another automatic wake. */
export async function escalateExhaustedIssueReviewPathRecovery(
db: Db,
input: { run: typeof heartbeatRuns.$inferSelect; issueId: string },
) {
const { run, issueId } = input;
const publications: ActivityPublication[] = [];
const postCommitActions: IssuePostCommitAction[] = [];
const action = await db.transaction(async (tx) => {
// Services must use the transaction connection for implicit settings reads
// too; borrowing the outer pool deadlocks when its only connection is held.
const issuesSvc = issueService(tx as unknown as Db);
// Share the issue fence with ownership, monitor, and interaction updates.
// Re-read the disposition under the lock rather than blocking a repaired task.
const issue = await tx.select({ ...getTableColumns(issues), externalConversationState: externalConversationStateSql() }).from(issues)
.where(and(eq(issues.companyId, run.companyId), eq(issues.id, issueId)))
.for("update").then((rows) => rows[0] ?? null);
if (!issue || issue.status !== "in_review" || issue.assigneeAgentId !== run.agentId
|| issue.assigneeUserId || isWaitingConversation(issue)
|| issue.externalConversationState === "waiting") return null;
// Startup recovery precedes monitor ticks. Preserve a due or claimed check
// only while the owner still allows the on-demand wake used by dispatch.
// Otherwise the dispatcher leaves it overdue indefinitely without consuming it.
if (hasUnconsumedIssueMonitorPath(issue, new Date())) {
const owner = await tx.select({ runtimeConfig: agents.runtimeConfig }).from(agents)
.where(and(eq(agents.companyId, run.companyId), eq(agents.id, issue.assigneeAgentId)))
.then((rows) => rows[0] ?? null);
if (owner && isHeartbeatWakeOnDemandEnabled(owner)) return null;
}
const attention = (await issuesSvc.listReviewAttention(run.companyId, [issue], tx)).get(issueId);
if (!attention || decideIssueReviewPathRecovery({
issueId,
sourceRunId: run.id,
assigneeAgentId: issue.assigneeAgentId,
contextSnapshot: run.contextSnapshot,
reviewAttention: attention,
existingWake: false,
}).kind !== "exhausted") return null;
const latestRun = await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns)
.where(and(eq(heartbeatRuns.companyId, run.companyId), or(
eq(heartbeatRuns.issueId, issueId),
eq(heartbeatRuns.nativeIssueId, issueId),
sql`coalesce(${heartbeatRuns.contextSnapshot}->>'issueId', ${heartbeatRuns.contextSnapshot}->>'taskId') = ${issueId}`,
)))
.orderBy(desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id)).limit(1)
.then((rows) => rows[0] ?? null);
if (latestRun?.id !== run.id || !TERMINAL_HEARTBEAT_RUN_STATUSES.has(run.status)) return null;
const consumedPathRef = reviewPathConsumedRefFromRun({
runId: run.id, issueId, contextSnapshot: run.contextSnapshot,
});
const nextAction = "Inspect the run, then restore a scheduled check or review path, retry the original assignee, or record an intentional resolution.";
const recoveryAction = await issueRecoveryActionService(tx as unknown as Db).upsertSourceScoped({
companyId: run.companyId,
sourceIssueId: issueId,
kind: "missing_disposition",
ownerType: "board",
previousOwnerAgentId: run.agentId,
returnOwnerAgentId: run.agentId,
cause: ISSUE_REVIEW_PATH_LOST_WAKE_REASON,
fingerprint: buildIssueReviewPathLostIdempotencyKey({ issueId, consumedPathRef }),
evidence: {
correctiveRunId: run.id,
consumedPathRef,
previousStatus: "in_review",
recoveryAttempt: 1,
maxRecoveryAttempts: 1,
},
nextAction,
wakePolicy: { type: "board_escalation", preservesSourceAssignee: true },
attemptCount: 1,
maxAttempts: 1,
lastAttemptAt: run.finishedAt ?? new Date(),
});
await issuesSvc.update(issueId, {
status: "blocked", companyGuard: run.companyId,
}, tx, publications, postCommitActions);
const notice = buildStrandedRecoveryEscalationNotice({
seed: {
title: "No follow-up scheduled",
tone: "danger",
body: "The automatic review-path repair finished without saving a scheduled check, reviewer, approval, or other maintained path. Paperclip has blocked this task for a board decision; no further automatic follow-up is scheduled.",
nextAction,
},
recoveryCause: ISSUE_REVIEW_PATH_LOST_WAKE_REASON,
recoveryActionId: recoveryAction.id,
recoveryOwner: null,
sourceRun: { id: run.id, agentId: run.agentId, status: run.status },
});
const comment = await issuesSvc.addComment(issueId, notice.body, {}, {
authorType: "system", presentation: notice.presentation, metadata: notice.metadata,
}, tx);
await logActivity(tx as unknown as Db, {
companyId: run.companyId,
actorType: "system",
actorId: "heartbeat",
agentId: run.agentId,
runId: run.id,
action: "issue.review_path_recovery_exhausted",
entityType: "issue",
entityId: issueId,
details: { recoveryActionId: recoveryAction.id, commentId: comment.id, consumedPathRef, recoveryAttempt: 1, maxRecoveryAttempts: 1 },
}, publications);
return recoveryAction;
});
for (const publication of publications) publishActivity(publication);
await executeIssuePostCommitActions(db, postCommitActions);
return action;
}
@@ -139,20 +139,20 @@ describe("review-path recovery", () => {
},
);
it("does not requeue when the bounded recovery run also ends pathless", () => {
it.each([
{ wakeReason: ISSUE_REVIEW_PATH_LOST_WAKE_REASON },
{ reviewPathRecoveryAttempt: 1 },
])("requires escalation when the bounded recovery run also ends pathless (%j)", (contextSnapshot) => {
const decision = decideIssueReviewPathRecovery({
issueId: "issue-1",
sourceRunId: "run-2",
assigneeAgentId: "agent-1",
contextSnapshot: {
wakeReason: ISSUE_REVIEW_PATH_LOST_WAKE_REASON,
reviewPathRecoveryAttempt: 1,
},
contextSnapshot,
reviewAttention: stalled,
existingWake: false,
});
expect(decision).toEqual({ kind: "skip", reason: "bounded review-path recovery already ran" });
expect(decision).toEqual({ kind: "exhausted" });
});
it("never wakes a healthy review", () => {
@@ -6,13 +6,18 @@ import { withRecoveryContext } from "./status-only-context.js";
export const ISSUE_REVIEW_PATH_LOST_WAKE_REASON = "issue_review_path_lost";
export const REVIEW_PATH_RECOVERY_INSTRUCTION =
"This issue is still in review but its last maintained review path was consumed. Restore a reviewer, interaction, approval, monitor, or other durable waiting path, or choose an explicit disposition. This is the only automatic review-path recovery wake for this fingerprint.";
"This issue is still in review but its last maintained review path was consumed. Restore a reviewer, interaction, approval, monitor, or other durable waiting path, or choose an explicit disposition. If an async check is still pending, persist a one-shot issue monitor before ending this run and report its scheduled check time. A promise to check later or a background watcher is not a maintained review path. This is the only automatic review-path recovery wake for this fingerprint; ending without a maintained path will require a board decision.";
const REVIEW_PATH_RECOVERY_IDEMPOTENCY_INDEX = "agent_wakeup_requests_review_path_recovery_idempotency_uq";
function readNonEmptyString(value: unknown) {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
}
export function isIssueReviewPathRecoveryRun(contextSnapshot: Record<string, unknown> | null | undefined) {
return readNonEmptyString(contextSnapshot?.wakeReason) === ISSUE_REVIEW_PATH_LOST_WAKE_REASON
|| contextSnapshot?.reviewPathRecoveryAttempt === 1;
}
export function reviewPathConsumedRefFromRun(input: {
runId: string;
issueId: string;
@@ -68,6 +73,7 @@ export type IssueReviewPathRecoveryDecision =
payload: Record<string, unknown>;
contextSnapshot: Record<string, unknown>;
}
| { kind: "exhausted" }
| { kind: "skip"; reason: string };
export function decideIssueReviewPathRecovery(input: {
@@ -84,11 +90,8 @@ export function decideIssueReviewPathRecovery(input: {
}
const context = input.contextSnapshot ?? {};
if (
readNonEmptyString(context.wakeReason) === ISSUE_REVIEW_PATH_LOST_WAKE_REASON
|| context.reviewPathRecoveryAttempt === 1
) {
return { kind: "skip", reason: "bounded review-path recovery already ran" };
if (isIssueReviewPathRecoveryRun(context)) {
return { kind: "exhausted" };
}
const consumedPathRef = reviewPathConsumedRefFromRun({
+17
View File
@@ -4,6 +4,8 @@ import { hasCommittedNativePlanWait } from "../native-runtime/native-plan-wait.j
import { isNativeWorkspaceExportRepairCause } from "@paperclipai/shared";
import { settleSlackConversation } from "../slack-conversation-lifecycle.js";
import { externalConversationStateSql } from "../slack-conversation-state.js";
import { isIssueReviewPathRecoveryRun } from "./review-path-recovery.js";
import { escalateExhaustedIssueReviewPathRecovery } from "./review-path-recovery-escalation.js";
import { executionRetryAccounting } from "../execution-recovery-attempt.js";
import { isExplicitContinuationRetryClaim } from "../explicit-continuation-retry-claim.js";
import {
@@ -4472,6 +4474,21 @@ export function recoveryService(
}
let latestRun = await getLatestIssueRun(issue.companyId, issue.id);
// Terminal run/wake rows survive a restart even if finalization never
// reached the escalation transaction. Retry that idempotent disposition
// before the participant-only review branch can skip pathless reviews.
if (issue.status === "in_review" && latestRun
&& isTerminalIssueRun(latestRun)
&& isIssueReviewPathRecoveryRun(latestRun.contextSnapshot)) {
const [repairRun] = await db.select().from(heartbeatRuns).where(and(
eq(heartbeatRuns.companyId, issue.companyId), eq(heartbeatRuns.id, latestRun.id),
));
if (repairRun && await escalateExhaustedIssueReviewPathRecovery(db, { run: repairRun, issueId: issue.id })) {
result.escalated += 1;
result.issueIds.push(issue.id);
continue;
}
}
// A native chat can finish between the earlier settlement read and this
// fresh run read, before its response is materialized. Its trusted
// finalizer owns that settlement; generic productive-work recovery must