From 82b71c7a34d4030430ee90ccafd985b07ab99e18 Mon Sep 17 00:00:00 2001 From: Kameron Smith <112618179+nullStack65@users.noreply.github.com> Date: Sat, 21 Nov 2026 07:20:27 +0000 Subject: [PATCH] feat(server): fine-grained event subscriptions Let a thread subscribe to the pull-request and thread events that should wake it. Ignored authors, including coderabbitai by default, no longer wake a watch, and unimplemented selectors fail instead of matching everything. Model: grok-4.7 Task: feat(server): fine-grained event subscriptions Agent: Platform Harness: t3 --- apps/server/src/mcp/McpHttpServer.ts | 7 + apps/server/src/mcp/advertisedJsonSchema.ts | 15 + .../src/mcp/toolkits/events/handlers.ts | 124 +++ apps/server/src/mcp/toolkits/events/tools.ts | 118 +++ .../src/mcp/toolkits/pullRequests/handlers.ts | 91 ++- .../src/mcp/toolkits/pullRequests/tools.ts | 16 +- .../src/orchestration-v2/ModelAlertReactor.ts | 237 +++++- .../PullRequestWatchReactor.ts | 255 +++++- .../eventSubscription.test.ts | 428 ++++++++++ .../src/orchestration-v2/eventSubscription.ts | 747 ++++++++++++++++++ .../persistence/EventSubscriptions.test.ts | 60 ++ .../src/persistence/EventSubscriptions.ts | 222 ++++++ apps/server/src/persistence/Migrations.ts | 2 + .../Migrations/098_EventSubscriptions.ts | 22 + .../src/provider/agentContextBudget.json | 2 +- apps/server/src/server.ts | 2 + docs/rfcs/event-subscriptions.md | 60 ++ docs/user/source-control.md | 2 +- packages/client-runtime/src/t3ToolSummary.ts | 9 + packages/contracts/src/eventSubscription.ts | 176 +++++ packages/contracts/src/index.ts | 1 + packages/shared/src/t3McpToolPresentation.ts | 18 + 22 files changed, 2547 insertions(+), 67 deletions(-) create mode 100644 apps/server/src/mcp/toolkits/events/handlers.ts create mode 100644 apps/server/src/mcp/toolkits/events/tools.ts create mode 100644 apps/server/src/orchestration-v2/eventSubscription.test.ts create mode 100644 apps/server/src/orchestration-v2/eventSubscription.ts create mode 100644 apps/server/src/persistence/EventSubscriptions.test.ts create mode 100644 apps/server/src/persistence/EventSubscriptions.ts create mode 100644 apps/server/src/persistence/Migrations/098_EventSubscriptions.ts create mode 100644 docs/rfcs/event-subscriptions.md create mode 100644 packages/contracts/src/eventSubscription.ts diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 2b69ea9c74cce..7f3af52758ce2 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -75,6 +75,8 @@ import { import * as WorktreeHandlers from "./toolkits/worktree/handlers.ts"; import { WorktreeToolkit } from "./toolkits/worktree/tools.ts"; import * as WorktreeMcpService from "./WorktreeMcpService.ts"; +import * as EventsHandlers from "./toolkits/events/handlers.ts"; +import { EventsToolkit } from "./toolkits/events/tools.ts"; import * as PullRequestsHandlers from "./toolkits/pullRequests/handlers.ts"; import * as ToolSearchHandlers from "./toolkits/toolSearch/handlers.ts"; import { ToolSearchToolkit } from "./toolkits/toolSearch/tools.ts"; @@ -1315,6 +1317,10 @@ export const layerPullRequestsToolkit = toolkitRegistration( PullRequestsHandlers.layer, ).pipe(Layer.provide(PullRequestWatchService.layer)); +export const layerEventsToolkit = toolkitRegistration(EventsToolkit, EventsHandlers.layer).pipe( + Layer.provide(PullRequestWatchService.layer), +); + const layerDeviceStandardToolkitRegistration = toolkitRegistration( DeviceStandardToolkit, DeviceHandlers.layerStandard, @@ -1372,6 +1378,7 @@ export const layerTools = Layer.mergeAll( layerPreviewControlsRegistration, layerWorktreeToolkitRegistration, layerPullRequestsToolkit, + layerEventsToolkit, layerDeviceToolkit, layerHtmlToolkit, layerMessageToolkit, diff --git a/apps/server/src/mcp/advertisedJsonSchema.ts b/apps/server/src/mcp/advertisedJsonSchema.ts index 8b8737a529183..16328b5f7ce17 100644 --- a/apps/server/src/mcp/advertisedJsonSchema.ts +++ b/apps/server/src/mcp/advertisedJsonSchema.ts @@ -71,7 +71,22 @@ const mergeTaggedObjects = (branches: ReadonlyArray): JsonObject | undefin return { type: "object", properties, required: [tag, ...requiredByAll] }; }; +// Effect encodes `Schema.Struct({})` as "not null". MCP requires `type: object`. +const isEmptyObjectSchema = (value: Json) => + Predicate.isObject(value) && + isNullSchema(value.not) && + (value.allOf === undefined || + (Array.isArray(value.allOf) && + value.allOf.every( + (part) => + Predicate.isObject(part) && + part.type === "object" && + Predicate.isObject(part.properties) && + Object.keys(part.properties).length === 0, + ))); + const compact = (schema: Json, optional: boolean): Json => { + if (isEmptyObjectSchema(schema)) return { type: "object", properties: {} }; if (Array.isArray(schema)) return schema.map((item) => compact(item, false)); if (!Predicate.isObject(schema)) return schema; const required = new Set(Array.isArray(schema.required) ? schema.required : []); diff --git a/apps/server/src/mcp/toolkits/events/handlers.ts b/apps/server/src/mcp/toolkits/events/handlers.ts new file mode 100644 index 0000000000000..ec0cfd1307ebf --- /dev/null +++ b/apps/server/src/mcp/toolkits/events/handlers.ts @@ -0,0 +1,124 @@ +import { + EventSubscriptionInvalidError, + PullRequestUnavailableError, + ThreadId, +} from "@t3tools/contracts"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import { prepareSubscribe } from "../../../orchestration-v2/eventSubscription.ts"; +import * as EventSubscriptionStore from "../../../persistence/EventSubscriptions.ts"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; +import * as McpToolAccess from "../../McpToolAccess.ts"; +import { + PullRequestHostRequiredError, + PullRequestTargetIncompleteError, + PullRequestUrlInvalidError, + PullRequestUrlUnavailableError, +} from "../../../pullRequest/pullRequestTarget.ts"; +import * as PullRequestWatchService from "../../../pullRequest/PullRequestWatchService.ts"; +import { EventsToolkit, type EventSubscribeInput } from "./tools.ts"; + +const unavailable = () => + new EventSubscriptionInvalidError({ + detail: "Event subscriptions are not available on this server.", + }); + +type WatchPullRequestError = + | PullRequestWatchService.PullRequestWatchFailedError + | PullRequestWatchService.PullRequestNotOpenError + | PullRequestWatchService.PullRequestWatchFromSubagentError + | PullRequestWatchService.PullRequestWatchThreadNotFoundError + | PullRequestUrlInvalidError + | PullRequestTargetIncompleteError + | PullRequestHostRequiredError + | PullRequestUrlUnavailableError + | PullRequestUnavailableError; + +export const subscribeEvent = Effect.fn("EventsToolkit.subscribe")(function* (input: { + readonly callerThreadId: ThreadId; + readonly request: EventSubscribeInput; + readonly store: EventSubscriptionStore.EventSubscriptionStore["Service"] | null; + readonly watchPullRequest: (url: string) => Effect.Effect; + readonly id: string; + readonly createdAt: string; +}) { + const prepared = prepareSubscribe({ + id: input.id, + subscriberThreadId: input.callerThreadId, + selector: input.request.selector, + events: input.request.events, + ignoreAuthors: input.request.ignoreAuthors, + delivery: input.request.delivery, + createdAt: input.createdAt, + }); + if (!prepared.ok) return yield* prepared.error; + if (input.store === null) return yield* unavailable(); + const selector = prepared.subscription.selector; + if (selector.entity === "pull_request" && selector.by === "url") { + yield* input.watchPullRequest(selector.url); + } + return yield* input.store.put(prepared.subscription); +}); + +export const layer = McpToolAccess.toLayer( + EventsToolkit, + Effect.gen(function* () { + const subscriptions = yield* Effect.serviceOption( + EventSubscriptionStore.EventSubscriptionStore, + ); + const watches = yield* PullRequestWatchService.PullRequestWatchService; + const random = yield* SecureRandom.SecureRandom; + const store = Option.getOrNull(subscriptions); + + const callerThreadId = Effect.gen(function* () { + const scope = yield* McpInvocationContext.McpInvocationContext; + const threadId = scope.thread?.threadId; + if (threadId === undefined) { + return yield* new EventSubscriptionInvalidError({ + detail: "This tool must be called from a thread.", + }); + } + return threadId; + }); + + return { + t3_event_subscribe: McpToolAccess.actsAsCaller((request) => + Effect.gen(function* () { + const callerThreadId_ = yield* callerThreadId; + const id = `evt_${yield* random.uuidV4().pipe(Effect.orDie)}`; + const createdAt = DateTime.formatIso(yield* DateTime.now); + return yield* subscribeEvent({ + callerThreadId: callerThreadId_, + request, + store, + id, + createdAt, + watchPullRequest: (url) => + watches + .setWatching({ + threadId: callerThreadId_, + target: { url }, + watching: true, + }) + .pipe(Effect.asVoid), + }); + }), + ), + t3_event_unsubscribe: McpToolAccess.actsAsCaller(({ id }) => + Effect.gen(function* () { + if (store === null) return yield* unavailable(); + return yield* store.remove(yield* callerThreadId, id); + }), + ), + t3_event_list: McpToolAccess.readsAsCaller(() => + Effect.gen(function* () { + if (store === null) return yield* unavailable(); + return { subscriptions: yield* store.listForSubscriber(yield* callerThreadId) }; + }), + ), + }; + }), +); diff --git a/apps/server/src/mcp/toolkits/events/tools.ts b/apps/server/src/mcp/toolkits/events/tools.ts new file mode 100644 index 0000000000000..6bab4ea8db257 --- /dev/null +++ b/apps/server/src/mcp/toolkits/events/tools.ts @@ -0,0 +1,118 @@ +import { + EventFilter, + EventSelector, + EventSubscription, + EventSubscriptionInvalidError, + EventSubscriptionPhase2Error, + EventSubscriptionSelectorUnsupportedError, + OrchestratorMcpFailure, + QuietHours, +} from "@t3tools/contracts"; +import { McpSchema, Tool, Toolkit } from "effect/ai"; +import * as Schema from "effect/Schema"; + +import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts"; +import { PersistenceDecodeError, PersistenceSqlError } from "../../../persistence/Errors.ts"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; +import * as PullRequestWatchService from "../../../pullRequest/PullRequestWatchService.ts"; +import { + PullRequestHostRequiredError, + PullRequestTargetIncompleteError, + PullRequestUrlInvalidError, + PullRequestUrlUnavailableError, +} from "../../../pullRequest/pullRequestTarget.ts"; +import { PullRequestUnavailableError } from "@t3tools/contracts"; + +const dependencies = [ + McpInvocationContext.McpInvocationContext, + ThreadManagementService.ThreadManagementService, + PullRequestWatchService.PullRequestWatchService, +]; + +const DeliveryInput = Schema.Struct({ + immediate: Schema.optional(Schema.Boolean), + coalesceWindowSeconds: Schema.optional(Schema.Int), + autoExpireOnClose: Schema.optional(Schema.Boolean), + onlyWhenIdle: Schema.optional(Schema.Boolean), + quietHours: Schema.optional(QuietHours), + maxWakesPerHour: Schema.optional(Schema.Int), +}); + +export const EventSubscribeInput = Schema.Struct({ + selector: EventSelector, + events: Schema.Array(EventFilter), + ignoreAuthors: Schema.optional(Schema.Array(Schema.String)), + delivery: Schema.optional(DeliveryInput), +}); +export type EventSubscribeInput = typeof EventSubscribeInput.Type; + +export const EventUnsubscribeInput = Schema.Struct({ + id: Schema.String, +}); +export type EventUnsubscribeInput = typeof EventUnsubscribeInput.Type; + +const failure = Schema.Union([ + OrchestratorMcpFailure, + EventSubscriptionPhase2Error, + EventSubscriptionSelectorUnsupportedError, + EventSubscriptionInvalidError, + PersistenceSqlError, + PersistenceDecodeError, + PullRequestWatchService.PullRequestWatchFailedError, + PullRequestWatchService.PullRequestNotOpenError, + PullRequestWatchService.PullRequestWatchFromSubagentError, + PullRequestWatchService.PullRequestWatchThreadNotFoundError, + PullRequestUrlInvalidError, + PullRequestTargetIncompleteError, + PullRequestHostRequiredError, + PullRequestUrlUnavailableError, + PullRequestUnavailableError, +]); + +const SubscribeTool = Tool.make("t3_event_subscribe", { + description: + "Subscribe this thread to events. Phase 1 accepts a pull request URL or a thread id. Other selectors and external sources return a typed error and are not stored.", + parameters: EventSubscribeInput, + success: EventSubscription, + failure, + failureMode: "return", + dependencies, +}) + .annotate(Tool.Title, "Subscribe to events") + .annotate(Tool.Readonly, false) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, true) + .annotate(Tool.OpenWorld, false) + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); + +const UnsubscribeTool = Tool.make("t3_event_unsubscribe", { + description: "Remove one of this thread's event subscriptions. Missing ids return removed=false.", + parameters: EventUnsubscribeInput, + success: Schema.Struct({ removed: Schema.Boolean }), + failure, + failureMode: "return", + dependencies, +}) + .annotate(Tool.Title, "Unsubscribe from events") + .annotate(Tool.Readonly, false) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, true) + .annotate(Tool.OpenWorld, false) + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); + +const ListTool = Tool.make("t3_event_list", { + description: "List this thread's event subscriptions.", + parameters: Schema.Struct({}), + success: Schema.Struct({ subscriptions: Schema.Array(EventSubscription) }), + failure, + failureMode: "return", + dependencies, +}) + .annotate(Tool.Title, "List event subscriptions") + .annotate(Tool.Readonly, true) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, true) + .annotate(Tool.OpenWorld, false) + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); + +export const EventsToolkit = Toolkit.make(SubscribeTool, UnsubscribeTool, ListTool); diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index 884dd09a3dea4..47dd006ccc59e 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -1,5 +1,6 @@ import { CommandId, + EventSubscriptionInvalidError, type OrchestrationProjectShell, type PullRequestState, type OrchestrationV2ThreadShell, @@ -8,6 +9,7 @@ import { } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; @@ -16,6 +18,11 @@ import * as ProjectService from "../../../project/ProjectService.ts"; import * as PullRequestWatchService from "../../../pullRequest/PullRequestWatchService.ts"; import { resolveTarget, type ResolvedTarget } from "../../../pullRequest/pullRequestTarget.ts"; import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts"; +import { + pullRequestSelectorKey, + watchSubscription, +} from "../../../orchestration-v2/eventSubscription.ts"; +import * as EventSubscriptionStore from "../../../persistence/EventSubscriptions.ts"; import { pullRequestSyncKey } from "../../../pullRequest/pullRequestSyncKey.ts"; import { sourceControlDefinitions } from "../../../sourceControl/sourceControlDefinitions.ts"; import { @@ -40,6 +47,7 @@ import { PullRequestProjectNotFoundError, PullRequestsToolkit, type ThreadPullRequestEntry, + type WatchPullRequestInput, CHILD_PULL_REQUEST_REPORT_NEXT, } from "./tools.ts"; @@ -147,6 +155,9 @@ const make = Effect.gen(function* () { const engine = yield* Orchestrator.OrchestratorV2; const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService; const watches = yield* PullRequestWatchService.PullRequestWatchService; + const subscriptions = Option.getOrNull( + yield* Effect.serviceOption(EventSubscriptionStore.EventSubscriptionStore), + ); const projects = yield* ProjectService.ProjectService; const random = yield* SecureRandom.SecureRandom; @@ -213,6 +224,62 @@ const make = Effect.gen(function* () { ); }); + const watchFiltersSet = (input: WatchPullRequestInput) => + input.events !== undefined || + input.ignoreAuthors !== undefined || + input.coalesceWindowSeconds !== undefined || + input.autoExpireOnClose !== undefined; + + const syncWatchSubscription = Effect.fnUntraced(function* ( + input: WatchPullRequestInput, + threadId: ThreadId, + url: string, + watching: boolean, + ) { + if (subscriptions === null) { + if (watching && watchFiltersSet(input)) { + return yield* new EventSubscriptionInvalidError({ + detail: "Event subscriptions are not available on this server.", + }); + } + return; + } + const key = pullRequestSelectorKey(url); + if (key === null) { + return yield* new EventSubscriptionInvalidError({ + detail: "The pull request URL is not valid.", + }); + } + const stored = (effect: Effect.Effect) => + effect.pipe( + Effect.tapError((cause) => + Effect.logWarning("event subscription update failed", { threadId, cause }), + ), + Effect.mapError( + () => + new EventSubscriptionInvalidError({ + detail: "Could not update the event subscription.", + }), + ), + ); + if (!watching || !watchFiltersSet(input)) { + yield* stored(subscriptions.removeKey(threadId, key)); + return; + } + const prepared = watchSubscription({ + id: `evt_${yield* random.uuidV4().pipe(Effect.orDie)}`, + subscriberThreadId: threadId, + url, + events: input.events, + ignoreAuthors: input.ignoreAuthors, + coalesceWindowSeconds: input.coalesceWindowSeconds, + autoExpireOnClose: input.autoExpireOnClose, + createdAt: DateTime.formatIso(yield* DateTime.now), + }); + if (!prepared.ok) return yield* prepared.error; + yield* stored(subscriptions.put(prepared.subscription)); + }); + const locateAll = Effect.fn("PullRequestsToolkit.locateAll")(function* ( targets: ReadonlyArray>, ) { @@ -439,8 +506,28 @@ const make = Effect.gen(function* () { Effect.map((thread) => listThreadPullRequests(thread, input.cursor, input.states)), ), ), - watch_pull_request: writesThread((input) => setWatching(input, true)), - unwatch_pull_request: writesThread((input) => setWatching(input, false)), + watch_pull_request: writesThread((input: WatchPullRequestInput) => + Effect.gen(function* () { + const result = yield* setWatching(input, true); + const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests"); + const threadId = input.threadId ?? scope.thread?.threadId; + if (threadId !== undefined) { + yield* syncWatchSubscription(input, threadId, result.url, true); + } + return result; + }), + ), + unwatch_pull_request: writesThread((input) => + Effect.gen(function* () { + const result = yield* setWatching(input, false); + const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests"); + const threadId = input.threadId ?? scope.thread?.threadId; + if (threadId !== undefined) { + yield* syncWatchSubscription(input, threadId, result.url, false); + } + return result; + }), + ), write_pull_request_guides: McpToolAccess.writesWithCapability((input) => Effect.gen(function* () { const located = yield* locateAll(input.pullRequests); diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts index 376817db10079..2bae0180d3479 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -10,6 +10,8 @@ import { ThreadPullRequestLinkSource, TrimmedNonEmptyString, ThreadId, + EventSubscriptionInvalidError, + PullRequestEventFilter, } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; import * as McpSchema from "effect/ai/McpSchema"; @@ -140,6 +142,7 @@ export const PullRequestToolError = Schema.Union([ PullRequestWatchService.PullRequestWatchFromSubagentError, PullRequestProjectNotFoundError, PullRequestGuideFailedError, + EventSubscriptionInvalidError, ]); export type PullRequestToolError = typeof PullRequestToolError.Type; @@ -324,10 +327,19 @@ const ListThreadPullRequestsTool = Tool.make("list_thread_pull_requests", { .annotate(Tool.Idempotent, true) .annotate(Tool.OpenWorld, false); +export const WatchPullRequestInput = Schema.Struct({ + ...PullRequestTargetInput.fields, + events: Schema.optional(Schema.Array(PullRequestEventFilter)), + ignoreAuthors: Schema.optional(Schema.Array(TrimmedNonEmptyString)), + coalesceWindowSeconds: Schema.optional(Schema.Int), + autoExpireOnClose: Schema.optional(Schema.Boolean), +}); +export type WatchPullRequestInput = typeof WatchPullRequestInput.Type; + const WatchPullRequestTool = Tool.make("watch_pull_request", { description: - "Watch an open PR for this thread, linking it first if needed. T3 wakes you on failed checks, passed required checks, new comments or reviews, or conflicts. Handle old comments first. Only later ones wake you. After this call, end your turn. The watch stays on after each wake, so do not call this again on a wake. A wake is not a merge decision. Check readiness yourself.", - parameters: PullRequestTargetInput, + "Watch an open PR for this thread, linking it first if needed. T3 wakes you on failed checks, passed required checks, new comments or reviews, or conflicts. Comments from coderabbitai do not wake unless ignoreAuthors is []. Optional events, coalesceWindowSeconds, and autoExpireOnClose narrow wakes. Handle old comments first. Only later ones wake you. After this call, end your turn. The watch stays on after each wake, so do not call this again on a wake. A wake is not a merge decision. Check readiness yourself.", + parameters: WatchPullRequestInput, success: WatchPullRequestResult, failure: PullRequestToolError, dependencies: watchDependencies, diff --git a/apps/server/src/orchestration-v2/ModelAlertReactor.ts b/apps/server/src/orchestration-v2/ModelAlertReactor.ts index ca74703d4f38a..f3f875d6e08c6 100644 --- a/apps/server/src/orchestration-v2/ModelAlertReactor.ts +++ b/apps/server/src/orchestration-v2/ModelAlertReactor.ts @@ -1,5 +1,6 @@ import { CommandId, + type EventSubscription, type EnvironmentId, isListedThreadLineage, MessageId, @@ -18,6 +19,7 @@ import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; import { formatThreadLink } from "@t3tools/shared/threadLinks"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; +import * as Option from "effect/Option"; import * as Digest from "effect/crypto/Digest"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -35,6 +37,7 @@ import * as Stream from "effect/Stream"; import * as HttpClient from "effect/http/HttpClient"; import * as HttpClientRequest from "effect/http/HttpClientRequest"; +import * as EventSubscriptionStore from "../persistence/EventSubscriptions.ts"; import * as ServerConfig from "../config.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as PeerMcpClient from "../peer/PeerMcpClient.ts"; @@ -43,6 +46,12 @@ import * as ServerSettings from "../serverSettings.ts"; import * as Orchestrator from "./Orchestrator.ts"; import { ProviderExhaustion } from "./ProviderExhaustion.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; +import { + cursorOf, + planThreadSubscription, + threadSelectorKey, + withCursor, +} from "./eventSubscription.ts"; import { judgeThread, threadEventAlert, @@ -746,7 +755,6 @@ export const watcherAlertMessage = (alert: WatcherAlert) => { } }; - /** Alerts ride in the watcher's next digest; a newer alert on the same subject replaces an older one. */ function alertDelivery(alert: WatcherAlert): { readonly coalesceKey: string; @@ -859,6 +867,10 @@ const TERMINAL_RUN_STATUSES: ReadonlyArray = [ export const make = Effect.gen(function* () { const engine = yield* Orchestrator.OrchestratorV2; + const subscriptionStore = yield* Effect.serviceOption( + EventSubscriptionStore.EventSubscriptionStore, + ); + let eventWakeSeq = 0; const projections = yield* ProjectionStore.ProjectionStoreV2; const settings = yield* ServerSettings.ServerSettingsService; const environment = yield* ServerEnvironment.ServerEnvironment; @@ -1161,7 +1173,158 @@ export const make = Effect.gen(function* () { return { _tag: "sent" } satisfies DeliveryResult; }); + const cursorUnchanged = (current: EventSubscription, next: EventSubscription) => + current.coalesceUntilMs === next.coalesceUntilMs && + current.pendingSummaries.join("\0") === next.pendingSummaries.join("\0") && + current.wakeTimesMs.join(",") === next.wakeTimesMs.join(",") && + JSON.stringify(current.deliveredSignatures) === JSON.stringify(next.deliveredSignatures); + + const subscriberIsIdle = Effect.fnUntraced(function* (subscription: EventSubscription) { + if (!subscription.delivery.onlyWhenIdle) return true; + const shell = yield* projections + .getThreadShell(subscription.subscriberThreadId) + .pipe(Effect.catchCause(() => Effect.succeed(null))); + return ( + shell !== null && + shell.deletedAt === null && + shell.activeRunId === null && + (shell.activityRunStatus ?? null) === null + ); + }); + + const applyThreadPlan = Effect.fnUntraced(function* ( + subscription: EventSubscription, + watchedThreadId: ThreadId, + title: string, + findings: ReadonlyArray<{ + readonly kind: string; + readonly detail: string; + readonly signature: string; + }>, + settled: boolean, + ) { + if (Option.isNone(subscriptionStore)) return; + const store = subscriptionStore.value; + const decision = planThreadSubscription({ + findings, + events: subscription.events ?? [], + delivery: subscription.delivery, + idle: yield* subscriberIsIdle(subscription), + nowMs: yield* Clock.currentTimeMillis, + state: cursorOf(subscription), + settled, + }); + if (decision.action === "wake") { + eventWakeSeq += 1; + const seq = eventWakeSeq; + yield* engine + .dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`server:event-sub:${subscription.id}:${seq}`), + threadId: subscription.subscriberThreadId, + messageId: MessageId.make(`message:event-sub:${subscription.id}:${seq}`), + text: [ + `Update on thread ${title} (${watchedThreadId}), which you subscribed to:`, + ...decision.summaries, + ].join("\n"), + notification: { + source: { kind: "monitor" }, + outcome: "updated", + summary: decision.summaries[0] ?? "thread event", + }, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }) + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("event subscription wake failed", { + id: subscription.id, + threadId: subscription.subscriberThreadId, + cause, + }), + ), + ); + } + 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; + } + 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 }), + ), + ); + }); + + const subscriptionsForThread = (threadId: ThreadId) => + Option.isNone(subscriptionStore) + ? Effect.succeed>([]) + : subscriptionStore.value + .listForSelector(threadSelectorKey(threadId)) + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("event subscription read failed", { threadId, cause }).pipe( + Effect.as>([]), + ), + ), + ); + + const flushPendingThreadSubscriptions = Effect.gen(function* () { + if (Option.isNone(subscriptionStore)) return; + const rows = yield* subscriptionStore.value + .listAll() + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("event subscription flush failed", { cause }).pipe( + Effect.as>([]), + ), + ), + ); + yield* Effect.forEach( + rows.filter((row) => row.selector.entity === "thread" && row.pendingSummaries.length > 0), + (subscription) => + Effect.gen(function* () { + if ( + subscription.selector.entity !== "thread" || + subscription.selector.by !== "thread_id" + ) { + return; + } + const shell = yield* projections + .getThreadShell(subscription.selector.threadId) + .pipe(Effect.catchCause(() => Effect.succeed(null))); + yield* applyThreadPlan( + subscription, + subscription.selector.threadId, + shell?.title ?? subscription.selector.threadId, + [], + false, + ); + }), + { discard: true }, + ); + }); + const flush: ModelAlertReactor["Service"]["flush"] = Effect.gen(function* () { + yield* flushPendingThreadSubscriptions.pipe( + Effect.catchCause((cause) => + Effect.logWarning("flushing thread event subscriptions failed", { cause }), + ), + ); const nowMs = yield* Clock.currentTimeMillis; const due = (yield* Ref.get(state)).outbox.filter((entry) => entry.nextAttemptAt <= nowMs); if (due.length === 0) return; @@ -1363,9 +1526,12 @@ export const make = Effect.gen(function* () { const current = yield* settings.getSettings; const here = yield* environment.getEnvironmentId; const watcher = current.modelAlertWatcher; - // The watcher's own turns would report to itself forever. - if (watcher?.environmentId === here && watcher.threadId === threadId) return; - if (watcher === null && current.modelAlertWebhookUrl.trim() === "") return; + // The watcher's own turns would report to itself forever. A subscription on that + // thread still delivers to its subscriber. + const selfWatch = watcher?.environmentId === here && watcher.threadId === threadId; + const noGlobalDestination = watcher === null && current.modelAlertWebhookUrl.trim() === ""; + const subscribed = yield* subscriptionsForThread(threadId); + if ((selfWatch || noGlobalDestination) && subscribed.length === 0) return; const shell = yield* projections.getThreadShell(threadId); if (shell === null || shell.deletedAt !== null) return; const nowMs = yield* Clock.currentTimeMillis; @@ -1381,31 +1547,52 @@ export const make = Effect.gen(function* () { const occurredAt = DateTime.formatIso(yield* DateTime.now); const recipient = yield* launchingThread(shell, here); const destinations = threadEventDestinations(recipient, current.modelAlertWebhookUrl); - if (recipient === null && destinations.length === 0 && judged.findings.length > 0) { + if ( + !selfWatch && + !noGlobalDestination && + recipient === null && + destinations.length === 0 && + judged.findings.length > 0 + ) { yield* Effect.logWarning("a thread event has no launching thread and no webhook", { threadId, kinds: judged.findings.map((finding) => finding.kind), }); } - const enqueued = yield* update((state) => { - const result = recordThreadEvents( - state, - { threadId, evaluated: judged.evaluated, findings: judged.findings }, - (finding) => - threadEventAlert({ - environmentId: here, - environmentLabel: label, - shell, - finding, - occurredAt, - recipient, - }), - destinations, - nowMs, - ); - return [result.enqueued, result.state]; - }); + const enqueued = + selfWatch || noGlobalDestination + ? false + : yield* update((state) => { + const result = recordThreadEvents( + state, + { threadId, evaluated: judged.evaluated, findings: judged.findings }, + (finding) => + threadEventAlert({ + environmentId: here, + environmentLabel: label, + shell, + finding, + occurredAt, + recipient, + }), + destinations, + nowMs, + ); + return [result.enqueued, result.state]; + }); if (enqueued) yield* Queue.offer(wake, undefined); + yield* Effect.forEach( + subscribed, + (subscription) => + applyThreadPlan( + subscription, + threadId, + shell.title, + judged.findings, + trigger === "settled", + ), + { discard: true }, + ); }); const threadTrigger = (event: OrchestrationV2DomainEvent): ThreadEventTrigger | undefined => { @@ -1588,4 +1775,6 @@ export const make = Effect.gen(function* () { return ModelAlertReactor.of({ start, handle, flush, sweep, linkRenewal }); }); -export const layer = Layer.effect(ModelAlertReactor, make); +export const layer = Layer.effect(ModelAlertReactor, make).pipe( + Layer.provide(EventSubscriptionStore.layer), +); diff --git a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts index 3485765a0ed93..3d2985c54c258 100644 --- a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts @@ -43,6 +43,16 @@ import { PULL_REQUEST_WATCH_NO_CHECKS_MS, pullRequestWatchMessage, } from "./pullRequestWatch.ts"; +import { + cursorOf, + planPullRequestSubscription, + pullRequestSelectorKey, + subscriptionWake, + virtualLegacySubscription, + withCursor, +} from "./eventSubscription.ts"; +import * as EventSubscriptionStore from "../persistence/EventSubscriptions.ts"; +import type { EventSubscription } from "@t3tools/contracts"; /** Checks take minutes; faster sweeps waste the account's shared host quota. */ const SWEEP_MINUTES = 2; @@ -237,6 +247,7 @@ export const make = Effect.gen(function* () { const projections = yield* ProjectionStore.ProjectionStoreV2; const pullRequests = yield* PullRequestService.PullRequestService; const random = yield* SecureRandom.SecureRandom; + const subscriptions = yield* Effect.serviceOption(EventSubscriptionStore.EventSubscriptionStore); const bootedAt = yield* Clock.currentTimeMillis; const lives = new Map(); @@ -524,13 +535,16 @@ export const make = Effect.gen(function* () { ); }); - const closed = (groupKey: string, target: WatchTarget) => + const closed = (groupKey: string, target: WatchTarget, pending: readonly string[] = []) => hold({ groupKey, target, next: null, wake: { - text: `Pull request #${target.link.number} (${target.link.url}) was closed, so T3 Code stopped watching it. Call watch_pull_request if it reopens.`, + text: [ + `Pull request #${target.link.number} (${target.link.url}) was closed, so T3 Code stopped watching it. Call watch_pull_request if it reopens.`, + ...pending, + ].join("\n"), notification: { source: { kind: "monitor" }, outcome: "updated", @@ -540,6 +554,113 @@ export const make = Effect.gen(function* () { reason: "closed", }); + const loadSubscription = Effect.fnUntraced(function* (target: WatchTarget) { + if (Option.isNone(subscriptions)) return { mode: "absent" as const }; + const key = pullRequestSelectorKey(target.link.url); + if (key === null) return { mode: "legacy" as const }; + const row = yield* subscriptions.value.get(target.thread.id, key).pipe( + Effect.catchCause((cause) => + Effect.logWarning("event subscription read failed", { + threadId: target.thread.id, + cause, + }).pipe(Effect.as(null)), + ), + ); + return row === null ? { mode: "legacy" as const } : { mode: "row" as const, row }; + }); + + const saveSubscription = (row: EventSubscription, state: EventSubscription) => + Option.isNone(subscriptions) + ? Effect.void + : subscriptions.value + .put(state) + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("event subscription update failed", { id: row.id, cause }), + ), + ); + + const dropSubscription = (row: EventSubscription) => + Option.isNone(subscriptions) + ? Effect.void + : subscriptions.value.remove(row.subscriberThreadId, row.id).pipe( + Effect.catchCause((cause) => + Effect.logWarning("event subscription removal failed", { id: row.id, cause }), + ), + Effect.asVoid, + ); + + const subscriberIdle = Effect.fnUntraced(function* ( + threadId: WatchTarget["thread"]["id"], + needed: boolean, + ) { + if (!needed) return true; + const shell = yield* projections + .getThreadShell(threadId) + .pipe(Effect.catchCause(() => Effect.succeed(null))); + return ( + shell !== null && + shell.deletedAt === null && + shell.activeRunId === null && + (shell.activityRunStatus ?? null) === null + ); + }); + + const finishClosed = Effect.fnUntraced(function* (groupKey: string, target: WatchTarget) { + const loaded = yield* loadSubscription(target); + const pending = loaded.mode === "row" ? loaded.row.pendingSummaries : []; + yield* closed(groupKey, target, pending); + if (loaded.mode === "row" && loaded.row.delivery.autoExpireOnClose) { + yield* dropSubscription(loaded.row); + } + }); + + const finishMerged = Effect.fnUntraced(function* (target: WatchTarget) { + const loaded = yield* loadSubscription(target); + if (loaded.mode === "absent") { + yield* record(target, null); + yield* ended(target, "merged"); + return; + } + const subscription = + loaded.mode === "row" + ? loaded.row + : virtualLegacySubscription(target.thread.id, target.link.url); + const decision = planPullRequestSubscription({ + changes: [], + events: subscription.events, + ignoreAuthors: subscription.ignoreAuthors, + delivery: subscription.delivery, + idle: true, + nowMs: yield* Clock.currentTimeMillis, + state: cursorOf(subscription), + terminal: "merged", + }); + yield* record( + target, + null, + decision.action === "wake" + ? { + ...subscriptionWake({ + number: target.link.number, + url: target.link.url, + summaries: decision.summaries, + }), + includesRemarks: false, + } + : undefined, + ); + if (loaded.mode === "row" && decision.expire) yield* dropSubscription(loaded.row); + yield* ended(target, "merged"); + }); + + const expireOnSettle = Effect.fnUntraced(function* (target: WatchTarget) { + const loaded = yield* loadSubscription(target); + if (loaded.mode === "row" && loaded.row.delivery.autoExpireOnClose) { + yield* dropSubscription(loaded.row); + } + }); + const endsWithoutRead = ({ thread, link }: WatchTarget): WatchEndReason | undefined => link.snapshot?.state === "merged" ? "merged" @@ -652,9 +773,7 @@ export const make = Effect.gen(function* () { if (detail.state !== "open") { lastReads.delete(group.key); return yield* eachTarget(group, (target) => - detail.state === "closed" - ? closed(group.key, target) - : record(target, null).pipe(Effect.tap(() => ended(target, "merged"))), + detail.state === "closed" ? finishClosed(group.key, target) : finishMerged(target), ); } @@ -696,35 +815,90 @@ export const make = Effect.gen(function* () { status: fingerprint?.status ?? null, remarks: fingerprint?.remarks ?? null, }); - yield* eachTarget(group, (target) => { - const report = evaluatePullRequestWatch(target.watch, detail, remarks, now); - if (report.changes.length > 0) { - const wake = { - ...pullRequestWatchMessage({ - number: target.link.number, - url: target.link.url, - baseBranch: detail.baseBranch, - headSha: report.next.headSha, - report, - }), - includesRemarks: report.changes.some((change) => change.kind === "remarks"), - }; - // An ending watch keeps what this pass saw, so watching again starts from it. - return hold( - report.exhausted - ? { - groupKey: group.key, - target, - next: null, - endedWatch: report.next, - wake, - reason: "comment-limit", - } - : { groupKey: group.key, target, next: report.next, wake }, - ); - } - return watchesEqual(report.next, target.watch) ? Effect.void : record(target, report.next); - }); + yield* eachTarget(group, (target) => + Effect.gen(function* () { + const report = evaluatePullRequestWatch(target.watch, detail, remarks, now); + const loaded = yield* loadSubscription(target); + if (loaded.mode === "absent") { + if (report.changes.length === 0) { + if (!watchesEqual(report.next, target.watch)) yield* record(target, report.next); + return; + } + const wake = { + ...pullRequestWatchMessage({ + number: target.link.number, + url: target.link.url, + baseBranch: detail.baseBranch, + headSha: report.next.headSha, + report, + }), + includesRemarks: report.changes.some((change) => change.kind === "remarks"), + }; + // An ending watch keeps what this pass saw, so watching again starts from it. + yield* hold( + report.exhausted + ? { + groupKey: group.key, + target, + next: null, + endedWatch: report.next, + wake, + reason: "comment-limit", + } + : { groupKey: group.key, target, next: report.next, wake }, + ); + return; + } + const subscription = + loaded.mode === "row" + ? loaded.row + : virtualLegacySubscription(target.thread.id, target.link.url); + const decision = planPullRequestSubscription({ + changes: report.changes, + events: subscription.events, + ignoreAuthors: subscription.ignoreAuthors, + delivery: subscription.delivery, + idle: yield* subscriberIdle(target.thread.id, subscription.delivery.onlyWhenIdle), + nowMs: now, + state: cursorOf(subscription), + }); + const remarksOnlyDropped = + report.changes.length > 0 && + report.changes.every((change) => change.kind === "remarks") && + !decision.includesRemarks; + const next = remarksOnlyDropped + ? { ...report.next, wakes: target.watch.wakes } + : report.next; + if (decision.action === "hold") return; + if (loaded.mode === "row") + yield* saveSubscription(loaded.row, withCursor(loaded.row, decision.state)); + if (decision.action === "wake") { + const wake = { + ...subscriptionWake({ + number: target.link.number, + url: target.link.url, + summaries: decision.summaries, + }), + includesRemarks: decision.includesRemarks, + }; + const endForComments = report.exhausted && decision.includesRemarks; + yield* hold( + endForComments + ? { + groupKey: group.key, + target, + next: null, + endedWatch: next, + wake, + reason: "comment-limit", + } + : { groupKey: group.key, target, next, wake }, + ); + return; + } + if (!watchesEqual(next, target.watch)) yield* record(target, next); + }), + ); }); /** Every watch, or with `changed`, only that pull request's after its host reported a change. */ @@ -775,8 +949,13 @@ export const make = Effect.gen(function* () { yield* Effect.forEach( ending, ([target, reason]) => - record(target, null).pipe( - Effect.tap(() => ended(target, reason)), + (reason === "merged" + ? finishMerged(target) + : record(target, null).pipe( + Effect.tap(() => (reason === "settled" ? expireOnSettle(target) : Effect.void)), + Effect.tap(() => ended(target, reason)), + ) + ).pipe( Effect.catchCause( logFailure("pull request watch stop failed", { threadId: target.thread.id, @@ -890,4 +1069,6 @@ export const make = Effect.gen(function* () { return { start, sweep } satisfies PullRequestWatchReactor["Service"]; }); -export const layer = Layer.effect(PullRequestWatchReactor, make); +export const layer = Layer.effect(PullRequestWatchReactor, make).pipe( + Layer.provide(EventSubscriptionStore.layer), +); diff --git a/apps/server/src/orchestration-v2/eventSubscription.test.ts b/apps/server/src/orchestration-v2/eventSubscription.test.ts new file mode 100644 index 0000000000000..503f9c68972a9 --- /dev/null +++ b/apps/server/src/orchestration-v2/eventSubscription.test.ts @@ -0,0 +1,428 @@ +import { + ThreadId, + type EventDeliveryPolicy, + type EventFilter, + type EventSelector, + type PullRequestComment, +} from "@t3tools/contracts"; +import { assert, describe, it } from "@effect/vitest"; +import * as Cause from "effect/Cause"; +import * as Effect from "effect/Effect"; + +import { subscribeEvent } from "../mcp/toolkits/events/handlers.ts"; + +import { + DEFAULT_PULL_REQUEST_IGNORE_AUTHORS, + emptyCursor, + planPullRequestSubscription, + planThreadSubscription, + prepareSubscribe, + quietHoursCover, + selectWatchChanges, + virtualLegacySubscription, + watchSubscription, + type SubscriptionCursor, +} from "./eventSubscription.ts"; +import type { PullRequestWatchChange } from "./pullRequestWatch.ts"; + +const THREAD = ThreadId.make("thread-1"); +const URL = "https://github.com/T3Tools/t3code/pull/12"; +const NOW = Date.parse("2026-11-21T15:30:00.000Z"); + +const off: EventDeliveryPolicy = { + coalesceWindowSeconds: null, + autoExpireOnClose: false, + onlyWhenIdle: false, + quietHours: null, + maxWakesPerHour: null, +}; + +const remark = (login: string, reviewState: string | null): PullRequestComment => ({ + id: `${login}-${reviewState ?? "comment"}`, + kind: reviewState === null ? "issue-comment" : "review", + author: { login, name: null, avatarUrl: null }, + body: "note", + createdAt: "2026-11-21T15:00:00.000Z", + url: null, + path: null, + reviewState, +}); + +const remarks = (login: string, reviewState: string | null = null): PullRequestWatchChange => ({ + kind: "remarks", + remarks: [remark(login, reviewState)], +}); + +const failed = (status: "failure" | "cancelled"): PullRequestWatchChange => ({ + kind: "checks-failed", + failed: [{ name: "ci", status, description: null, url: null }], +}); + +const plan = ( + changes: readonly PullRequestWatchChange[], + events: readonly EventFilter[] | null, + extras: { + readonly ignoreAuthors?: readonly string[]; + readonly delivery?: EventDeliveryPolicy; + readonly state?: SubscriptionCursor; + readonly nowMs?: number; + readonly idle?: boolean; + readonly terminal?: "merged" | "closed" | null; + } = {}, +) => + planPullRequestSubscription({ + changes, + events, + ignoreAuthors: extras.ignoreAuthors ?? [...DEFAULT_PULL_REQUEST_IGNORE_AUTHORS], + delivery: extras.delivery ?? off, + idle: extras.idle ?? true, + nowMs: extras.nowMs ?? NOW, + state: extras.state ?? emptyCursor(), + ...(extras.terminal === undefined ? {} : { terminal: extras.terminal }), + }); + +describe("event subscriptions", () => { + it("does not wake on an ignored coderabbitai comment, including the [bot] suffix", () => { + const ignored = plan([remarks("coderabbitai[bot]")], [{ name: "comment.human" }]); + assert.strictEqual(ignored.action, "consume"); + assert.deepEqual(ignored.summaries, []); + const human = plan([remarks("ada")], [{ name: "comment.human" }]); + assert.strictEqual(human.action, "wake"); + assert.deepEqual(human.summaries, ["Comment from ada"]); + }); + + it("drops a cancelled check when cancelled is excluded and still wakes on a failure", () => { + const events = [{ name: "checks.failed" as const, exclude: ["cancelled" as const] }]; + const cancelled = plan([failed("cancelled")], events); + assert.strictEqual(cancelled.action, "consume"); + const failure = plan([failed("failure")], events); + assert.strictEqual(failure.action, "wake"); + assert.deepEqual(failure.summaries, ["Failed checks: ci"]); + const kept = plan([failed("cancelled")], [{ name: "checks.failed" }]); + assert.strictEqual(kept.action, "wake"); + }); + + it("wakes each pull request event only when that event is selected", () => { + const cases: ReadonlyArray<{ + readonly event: EventFilter; + readonly change: PullRequestWatchChange; + readonly summary: string; + }> = [ + { + event: { name: "checks.required_passed" }, + change: { kind: "checks-passed", count: 2, required: true }, + summary: "Required checks passed", + }, + { + event: { name: "review.changes_requested" }, + change: remarks("ada", "CHANGES_REQUESTED"), + summary: "Changes requested by ada", + }, + { + event: { name: "review.approved" }, + change: remarks("ada", "APPROVED"), + summary: "Approved by ada", + }, + { + event: { name: "conflict.detected" }, + change: { kind: "conflicting" }, + summary: "Merge conflict", + }, + ]; + for (const entry of cases) { + const selected = plan([entry.change], [entry.event], { ignoreAuthors: [] }); + assert.strictEqual(selected.action, "wake", entry.event.name); + assert.deepEqual(selected.summaries, [entry.summary]); + const other = cases.find((candidate) => candidate.event.name !== entry.event.name)!; + const skipped = plan([entry.change], [other.event], { ignoreAuthors: [] }); + assert.strictEqual( + skipped.action, + "consume", + `${entry.event.name} selected ${other.event.name}`, + ); + } + const merged = plan([], [{ name: "merged" }], { terminal: "merged" }); + assert.strictEqual(merged.action, "wake"); + assert.deepEqual(merged.summaries, ["Pull request merged"]); + const notMerged = plan([], [{ name: "comment.human" }], { terminal: "merged" }); + assert.strictEqual(notMerged.action, "consume"); + const advisory = plan( + [{ kind: "checks-passed", count: 1, required: false }], + [{ name: "checks.required_passed" }], + ); + assert.strictEqual(advisory.action, "consume"); + }); + + it("keeps legacy watches waking on failures and human comments while ignoring coderabbitai", () => { + const legacy = virtualLegacySubscription(THREAD, URL); + assert.deepEqual(legacy.ignoreAuthors, ["coderabbitai"]); + assert.strictEqual(legacy.events, null); + assert.strictEqual(legacy.delivery.autoExpireOnClose, false); + const failure = plan([failed("failure"), failed("cancelled")], null); + assert.strictEqual(failure.action, "wake"); + const human = plan([remarks("ada")], null); + assert.strictEqual(human.action, "wake"); + const bot = plan([remarks("CodeRabbitAI[bot]")], null); + assert.strictEqual(bot.action, "consume"); + const optedOut = plan([remarks("coderabbitai")], null, { ignoreAuthors: [] }); + assert.strictEqual(optedOut.action, "wake"); + }); + + it("coalesces two events inside the window into one wake", () => { + const delivery: EventDeliveryPolicy = { ...off, coalesceWindowSeconds: 60 }; + const first = plan([remarks("ada")], [{ name: "comment.human" }], { + delivery, + ignoreAuthors: [], + }); + assert.strictEqual(first.action, "consume"); + assert.deepEqual(first.state.pendingSummaries, ["Comment from ada"]); + const second = plan([remarks("grace")], [{ name: "comment.human" }], { + delivery, + ignoreAuthors: [], + state: first.state, + nowMs: NOW + 1_000, + }); + assert.strictEqual(second.action, "consume"); + assert.deepEqual(second.state.pendingSummaries, ["Comment from ada", "Comment from grace"]); + const flushed = plan([], [{ name: "comment.human" }], { + delivery, + state: second.state, + nowMs: NOW + 60_000, + }); + assert.strictEqual(flushed.action, "wake"); + assert.deepEqual(flushed.summaries, ["Comment from ada", "Comment from grace"]); + assert.deepEqual(flushed.state.pendingSummaries, []); + }); + + it("removes an autoExpireOnClose subscription when the pull request merges or closes", () => { + const delivery: EventDeliveryPolicy = { ...off, autoExpireOnClose: true }; + assert.strictEqual( + plan([], [{ name: "merged" }], { delivery, terminal: "merged" }).expire, + true, + ); + assert.strictEqual( + plan([], [{ name: "merged" }], { delivery, terminal: "closed" }).expire, + true, + ); + assert.strictEqual(plan([], [{ name: "merged" }], { terminal: "merged" }).expire, false); + assert.strictEqual(plan([], [{ name: "merged" }], { terminal: "closed" }).expire, false); + }); + + it("enforces idle, quiet hours, and the hourly wake cap by holding the cursor", () => { + const comment = [remarks("ada")]; + const events = [{ name: "comment.human" as const }]; + const busy = plan(comment, events, { + ignoreAuthors: [], + delivery: { ...off, onlyWhenIdle: true }, + idle: false, + }); + assert.strictEqual(busy.action, "hold"); + const quiet = plan(comment, events, { + ignoreAuthors: [], + delivery: { + ...off, + quietHours: { start: "15:00", end: "16:00", timeZone: "UTC" }, + }, + }); + assert.strictEqual(quiet.action, "hold"); + assert.strictEqual( + quietHoursCover({ start: "16:00", end: "17:00", timeZone: "UTC" }, NOW), + false, + ); + assert.strictEqual( + quietHoursCover({ start: "22:00", end: "06:00", timeZone: "UTC" }, NOW), + false, + ); + assert.strictEqual( + quietHoursCover( + { start: "22:00", end: "06:00", timeZone: "UTC" }, + Date.parse("2026-11-21T23:10:00.000Z"), + ), + true, + ); + const capped = plan(comment, events, { + ignoreAuthors: [], + delivery: { ...off, maxWakesPerHour: 1 }, + state: { ...emptyCursor(), wakeTimesMs: [NOW - 1_000] }, + }); + assert.strictEqual(capped.action, "hold"); + const later = plan(comment, events, { + ignoreAuthors: [], + delivery: { ...off, maxWakesPerHour: 1 }, + state: { ...emptyCursor(), wakeTimesMs: [NOW - 3_600_001] }, + }); + assert.strictEqual(later.action, "wake"); + }); + + it("fails a phase-2 or unimplemented selector before a subscription exists", () => { + const phase2 = prepareSubscribe({ + id: "evt_1", + subscriberThreadId: THREAD, + selector: { entity: "external", source: "linear" }, + events: [{ name: "comment.human" }], + createdAt: "2026-11-21T15:30:00.000Z", + }); + assert.strictEqual(phase2.ok, false); + if (!phase2.ok) assert.strictEqual(phase2.error._tag, "EventSubscriptionPhase2Error"); + const webhook = prepareSubscribe({ + id: "evt_2", + subscriberThreadId: THREAD, + selector: { entity: "webhook", source: "gmail" }, + events: [{ name: "comment.human" }], + createdAt: "2026-11-21T15:30:00.000Z", + }); + assert.strictEqual(webhook.ok, false); + if (!webhook.ok) assert.strictEqual(webhook.error._tag, "EventSubscriptionPhase2Error"); + for (const selector of [ + { entity: "pull_request" as const, by: "repository" as const, repository: "t3tools/t3code" }, + { entity: "pull_request" as const, by: "label" as const, label: "bug" }, + { entity: "pull_request" as const, by: "path_glob" as const, pathGlob: "apps/**" }, + { entity: "thread" as const, by: "tag" as const, tag: "ops" }, + { entity: "thread" as const, by: "domain" as const, domain: "inbox" }, + ]) { + const rejected = prepareSubscribe({ + id: "evt_3", + subscriberThreadId: THREAD, + selector, + events: selector.entity === "thread" ? [{ name: "stuck" }] : [{ name: "merged" }], + createdAt: "2026-11-21T15:30:00.000Z", + }); + assert.strictEqual(rejected.ok, false, selector.by); + if (!rejected.ok) { + assert.strictEqual(rejected.error._tag, "EventSubscriptionSelectorUnsupportedError"); + } + } + const zone = prepareSubscribe({ + id: "evt_4", + subscriberThreadId: THREAD, + selector: { entity: "pull_request", by: "url", url: URL }, + events: [{ name: "merged" }], + delivery: { quietHours: { start: "01:00", end: "02:00", timeZone: "Not/AZone" } }, + createdAt: "2026-11-21T15:30:00.000Z", + }); + assert.strictEqual(zone.ok, false); + if (!zone.ok) assert.strictEqual(zone.error._tag, "EventSubscriptionInvalidError"); + }); + + it.effect("does not watch or store a phase-2 or unsupported subscribe", () => + Effect.gen(function* () { + const rejected = (selector: EventSelector, events: ReadonlyArray, tag: string) => + Effect.gen(function* () { + let watched = 0; + let stored = 0; + const exit = yield* Effect.exit( + subscribeEvent({ + callerThreadId: THREAD, + request: { selector, events: [...events] }, + id: "evt_rejected", + createdAt: "2026-11-21T15:30:00.000Z", + store: { + put: () => { + stored += 1; + return Effect.die("stored"); + }, + } as never, + watchPullRequest: () => { + watched += 1; + return Effect.die("watched"); + }, + }), + ); + assert.strictEqual(watched, 0); + assert.strictEqual(stored, 0); + assert.strictEqual(exit._tag, "Failure"); + if (exit._tag === "Failure") { + const reason = exit.cause.reasons[0]; + assert.ok(reason !== undefined && Cause.isFailReason(reason)); + if (reason !== undefined && Cause.isFailReason(reason)) { + assert.strictEqual(reason.error._tag, tag); + } + } + }); + yield* rejected( + { entity: "external", source: "linear" }, + [{ name: "comment.human" }], + "EventSubscriptionPhase2Error", + ); + yield* rejected( + { entity: "webhook", source: "quo" }, + [{ name: "comment.human" }], + "EventSubscriptionPhase2Error", + ); + yield* rejected( + { entity: "pull_request", by: "label", label: "bug" }, + [{ name: "merged" }], + "EventSubscriptionSelectorUnsupportedError", + ); + yield* rejected( + { entity: "thread", by: "domain", domain: "inbox" }, + [{ name: "stuck" }], + "EventSubscriptionSelectorUnsupportedError", + ); + }), + ); + + it("stores omitted delivery fields as off and defaults pull request ignoreAuthors", () => { + const stored = prepareSubscribe({ + id: "evt_5", + subscriberThreadId: THREAD, + selector: { entity: "pull_request", by: "url", url: URL }, + events: [{ name: "comment.human" }], + createdAt: "2026-11-21T15:30:00.000Z", + }); + assert.strictEqual(stored.ok, true); + if (stored.ok) { + assert.deepEqual(stored.subscription.ignoreAuthors, ["coderabbitai"]); + assert.strictEqual(stored.subscription.delivery.autoExpireOnClose, false); + assert.strictEqual(stored.subscription.delivery.onlyWhenIdle, false); + assert.strictEqual(stored.subscription.delivery.quietHours, null); + assert.strictEqual(stored.subscription.delivery.maxWakesPerHour, null); + assert.strictEqual(stored.subscription.delivery.coalesceWindowSeconds, null); + } + const watched = watchSubscription({ + id: "evt_6", + subscriberThreadId: THREAD, + url: `${URL}/files`, + createdAt: "2026-11-21T15:30:00.000Z", + }); + assert.strictEqual(watched.ok, true); + if (watched.ok) { + assert.strictEqual(watched.subscription.events, null); + assert.strictEqual( + watched.selectorKey, + "pull_request:url:https://github.com/T3Tools/t3code/pull/12", + ); + } + const selected = selectWatchChanges( + [remarks("ada", "REQUESTED_CHANGES")], + [{ name: "review.changes_requested" }], + [], + ); + assert.strictEqual(selected.summaries[0], "Changes requested by ada"); + }); + + it("expires a thread subscription when the watched thread settles", () => { + const delivery: EventDeliveryPolicy = { ...off, autoExpireOnClose: true }; + const ended = planThreadSubscription({ + findings: [{ kind: "lane-ended", detail: "The lane finished.", signature: "run-1" }], + events: [{ name: "lane-ended" }], + delivery, + idle: true, + nowMs: NOW, + state: emptyCursor(), + settled: true, + }); + assert.strictEqual(ended.action, "wake"); + assert.strictEqual(ended.expire, true); + const kept = planThreadSubscription({ + findings: [], + events: [{ name: "stuck" }], + delivery: off, + idle: false, + nowMs: NOW, + state: emptyCursor(), + settled: true, + }); + assert.strictEqual(kept.expire, false); + }); +}); diff --git a/apps/server/src/orchestration-v2/eventSubscription.ts b/apps/server/src/orchestration-v2/eventSubscription.ts new file mode 100644 index 0000000000000..fcb871fe5643d --- /dev/null +++ b/apps/server/src/orchestration-v2/eventSubscription.ts @@ -0,0 +1,747 @@ +import { + EventSubscriptionInvalidError, + EventSubscriptionPhase2Error, + EventSubscriptionSelectorUnsupportedError, + type EventDeliveryPolicy, + type EventFilter, + type EventSelector, + type EventSubscription, + type PullRequestEventFilter, + type QuietHours, + type ThreadId, +} from "@t3tools/contracts"; +import type { + OrchestrationV2Notification, + PullRequestCheck, + PullRequestComment, +} from "@t3tools/contracts"; + +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 HOUR_MS = 3_600_000; +const CLOCK_RE = /^([01]\d|2[0-3]):([0-5]\d)$/; + +export interface SubscriptionCursor { + readonly coalesceUntilMs: number | null; + readonly pendingSummaries: readonly string[]; + readonly wakeTimesMs: readonly number[]; + readonly deliveredSignatures: Readonly>; +} + +export const emptyCursor = (): SubscriptionCursor => ({ + coalesceUntilMs: null, + pendingSummaries: [], + wakeTimesMs: [], + deliveredSignatures: {}, +}); + +export function canonicalAuthor(login: string): string { + return login + .trim() + .toLowerCase() + .replace(/\[bot\]$/i, ""); +} + +export function authorIgnored( + login: string | null | undefined, + ignore: readonly string[], +): boolean { + if (login == null || login.trim() === "") return false; + const key = canonicalAuthor(login); + return ignore.some((entry) => canonicalAuthor(entry) === key); +} + +export function normalizePullRequestUrl(raw: string): string { + const url = new URL(raw); + url.hash = ""; + url.search = ""; + const path = url.pathname.replace(/\/+$/, "").replace(/\/(files|commits|checks)$/i, ""); + return `${url.protocol.toLowerCase()}//${url.host.toLowerCase()}${path}`; +} + +export function pullRequestSelectorKey(url: string): string | null { + try { + return `pull_request:url:${normalizePullRequestUrl(url)}`; + } catch { + return null; + } +} + +export function threadSelectorKey(threadId: string): string { + return `thread:thread_id:${threadId}`; +} + +export function selectorKey(selector: EventSelector): string | null { + if (selector.entity === "pull_request" && selector.by === "url") { + return pullRequestSelectorKey(selector.url); + } + if (selector.entity === "thread" && selector.by === "thread_id") { + return threadSelectorKey(selector.threadId); + } + return null; +} + +export interface DeliveryInput { + readonly immediate?: boolean | undefined; + readonly coalesceWindowSeconds?: number | null | undefined; + readonly autoExpireOnClose?: boolean | undefined; + readonly onlyWhenIdle?: boolean | undefined; + readonly quietHours?: QuietHours | null | undefined; + readonly maxWakesPerHour?: number | null | undefined; +} + +export function normalizeDelivery( + input: DeliveryInput | undefined, +): + | { readonly ok: true; readonly delivery: EventDeliveryPolicy } + | { readonly ok: false; readonly error: EventSubscriptionInvalidError } { + const window = input?.coalesceWindowSeconds ?? null; + if (window !== null && (!Number.isInteger(window) || window < 0)) { + return { + ok: false, + error: new EventSubscriptionInvalidError({ + detail: "coalesceWindowSeconds must be a non-negative integer.", + }), + }; + } + if (input?.immediate === true && window !== null && window > 0) { + return { + ok: false, + error: new EventSubscriptionInvalidError({ + detail: "immediate does not combine with a coalesce window.", + }), + }; + } + const maxWakes = input?.maxWakesPerHour ?? null; + if (maxWakes !== null && (!Number.isInteger(maxWakes) || maxWakes < 1)) { + return { + ok: false, + error: new EventSubscriptionInvalidError({ + detail: "maxWakesPerHour must be a positive integer.", + }), + }; + } + const quiet = input?.quietHours ?? null; + if (quiet !== null) { + const invalid = validateQuietHours(quiet); + if (invalid !== null) { + return { ok: false, error: new EventSubscriptionInvalidError({ detail: invalid }) }; + } + } + return { + ok: true, + delivery: { + coalesceWindowSeconds: + input?.immediate === true || window === null || window === 0 ? null : window, + autoExpireOnClose: input?.autoExpireOnClose === true, + onlyWhenIdle: input?.onlyWhenIdle === true, + quietHours: quiet, + maxWakesPerHour: maxWakes, + }, + }; +} + +function validateQuietHours(hours: QuietHours): string | null { + if (!CLOCK_RE.test(hours.start) || !CLOCK_RE.test(hours.end)) { + return "quietHours start and end must be HH:MM in 24-hour time."; + } + try { + new Intl.DateTimeFormat("en-US", { timeZone: hours.timeZone }).format(0); + } catch { + return `quietHours timeZone is not a valid IANA zone: ${hours.timeZone}.`; + } + return null; +} + +/** Minutes from midnight in the zone. Throws when the zone is invalid. */ +export function minutesInZone(nowMs: number, timeZone: string): number { + const parts = new Intl.DateTimeFormat("en-US", { + timeZone, + hour: "2-digit", + minute: "2-digit", + hourCycle: "h23", + }).formatToParts(nowMs); + const hour = Number(parts.find((part) => part.type === "hour")?.value ?? "0"); + const minute = Number(parts.find((part) => part.type === "minute")?.value ?? "0"); + return hour * 60 + minute; +} + +export function quietHoursCover(hours: QuietHours | null, nowMs: number): boolean { + if (hours === null || hours.start === hours.end) return false; + const now = minutesInZone(nowMs, hours.timeZone); + const start = clockMinutes(hours.start); + const end = clockMinutes(hours.end); + return start < end ? now >= start && now < end : now >= start || now < end; +} + +function clockMinutes(value: string): number { + const match = CLOCK_RE.exec(value); + if (match === null) return 0; + return Number(match[1]) * 60 + Number(match[2]); +} + +function eventFamily(name: string): "pull_request" | "thread" { + return THREAD_EVENT_NAMES.has(name) ? "thread" : "pull_request"; +} + +export type SubscribeRejection = + | EventSubscriptionPhase2Error + | EventSubscriptionSelectorUnsupportedError + | EventSubscriptionInvalidError; + +export function prepareSubscribe(input: { + readonly id: string; + readonly subscriberThreadId: ThreadId; + readonly selector: EventSelector; + readonly events: readonly EventFilter[]; + readonly ignoreAuthors?: readonly string[] | undefined; + readonly delivery?: DeliveryInput | undefined; + readonly createdAt: string; +}): + | { readonly ok: true; readonly subscription: EventSubscription; readonly selectorKey: string } + | { + readonly ok: false; + readonly error: SubscribeRejection; + } { + if (input.selector.entity === "webhook" || input.selector.entity === "external") { + return { + ok: false, + error: new EventSubscriptionPhase2Error({ + entity: input.selector.entity, + source: input.selector.source, + }), + }; + } + if (input.selector.entity === "pull_request" && input.selector.by !== "url") { + return { + ok: false, + error: new EventSubscriptionSelectorUnsupportedError({ + entity: "pull_request", + by: input.selector.by, + }), + }; + } + if (input.selector.entity === "thread" && input.selector.by !== "thread_id") { + return { + ok: false, + error: new EventSubscriptionSelectorUnsupportedError({ + entity: "thread", + by: input.selector.by, + }), + }; + } + if (input.events.length === 0) { + return { + ok: false, + error: new EventSubscriptionInvalidError({ detail: "Select at least one event." }), + }; + } + const family = input.selector.entity; + const mismatched = input.events.find((event) => eventFamily(event.name) !== family); + if (mismatched !== undefined) { + return { + ok: false, + error: new EventSubscriptionInvalidError({ + detail: `${mismatched.name} is not a ${family} event.`, + }), + }; + } + const key = selectorKey(input.selector); + if (key === null) { + const detail = + input.selector.entity === "pull_request" + ? "The pull request URL is not valid." + : "The selector could not be stored."; + return { + ok: false, + error: new EventSubscriptionInvalidError({ detail }), + }; + } + const delivery = normalizeDelivery(input.delivery); + if (!delivery.ok) return delivery; + const ignoreAuthors = + input.ignoreAuthors !== undefined + ? [...input.ignoreAuthors] + : family === "pull_request" + ? [...DEFAULT_PULL_REQUEST_IGNORE_AUTHORS] + : []; + return { + ok: true, + selectorKey: key, + subscription: { + id: input.id, + subscriberThreadId: input.subscriberThreadId, + selector: input.selector, + events: [...input.events], + ignoreAuthors, + delivery: delivery.delivery, + createdAt: input.createdAt, + ...emptyCursor(), + }, + }; +} + +/** A watch that passes filters. Omitted events keep the legacy wake set. */ +export function watchSubscription(input: { + readonly id: string; + readonly subscriberThreadId: ThreadId; + readonly url: string; + readonly events?: readonly PullRequestEventFilter[] | undefined; + readonly ignoreAuthors?: readonly string[] | undefined; + readonly coalesceWindowSeconds?: number | undefined; + readonly autoExpireOnClose?: boolean | undefined; + readonly createdAt: string; +}): + | { readonly ok: true; readonly subscription: EventSubscription; readonly selectorKey: string } + | { + readonly ok: false; + readonly error: EventSubscriptionInvalidError; + } { + const delivery = normalizeDelivery({ + ...(input.coalesceWindowSeconds === undefined + ? {} + : { coalesceWindowSeconds: input.coalesceWindowSeconds }), + ...(input.autoExpireOnClose === undefined + ? {} + : { autoExpireOnClose: input.autoExpireOnClose }), + }); + if (!delivery.ok) return delivery; + const key = pullRequestSelectorKey(input.url); + if (key === null) { + return { + ok: false, + error: new EventSubscriptionInvalidError({ detail: "The pull request URL is not valid." }), + }; + } + return { + ok: true, + selectorKey: key, + subscription: { + id: input.id, + subscriberThreadId: input.subscriberThreadId, + selector: { entity: "pull_request", by: "url", url: input.url }, + events: input.events === undefined ? null : [...input.events], + ignoreAuthors: + input.ignoreAuthors === undefined + ? [...DEFAULT_PULL_REQUEST_IGNORE_AUTHORS] + : [...input.ignoreAuthors], + delivery: delivery.delivery, + createdAt: input.createdAt, + ...emptyCursor(), + }, + }; +} + +export function virtualLegacySubscription( + subscriberThreadId: ThreadId, + url: string, +): EventSubscription { + const prepared = watchSubscription({ + id: "virtual", + subscriberThreadId, + url, + createdAt: "1970-01-01T00:00:00.000Z", + }); + if (!prepared.ok) { + throw new Error(prepared.error.message); + } + return prepared.subscription; +} + +export function cursorOf(subscription: EventSubscription): SubscriptionCursor { + return { + coalesceUntilMs: subscription.coalesceUntilMs, + pendingSummaries: subscription.pendingSummaries, + wakeTimesMs: subscription.wakeTimesMs, + deliveredSignatures: subscription.deliveredSignatures, + }; +} + +export function withCursor( + subscription: EventSubscription, + cursor: SubscriptionCursor, +): EventSubscription { + return { ...subscription, ...cursor }; +} + +function reviewClass( + remark: PullRequestComment, +): "review.approved" | "review.changes_requested" | "comment.human" { + const state = (remark.reviewState ?? "").toUpperCase().replaceAll("-", "_"); + if (state === "APPROVED") return "review.approved"; + if (state === "CHANGES_REQUESTED" || state === "REQUESTED_CHANGES") { + return "review.changes_requested"; + } + return "comment.human"; +} + +function remarkSelected( + remark: PullRequestComment, + events: readonly EventFilter[] | null, + ignoreAuthors: readonly string[], +): boolean { + if (authorIgnored(remark.author?.login, ignoreAuthors)) return false; + if (events === null) return true; + const name = reviewClass(remark); + return events.some((event) => event.name === name); +} + +function failedFilters(events: readonly EventFilter[] | null) { + if (events === null) return { includeFailure: true, includeCancelled: true }; + const filters = events.filter( + (event): event is Extract => + event.name === "checks.failed", + ); + return { + includeFailure: filters.length > 0, + includeCancelled: filters.some((event) => !event.exclude?.includes("cancelled")), + }; +} + +function keepCheck(check: PullRequestCheck, failed: ReturnType): boolean { + if (check.status === "cancelled") return failed.includeCancelled; + if (check.status === "failure") return failed.includeFailure; + return false; +} + +function summaryOf(change: PullRequestWatchChange): string { + switch (change.kind) { + case "checks-failed": { + const names = change.failed.map((check) => check.name).join(", "); + return change.failed.every((check) => check.status === "cancelled") + ? `Cancelled checks: ${names}` + : `Failed checks: ${names}`; + } + case "checks-passed": + return change.required ? "Required checks passed" : "Checks passed"; + case "checks-awaiting-approval": + return `Checks awaiting approval: ${change.checks.map((check) => check.name).join(", ")}`; + case "remarks": + return change.remarks + .map((remark) => { + const who = remark.author?.login ?? "someone"; + const kind = reviewClass(remark); + if (kind === "review.approved") return `Approved by ${who}`; + if (kind === "review.changes_requested") return `Changes requested by ${who}`; + return `Comment from ${who}`; + }) + .join("; "); + case "no-checks": + return `No checks reported after ${change.minutes} minutes`; + case "conflicting": + return "Merge conflict"; + case "needs-rebase": + return "Rebase required"; + case "merge-queue-removed": + return change.reason === null + ? "Removed from the merge queue" + : `Removed from the merge queue: ${change.reason}`; + } +} + +export function selectWatchChanges( + changes: readonly PullRequestWatchChange[], + events: readonly EventFilter[] | null, + ignoreAuthors: readonly string[], +): { + readonly changes: ReadonlyArray; + readonly summaries: readonly string[]; +} { + const selected: PullRequestWatchChange[] = []; + const failed = failedFilters(events); + for (const change of changes) { + switch (change.kind) { + case "checks-failed": { + const kept = change.failed.filter((check) => keepCheck(check, failed)); + if (kept.length > 0) selected.push({ kind: "checks-failed", failed: kept }); + break; + } + case "checks-passed": + if ( + events === null || + (change.required && events.some((event) => event.name === "checks.required_passed")) + ) { + selected.push(change); + } + break; + case "remarks": { + const remarks = change.remarks.filter((remark) => + remarkSelected(remark, events, ignoreAuthors), + ); + if (remarks.length > 0) selected.push({ kind: "remarks", remarks }); + break; + } + case "conflicting": + if (events === null || events.some((event) => event.name === "conflict.detected")) { + selected.push(change); + } + break; + case "checks-awaiting-approval": + case "no-checks": + case "needs-rebase": + case "merge-queue-removed": + if (events === null) selected.push(change); + break; + } + } + return { changes: selected, summaries: selected.map(summaryOf) }; +} + +function shouldHold( + delivery: EventDeliveryPolicy, + idle: boolean, + nowMs: number, + wakeTimesMs: readonly number[], +): boolean { + if (delivery.onlyWhenIdle && !idle) return true; + if (delivery.quietHours !== null && quietHoursCover(delivery.quietHours, nowMs)) return true; + if (delivery.maxWakesPerHour !== null) { + const recent = wakeTimesMs.filter((time) => nowMs - time < HOUR_MS).length; + if (recent >= delivery.maxWakesPerHour) return true; + } + return false; +} + +function afterWake(state: SubscriptionCursor, nowMs: number): SubscriptionCursor { + return { + coalesceUntilMs: null, + pendingSummaries: [], + wakeTimesMs: [...state.wakeTimesMs.filter((time) => nowMs - time < HOUR_MS), nowMs], + deliveredSignatures: state.deliveredSignatures, + }; +} + +export interface PullRequestPlan { + readonly action: "wake" | "consume" | "hold"; + readonly changes: ReadonlyArray; + readonly summaries: readonly string[]; + readonly state: SubscriptionCursor; + readonly expire: boolean; + readonly includesRemarks: boolean; +} + +export function planPullRequestSubscription(input: { + readonly changes: readonly PullRequestWatchChange[]; + readonly events: readonly EventFilter[] | null; + readonly ignoreAuthors: readonly string[]; + readonly delivery: EventDeliveryPolicy; + readonly idle: boolean; + readonly nowMs: number; + readonly state: SubscriptionCursor; + readonly terminal?: "merged" | "closed" | null; +}): PullRequestPlan { + const terminal = input.terminal ?? null; + if (terminal === "closed") { + const summaries = input.state.pendingSummaries; + return { + action: summaries.length > 0 ? "wake" : "consume", + changes: [], + summaries, + state: summaries.length > 0 ? afterWake(input.state, input.nowMs) : input.state, + expire: input.delivery.autoExpireOnClose, + includesRemarks: false, + }; + } + if (terminal === "merged") { + const wantMerged = input.events?.some((event) => event.name === "merged") === true; + const summaries = [ + ...input.state.pendingSummaries, + ...(wantMerged ? ["Pull request merged"] : []), + ]; + return { + action: summaries.length > 0 ? "wake" : "consume", + changes: [], + summaries, + state: + summaries.length > 0 ? afterWake(input.state, input.nowMs) : emptyCursorOf(input.state), + expire: input.delivery.autoExpireOnClose, + includesRemarks: false, + }; + } + + const selected = selectWatchChanges(input.changes, input.events, input.ignoreAuthors); + const pending = input.state.pendingSummaries; + const windowSec = input.delivery.coalesceWindowSeconds ?? 0; + const due = input.state.coalesceUntilMs !== null && input.nowMs >= input.state.coalesceUntilMs; + const selectedNow = selected.summaries.length > 0; + const remarksOnly = + selected.changes.length > 0 && selected.changes.every((change) => change.kind === "remarks"); + + if (!selectedNow && pending.length === 0) { + return { + action: "consume", + changes: [], + summaries: [], + state: input.state, + expire: false, + includesRemarks: false, + }; + } + if (!selectedNow && !due) { + return { + action: "consume", + changes: [], + summaries: [], + state: input.state, + expire: false, + includesRemarks: false, + }; + } + if (shouldHold(input.delivery, input.idle, input.nowMs, input.state.wakeTimesMs)) { + return { + action: "hold", + changes: selected.changes, + summaries: selected.summaries, + state: input.state, + expire: false, + includesRemarks: remarksOnly, + }; + } + if (selectedNow && windowSec > 0 && !due) { + return { + action: "consume", + changes: [], + summaries: [], + state: { + ...input.state, + coalesceUntilMs: input.state.coalesceUntilMs ?? input.nowMs + windowSec * 1000, + pendingSummaries: [...pending, ...selected.summaries], + }, + expire: false, + includesRemarks: false, + }; + } + const summaries = [...pending, ...selected.summaries]; + return { + action: "wake", + changes: selected.changes, + summaries, + state: afterWake(input.state, input.nowMs), + expire: false, + includesRemarks: + remarksOnly || summaries.every((line) => /^(Comment|Approved|Changes requested)/.test(line)), + }; +} + +function emptyCursorOf(state: SubscriptionCursor): SubscriptionCursor { + return { ...emptyCursor(), deliveredSignatures: state.deliveredSignatures }; +} + +export interface ThreadPlan { + readonly action: "wake" | "consume" | "hold"; + readonly summaries: readonly string[]; + readonly state: SubscriptionCursor; + readonly expire: boolean; +} + +export function planThreadSubscription(input: { + readonly findings: readonly { + readonly kind: string; + readonly detail: string; + readonly signature: string; + }[]; + readonly events: readonly { readonly name: string }[]; + readonly delivery: EventDeliveryPolicy; + readonly idle: boolean; + readonly nowMs: number; + readonly state: SubscriptionCursor; + readonly settled: boolean; +}): ThreadPlan { + const names = new Set(input.events.map((event) => event.name)); + const fresh = input.findings.filter( + (finding) => + names.has(finding.kind) && + input.state.deliveredSignatures[finding.kind] !== finding.signature, + ); + const lines = fresh.map((finding) => `${finding.kind}: ${finding.detail}`); + const signatures = { ...input.state.deliveredSignatures }; + for (const finding of fresh) signatures[finding.kind] = finding.signature; + const pending = input.state.pendingSummaries; + const windowSec = input.delivery.coalesceWindowSeconds ?? 0; + const due = input.state.coalesceUntilMs !== null && input.nowMs >= input.state.coalesceUntilMs; + + if (input.settled) { + const summaries = [...pending, ...lines]; + return { + action: summaries.length > 0 ? "wake" : "consume", + summaries, + state: { + ...(summaries.length > 0 ? afterWake(input.state, input.nowMs) : input.state), + deliveredSignatures: signatures, + ...(summaries.length === 0 ? {} : { pendingSummaries: [], coalesceUntilMs: null }), + }, + expire: input.delivery.autoExpireOnClose, + }; + } + + if (lines.length === 0 && pending.length === 0) { + return { action: "consume", summaries: [], state: input.state, expire: false }; + } + if (lines.length === 0 && !due) { + return { action: "consume", summaries: [], state: input.state, expire: false }; + } + if (shouldHold(input.delivery, input.idle, input.nowMs, input.state.wakeTimesMs)) { + if (lines.length === 0) { + return { action: "hold", summaries: [], state: input.state, expire: false }; + } + return { + action: "consume", + summaries: [], + state: { + ...input.state, + deliveredSignatures: signatures, + pendingSummaries: [...pending, ...lines], + coalesceUntilMs: + input.state.coalesceUntilMs ?? + (windowSec > 0 ? input.nowMs + windowSec * 1000 : input.nowMs), + }, + expire: false, + }; + } + if (lines.length > 0 && windowSec > 0 && !due) { + return { + action: "consume", + summaries: [], + state: { + ...input.state, + deliveredSignatures: signatures, + coalesceUntilMs: input.state.coalesceUntilMs ?? input.nowMs + windowSec * 1000, + pendingSummaries: [...pending, ...lines], + }, + expire: false, + }; + } + return { + action: "wake", + summaries: [...pending, ...lines], + state: { ...afterWake(input.state, input.nowMs), deliveredSignatures: signatures }, + expire: false, + }; +} + +export function subscriptionWake(input: { + readonly number: number; + readonly url: string; + readonly summaries: readonly string[]; +}): { readonly text: string; readonly notification: OrchestrationV2Notification } { + const summary = input.summaries[0] ?? "update"; + const failed = input.summaries.some((line) => /fail|conflict|cancel|rebase/i.test(line)); + return { + text: [ + `Update on pull request #${input.number} (${input.url}), which T3 Code is watching for you:`, + ...input.summaries, + "", + "T3 Code is still watching this pull request.", + ].join("\n"), + notification: { + source: { kind: "monitor" }, + outcome: failed ? "failed" : "updated", + summary: `#${input.number}: ${summary}`, + }, + }; +} diff --git a/apps/server/src/persistence/EventSubscriptions.test.ts b/apps/server/src/persistence/EventSubscriptions.test.ts new file mode 100644 index 0000000000000..ca8fc0f13df84 --- /dev/null +++ b/apps/server/src/persistence/EventSubscriptions.test.ts @@ -0,0 +1,60 @@ +import { ThreadId } from "@t3tools/contracts"; +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { prepareSubscribe, pullRequestSelectorKey } from "../orchestration-v2/eventSubscription.ts"; +import * as EventSubscriptionStore from "./EventSubscriptions.ts"; +import * as SqlitePersistence from "./Sqlite.ts"; + +const THREAD = ThreadId.make("thread-1"); +const OTHER = ThreadId.make("thread-2"); + +describe("EventSubscriptionStore", () => { + it.effect("lists the caller, updates the same selector, and unsubscribes idempotently", () => + Effect.gen(function* () { + const store = yield* EventSubscriptionStore.EventSubscriptionStore; + const prepared = prepareSubscribe({ + id: "evt_1", + subscriberThreadId: THREAD, + selector: { + entity: "pull_request", + by: "url", + url: "https://github.com/T3Tools/t3code/pull/12", + }, + events: [{ name: "comment.human" }], + createdAt: "2026-11-21T15:30:00.000Z", + }); + assert.strictEqual(prepared.ok, true); + if (!prepared.ok) return; + yield* store.put(prepared.subscription); + const again = yield* store.put({ ...prepared.subscription, id: "evt_replaced" }); + assert.strictEqual(again.id, "evt_1"); + const listed = yield* store.listForSubscriber(THREAD); + assert.strictEqual(listed.length, 1); + assert.deepEqual(yield* store.listForSubscriber(OTHER), []); + const removed = yield* store.remove(THREAD, "evt_1"); + assert.strictEqual(removed.removed, true); + assert.strictEqual((yield* store.remove(THREAD, "evt_1")).removed, false); + assert.strictEqual((yield* store.remove(OTHER, "evt_1")).removed, false); + const closed = yield* store.put({ + ...prepared.subscription, + delivery: { ...prepared.subscription.delivery, autoExpireOnClose: true }, + }); + const key = pullRequestSelectorKey( + closed.selector.entity === "pull_request" && closed.selector.by === "url" + ? closed.selector.url + : "", + ); + assert.ok(key !== null); + if (key === null) return; + const expired = yield* store.removeKey(THREAD, key); + assert.strictEqual(expired.removed, true); + assert.deepEqual(yield* store.listForSubscriber(THREAD), []); + }).pipe( + Effect.provide( + EventSubscriptionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)), + ), + ), + ); +}); diff --git a/apps/server/src/persistence/EventSubscriptions.ts b/apps/server/src/persistence/EventSubscriptions.ts new file mode 100644 index 0000000000000..9e573f5446435 --- /dev/null +++ b/apps/server/src/persistence/EventSubscriptions.ts @@ -0,0 +1,222 @@ +import { + EventSubscription, + type EventSubscription as EventSubscriptionDocument, + type ThreadId, +} from "@t3tools/contracts"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as SqlSchema from "effect/sql/SqlSchema"; + +import { selectorKey } from "../orchestration-v2/eventSubscription.ts"; +import { PersistenceDecodeError, PersistenceSqlError } from "./Errors.ts"; + +export type EventSubscriptionStoreError = PersistenceDecodeError | PersistenceSqlError; + +const DocumentRow = Schema.Struct({ + document: Schema.fromJsonString(EventSubscription), +}); + +const encodeDocument = Schema.encodeEffect(Schema.fromJsonString(EventSubscription)); + +export class EventSubscriptionStore extends Context.Service< + EventSubscriptionStore, + { + readonly put: ( + subscription: EventSubscriptionDocument, + ) => Effect.Effect; + readonly get: ( + subscriberThreadId: ThreadId, + key: string, + ) => Effect.Effect; + readonly listForSubscriber: ( + subscriberThreadId: ThreadId, + ) => Effect.Effect, EventSubscriptionStoreError>; + readonly listForSelector: ( + key: string, + ) => Effect.Effect, EventSubscriptionStoreError>; + readonly listAll: () => Effect.Effect< + ReadonlyArray, + EventSubscriptionStoreError + >; + readonly remove: ( + subscriberThreadId: ThreadId, + id: string, + ) => Effect.Effect<{ readonly removed: boolean }, EventSubscriptionStoreError>; + readonly removeKey: ( + subscriberThreadId: ThreadId, + key: string, + ) => Effect.Effect<{ readonly removed: boolean }, EventSubscriptionStoreError>; + } +>()("t3/persistence/EventSubscriptions/EventSubscriptionStore") {} + +function toError(operation: string) { + return (cause: unknown): EventSubscriptionStoreError => + Schema.isSchemaError(cause) + ? PersistenceDecodeError.fromSchemaError(operation, cause) + : new PersistenceSqlError({ operation, cause }); +} + +const make = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const findOne = SqlSchema.findOneOption({ + Request: Schema.Struct({ subscriberThreadId: Schema.String, selectorKey: Schema.String }), + Result: DocumentRow, + execute: ({ subscriberThreadId, selectorKey: key }) => + sql` + SELECT document_json AS "document" + FROM event_subscriptions + WHERE subscriber_thread_id = ${subscriberThreadId} AND selector_key = ${key} + `, + }); + + const listBySubscriber = SqlSchema.findAll({ + Request: Schema.Struct({ subscriberThreadId: Schema.String }), + Result: DocumentRow, + execute: ({ subscriberThreadId }) => + sql` + SELECT document_json AS "document" + FROM event_subscriptions + WHERE subscriber_thread_id = ${subscriberThreadId} + ORDER BY created_at, id + `, + }); + + const listBySelector = SqlSchema.findAll({ + Request: Schema.Struct({ selectorKey: Schema.String }), + Result: DocumentRow, + execute: ({ selectorKey: key }) => + sql` + SELECT document_json AS "document" + FROM event_subscriptions + WHERE selector_key = ${key} + ORDER BY created_at, id + `, + }); + + const listEvery = SqlSchema.findAll({ + Request: Schema.Struct({}), + Result: DocumentRow, + execute: () => + sql` + SELECT document_json AS "document" + FROM event_subscriptions + ORDER BY created_at, id + `, + }); + + const read = (operation: string, effect: Effect.Effect) => + effect.pipe(NodeSqliteClient.readOnly, Effect.mapError(toError(operation))); + + const get = Effect.fn("EventSubscriptionStore.get")(function* ( + subscriberThreadId: ThreadId, + key: string, + ) { + const row = yield* read( + "getEventSubscription", + findOne({ subscriberThreadId, selectorKey: key }), + ); + return Option.getOrNull(Option.map(row, (found) => found.document)); + }); + + return EventSubscriptionStore.of({ + get, + listForSubscriber: Effect.fn("EventSubscriptionStore.listForSubscriber")( + function* (subscriberThreadId) { + const rows = yield* read( + "listEventSubscriptions", + listBySubscriber({ subscriberThreadId }), + ); + return rows.map((row) => row.document); + }, + ), + listForSelector: Effect.fn("EventSubscriptionStore.listForSelector")(function* (key) { + const rows = yield* read( + "listEventSubscriptionsBySelector", + listBySelector({ selectorKey: key }), + ); + return rows.map((row) => row.document); + }), + listAll: Effect.fn("EventSubscriptionStore.listAll")(function* () { + const rows = yield* read("listAllEventSubscriptions", listEvery({})); + return rows.map((row) => row.document); + }), + put: Effect.fn("EventSubscriptionStore.put")(function* (subscription) { + const key = selectorKey(subscription.selector); + if (key === null) { + return yield* new PersistenceDecodeError({ + operation: "putEventSubscription", + issue: "selector is not storable", + }); + } + const existing = yield* get(subscription.subscriberThreadId, key); + const stored = + existing === null + ? subscription + : { ...subscription, id: existing.id, createdAt: existing.createdAt }; + const documentJson = yield* encodeDocument(stored).pipe( + Effect.mapError((cause) => + PersistenceDecodeError.fromSchemaError("putEventSubscription", cause), + ), + ); + yield* sql` + INSERT INTO event_subscriptions ( + id, + subscriber_thread_id, + selector_key, + document_json, + created_at + ) + VALUES ( + ${stored.id}, + ${stored.subscriberThreadId}, + ${key}, + ${documentJson}, + ${stored.createdAt} + ) + ON CONFLICT (subscriber_thread_id, selector_key) + DO UPDATE SET document_json = excluded.document_json + `.pipe(Effect.mapError(toError("putEventSubscription"))); + return stored; + }), + remove: Effect.fn("EventSubscriptionStore.remove")( + function* (subscriberThreadId, id) { + const existing = yield* sql<{ readonly id: string }>` + SELECT id AS "id" + FROM event_subscriptions + WHERE subscriber_thread_id = ${subscriberThreadId} AND id = ${id} + `; + if (existing.length === 0) return { removed: false }; + yield* sql` + DELETE FROM event_subscriptions + WHERE subscriber_thread_id = ${subscriberThreadId} AND id = ${id} + `.pipe(Effect.asVoid); + return { removed: true }; + }, + Effect.mapError(toError("removeEventSubscription")), + ), + removeKey: Effect.fn("EventSubscriptionStore.removeKey")( + function* (subscriberThreadId, key) { + const existing = yield* sql<{ readonly id: string }>` + SELECT id AS "id" + FROM event_subscriptions + WHERE subscriber_thread_id = ${subscriberThreadId} AND selector_key = ${key} + `; + if (existing.length === 0) return { removed: false }; + yield* sql` + DELETE FROM event_subscriptions + WHERE subscriber_thread_id = ${subscriberThreadId} AND selector_key = ${key} + `.pipe(Effect.asVoid); + return { removed: true }; + }, + Effect.mapError(toError("removeEventSubscription")), + ), + }); +}); + +export const layer = Layer.effect(EventSubscriptionStore, make); diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 6118c51093f9c..df52ee99224bd 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -105,6 +105,7 @@ import Migration0094 from "./Migrations/094_TurnItemMessageOrdinalIndex.ts"; import Migration0095 from "./Migrations/095_TurnItemInlineWorkOutput.ts"; import Migration0096 from "./Migrations/096_RepairStaleTitleRegeneration.ts"; import Migration0097 from "./Migrations/097_AuthSessionFounder.ts"; +import Migration0098 from "./Migrations/098_EventSubscriptions.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -205,6 +206,7 @@ const migrationEntries = [ [95, "TurnItemInlineWorkOutput", Migration0095], [96, "RepairStaleTitleRegeneration", Migration0096], [97, "AuthSessionFounder", Migration0097], + [98, "EventSubscriptions", Migration0098], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/098_EventSubscriptions.ts b/apps/server/src/persistence/Migrations/098_EventSubscriptions.ts new file mode 100644 index 0000000000000..40e33199a0ba4 --- /dev/null +++ b/apps/server/src/persistence/Migrations/098_EventSubscriptions.ts @@ -0,0 +1,22 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +/** Per-agent event subscriptions. The document is the EventSubscription contract. */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + CREATE TABLE IF NOT EXISTS event_subscriptions ( + id TEXT PRIMARY KEY, + subscriber_thread_id TEXT NOT NULL, + selector_key TEXT NOT NULL, + document_json TEXT NOT NULL, + created_at TEXT NOT NULL, + UNIQUE (subscriber_thread_id, selector_key) + ) + `; + yield* sql` + CREATE INDEX IF NOT EXISTS event_subscriptions_selector + ON event_subscriptions (selector_key) + `; +}); diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index c2084d57162bb..7f141519d4361 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5930, "codexAdditionalContextBytes": 7324, - "mcpToolListJsonBytes": 55827 + "mcpToolListJsonBytes": 61303 } diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index d8cf2f4a8c7dd..11bbe4a12ede2 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -4,6 +4,7 @@ import * as Random from "effect/Random"; import * as EnvironmentKeys from "./cloud/environmentKeys.ts"; import * as AssetSigner from "./assets/AssetSigner.ts"; import * as DatabaseStorage from "./persistence/DatabaseStorage.ts"; +import * as EventSubscriptionStore from "./persistence/EventSubscriptions.ts"; import * as StorageCleanup from "./storageCleanup.ts"; import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts"; import * as PullRequestWatchReactor from "./orchestration-v2/PullRequestWatchReactor.ts"; @@ -885,6 +886,7 @@ const layerMakeRoutes = Layer.mergeAll( speechStreamRouteLayer, ), McpHttpServer.layer.pipe( + Layer.provide(EventSubscriptionStore.layer), Layer.provide(ProviderAdapterRegistry.layerFromProviderInstanceRegistry), Layer.provide(McpOAuth.layerMcpClientAuthenticator), ), diff --git a/docs/rfcs/event-subscriptions.md b/docs/rfcs/event-subscriptions.md new file mode 100644 index 0000000000000..76597a76eeeea --- /dev/null +++ b/docs/rfcs/event-subscriptions.md @@ -0,0 +1,60 @@ +# Event subscriptions + +`watch_pull_request` and the thread-alert path wake an agent on every check and comment, including bot skip-reviews such as coderabbitai. An agent needs to choose which events, which entity, and when a wake is delivered. + +## Contract + +`EventSubscription` lives in `packages/contracts/src/eventSubscription.ts`. One row per subscriber thread and selector is stored in SQLite (`event_subscriptions`, migration 98). The existing pull-request watch reactor and the thread-alert reactor read that row. There is no second poller. + +Phase 1 stores and evaluates: + +- a pull request selected by URL +- a thread selected by id + +Repository, label, and path-glob selectors, and thread tag and domain selectors, are in the schema. A subscribe call that uses one returns `EventSubscriptionSelectorUnsupportedError` and stores nothing. An unimplemented selector is never treated as a match of everything. + +`webhook` and `external` selectors (Linear, fleet health sentinel, approvals queue, Quo, Gmail) are schema variants only. Subscribing returns `EventSubscriptionPhase2Error` and stores nothing. This slice does not call those sources. + +## Pull-request events + +A filtered subscription wakes only for the selected names: + +- `checks.required_passed` +- `checks.failed`, with optional `exclude: ["cancelled"]` +- `review.changes_requested` +- `review.approved` +- `comment.human` +- `conflict.detected` +- `merged` + +`ignoreAuthors` drops those authors before a comment or review can wake the subscriber. Matching is case-insensitive and ignores a trailing `[bot]`. + +`events: null` keeps today's wake set (including cancelled checks, advisory checks passing, awaiting approval, no checks, needs-rebase, and merge-queue removal) minus ignored authors. It does not wake on merge. A filtered subscription does not wake on those advisory changes. + +## Delivery + +All of these fields are enforced on the subscription. None are stored while the reactor ignores them. + +- `immediate` and `coalesceWindowSeconds`: a null window wakes at once. A positive window stashes the burst and wakes once when the window is due. The existing pull-request sweep (about two minutes) and the thread-alert flush (about 30 seconds) flush a due window. There is no new scheduler. +- `autoExpireOnClose`: the row is removed when the pull request merges or closes, and when a watched thread settles. +- `onlyWhenIdle`: a wake waits while the subscriber has an active run. The next sweep or flush retries. +- `quietHours`: a wake waits while the subscriber's local time is inside the window. +- `maxWakesPerHour`: a wake waits after the cap until an older wake falls out of the hour. + +`immediate: true` together with a positive window is `EventSubscriptionInvalidError`. + +## `ignoreAuthors` default + +The upgraded watch and a pull-request subscribe that omits `ignoreAuthors` default to `["coderabbitai"]`. The filter drops comments and reviews only. A real check failure and a human comment still wake, which is what current callers rely on. Pass `ignoreAuthors: []` to hear coderabbitai. A thread subscription defaults to an empty ignore list. + +Callers of `watch_pull_request` that omit the new options do not get a stored subscription. When the store is present, the reactor applies that default as a virtual legacy subscription. When the store is absent, the old wake path is unchanged. + +Passing `events`, `ignoreAuthors`, `coalesceWindowSeconds`, or `autoExpireOnClose` stores a subscription for that thread and URL and keeps the existing watch. Watching again with none of those options removes the row and restores the virtual legacy watch. `unwatch_pull_request` removes the row. + +## Tools + +- `t3_event_subscribe` +- `t3_event_unsubscribe` (idempotent; another thread's row is left in place) +- `t3_event_list` (the caller's rows only) + +A pull-request URL subscription also starts the existing watch. If that watch fails, nothing is stored. diff --git a/docs/user/source-control.md b/docs/user/source-control.md index 2f068d8827494..e5ba8f37a9aaf 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -331,7 +331,7 @@ check fails or waits for a maintainer's approval, the required checks pass, some conflict. On github.com it also wakes the agent, with GitHub's reason, when the merge queue drops the pull request without merging it. Threads in a project that watch the same pull request share one check. On GitHub, a check first asks whether anything changed and reads the pull request only when it did, which keeps -watching inside GitHub's rate limit. Comments from your own account do not wake it. Watching ends +watching inside GitHub's rate limit. Comments from your own account do not wake it. Comments and reviews from coderabbitai do not wake it either, unless the caller passes `ignoreAuthors` as an empty list. Optional `events`, `coalesceWindowSeconds`, and `autoExpireOnClose` on `watch_pull_request` choose which changes wake the thread and whether the watch ends when the pull request closes. `t3_event_subscribe` uses the same filters for a pull request URL or another thread. Watching ends when the pull request merges or closes, after 10 wakes in a row that bring only comments, after 8 failed reads in a row, or when you press Stop on the thread. A rate limit only pauses watching. Settling or archiving a thread also ends all its watches. Unsettle the thread before starting a new diff --git a/packages/client-runtime/src/t3ToolSummary.ts b/packages/client-runtime/src/t3ToolSummary.ts index 3cec41a44476a..a6fbe5eb15155 100644 --- a/packages/client-runtime/src/t3ToolSummary.ts +++ b/packages/client-runtime/src/t3ToolSummary.ts @@ -429,6 +429,15 @@ export function summarizeT3ToolCalls( quantity(selected.length, "pull request"), ); break; + case "event-subscribe": + label = phrase("Subscribed", "subscribe", `to events ${times}`); + break; + case "event-unsubscribe": + label = phrase("Unsubscribed", "unsubscribe", `from events ${times}`); + break; + case "event-list": + label = phrase("Listed", "list", `event subscriptions ${times}`); + break; case "list-prs": label = phrase( "Checked", diff --git a/packages/contracts/src/eventSubscription.ts b/packages/contracts/src/eventSubscription.ts new file mode 100644 index 0000000000000..49ebdff19d2da --- /dev/null +++ b/packages/contracts/src/eventSubscription.ts @@ -0,0 +1,176 @@ +import * as Schema from "effect/Schema"; + +import { + IsoDateTime, + NonNegativeInt, + PositiveInt, + ThreadId, + TrimmedNonEmptyString, +} from "./baseSchemas.ts"; + +/** + * Fine-grained per-agent event subscriptions. + * Phase 1 delivers pull-request URL selectors and thread-id selectors. + * Repository, label, path-glob, tag, and domain selectors are typed and rejected until implemented. + * Webhook and external sources are typed and rejected until phase 2. + */ + +export const ExternalEventSource = Schema.Literals([ + "linear", + "fleet_health_sentinel", + "approvals_queue", + "quo", + "gmail", +]); +export type ExternalEventSource = typeof ExternalEventSource.Type; + +export const PullRequestEventFilter = Schema.Union([ + Schema.Struct({ name: Schema.Literal("checks.required_passed") }), + Schema.Struct({ + name: Schema.Literal("checks.failed"), + exclude: Schema.optional(Schema.Array(Schema.Literal("cancelled"))), + }), + Schema.Struct({ name: Schema.Literal("review.changes_requested") }), + Schema.Struct({ name: Schema.Literal("review.approved") }), + Schema.Struct({ name: Schema.Literal("comment.human") }), + Schema.Struct({ name: Schema.Literal("conflict.detected") }), + Schema.Struct({ name: Schema.Literal("merged") }), +]); +export type PullRequestEventFilter = typeof PullRequestEventFilter.Type; + +/** Names match the thread-alert kinds the server already judges. */ +export const ThreadEventFilter = Schema.Struct({ + name: Schema.Literals(["lane-ended", "promise-without-wake", "stuck", "needs-person"]), +}); +export type ThreadEventFilter = typeof ThreadEventFilter.Type; + +export const EventFilter = Schema.Union([PullRequestEventFilter, ThreadEventFilter]); +export type EventFilter = typeof EventFilter.Type; + +export const PullRequestSelector = Schema.Union([ + Schema.Struct({ + entity: Schema.Literal("pull_request"), + by: Schema.Literal("url"), + url: TrimmedNonEmptyString, + }), + Schema.Struct({ + entity: Schema.Literal("pull_request"), + by: Schema.Literal("repository"), + repository: TrimmedNonEmptyString, + }), + Schema.Struct({ + entity: Schema.Literal("pull_request"), + by: Schema.Literal("label"), + label: TrimmedNonEmptyString, + }), + Schema.Struct({ + entity: Schema.Literal("pull_request"), + by: Schema.Literal("path_glob"), + pathGlob: TrimmedNonEmptyString, + }), +]); +export type PullRequestSelector = typeof PullRequestSelector.Type; + +export const ThreadSelector = Schema.Union([ + Schema.Struct({ + entity: Schema.Literal("thread"), + by: Schema.Literal("thread_id"), + threadId: ThreadId, + }), + Schema.Struct({ + entity: Schema.Literal("thread"), + by: Schema.Literal("tag"), + tag: TrimmedNonEmptyString, + }), + Schema.Struct({ + entity: Schema.Literal("thread"), + by: Schema.Literal("domain"), + domain: TrimmedNonEmptyString, + }), +]); +export type ThreadSelector = typeof ThreadSelector.Type; + +export const ExternalSelector = Schema.Union([ + Schema.Struct({ + entity: Schema.Literal("webhook"), + source: ExternalEventSource, + }), + Schema.Struct({ + entity: Schema.Literal("external"), + source: ExternalEventSource, + }), +]); +export type ExternalSelector = typeof ExternalSelector.Type; + +export const EventSelector = Schema.Union([PullRequestSelector, ThreadSelector, ExternalSelector]); +export type EventSelector = typeof EventSelector.Type; + +export const QuietHours = Schema.Struct({ + start: TrimmedNonEmptyString, + end: TrimmedNonEmptyString, + timeZone: TrimmedNonEmptyString, +}); +export type QuietHours = typeof QuietHours.Type; + +/** + * `coalesceWindowSeconds` null means immediate. The other fields are stored only when the + * reactor enforces them; a subscribe call that asks for a policy this build does not enforce + * is rejected instead of stored. + */ +export const EventDeliveryPolicy = Schema.Struct({ + coalesceWindowSeconds: Schema.NullOr(NonNegativeInt), + autoExpireOnClose: Schema.Boolean, + onlyWhenIdle: Schema.Boolean, + quietHours: Schema.NullOr(QuietHours), + maxWakesPerHour: Schema.NullOr(PositiveInt), +}); +export type EventDeliveryPolicy = typeof EventDeliveryPolicy.Type; + +export const EventSubscription = Schema.Struct({ + id: TrimmedNonEmptyString, + subscriberThreadId: ThreadId, + selector: EventSelector, + /** Null keeps the legacy pull-request wake set, minus ignored authors. */ + events: Schema.NullOr(Schema.Array(EventFilter)), + ignoreAuthors: Schema.Array(TrimmedNonEmptyString), + delivery: EventDeliveryPolicy, + createdAt: IsoDateTime, + coalesceUntilMs: Schema.NullOr(Schema.Number), + pendingSummaries: Schema.Array(Schema.String), + wakeTimesMs: Schema.Array(Schema.Number), + deliveredSignatures: Schema.Record(Schema.String, Schema.String), +}); +export type EventSubscription = typeof EventSubscription.Type; + +export class EventSubscriptionPhase2Error extends Schema.TaggedError()( + "EventSubscriptionPhase2Error", + { + entity: Schema.Literals(["webhook", "external"]), + source: ExternalEventSource, + }, +) { + override get message(): string { + return `${this.entity} subscriptions for ${this.source} are not active until phase 2.`; + } +} + +export class EventSubscriptionSelectorUnsupportedError extends Schema.TaggedError()( + "EventSubscriptionSelectorUnsupportedError", + { + entity: Schema.Literals(["pull_request", "thread"]), + by: Schema.String, + }, +) { + override get message(): string { + return `Selecting a ${this.entity} by ${this.by} is not active yet. Use a pull request URL or a thread id.`; + } +} + +export class EventSubscriptionInvalidError extends Schema.TaggedError()( + "EventSubscriptionInvalidError", + { detail: Schema.String }, +) { + override get message(): string { + return this.detail; + } +} diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 4a7fe499f9b0b..12da81b919b51 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -47,6 +47,7 @@ export * from "./peerLink.ts"; export * from "./linkedSidebar.ts"; export * from "./threadMetadataMcp.ts"; export * from "./threadPullRequest.ts"; +export * from "./eventSubscription.ts"; export * from "./threadSearch.ts"; export * from "./threadTags.ts"; export * from "./threadStanding.ts"; diff --git a/packages/shared/src/t3McpToolPresentation.ts b/packages/shared/src/t3McpToolPresentation.ts index f1c95a9fee408..eb94c8aed7908 100644 --- a/packages/shared/src/t3McpToolPresentation.ts +++ b/packages/shared/src/t3McpToolPresentation.ts @@ -65,6 +65,9 @@ export type T3McpToolSummaryAction = | "list-prs" | "watch-pr" | "unwatch-pr" + | "event-subscribe" + | "event-unsubscribe" + | "event-list" | "write-pr-guides" | "read-pr-guide" | "browser" @@ -135,6 +138,21 @@ const T3_MCP_TOOLS: Readonly> = { "unwatch-pr", "pull-request", ), + t3_event_subscribe: tool( + ["Subscribe", "Subscribing", "Subscribed", "to events"], + "event-subscribe", + "pull-request", + ), + t3_event_unsubscribe: tool( + ["Unsubscribe", "Unsubscribing", "Unsubscribed", "from events"], + "event-unsubscribe", + "pull-request", + ), + t3_event_list: tool( + ["List", "Listing", "Listed", "event subscriptions"], + "event-list", + "pull-request", + ), write_pull_request_guides: tool( ["Write", "Writing", "Started writing", "review guides"], "write-pr-guides",