diff --git a/apps/api/src/services/vm-prompt-delivery-startup.ts b/apps/api/src/services/vm-prompt-delivery-startup.ts new file mode 100644 index 0000000000..fb81339c12 --- /dev/null +++ b/apps/api/src/services/vm-prompt-delivery-startup.ts @@ -0,0 +1,34 @@ +import type { Env } from '../env'; + +/** + * Before TaskRunner commits in_progress, placement may not have created or linked a + * workspace. Submission writers bind tasks.chat_session_id before starting the runner + * (persistVmTaskSession, reserved submissions, dispatch_task and ProjectOrchestrator). + * A follow-up in this window has nothing to wake and must wait in the existing inbox. + * + * Recovery also queues tasks: retained sleeping_at, the same history required by + * loadRecoveryContext, leaves those conversations with ensureSessionRecovery. A mere + * checkpoint row is not sleep history. Do not use execution_step or started_at here: + * startup and retry writers do not maintain those as a first-placement discriminator. + */ +export async function isVmPromptTargetStarting( + env: Env, + projectId: string, + chatSessionId: string +): Promise { + const starting = await env.DATABASE.prepare( + `SELECT task.id + FROM tasks task + WHERE task.project_id = ? AND task.chat_session_id = ? + AND task.status IN ('draft', 'ready', 'queued', 'delegated') + AND NOT EXISTS ( + SELECT 1 FROM session_snapshots snapshot + WHERE snapshot.chat_session_id = task.chat_session_id + AND snapshot.sleeping_at IS NOT NULL + ) + LIMIT 1` + ) + .bind(projectId, chatSessionId) + .first(); + return starting !== null; +} diff --git a/apps/api/src/services/vm-prompt-delivery-target.ts b/apps/api/src/services/vm-prompt-delivery-target.ts index 54c1674cee..d50991b860 100644 --- a/apps/api/src/services/vm-prompt-delivery-target.ts +++ b/apps/api/src/services/vm-prompt-delivery-target.ts @@ -20,6 +20,7 @@ import { classifySessionRecoveryRefusal } from './session-recovery-refusals'; import { sessionSleepClaimLeaseMs } from './session-snapshot-sleep-claim'; import { signalSessionWakeReadyBestEffort } from './session-wake-ready'; import { isSessionWakeReadyCurrent } from './session-wake-ready-authority'; +import { isVmPromptTargetStarting } from './vm-prompt-delivery-startup'; /** ProjectData owns the delivery contract these describe; re-exported for worker callers. */ export type { VmPromptDeliverySourceTaskGuard, VmPromptDeliveryTarget }; @@ -330,6 +331,10 @@ export async function resolveVmPromptDeliveryTarget( runSideEffectGuard ); } + if (await isVmPromptTargetStarting(env, projectId, chatSessionId)) { + // Readiness retries preserve the attempt budget; the delivery TTL bounds this wait. + return { kind: 'retry', reason: 'Task is still starting; no workspace yet' }; + } const guarded = await runSideEffectGuard(); if (guarded) return { kind: 'guarded', result: guarded }; const recovery = await ensureSessionRecovery(env, projectId, chatSessionId, sourceTaskGuard, { diff --git a/apps/api/tests/workers/eviction-restored-session-prompt.test.ts b/apps/api/tests/workers/eviction-restored-session-prompt.test.ts index f942ff8194..1f93f7400e 100644 --- a/apps/api/tests/workers/eviction-restored-session-prompt.test.ts +++ b/apps/api/tests/workers/eviction-restored-session-prompt.test.ts @@ -11,11 +11,6 @@ * instead drive snapshot completion, node selection, provisioning/readiness and TaskRunner linking. */ import { resolveDurableExecutionConfig } from '@simple-agent-manager/project-data/internal/do/durable-execution-config'; -import { - claimDuePromptDeliveries, - type PromptDeliveryResult, -} from '@simple-agent-manager/project-data/internal/do/prompt-delivery'; -import { runPromptDeliveryClaim } from '@simple-agent-manager/project-data/internal/do/prompt-delivery-runner'; import { buildVmPromptDeliveryCapabilitiesPath } from '@simple-agent-manager/shared'; import { env, runInDurableObject, SELF } from 'cloudflare:test'; import { eq } from 'drizzle-orm'; @@ -26,7 +21,6 @@ import * as schema from '../../src/db/schema'; import type { TaskRunner, TaskRunnerState } from '../../src/durable-objects/task-runner'; import { ensureSessionLinked } from '../../src/durable-objects/task-runner/session-linking'; import type { TaskRunnerContext } from '../../src/durable-objects/task-runner/types'; -import type { Env } from '../../src/env'; import { CAPACITY_PLACEMENT_SNAPSHOT_SQL_ASSIGNMENTS, capacityPlacementSnapshotSqlValues, @@ -42,7 +36,6 @@ import { SESSION_RECOVERY_INITIAL_PROMPT, } from '../../src/services/session-sleep-fallback-messages'; import { buildSessionSnapshotR2Key } from '../../src/services/session-snapshots'; -import { DefaultVmPromptDeliveryAdapter } from '../../src/services/vm-prompt-delivery-adapter'; import { ensurePoolsWithStarterMachines } from '../helpers/capacity-pool-picks'; import { acceptedPromptResponse, @@ -59,6 +52,7 @@ import { seedUser, seedWorkspace, } from './helpers/seed-d1'; +import { runDueDelivery } from './helpers/vm-prompt-delivery'; const config = resolveDurableExecutionConfig({}); /** Captured before any test replaces it, so a second VM double cannot call into the first. */ @@ -222,31 +216,6 @@ async function evict(f: Fixture, interruptedWork?: boolean): Promise { expect(response.status, await response.text()).toBe(204); } -/** One pass of the production delivery claim runner for whatever is due at `now`. */ -async function runDueDelivery(f: Fixture, now = Date.now()): Promise { - return runInDurableObject(f.stub, async (instance, state) => { - const [claim] = claimDuePromptDeliveries(state.storage.sql, config, now); - if (!claim) return null; - // Bindings must come from the object's own context, as in its production alarm. - const objectEnv = (instance as unknown as { env: Env }).env; - return runPromptDeliveryClaim( - state.storage.sql, - objectEnv, - config, - claim, - new DefaultVmPromptDeliveryAdapter(objectEnv), - { - projectId: f.projectId, - recalculateAlarm: async () => undefined, - broadcastEvent: () => undefined, - armIdleCleanup: () => undefined, - nudgeDeliveries: () => 0, - scheduleSummarySync: () => undefined, - } - ); - }); -} - /** * Write what node selection through workspace_ready leave behind for this wake: a running * replacement workspace on another node bound to the chat, the task delegated to it, the diff --git a/apps/api/tests/workers/helpers/provider-limit-restore.ts b/apps/api/tests/workers/helpers/provider-limit-restore.ts index e0e106f43a..d2d4ecc786 100644 --- a/apps/api/tests/workers/helpers/provider-limit-restore.ts +++ b/apps/api/tests/workers/helpers/provider-limit-restore.ts @@ -1,10 +1,4 @@ /** Real Workers restoration fixture; only external VM HTTP is doubled. */ -import { resolveDurableExecutionConfig } from '@simple-agent-manager/project-data/internal/do/durable-execution-config'; -import { - claimDuePromptDeliveries, - type PromptDeliveryResult, -} from '@simple-agent-manager/project-data/internal/do/prompt-delivery'; -import { runPromptDeliveryClaim } from '@simple-agent-manager/project-data/internal/do/prompt-delivery-runner'; import { env, runInDurableObject, SELF } from 'cloudflare:test'; import { eq } from 'drizzle-orm'; import { drizzle } from 'drizzle-orm/d1'; @@ -12,7 +6,6 @@ import { expect, vi } from 'vitest'; import * as schema from '../../../src/db/schema'; import type { TaskRunner } from '../../../src/durable-objects/task-runner'; -import type { Env } from '../../../src/env'; import { getSelectedAgentCredentialReference } from '../../../src/routes/credentials'; import { CAPACITY_PLACEMENT_SNAPSHOT_SQL_ASSIGNMENTS, @@ -22,7 +15,6 @@ import { encrypt } from '../../../src/services/encryption'; import { signCallbackToken } from '../../../src/services/jwt'; import { resolveTaskStartPlacementCredentialAttribution } from '../../../src/services/placement-resolver'; import { resolveSessionRuntimeContract } from '../../../src/services/session-runtime-contract'; -import { DefaultVmPromptDeliveryAdapter } from '../../../src/services/vm-prompt-delivery-adapter'; import { ensurePoolsWithStarterMachines } from '../../helpers/capacity-pool-picks'; import { projectStub, sqlRows, testEnv } from './agent-message-channels'; import { pauseAlarms, pauseNodeAlarms, type StateWriteHook } from './durable-alarm-control'; @@ -35,7 +27,6 @@ import { seedUser, seedWorkspace, } from './seed-d1'; -const config = resolveDurableExecutionConfig({}); export function taskRunner(taskId: string): DurableObjectStub { return env.TASK_RUNNER.get(env.TASK_RUNNER.idFromName(taskId)) as DurableObjectStub; } @@ -208,33 +199,6 @@ export async function agentOnVm(taskMode: TaskMode, agentType = 'claude-code') { }; } -/** Claim one due prompt delivery and run it through the real delivery runner. */ -export async function runDueDelivery( - f: Fixture, - now = Date.now() -): Promise { - return runInDurableObject(f.stub, async (instance, state) => { - const [claim] = claimDuePromptDeliveries(state.storage.sql, config, now); - if (!claim) return null; - // Bindings must come from the object's own context, as in its production alarm. - const objectEnv = (instance as unknown as { env: Env }).env; - return runPromptDeliveryClaim( - state.storage.sql, - objectEnv, - config, - claim, - new DefaultVmPromptDeliveryAdapter(objectEnv), - { - projectId: f.projectId, - recalculateAlarm: async () => undefined, - broadcastEvent: () => undefined, - armIdleCleanup: () => undefined, - nudgeDeliveries: () => 0, - scheduleSummarySync: () => undefined, - } - ); - }); -} export async function taskRow(taskId: string) { return env.DATABASE.prepare('SELECT status, execution_step FROM tasks WHERE id = ?') .bind(taskId) @@ -364,3 +328,5 @@ export async function deleteSleptWorkspace(nodeId: string, taskId: string): Prom runtime_deletion_proof: 'vm_agent_confirmed', }); } + +export { runDueDelivery } from './vm-prompt-delivery'; diff --git a/apps/api/tests/workers/helpers/vm-prompt-delivery.ts b/apps/api/tests/workers/helpers/vm-prompt-delivery.ts new file mode 100644 index 0000000000..e7b5ecdd5b --- /dev/null +++ b/apps/api/tests/workers/helpers/vm-prompt-delivery.ts @@ -0,0 +1,38 @@ +import { resolveDurableExecutionConfig } from '@simple-agent-manager/project-data/internal/do/durable-execution-config'; +import { claimDuePromptDeliveries } from '@simple-agent-manager/project-data/internal/do/prompt-delivery'; +import { runPromptDeliveryClaim } from '@simple-agent-manager/project-data/internal/do/prompt-delivery-runner'; +import { runInDurableObject } from 'cloudflare:test'; + +import type { Env } from '../../../src/env'; +import { DefaultVmPromptDeliveryAdapter } from '../../../src/services/vm-prompt-delivery-adapter'; +import type { projectStub } from './agent-message-channels'; + +const config = resolveDurableExecutionConfig({}); + +/** Run one due claim with real object bindings and the production VM adapter. */ +export async function runDueDelivery( + f: { stub: ReturnType; projectId: string }, + now = Date.now() +) { + return runInDurableObject(f.stub, async (instance, state) => { + const [claim] = claimDuePromptDeliveries(state.storage.sql, config, now); + if (!claim) return null; + // Bindings must come from the object's own context, as in its production alarm. + const objectEnv = (instance as unknown as { env: Env }).env; + return runPromptDeliveryClaim( + state.storage.sql, + objectEnv, + config, + claim, + new DefaultVmPromptDeliveryAdapter(objectEnv), + { + projectId: f.projectId, + recalculateAlarm: async () => undefined, + broadcastEvent: () => undefined, + armIdleCleanup: () => undefined, + nudgeDeliveries: () => 0, + scheduleSummarySync: () => undefined, + } + ); + }); +} diff --git a/apps/api/tests/workers/vm-prompt-delivery-sleep-claim-hold.test.ts b/apps/api/tests/workers/vm-prompt-delivery-sleep-claim-hold.test.ts index 7a26e682e5..72dcb857fb 100644 --- a/apps/api/tests/workers/vm-prompt-delivery-sleep-claim-hold.test.ts +++ b/apps/api/tests/workers/vm-prompt-delivery-sleep-claim-hold.test.ts @@ -12,30 +12,24 @@ * and the production delivery runner attempts it against a VM double that would accept it. */ import { resolveDurableExecutionConfig } from '@simple-agent-manager/project-data/internal/do/durable-execution-config'; -import { - claimDuePromptDeliveries, - type PromptDeliveryResult, -} from '@simple-agent-manager/project-data/internal/do/prompt-delivery'; -import { runPromptDeliveryClaim } from '@simple-agent-manager/project-data/internal/do/prompt-delivery-runner'; import { buildVmPromptDeliveryCapabilitiesPath } from '@simple-agent-manager/shared'; -import { env, runInDurableObject } from 'cloudflare:test'; +import { env } from 'cloudflare:test'; import { drizzle } from 'drizzle-orm/d1'; import { afterEach, describe, expect, it, vi } from 'vitest'; import * as schema from '../../src/db/schema'; -import type { Env } from '../../src/env'; import { getNodeBackendBaseUrl } from '../../src/services/node-agent-readiness'; import * as projectData from '../../src/services/project-data'; import { ensureSessionSnapshotForSleep } from '../../src/services/session-snapshot-prepare'; import { claimSessionSnapshotSleep } from '../../src/services/session-snapshot-sleep-claim'; import { failSessionSnapshotSleepBeforeTeardown } from '../../src/services/session-snapshot-sleep-failure'; -import { DefaultVmPromptDeliveryAdapter } from '../../src/services/vm-prompt-delivery-adapter'; import { resolveVmPromptDeliveryTarget } from '../../src/services/vm-prompt-delivery-target'; import { acceptedPromptResponse, versionedPromptCapabilities, } from '../helpers/vm-prompt-delivery-fixtures'; import { inboxRows, sqlRows, testEnv, twoAgentProject } from './helpers/agent-message-channels'; +import { runDueDelivery } from './helpers/vm-prompt-delivery'; const config = resolveDurableExecutionConfig({}); const RUNTIME_IDENTITY = 'sleep-claim-runtime'; @@ -118,30 +112,6 @@ function installVm(f: Fixture) { return { prompts }; } -/** One pass of the production delivery claim runner for whatever is due at `now`. */ -async function runDueDelivery(f: Fixture, now: number): Promise { - return runInDurableObject(f.stub, async (instance, state) => { - const [claim] = claimDuePromptDeliveries(state.storage.sql, config, now); - if (!claim) return null; - const objectEnv = (instance as unknown as { env: Env }).env; - return runPromptDeliveryClaim( - state.storage.sql, - objectEnv, - config, - claim, - new DefaultVmPromptDeliveryAdapter(objectEnv), - { - projectId: f.projectId, - recalculateAlarm: async () => undefined, - broadcastEvent: () => undefined, - armIdleCleanup: () => undefined, - nudgeDeliveries: () => 0, - scheduleSummarySync: () => undefined, - } - ); - }); -} - async function deliveryState(f: Fixture) { const [row] = await sqlRows<{ delivery_state: string; last_error: string | null }>( f.stub, diff --git a/apps/api/tests/workers/vm-prompt-delivery-task-starting.test.ts b/apps/api/tests/workers/vm-prompt-delivery-task-starting.test.ts new file mode 100644 index 0000000000..4949ecbda0 --- /dev/null +++ b/apps/api/tests/workers/vm-prompt-delivery-task-starting.test.ts @@ -0,0 +1,334 @@ +/** #2847: a follow-up before first placement is not a request to recover a slept VM. */ +import { resolveDurableExecutionConfig } from '@simple-agent-manager/project-data/internal/do/durable-execution-config'; +import { expireDuePromptDeliveries } from '@simple-agent-manager/project-data/internal/do/prompt-delivery'; +import { buildVmPromptDeliveryCapabilitiesPath } from '@simple-agent-manager/shared'; +import { env, runInDurableObject } from 'cloudflare:test'; +import { drizzle } from 'drizzle-orm/d1'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import * as schema from '../../src/db/schema'; +import { getNodeBackendBaseUrl } from '../../src/services/node-agent-readiness'; +import * as placement from '../../src/services/placement-resolver'; +import * as projectData from '../../src/services/project-data'; +import * as recovery from '../../src/services/session-recovery'; +import type { SubmitVmTaskInput } from '../../src/services/submit-vm-task'; +import { persistVmTaskSession } from '../../src/services/submit-vm-task-effects'; +import { resolveVmPromptDeliveryTarget } from '../../src/services/vm-prompt-delivery-target'; +import { + acceptedPromptResponse, + versionedPromptCapabilities, +} from '../helpers/vm-prompt-delivery-fixtures'; +import { projectStub, sqlRows, testEnv } from './helpers/agent-message-channels'; +import { + seedAgentSession, + seedInstallation, + seedNode, + seedProject, + seedTask, + seedUser, + seedWorkspace, +} from './helpers/seed-d1'; +import { runDueDelivery } from './helpers/vm-prompt-delivery'; + +const config = resolveDurableExecutionConfig({}); +afterEach(() => vi.restoreAllMocks()); + +async function startingConversation(status = 'queued') { + const id = crypto.randomUUID(); + const userId = `user-${id}`; + const projectId = `project-${id}`; + const taskId = `task-${id}`; + await seedUser(userId); + await seedInstallation(id, userId); + await seedProject(projectId, userId, id); + await seedTask(taskId, projectId, userId, { status }); + // Exercise the primary web submission writer: it creates a workspace-less chat and + // binds tasks.chat_session_id before returning it to the caller or starting the runner. + const chatSessionId = await persistVmTaskSession( + { + env: testEnv, + projectId, + taskId, + user: { id: userId }, + body: {}, + message: 'Initial task', + setOperation: () => undefined, + getOperation: () => 'session_create', + } as SubmitVmTaskInput, + drizzle(env.DATABASE, { schema }), + 'Waiting for first VM' + ); + const stub = projectStub(projectId); + expect( + await env.DATABASE.prepare('SELECT chat_session_id FROM tasks WHERE id = ?') + .bind(taskId) + .first() + ).toMatchObject({ chat_session_id: chatSessionId }); + return { id, userId, projectId, taskId, chatSessionId, stub }; +} +type Fixture = Awaited>; +const resolve = (f: Fixture, allowWake = true) => + resolveVmPromptDeliveryTarget( + testEnv, + f.projectId, + f.chatSessionId, + undefined, + async () => null, + { allowWake } + ); + +async function queueFollowup(f: Fixture) { + await projectData.acceptPromptDelivery(testEnv, f.projectId, { + targetSessionId: f.chatSessionId, + displayContent: 'Add this detail to the task', + senderType: 'human', + senderId: f.userId, + messageClass: 'deliver', + sourceKind: 'user_followup', + ttlMs: config.ttlMs, + }); +} +async function inbox(f: Fixture) { + const [row] = await sqlRows<{ + delivery_state: string; + delivery_attempts: number; + expires_at: number; + next_attempt_at: number; + last_error: string | null; + }>( + f.stub, + 'SELECT delivery_state, delivery_attempts, expires_at, next_attempt_at, last_error FROM session_inbox WHERE target_session_id = ?', + f.chatSessionId + ); + return row!; +} + +async function readyRuntime(f: Fixture) { + const nodeId = `node-${f.id}`; + const workspaceId = `workspace-${f.id}`; + const agentSessionId = `agent-${f.id}`; + await seedNode(nodeId, f.userId); + await seedWorkspace(workspaceId, nodeId, f.userId, { + projectId: f.projectId, + chatSessionId: f.chatSessionId, + }); + await seedAgentSession(agentSessionId, workspaceId, f.userId); + await env.DATABASE.prepare( + "UPDATE tasks SET status = 'in_progress', workspace_id = ? WHERE id = ?" + ) + .bind(workspaceId, f.taskId) + .run(); + await projectData.linkSessionToWorkspace(testEnv, f.projectId, f.chatSessionId, workspaceId); + const prompts: string[] = []; + let busy = true; + const base = getNodeBackendBaseUrl(nodeId, testEnv); + const passthrough = globalThis.fetch; + vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => { + const request = input instanceof Request ? input : new Request(String(input), init); + if (!request.url.startsWith(base)) return passthrough(input, init); + if (new URL(request.url).pathname === buildVmPromptDeliveryCapabilitiesPath(workspaceId)) { + return Response.json(versionedPromptCapabilities('first-runtime')); + } + if (new URL(request.url).pathname.endsWith('/prompt')) { + const body = JSON.parse(typeof init?.body === 'string' ? init.body : await request.text()); + if (busy) + return Response.json( + { + ...acceptedPromptResponse(agentSessionId, body.deliveryId, 'first-runtime', Date.now()), + status: 'not_ready', + }, + { status: 409 } + ); + prompts.push(body.deliveryId); + return Response.json( + acceptedPromptResponse(agentSessionId, body.deliveryId, 'first-runtime', Date.now()) + ); + } + return Response.json({ ok: true }); + }); + return { + prompts, + finishFirstTurn: () => { + busy = false; + }, + }; +} + +describe('follow-ups before first VM placement', () => { + it.each(['draft', 'ready', 'queued', 'delegated'])( + 'holds %s without trying recovery or failing the chat', + async (status) => { + const f = await startingConversation(status); + const wake = vi.spyOn(recovery, 'ensureSessionRecovery'); + await queueFollowup(f); + expect(await runDueDelivery(f)).toMatchObject({ + kind: 'retry', + reason: 'not_ready', + error: 'Task is still starting; no workspace yet', + }); + expect(wake).not.toHaveBeenCalled(); + expect(await inbox(f)).toMatchObject({ delivery_state: 'retry_wait' }); + expect(await f.stub.getSession(f.chatSessionId)).toMatchObject({ status: 'active' }); + } + ); + + it('survives more than the attempt cap, waits behind the first turn, then delivers', async () => { + const f = await startingConversation(); + await queueFollowup(f); + const expiry = (await inbox(f)).expires_at; + for (let attempt = 0; attempt < config.maxAttempts + 2; attempt++) { + expect(await runDueDelivery(f, (await inbox(f)).next_attempt_at ?? Date.now())).toMatchObject( + { + kind: 'retry', + reason: 'not_ready', + } + ); + expect(await inbox(f)).toMatchObject({ delivery_state: 'retry_wait', expires_at: expiry }); + expect((await inbox(f)).delivery_attempts).toBeLessThan(config.maxAttempts); + } + const vm = await readyRuntime(f); + expect(await runDueDelivery(f, (await inbox(f)).next_attempt_at)).toMatchObject({ + kind: 'retry', + reason: 'busy', + }); + expect(vm.prompts).toEqual([]); + vm.finishFirstTurn(); + // The next backoff attempt reaches the newly idle VM without a second human message. + expect(await runDueDelivery(f, (await inbox(f)).next_attempt_at)).toMatchObject({ + kind: 'accepted', + }); + expect(vm.prompts).toHaveLength(1); + expect(await inbox(f)).toMatchObject({ delivery_state: 'acked', expires_at: expiry }); + }); + + it('expires a follow-up that is still waiting for its first VM', async () => { + const f = await startingConversation(); + await queueFollowup(f); + await runDueDelivery(f); + const expiry = (await inbox(f)).expires_at; + const expired = await runInDurableObject(f.stub, (_instance, state) => + expireDuePromptDeliveries(state.storage.sql, config, expiry) + ); + expect(expired.expired).toBeGreaterThan(0); + expect(await inbox(f)).toMatchObject({ delivery_state: 'expired', expires_at: expiry }); + expect(await runDueDelivery(f, expiry + 1)).toBeNull(); + }); + + it.each(['in_progress', 'awaiting_followup', 'completed', 'failed', 'cancelled', 'sleeping'])( + 'keeps missing-runtime diagnostics for %s', + async (status) => { + const f = await startingConversation(status); + expect(await resolve(f)).toMatchObject({ + kind: 'failed', + reason: 'wake_refused', + error: expect.stringContaining('sleeping_snapshot_missing'), + }); + } + ); + + it("does not treat another project or another chat's queued task as startup", async () => { + const f = await startingConversation(); + expect(await resolve({ ...f, projectId: `other-${f.id}` })).toMatchObject({ + kind: 'failed', + reason: 'wake_refused', + }); + expect(await resolve({ ...f, chatSessionId: `other-${f.id}` })).toMatchObject({ + kind: 'failed', + reason: 'wake_refused', + }); + expect(await resolve(f)).toMatchObject({ kind: 'retry' }); + }); + + it.each([null, '2026-11-01T00:00:00Z'])( + 'distinguishes a checkpoint from retained sleep history (%s)', + async (sleepingAt) => { + const f = await startingConversation(); + await env.DATABASE.prepare( + `INSERT INTO session_snapshots + (id, project_id, user_id, chat_session_id, runtime, status, degradation, manifest_r2_key, expires_at, sleeping_at, created_at, updated_at) + VALUES (?, ?, ?, ?, 'vm', 'available', 'none', 'manifest', '2099-01-01T00:00:00Z', ?, datetime('now'), datetime('now'))` + ) + .bind(`snapshot-${f.id}`, f.projectId, f.userId, f.chatSessionId, sleepingAt) + .run(); + // Recovery is a separate lifecycle owner; this routing control stubs only its result. + // Existing session-recovery-handoff and wake-handoff suites exercise the real owner. + const wake = vi + .spyOn(recovery, 'ensureSessionRecovery') + .mockResolvedValue({ status: 'waking', taskId: f.taskId }); + if (sleepingAt) { + expect(await resolve(f)).toEqual({ + kind: 'retry', + reason: `Session is waking (${f.taskId})`, + }); + expect(wake).toHaveBeenCalledOnce(); + } else { + expect(await resolve(f)).toEqual({ + kind: 'retry', + reason: 'Task is still starting; no workspace yet', + }); + expect(wake).not.toHaveBeenCalled(); + } + } + ); + + it('continues a real retained VM wake whose recovery task is queued with no linked workspace', async () => { + const f = await startingConversation(); + const oldWorkspace = `retired-${f.id}`; + await seedNode(`old-node-${f.id}`, f.userId); + await seedWorkspace(oldWorkspace, `old-node-${f.id}`, f.userId, { + projectId: f.projectId, + status: 'deleted', + }); + await env.DATABASE.prepare( + `INSERT INTO session_snapshots + (id, project_id, workspace_id, user_id, chat_session_id, runtime, status, degradation, + manifest_r2_key, expires_at, sleeping_at, sleep_status, recovery_status, recovery_task_id, + recovery_attempt_id, recovery_claimed_at, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, 'vm', 'available', 'none', 'manifest', '2099-01-01T00:00:00Z', + ?, 'sleeping', 'waking', ?, 'wake-attempt', ?, datetime('now'), datetime('now'))` + ) + .bind( + `snapshot-${f.id}`, + f.projectId, + oldWorkspace, + f.userId, + f.chatSessionId, + new Date().toISOString(), + f.taskId, + new Date().toISOString() + ) + .run(); + // Only cloud placement/credential discovery is substituted. The resolver, recovery + // context, deletion fence and snapshot claim all execute against real D1. + vi.spyOn( + placement, + 'resolveTaskStartPlacementCredentialAttributionFromPlacement' + ).mockImplementation(async (_db, plan) => ({ + placement: plan, + effectiveProvider: 'hetzner', + credential: { credentialSource: 'user', providerName: 'hetzner' }, + capacityPoolSelection: null, + quotaCredentialSource: 'user', + capacityPlacementSnapshot: null, + credentialAttributionUserId: f.userId, + credentialAttributionProjectId: null, + credentialAttributionSource: 'user', + credentialAttribution: { userId: f.userId, projectId: null, source: 'user' }, + })); + expect(await resolve(f)).toEqual({ kind: 'retry', reason: `Session is waking (${f.taskId})` }); + expect( + await env.DATABASE.prepare( + 'SELECT recovery_status, recovery_task_id FROM session_snapshots WHERE chat_session_id = ?' + ) + .bind(f.chatSessionId) + .first() + ).toMatchObject({ recovery_status: 'waking', recovery_task_id: f.taskId }); + }); + + it('preserves allowWake=false and skips recovery for a missing runtime', async () => { + const f = await startingConversation(); + const wake = vi.spyOn(recovery, 'ensureSessionRecovery'); + expect(await resolve(f, false)).toEqual({ kind: 'retry', reason: 'session_not_awake' }); + expect(wake).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/www/src/content/docs/docs/architecture/durable-objects.md b/apps/www/src/content/docs/docs/architecture/durable-objects.md index 585bf1c7fa..d176ba1e44 100644 --- a/apps/www/src/content/docs/docs/architecture/durable-objects.md +++ b/apps/www/src/content/docs/docs/architecture/durable-objects.md @@ -47,7 +47,7 @@ Message search on a ProjectData object works inside configured windows (`searchM Comment threads on chat messages and on Library files share one set of ProjectData tables, `anchored_comment_threads`, `anchored_comment_replies` and `anchored_comment_status_mutations` (DO migration `073-anchored-comment-threads`, `packages/project-data/src/do/anchored-comments-migration.ts`). Every row carries a non-null anchor kind and scope key (the chat session id for a message thread, the file id for a file thread), CHECK constraints tie the scope key to the typed column, and every read and write takes a typed anchor scope (`anchored-comment-scope.ts`), so a thread id alone never reaches a row. Thread, reply, status and idempotency logic is written once (`anchored-comment-store.ts`, `anchored-comment-mutations.ts`); `comments.ts` and `library-file-comments.ts` only add their anchor's checks and response shape. The migration copied the earlier per-kind tables (`comment_threads` and `library_file_comment_threads` with their replies and status mutations) with ids preserved and logs a parity check per project (`comments.migration_parity`). Those tables are kept, unwritten, as a recovery path. -ProjectData also owns the single durable prompt-delivery queue used by browser followups and agent handoffs. Acceptance persists the visible transcript message and its stable delivery identity before runtime I/O. Alarm-driven attempts use bounded exponential backoff, a finite lifetime, compare-and-set attempt tokens, and stable VM receipts. A lost response is reconciled before retry; if receipt evidence is unavailable or belongs to another runtime, the delivery becomes explicitly ambiguous and is not replayed. Urgent mailbox classes (`interrupt`, `preempt_and_replan`, `shutdown_with_final_prompt`) add stop-and-deliver: when the target VM rejects the submit because a prompt turn is in flight, the claim runner cancels that turn through the same transport as the user stop button, records the control-plane turn end, and the turn-end fan-out releases the urgent delivery so it becomes the target's next prompt. Informational classes (`notify`, `deliver`) never stop a turn. Busy informational deliveries share one exponential-backoff deadline per target session, independent of the capped per-message attempt count; the existing retry base/max settings and delivery TTL still bound retries. An idle or turn-end signal releases that target immediately, including when it arrives before the busy response. A waking VM conversation holds its queued prompts until the TaskRunner commits the agent handoff: `resolveVmPromptDeliveryTarget()` (`apps/api/src/services/vm-prompt-delivery-target.ts`) answers not-ready while the snapshot claim is `waking`, or `restored` for that workspace, and the claiming task is still queued or delegated. The commit's readiness signal (`signalSessionWakeReady()`) then makes the parked prompt due at once. The same resolver answers not-ready while the session's sleep is claimed (`preparing` inside `SESSION_SLEEP_CLAIM_LEASE_MS`, or `stopping`; `isSleepClaimHoldingDelivery()`), because a required sleep cancels the turn and the VM restarts the agent idle: a queued prompt delivered then would start a new turn and abort the sleep. Delivering earlier would let an event-wake prompt mark its batch delivered before the runner's final authority check, which would read the wake's own delivery as revocation and stop the runtime. The woken agent can also read or acknowledge its own event before the commit, which no hold covers, so the runner's check accepts its own chat having consumed the batch (`acceptConsumedByTarget` in `validateProjectEventWakeRecoveryAuthority()`). A wake whose restore resumes the saved agent session never receives the fresh-start prompt, so when nothing is queued for it (an agent whose work was interrupted by eviction, regardless of task or conversation mode), the TaskRunner queues that prompt itself as a `checkpoint_continuation` delivery after the ProjectData wake and before the commit (`queueRestoredSessionPrompt()` in `apps/api/src/services/restored-session-prompt.ts`), and the same hold delivers it once. The VM records pre-stop prompt/background-work ownership in its durable eviction callback journal. A known-idle session receives no continuation. Missing evidence from older agents or an already-lost harness triggers transcript/workspace reconciliation; the prompt tells the agent to remain idle if the work had already finished. The delivery stays valid only while it is the chat's latest continuation and its task is live and owns the chat (`invalidCheckpointContinuationTarget()`). Active-only indexes keep claim, ordering and expiry reads independent of retained mailbox history. +ProjectData also owns the single durable prompt-delivery queue used by browser followups and agent handoffs. Acceptance persists the visible transcript message and its stable delivery identity before runtime I/O. Alarm-driven attempts use bounded exponential backoff, a finite lifetime, compare-and-set attempt tokens, and stable VM receipts. A lost response is reconciled before retry; if receipt evidence is unavailable or belongs to another runtime, the delivery becomes explicitly ambiguous and is not replayed. Urgent mailbox classes (`interrupt`, `preempt_and_replan`, `shutdown_with_final_prompt`) add stop-and-deliver: when the target VM rejects the submit because a prompt turn is in flight, the claim runner cancels that turn through the same transport as the user stop button, records the control-plane turn end, and the turn-end fan-out releases the urgent delivery so it becomes the target's next prompt. Informational classes (`notify`, `deliver`) never stop a turn. Busy informational deliveries share one exponential-backoff deadline per target session, independent of the capped per-message attempt count; the existing retry base/max settings and delivery TTL still bound retries. An idle or turn-end signal releases that target immediately, including when it arrives before the busy response. Before a task's first workspace is linked, follow-ups remain queued while its status is `draft`, `ready`, `queued` or `delegated` and it has no retained `sleeping_at` history (`isVmPromptTargetStarting()` in `apps/api/src/services/vm-prompt-delivery-startup.ts`); these readiness retries preserve the delivery attempt budget and retain the original delivery TTL. A waking VM conversation holds its queued prompts until the TaskRunner commits the agent handoff: `resolveVmPromptDeliveryTarget()` (`apps/api/src/services/vm-prompt-delivery-target.ts`) answers not-ready while the snapshot claim is `waking`, or `restored` for that workspace, and the claiming task is still queued or delegated. The commit's readiness signal (`signalSessionWakeReady()`) then makes the parked prompt due at once. The same resolver answers not-ready while the session's sleep is claimed (`preparing` inside `SESSION_SLEEP_CLAIM_LEASE_MS`, or `stopping`; `isSleepClaimHoldingDelivery()`), because a required sleep cancels the turn and the VM restarts the agent idle: a queued prompt delivered then would start a new turn and abort the sleep. Delivering earlier would let an event-wake prompt mark its batch delivered before the runner's final authority check, which would read the wake's own delivery as revocation and stop the runtime. The woken agent can also read or acknowledge its own event before the commit, which no hold covers, so the runner's check accepts its own chat having consumed the batch (`acceptConsumedByTarget` in `validateProjectEventWakeRecoveryAuthority()`). A wake whose restore resumes the saved agent session never receives the fresh-start prompt, so when nothing is queued for it (an agent whose work was interrupted by eviction, regardless of task or conversation mode), the TaskRunner queues that prompt itself as a `checkpoint_continuation` delivery after the ProjectData wake and before the commit (`queueRestoredSessionPrompt()` in `apps/api/src/services/restored-session-prompt.ts`), and the same hold delivers it once. The VM records pre-stop prompt/background-work ownership in its durable eviction callback journal. A known-idle session receives no continuation. Missing evidence from older agents or an already-lost harness triggers transcript/workspace reconciliation; the prompt tells the agent to remain idle if the work had already finished. The delivery stays valid only while it is the chat's latest continuation and its task is live and owns the chat (`invalidCheckpointContinuationTarget()`). Active-only indexes keep claim, ordering and expiry reads independent of retained mailbox history. ProjectData stores the durable foundation for project event subscriptions in the same per-project SQLite database. Normalized events are admitted by project, source, delivery key, and payload fingerprint; duplicate replays are idempotent, while the same source/key with a different fingerprint becomes a visible conflict. V1 subscription filters compile only allowlisted exact/set match keys for source, event type, subject type, subject ID, and severity. GitHub producers use source `github` and skip projects owned by the system sentinel user (`findProjectsForGitHubRepository()`, `packages/repo-hosting/src/github-project-repositories.ts`); CI events such as `check_run.completed`, `check_suite.completed`, and `workflow_run.completed` use the head commit SHA as the subject when GitHub provides one and carry repository, PR, run, suite, and check IDs in metadata. Review events such as `pull_request_review.submitted` and `pull_request_review_comment.created` use the pull request number as the subject and carry review/comment commit IDs in metadata. Generic webhook producers use source `webhook`, event types such as `webhook.accepted` and `webhook.filtered`, and the webhook trigger ID as the subject. Delivery batches resolve the subscription's requested delivery through an explicit adapter-capability and authorization decision, then store requested delivery, resolved delivery, and the adapter decision separately for audit. Migration `040-project-event-pull-ack` adds the pull-model acknowledgement state (`ack_required`, `delivered_at`, `acked_at`, and `acked_by_*`) plus a replay index over subscription matches. Agents use MCP to list missed/queued summaries, fetch full event details on demand, and ack processed deliveries. The resolver can record pending durable-queue, runtime-adapter, or spawn decisions. Prompt-queue delivery is implemented: `existing_session_prompt` subscriptions wake the target chat through the existing prompt-delivery queue, `runtime_interrupt` subscriptions do the same with the `interrupt` mailbox class, which may cancel the target's in-flight turn so the wake prompt is delivered immediately (stop-and-deliver), and `runtime_steer` subscriptions (the default for agent-created subscriptions and agent-message notices) carry the `steer` delivery intent, which adds the batch to a running turn without stopping it and falls back to an ordinary wake prompt when there is no turn to steer (`buildWakePromptInput`). A chat holds at most one wake that has not yet reached its runtime: wake candidate selection and the wake alarm schedule both skip a chat with a pending prompt-queue batch through one shared predicate (`WAKE_TARGET_HAS_UNDELIVERED_WAKE_SQL` in `packages/project-data/src/do/project-events-wake-config.ts`), so once the runtime accepts that wake the next one can queue, acknowledged or not. Pull reads of events that were never injected record `recorded_not_injected` (`createPullDeliveryBatch` in `project-events-pull.ts`). In-harness runtime steering, native runtime interrupts, and task spawning remain unimplemented until their adapters are enabled. Future delivery surfaces must reuse the existing prompt-delivery queue and receipt/ambiguity handling rather than creating a second prompt-delivery engine. Do not introduce parallel `event_bus_*` tables; project eventing storage is the canonical `project_event_*` schema. diff --git a/tasks/archive/2026-11-17-hold-first-vm-follow-ups.md b/tasks/archive/2026-11-17-hold-first-vm-follow-ups.md new file mode 100644 index 0000000000..f167b33cba --- /dev/null +++ b/tasks/archive/2026-11-17-hold-first-vm-follow-ups.md @@ -0,0 +1,67 @@ +# Hold follow-ups before the first VM (#2847) + +## Scope and authorization + +DRAFT PR ONLY. Do not mark ready, merge, deploy production, or open GitHub issues. +SAM task: 01M7MC453ZXPZ0TQA2RF08FJ1D. Idea: [01M7MC3E482AXTABR5G68BQRV2](https://app.simple-agent-manager.org/projects/01KHRJGANBBWGDY1NZ0KVF0D4J/ideas/01M7MC3E482AXTABR5G68BQRV2). + +## Problem and preflight + +A follow-up while the initial task waits for capacity reaches sleep recovery with no workspace or sleep snapshot, fails with `sleeping_snapshot_missing`, and fails the conversation. This is a business-logic-change crossing D1 task/runtime state and the ProjectData durable inbox. Keep the existing queue, attempt policy and TTL. + +Research baseline: e5c5aa4f77e6adf389a24b25b9470a69c24acbff. Rechecked upstream main, 24 open PR titles, SAM task search for resolver and idea search for the refusal on 2026-11-17; no overlapping initial-start fix. Related #2693 and genuine sleep/Instant failures are distinct. Production anomaly sweep confirms genuine queued wakes exist; it does not reproduce the external reporter's case (no runtime IDs supplied). + +Prior art: [leonceaklin's report](https://github.com/raphaeltm/simple-agent-manager/issues/2847) and [fork PR #17](https://github.com/zebra-pig/simple-agent-manager/pull/17). Independently reviewed candidate patch: starting task status alone cannot distinguish recovery, because recovery requeues tasks. Retained `sleeping_at` must preserve recovery authority. Credit reporter's diagnosis and approach in upstream PR. + +Data flow: user follow-up → ProjectData acceptPromptDelivery → session_inbox claim/runPromptDeliveryClaim → DefaultVmPromptDeliveryAdapter → resolveVmPromptDeliveryTarget → D1 runtime/startup lookup → retry or VM prompt acceptance. Existing first-turn activity gate and turn-end nudge own ordering. TTL, not capacity retries, bounds waiting. + +## Writer inventory and design + +- `submit-vm-task.ts` / `submit-vm-task-effects.ts`, reserved submission storage, MCP dispatch, /sam dispatch/retry, trigger submission, project orchestrator: inspect exact task/chat binding creation before the runtime exists. +- TaskRunner `ensureSessionLinked` binds both task and workspace; workspace becomes ready before agent-session step commits `transitionToInProgress` (delegated → in_progress). +- `session-recovery.ts` reuses/requeues or replaces the task; retains sleep snapshot and releases previous task/workspace chat links. Snapshot lifecycle may create a checkpoint before any sleep; mere snapshot presence must not exclude startup. +- Nullers (recovery cleanup, unlink/stop) must not qualify an unrelated task. Query binds both project and exact chat; never falls back to project-wide queued work. +- Change only no-workspace target resolution. Add one bounded existence read there; no extra queries on live runtime path. Target file is 494 lines, so isolate startup lookup in a small service to stay within source-size rule. +- No public API, env, schema, or architecture change. Existing queue contract is restored; document behavior in architecture/durable-objects.md and validation here and in PR. + +## Checklist / acceptance + +- [x] Finish writer inventory with exact paths and verification evidence. +- [x] Real-D1 regression goes red pre-fix for initial queued/delegated follow-ups. +- [x] Hold draft/ready/queued/delegated conversations without retained sleep, without recovery or failure. +- [x] Real durable inbox keeps retry attempts below cap; delivers after readiness and first turn end. +- [x] Existing TTL expires a still-waiting follow-up without renewal. +- [x] Genuine slept sessions with queued recovery tasks still reach recovery. +- [x] in_progress missing runtime, terminal tasks, project/chat mismatch, snapshot authority and allowWake=false controls retain behavior. +- [x] Relevant local tests, lint/typecheck/build and full dispatched CI complete. +- [x] Local specialist reviews complete and findings resolved. +- [x] Reserve/deploy staging, verify changed flow, clean up and release lease. +- [x] Draft PR includes Closes #2847, contribution credit, review/CI/staging evidence and explicit draft-only constraint. +- [x] Update SAM idea with PR and findings; leave task file active pending human completion confirmation. + +## Verification evidence + +Clean pre-fix Workers run (2026-11-17 09:19 UTC): 16 tests collected, 8 expected failures / 8 passing controls, no fixture or collection failures. The draft/ready/queued/delegated inbox slices fail with `wake_refused / sleeping_snapshot_missing`; eventual-delivery/TTL and checkpoint controls fail from the same incorrect classification. Log: `.tmp/2847/red-confirmed.log` (local). Root baseline lint 22/22 and typecheck 36/36 succeeded. + +Writer inventory verified by independent Cloudflare review: `submit-vm-task-effects.ts:65–80`, `reserved-task-submission-storage.ts:25–47`, `routes/mcp/dispatch-tool.ts:451–481,610–615`, `project-orchestrator/scheduling.ts:483–518`; `/sam` dispatch/retry and trigger submission use reserved task storage. TaskRunner `workspace-steps.ts:79–86` commits queued → delegated, `in-progress-transition.ts:43–75` commits delegated → in_progress. `session-linking.ts` binds workspace+task before handoff; recovery nullers keep retained sleep history, and sleeping_at is cleared after replacement linkage. These are inspected real writers, while the new regression executes the primary web writer. + +Post-fix validation: final startup Workers suite 17/17 passed; three adjacent suites (sleep-claim hold, wake-handoff gate, real wake-event handoff) 50/50 passed. A first combined run caught an incomplete test VM busy response and an overly exact expiration write-count assertion; both fixtures were corrected and final startup run passed. This does not substitute for live staging. Cloudflare specialist PASS; test-engineer finding addressed and re-reviewed PASS; task completion/constitution/doc-sync PASS for implementation, with CI/staging still pending. Root lint (22 tasks), typecheck (36), build (18), final API typecheck and changed-file formatting passed. + +Broad local test run: 38/39 package tasks passed. API collected 1,088 files (1,083 passed, three skipped, two failed); all three failures were 5-second timeouts in unchanged archive-sharding/default-capacity-pools tests. Both files passed in isolation with unchanged timeouts and one worker: 230/230. Logs: `.tmp/2847/full-test.log` and `.tmp/2847/isolated-timeouts.log`. No unrelated timeout changes. + +SonarCloud identified 21 duplicated lines in the new delivery claim test harness. Consolidated the four identical copies into `tests/workers/helpers/vm-prompt-delivery.ts`; the provider-limit helper re-exports it to preserve callers. Test-engineer re-review PASS: config, bindings, claim selection, hooks and timing unchanged. All five affected Workers suites passed (49/49), including after the safe-main merge; runtime implementation unchanged. + +Final code validation on `365a5a82dd82c6b34f76bb761b52c2b57fc5c371`: full manually dispatched [CI 44124710948](https://github.com/raphaeltm/simple-agent-manager/actions/runs/44124710948) passed all three API and seven Workers shards, CLI, other packages, lint, build/typecheck and quality checks while PR remains draft. Quick draft CI, E2E mock/worker smoke and SonarCloud also passed. Local post-merge build passed 18 tasks/297 docs pages, API typecheck, secret-readback policy gate and all five affected Workers suites (49/49). The safe deployment prerequisite #2841 merged into main and this branch; no readiness/merge/production action was taken for this PR. + +## Live staging evidence (2026-11-17 UTC) + +[Deployment 44147093759](https://github.com/raphaeltm/simple-agent-manager/actions/runs/44147093759) succeeded, including the actual smoke-test step, on the exact code-validation head above. Cloudflare reported API version `bdcadf88-b09f-49c9-993d-ffdd7b62e867` at 100%, annotated with that commit. Workload sign-in as the manually configured `staging2-test-user` succeeded after the safe deployment applied its trust; dashboard, projects and infrastructure settings loaded in Chromium and screenshots were inspected. One bounded fresh VM used the user's explicit Claude OAuth configuration and existing compute pool, without changing shared settings. + +- 18:57:43: submit created project `01M7NDYAY28R2GZ73VYPVVHKKC`, task `01M7NDYCTJ8EQYE9D781ZRK5TB` and chat `f8bfae1e-1a5f-4114-a36b-389c4308902d`. +- 18:57:44: task was `queued` / `node_selection`, workspace NULL. At 18:57:45 one follow-up was accepted as queued, delivery `01M7NDYK1P8SK8PQVMFQJ18976`. +- 18:58–19:02: conversation stayed active, task queued with no workspace, no error and no sleep snapshot. A fresh VM heartbeated; its ready signal arrived at 19:02:11 without intervention. Workspace `01M7NE6VPSC3PYQ4K98NK3B8M8` linked at 19:02:18; delegated at 19:02:21 and in_progress at 19:02:56. +- 19:04:05.703: initial assistant response. At 19:04:10.977–11.065: original queued follow-up response, each marker exactly once, in order, without resending. Final session active/idle, task `in_progress` / `awaiting_followup`, error NULL and no retained sleep snapshot. The verification reader was corrected to join transcript streaming chunks; the product was not changed for this harness assumption. +- Desktop and 375×667 mobile delivery screenshots were inspected. Evidence retained in SAM library `/engineering/2847/`: pending `01M7NE52TM2YP9G557HWK3N2CE`, delivered desktop `01M7NEFEDHX8HTBW3AWYTSAKSP`, mobile `01M7NEFH5KJ88EHYJSRPXJYFNK`, timeline `01M7NEFKR515CBD47GEA6RAYRD`, response JSON `01M7NEFPV6W5Q82PNFZ9TB5TTP`. +- Cleanup: session stopped 19:07:55; workspace already absent (404) through normal stop cleanup; strict VM deletion returned 200 at 19:08:45, project deletion 200 at 19:08:46. D1 independently confirmed the disposable project/task/workspace/node absent; baseline node `01M7M63HHAKV258FPFNC9Y04AB` preserved. Cleanup evidence `01M7NEKMDN9TSPWK14XR60SXBH`. + +Staging release [44155480622](https://github.com/raphaeltm/simple-agent-manager/actions/runs/44155480622) succeeded after checks and cleanup. At 19:11:03 UTC readback showed holder NULL and the next queued task in its turn; normal early-release handoff sent to that task. No live hour-long TTL or genuine-sleep matrix was run; those controls are covered through the real migrated D1/ProjectData regressions. CodeRabbit automatic check is SKIPPED for this draft; no review has arrived and no ready-only review phase was triggered. Task file stays active pending human confirmation.