diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index b57fa707bebd3..c504367f6fa83 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -31,6 +31,7 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Deferred from "effect/Deferred"; import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Ref from "effect/Ref"; import * as HttpClient from "effect/http/HttpClient"; @@ -55,6 +56,8 @@ import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as PeerMcpClient from "../peer/PeerMcpClient.ts"; import * as EventSink from "./EventSink.ts"; +import * as EventSubscriptionStore from "../persistence/EventSubscriptions.ts"; +import { prepareSubscribe, threadSelectorKey } from "./eventSubscription.ts"; import * as ModelAlertReactor from "./ModelAlertReactor.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; import * as Orchestrator from "./Orchestrator.ts"; @@ -1427,13 +1430,22 @@ const hereEnvironmentId = EnvironmentId.make("environment:model-alert-here"); /** A model alert reactor here whose peer link records each send, failing the first `failSends`. */ const makeModelAlertReactor = (input: { - readonly watcher: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId }; + readonly watcher: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId } | null; readonly failSends?: number; + readonly subscriptions?: EventSubscriptionStore.EventSubscriptionStore["Service"]; + readonly config?: ServerConfig.ServerConfig["Service"]; + readonly fileSystem?: FileSystem.FileSystem; }) => Effect.gen(function* () { const sends = yield* Ref.make>>([]); const failures = yield* Ref.make(input.failSends ?? 0); - const reactor = yield* ModelAlertReactor.make.pipe( + const build = + input.fileSystem === undefined + ? ModelAlertReactor.make + : ModelAlertReactor.make.pipe( + Effect.provideService(FileSystem.FileSystem, input.fileSystem), + ); + const reactor = yield* build.pipe( Effect.provide( Layer.mergeAll( ServerSettings.layerTest({ modelAlertWatcher: input.watcher }), @@ -1468,7 +1480,12 @@ const makeModelAlertReactor = (input: { HttpClient.HttpClient, HttpClient.make(() => Effect.die("no webhook is set")), ), - layerServerConfig, + input.config === undefined + ? layerServerConfig + : Layer.succeed(ServerConfig.ServerConfig, input.config), + input.subscriptions === undefined + ? Layer.empty + : Layer.succeed(EventSubscriptionStore.EventSubscriptionStore, input.subscriptions), ).pipe(Layer.provideMerge(Layer.merge(NodeServices.layer, NodeCrypto.layer))), ), ); @@ -6171,6 +6188,389 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => { }), ); + it.effect.each([ + "both", + "read", + "dispatch", + "persist", + "cursor", + "redirect", + "pending", + "recurrence", + ] as const)("lane routing survives %s and preserves exactly one durable result", (scenario) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const eventSink = yield* EventSink.EventSinkV2; + const fs = yield* FileSystem.FileSystem.pipe(Effect.provide(NodeServices.layer)); + const config = yield* ServerConfig.ServerConfig.pipe( + Effect.provide( + ServerConfig.layerTest(process.cwd(), { prefix: `t3-lane-repair-${scenario}-` }).pipe( + Layer.provide(NodeServices.layer), + ), + ), + ); + const projectId = ProjectId.make(`project:lane-repair:${scenario}`); + yield* ProjectService.ProjectService.pipe( + Effect.flatMap((projects) => + projects.create({ + commandId: CommandId.make(`${projectId}:create`), + projectId, + title: "Lane repair", + workspaceRoot: `/workspace/lane-repair/${scenario}`, + }), + ), + ); + const create = (name: string, launcher?: ThreadId) => { + const threadId = ThreadId.make(`thread:lane-repair:${scenario}:${name}`); + return orchestrator + .dispatch({ + type: "thread.create", + commandId: CommandId.make(`${threadId}:create`), + threadId, + projectId, + title: name, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "agent", + creationSource: "mcp", + ...(launcher === undefined ? {} : { inboxOrigin: { kind: "agent", id: launcher } }), + }) + .pipe(Effect.as(threadId)); + }; + const subscriber = yield* create("subscriber"); + const child = yield* create("child", scenario === "both" ? subscriber : undefined); + const watcher = scenario === "both" ? yield* create("watcher") : null; + const inactive = !["both", "dispatch", "cursor", "recurrence"].includes(scenario); + if (inactive) { + yield* orchestrator.dispatch({ + type: "thread.settle", + commandId: CommandId.make(`${subscriber}:settle`), + threadId: subscriber, + }); + } + const replacement = scenario === "redirect" ? yield* create("replacement") : subscriber; + if (scenario === "redirect") { + yield* orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make(`${subscriber}:redirect`), + threadId: subscriber, + replacedByThreadId: replacement, + }); + yield* orchestrator.dispatch({ + type: "thread.archive", + commandId: CommandId.make(`${subscriber}:archive`), + threadId: subscriber, + }); + } + const store = yield* EventSubscriptionStore.EventSubscriptionStore.pipe( + Effect.provide( + EventSubscriptionStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)), + ), + ); + const prepared = prepareSubscribe({ + id: `evt_lane_repair_${scenario}`, + subscriberThreadId: subscriber, + selector: { entity: "thread", by: "thread_id", threadId: child }, + events: [{ name: "lane-ended" }], + createdAt: "2026-11-30T00:00:00.000Z", + }); + assert.isTrue(prepared.ok); + if (!prepared.ok) return; + yield* store.put({ + ...prepared.subscription, + ...(scenario === "pending" + ? { + pendingSummaries: ["stuck: retained earlier result"], + coalesceUntilMs: Number.MAX_SAFE_INTEGER, + } + : {}), + }); + let failedOnce = false; + const build = () => + makeModelAlertReactor({ + watcher: + watcher === null ? null : { environmentId: hereEnvironmentId, threadId: watcher }, + subscriptions: { + ...store, + put: (row) => { + if (scenario === "cursor" && !failedOnce) { + failedOnce = true; + return Effect.die("synthetic crash after dispatch before cursor persistence"); + } + return store.put(row); + }, + }, + config, + fileSystem: + scenario === "persist" + ? { + ...fs, + rename: (from, to) => + Effect.gen(function* () { + if (!failedOnce && to.endsWith("/model-alerts.json")) { + const saved = JSON.parse(yield* fs.readFileString(from)); + if (saved.laneDelivered.length > 0) { + failedOnce = true; + return yield* Effect.die("synthetic durable write failure"); + } + } + return yield* fs.rename(from, to); + }), + } + : fs, + }).pipe( + Effect.provideService(ProjectionStore.ProjectionStoreV2, { + ...projections, + getThreadShell: (id) => { + if (scenario === "read" && id === subscriber && !failedOnce) { + failedOnce = true; + return Effect.die("synthetic temporary projection failure"); + } + return projections.getThreadShell(id); + }, + }), + Effect.provideService(Orchestrator.OrchestratorV2, { + ...orchestrator, + dispatch: (command) => { + if (scenario === "dispatch" && command.type === "message.dispatch" && !failedOnce) { + failedOnce = true; + return Effect.die("synthetic dispatch failure"); + } + return orchestrator.dispatch(command); + }, + }), + ); + const first = runEvent({ + threadId: child, + runId: RunId.make(`${child}:failed:1`), + ordinal: 1, + status: "failed", + now: yield* DateTime.now, + }); + yield* eventSink.write({ + commandId: CommandId.make(`${child}:failed:1`), + events: [first], + }); + let { reactor } = yield* build(); + yield* reactor.handle(first); + if (["read", "dispatch", "persist", "cursor"].includes(scenario)) { + assert.isTrue(failedOnce); + assert.equal((yield* store.listForSelector(threadSelectorKey(child))).length, 1); + const disk = yield* fs + .readFileString(`${config.stateDir}/model-alerts.json`) + .pipe(Effect.orElseSucceed(() => '{"laneDelivered":[]}')); + assert.deepEqual(JSON.parse(disk).laneDelivered, [], "failed work stays retryable"); + ({ reactor } = yield* build()); + yield* reactor.handle(first); + } + const saved = JSON.parse(yield* fs.readFileString(`${config.stateDir}/model-alerts.json`)); + assert.equal(saved.laneDelivered.length, 1); + if (inactive && scenario !== "redirect") { + assert.equal( + saved.outbox.filter( + (entry: { alert: { kind: string } }) => entry.alert.kind === "lane-ended", + ).length, + 1, + ); + } + // Reload the reactor after queueing, before flushing, to exercise the persisted outbox/key. + ({ reactor } = yield* build()); + yield* reactor.handle(first); + yield* reactor.flush; + yield* TestClock.adjust("11 minutes"); + yield* reactor.flush; + const result = yield* orchestrator.getThreadRecords(replacement, ["messages", "runs"]); + assert.equal(result.messages.length, 1); + assert.equal(result.runs.length, 1); + if (inactive && scenario !== "redirect") { + assert.equal(result.runs[0]?.delivery?.class, "digest"); + assert.deepEqual(yield* store.listForSelector(threadSelectorKey(child)), []); + } else { + assert.notEqual(result.runs[0]?.delivery?.class, "digest"); + } + if (scenario === "pending") + assert.include(result.messages[0]?.text, "retained earlier result"); + if (scenario === "redirect") { + assert.deepEqual( + (yield* orchestrator.getThreadRecords(subscriber, ["messages"])).messages, + [], + ); + assert.equal((yield* store.listForSelector(threadSelectorKey(child))).length, 1); + } + if (scenario === "recurrence") { + for (const [ordinal, status] of [ + [2, "completed"], + [3, "failed"], + [4, "failed"], + ] as const) { + const event = runEvent({ + threadId: child, + runId: RunId.make(`${child}:${ordinal}`), + ordinal, + status, + now: yield* DateTime.now, + }); + yield* eventSink.write({ + commandId: CommandId.make(`${child}:${ordinal}`), + events: [event], + }); + yield* reactor.handle(event); + } + assert.equal( + (yield* orchestrator.getThreadRecords(subscriber, ["messages"])).messages.length, + 2, + ); + } + }), + ); + + // CLO-1302: audit thread c964fe48 was woken about ten times by child 98fbc01a ending after it + // had settled. A settled launcher is detached; an active one hears each condition once. + it.effect( + "lane-ended never wakes a settled launcher and wakes an active one once per condition", + () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const projectId = ProjectId.make("project:lane-storm"); + yield* ProjectService.ProjectService.pipe( + Effect.flatMap((projects) => + projects.create({ + commandId: CommandId.make("command:lane-storm-project"), + projectId, + title: "Lane storm", + workspaceRoot: "/workspace/lane-storm", + }), + ), + ); + const createThread = (name: string, launcher?: ThreadId) => + orchestrator + .dispatch({ + type: "thread.create", + createdBy: "agent", + creationSource: "mcp", + ...(launcher === undefined ? {} : { inboxOrigin: { kind: "agent", id: launcher } }), + commandId: CommandId.make(`command:lane-storm:${name}`), + threadId: ThreadId.make(`thread:${name}`), + projectId, + title: name, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }) + .pipe(Effect.as(ThreadId.make(`thread:${name}`))); + const watcher = yield* createThread("lane-storm-watcher"); + const settledLauncher = yield* createThread("c964fe48"); + const settledChild = yield* createThread("98fbc01a", settledLauncher); + const activeLauncher = yield* createThread("active-launcher"); + const activeChild = yield* createThread("active-child", activeLauncher); + yield* orchestrator.dispatch({ + type: "thread.settle", + commandId: CommandId.make("command:lane-storm:settle"), + threadId: settledLauncher, + }); + const store = yield* EventSubscriptionStore.EventSubscriptionStore.pipe( + Effect.provide( + EventSubscriptionStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)), + ), + ); + for (const [subscriber, child] of [ + [settledLauncher, settledChild], + [activeLauncher, activeChild], + ] as const) { + const prepared = prepareSubscribe({ + id: `evt_${subscriber}`, + subscriberThreadId: subscriber, + selector: { entity: "thread", by: "thread_id", threadId: child }, + events: [{ name: "lane-ended" }], + createdAt: "2026-11-27T00:00:00.000Z", + }); + assert.isTrue(prepared.ok); + if (prepared.ok) yield* store.put(prepared.subscription); + } + const { reactor } = yield* makeModelAlertReactor({ + watcher: { environmentId: hereEnvironmentId, threadId: watcher }, + subscriptions: store, + }); + // Ten runs of each child end the same way, the storm the audit thread saw. + for (let ordinal = 1; ordinal <= 10; ordinal++) { + for (const child of [settledChild, activeChild]) { + const failed = runEvent({ + threadId: child, + runId: RunId.make(`run:${child}:${ordinal}`), + ordinal, + status: "failed", + now, + }); + yield* eventSink.write({ + commandId: CommandId.make(`command:${child}:${ordinal}`), + events: [failed], + }); + yield* reactor.handle(failed); + } + yield* reactor.flush; + } + yield* TestClock.adjust("11 minutes"); + yield* reactor.flush; + + const settled = yield* orchestrator.getThreadRecords(settledLauncher, ["messages", "runs"]); + const active = yield* orchestrator.getThreadProjection(activeLauncher); + assert.deepEqual( + [settled.messages.length, active.messages.length], + [1, 1], + "each launcher retains exactly one result on its selected delivery path", + ); + assert.equal(settled.runs.length, 1); + assert.equal(settled.runs[0]?.delivery?.class, "digest"); + assert.equal(settled.runs[0]?.delivery?.category, "lane_result"); + assert.deepEqual(yield* store.listForSelector(threadSelectorKey(settledChild)), []); + + const wakes = active.messages.filter((message) => + message.text.startsWith("Update on thread"), + ); + assert.equal(wakes.length, 1); + assert.include(wakes[0]?.text, "lane-ended"); + + // The Home wake-loop detector suppresses wakes for a thread; its next alert is a digest. + const suppress = prepareSubscribe({ + id: "evt_wake_loop", + subscriberThreadId: watcher, + selector: { entity: "thread", by: "thread_id", threadId: activeLauncher }, + events: [{ name: "wake-suppressed" }], + createdAt: "2026-11-27T00:00:00.000Z", + }); + assert.isTrue(suppress.ok); + if (suppress.ok) yield* store.put(suppress.subscription); + const runsBefore = (yield* orchestrator.getThreadRecords(activeLauncher, ["runs"])).runs + .length; + yield* TestClock.adjust("2 hours"); + const disk = runEvent({ + threadId: activeChild, + runId: RunId.make(`run:${activeChild}:disk`), + ordinal: 11, + status: "interrupted", + now: yield* DateTime.now, + }); + yield* eventSink.write({ + commandId: CommandId.make("command:lane-storm:disk"), + events: [disk], + }); + yield* reactor.handle(disk); + yield* reactor.flush; + const after = yield* orchestrator.getThreadRecords(activeLauncher, ["messages", "runs"]); + const added = after.runs.slice(runsBefore); + assert.equal(added.length, 1); + assert.deepStrictEqual(added[0]?.delivery, { class: "digest", category: "alert" }); + }), + ); + it.effect.each(["usage limit", "self"] as const)( "a failed thread with no launcher wakes the watcher once, except for its %s", (exception) => diff --git a/apps/server/src/orchestration-v2/ModelAlertReactor.ts b/apps/server/src/orchestration-v2/ModelAlertReactor.ts index 1c8185549e6b7..a7df1c8b074bc 100644 --- a/apps/server/src/orchestration-v2/ModelAlertReactor.ts +++ b/apps/server/src/orchestration-v2/ModelAlertReactor.ts @@ -65,6 +65,7 @@ import { isStrandedQueueSignature, judgeThread, keepStrandedQueueReport, + laneEventOf, type StrandedQueue, threadEventAlert, launchingThreadId, @@ -78,6 +79,13 @@ import { withPullRequestStates, type ThreadFinding, } from "./ThreadEventAlerts.ts"; +import { + decideLaneEvent, + type LaneDecision, + laneConditionKey, + laneThreadState, + retainLaneDelivered, +} from "./laneEventRouting.ts"; import { alertIsStale, expectsAutoResume, @@ -179,6 +187,8 @@ export const ModelAlertState = Schema.Struct({ failureWakeSentAt: Schema.Record(Schema.String, Schema.Number).pipe( Schema.withDecodingDefault(Effect.succeed({})), ), + /** Lane-event conditions already routed, keyed recipient > child > condition (CLO-1302). */ + laneDelivered: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))), outbox: Schema.Array(Delivery), }); export type ModelAlertState = typeof ModelAlertState.Type; @@ -190,6 +200,7 @@ export const EMPTY_MODEL_ALERT_STATE: ModelAlertState = { resuming: {}, incidentSentAt: {}, failureWakeSentAt: {}, + laneDelivered: [], outbox: [], }; @@ -958,6 +969,8 @@ export const deliverAlertToWatcher = Effect.fnUntraced(function* ( watcher: ModelAlertWatcher, here: EnvironmentId, expiresAtMs?: number, + /** A wake-suppressed watcher still gets the alert, but only as a digest. */ + wakeSuppressed = false, ) { const message = watcherAlertMessage(alert); // Run ids can be long; a retry key must stay under the 256 characters the peer accepts. @@ -967,7 +980,7 @@ export const deliverAlertToWatcher = Effect.fnUntraced(function* ( const expiresAt = DateTime.makeUnsafe( expiresAtMs ?? DateTime.toEpochMillis(yield* DateTime.now) + ALERT_DIGEST_TTL_MS, ); - const deliveryClass = isFailureWake(alert) ? "next_turn" : "digest"; + const deliveryClass = isFailureWake(alert) && !wakeSuppressed ? "next_turn" : "digest"; if (watcher.environmentId === here) { // A retired watcher never takes a turn: the alert follows its redirect, or is dropped with a // warning when the chain cannot be resolved. @@ -1079,19 +1092,33 @@ export const make = Effect.gen(function* () { const current = yield* Ref.get(state); const [result, next] = change(current); if (next === current) return result; - yield* Ref.set(state, next); yield* encodeState(next).pipe( Effect.flatMap((contents) => writeFileStringAtomically({ filePath, contents })), Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(Path.Path, path), - Effect.catchCause((cause) => - Effect.logWarning("saving model alerts failed", { filePath, cause }), - ), + Effect.orDie, ); + yield* Ref.set(state, next); return result; }), ); + /** + * A `wake-suppressed` subscription on a thread (set by the Home wake-loop detector, + * `wake-loop::`) turns every server wake for that thread into a digest. + */ + const wakeSuppressed = (threadId: ThreadId) => + Option.isNone(subscriptionStore) + ? Effect.succeed(false) + : subscriptionStore.value.listForSelector(threadSelectorKey(threadId)).pipe( + Effect.map((rows) => + rows.some((row) => + (row.events ?? []).some((event) => event.name === "wake-suppressed"), + ), + ), + Effect.catchCause(() => Effect.succeed(false)), + ); + const sha256Hex = (identity: string) => crypto .digest(Digest.sha256, new TextEncoder().encode(identity)) @@ -1101,6 +1128,7 @@ export const make = Effect.gen(function* () { watcher: ModelAlertWatcher, here: EnvironmentId, expiresAtMs: number, + wakeSuppressed: boolean, ) => deliverAlertToWatcher( { @@ -1113,6 +1141,7 @@ export const make = Effect.gen(function* () { watcher, here, expiresAtMs, + wakeSuppressed, ); const WatcherThreadStatus = Schema.Struct({ @@ -1432,6 +1461,7 @@ export const make = Effect.gen(function* () { target, here, entry.digestExpiresAt ?? nowMs + ALERT_DIGEST_TTL_MS, + target.environmentId === here && (yield* wakeSuppressed(target.threadId)), ); return { _tag: "sent" } satisfies DeliveryResult; }); @@ -1465,8 +1495,9 @@ export const make = Effect.gen(function* () { readonly signature: string; }>, settled: boolean, + laneDeliveryIdentity?: string, ) { - if (Option.isNone(subscriptionStore)) return; + if (Option.isNone(subscriptionStore)) return false; const store = subscriptionStore.value; const decision = planThreadSubscription({ findings, @@ -1486,21 +1517,21 @@ export const make = Effect.gen(function* () { { sourceKind: "event", subscriptionId: subscription.id }, ).pipe( Effect.map((wake) => wake.threadId), - Effect.catchCause((cause) => - Effect.logWarning("event subscription wake dropped", { - id: subscription.id, - threadId: subscription.subscriberThreadId, - cause, - }).pipe(Effect.as(null)), - ), + Effect.orDie, ); + // A replay after dispatch but before cursor/dedupe persistence must reuse the same command. + const deliveryId = + laneDeliveryIdentity === undefined + ? `${subscription.id}:${seq}` + : yield* sha256Hex(`${subscription.id}\n${laneDeliveryIdentity}`); + const suppressed = wakeTarget !== null && (yield* wakeSuppressed(wakeTarget)); if (wakeTarget !== null) yield* engine .dispatch({ type: "message.dispatch", - commandId: CommandId.make(`server:event-sub:${subscription.id}:${seq}`), + commandId: CommandId.make(`server:event-sub:${deliveryId}`), threadId: wakeTarget, - messageId: MessageId.make(`message:event-sub:${subscription.id}:${seq}`), + messageId: MessageId.make(`message:event-sub:${deliveryId}`), text: [ `Update on thread ${title} (${watchedThreadId}), which you subscribed to:`, ...decision.summaries, @@ -1512,40 +1543,21 @@ export const make = Effect.gen(function* () { }, attachments: [], dispatchMode: { type: "queue_after_active" }, + ...(suppressed + ? { delivery: { class: "digest" as const, category: "alert" as const } } + : {}), createdBy: "agent", creationSource: "server", }) - .pipe( - Effect.catchCause((cause) => - Effect.logWarning("event subscription wake failed", { - id: subscription.id, - threadId: subscription.subscriberThreadId, - cause, - }), - ), - ); + .pipe(Effect.orDie); } if (decision.expire) { - yield* store.remove(subscription.subscriberThreadId, subscription.id).pipe( - Effect.catchCause((cause) => - Effect.logWarning("event subscription removal failed", { - id: subscription.id, - cause, - }), - ), - Effect.asVoid, - ); - return; + yield* store.remove(subscription.subscriberThreadId, subscription.id).pipe(Effect.orDie); + return decision.action === "wake"; } const next = withCursor(subscription, decision.state); - if (cursorUnchanged(subscription, next)) return; - yield* store - .put(next) - .pipe( - Effect.catchCause((cause) => - Effect.logWarning("event subscription update failed", { id: subscription.id, cause }), - ), - ); + if (!cursorUnchanged(subscription, next)) yield* store.put(next).pipe(Effect.orDie); + return decision.action === "wake" || next.pendingSummaries.length > 0; }); const subscriptionsForThread = (threadId: ThreadId) => @@ -1793,6 +1805,76 @@ export const make = Effect.gen(function* () { return { environmentId: here, threadId: launcher.id } satisfies ModelAlertWatcher; }); + /** Read failures defer routing; only a successful null read means the thread is missing. */ + const routeLaneEnded = Effect.fnUntraced(function* ( + shell: OrchestrationV2ThreadShell, + recipientId: string | null, + ) { + let recipient = + recipientId === null ? null : yield* projections.getThreadShell(ThreadId.make(recipientId)); + // Redirect tombstones take precedence over the retired thread's settled/archived state. + if (recipient?.replacedByThreadId != null) { + const target = yield* resolveWakeTarget( + (threadId) => engine.getThreadShell(threadId), + recipient.id, + { sourceKind: "event" }, + ); + recipientId = target.threadId; + recipient = yield* projections.getThreadShell(target.threadId); + } + const decision = decideLaneEvent(laneEventOf(shell, recipientId), { + threads: { + ...(recipientId === null ? {} : { [recipientId]: { state: laneThreadState(recipient) } }), + [shell.id]: { state: laneThreadState(shell) }, + }, + delivered: (yield* Ref.get(state)).laneDelivered, + }); + return { decision, recipient }; + }); + + const rememberLaneDelivery = (key: string) => + update((current) => [ + undefined, + current.laneDelivered.includes(key) + ? current + : { + ...current, + laneDelivered: [...current.laneDelivered, key].slice(-MAX_REPORTED), + }, + ]); + + /** A settled, archived or missing subscriber no longer hears its child's lane ending. */ + const detachLaneEnded = Effect.fnUntraced(function* ( + subscription: EventSubscription, + recipient: OrchestrationV2ThreadShell | null, + ) { + const events = subscription.events ?? []; + if (Option.isNone(subscriptionStore) || !events.some((e) => e.name === "lane-ended")) { + return subscription; + } + const state = laneThreadState(recipient); + if (state === "idle" || state === "running") return subscription; + const remaining = events.filter((e) => e.name !== "lane-ended"); + const store = subscriptionStore.value; + yield* Effect.logInfo("detached an inactive subscriber from lane-ended", { + id: subscription.id, + subscriberThreadId: subscription.subscriberThreadId, + state, + }); + if (remaining.length === 0) { + yield* store.remove(subscription.subscriberThreadId, subscription.id).pipe(Effect.orDie); + return null; + } + const next = { + ...subscription, + events: remaining, + pendingSummaries: [], + coalesceUntilMs: null, + }; + yield* store.put(next).pipe(Effect.orDie); + return next; + }); + /** Judges one thread for the kinds a trigger can change, and queues what is newly true. */ const handleThreadEvents = Effect.fnUntraced(function* ( threadId: ThreadId, @@ -1827,6 +1909,80 @@ export const make = Effect.gen(function* () { const label = (yield* environment.getDescriptor).label; const occurredAt = DateTime.formatIso(yield* DateTime.now); const launcher = yield* launchingThread(shell, here); + const laneFinding = judged.findings.find((finding) => finding.kind === "lane-ended"); + const laneEnded = laneFinding !== undefined; + if (judged.evaluated.includes("lane-ended") && laneThreadState(shell) !== "running") { + yield* update((current) => { + const laneDelivered = retainLaneDelivered( + current.laneDelivered, + shell.id, + laneEnded ? laneConditionKey(laneEventOf(shell, null)) : null, + ); + return [ + undefined, + laneDelivered.length === current.laneDelivered.length + ? current + : { ...current, laneDelivered }, + ]; + }); + } + const queueLaneDigest = Effect.fnUntraced(function* ( + route: { + readonly decision: LaneDecision; + readonly recipient: OrchestrationV2ThreadShell | null; + }, + pending: ReadonlyArray = [], + ) { + const key = route.decision.deliveredKey; + if (key === undefined || laneFinding === undefined) return; + // Keep the settled launcher's result as a non-waking digest even without a webhook. + const recipient = + route.recipient === null || + route.recipient.deletedAt !== null || + route.recipient.archivedAt !== null + ? null + : { environmentId: here, threadId: route.recipient.id }; + const destinations = threadEventDestinations(recipient, current.modelAlertWebhookUrl); + const alert = threadEventAlert({ + environmentId: here, + environmentLabel: label, + shell, + finding: + pending.length === 0 + ? laneFinding + : { + ...laneFinding, + detail: [laneFinding.detail, ...pending].join("\n"), + }, + occurredAt, + recipient, + }); + const enqueued = yield* update((initial) => { + if (initial.laneDelivered.includes(key)) return [false, initial]; + const queued = enqueueAlert(initial.outbox, alert, destinations, nowMs); + if (!queued.enqueued) return [false, initial]; + return [ + true, + { + ...initial, + outbox: queued.outbox, + laneDelivered: [...initial.laneDelivered, key].slice(-MAX_REPORTED), + }, + ]; + }); + if (enqueued) yield* Queue.offer(wake, undefined); + }); + const launcherId = launchingThreadId(shell.inbox); + const launcherSubscribed = subscribed.some( + (row) => + row.subscriberThreadId === launcherId && + (row.events ?? []).some((event) => event.name === "lane-ended"), + ); + if (laneEnded && !selfWatch && !noGlobalDestination && !launcherSubscribed) { + const route = yield* routeLaneEnded(shell, launcherId === shell.id ? null : launcherId); + if (route.decision.action !== "drop") yield* queueLaneDigest(route); + } + const outboxFindings = judged.findings.filter((finding) => finding.kind !== "lane-ended"); if ( !selfWatch && !noGlobalDestination && @@ -1846,6 +2002,7 @@ export const make = Effect.gen(function* () { let state = initial; let queued = false; for (const kind of judged.evaluated) { + if (kind === "lane-ended") continue; const recipient = kind === "thread-failed" ? watcher : launcher; const destinations = threadEventDestinations( recipient, @@ -1853,7 +2010,7 @@ export const make = Effect.gen(function* () { ); const result = recordThreadEvents( state, - { threadId, evaluated: [kind], findings: judged.findings, ...context }, + { threadId, evaluated: [kind], findings: outboxFindings, ...context }, (finding) => threadEventAlert({ environmentId: here, @@ -1874,14 +2031,52 @@ export const make = Effect.gen(function* () { if (enqueued) yield* Queue.offer(wake, undefined); yield* Effect.forEach( subscribed, - (subscription) => - applyThreadPlan( - subscription, - threadId, - shell.title, - judged.findings, - trigger === "settled", - ), + (row) => + Effect.gen(function* () { + let subscription: EventSubscription | null = row; + let route: { + readonly decision: LaneDecision; + readonly recipient: OrchestrationV2ThreadShell | null; + } | null = null; + if (laneEnded && (row.events ?? []).some((event) => event.name === "lane-ended")) { + route = yield* routeLaneEnded(shell, row.subscriberThreadId); + if (route.decision.action === "digest") { + yield* queueLaneDigest(route, row.pendingSummaries); + if ( + route.decision.deliveredKey !== undefined && + (yield* Ref.get(state)).laneDelivered.includes(route.decision.deliveredKey) + ) { + subscription = yield* detachLaneEnded(row, route.recipient); + } + } else if ( + route.decision.action === "drop" && + laneThreadState(route.recipient) !== "idle" && + laneThreadState(route.recipient) !== "running" + ) { + // A previous successful queue is enough to finish an interrupted detach. + subscription = yield* detachLaneEnded(row, route.recipient); + } + } + if (subscription === null) return; + const wakesSubscriber = route === null || route.decision.action === "wake"; + const queued = yield* applyThreadPlan( + subscription, + threadId, + shell.title, + wakesSubscriber ? judged.findings : outboxFindings, + trigger === "settled", + route?.decision.action === "wake" + ? `${route.decision.deliveredKey}:${shell.latestRunId}` + : undefined, + ); + if ( + queued && + route?.decision.action === "wake" && + route.decision.deliveredKey !== undefined + ) { + yield* rememberLaneDelivery(route.decision.deliveredKey); + } + }), { discard: true }, ); }); diff --git a/apps/server/src/orchestration-v2/ThreadEventAlerts.ts b/apps/server/src/orchestration-v2/ThreadEventAlerts.ts index d1c53eb0b1462..5ebe1d7cde476 100644 --- a/apps/server/src/orchestration-v2/ThreadEventAlerts.ts +++ b/apps/server/src/orchestration-v2/ThreadEventAlerts.ts @@ -9,6 +9,7 @@ import { } from "@t3tools/contracts"; import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; import { threadPullRequestKeyOf } from "../sourceControl/threadPullRequests.ts"; +import type { LaneEvent } from "./laneEventRouting.ts"; import { formatThreadLink } from "@t3tools/shared/threadLinks"; import * as DateTime from "effect/DateTime"; import * as Schema from "effect/Schema"; @@ -111,6 +112,22 @@ const openPullRequests = (shell: WatchedShell) => (link) => link.snapshot === null || link.snapshot.state === "open", ); +/** The lane-routing view of this thread ending, as one recipient would receive it. */ +export const laneEventOf = (shell: WatchedShell, recipient: string | null): LaneEvent => { + const failed = shell.status === "failed" || shell.status === "interrupted"; + return { + child_thread_id: shell.id, + owner: recipient, + kind: "lane-ended", + condition: { + outcome: shell.status, + error: failed ? (shell.lastError ?? shell.status) : null, + open_prs: openPullRequests(shell).map(threadPullRequestKeyOf), + question: shell.pendingRuntimeRequest === null ? null : "pending-request", + }, + }; +}; + /** The links a lane-ended re-judge should reread from the host: the ones it counts as open. */ export const openPullRequestLinks = (shell: Pick) => openPullRequests(shell as WatchedShell); diff --git a/apps/server/src/orchestration-v2/eventSubscription.ts b/apps/server/src/orchestration-v2/eventSubscription.ts index 9d00d3305e95d..e5fbe00b9b60a 100644 --- a/apps/server/src/orchestration-v2/eventSubscription.ts +++ b/apps/server/src/orchestration-v2/eventSubscription.ts @@ -21,7 +21,13 @@ import type { PullRequestWatchChange } from "./pullRequestWatch.ts"; /** Dropped before a comment or review can wake. Match ignores case and a trailing `[bot]`. */ export const DEFAULT_PULL_REQUEST_IGNORE_AUTHORS = ["coderabbitai"] as const; -const THREAD_EVENT_NAMES = new Set(["lane-ended", "promise-without-wake", "stuck", "needs-person"]); +const THREAD_EVENT_NAMES = new Set([ + "lane-ended", + "promise-without-wake", + "stuck", + "needs-person", + "wake-suppressed", +]); const HOUR_MS = 3_600_000; const CLOCK_RE = /^([01]\d|2[0-3]):([0-5]\d)$/; diff --git a/apps/server/src/orchestration-v2/laneEventRouting.conformance.json b/apps/server/src/orchestration-v2/laneEventRouting.conformance.json new file mode 100644 index 0000000000000..56b36b1ce05cd --- /dev/null +++ b/apps/server/src/orchestration-v2/laneEventRouting.conformance.json @@ -0,0 +1,126 @@ +{ + "description": "Conformance contract for lane-event routing and standing-manager mailbox rules (CLO-1302, CLO-1303). scripts/lane_event_routing.py and the t3code port must both produce these decisions.", + "cases": [ + { + "name": "replay-c964fe48-98fbc01a-settled-launcher-zero-wakes", + "comment": "Audit thread c964fe48 settled; child 98fbc01a (declarative factory RFC) ended repeatedly across 10 runs with no open PR and no failure, plus a later provider-limit failure repeated with different numbers. The launcher must never be woken.", + "world": {"threads": {"c964fe48": {"state": "settled"}, "98fbc01a": {"state": "idle"}}, "delivered": []}, + "events": [ + {"child_thread_id": "98fbc01a", "owner": "c964fe48", "kind": "lane-ended", "condition": {"outcome": "completed"}}, + {"child_thread_id": "98fbc01a", "owner": "c964fe48", "kind": "lane-ended", "condition": {"outcome": "completed"}}, + {"child_thread_id": "98fbc01a", "owner": "c964fe48", "kind": "lane-ended", "condition": {"outcome": "completed"}}, + {"child_thread_id": "98fbc01a", "owner": "c964fe48", "kind": "lane-ended", "condition": {"outcome": "failed", "error": "Antigravity usage limit reached, resets at 2026-12-03T07:01:49Z"}}, + {"child_thread_id": "98fbc01a", "owner": "c964fe48", "kind": "lane-ended", "condition": {"outcome": "failed", "error": "Antigravity usage limit reached, resets at 2026-12-03T07:01:50Z"}}, + {"child_thread_id": "98fbc01a", "owner": "c964fe48", "kind": "lane-ended", "condition": {"outcome": "completed"}} + ], + "expect_actions": ["digest", "drop", "drop", "digest", "drop", "drop"], + "expect_wakes": 0 + }, + { + "name": "archived-or-missing-launcher-is-detached", + "world": {"threads": {"child": {"state": "idle"}, "gone": {"state": "archived"}}, "delivered": []}, + "events": [ + {"child_thread_id": "child", "owner": "gone", "kind": "lane-ended", "condition": {"outcome": "failed", "error": "boom 3"}}, + {"child_thread_id": "child", "owner": "never-existed", "kind": "lane-ended", "condition": {"outcome": "failed", "error": "boom 4"}} + ], + "expect_actions": ["digest", "drop"], + "expect_wakes": 0 + }, + { + "name": "active-owner-one-alert-per-condition", + "comment": "The owner is active and the child ended with an open PR: wake once, then drop identical repeats; a changed open-PR set is a new condition.", + "world": {"threads": {"owner": {"state": "idle"}, "child": {"state": "idle"}}, "delivered": []}, + "events": [ + {"child_thread_id": "child", "owner": "owner", "kind": "lane-ended", "condition": {"outcome": "completed", "open_prs": ["org/repo#1"]}}, + {"child_thread_id": "child", "owner": "owner", "kind": "lane-ended", "condition": {"outcome": "completed", "open_prs": ["org/repo#1"]}}, + {"child_thread_id": "child", "owner": "owner", "kind": "lane-ended", "condition": {"outcome": "completed", "open_prs": ["org/repo#1", "org/repo#2"]}}, + {"child_thread_id": "child", "owner": "owner", "kind": "lane-ended", "condition": {"outcome": "completed", "open_prs": ["org/repo#2", "org/repo#1"]}} + ], + "expect_actions": ["wake", "drop", "wake", "drop"], + "expect_wakes": 2 + }, + { + "name": "same-failure-class-different-numbers-dedupes", + "world": {"threads": {"owner": {"state": "idle"}, "child": {"state": "idle"}}, "delivered": []}, + "events": [ + {"child_thread_id": "child", "owner": "owner", "kind": "lane-ended", "condition": {"outcome": "failed", "error": "HTTP 500 for request 1234"}}, + {"child_thread_id": "child", "owner": "owner", "kind": "lane-ended", "condition": {"outcome": "failed", "error": "HTTP 500 for request 9876"}}, + {"child_thread_id": "child", "owner": "owner", "kind": "lane-ended", "condition": {"outcome": "failed", "error": "disk full"}} + ], + "expect_actions": ["wake", "drop", "wake"], + "expect_wakes": 2 + }, + { + "name": "target-running-drops", + "world": {"threads": {"owner": {"state": "idle"}, "child": {"state": "running"}}, "delivered": []}, + "events": [ + {"child_thread_id": "child", "owner": "owner", "kind": "lane-ended", "condition": {"outcome": "failed", "error": "x"}}, + {"child_thread_id": "child", "owner": "owner", "kind": "pr-checks-failed", "superseded": true, "condition": {"outcome": "failed"}} + ], + "expect_actions": ["drop", "drop"], + "expect_wakes": 0 + }, + { + "name": "pr-events-routing", + "comment": "Passing checks and merges go to the merge-queue code handler; only failures and review requests wake a model.", + "world": {"threads": {"owner": {"state": "idle"}, "child": {"state": "idle"}}, "delivered": []}, + "events": [ + {"child_thread_id": "child", "owner": "owner", "kind": "pr-checks-passed", "condition": {"outcome": "passed", "open_prs": ["org/repo#9"]}}, + {"child_thread_id": "child", "owner": "owner", "kind": "pr-merged", "condition": {"outcome": "merged", "open_prs": []}}, + {"child_thread_id": "child", "owner": "owner", "kind": "pr-checks-failed", "condition": {"outcome": "failed", "error": "lint failed", "open_prs": ["org/repo#9"]}}, + {"child_thread_id": "child", "owner": "owner", "kind": "review-requested", "condition": {"outcome": "review", "open_prs": ["org/repo#9"]}} + ], + "expect_actions": ["code-handler", "code-handler", "wake", "wake"], + "expect_wakes": 2 + }, + { + "name": "requester-is-used-when-no-owner", + "world": {"threads": {"req": {"state": "settled"}, "child": {"state": "idle"}}, "delivered": []}, + "events": [ + {"child_thread_id": "child", "requester": "req", "kind": "lane-ended", "condition": {"outcome": "failed", "error": "z"}} + ], + "expect_actions": ["digest"], + "expect_wakes": 0 + }, + { + "name": "mailbox-founder-first-and-batched", + "comment": "Seven queued messages become one turn: founder first, then CEO, then the rest in arrival order. Digest items start no turn.", + "queued": [ + {"id": "m1", "at": "2026-11-27T10:00:00Z", "sender_role": "agent"}, + {"id": "m2", "at": "2026-11-27T10:01:00Z", "sender_role": "ceo"}, + {"id": "m3", "at": "2026-11-27T10:02:00Z", "sender_role": "agent"}, + {"id": "m4", "at": "2026-11-27T10:03:00Z", "sender_role": "founder"}, + {"id": "d1", "at": "2026-11-27T10:04:00Z", "sender_role": "agent", "kind": "digest"} + ], + "current_priority": null, + "expect": {"turns": 1, "batch": ["m4", "m2", "m1", "m3"], "digest": ["d1"], "preempt": false} + }, + { + "name": "mailbox-digest-only-starts-no-turn", + "queued": [ + {"id": "d1", "at": "2026-11-27T10:00:00Z", "sender_role": "agent", "kind": "digest"}, + {"id": "d2", "at": "2026-11-27T10:01:00Z", "sender_role": "agent", "kind": "digest"} + ], + "current_priority": null, + "expect": {"turns": 0, "batch": [], "digest": ["d1", "d2"], "preempt": false} + }, + { + "name": "mailbox-founder-preempts-agent-turn", + "queued": [{"id": "f1", "at": "2026-11-27T10:00:00Z", "sender_role": "founder"}], + "current_priority": 2, + "expect": {"turns": 1, "batch": ["f1"], "digest": [], "preempt": true} + }, + { + "name": "mailbox-ceo-preempts-agent-turn-not-founder-turn", + "queued": [{"id": "c1", "at": "2026-11-27T10:00:00Z", "sender_role": "ceo"}], + "current_priority": 0, + "expect": {"turns": 1, "batch": ["c1"], "digest": [], "preempt": false} + }, + { + "name": "mailbox-agent-does-not-preempt", + "queued": [{"id": "a1", "at": "2026-11-27T10:00:00Z", "sender_role": "agent"}], + "current_priority": 2, + "expect": {"turns": 1, "batch": ["a1"], "digest": [], "preempt": false} + } + ] +} diff --git a/apps/server/src/orchestration-v2/laneEventRouting.test.ts b/apps/server/src/orchestration-v2/laneEventRouting.test.ts new file mode 100644 index 0000000000000..f5c8d3e2327d1 --- /dev/null +++ b/apps/server/src/orchestration-v2/laneEventRouting.test.ts @@ -0,0 +1,100 @@ +// @effect-diagnostics nodeBuiltinImport:off -- Hashes the vendored contract bytes against the Home pin. +import * as NodeCrypto from "node:crypto"; +import * as NodeFS from "node:fs"; + +import { assert, describe, it } from "@effect/vitest"; + +import { + laneFailureClass, + replayLaneEvents, + type LaneEvent, + type LaneWorld, +} from "./laneEventRouting.ts"; + +// sha256 of config/lane-event-routing/conformance.json in nullStack65/closura-agent-config at +// 40e39541c6. Update both together; the Python reference and this port must agree on one contract. +const HOME_CONFORMANCE_SHA256 = "e6460764fd173a4b7e4c3391f5b46f3e0ff8d0ac62a341ff41f025109c28a99f"; + +const raw = NodeFS.readFileSync(new URL("./laneEventRouting.conformance.json", import.meta.url)); +const contract = JSON.parse(raw.toString("utf8")) as { + readonly cases: ReadonlyArray<{ + readonly name: string; + readonly world?: LaneWorld; + readonly events?: ReadonlyArray; + readonly expect_actions?: ReadonlyArray; + readonly expect_wakes?: number; + }>; +}; +const sha256 = (bytes: Buffer) => NodeCrypto.createHash("sha256").update(bytes).digest("hex"); + +describe("lane event routing conformance", () => { + it("vendors the Home contract byte for byte", () => { + assert.strictEqual(sha256(raw), HOME_CONFORMANCE_SHA256); + // Set in a Home + t3code checkout to catch drift before the pin is bumped. + const homeCopy = process.env.CLOSURA_LANE_EVENT_CONFORMANCE; + if (homeCopy && NodeFS.existsSync(homeCopy)) { + assert.strictEqual(sha256(NodeFS.readFileSync(homeCopy)), HOME_CONFORMANCE_SHA256); + } + }); + + const eventCases = contract.cases.filter((c) => c.events !== undefined); + + it("covers every lane-event case in the contract", () => { + assert.isAtLeast(eventCases.length, 7); + }); + + it.each(eventCases)("$name", (testCase) => { + const decisions = replayLaneEvents( + testCase.events ?? [], + testCase.world ?? { threads: {}, delivered: [] }, + ); + assert.deepStrictEqual( + decisions.map((decision) => decision.action), + testCase.expect_actions, + ); + assert.strictEqual( + decisions.filter((decision) => decision.action === "wake").length, + testCase.expect_wakes, + ); + }); + + it("routes every c964fe48 alert about 98fbc01a away from the settled launcher", () => { + const replay = contract.cases.find((c) => c.name.startsWith("replay-c964fe48-98fbc01a")); + assert.isDefined(replay); + const decisions = replayLaneEvents(replay?.events ?? [], replay?.world as LaneWorld); + assert.strictEqual(decisions.length, 6); + for (const decision of decisions) { + assert.notStrictEqual(decision.recipient, "c964fe48"); + assert.notStrictEqual(decision.action, "wake"); + } + }); + + it("classes provider limits together and strips digits and uuids", () => { + assert.strictEqual(laneFailureClass("HTTP 429 Too Many Requests"), "provider-limit"); + assert.strictEqual(laneFailureClass("Out of usage until 7pm"), "provider-limit"); + assert.strictEqual( + laneFailureClass("run 0b6d8a8e-1c1f-4d1e-9b0a-1a2b3c4d5e6f failed after 12 tries"), + laneFailureClass("run 9f9f9f9f-0000-4000-8000-000000000000 failed after 3 tries"), + ); + assert.strictEqual(laneFailureClass(null), "none"); + }); + + it("reports the same failure again after recovery, but suppresses repeats within an episode", () => { + const failed: LaneEvent = { + child_thread_id: "child", + owner: "owner", + condition: { outcome: "failed", error: "disk full" }, + }; + const recovered: LaneEvent = { + ...failed, + condition: { outcome: "completed" }, + }; + assert.deepEqual( + replayLaneEvents([failed, failed, recovered, failed, failed], { + threads: { child: { state: "idle" }, owner: { state: "idle" } }, + delivered: [], + }).map((decision) => decision.action), + ["wake", "drop", "digest", "wake", "drop"], + ); + }); +}); diff --git a/apps/server/src/orchestration-v2/laneEventRouting.ts b/apps/server/src/orchestration-v2/laneEventRouting.ts new file mode 100644 index 0000000000000..0eb3ecfefe01c --- /dev/null +++ b/apps/server/src/orchestration-v2/laneEventRouting.ts @@ -0,0 +1,174 @@ +/** + * Lane-event routing (Closura CLO-1302). A port of `scripts/lane_event_routing.py` in + * nullStack65/closura-agent-config; both must agree with `laneEventRouting.conformance.json`. + */ + +export type LaneThreadState = "running" | "idle" | "settled" | "archived" | "deleted" | "missing"; + +export interface LaneCondition { + readonly outcome?: string | null; + readonly error?: string | null; + readonly open_prs?: ReadonlyArray | null; + readonly question?: string | null; +} + +export interface LaneEvent { + readonly child_thread_id: string; + readonly owner?: string | null; + readonly requester?: string | null; + readonly kind?: string; + readonly superseded?: boolean; + readonly condition?: LaneCondition | null; + readonly set_state?: Readonly>; +} + +export interface LaneWorld { + readonly threads: Readonly>; + readonly delivered: ReadonlyArray; +} + +export type LaneAction = "drop" | "digest" | "wake" | "code-handler"; + +export interface LaneDecision { + readonly action: LaneAction; + readonly recipient: string | null; + readonly reason: string; + readonly handler?: "merge-queue"; + readonly deliveredKey?: string; +} + +/** The agent-only role that receives detached digests; it never starts a turn. */ +export const LANE_DIGEST_ROLE = "ops-bus"; + +const INACTIVE_STATES = new Set(["settled", "archived", "deleted", "missing"]); +const CODE_HANDLED_KINDS = new Set(["pr-checks-passed", "pr-merged"]); +const WAKING_KINDS = new Set(["pr-checks-failed", "review-requested", "founder-question"]); +const UUID = /[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}/g; +const PROVIDER_LIMIT = /usage limit|quota|rate.?limit|out of usage|\b429\b|capacity/; + +export const laneFailureClass = (error: string | null | undefined): string => { + const text = (error ?? "").toLowerCase().replace(UUID, ""); + if (PROVIDER_LIMIT.test(text)) return "provider-limit"; + const normalized = text.replace(/\d+/g, "#").replace(/\s+/g, " ").trim().slice(0, 60); + return normalized === "" ? "none" : normalized; +}; + +export const laneConditionKey = (event: LaneEvent): string => { + const condition = event.condition ?? {}; + const prs = [...(condition.open_prs ?? [])].map(String).toSorted().join(","); + return `${condition.outcome || "ended"}|${laneFailureClass(condition.error)}|${prs}`; +}; + +export const laneDeliveredKey = (recipient: string, event: LaneEvent): string => + `${recipient}>${event.child_thread_id}>${laneConditionKey(event)}`; + +/** Recovery retires actionable conditions; a no-work digest stays quiet across later runs. */ +export const retainLaneDelivered = ( + delivered: ReadonlyArray, + childId: string, + condition: string | null, +): string[] => + delivered.filter((key) => { + const child = key.indexOf(">") + 1; + const prefix = `${childId}>`; + if (!key.slice(child).startsWith(prefix)) return true; + const previous = key.slice(child + prefix.length); + return previous === condition || previous.endsWith("|none|"); + }); + +export const laneThreadState = ( + shell: { + readonly deletedAt: unknown; + readonly archivedAt: unknown; + readonly settledOverride: string | null; + readonly activeRunId: unknown; + readonly activityRunStatus?: unknown; + } | null, +): LaneThreadState => { + if (shell === null) return "missing"; + if (shell.deletedAt !== null) return "deleted"; + if (shell.archivedAt !== null) return "archived"; + if (shell.settledOverride === "settled") return "settled"; + if (shell.activeRunId !== null || (shell.activityRunStatus ?? null) !== null) return "running"; + return "idle"; +}; + +const recipientOf = (event: LaneEvent): string | null => event.owner || event.requester || null; + +export const decideLaneEvent = (event: LaneEvent, world: LaneWorld): LaneDecision => { + const delivered = new Set(world.delivered); + const kind = event.kind ?? "lane-ended"; + + if (world.threads[event.child_thread_id]?.state === "running" || event.superseded) { + return { action: "drop", recipient: null, reason: "target running or superseded" }; + } + + const recipient = recipientOf(event); + const state = recipient ? (world.threads[recipient]?.state ?? "missing") : "missing"; + if (INACTIVE_STATES.has(state)) { + const key = laneDeliveredKey(LANE_DIGEST_ROLE, event); + if (delivered.has(key)) { + return { + action: "drop", + recipient: LANE_DIGEST_ROLE, + reason: "digest already delivered for condition", + }; + } + return { + action: "digest", + recipient: LANE_DIGEST_ROLE, + reason: `recipient ${state}; detached`, + deliveredKey: key, + }; + } + + const owner = recipient as string; + const key = laneDeliveredKey(owner, event); + if (delivered.has(key)) { + return { action: "drop", recipient: owner, reason: "already delivered for condition" }; + } + if (CODE_HANDLED_KINDS.has(kind)) { + return { + action: "code-handler", + recipient: owner, + handler: "merge-queue", + reason: "pr event handled by code", + deliveredKey: key, + }; + } + if (WAKING_KINDS.has(kind)) { + return { action: "wake", recipient: owner, reason: kind, deliveredKey: key }; + } + const condition = event.condition ?? {}; + if ((condition.open_prs ?? []).length === 0 && !condition.error && !condition.question) { + return { + action: "digest", + recipient: owner, + reason: "only action is to re-settle", + deliveredKey: key, + }; + } + return { + action: "wake", + recipient: owner, + reason: "open work or failure on the lane", + deliveredKey: key, + }; +}; + +export const replayLaneEvents = ( + events: ReadonlyArray, + world: LaneWorld, +): ReadonlyArray => { + const threads: Record = { ...world.threads }; + let delivered = [...world.delivered]; + return events.map((event) => { + for (const [id, patch] of Object.entries(event.set_state ?? {})) threads[id] = patch; + if (threads[event.child_thread_id]?.state !== "running" && !event.superseded) { + delivered = retainLaneDelivered(delivered, event.child_thread_id, laneConditionKey(event)); + } + const decision = decideLaneEvent(event, { threads, delivered }); + if (decision.deliveredKey) delivered.push(decision.deliveredKey); + return decision; + }); +}; diff --git a/packages/contracts/src/eventSubscription.ts b/packages/contracts/src/eventSubscription.ts index 49ebdff19d2da..84a0e6ad48a3c 100644 --- a/packages/contracts/src/eventSubscription.ts +++ b/packages/contracts/src/eventSubscription.ts @@ -38,9 +38,18 @@ export const PullRequestEventFilter = Schema.Union([ ]); export type PullRequestEventFilter = typeof PullRequestEventFilter.Type; -/** Names match the thread-alert kinds the server already judges. */ +/** + * Names match the thread-alert kinds the server already judges. `wake-suppressed` matches no + * finding: its presence turns every server wake for the watched thread into a digest. + */ export const ThreadEventFilter = Schema.Struct({ - name: Schema.Literals(["lane-ended", "promise-without-wake", "stuck", "needs-person"]), + name: Schema.Literals([ + "lane-ended", + "promise-without-wake", + "stuck", + "needs-person", + "wake-suppressed", + ]), }); export type ThreadEventFilter = typeof ThreadEventFilter.Type; diff --git a/vite.config.ts b/vite.config.ts index eeaec48bb9e53..c995cea50217b 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -183,6 +183,8 @@ export default defineConfig({ "infra/task-cache/vendor/**", // Macroscope requires one glob per line; Markdown formatting corrupts it. ".macroscope/ignore.md", + // Closura: byte-pinned copy of the Home lane-event contract; formatting breaks its sha test. + "apps/server/src/orchestration-v2/laneEventRouting.conformance.json", // Rendered by qa/render-map.ts from qa/features.ts; the next sweep rewrites it. "docs/FEATURES.md", ".alchemy",