mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 18:35:33 +01:00
## Thinking Path > - Paperclip manages AI agents doing work for people. > - Agent verification must finish before an accepted task can start. > - A missing AI account default can prevent verification before a provider starts. > - Lifecycle policy treated that owned configuration refusal as a temporary failure and retried each minute. > - The accepted turn remained Queued without explaining the prerequisite. > - Park account configuration failures and reuse the task's existing inline connection card. > - Successful repair rechecks verification and releases the original queued turn under its original authority. ## Linked Issues or Issue Description **What happened?** An OpenCode agent selected the responsible user's OpenRouter default, but that default did not exist. Verification retried unchanged configuration indefinitely and its accepted task stayed Queued. **Expected behavior:** Preserve accepted work, explain the setup prerequisite, and let the appropriate person repair it using the existing task connection UI. Completion must verify the agent before starting the same queued turn. Genuine pause, approval and access gates remain effective. **Reproduction:** Create an OpenCode Runner agent with a responsible-user OpenRouter binding and no personal default; assign a task while verification is pending. The base retries verification and shows an unexplained queue. Related: #18702 handles pending task connection recovery after account repair. This PR handles the earlier agent-verification boundary. #20330 addresses a separate Codex governed-wait timeout and is already merged. ## What Changed - Share owned account-selection failure evidence through a pure library contract. Lifecycle policy parks those configuration failures with fixed, redacted guidance; temporary infrastructure errors retain their retries. - Batch setup-state reads for unstarted queued turns. Distinguish manual repair from automatic setup retries and preserve Stop, started/history state and lifecycle holds. - Reuse the existing `connection_intent` card, account selection and completion APIs. Its controller-only `agentSetup` marker accepts only never-started legacy turns; runtime tokens still require a running run. - Address the card to the lifecycle verifier's account owner, preserving the task's execution principal and private-task visibility. Attach missing cards on admission, verification, startup and full recovery, including retained retries and continuations. Repeated delivery and publication remain bounded. A new queued turn supersedes the setup card of a stopped turn; generic connection cards retain cross-run reuse. - Recheck lifecycle verification after usable-account completion, then release the existing turn through the normal readiness path. Preserve decline, Stop, reassignment and changed setup-owner gates. Fence an in-flight verification failure from overwriting a repair; add no provider wake or recurring worker. - Park owned account refusals during resume as well as initial verification. Bind setup cards to the lifecycle operation, settle obsolete deliveries, and keep explicit Retry guidance accurate. - Reuse the router’s existing lifecycle pin for setup repair without rerouting the task, advancing the pool cursor, or replacing its saved binding. Legacy direct-account cards remain readable. - Hide the incorrect Resume banner during setup, retaining genuine manual/budget pause controls. Document the execution and retry contract. ## Verification - Red: eight original behavior assertions failed on the base, including the real selector's retry decision and the real batched queue projection. Six owned selection cases failed classification. Temporary-error presentation, different task/verifier users, retained retry/continuation recovery and the setup Resume banner also have failing-before/passing-after regressions. - Green: 430 affected backend, lifecycle, shared-contract and UI tests passed before the final review corrections. Subsequent focused runs cover one inline card, real account selection/completion, duplicate delivery/publication, verification before readiness, unchanged run authority, private tasks, no extra provider wake, decline/Stop/reassignment, company isolation, invalid runtime tokens, transient retries and redacted diagnostics. - Final setup/card and generic connection-service suites: 49 tests passed. The stopped-turn case failed before the correction, then passed with real account completion, the stopped source remaining cancelled, and the replacement source remaining queued. - After rebase, all 129 focused assertions passed. The local queue suite’s 88 execution assertions passed repeatedly, but its database-fixture teardown exceeded both 30-second and 120-second hooks. An isolated queue case completed, and the setup/connection suites fully passed. The original queue test and cleanup remain unchanged; broad CI supplies the full-suite result. - Server/UI typechecks, module boundaries, token gates and diff checks passed. `pnpm verify --explain` requested broad CI because the execution-contract document changed; no redundant full local suite was substituted. - Real source acceptance: macOS arm64, Node 26.4.0, isolated embedded PostgreSQL and local board identity. Created an OpenCode/OpenRouter agent and task through the API with no default. Admission retained one unstarted turn and produced the existing inline Connect OpenRouter card. The browser opened its credential form and closed it without entering credentials. The same card/run persisted after server restart and reload, with the setup label and no incorrect Resume. The browser also reproduced Stop followed by a new queued turn retaining the stale card on the prior head. On `12f609c98372fd1e50644028db75cfcc8deb210d`, startup superseded the stale card and retained the same replacement turn, with the original turn still cancelled and no provider execution. - The earlier CI case-search failure also reproduces on exact base `0e3fdebea8257bdff11573081c76b306f12db230` without this PR. Its repair is now in master via #20371; this branch is rebased onto it and contains no API-search changes. - Staging's actual Runtime test returned “Connect an account and choose your personal default” before provider startup. The original turn later started independently on deployed code, then hit a separate workspace-export failure. Automatic file recovery subsequently marked that run successful; its task remains Blocked and the trial’s useful output is unverified. This PR is not deployed; provider authentication through its card and downstream publication remain unverified. No account, credential, default, permission or binding was changed during diagnosis. - Previous revision review: Greptile 5/5 on `12f609c98372fd1e50644028db75cfcc8deb210d`, with all four inline findings addressed and resolved. [Full CI passed](https://github.com/paperclipai/paperclip/actions/runs/42713494508) on that revision: 59 successful checks, one neutral check and three intentional skips, with no pending or failed checks. - Latest revision `976bcae993805a8a2222395bbff9394f6791b424`: resume, router and Retry-copy regressions failed before repair. Green: 92 lifecycle/setup/shared tests, 83 setup/generic-connection/router tests, and 137 UI/shared tests. Server/UI typechecks, module boundaries and token gates passed. [Full CI passed](https://github.com/paperclipai/paperclip/actions/runs/42720731137) on this exact revision: 59 successful checks and three intentional skips, with no pending or failed checks. Greptile reviewed this head at 5/5; all six review findings are addressed and resolved. Real Stop/retry acceptance retained the same replacement turn and current-operation card through two actual server restarts, with no provider execution. ## Risks - Known account configuration failures now require repair or explicit Retry. Temporary failures keep automatic retries; accepted work and authority remain intact. - The projection adds one company-scoped batch read only for unstarted queued turns. Card attachment examines at most 100 active candidates and adds no timer, worker, schema or migration. - The optional stored setup-card marker requires an aware reader during rollback. No run/session/checkpoint identity format changes. Setup presentation grants no access and cannot bypass verification or other gates. ## Model Used - OpenAI GPT-6 (Codex), with reasoning, tool use, code editing and test execution. The exact serving model identifier and context-window size are not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
457 lines
28 KiB
TypeScript
457 lines
28 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { agents, companies, companyMemberships, createDb, applyPendingMigrations, closeRegisteredClients, type Db } from "@paperclipai/db";
|
|
import { eq, sql } from "drizzle-orm";
|
|
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js";
|
|
import { createAgentLifecycle, configureAgentLifecycle } from "../../../services/agent-lifecycle.js";
|
|
import { createAgentLifecycleEffects } from "../../../services/agent-lifecycle.js";
|
|
import { requestAgentLifecycleRecheckInTransaction, startAgentLifecycle } from "../index.js";
|
|
import { createLifecycleStore } from "../adapters/postgres.js";
|
|
import { createLifecycleWorker } from "../application/worker.js";
|
|
import type { LifecycleAgent } from "../application/ports.js";
|
|
import { DELIVERY_QUEUES, notifyDeliveryWork } from "../../../services/delivery-work-notifications.js";
|
|
import { resolveExternalTestDatabaseUrl } from "../../../__tests__/helpers/external-test-database.js";
|
|
|
|
import { aiConnectionService } from "../../../services/ai-connections.js";
|
|
|
|
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_LIFECYCLE_VERIFICATION_RETRY_TEST_DATABASE_URL");
|
|
const support = external ? { supported: true } : await getEmbeddedPostgresTestSupport();
|
|
(support.supported ? describe : describe.skip)("failed lifecycle verification retries", () => {
|
|
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
|
let db: Db;
|
|
let companyId: string;
|
|
const workers: Array<{ stop(): Promise<void> }> = [];
|
|
beforeAll(async () => {
|
|
if (external) { await applyPendingMigrations(external); db = createDb(external, { maxConnections: 4 }); }
|
|
else { database = await startEmbeddedPostgresTestDatabase("paperclip-verification-retry-"); db = createDb(database.connectionString, { maxConnections: 4 }); }
|
|
}, 90_000);
|
|
afterAll(async () => { if (external) await closeRegisteredClients(external); else await database?.cleanup(); });
|
|
beforeEach(async () => {
|
|
companyId = randomUUID();
|
|
await db.insert(companies).values({ id: companyId, name: "Verification retry", issuePrefix: `V${companyId.slice(0, 7)}` });
|
|
});
|
|
afterEach(async () => {
|
|
for (const worker of workers.splice(0)) await worker.stop();
|
|
// Retire only this test's synthetic records so later coordinator reads stay isolated.
|
|
await db.update(agents).set({ lifecycleState: "terminated", status: "terminated" }).where(eq(agents.companyId, companyId));
|
|
});
|
|
const current = async (id: string) => (await db.select().from(agents).where(eq(agents.id, id)))[0]!;
|
|
async function failed(code = "harness_test_failed") {
|
|
const runHost = vi.fn(async (agent: LifecycleAgent) => {
|
|
if (agent.lifecycleState === "verifying") throw Object.assign(new Error("private provider detail"), { code });
|
|
return "complete" as const;
|
|
});
|
|
const driver = { requiredPluginIds: async () => [], runHost, runPlugin: async () => "complete" as const };
|
|
const work = configureAgentLifecycle(db, driver); workers.push(work);
|
|
const agent = await createAgentLifecycle(db).requestHire(companyId, { name: "Retry fixture", adapterType: "process", adapterConfig: { command: "missing-command" } });
|
|
await work.process(agent.id);
|
|
if (code === "harness_test_failed") {
|
|
for (let retry = 0; retry < 2; retry++) {
|
|
expect((await current(agent.id)).lifecycleOperation?.retryRequired).toBeUndefined();
|
|
await db.update(agents).set({ lifecycleOperation: sql`${agents.lifecycleOperation} - 'retryAt'` }).where(eq(agents.id, agent.id));
|
|
await work.process(agent.id);
|
|
}
|
|
}
|
|
return { agent: await current(agent.id), work, driver, runHost };
|
|
}
|
|
|
|
it("parks a real missing-default selection across restart and permits repair through the normal ready handoff", async () => {
|
|
const userId = randomUUID();
|
|
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: userId, status: "active" });
|
|
let repaired = false;
|
|
const runHost = vi.fn(async (agent: LifecycleAgent) => {
|
|
if (agent.lifecycleState === "verifying" && !repaired) await aiConnectionService(db).select({
|
|
companyId, userId, agentId: agent.id, adapterType: "paperclip_runner", runnerProvider: "opencode",
|
|
model: "openrouter/deepseek/deepseek-v4.1-flash-1017",
|
|
binding: { mode: "responsible_user", provider: "openrouter", method: "api_key" },
|
|
});
|
|
return "complete" as const;
|
|
});
|
|
const onReady = vi.fn();
|
|
const driver = { requiredPluginIds: async () => [], runHost, runPlugin: async () => "complete" as const, onReady };
|
|
const work = configureAgentLifecycle(db, driver); workers.push(work);
|
|
const hired = await createAgentLifecycle(db).requestHire(companyId, { name: "Missing default", adapterType: "process" });
|
|
await work.process(hired.id);
|
|
const held = await current(hired.id);
|
|
expect(held).toMatchObject({ lifecycleState: "verifying", status: "paused", lifecycleOperation: { retryRequired: true } });
|
|
expect(held.lifecycleError).toContain("personal default");
|
|
expect(held.lifecycleError).not.toContain("retry automatically");
|
|
expect(held.lifecycleOperation).not.toHaveProperty("retryAt");
|
|
expect(onReady).not.toHaveBeenCalled();
|
|
await work.stop();
|
|
const restarted = startAgentLifecycle(db, createAgentLifecycleEffects(), driver, () => true); workers.push(restarted);
|
|
const calls = runHost.mock.calls.length;
|
|
expect(await restarted.hasPending()).toBe(false);
|
|
expect(restarted.nextRunAt()).toBeNull();
|
|
await restarted.sweep();
|
|
expect(runHost).toHaveBeenCalledTimes(calls);
|
|
// Repair and Retry must still pass verification before the normal ready handoff.
|
|
repaired = true;
|
|
await createAgentLifecycle(db).retry(hired.id);
|
|
await restarted.sweep();
|
|
expect(await current(hired.id)).toMatchObject({ lifecycleState: "ready", status: "idle", lifecycleError: null });
|
|
expect(onReady).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it("parks owned account failures after pause/resume and accepts a durable connection repair recheck", async () => {
|
|
const userId = randomUUID();
|
|
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: userId, status: "active" });
|
|
let repaired = false;
|
|
const runHost = vi.fn(async (agent: LifecycleAgent) => {
|
|
if (agent.lifecycleState === "resuming" && !repaired) await aiConnectionService(db).select({ companyId, userId,
|
|
agentId: agent.id, adapterType: "paperclip_runner", runnerProvider: "opencode",
|
|
model: "openrouter/deepseek/deepseek-v4.1-flash-1017", binding: { mode: "responsible_user", provider: "openrouter", method: "api_key" } });
|
|
return "complete" as const;
|
|
});
|
|
const onReady = vi.fn();
|
|
const driver = { requiredPluginIds: async () => [], runHost, runPlugin: async () => "complete" as const, onReady };
|
|
const lifecycle = createAgentLifecycle(db), work = configureAgentLifecycle(db, driver); workers.push(work);
|
|
const hired = await lifecycle.requestHire(companyId, { name: "Resume account repair", adapterType: "process" });
|
|
await work.process(hired.id);
|
|
await lifecycle.pauseAgent(hired.id); await work.process(hired.id);
|
|
expect((await current(hired.id)).lifecycleState).toBe("paused");
|
|
onReady.mockClear();
|
|
await lifecycle.resumeAgent(hired.id); await work.process(hired.id);
|
|
const held = await current(hired.id);
|
|
expect(held).toMatchObject({ lifecycleState: "resuming", lifecycleOperation: { retryRequired: true } });
|
|
expect(held.lifecycleOperation).not.toHaveProperty("retryAt");
|
|
await work.stop();
|
|
const restarted = startAgentLifecycle(db, createAgentLifecycleEffects(), driver, () => true); workers.push(restarted);
|
|
const calls = runHost.mock.calls.length;
|
|
expect(await restarted.hasPending()).toBe(false);
|
|
expect(restarted.nextRunAt()).toBeNull();
|
|
await restarted.sweep(); expect(runHost).toHaveBeenCalledTimes(calls);
|
|
repaired = true;
|
|
expect(await db.transaction(tx => requestAgentLifecycleRecheckInTransaction(tx, { companyId, agentId: hired.id,
|
|
configurationRepaired: true }, () => notifyDeliveryWork(tx, DELIVERY_QUEUES.agentLifecycle)))).toBe(true);
|
|
await restarted.sweep();
|
|
expect((await current(hired.id)).lifecycleState).toBe("ready");
|
|
expect(onReady).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it("persists a failed test across worker restarts without scanning, claiming, or probing it again", async () => {
|
|
const { agent, work, driver, runHost } = await failed();
|
|
expect(agent).toMatchObject({ lifecycleState: "verifying", status: "paused", lifecycleOperation: { retryRequired: true } });
|
|
expect(agent.lifecycleOperation).not.toHaveProperty("retryAt");
|
|
expect(agent.lifecycleOperation).not.toHaveProperty("leaseOwner");
|
|
expect(agent.lifecycleError).toContain("Automatic verification is paused");
|
|
expect(agent.lifecycleError).not.toContain("private provider detail");
|
|
await work.stop();
|
|
const restarted = startAgentLifecycle(db, createAgentLifecycleEffects(), driver, () => true); workers.push(restarted);
|
|
const calls = runHost.mock.calls.length;
|
|
expect(await restarted.hasPending()).toBe(false);
|
|
expect(restarted.nextRunAt()).toBeNull();
|
|
await restarted.sweep();
|
|
const store = createLifecycleStore(db, createAgentLifecycleEffects());
|
|
const tomorrow = new Date(Date.now() + 86_400_000);
|
|
expect(await store.pending(100, tomorrow)).not.toContain(agent.id);
|
|
expect(await store.claim(agent.id, "new-owner", tomorrow)).toBeNull();
|
|
await work.process(agent.id);
|
|
expect(runHost).toHaveBeenCalledTimes(calls);
|
|
expect((await current(agent.id)).lifecycleOperation).toEqual(agent.lifecycleOperation);
|
|
});
|
|
|
|
it("does not let an in-flight failed verifier overwrite a completed connection repair", async () => {
|
|
const [agent] = await db.insert(agents).values({ companyId, name: "Repair while checking", status: "paused",
|
|
lifecycleState: "verifying", lifecycleHolds: [], lifecycleRequiredPluginIds: [],
|
|
lifecycleOperation: { id: randomUUID(), hostComplete: false, completedPluginIds: [], attempts: 0, verificationFailures: 2 } }).returning();
|
|
const store = createLifecycleStore(db, createAgentLifecycleEffects());
|
|
const owner = "old-account-check";
|
|
const claimed = await store.claim(agent!.id, owner, new Date());
|
|
expect(claimed).not.toBeNull();
|
|
await db.transaction(async tx => {
|
|
expect(await requestAgentLifecycleRecheckInTransaction(tx, { companyId, agentId: agent!.id,
|
|
expectedVersion: agent!.lifecycleVersion, configurationRepaired: true },
|
|
() => notifyDeliveryWork(tx, DELIVERY_QUEUES.agentLifecycle))).toBe(true);
|
|
});
|
|
await store.defer(claimed!, owner, "Old missing account", new Date(), { retryRequired: true });
|
|
const repaired = await current(agent!.id);
|
|
expect(repaired.lifecycleError).toBeNull();
|
|
expect(repaired.lifecycleOperation).not.toHaveProperty("retryRequired");
|
|
expect(repaired.lifecycleOperation).not.toHaveProperty("retryAt");
|
|
expect(repaired.lifecycleOperation).not.toHaveProperty("verificationFailures");
|
|
expect(await store.claim(agent!.id, "new-check", new Date())).not.toBeNull();
|
|
});
|
|
|
|
it("permits an explicit retry of the same operation and completes verification before readiness", async () => {
|
|
const { agent, work, runHost } = await failed();
|
|
let release!: () => void;
|
|
const verification = new Promise<void>(resolve => { release = resolve; });
|
|
runHost.mockImplementation(async () => { await verification; return "complete"; });
|
|
let processing: Promise<void> | undefined;
|
|
try {
|
|
await createAgentLifecycle(db).retry(agent.id);
|
|
processing = work.process(agent.id);
|
|
const retried = await current(agent.id);
|
|
expect(retried).toMatchObject({ lifecycleState: "verifying", status: "paused" });
|
|
expect(retried.lifecycleOperation).not.toHaveProperty("retryRequired");
|
|
expect(retried.lifecycleOperation).not.toHaveProperty("verificationFailures");
|
|
expect(retried.lifecycleOperation!.id).toBe(agent.lifecycleOperation!.id);
|
|
} finally {
|
|
release();
|
|
await processing;
|
|
}
|
|
expect(await current(agent.id)).toMatchObject({ lifecycleState: "ready", status: "idle", lifecycleError: null });
|
|
});
|
|
|
|
it("does not spend verification retries on claims deferred before the host test", async () => {
|
|
const [agent] = await db.insert(agents).values({ companyId, name: "Deferred verification", status: "paused",
|
|
lifecycleState: "verifying", lifecycleRequiredPluginIds: [],
|
|
lifecycleOperation: { id: randomUUID(), hostComplete: false, completedPluginIds: [], attempts: 0 } }).returning();
|
|
const store = createLifecycleStore(db, createAgentLifecycleEffects());
|
|
let allowed = true;
|
|
let deferBeforeHost = true;
|
|
const runHost = vi.fn(async () => { throw Object.assign(new Error("test failed"), { code: "harness_test_failed" }); });
|
|
const work = createLifecycleWorker({ ...store, async claim(...args) {
|
|
const claimed = await store.claim(...args);
|
|
if (claimed && deferBeforeHost) allowed = false;
|
|
return claimed;
|
|
} }, { requiredPluginIds: async () => [], runPlugin: async () => "complete", runHost }, () => {}, () => allowed);
|
|
workers.push(work);
|
|
const due = async () => {
|
|
allowed = true;
|
|
await db.update(agents).set({ lifecycleOperation: sql`${agents.lifecycleOperation} - 'retryAt'` }).where(eq(agents.id, agent.id));
|
|
await work.process(agent.id);
|
|
};
|
|
await due(); await due();
|
|
expect(runHost).not.toHaveBeenCalled();
|
|
expect((await current(agent.id)).lifecycleOperation).toMatchObject({ attempts: 2 });
|
|
expect((await current(agent.id)).lifecycleOperation).not.toHaveProperty("verificationFailures");
|
|
deferBeforeHost = false;
|
|
await due();
|
|
expect((await current(agent.id)).lifecycleOperation).toMatchObject({ attempts: 3, verificationFailures: 1 });
|
|
expect((await current(agent.id)).lifecycleOperation?.retryRequired).toBeUndefined();
|
|
// Another deferred claim preserves the already recorded failed test.
|
|
deferBeforeHost = true; await due();
|
|
expect((await current(agent.id)).lifecycleOperation?.verificationFailures).toBe(1);
|
|
deferBeforeHost = false;
|
|
await due();
|
|
expect((await current(agent.id)).lifecycleOperation?.retryRequired).toBeUndefined();
|
|
await due();
|
|
expect(runHost).toHaveBeenCalledTimes(3);
|
|
expect((await current(agent.id)).lifecycleOperation).toMatchObject({ verificationFailures: 3, retryRequired: true });
|
|
});
|
|
|
|
it("keeps checking an outdated remote Runner past the failure budget and becomes ready once it matches", async () => {
|
|
const { agent, work, runHost } = await failed("runner_revision_mismatch");
|
|
for (let check = 0; check < 5; check++) {
|
|
const waiting = await current(agent.id);
|
|
expect(waiting).toMatchObject({ lifecycleState: "verifying", status: "paused" });
|
|
expect(waiting.lifecycleOperation?.retryRequired).toBeUndefined();
|
|
expect(waiting.lifecycleOperation?.verificationFailures).toBeUndefined();
|
|
expect(waiting.lifecycleOperation?.retryAt).toEqual(expect.any(String));
|
|
expect(waiting.lifecycleError).toContain("Runner is being updated");
|
|
expect(waiting.lifecycleError).not.toContain("Automatic verification is paused");
|
|
await db.update(agents).set({ lifecycleOperation: sql`${agents.lifecycleOperation} - 'retryAt'` }).where(eq(agents.id, agent.id));
|
|
await work.process(agent.id);
|
|
}
|
|
runHost.mockImplementation(async () => "complete");
|
|
await db.update(agents).set({ lifecycleOperation: sql`${agents.lifecycleOperation} - 'retryAt'` }).where(eq(agents.id, agent.id));
|
|
await work.process(agent.id);
|
|
expect(await current(agent.id)).toMatchObject({ lifecycleState: "ready", status: "idle", lifecycleError: null });
|
|
});
|
|
|
|
it("recovers from a generic failed test before the automatic retry budget is exhausted", async () => {
|
|
const { agent, work, runHost } = await failed("harness_probe_timed_out");
|
|
runHost.mockRejectedValueOnce(Object.assign(new Error("temporary test failure"), { code: "harness_test_failed" }));
|
|
await db.update(agents).set({ lifecycleOperation: sql`${agents.lifecycleOperation} - 'retryAt'` }).where(eq(agents.id, agent.id));
|
|
await work.process(agent.id);
|
|
expect((await current(agent.id)).lifecycleOperation?.retryRequired).toBeUndefined();
|
|
runHost.mockResolvedValue("complete");
|
|
await db.update(agents).set({ lifecycleOperation: sql`${agents.lifecycleOperation} - 'retryAt'` }).where(eq(agents.id, agent.id));
|
|
await work.process(agent.id);
|
|
expect((await current(agent.id)).lifecycleState).toBe("ready");
|
|
});
|
|
|
|
it("rechecks changed execution configuration but leaves a name edit waiting", async () => {
|
|
const { agent, work, runHost } = await failed();
|
|
const lifecycle = createAgentLifecycle(db);
|
|
await lifecycle.updateConfiguration(agent.id, { name: "Renamed fixture" });
|
|
expect((await current(agent.id)).lifecycleOperation!.retryRequired).toBe(true);
|
|
runHost.mockResolvedValue("complete");
|
|
await lifecycle.updateConfiguration(agent.id, { adapterConfig: { command: process.execPath } });
|
|
const changed = await current(agent.id);
|
|
expect(changed.lifecycleOperation).not.toHaveProperty("retryRequired");
|
|
expect(changed.lifecycleOperation).not.toHaveProperty("verificationFailures");
|
|
expect(changed.lifecycleOperation!.id).not.toBe(agent.lifecycleOperation!.id);
|
|
await work.process(agent.id);
|
|
expect((await current(agent.id)).lifecycleState).toBe("ready");
|
|
});
|
|
|
|
it("does not let a stale verification failure park newly saved configuration", async () => {
|
|
const { agent, work } = await failed("harness_auth_failed");
|
|
await work.stop();
|
|
const store = createLifecycleStore(db, createAgentLifecycleEffects());
|
|
await store.change(agent.id, "retry");
|
|
const claimed = await store.claim(agent.id, "old-verification", new Date());
|
|
expect(claimed).not.toBeNull();
|
|
await createAgentLifecycle(db).updateConfiguration(agent.id, { adapterConfig: { command: process.execPath } });
|
|
expect(await store.defer(claimed!, "old-verification", "Old failure", new Date(), { retryRequired: true })).toBe(false);
|
|
expect((await current(agent.id)).lifecycleOperation?.retryRequired).toBeUndefined();
|
|
});
|
|
|
|
it.each(["harness_probe_timed_out", "test_environment_unavailable", "ECONNRESET", "unclassified"])("keeps automatic recovery for %s", async code => {
|
|
const { agent } = await failed(code);
|
|
expect(agent.lifecycleOperation).not.toHaveProperty("retryRequired");
|
|
expect(Date.parse(agent.lifecycleOperation!.retryAt!)).toBeGreaterThan(Date.now());
|
|
const store = createLifecycleStore(db, createAgentLifecycleEffects());
|
|
expect(await store.pending(100, new Date(Date.now() + 120_000))).toContain(agent.id);
|
|
expect(await store.claim(agent.id, "automatic-retry", new Date(Date.now() + 120_000))).not.toBeNull();
|
|
});
|
|
|
|
it("still completes termination and cleanup when verification needs repair", async () => {
|
|
const { agent, work, runHost } = await failed();
|
|
runHost.mockResolvedValue("complete");
|
|
await createAgentLifecycle(db).terminateAgent(agent.id);
|
|
await work.process(agent.id);
|
|
expect((await current(agent.id)).lifecycleState).toBe("terminated");
|
|
expect(runHost.mock.calls.map(([a]) => a.lifecycleState)).toContain("cleaning_up");
|
|
});
|
|
|
|
async function eventWaitFixture() {
|
|
let complete = false;
|
|
const runHost = vi.fn(async (agent: LifecycleAgent) => agent.lifecycleState !== "verifying" || complete
|
|
? "complete" as const : "waiting" as const);
|
|
const driver = { requiredPluginIds: async () => [], runPlugin: async () => "complete" as const, runHost };
|
|
const work = configureAgentLifecycle(db, driver); workers.push(work);
|
|
const agent = await createAgentLifecycle(db).requestHire(companyId, { name: "External reply wait", adapterType: "process" });
|
|
await work.process(agent.id);
|
|
return { agent: await current(agent.id), work, driver, runHost, complete: () => { complete = true; } };
|
|
}
|
|
function recheck(tx: Pick<Db, "select" | "update">, id: string, scopeCompanyId = companyId, version?: number) {
|
|
return requestAgentLifecycleRecheckInTransaction(tx,
|
|
{ companyId: scopeCompanyId, agentId: id, expectedVersion: version },
|
|
() => notifyDeliveryWork(tx, DELIVERY_QUEUES.agentLifecycle));
|
|
}
|
|
|
|
it("parks healthy external verification without a retry deadline, claim or readiness bypass", async () => {
|
|
const { agent, work, runHost } = await eventWaitFixture();
|
|
expect(agent).toMatchObject({ lifecycleState: "verifying", status: "paused", lifecycleError: null,
|
|
lifecycleOperation: { waitingForSignal: true, hostComplete: false } });
|
|
expect(agent.lifecycleOperation).not.toHaveProperty("retryAt");
|
|
expect(agent.lifecycleOperation).not.toHaveProperty("retryRequired");
|
|
expect(agent.lifecycleOperation).not.toHaveProperty("leaseOwner");
|
|
const store = createLifecycleStore(db, createAgentLifecycleEffects()), calls = runHost.mock.calls.length;
|
|
const later = new Date(Date.now() + 86_400_000);
|
|
expect(await store.pending(100, later)).not.toContain(agent.id);
|
|
expect(await store.claim(agent.id, "unnotified", later)).toBeNull();
|
|
await work.process(agent.id);
|
|
expect(runHost).toHaveBeenCalledTimes(calls);
|
|
expect((await current(agent.id)).lifecycleState).toBe("verifying");
|
|
});
|
|
|
|
it.each(["during", "after"] as const)("retains a committed recheck %s the active attempt parks", async ordering => {
|
|
let entered!: () => void, release!: () => void, ready = false;
|
|
const inside = new Promise<void>(resolve => { entered = resolve; });
|
|
const hold = new Promise<void>(resolve => { release = resolve; });
|
|
const runHost = vi.fn(async (agent: LifecycleAgent) => {
|
|
if (agent.lifecycleState !== "verifying" || ready) return "complete" as const;
|
|
entered(); await hold; return "waiting" as const;
|
|
});
|
|
const work = configureAgentLifecycle(db, { requiredPluginIds: async () => [], runPlugin: async () => "complete", runHost });
|
|
workers.push(work);
|
|
const agent = await createAgentLifecycle(db).requestHire(companyId, { name: "Commit race", adapterType: "process" });
|
|
const processing = work.process(agent.id);
|
|
await inside;
|
|
try {
|
|
if (ordering === "after") { release(); await processing; }
|
|
await db.transaction(async tx => {
|
|
expect(await recheck(tx, agent.id)).toBe(true);
|
|
});
|
|
ready = true;
|
|
} finally { release(); await processing; }
|
|
const signalled = await current(agent.id);
|
|
expect(signalled.lifecycleOperation?.waitingForSignal).not.toBe(true);
|
|
expect(signalled.lifecycleOperation).not.toHaveProperty("retryAt");
|
|
await work.process(agent.id);
|
|
expect(await current(agent.id)).toMatchObject({ lifecycleState: "ready", status: "idle" });
|
|
expect(runHost.mock.calls.filter(([a]) => a.lifecycleState === "verifying")).toHaveLength(2);
|
|
});
|
|
|
|
it("retains a committed recheck when an expired attempt returns its earlier wait", async () => {
|
|
const { agent, work, complete, runHost } = await eventWaitFixture();
|
|
await db.transaction(async tx => { expect(await recheck(tx, agent.id)).toBe(true); });
|
|
const store = createLifecycleStore(db, createAgentLifecycleEffects());
|
|
const owner = "expired-verification-owner";
|
|
// Use the store's normal clock input: the real claim is already expired when
|
|
// confirmation commits, without changing timers or waiting two minutes.
|
|
const claimed = await store.claim(agent.id, owner, new Date(Date.now() - 121_000));
|
|
if (!claimed) throw new Error("Expected a real verification claim");
|
|
expect(Date.parse(claimed.lifecycleOperation!.leaseUntil!)).toBeLessThan(Date.now());
|
|
await db.transaction(async tx => { expect(await recheck(tx, agent.id)).toBe(true); });
|
|
const afterConfirmation = await current(agent.id);
|
|
complete();
|
|
expect(await store.defer(claimed, owner, null, new Date(), { waitForSignal: true })).toBe(true);
|
|
const signalled = await current(agent.id);
|
|
expect(signalled.lifecycleOperation).not.toHaveProperty("waitingForSignal");
|
|
expect(afterConfirmation.lifecycleOperation).toMatchObject({ leaseOwner: owner, recheckRequested: true });
|
|
expect(signalled.lifecycleOperation).not.toHaveProperty("leaseOwner");
|
|
expect(signalled.lifecycleOperation).not.toHaveProperty("retryAt");
|
|
expect(await store.pending(100, new Date())).toContain(agent.id);
|
|
await work.process(agent.id);
|
|
expect(await current(agent.id)).toMatchObject({ lifecycleState: "ready", status: "idle" });
|
|
expect(runHost.mock.calls.filter(([a]) => a.lifecycleState === "verifying")).toHaveLength(2);
|
|
});
|
|
|
|
it("rolls back the recheck with its producer and coalesces redundant committed signals", async () => {
|
|
const { agent, work, complete, runHost } = await eventWaitFixture();
|
|
await expect(db.transaction(async tx => {
|
|
expect(await recheck(tx, agent.id)).toBe(true);
|
|
throw new Error("Rollback this producer");
|
|
})).rejects.toThrow("Rollback this producer");
|
|
expect((await current(agent.id)).lifecycleOperation?.waitingForSignal).toBe(true);
|
|
await db.transaction(async tx => {
|
|
expect(await recheck(tx, agent.id)).toBe(true);
|
|
expect(await recheck(tx, agent.id)).toBe(true);
|
|
});
|
|
complete(); await work.process(agent.id);
|
|
const calls = runHost.mock.calls.length;
|
|
await work.process(agent.id);
|
|
expect(runHost).toHaveBeenCalledTimes(calls);
|
|
expect((await current(agent.id)).lifecycleState).toBe("ready");
|
|
});
|
|
|
|
it("finishes a committed recheck on a new owner without a post-commit scheduling call", async () => {
|
|
const { agent, work, driver, complete } = await eventWaitFixture();
|
|
await work.stop();
|
|
await db.transaction(async tx => { expect(await recheck(tx, agent.id)).toBe(true); });
|
|
complete();
|
|
// No process/Retry/wake callback follows the committed producer here.
|
|
const restarted = startAgentLifecycle(db, createAgentLifecycleEffects(), driver, () => true); workers.push(restarted);
|
|
await restarted.sweep();
|
|
expect(await current(agent.id)).toMatchObject({ lifecycleState: "ready", status: "idle" });
|
|
expect(await restarted.hasPending()).toBe(false);
|
|
});
|
|
|
|
it("rechecks a saved wait once at startup and remains parked without recurring startup scans", async () => {
|
|
const { agent, work, driver, runHost } = await eventWaitFixture();
|
|
await work.stop();
|
|
const restarted = startAgentLifecycle(db, createAgentLifecycleEffects(), driver, () => true); workers.push(restarted);
|
|
const calls = runHost.mock.calls.length;
|
|
expect(await restarted.hasPending()).toBe(true);
|
|
await restarted.sweep();
|
|
expect(runHost).toHaveBeenCalledTimes(calls + 1);
|
|
expect((await current(agent.id)).lifecycleOperation?.waitingForSignal).toBe(true);
|
|
expect(await restarted.hasPending()).toBe(false);
|
|
expect(restarted.nextRunAt()).toBeNull();
|
|
await restarted.sweep();
|
|
expect(runHost).toHaveBeenCalledTimes(calls + 1);
|
|
});
|
|
|
|
it("does not rearm a parked wait after a company or version mismatch, pause or required manual repair", async () => {
|
|
const { agent, work } = await eventWaitFixture();
|
|
await db.transaction(async tx => {
|
|
expect(await recheck(tx, agent.id, randomUUID())).toBe(false);
|
|
expect(await recheck(tx, agent.id, companyId, agent.lifecycleVersion - 1)).toBe(false);
|
|
});
|
|
expect((await current(agent.id)).lifecycleOperation).toEqual(agent.lifecycleOperation);
|
|
await createAgentLifecycle(db).pauseAgent(agent.id);
|
|
await work.process(agent.id);
|
|
await db.transaction(async tx => { expect(await recheck(tx, agent.id)).toBe(false); });
|
|
expect(await current(agent.id)).toMatchObject({ lifecycleState: "paused", status: "paused" });
|
|
const manual = await failed();
|
|
await db.transaction(async tx => { expect(await recheck(tx, manual.agent.id)).toBe(false); });
|
|
expect((await current(manual.agent.id)).lifecycleOperation?.retryRequired).toBe(true);
|
|
});
|
|
});
|