diff --git a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts index df6170bcd3c59..f1caaa07fadd9 100644 --- a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts @@ -530,3 +530,199 @@ it.effect("sql: a subagent thread becomes a candidate once its parent is done", assert.deepEqual(new Set(yield* ids()), new Set([child, orphan])); }).pipe(Effect.provide(layerSql)), ); + +it.effect("sql: a subagent is a candidate once its parent has its result", () => + Effect.gen(function* () { + const store = yield* ProjectionStore.ProjectionStoreV2; + const parent = yield* createThread("delivered-parent"); + const child = yield* createThread("delivered-child", { + lineage: { parentThreadId: parent, relationshipToParent: "subagent", rootThreadId: parent }, + }); + const ids = () => + store.getSettlementCandidates().pipe(Effect.map((rows) => rows.map((row) => row.id))); + assert.deepEqual(yield* ids(), [parent]); + const taskId = NodeId.make("node:delivered-child"); + const record = (delivery: "pending" | "claimed" | "delivered", result: string | null) => + store.apply({ + id: EventId.make(`event:delivered-child:${delivery}:${result ?? "none"}`), + type: "subagent.updated", + threadId: parent, + nodeId: taskId, + driver: ProviderDriverKind.make("codex"), + providerInstanceId, + occurredAt: now, + payload: { + id: taskId, + threadId: parent, + runId: null, + parentNodeId: taskId, + origin: "app_owned", + createdBy: "agent", + driver: ProviderDriverKind.make("codex"), + providerInstanceId, + providerThreadId: null, + childThreadId: child, + nativeTaskRef: null, + prompt: "Do the work", + title: "child", + model: null, + completionDelivery: { state: delivery, observedByRunId: null }, + status: "completed", + result, + startedAt: old, + completedAt: old, + updatedAt: now, + }, + }); + yield* record("delivered", null); + assert.deepEqual(yield* ids(), [parent]); + yield* record("pending", "done"); + assert.deepEqual(yield* ids(), [parent]); + yield* record("claimed", "done"); + assert.deepEqual(yield* ids(), [parent]); + yield* record("delivered", "done"); + assert.deepEqual(new Set(yield* ids()), new Set([parent, child])); + }).pipe(Effect.provide(layerSql)), +); + +it.effect("sql: a running provider subagent result does not make the child a candidate", () => + Effect.gen(function* () { + const store = yield* ProjectionStore.ProjectionStoreV2; + const parent = yield* createThread("running-parent"); + const child = yield* createThread("running-child", { + lineage: { parentThreadId: parent, relationshipToParent: "subagent", rootThreadId: parent }, + }); + const ids = () => + store.getSettlementCandidates().pipe(Effect.map((rows) => rows.map((row) => row.id))); + const taskId = NodeId.make("node:running-child"); + const record = (status: "running" | "completed") => + store.apply({ + id: EventId.make(`event:running-child:${status}`), + type: "subagent.updated", + threadId: parent, + nodeId: taskId, + driver: ProviderDriverKind.make("codex"), + providerInstanceId, + occurredAt: now, + payload: { + id: taskId, + threadId: parent, + runId: null, + parentNodeId: taskId, + origin: "provider_native", + createdBy: "agent", + driver: ProviderDriverKind.make("codex"), + providerInstanceId, + providerThreadId: null, + childThreadId: child, + nativeTaskRef: null, + prompt: "Do the work", + title: "child", + model: null, + status, + result: "still going", + startedAt: old, + completedAt: status === "completed" ? now : null, + updatedAt: now, + }, + }); + yield* record("running"); + assert.deepEqual(yield* ids(), [parent]); + yield* record("completed"); + assert.deepEqual(new Set(yield* ids()), new Set([parent, child])); + }).pipe(Effect.provide(layerSql)), +); + +it.effect("sql: an open follow-up keeps a delivered subagent out of the candidates", () => + Effect.gen(function* () { + const store = yield* ProjectionStore.ProjectionStoreV2; + const parent = yield* createThread("follow-up-parent"); + const child = yield* createThread("follow-up-child", { + lineage: { parentThreadId: parent, relationshipToParent: "subagent", rootThreadId: parent }, + }); + const ids = () => + store.getSettlementCandidates().pipe(Effect.map((rows) => rows.map((row) => row.id))); + const task = ( + name: string, + status: "completed" | "pending", + delivery: "delivered" | "pending", + result: string | null, + ) => + store.apply({ + id: EventId.make(`event:follow-up:${name}`), + type: "subagent.updated", + threadId: parent, + nodeId: NodeId.make(`node:${name}`), + driver: ProviderDriverKind.make("codex"), + providerInstanceId, + occurredAt: now, + payload: { + id: NodeId.make(`node:${name}`), + threadId: parent, + runId: null, + parentNodeId: NodeId.make(`node:${name}`), + origin: "app_owned", + createdBy: "agent", + driver: ProviderDriverKind.make("codex"), + providerInstanceId, + providerThreadId: null, + childThreadId: child, + nativeTaskRef: null, + prompt: "Do the work", + title: name, + model: null, + completionDelivery: { state: delivery, observedByRunId: null }, + status, + result, + startedAt: old, + completedAt: status === "completed" ? old : null, + updatedAt: now, + }, + }); + yield* task("follow-up-done", "completed", "delivered", "done"); + yield* task("follow-up-open", "pending", "pending", null); + assert.deepEqual(yield* ids(), [parent]); + yield* task("follow-up-open", "completed", "delivered", "also done"); + assert.deepEqual(new Set(yield* ids()), new Set([parent, child])); + }).pipe(Effect.provide(layerSql)), +); + +it.effect("sql: a runless subagent still reports a provider monitor", () => + Effect.gen(function* () { + const store = yield* ProjectionStore.ProjectionStoreV2; + const parent = yield* createThread("monitor-parent", { settledOverride: "settled" }); + const child = yield* createThread("monitor-child", { + lineage: { parentThreadId: parent, relationshipToParent: "subagent", rootThreadId: parent }, + }); + yield* store.apply({ + id: EventId.make("event:monitor-child:provider"), + type: "provider-thread.updated", + threadId: child, + occurredAt: now, + payload: { + id: ProviderThreadId.make("provider-thread:monitor-child"), + appThreadId: child, + ownerNodeId: null, + driver: ProviderDriverKind.make("codex"), + providerInstanceId, + providerSessionId: null, + nativeThreadRef: null, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + createdAt: old, + updatedAt: now, + pendingBackgroundTasks: [{ taskId: "tail", kind: "monitor", description: "logs" }], + }, + }); + const candidates = yield* store.getSettlementCandidates(); + const row = candidates.find((candidate) => candidate.id === child); + assert.equal(row === undefined, false); + assert.deepEqual(row?.pendingBackgroundTasks, [ + { taskId: "tail", kind: "monitor", description: "logs" }, + ]); + }).pipe(Effect.provide(layerSql)), +); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index a97180024c12e..f2b9e0602e0f1 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -8447,6 +8447,23 @@ export const layer: Layer.Layer = AND json_extract(parent.payload_json, '$.archivedAt') IS NULL AND json_extract(parent.payload_json, '$.settledOverride') IS NOT 'settled' ) + OR ( + EXISTS ( + SELECT 1 FROM orchestration_v2_projection_subagents child_task + WHERE child_task.child_thread_id = t.thread_id + AND child_task.status IN ('completed', 'interrupted', 'cancelled') + AND json_type(child_task.payload_json, '$.result') = 'text' + AND COALESCE(child_task.completion_delivery_state, '') NOT IN ('pending', 'claimed') + ) + AND NOT EXISTS ( + SELECT 1 FROM orchestration_v2_projection_subagents open_task + WHERE open_task.child_thread_id = t.thread_id + AND ( + open_task.status IN ('idle', 'pending', 'running', 'waiting') + OR COALESCE(open_task.completion_delivery_state, '') IN ('pending', 'claimed') + ) + ) + ) ) AND NOT EXISTS ( SELECT 1 FROM orchestration_v2_projection_runs active @@ -8531,9 +8548,16 @@ export const layer: Layer.Layer = pendingGuestMessageCount: pendingGuestMessageCount(thread.guestShare), pendingBackgroundTasks: derivePendingBackgroundWork({ latestRun: - latestRunId === null || status === "idle" - ? null - : { id: latestRunId, ordinal: 0, status }, + thread.lineage.relationshipToParent === "subagent" && + (latestRunId === null || status === "idle") + ? { + id: RunId.make(`run:subagent:${thread.id}`), + ordinal: 0, + status: "completed", + } + : latestRunId === null || status === "idle" + ? null + : { id: latestRunId, ordinal: 0, status }, providerThreads: providerThreadsByThreadId.get(thread.id) ?? [], turnItems: pendingTurnItemsByThreadId.get(thread.id) ?? [], activeProviderThreadId: thread.activeProviderThreadId, diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index e84e6ce7791a5..6818c26297c8e 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -8,6 +8,8 @@ import { ProviderInstanceId, MessageId, RuntimeRequestId, + NodeId, + ProviderDriverKind, RunId, type OrchestrationV2Run, ThreadId, @@ -231,6 +233,109 @@ describe("isAutoSettlementCandidate", () => { ), ).toBe(true); }); + + it("never settles a founder inbox or a failed agent-only thread", () => { + for (const audience of ["kameron", "jeff", "shared"] as const) { + expect( + ThreadSettlementService.isAutoSettlementCandidate( + shell({ + status: "completed", + inbox: makeThreadInbox({ + actor: + audience === "shared" + ? { kind: "agent", id: "lane" } + : { kind: "human", id: audience }, + routing: { audience, attentionKind: audience === "shared" ? "FYI" : "action" }, + }), + }), + NOW_MS, + ), + ).toBe(false); + } + expect( + ThreadSettlementService.isAutoSettlementCandidate( + shell({ + status: "failed", + inbox: makeThreadInbox({ + actor: { kind: "agent", id: "lane" }, + routing: { + audience: "agent-only", + assignee: { kind: "agent", id: "lane" }, + attentionKind: "background", + }, + }), + }), + NOW_MS, + ), + ).toBe(false); + }); +}); + +describe("settlesFinishedAgentWork", () => { + const agent = makeThreadInbox({ + actor: { kind: "agent", id: "lane" }, + routing: { + audience: "agent-only", + assignee: { kind: "agent", id: "lane" }, + attentionKind: "background", + }, + }); + const finished = (status: SettlementShell["status"], overrides: Partial = {}) => + shell({ inbox: agent, status, ...overrides }); + + it("settles completed, interrupted and cancelled agent-only work only", () => { + for (const status of ["completed", "interrupted", "cancelled"] as const) { + expect(ThreadSettlementService.settlesFinishedAgentWork(finished(status))).toBe(true); + } + for (const status of ["failed", "idle", "queued", "running", "rolled_back"] as const) { + expect(ThreadSettlementService.settlesFinishedAgentWork(finished(status))).toBe(false); + } + for (const audience of ["kameron", "jeff", "shared"] as const) { + expect( + ThreadSettlementService.settlesFinishedAgentWork( + finished("completed", { + inbox: makeThreadInbox({ + actor: { kind: "agent", id: "lane" }, + routing: { audience, attentionKind: "background" }, + }), + }), + ), + ).toBe(false); + } + expect( + ThreadSettlementService.settlesFinishedAgentWork( + finished("completed", { + pendingBackgroundTasks: [ + { taskId: "pull-request-watch:github.com/acme/app#1", kind: "monitor" }, + ], + }), + ), + ).toBe(false); + expect( + ThreadSettlementService.settlesFinishedAgentWork( + finished("completed", { + pendingBackgroundTasks: [{ taskId: "tail", kind: "monitor", description: "logs" }], + }), + ), + ).toBe(false); + expect( + ThreadSettlementService.settlesFinishedAgentWork( + finished("completed", { + pendingBackgroundTasks: [{ taskId: "child", kind: "subagent", description: "Review" }], + }), + ), + ).toBe(false); + expect( + ThreadSettlementService.settlesFinishedAgentWork( + finished("completed", { + standing: { name: "Ops", role: null, avatarId: "bolt", accent: "sky" }, + }), + ), + ).toBe(false); + expect(ThreadSettlementService.settlesFinishedAgentWork(shell({ status: "completed" }))).toBe( + false, + ); + }); }); describe("resolveAutoSettlementAt", () => { @@ -893,6 +998,351 @@ describe("ThreadSettlementServiceV2 worker", () => { }).pipe(Effect.provide(fixture.layer)); }), ); + + it.effect("startup sweep settles finished agent-only threads and leaves holds unsettled", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const agent = makeThreadInbox({ + actor: { kind: "agent", id: "lane" }, + routing: { + audience: "agent-only", + assignee: { kind: "agent", id: "lane" }, + attentionKind: "background", + }, + }); + const done = ( + id: string, + status: SettlementShell["status"], + overrides: Partial = {}, + ) => + makeThread(id, { + inbox: agent, + status, + latestRunId: RunId.make(`run:${id}`), + latestRunCompletedAt: DateTime.makeUnsafe(NOW), + ...overrides, + }); + const completed = done("completed", "completed"); + const interrupted = done("interrupted", "interrupted"); + const cancelled = done("cancelled", "cancelled"); + const failed = done("failed", "failed"); + const watched = done("watched", "completed", { + pendingBackgroundTasks: [ + { taskId: "pull-request-watch:github.com/acme/app#1", kind: "monitor" }, + ], + }); + const monitored = done("monitored", "completed", { + pendingBackgroundTasks: [{ taskId: "tail", kind: "monitor", description: "logs" }], + }); + const snoozed = done("snoozed", "completed", { + snoozedUntil: DateTime.makeUnsafe(Date.parse(NOW) + 60_000), + snoozedAt: DateTime.makeUnsafe(Date.parse(NOW) - 60_000), + }); + const queued = done("queued", "queued"); + const queuedMessage = done("queued-message", "completed", { + latestUserMessageAt: DateTime.makeUnsafe(NOW), + latestRunRequestedAt: DateTime.makeUnsafe(Date.parse(NOW) - 60_000), + latestRunStartedAt: DateTime.makeUnsafe(Date.parse(NOW) - 60_000), + latestRunCompletedAt: DateTime.makeUnsafe(Date.parse(NOW) - 60_000), + }); + const asked = done("asked", "completed", { + pendingRuntimeRequest: { + id: RuntimeRequestId.make("request:asked"), + kind: "user_input", + createdAt: DateTime.makeUnsafe(NOW), + }, + }); + const idle = makeThread("idle-agent", { inbox: agent, status: "idle" }); + const already = done("already", "completed", { settledOverride: "settled" }); + const standing = done("standing", "completed", { + standing: { name: "Ops", role: null, avatarId: "bolt", accent: "sky" }, + }); + const human = (id: "kameron" | "jeff" | "shared") => + done(id, "completed", { + inbox: makeThreadInbox({ + actor: id === "shared" ? { kind: "agent", id: "lane" } : { kind: "human", id }, + routing: { audience: id, attentionKind: id === "shared" ? "FYI" : "action" }, + }), + }); + const threads = [ + completed, + interrupted, + cancelled, + failed, + watched, + monitored, + snoozed, + queued, + queuedMessage, + asked, + idle, + already, + standing, + human("kameron"), + human("jeff"), + human("shared"), + ]; + const fixture = yield* makeHarness({ + snapshot: makeSnapshot(threads), + settings: { + ...DEFAULT_SERVER_SETTINGS, + sidebarAutoSettleAfterDays: null, + sidebarAutoSettleOnMerge: false, + }, + }); + yield* Effect.gen(function* () { + const service = yield* ThreadSettlementService.ThreadSettlementServiceV2; + yield* startHarness(service, fixture.activation, fixture.snapshotReads); + expect( + (yield* Ref.get(fixture.commands)).map((command) => command.threadId).toSorted(), + ).toEqual([cancelled.id, completed.id, interrupted.id].toSorted()); + for (const command of yield* Ref.get(fixture.commands)) { + expect(command.settledAt).toBeUndefined(); + } + const settledIds = new Set([completed.id, interrupted.id, cancelled.id]); + yield* Ref.update(fixture.snapshots, (snapshot) => ({ + ...snapshot, + threads: snapshot.threads.map((thread) => + thread.id === watched.id + ? { ...thread, pendingBackgroundTasks: [] } + : settledIds.has(thread.id) + ? { ...thread, settledOverride: "settled" as const } + : thread, + ), + })); + yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 99 }); + yield* Queue.take(fixture.snapshotReads); + yield* service.drain; + expect( + (yield* Ref.get(fixture.commands)).map((command) => command.threadId).toSorted(), + ).toEqual([cancelled.id, completed.id, interrupted.id, watched.id].toSorted()); + expect(yield* Ref.get(fixture.branchCalls)).toEqual([]); + }).pipe(Effect.provide(fixture.layer)); + }), + ); + + it.effect( + "day and merge settings still leave founder inboxes and failed agent work unsettled", + () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const agent = makeThreadInbox({ + actor: { kind: "agent", id: "lane" }, + routing: { + audience: "agent-only", + assignee: { kind: "agent", id: "lane" }, + attentionKind: "background", + }, + }); + const done = (id: string, status: SettlementShell["status"], inbox = agent) => + makeThread(id, { + inbox, + status, + latestRunId: RunId.make(`run:${id}`), + latestRunCompletedAt: DateTime.makeUnsafe("2026-08-20T00:00:00.000Z"), + }); + const founder = (id: "kameron" | "jeff" | "shared") => + done( + id, + "completed", + makeThreadInbox({ + actor: id === "shared" ? { kind: "agent", id: "lane" } : { kind: "human", id }, + routing: { audience: id, attentionKind: id === "shared" ? "FYI" : "action" }, + }), + ); + const finished = done("finished-agent", "completed"); + const failed = done("failed-agent", "failed"); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([ + finished, + failed, + founder("kameron"), + founder("jeff"), + founder("shared"), + ]), + }); + yield* Effect.gen(function* () { + const service = yield* ThreadSettlementService.ThreadSettlementServiceV2; + yield* startHarness(service, fixture.activation, fixture.snapshotReads); + expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([ + finished.id, + ]); + }).pipe(Effect.provide(fixture.layer)); + }), + ); + + it.effect("leaves a queued subagent and a monitored subagent unsettled", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const child = ( + id: string, + status: SettlementShell["status"], + pendingBackgroundTasks: SettlementShell["pendingBackgroundTasks"] = [], + ) => + makeThread(id, { + status, + lineage: { + rootThreadId: ThreadId.make("subagent-parent"), + parentThreadId: ThreadId.make("subagent-parent"), + relationshipToParent: "subagent", + }, + pendingBackgroundTasks, + latestRunId: RunId.make(`run:${id}`), + latestRunCompletedAt: DateTime.makeUnsafe(NOW), + }); + const ready = child("subagent-ready", "completed"); + const queued = child("subagent-queued", "queued"); + const monitored = child("subagent-monitored", "completed", [ + { taskId: "tail", kind: "monitor", description: "logs" }, + ]); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([ready, queued, monitored]), + settings: { + ...DEFAULT_SERVER_SETTINGS, + sidebarAutoSettleAfterDays: null, + sidebarAutoSettleOnMerge: false, + }, + }); + yield* Effect.gen(function* () { + const service = yield* ThreadSettlementService.ThreadSettlementServiceV2; + yield* startHarness(service, fixture.activation, fixture.snapshotReads); + expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([ + ready.id, + ]); + }).pipe(Effect.provide(fixture.layer)); + }), + ); + + it.effect( + "settles a finished subagent when its parent has the result and keeps a failed one", + () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const store = yield* ProjectionStore.ProjectionStoreV2; + const parent = appThread("result-parent", null); + const childOf = (id: string) => ({ + ...appThread(id, null), + lineage: { + rootThreadId: parent.id, + parentThreadId: parent.id, + relationshipToParent: "subagent" as const, + }, + }); + const finished = childOf("result-finished"); + const failed = childOf("result-failed"); + const marker = appThread("result-marker", "settled"); + for (const thread of [parent, finished, failed, marker]) { + yield* store.apply({ + type: "thread.created", + id: EventId.make(`created:${thread.id}`), + threadId: thread.id, + occurredAt: thread.createdAt, + payload: thread, + }); + } + const run = (threadId: ThreadId, status: "completed" | "failed"): OrchestrationV2Run => ({ + id: RunId.make(`run:${threadId}`), + threadId, + ordinal: 1, + providerInstanceId: parent.providerInstanceId, + modelSelection: parent.modelSelection, + providerThreadId: null, + userMessageId: MessageId.make(`message:${threadId}`), + rootNodeId: null, + activeAttemptId: null, + status, + requestedAt: DateTime.makeUnsafe(NOW), + startedAt: DateTime.makeUnsafe(NOW), + completedAt: DateTime.makeUnsafe(NOW), + checkpointId: null, + contextHandoffId: null, + }); + for (const payload of [run(finished.id, "completed"), run(failed.id, "failed")]) { + yield* store.apply({ + type: "run.created", + id: EventId.make(`created:${payload.id}`), + threadId: payload.threadId, + occurredAt: DateTime.makeUnsafe(NOW), + payload, + }); + } + const task = (thread: OrchestrationV2AppThread) => { + const id = NodeId.make(`node:${thread.id}`); + return { + id: EventId.make(`event:${thread.id}`), + type: "subagent.updated" as const, + threadId: parent.id, + nodeId: id, + driver: ProviderDriverKind.make("codex"), + providerInstanceId: parent.providerInstanceId, + occurredAt: DateTime.makeUnsafe(NOW), + payload: { + id, + threadId: parent.id, + runId: null, + parentNodeId: id, + origin: "app_owned" as const, + createdBy: "agent" as const, + driver: ProviderDriverKind.make("codex"), + providerInstanceId: parent.providerInstanceId, + providerThreadId: null, + childThreadId: thread.id, + nativeTaskRef: null, + prompt: "Do the work", + title: thread.title, + model: null, + completionDelivery: { state: "delivered" as const, observedByRunId: null }, + status: "completed" as const, + result: "done", + startedAt: DateTime.makeUnsafe(NOW), + completedAt: DateTime.makeUnsafe(NOW), + updatedAt: DateTime.makeUnsafe(NOW), + }, + }; + }; + const finishedTask = task(finished); + const failedTask = task(failed); + const done = yield* Deferred.make(); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([]), + projections: store, + settings: { + ...DEFAULT_SERVER_SETTINGS, + sidebarAutoSettleAfterDays: null, + sidebarAutoSettleOnMerge: false, + }, + onDispatch: (command) => + store.getThread(command.threadId).pipe( + Effect.flatMap((thread) => + store.apply( + settledEvent({ + ...thread, + settledOverride: "settled", + settledAt: DateTime.makeUnsafe(NOW), + }), + ), + ), + Effect.andThen(Deferred.succeed(done, undefined).pipe(Effect.ignore)), + Effect.orDie, + ), + }); + yield* Effect.gen(function* () { + const service = yield* ThreadSettlementService.ThreadSettlementServiceV2; + yield* startHarness(service, fixture.activation, fixture.snapshotReads); + expect(yield* Ref.get(fixture.commands)).toEqual([]); + yield* store.apply(finishedTask); + yield* store.apply(failedTask); + yield* fixture.publishEvent(finishedTask); + yield* fixture.publishEvent(failedTask); + yield* Deferred.await(done); + yield* service.drain; + expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([ + finished.id, + ]); + }).pipe(Effect.provide(fixture.layer)); + }).pipe(Effect.provide(projectionStoreSql)), + ); + it.effect("settles a merged pull request stored only in the thread links", () => Effect.gen(function* () { yield* TestClock.setTime(Date.parse(NOW)); diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index b6d33ea1c88d4..39315fe2af03f 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -158,12 +158,39 @@ function pullRequestSettles( return pullRequestAtMs >= userAnchorMs; } +const FINISHED_AGENT_RUN_STATUSES = new Set(["completed", "interrupted", "cancelled"]); +const SUBAGENT_SETTLE_STATUSES = new Set(["idle", "completed", "interrupted", "cancelled"]); + +function agentBackgroundWorkPending( + thread: Pick, +): boolean { + const tasks = thread.pendingBackgroundTasks ?? []; + return tasks.some((task) => task.kind === "monitor" || backgroundWorkHoldsCompletion([task])); +} + +export function settlesFinishedAgentWork( + thread: Pick< + ProjectionStore.ProjectionSettlementCandidate, + "inbox" | "status" | "pendingBackgroundTasks" | "standing" + >, +): boolean { + if (thread.standing != null || thread.inbox?.audience !== "agent-only") return false; + if (!FINISHED_AGENT_RUN_STATUSES.has(thread.status)) return false; + return !agentBackgroundWorkPending(thread); +} + +const HUMAN_INBOX_AUDIENCES = new Set(["kameron", "jeff", "shared"]); + export function isAutoSettlementCandidate( thread: Omit, nowMs: number, ): boolean { if (thread.archivedAt !== null || thread.settledOverride !== null) return false; if (thread.pinnedAt != null || thread.autoSettleDisabledAt != null) return false; + if (thread.inbox?.audience !== undefined && HUMAN_INBOX_AUDIENCES.has(thread.inbox.audience)) { + return false; + } + if (thread.inbox?.audience === "agent-only" && thread.status === "failed") return false; // A standing bot is a long-lived lane, never finished work. if (thread.standing != null) return false; if (thread.pendingRuntimeRequest !== null) return false; @@ -366,16 +393,21 @@ export const make = Effect.gen(function* () { // Merge events resweep all candidates because unlinked threads settle through branch lookup. const candidates = threads.filter( (thread) => - (automaticSettlementEnabled || thread.lineage.relationshipToParent === "subagent") && - isAutoSettlementCandidate(thread, nowMs), + isAutoSettlementCandidate(thread, nowMs) && + (automaticSettlementEnabled || + thread.lineage.relationshipToParent === "subagent" || + settlesFinishedAgentWork(thread)), ); // Runs per candidate thread, thousands per sweep on busy servers; the sweep owns the span. const settleThread = Effect.fnUntraced( function* (thread: (typeof candidates)[number], pullRequest: SettlementPullRequest | null) { - if (thread.lineage.relationshipToParent === "subagent") { - // The store returns a subagent only once its parent is done, so it - // settles with the parent and never runs its own lookup. + if ( + (thread.lineage.relationshipToParent === "subagent" && + SUBAGENT_SETTLE_STATUSES.has(thread.status) && + !agentBackgroundWorkPending(thread)) || + settlesFinishedAgentWork(thread) + ) { const uuid = yield* random.uuidV4(); yield* orchestrator.dispatch({ type: "thread.auto-settle", @@ -385,6 +417,7 @@ export const make = Effect.gen(function* () { }); return null; } + if (thread.lineage.relationshipToParent === "subagent") return null; // thread.auto-settle does not recheck settings, so read them per decision; reads are cached. const currentSettings = resolveProjectSettings( yield* settingsService.getSettings, @@ -426,7 +459,12 @@ export const make = Effect.gen(function* () { const lookupCandidates = (yield* Effect.forEach( candidates, (thread) => { - if (thread.lineage.relationshipToParent === "subagent") return settleThread(thread, null); + if ( + thread.lineage.relationshipToParent === "subagent" || + settlesFinishedAgentWork(thread) + ) { + return settleThread(thread, null); + } const projectSettings = resolveProjectSettings(settings, thread.projectId).settings; // Skip no-op decisions; actual settlement still reads fresh settings before dispatch. const settledAt = resolveAutoSettlementAt({ @@ -764,10 +802,13 @@ export const make = Effect.gen(function* () { case "run.background-work-cancelled": return enqueueThread(event.threadId); // Sweep only when the work can have ended: progress updates cannot settle anything. - case "subagent.updated": - return isOrchestrationV2WorkActive(event.payload.status) - ? Effect.void - : enqueueThread(event.threadId); + case "subagent.updated": { + if (isOrchestrationV2WorkActive(event.payload.status)) return Effect.void; + const childThreadId = event.payload.childThreadId; + return enqueueThread(event.threadId).pipe( + Effect.andThen(childThreadId === null ? Effect.void : enqueueThread(childThreadId)), + ); + } case "provider-thread.updated": return backgroundWorkHoldsCompletion(event.payload.pendingBackgroundTasks ?? []) ? Effect.void