Add PR monitoring: server-driven babysit mode for agent threads
Threads can now formally monitor a PR after creating it. The agent calls a new monitor_start MCP tool; a dedicated PullRequestMonitor service polls GitHub every 30s, diffs review comments / reviews / check runs against a per-thread cursor, and wakes the thread with a self-contained prompt when there is something to address. The server — never the agent — declares the PR ready from head-SHA-anchored GitHub state. - GitHub monitor snapshot fetch (reviews, threads, check runs, mergeability) with pure cursor-diff and readiness modules - thread.monitor.start/update/end domain events through decider/projector, monitor state on the thread shell, migration 034 (monitor_json) - Wake dispatch protocol: claim → fresh terminal revalidation at the send boundary → dispatch → cursor ack only after accepted start; user turns always win and rewind in-flight wake cursors so events re-diff; 10-wake circuit breaker ends as needs-attention - Monitoring holds the thread unsettled; user settle ends the monitor; session teardown ends it as session-ended - UI: steady cyan Monitoring pill (never masks approval/input/failed), blockers sub-line, header MonitorStrip with Stop, emerald Ready-to-merge state with confirm dialog; clients can only end a monitor as "stopped" Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
a17cbc3b40
commit
63e07db893
41 files changed
+3178
-21
No files matched your search
@@ -22,6 +22,8 @@ import {
|
||||
PreviewSnapshotToolkit,
|
||||
PreviewStandardToolkit,
|
||||
} from "./toolkits/preview/tools.ts";
|
||||
import { MonitorToolkitHandlersLive } from "./toolkits/monitor/handlers.ts";
|
||||
import { MonitorToolkit } from "./toolkits/monitor/tools.ts";
|
||||
|
||||
const unauthorized = HttpServerResponse.jsonUnsafe(
|
||||
{
|
||||
@@ -208,10 +210,17 @@ export const PreviewToolkitRegistrationLive = Layer.mergeAll(
|
||||
PreviewSnapshotRegistrationLive,
|
||||
);
|
||||
|
||||
export const MonitorToolkitRegistrationLive = McpServer.toolkit(MonitorToolkit).pipe(
|
||||
Layer.provide(MonitorToolkitHandlersLive),
|
||||
);
|
||||
|
||||
const McpTransportLive = McpServer.layerHttp({
|
||||
name: "T3 Code",
|
||||
version: packageJson.version,
|
||||
path: "/mcp",
|
||||
}).pipe(Layer.provide(McpAuthMiddlewareLive));
|
||||
|
||||
export const layer = PreviewToolkitRegistrationLive.pipe(Layer.provideMerge(McpTransportLive));
|
||||
export const layer = Layer.mergeAll(
|
||||
PreviewToolkitRegistrationLive,
|
||||
MonitorToolkitRegistrationLive,
|
||||
).pipe(Layer.provideMerge(McpTransportLive));
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
export type McpCapability = "preview";
|
||||
export type McpCapability = "preview" | "monitor";
|
||||
|
||||
export interface McpInvocationScope {
|
||||
readonly environmentId: EnvironmentId;
|
||||
@@ -25,7 +25,7 @@ export class McpInvocationContext extends Context.Service<
|
||||
>()("t3/mcp/McpInvocationContext") {}
|
||||
|
||||
export const requireMcpCapability = Effect.fn("mcp.requireCapability")(function* (
|
||||
capability: McpCapability,
|
||||
capability: "preview",
|
||||
) {
|
||||
const invocation = yield* McpInvocationContext;
|
||||
if (!invocation.capabilities.has(capability)) {
|
||||
|
||||
@@ -114,7 +114,7 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
|
||||
threadId: ThreadId.make(request.threadId),
|
||||
providerSessionId,
|
||||
providerInstanceId: ProviderInstanceId.make(request.providerInstanceId),
|
||||
capabilities: new Set(["preview"]),
|
||||
capabilities: new Set(["preview", "monitor"]),
|
||||
issuedAt,
|
||||
expiresAt,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import { CommandId } from "@t3tools/contracts";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as McpInvocationContext from "../../McpInvocationContext.ts";
|
||||
import * as MonitorRegistry from "../../../monitor/MonitorRegistry.ts";
|
||||
import { cursorFromSnapshot } from "../../../monitor/monitorDiff.ts";
|
||||
import { OrchestrationEngineService } from "../../../orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { getPullRequestMonitorSnapshot } from "../../../sourceControl/gitHubPullRequestMonitor.ts";
|
||||
import { MonitorStartError, MonitorToolkit } from "./tools.ts";
|
||||
|
||||
const monitorStart = Effect.fn("MonitorToolkit.monitorStart")(function* ({
|
||||
prNumber,
|
||||
}: {
|
||||
readonly prNumber: number;
|
||||
}) {
|
||||
const invocation = yield* McpInvocationContext.McpInvocationContext;
|
||||
if (!invocation.capabilities.has("monitor")) {
|
||||
return yield* new MonitorStartError({ message: "PR monitoring is not available." });
|
||||
}
|
||||
const registry = yield* MonitorRegistry.MonitorRegistry;
|
||||
const existing = yield* registry.get(invocation.threadId);
|
||||
if (Option.isSome(existing)) {
|
||||
if (existing.value.prNumber !== prNumber) {
|
||||
return yield* new MonitorStartError({
|
||||
message: `This thread is already monitoring PR #${existing.value.prNumber}. Ask the user before switching to a different pull request.`,
|
||||
});
|
||||
}
|
||||
return {
|
||||
prNumber,
|
||||
status: "monitoring" as const,
|
||||
warning: null,
|
||||
message: `PR #${prNumber} is already being monitored.`,
|
||||
};
|
||||
}
|
||||
|
||||
const snapshots = yield* ProjectionSnapshotQuery;
|
||||
const readModel = yield* snapshots.getCommandReadModel();
|
||||
const thread = readModel.threads.find((candidate) => candidate.id === invocation.threadId);
|
||||
const project = thread
|
||||
? readModel.projects.find((candidate) => candidate.id === thread.projectId)
|
||||
: undefined;
|
||||
if (!thread || !project) {
|
||||
return yield* new MonitorStartError({ message: "The invoking thread no longer exists." });
|
||||
}
|
||||
const repoCwd = thread.worktreePath ?? project.workspaceRoot;
|
||||
const snapshot = yield* getPullRequestMonitorSnapshot({
|
||||
cwd: repoCwd,
|
||||
pullRequestNumber: prNumber,
|
||||
}).pipe(Effect.mapError((error) => new MonitorStartError({ message: error.message })));
|
||||
if (snapshot.state !== "open") {
|
||||
return yield* new MonitorStartError({
|
||||
message: `PR #${prNumber} is ${snapshot.state}; only open pull requests can be monitored.`,
|
||||
});
|
||||
}
|
||||
|
||||
const createdAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const commandId = CommandId.make(yield* crypto.randomUUIDv4);
|
||||
const warning = snapshot.draft
|
||||
? `PR #${prNumber} is a draft. Monitoring started, but review bots may not run until it is marked ready for review.`
|
||||
: null;
|
||||
const generation = yield* Clock.currentTimeMillis;
|
||||
const won = yield* registry.registerIfAbsent({
|
||||
threadId: invocation.threadId,
|
||||
prNumber,
|
||||
generation,
|
||||
cursor: cursorFromSnapshot(snapshot),
|
||||
wakeCount: 0,
|
||||
repoCwd,
|
||||
});
|
||||
if (!won) {
|
||||
// A concurrent monitor_start beat us between the existence check and the
|
||||
// registration write. Surface it rather than clobbering the winner.
|
||||
return yield* new MonitorStartError({
|
||||
message: "A monitor was just started for this thread; check its status before retrying.",
|
||||
});
|
||||
}
|
||||
yield* OrchestrationEngineService.pipe(
|
||||
Effect.flatMap((engine) =>
|
||||
engine.dispatch({
|
||||
type: "thread.monitor.start",
|
||||
commandId,
|
||||
threadId: invocation.threadId,
|
||||
prNumber,
|
||||
blockersSummary: warning ?? "",
|
||||
headSha: snapshot.headSha,
|
||||
createdAt,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((error) => new MonitorStartError({ message: String(error) })),
|
||||
// Roll back only the registration this call installed — a raced winner's
|
||||
// registration must survive our failure.
|
||||
Effect.onError(() => registry.removeGeneration(invocation.threadId, generation)),
|
||||
);
|
||||
return {
|
||||
prNumber,
|
||||
status: "monitoring" as const,
|
||||
warning,
|
||||
message: warning ?? `Started monitoring PR #${prNumber}.`,
|
||||
};
|
||||
});
|
||||
|
||||
export const MonitorToolkitHandlersLive = MonitorToolkit.toLayer({
|
||||
monitor_start: (input) =>
|
||||
monitorStart(input).pipe(
|
||||
Effect.catch((error) =>
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"_tag" in error &&
|
||||
error._tag === "MonitorStartError"
|
||||
? error
|
||||
: new MonitorStartError({ message: String(error) }),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import { Tool, Toolkit } from "effect/unstable/ai";
|
||||
|
||||
import * as McpInvocationContext from "../../McpInvocationContext.ts";
|
||||
import * as MonitorRegistry from "../../../monitor/MonitorRegistry.ts";
|
||||
import { OrchestrationEngineService } from "../../../orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as GitHubCli from "../../../sourceControl/GitHubCli.ts";
|
||||
|
||||
export class MonitorStartError extends Schema.TaggedErrorClass<MonitorStartError>()(
|
||||
"MonitorStartError",
|
||||
{ message: Schema.String },
|
||||
) {}
|
||||
|
||||
export const MonitorStartTool = Tool.make("monitor_start", {
|
||||
description:
|
||||
"Start monitoring a pull request for this thread. Call this after creating or identifying the PR when the user has asked you to monitor, babysit, or watch it for review feedback and CI results. The server will watch the PR and wake this thread when there is something to address. Never create the PR as a draft — review bots do not run on drafts.",
|
||||
parameters: Schema.Struct({ prNumber: Schema.Int.check(Schema.isGreaterThan(0)) }),
|
||||
success: Schema.Struct({
|
||||
prNumber: Schema.Number,
|
||||
status: Schema.Literal("monitoring"),
|
||||
warning: Schema.NullOr(Schema.String),
|
||||
message: Schema.String,
|
||||
}),
|
||||
failure: MonitorStartError,
|
||||
dependencies: [
|
||||
McpInvocationContext.McpInvocationContext,
|
||||
MonitorRegistry.MonitorRegistry,
|
||||
OrchestrationEngineService,
|
||||
ProjectionSnapshotQuery,
|
||||
GitHubCli.GitHubCli,
|
||||
Crypto.Crypto,
|
||||
],
|
||||
})
|
||||
.annotate(Tool.Title, "Start PR monitoring")
|
||||
.annotate(Tool.Idempotent, true)
|
||||
.annotate(Tool.Destructive, false)
|
||||
.annotate(Tool.OpenWorld, true);
|
||||
|
||||
export const MonitorToolkit = Toolkit.make(MonitorStartTool);
|
||||
@@ -0,0 +1,129 @@
|
||||
import { CommandId, type ThreadId } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import type { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
|
||||
import type { PullRequestMonitorCursor } from "./monitorDiff.ts";
|
||||
|
||||
export interface MonitorRegistration {
|
||||
readonly threadId: ThreadId;
|
||||
readonly prNumber: number;
|
||||
readonly generation: number;
|
||||
readonly cursor: PullRequestMonitorCursor;
|
||||
readonly wakeCount: number;
|
||||
readonly repoCwd: string;
|
||||
}
|
||||
|
||||
export interface MonitorRegistryShape {
|
||||
/** Registers only when the thread has no active registration; returns
|
||||
whether this call won. Losing concurrent monitor_start calls must not
|
||||
clobber the winner's cursor/generation. */
|
||||
readonly registerIfAbsent: (registration: MonitorRegistration) => Effect.Effect<boolean>;
|
||||
/** Removes only the exact generation the caller installed, so a failed
|
||||
start can roll back without erasing a racing winner's registration. */
|
||||
readonly removeGeneration: (threadId: ThreadId, generation: number) => Effect.Effect<void>;
|
||||
readonly get: (threadId: ThreadId) => Effect.Effect<Option.Option<MonitorRegistration>>;
|
||||
readonly updateCursor: (
|
||||
threadId: ThreadId,
|
||||
cursor: PullRequestMonitorCursor,
|
||||
) => Effect.Effect<void>;
|
||||
readonly incrementWake: (threadId: ThreadId) => Effect.Effect<number>;
|
||||
readonly remove: (threadId: ThreadId) => Effect.Effect<Option.Option<MonitorRegistration>>;
|
||||
readonly listActive: Effect.Effect<ReadonlyArray<MonitorRegistration>>;
|
||||
}
|
||||
|
||||
export class MonitorRegistry extends Context.Service<MonitorRegistry, MonitorRegistryShape>()(
|
||||
"t3/monitor/MonitorRegistry",
|
||||
) {}
|
||||
|
||||
// Module-global store, mirroring McpProviderSession: the registry is
|
||||
// constructed both in the runtime core (for the poller) and inside the MCP
|
||||
// routes layer (for monitor_start), and those two layer instances must see
|
||||
// the same registrations. All operations are synchronous, so plain-Map
|
||||
// mutation inside Effect.sync is atomic per call.
|
||||
const registrations = new Map<ThreadId, MonitorRegistration>();
|
||||
|
||||
const make: MonitorRegistryShape = {
|
||||
registerIfAbsent: (registration) =>
|
||||
Effect.sync(() => {
|
||||
if (registrations.has(registration.threadId)) return false;
|
||||
registrations.set(registration.threadId, registration);
|
||||
return true;
|
||||
}),
|
||||
removeGeneration: (threadId, generation) =>
|
||||
Effect.sync(() => {
|
||||
const current = registrations.get(threadId);
|
||||
if (current !== undefined && current.generation === generation) {
|
||||
registrations.delete(threadId);
|
||||
}
|
||||
}),
|
||||
get: (threadId) => Effect.sync(() => Option.fromNullishOr(registrations.get(threadId))),
|
||||
updateCursor: (threadId, cursor) =>
|
||||
Effect.sync(() => {
|
||||
const current = registrations.get(threadId);
|
||||
if (current !== undefined) registrations.set(threadId, { ...current, cursor });
|
||||
}),
|
||||
incrementWake: (threadId) =>
|
||||
Effect.sync(() => {
|
||||
const current = registrations.get(threadId);
|
||||
const wakeCount = (current?.wakeCount ?? 0) + 1;
|
||||
if (current !== undefined) registrations.set(threadId, { ...current, wakeCount });
|
||||
return wakeCount;
|
||||
}),
|
||||
remove: (threadId) =>
|
||||
Effect.sync(() => {
|
||||
const current = registrations.get(threadId);
|
||||
registrations.delete(threadId);
|
||||
return Option.fromNullishOr(current);
|
||||
}),
|
||||
listActive: Effect.sync(() => [...registrations.values()]),
|
||||
};
|
||||
|
||||
// The engine used for teardown dispatch is bound by PullRequestMonitor when
|
||||
// it starts (it is the only construction site that has the engine and runs in
|
||||
// the runtime core). Until then teardown just clears the store.
|
||||
let activeEngine: OrchestrationEngineService["Service"] | undefined;
|
||||
|
||||
export const bindEngine = (engine: OrchestrationEngineService["Service"]): void => {
|
||||
activeEngine = engine;
|
||||
};
|
||||
|
||||
export const layer = Layer.effect(
|
||||
MonitorRegistry,
|
||||
Effect.acquireRelease(Effect.succeed(MonitorRegistry.of(make)), () =>
|
||||
Effect.gen(function* () {
|
||||
for (const registration of [...registrations.values()]) {
|
||||
yield* endActiveMonitorForSession(registration.threadId);
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
export const endActiveMonitorForSession = (threadId: ThreadId): Effect.Effect<void> =>
|
||||
Effect.gen(function* () {
|
||||
const registration = yield* make.remove(threadId);
|
||||
if (Option.isNone(registration) || activeEngine === undefined) return;
|
||||
const endedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const commandId = CommandId.make(`monitor-session-ended:${threadId}:${endedAt}`);
|
||||
yield* activeEngine.dispatch({
|
||||
type: "thread.monitor.end",
|
||||
commandId,
|
||||
threadId,
|
||||
reason: "session-ended",
|
||||
blockersSummary: "",
|
||||
endedAt,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.catch((error) => Effect.logWarning("monitor teardown failed", { threadId, error })),
|
||||
);
|
||||
|
||||
export const __testing = {
|
||||
make,
|
||||
reset: (): void => {
|
||||
registrations.clear();
|
||||
activeEngine = undefined;
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,342 @@
|
||||
import {
|
||||
CommandId,
|
||||
EventId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationCommand,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { OrchestrationCommandInvariantError } from "../orchestration/Errors.ts";
|
||||
import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import type { PullRequestMonitorSnapshot } from "../sourceControl/gitHubPullRequestMonitor.ts";
|
||||
import * as MonitorRegistry from "./MonitorRegistry.ts";
|
||||
import { cursorFromSnapshot } from "./monitorDiff.ts";
|
||||
import { make, PullRequestSnapshotFetcher } from "./PullRequestMonitor.ts";
|
||||
|
||||
const threadId = ThreadId.make("monitor-thread");
|
||||
const now = "2026-07-23T00:00:00.000Z";
|
||||
|
||||
const snapshot = (
|
||||
overrides: Partial<PullRequestMonitorSnapshot> = {},
|
||||
): PullRequestMonitorSnapshot => ({
|
||||
state: "open",
|
||||
draft: false,
|
||||
headSha: "head-1",
|
||||
mergeability: "mergeable",
|
||||
behindBaseBy: null,
|
||||
requiredChecksKnown: true,
|
||||
reviews: [],
|
||||
reviewThreads: [],
|
||||
issueComments: [],
|
||||
checkRuns: [
|
||||
{
|
||||
id: "ci-1",
|
||||
name: "CI",
|
||||
status: "in-progress",
|
||||
conclusion: null,
|
||||
startedAt: now,
|
||||
headSha: "head-1",
|
||||
},
|
||||
],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const comment = (id: string) => ({
|
||||
id,
|
||||
author: { login: "bugbot", type: "app" as const },
|
||||
body: `Finding ${id}`,
|
||||
path: "src/file.ts",
|
||||
line: 12,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
resolved: false,
|
||||
});
|
||||
|
||||
const thread = (busy = false): OrchestrationThread => ({
|
||||
id: threadId,
|
||||
projectId: ProjectId.make("project"),
|
||||
title: "Monitor",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("claude"), model: "default" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: "feature",
|
||||
worktreePath: "/repo",
|
||||
latestTurn: busy
|
||||
? {
|
||||
turnId: TurnId.make("busy-turn"),
|
||||
state: "running",
|
||||
requestedAt: now,
|
||||
startedAt: now,
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
}
|
||||
: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
monitor: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
});
|
||||
|
||||
const harness = Effect.fn("PullRequestMonitor.testHarness")(function* (input: {
|
||||
readonly initial: PullRequestMonitorSnapshot;
|
||||
readonly current: { value: PullRequestMonitorSnapshot };
|
||||
readonly wakeCount?: number;
|
||||
readonly failWake?: boolean;
|
||||
readonly busy?: { value: boolean };
|
||||
readonly afterUpdate?: () => void;
|
||||
readonly changeGenerationAfterUpdate?: boolean;
|
||||
}) {
|
||||
let registration: MonitorRegistry.MonitorRegistration | undefined = {
|
||||
threadId,
|
||||
prNumber: 42,
|
||||
generation: 1,
|
||||
cursor: cursorFromSnapshot(input.initial),
|
||||
wakeCount: input.wakeCount ?? 0,
|
||||
repoCwd: "/repo",
|
||||
};
|
||||
const commands: OrchestrationCommand[] = [];
|
||||
const ordering: string[] = [];
|
||||
const registry = MonitorRegistry.MonitorRegistry.of({
|
||||
registerIfAbsent: (next) =>
|
||||
Effect.sync(() => {
|
||||
if (registration !== undefined) return false;
|
||||
registration = next;
|
||||
return true;
|
||||
}),
|
||||
removeGeneration: (_, generation) =>
|
||||
Effect.sync(() => {
|
||||
if (registration?.generation === generation) registration = undefined;
|
||||
}),
|
||||
get: () => Effect.sync(() => (registration ? Option.some(registration) : Option.none())),
|
||||
updateCursor: (_, cursor) =>
|
||||
Effect.sync(() => {
|
||||
ordering.push("ack");
|
||||
if (registration) registration = { ...registration, cursor };
|
||||
}),
|
||||
incrementWake: () =>
|
||||
Effect.sync(() => {
|
||||
const count = (registration?.wakeCount ?? 0) + 1;
|
||||
if (registration) registration = { ...registration, wakeCount: count };
|
||||
return count;
|
||||
}),
|
||||
remove: () =>
|
||||
Effect.sync(() => {
|
||||
const removed = registration ? Option.some(registration) : Option.none();
|
||||
registration = undefined;
|
||||
return removed;
|
||||
}),
|
||||
listActive: Effect.sync(() => (registration ? [registration] : [])),
|
||||
});
|
||||
const engine = OrchestrationEngineService.of({
|
||||
readEvents: () => Stream.empty,
|
||||
streamDomainEvents: Stream.empty,
|
||||
latestSequence: Effect.succeed(0),
|
||||
dispatch: (command) => {
|
||||
commands.push(command);
|
||||
if (command.type === "thread.monitor.update") {
|
||||
input.afterUpdate?.();
|
||||
if (input.changeGenerationAfterUpdate && registration) {
|
||||
registration = { ...registration, generation: registration.generation + 1 };
|
||||
}
|
||||
}
|
||||
if (command.type === "thread.turn.start") {
|
||||
ordering.push("dispatch");
|
||||
if (input.failWake) {
|
||||
return Effect.fail(
|
||||
new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: "rejected",
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
return Effect.succeed({ sequence: commands.length });
|
||||
},
|
||||
});
|
||||
const monitor = yield* make.pipe(
|
||||
Effect.provideService(MonitorRegistry.MonitorRegistry, registry),
|
||||
Effect.provideService(PullRequestSnapshotFetcher, {
|
||||
fetch: () => Effect.succeed(input.current.value),
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngineService, engine),
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.mock(ProjectionSnapshotQuery)({
|
||||
getThreadDetailById: () =>
|
||||
Effect.succeed(Option.some(thread(input.busy?.value ?? false))),
|
||||
}),
|
||||
NodeServices.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
return { monitor, commands, ordering, getRegistration: () => registration };
|
||||
});
|
||||
|
||||
const endReason = (commands: ReadonlyArray<OrchestrationCommand>) =>
|
||||
commands.find((command) => command.type === "thread.monitor.end");
|
||||
|
||||
describe("PullRequestMonitor dispatch protocol", () => {
|
||||
it.effect("terminal-discards-cycle", () =>
|
||||
Effect.gen(function* () {
|
||||
const initial = snapshot();
|
||||
const h = yield* harness({
|
||||
initial,
|
||||
current: { value: snapshot({ state: "merged", reviewThreads: [comment("late")] }) },
|
||||
});
|
||||
yield* h.monitor.pollOnce;
|
||||
assert.strictEqual(endReason(h.commands)?.type, "thread.monitor.end");
|
||||
assert.strictEqual(
|
||||
h.commands.some((command) => command.type === "thread.turn.start"),
|
||||
false,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ready-ends after a final update", () =>
|
||||
Effect.gen(function* () {
|
||||
const ready = snapshot({
|
||||
checkRuns: [{ ...snapshot().checkRuns[0]!, status: "completed", conclusion: "success" }],
|
||||
});
|
||||
const h = yield* harness({ initial: snapshot(), current: { value: ready } });
|
||||
yield* h.monitor.pollOnce;
|
||||
assert.deepStrictEqual(
|
||||
h.commands.map((command) => command.type),
|
||||
["thread.monitor.update", "thread.monitor.end"],
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("wake-then-ack ordering", () =>
|
||||
Effect.gen(function* () {
|
||||
const h = yield* harness({
|
||||
initial: snapshot(),
|
||||
current: { value: snapshot({ reviewThreads: [comment("one")] }) },
|
||||
});
|
||||
yield* h.monitor.pollOnce;
|
||||
assert.deepStrictEqual(h.ordering, ["dispatch", "ack"]);
|
||||
assert.strictEqual(h.getRegistration()?.wakeCount, 1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("failed-dispatch-preserves-cursor", () =>
|
||||
Effect.gen(function* () {
|
||||
const initial = snapshot();
|
||||
const h = yield* harness({
|
||||
initial,
|
||||
current: { value: snapshot({ reviewThreads: [comment("one")] }) },
|
||||
failWake: true,
|
||||
});
|
||||
yield* h.monitor.pollOnce;
|
||||
assert.deepStrictEqual(h.getRegistration()?.cursor, cursorFromSnapshot(initial));
|
||||
assert.strictEqual(h.getRegistration()?.wakeCount, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("user-turn-discards-pending-wake", () =>
|
||||
Effect.gen(function* () {
|
||||
const busy = { value: true };
|
||||
const h = yield* harness({
|
||||
initial: snapshot(),
|
||||
current: { value: snapshot({ reviewThreads: [comment("one")] }) },
|
||||
busy,
|
||||
});
|
||||
yield* h.monitor.pollOnce;
|
||||
assert.strictEqual(
|
||||
h.commands.some((command) => command.type === "thread.turn.start"),
|
||||
false,
|
||||
);
|
||||
assert.deepStrictEqual(h.getRegistration()?.cursor, cursorFromSnapshot(snapshot()));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("generation-change-discards", () =>
|
||||
Effect.gen(function* () {
|
||||
const h = yield* harness({
|
||||
initial: snapshot(),
|
||||
current: { value: snapshot({ reviewThreads: [comment("one")] }) },
|
||||
changeGenerationAfterUpdate: true,
|
||||
});
|
||||
yield* h.monitor.pollOnce;
|
||||
assert.strictEqual(
|
||||
h.commands.some((command) => command.type === "thread.turn.start"),
|
||||
false,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("coalesces events while a wake is in flight", () =>
|
||||
Effect.gen(function* () {
|
||||
const current = { value: snapshot({ reviewThreads: [comment("one")] }) };
|
||||
const h = yield* harness({ initial: snapshot(), current });
|
||||
yield* h.monitor.pollOnce;
|
||||
current.value = snapshot({
|
||||
reviewThreads: [comment("one"), comment("two"), comment("three")],
|
||||
});
|
||||
yield* h.monitor.pollOnce;
|
||||
assert.strictEqual(
|
||||
h.commands.filter((command) => command.type === "thread.turn.start").length,
|
||||
1,
|
||||
);
|
||||
yield* h.monitor.handleDomainEvent({
|
||||
sequence: 1,
|
||||
eventId: EventId.make("session-ready"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("session-ready"),
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
type: "thread.session-set",
|
||||
payload: {
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "ready",
|
||||
providerName: "claude",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
},
|
||||
});
|
||||
yield* h.monitor.pollOnce;
|
||||
const wakes = h.commands.filter((command) => command.type === "thread.turn.start");
|
||||
assert.strictEqual(wakes.length, 2);
|
||||
assert.match(wakes[1]!.message.text, /Finding two/);
|
||||
assert.match(wakes[1]!.message.text, /Finding three/);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("breaker-at-10", () =>
|
||||
Effect.gen(function* () {
|
||||
const h = yield* harness({
|
||||
initial: snapshot(),
|
||||
current: { value: snapshot({ reviewThreads: [comment("one")] }) },
|
||||
wakeCount: 10,
|
||||
});
|
||||
yield* h.monitor.pollOnce;
|
||||
const ended = endReason(h.commands);
|
||||
assert.strictEqual(ended?.type === "thread.monitor.end" && ended.reason, "needs-attention");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,371 @@
|
||||
import { CommandId, MessageId, type OrchestrationEvent, type ThreadId } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
|
||||
|
||||
import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
getPullRequestMonitorSnapshot,
|
||||
type GitHubPullRequestMonitorError,
|
||||
type PullRequestMonitorSnapshot,
|
||||
} from "../sourceControl/gitHubPullRequestMonitor.ts";
|
||||
import * as MonitorRegistry from "./MonitorRegistry.ts";
|
||||
import { diffPullRequestMonitorSnapshot, type PullRequestMonitorCursor } from "./monitorDiff.ts";
|
||||
import { computeReadiness } from "./readiness.ts";
|
||||
import { buildWakePrompt, formatBlockersSummary } from "./wakePrompt.ts";
|
||||
|
||||
const POLL_INTERVAL = Duration.seconds(30);
|
||||
const MAX_BACKOFF = Duration.minutes(5);
|
||||
|
||||
interface WakeClaim {
|
||||
readonly generation: number;
|
||||
readonly commandId: CommandId;
|
||||
readonly phase: "pending" | "in-flight";
|
||||
// Cursor as it was before this wake acked, so a wake that dies after the
|
||||
// ack — provider start failure, superseded by a user turn — can rewind and
|
||||
// let the next poll re-diff the same events instead of losing them (I5).
|
||||
readonly previousCursor: PullRequestMonitorCursor;
|
||||
}
|
||||
|
||||
export interface PullRequestSnapshotFetcherShape {
|
||||
readonly fetch: (input: {
|
||||
readonly cwd: string;
|
||||
readonly pullRequestNumber: number;
|
||||
}) => Effect.Effect<PullRequestMonitorSnapshot, GitHubPullRequestMonitorError>;
|
||||
}
|
||||
|
||||
export class PullRequestSnapshotFetcher extends Context.Service<
|
||||
PullRequestSnapshotFetcher,
|
||||
PullRequestSnapshotFetcherShape
|
||||
>()("t3/monitor/PullRequestMonitor/PullRequestSnapshotFetcher") {}
|
||||
|
||||
export const PullRequestSnapshotFetcherLive = Layer.effect(
|
||||
PullRequestSnapshotFetcher,
|
||||
Effect.gen(function* () {
|
||||
const githubCli = yield* GitHubCli.GitHubCli;
|
||||
return PullRequestSnapshotFetcher.of({
|
||||
fetch: (input) =>
|
||||
getPullRequestMonitorSnapshot(input).pipe(
|
||||
Effect.provideService(GitHubCli.GitHubCli, githubCli),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
export class PullRequestMonitor extends Context.Service<
|
||||
PullRequestMonitor,
|
||||
{
|
||||
readonly start: () => Effect.Effect<void>;
|
||||
readonly pollOnce: Effect.Effect<void>;
|
||||
readonly handleDomainEvent: (event: OrchestrationEvent) => Effect.Effect<void>;
|
||||
}
|
||||
>()("t3/monitor/PullRequestMonitor") {}
|
||||
|
||||
const threadIdOf = (event: OrchestrationEvent): ThreadId | undefined =>
|
||||
"threadId" in event.payload ? event.payload.threadId : undefined;
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const registry = yield* MonitorRegistry.MonitorRegistry;
|
||||
const fetcher = yield* PullRequestSnapshotFetcher;
|
||||
const engine = yield* OrchestrationEngineService;
|
||||
// Give session-teardown paths (which run outside this service's context) a
|
||||
// way to dispatch thread.monitor.end through the real engine.
|
||||
MonitorRegistry.bindEngine(engine);
|
||||
const snapshots = yield* ProjectionSnapshotQuery;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const claims = yield* Ref.make<ReadonlyMap<ThreadId, WakeClaim>>(new Map());
|
||||
const latestStates = yield* Ref.make<ReadonlyMap<ThreadId, PullRequestMonitorSnapshot["state"]>>(
|
||||
new Map(),
|
||||
);
|
||||
const lastPollFailed = yield* Ref.make(false);
|
||||
|
||||
const mutateClaim = (
|
||||
threadId: ThreadId,
|
||||
f: (claim: WakeClaim | undefined) => WakeClaim | undefined,
|
||||
) =>
|
||||
Ref.update(claims, (current) => {
|
||||
const next = new Map(current);
|
||||
const claim = f(next.get(threadId));
|
||||
if (claim === undefined) next.delete(threadId);
|
||||
else next.set(threadId, claim);
|
||||
return next;
|
||||
});
|
||||
|
||||
// Drop a claim matching `shouldRelease`; if its wake had already advanced
|
||||
// the cursor, rewind to the pre-wake cursor so those events re-diff (I5).
|
||||
const releaseClaim = (threadId: ThreadId, shouldRelease: (claim: WakeClaim) => boolean) =>
|
||||
Ref.modify(claims, (current) => {
|
||||
const claim = current.get(threadId);
|
||||
if (claim === undefined || !shouldRelease(claim)) {
|
||||
return [undefined, current] as const;
|
||||
}
|
||||
const next = new Map(current);
|
||||
next.delete(threadId);
|
||||
return [claim, next] as const;
|
||||
}).pipe(
|
||||
Effect.flatMap((released) =>
|
||||
released === undefined || released.phase !== "in-flight"
|
||||
? Effect.void
|
||||
: registry.updateCursor(threadId, released.previousCursor),
|
||||
),
|
||||
);
|
||||
|
||||
const dispatchUpdate = Effect.fn("PullRequestMonitor.dispatchUpdate")(function* (
|
||||
threadId: ThreadId,
|
||||
blockersSummary: string,
|
||||
headSha: string,
|
||||
wakeCount: number,
|
||||
) {
|
||||
const updatedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
yield* engine.dispatch({
|
||||
type: "thread.monitor.update",
|
||||
commandId: CommandId.make(yield* crypto.randomUUIDv4),
|
||||
threadId,
|
||||
blockersSummary,
|
||||
headSha,
|
||||
wakeCount,
|
||||
updatedAt,
|
||||
});
|
||||
});
|
||||
|
||||
const end = Effect.fn("PullRequestMonitor.end")(function* (
|
||||
threadId: ThreadId,
|
||||
reason: "ready" | "terminal" | "needs-attention",
|
||||
blockersSummary: string,
|
||||
) {
|
||||
// Dispatch before removing: if the end event fails to persist, the
|
||||
// registration survives and the next poll retries the same terminal /
|
||||
// ready / breaker verdict, instead of leaving the projection stuck on
|
||||
// "monitoring" with nothing polling it.
|
||||
const endedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
yield* engine.dispatch({
|
||||
type: "thread.monitor.end",
|
||||
commandId: CommandId.make(yield* crypto.randomUUIDv4),
|
||||
threadId,
|
||||
reason,
|
||||
blockersSummary,
|
||||
endedAt,
|
||||
});
|
||||
yield* registry.remove(threadId);
|
||||
yield* mutateClaim(threadId, () => undefined);
|
||||
});
|
||||
|
||||
const dispatchWake = Effect.fn("PullRequestMonitor.dispatchWake")(function* (
|
||||
registration: MonitorRegistry.MonitorRegistration,
|
||||
snapshot: PullRequestMonitorSnapshot,
|
||||
nextCursor: PullRequestMonitorCursor,
|
||||
prompt: string,
|
||||
) {
|
||||
const commandId = CommandId.make(yield* crypto.randomUUIDv4);
|
||||
let claimed = false;
|
||||
yield* Ref.update(claims, (current) => {
|
||||
if (current.has(registration.threadId)) return current;
|
||||
claimed = true;
|
||||
return new Map(current).set(registration.threadId, {
|
||||
generation: registration.generation,
|
||||
commandId,
|
||||
phase: "pending",
|
||||
previousCursor: registration.cursor,
|
||||
});
|
||||
});
|
||||
if (!claimed) return;
|
||||
|
||||
const current = yield* registry.get(registration.threadId);
|
||||
// Fresh terminal read at the send boundary (I1): the poll's snapshot is
|
||||
// seconds stale by now, and a merge in that window must veto the wake —
|
||||
// the cached `latestStates` alone cannot see it.
|
||||
const freshState: PullRequestMonitorSnapshot["state"] | "unknown" = yield* fetcher
|
||||
.fetch({ cwd: registration.repoCwd, pullRequestNumber: registration.prNumber })
|
||||
.pipe(
|
||||
Effect.map((fresh) => fresh.state),
|
||||
Effect.orElseSucceed(() => "unknown" as const),
|
||||
);
|
||||
const state =
|
||||
freshState === "unknown"
|
||||
? (yield* Ref.get(latestStates)).get(registration.threadId)
|
||||
: freshState;
|
||||
const thread = yield* snapshots.getThreadDetailById(registration.threadId);
|
||||
const validRegistration =
|
||||
Option.isSome(current) && current.value.generation === registration.generation;
|
||||
const busy =
|
||||
Option.isNone(thread) ||
|
||||
thread.value.latestTurn?.state === "running" ||
|
||||
(thread.value.session?.activeTurnId !== null &&
|
||||
thread.value.session?.activeTurnId !== undefined) ||
|
||||
thread.value.session?.status === "starting" ||
|
||||
thread.value.session?.status === "running";
|
||||
const stillClaimed =
|
||||
(yield* Ref.get(claims)).get(registration.threadId)?.commandId === commandId;
|
||||
if (!validRegistration || state === "closed" || state === "merged" || busy || !stillClaimed) {
|
||||
yield* mutateClaim(registration.threadId, (claim) =>
|
||||
claim?.commandId === commandId ? undefined : claim,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const createdAt = DateTime.formatIso(yield* DateTime.now);
|
||||
yield* engine
|
||||
.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId,
|
||||
threadId: registration.threadId,
|
||||
message: {
|
||||
messageId: MessageId.make(yield* crypto.randomUUIDv4),
|
||||
role: "user",
|
||||
text: prompt,
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: thread.value.runtimeMode,
|
||||
interactionMode: thread.value.interactionMode,
|
||||
createdAt,
|
||||
})
|
||||
.pipe(
|
||||
Effect.tap(() =>
|
||||
mutateClaim(registration.threadId, (claim) =>
|
||||
claim?.commandId === commandId ? { ...claim, phase: "in-flight" } : claim,
|
||||
),
|
||||
),
|
||||
Effect.tap(() => registry.updateCursor(registration.threadId, nextCursor)),
|
||||
Effect.tapError(() =>
|
||||
mutateClaim(registration.threadId, (claim) =>
|
||||
claim?.commandId === commandId ? undefined : claim,
|
||||
),
|
||||
),
|
||||
);
|
||||
const wakeCount = yield* registry.incrementWake(registration.threadId);
|
||||
yield* dispatchUpdate(
|
||||
registration.threadId,
|
||||
formatBlockersSummary(computeReadiness(snapshot)),
|
||||
snapshot.headSha,
|
||||
wakeCount,
|
||||
);
|
||||
});
|
||||
|
||||
const pollRegistration = Effect.fn("PullRequestMonitor.pollRegistration")(function* (
|
||||
registration: MonitorRegistry.MonitorRegistration,
|
||||
) {
|
||||
const snapshot = yield* fetcher.fetch({
|
||||
cwd: registration.repoCwd,
|
||||
pullRequestNumber: registration.prNumber,
|
||||
});
|
||||
yield* Ref.update(latestStates, (states) =>
|
||||
new Map(states).set(registration.threadId, snapshot.state),
|
||||
);
|
||||
const readiness = computeReadiness(snapshot);
|
||||
const summary = formatBlockersSummary(readiness);
|
||||
|
||||
if (snapshot.state !== "open") {
|
||||
yield* end(registration.threadId, "terminal", summary);
|
||||
return;
|
||||
}
|
||||
if (readiness.ready) {
|
||||
yield* dispatchUpdate(
|
||||
registration.threadId,
|
||||
summary,
|
||||
snapshot.headSha,
|
||||
registration.wakeCount,
|
||||
);
|
||||
yield* end(registration.threadId, "ready", summary);
|
||||
return;
|
||||
}
|
||||
|
||||
const diff = diffPullRequestMonitorSnapshot(registration.cursor, snapshot);
|
||||
yield* dispatchUpdate(registration.threadId, summary, snapshot.headSha, registration.wakeCount);
|
||||
if (diff.actionableEvents.length === 0) return;
|
||||
if (registration.wakeCount >= 10) {
|
||||
yield* end(registration.threadId, "needs-attention", summary);
|
||||
return;
|
||||
}
|
||||
yield* dispatchWake(
|
||||
registration,
|
||||
snapshot,
|
||||
diff.nextCursor,
|
||||
buildWakePrompt({
|
||||
prNumber: registration.prNumber,
|
||||
wakeCount: registration.wakeCount + 1,
|
||||
events: diff.actionableEvents,
|
||||
snapshot,
|
||||
readiness,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const pollOnce = Ref.set(lastPollFailed, false).pipe(
|
||||
Effect.andThen(registry.listActive),
|
||||
Effect.flatMap((registrations) =>
|
||||
Effect.forEach(
|
||||
registrations,
|
||||
(registration) =>
|
||||
pollRegistration(registration).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("pull request monitor poll failed", {
|
||||
threadId: registration.threadId,
|
||||
cause,
|
||||
}).pipe(Effect.andThen(Ref.set(lastPollFailed, true))),
|
||||
),
|
||||
),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const onEvent = (event: OrchestrationEvent) => {
|
||||
const threadId = threadIdOf(event);
|
||||
if (threadId === undefined) return Effect.void;
|
||||
if (
|
||||
event.type === "thread.deleted" ||
|
||||
event.type === "thread.archived" ||
|
||||
event.type === "thread.settled" ||
|
||||
event.type === "thread.monitor-ended"
|
||||
) {
|
||||
return registry
|
||||
.remove(threadId)
|
||||
.pipe(Effect.andThen(mutateClaim(threadId, () => undefined)), Effect.asVoid);
|
||||
}
|
||||
if (event.type === "thread.turn-start-requested") {
|
||||
// A turn we didn't start won the thread. Drop our claim — and if our
|
||||
// wake had already acked the cursor (in-flight), rewind it so the
|
||||
// superseded events re-diff next poll instead of being lost (I5).
|
||||
return releaseClaim(threadId, (claim) => claim.commandId !== event.commandId);
|
||||
}
|
||||
if (
|
||||
event.type === "thread.activity-appended" &&
|
||||
event.payload.activity.kind === "provider.turn.start.failed"
|
||||
) {
|
||||
// engine.dispatch succeeded but the provider reactor failed the turn
|
||||
// asynchronously — the acked events never reached an agent (I5).
|
||||
return releaseClaim(threadId, () => true);
|
||||
}
|
||||
if (event.type === "thread.session-set") {
|
||||
const status = event.payload.session.status;
|
||||
if (status !== "starting" && status !== "running") {
|
||||
return mutateClaim(threadId, (claim) => (claim?.phase === "in-flight" ? undefined : claim));
|
||||
}
|
||||
}
|
||||
return Effect.void;
|
||||
};
|
||||
|
||||
const start = Effect.fn("PullRequestMonitor.start")(function* () {
|
||||
yield* Effect.forkDetach(Stream.runForEach(engine.streamDomainEvents, onEvent));
|
||||
yield* Effect.forkDetach(
|
||||
Effect.forever(
|
||||
pollOnce.pipe(
|
||||
Effect.andThen(Ref.get(lastPollFailed)),
|
||||
Effect.flatMap((failed) => Effect.sleep(failed ? MAX_BACKOFF : POLL_INTERVAL)),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return PullRequestMonitor.of({ start, pollOnce, handleDomainEvent: onEvent });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(PullRequestMonitor, make);
|
||||
@@ -0,0 +1,126 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
|
||||
import type { PullRequestMonitorSnapshot } from "../sourceControl/gitHubPullRequestMonitor.ts";
|
||||
import { cursorFromSnapshot, diffPullRequestMonitorSnapshot } from "./monitorDiff.ts";
|
||||
|
||||
const snapshot = (
|
||||
overrides: Partial<PullRequestMonitorSnapshot> = {},
|
||||
): PullRequestMonitorSnapshot => ({
|
||||
state: "open",
|
||||
draft: false,
|
||||
headSha: "head-1",
|
||||
mergeability: "mergeable",
|
||||
behindBaseBy: null,
|
||||
requiredChecksKnown: true,
|
||||
reviews: [],
|
||||
reviewThreads: [],
|
||||
issueComments: [],
|
||||
checkRuns: [],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const thread = (updatedAt = "2026-01-01T00:00:00Z", resolved = false) => ({
|
||||
id: "thread-1",
|
||||
author: { login: "review-bot", type: "app" as const },
|
||||
body: "Fix this",
|
||||
path: "src/a.ts",
|
||||
line: 3,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
updatedAt,
|
||||
resolved,
|
||||
});
|
||||
|
||||
const check = (id: string, conclusion: "success" | "failure") => ({
|
||||
id,
|
||||
name: "CI",
|
||||
status: "completed" as const,
|
||||
conclusion,
|
||||
startedAt: "2026-01-01T00:00:00Z",
|
||||
headSha: "head-1",
|
||||
});
|
||||
|
||||
describe("pull request monitor diff", () => {
|
||||
it("baselines every existing event", () => {
|
||||
const initial = snapshot({
|
||||
reviewThreads: [thread()],
|
||||
checkRuns: [check("run-1", "failure")],
|
||||
});
|
||||
assert.deepStrictEqual(
|
||||
diffPullRequestMonitorSnapshot(cursorFromSnapshot(initial), initial).actionableEvents,
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
it("detects a new comment and an edit by id plus updatedAt", () => {
|
||||
const emptyCursor = cursorFromSnapshot(snapshot());
|
||||
const withComment = snapshot({ reviewThreads: [thread()] });
|
||||
const added = diffPullRequestMonitorSnapshot(emptyCursor, withComment);
|
||||
assert.deepStrictEqual(added.actionableEvents, [
|
||||
{ kind: "new-review-comment", threadId: "thread-1", edited: false },
|
||||
]);
|
||||
|
||||
const edited = diffPullRequestMonitorSnapshot(
|
||||
added.nextCursor,
|
||||
snapshot({ reviewThreads: [thread("2026-01-02T00:00:00Z")] }),
|
||||
);
|
||||
assert.deepStrictEqual(edited.actionableEvents, [
|
||||
{ kind: "new-review-comment", threadId: "thread-1", edited: true },
|
||||
]);
|
||||
});
|
||||
|
||||
it("detects new and edited bot issue comments", () => {
|
||||
const issueComment = {
|
||||
id: "comment-1",
|
||||
author: { login: "review-bot", type: "app" as const },
|
||||
body: "Please update this",
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
updatedAt: "2026-01-01T00:00:00Z",
|
||||
};
|
||||
const added = diffPullRequestMonitorSnapshot(
|
||||
cursorFromSnapshot(snapshot()),
|
||||
snapshot({ issueComments: [issueComment] }),
|
||||
);
|
||||
assert.deepStrictEqual(added.actionableEvents, [
|
||||
{ kind: "new-review-comment", threadId: "comment-1", edited: false },
|
||||
]);
|
||||
const edited = diffPullRequestMonitorSnapshot(
|
||||
added.nextCursor,
|
||||
snapshot({
|
||||
issueComments: [{ ...issueComment, updatedAt: "2026-01-02T00:00:00Z" }],
|
||||
}),
|
||||
);
|
||||
assert.deepStrictEqual(edited.actionableEvents, [
|
||||
{ kind: "new-review-comment", threadId: "comment-1", edited: true },
|
||||
]);
|
||||
});
|
||||
|
||||
it("records a resolved transition without waking", () => {
|
||||
const initial = snapshot({ reviewThreads: [thread()] });
|
||||
const result = diffPullRequestMonitorSnapshot(
|
||||
cursorFromSnapshot(initial),
|
||||
snapshot({ reviewThreads: [thread("2026-01-02T00:00:00Z", true)] }),
|
||||
);
|
||||
assert.deepStrictEqual(result.actionableEvents, []);
|
||||
assert.strictEqual(result.nextCursor.threadVersions["thread-1"]?.resolved, true);
|
||||
});
|
||||
|
||||
it("does not wake for a rerun of an already-seen failure", () => {
|
||||
const initial = snapshot({ checkRuns: [check("run-1", "failure")] });
|
||||
const result = diffPullRequestMonitorSnapshot(
|
||||
cursorFromSnapshot(initial),
|
||||
snapshot({ checkRuns: [check("run-2", "failure")] }),
|
||||
);
|
||||
assert.deepStrictEqual(result.actionableEvents, []);
|
||||
});
|
||||
|
||||
it("wakes for a new failure after a seen success", () => {
|
||||
const initial = snapshot({ checkRuns: [check("run-1", "success")] });
|
||||
const result = diffPullRequestMonitorSnapshot(
|
||||
cursorFromSnapshot(initial),
|
||||
snapshot({ checkRuns: [check("run-2", "failure")] }),
|
||||
);
|
||||
assert.deepStrictEqual(result.actionableEvents, [
|
||||
{ kind: "check-failed", checkRunId: "run-2", checkName: "CI" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
import type {
|
||||
PullRequestMonitorCheckRun,
|
||||
PullRequestMonitorSnapshot,
|
||||
} from "../sourceControl/gitHubPullRequestMonitor.ts";
|
||||
|
||||
export interface PullRequestMonitorCursor {
|
||||
readonly headSha: string;
|
||||
readonly reviewStates: Readonly<Record<string, string>>;
|
||||
readonly threadVersions: Readonly<
|
||||
Record<string, { readonly updatedAt: string; readonly resolved: boolean }>
|
||||
>;
|
||||
readonly issueCommentVersions: Readonly<Record<string, string>>;
|
||||
readonly checkRuns: Readonly<
|
||||
Record<string, { readonly runId: string; readonly outcome: "success" | "failure" | "pending" }>
|
||||
>;
|
||||
readonly behindBase: boolean;
|
||||
}
|
||||
|
||||
export type PullRequestMonitorActionableEvent =
|
||||
| { readonly kind: "new-review-comment"; readonly threadId: string; readonly edited: boolean }
|
||||
| { readonly kind: "changes-requested-review"; readonly reviewId: string }
|
||||
| { readonly kind: "check-failed"; readonly checkRunId: string; readonly checkName: string }
|
||||
| { readonly kind: "behind-base" };
|
||||
|
||||
const checkOutcome = (check: PullRequestMonitorCheckRun): "success" | "failure" | "pending" => {
|
||||
if (check.status !== "completed") return "pending";
|
||||
if (
|
||||
check.conclusion === "success" ||
|
||||
check.conclusion === "neutral" ||
|
||||
check.conclusion === "skipped"
|
||||
) {
|
||||
return "success";
|
||||
}
|
||||
return "failure";
|
||||
};
|
||||
|
||||
export function cursorFromSnapshot(snapshot: PullRequestMonitorSnapshot): PullRequestMonitorCursor {
|
||||
return {
|
||||
headSha: snapshot.headSha,
|
||||
reviewStates: Object.fromEntries(snapshot.reviews.map((review) => [review.id, review.state])),
|
||||
threadVersions: Object.fromEntries(
|
||||
snapshot.reviewThreads.map((thread) => [
|
||||
thread.id,
|
||||
{ updatedAt: thread.updatedAt, resolved: thread.resolved },
|
||||
]),
|
||||
),
|
||||
issueCommentVersions: Object.fromEntries(
|
||||
snapshot.issueComments.map((comment) => [comment.id, comment.updatedAt]),
|
||||
),
|
||||
checkRuns: Object.fromEntries(
|
||||
snapshot.checkRuns
|
||||
.filter((check) => check.headSha === snapshot.headSha)
|
||||
.map((check) => [check.name, { runId: check.id, outcome: checkOutcome(check) }]),
|
||||
),
|
||||
behindBase: (snapshot.behindBaseBy ?? 0) > 0,
|
||||
};
|
||||
}
|
||||
|
||||
export function diffPullRequestMonitorSnapshot(
|
||||
previousCursor: PullRequestMonitorCursor,
|
||||
snapshot: PullRequestMonitorSnapshot,
|
||||
): {
|
||||
readonly actionableEvents: ReadonlyArray<PullRequestMonitorActionableEvent>;
|
||||
readonly nextCursor: PullRequestMonitorCursor;
|
||||
} {
|
||||
const actionableEvents: PullRequestMonitorActionableEvent[] = [];
|
||||
for (const thread of snapshot.reviewThreads) {
|
||||
const previous = previousCursor.threadVersions[thread.id];
|
||||
if (!thread.resolved && (!previous || previous.updatedAt !== thread.updatedAt)) {
|
||||
actionableEvents.push({
|
||||
kind: "new-review-comment",
|
||||
threadId: thread.id,
|
||||
edited: previous !== undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const comment of snapshot.issueComments) {
|
||||
const previousUpdatedAt = previousCursor.issueCommentVersions[comment.id];
|
||||
if (!previousUpdatedAt || previousUpdatedAt !== comment.updatedAt) {
|
||||
actionableEvents.push({
|
||||
kind: "new-review-comment",
|
||||
threadId: comment.id,
|
||||
edited: previousUpdatedAt !== undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const review of snapshot.reviews) {
|
||||
if (
|
||||
review.commitSha === snapshot.headSha &&
|
||||
review.state === "changes-requested" &&
|
||||
previousCursor.reviewStates[review.id] !== "changes-requested"
|
||||
) {
|
||||
actionableEvents.push({ kind: "changes-requested-review", reviewId: review.id });
|
||||
}
|
||||
}
|
||||
for (const check of snapshot.checkRuns.filter((item) => item.headSha === snapshot.headSha)) {
|
||||
const outcome = checkOutcome(check);
|
||||
const previous = previousCursor.checkRuns[check.name];
|
||||
// A rerun preserves the check-name outcome history; only success -> failure wakes again.
|
||||
if (outcome === "failure" && previous?.outcome !== "failure") {
|
||||
actionableEvents.push({
|
||||
kind: "check-failed",
|
||||
checkRunId: check.id,
|
||||
checkName: check.name,
|
||||
});
|
||||
}
|
||||
}
|
||||
if ((snapshot.behindBaseBy ?? 0) > 0 && !previousCursor.behindBase) {
|
||||
actionableEvents.push({ kind: "behind-base" });
|
||||
}
|
||||
return { actionableEvents, nextCursor: cursorFromSnapshot(snapshot) };
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
|
||||
import type { PullRequestMonitorSnapshot } from "../sourceControl/gitHubPullRequestMonitor.ts";
|
||||
import { computeReadiness } from "./readiness.ts";
|
||||
|
||||
const snapshot = (
|
||||
overrides: Partial<PullRequestMonitorSnapshot> = {},
|
||||
): PullRequestMonitorSnapshot => ({
|
||||
state: "open",
|
||||
draft: false,
|
||||
headSha: "head-2",
|
||||
mergeability: "mergeable",
|
||||
behindBaseBy: null,
|
||||
requiredChecksKnown: true,
|
||||
reviews: [],
|
||||
reviewThreads: [],
|
||||
issueComments: [],
|
||||
checkRuns: [
|
||||
{
|
||||
id: "run-1",
|
||||
name: "CI",
|
||||
status: "completed",
|
||||
conclusion: "success",
|
||||
startedAt: null,
|
||||
headSha: "head-2",
|
||||
},
|
||||
],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("pull request monitor readiness", () => {
|
||||
it("keeps blocking on a changes-requested review even after a push", () => {
|
||||
// A stale change request must hold the gate until the bot re-reviews;
|
||||
// otherwise every fix push would flash green before re-review lands.
|
||||
const result = computeReadiness(
|
||||
snapshot({
|
||||
reviews: [
|
||||
{
|
||||
id: "review-1",
|
||||
author: { login: "review-bot", type: "app" },
|
||||
state: "changes-requested",
|
||||
submittedAt: "2026-01-01T00:00:00Z",
|
||||
commitSha: "head-1",
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
assert.strictEqual(result.ready, false);
|
||||
assert.deepStrictEqual(result.blockers, [
|
||||
{ kind: "changes-requested", reviewer: "review-bot" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("ignores stale approvals after a push", () => {
|
||||
const result = computeReadiness(
|
||||
snapshot({
|
||||
reviews: [
|
||||
{
|
||||
id: "review-1",
|
||||
author: { login: "review-bot", type: "app" },
|
||||
state: "approved",
|
||||
submittedAt: "2026-01-01T00:00:00Z",
|
||||
commitSha: "head-1",
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
// A stale approval neither blocks nor counts as fresh green evidence.
|
||||
assert.strictEqual(result.ready, true);
|
||||
});
|
||||
|
||||
it("does not report ready when no check runs exist", () => {
|
||||
const result = computeReadiness(snapshot({ checkRuns: [] }));
|
||||
assert.strictEqual(result.ready, false);
|
||||
assert.strictEqual(result.label, "no-known-blockers");
|
||||
assert.deepStrictEqual(result.blockers, [{ kind: "checks-missing" }]);
|
||||
});
|
||||
|
||||
it("returns terminal blockers for merged and closed snapshots", () => {
|
||||
for (const state of ["merged", "closed"] as const) {
|
||||
const result = computeReadiness(snapshot({ state }));
|
||||
assert.strictEqual(result.ready, false);
|
||||
assert.deepStrictEqual(result.blockers[0], { kind: "terminal", state });
|
||||
}
|
||||
});
|
||||
|
||||
it("uses the honest fallback label when required-check evidence is unavailable", () => {
|
||||
const result = computeReadiness(snapshot({ requiredChecksKnown: false }));
|
||||
assert.strictEqual(result.ready, true);
|
||||
assert.strictEqual(result.label, "no-known-blockers");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { PullRequestMonitorSnapshot } from "../sourceControl/gitHubPullRequestMonitor.ts";
|
||||
|
||||
export type PullRequestMonitorBlocker =
|
||||
| { readonly kind: "terminal"; readonly state: "closed" | "merged" }
|
||||
| { readonly kind: "draft" }
|
||||
| { readonly kind: "mergeability"; readonly state: "conflicting" | "unknown" }
|
||||
| { readonly kind: "checks-missing" }
|
||||
| { readonly kind: "check-pending"; readonly checkName: string }
|
||||
| { readonly kind: "check-failed"; readonly checkName: string }
|
||||
| { readonly kind: "changes-requested"; readonly reviewer: string }
|
||||
| { readonly kind: "unresolved-thread"; readonly threadId: string };
|
||||
|
||||
export interface PullRequestMonitorReadiness {
|
||||
readonly ready: boolean;
|
||||
readonly label: "ready-to-merge" | "no-known-blockers";
|
||||
readonly blockers: ReadonlyArray<PullRequestMonitorBlocker>;
|
||||
}
|
||||
|
||||
export function computeReadiness(
|
||||
snapshot: PullRequestMonitorSnapshot,
|
||||
): PullRequestMonitorReadiness {
|
||||
const blockers: PullRequestMonitorBlocker[] = [];
|
||||
if (snapshot.state !== "open") blockers.push({ kind: "terminal", state: snapshot.state });
|
||||
if (snapshot.draft) blockers.push({ kind: "draft" });
|
||||
if (snapshot.mergeability !== "mergeable") {
|
||||
blockers.push({ kind: "mergeability", state: snapshot.mergeability });
|
||||
}
|
||||
const currentChecks = snapshot.checkRuns.filter((check) => check.headSha === snapshot.headSha);
|
||||
if (currentChecks.length === 0) blockers.push({ kind: "checks-missing" });
|
||||
for (const check of currentChecks) {
|
||||
if (check.status !== "completed") {
|
||||
blockers.push({ kind: "check-pending", checkName: check.name });
|
||||
} else if (
|
||||
check.conclusion !== "success" &&
|
||||
check.conclusion !== "neutral" &&
|
||||
check.conclusion !== "skipped"
|
||||
) {
|
||||
blockers.push({ kind: "check-failed", checkName: check.name });
|
||||
}
|
||||
}
|
||||
for (const review of snapshot.reviews) {
|
||||
// Stale approvals must not count toward green, but a changes-requested
|
||||
// review blocks regardless of which commit it reviewed — GitHub keeps it
|
||||
// active until dismissed or superseded by a re-review.
|
||||
if (review.author.type === "app" && review.state === "changes-requested") {
|
||||
blockers.push({ kind: "changes-requested", reviewer: review.author.login });
|
||||
}
|
||||
}
|
||||
for (const thread of snapshot.reviewThreads) {
|
||||
if (
|
||||
!thread.resolved &&
|
||||
(!snapshot.monitoringStartedAt || thread.createdAt >= snapshot.monitoringStartedAt)
|
||||
) {
|
||||
blockers.push({ kind: "unresolved-thread", threadId: thread.id });
|
||||
}
|
||||
}
|
||||
|
||||
const evidenceSupportsReadyLabel = snapshot.requiredChecksKnown && currentChecks.length > 0;
|
||||
return {
|
||||
ready: blockers.length === 0,
|
||||
label: evidenceSupportsReadyLabel ? "ready-to-merge" : "no-known-blockers",
|
||||
blockers,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { PullRequestMonitorSnapshot } from "../sourceControl/gitHubPullRequestMonitor.ts";
|
||||
import type { PullRequestMonitorActionableEvent } from "./monitorDiff.ts";
|
||||
import type { PullRequestMonitorReadiness } from "./readiness.ts";
|
||||
|
||||
const excerpt = (body: string) => body.replace(/\s+/g, " ").trim().slice(0, 280);
|
||||
|
||||
export function formatBlockersSummary(readiness: PullRequestMonitorReadiness): string {
|
||||
if (readiness.blockers.length === 0)
|
||||
return readiness.label === "ready-to-merge" ? "Ready to merge" : "No known blockers";
|
||||
return readiness.blockers
|
||||
.map((blocker) => {
|
||||
switch (blocker.kind) {
|
||||
case "terminal":
|
||||
return `PR is ${blocker.state}`;
|
||||
case "draft":
|
||||
return "PR is a draft";
|
||||
case "mergeability":
|
||||
return `Mergeability: ${blocker.state}`;
|
||||
case "checks-missing":
|
||||
return "No check results are available";
|
||||
case "check-pending":
|
||||
return `${blocker.checkName}: pending`;
|
||||
case "check-failed":
|
||||
return `${blocker.checkName}: failed`;
|
||||
case "changes-requested":
|
||||
return `${blocker.reviewer}: changes requested`;
|
||||
case "unresolved-thread":
|
||||
return `Review thread ${blocker.threadId}: unresolved`;
|
||||
}
|
||||
})
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
function formatEvent(
|
||||
event: PullRequestMonitorActionableEvent,
|
||||
snapshot: PullRequestMonitorSnapshot,
|
||||
): string {
|
||||
switch (event.kind) {
|
||||
case "new-review-comment": {
|
||||
const thread = snapshot.reviewThreads.find((item) => item.id === event.threadId);
|
||||
const comment = snapshot.issueComments.find((item) => item.id === event.threadId);
|
||||
if (thread) {
|
||||
const location =
|
||||
thread.path === null
|
||||
? ""
|
||||
: `, ${thread.path}${thread.line === null ? "" : `:${thread.line}`}`;
|
||||
return `- Comment from ${thread.author.login}${location}: ${excerpt(thread.body)}`;
|
||||
}
|
||||
return comment
|
||||
? `- Comment from ${comment.author.login}: ${excerpt(comment.body)}`
|
||||
: `- ${event.edited ? "Updated" : "New"} review comment (${event.threadId})`;
|
||||
}
|
||||
case "changes-requested-review": {
|
||||
const review = snapshot.reviews.find((item) => item.id === event.reviewId);
|
||||
return `- ${review?.author.login ?? "Reviewer"} requested changes`;
|
||||
}
|
||||
case "check-failed": {
|
||||
const check = snapshot.checkRuns.find((item) => item.id === event.checkRunId);
|
||||
return `- Check ${event.checkName}: ${check?.conclusion ?? "failure"}`;
|
||||
}
|
||||
case "behind-base":
|
||||
return `- PR is behind main${snapshot.behindBaseBy === null ? "" : ` by ${snapshot.behindBaseBy} commit(s)`}`;
|
||||
}
|
||||
}
|
||||
|
||||
export function buildWakePrompt(input: {
|
||||
readonly prNumber: number;
|
||||
readonly wakeCount: number;
|
||||
readonly events: ReadonlyArray<PullRequestMonitorActionableEvent>;
|
||||
readonly snapshot: PullRequestMonitorSnapshot;
|
||||
readonly readiness: PullRequestMonitorReadiness;
|
||||
}): string {
|
||||
return `New activity on PR #${input.prNumber} (monitoring, wake ${input.wakeCount}/10).
|
||||
|
||||
${input.events.map((event) => formatEvent(event, input.snapshot)).join("\n")}
|
||||
|
||||
Status: ${formatBlockersSummary(input.readiness)}
|
||||
Head: ${input.snapshot.headSha} (approvals/checks are evaluated against this commit)
|
||||
|
||||
Policy:
|
||||
- Verify bot claims against the source before acting.
|
||||
- Fix legitimate findings and push.
|
||||
- Dismiss false positives with a brief reply — never silently ignore or comply.
|
||||
- For CI failures: compare against main; re-run suspected flakes; if the same real failure repeats, ask the user via a question rather than guessing.
|
||||
- Rebase if the PR is behind main.
|
||||
- If the goal has become impossible, say so and ask the user.`;
|
||||
}
|
||||
@@ -611,6 +611,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
monitor: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -713,6 +714,70 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.monitor-started": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) return;
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
monitor: {
|
||||
prNumber: event.payload.prNumber,
|
||||
status: "monitoring",
|
||||
blockersSummary: event.payload.blockersSummary,
|
||||
headSha: event.payload.headSha,
|
||||
wakeCount: 0,
|
||||
startedAt: event.payload.startedAt,
|
||||
endedAt: null,
|
||||
endedReason: null,
|
||||
},
|
||||
updatedAt: event.payload.startedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.monitor-snapshot-updated": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow) || existingRow.value.monitor === null) return;
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
monitor: {
|
||||
...existingRow.value.monitor,
|
||||
blockersSummary: event.payload.blockersSummary,
|
||||
headSha: event.payload.headSha,
|
||||
wakeCount: event.payload.wakeCount,
|
||||
},
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.monitor-ended": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow) || existingRow.value.monitor === null) return;
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
monitor: {
|
||||
...existingRow.value.monitor,
|
||||
status:
|
||||
event.payload.reason === "ready"
|
||||
? "ready"
|
||||
: event.payload.reason === "needs-attention"
|
||||
? "needs-attention"
|
||||
: "stopped",
|
||||
blockersSummary: event.payload.blockersSummary,
|
||||
endedAt: event.payload.endedAt,
|
||||
endedReason: event.payload.reason,
|
||||
},
|
||||
updatedAt: event.payload.endedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.meta-updated": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
|
||||
@@ -312,6 +312,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
monitor: null,
|
||||
deletedAt: null,
|
||||
messages: [
|
||||
{
|
||||
@@ -426,6 +427,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
monitor: null,
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running",
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationThread,
|
||||
OrchestrationThreadDetailSnapshot,
|
||||
OrchestrationThreadMonitor,
|
||||
ProjectScript,
|
||||
TurnId,
|
||||
type OrchestrationCheckpointSummary,
|
||||
@@ -78,6 +79,7 @@ const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;
|
||||
const ProjectionThreadDbRowSchema = ProjectionThread.mapFields(
|
||||
Struct.assign({
|
||||
modelSelection: Schema.fromJsonString(ModelSelection),
|
||||
monitor: Schema.NullOr(Schema.fromJsonString(OrchestrationThreadMonitor)),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
||||
@@ -338,6 +340,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
monitor_json AS "monitor",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -370,6 +373,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
monitor_json AS "monitor",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -404,6 +408,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
monitor_json AS "monitor",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -770,6 +775,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
monitor_json AS "monitor",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -1206,6 +1212,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
monitor: row.monitor,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: messagesByThread.get(row.threadId) ?? [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
@@ -1408,6 +1415,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
monitor: row.monitor,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
@@ -1541,6 +1549,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
monitor: row.monitor,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
@@ -1679,6 +1688,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settledAt: row.settledAt,
|
||||
snoozedUntil: row.snoozedUntil,
|
||||
snoozedAt: row.snoozedAt,
|
||||
monitor: row.monitor,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
@@ -1923,6 +1933,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settledAt: threadRow.value.settledAt,
|
||||
snoozedUntil: threadRow.value.snoozedUntil,
|
||||
snoozedAt: threadRow.value.snoozedAt,
|
||||
monitor: threadRow.value.monitor,
|
||||
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
|
||||
latestUserMessageAt: threadRow.value.latestUserMessageAt,
|
||||
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
|
||||
@@ -2021,6 +2032,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
settledAt: threadRow.value.settledAt,
|
||||
snoozedUntil: threadRow.value.snoozedUntil,
|
||||
snoozedAt: threadRow.value.snoozedAt,
|
||||
monitor: threadRow.value.monitor,
|
||||
deletedAt: null,
|
||||
messages: messageRows.map((row) => {
|
||||
const message = {
|
||||
|
||||
@@ -13,6 +13,9 @@ import {
|
||||
ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,
|
||||
ThreadSnoozedPayload as ContractsThreadSnoozedPayloadSchema,
|
||||
ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,
|
||||
ThreadMonitorStartedPayload as ContractsThreadMonitorStartedPayloadSchema,
|
||||
ThreadMonitorSnapshotUpdatedPayload as ContractsThreadMonitorSnapshotUpdatedPayloadSchema,
|
||||
ThreadMonitorEndedPayload as ContractsThreadMonitorEndedPayloadSchema,
|
||||
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
|
||||
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
|
||||
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
|
||||
@@ -42,6 +45,10 @@ export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
|
||||
export const ThreadUnsettledPayload = ContractsThreadUnsettledPayloadSchema;
|
||||
export const ThreadSnoozedPayload = ContractsThreadSnoozedPayloadSchema;
|
||||
export const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;
|
||||
export const ThreadMonitorStartedPayload = ContractsThreadMonitorStartedPayloadSchema;
|
||||
export const ThreadMonitorSnapshotUpdatedPayload =
|
||||
ContractsThreadMonitorSnapshotUpdatedPayloadSchema;
|
||||
export const ThreadMonitorEndedPayload = ContractsThreadMonitorEndedPayloadSchema;
|
||||
|
||||
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
|
||||
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
import {
|
||||
CommandId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationReadModel,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { decideOrchestrationCommand } from "./decider.ts";
|
||||
|
||||
const NOW = "2026-07-23T12:00:00.000Z";
|
||||
|
||||
const makeReadModel = (monitor: OrchestrationThread["monitor"] = null): OrchestrationReadModel => ({
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [
|
||||
{
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("claude"), model: "claude-opus" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: "feature",
|
||||
worktreePath: "/repo",
|
||||
latestTurn: null,
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
monitor,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
},
|
||||
],
|
||||
updatedAt: NOW,
|
||||
});
|
||||
|
||||
const activeMonitor: NonNullable<OrchestrationThread["monitor"]> = {
|
||||
prNumber: 42,
|
||||
status: "monitoring",
|
||||
blockersSummary: "waiting",
|
||||
headSha: "abc",
|
||||
wakeCount: 0,
|
||||
startedAt: NOW,
|
||||
endedAt: null,
|
||||
endedReason: null,
|
||||
};
|
||||
|
||||
const commandId = (value: string) => CommandId.make(value);
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
|
||||
it.layer(NodeServices.layer)("monitor decider", (it) => {
|
||||
it.effect("starts and idempotently re-emits the same PR", () =>
|
||||
Effect.gen(function* () {
|
||||
const start = {
|
||||
type: "thread.monitor.start" as const,
|
||||
commandId: commandId("start"),
|
||||
threadId,
|
||||
prNumber: 42,
|
||||
blockersSummary: "",
|
||||
headSha: "abc",
|
||||
createdAt: NOW,
|
||||
};
|
||||
const event = yield* decideOrchestrationCommand({
|
||||
command: start,
|
||||
readModel: makeReadModel(),
|
||||
});
|
||||
expect("type" in event ? event.type : event[0]?.type).toBe("thread.monitor-started");
|
||||
const repeated = yield* decideOrchestrationCommand({
|
||||
command: { ...start, commandId: commandId("again"), headSha: "new" },
|
||||
readModel: makeReadModel(activeMonitor),
|
||||
});
|
||||
if ("type" in repeated && repeated.type === "thread.monitor-started") {
|
||||
const payload = repeated.payload as {
|
||||
readonly headSha: string;
|
||||
readonly startedAt: string;
|
||||
};
|
||||
expect(payload.headSha).toBe("abc");
|
||||
expect(payload.startedAt).toBe(NOW);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects a different PR and updates/ends only an active monitor", () =>
|
||||
Effect.gen(function* () {
|
||||
const different = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.monitor.start",
|
||||
commandId: commandId("different"),
|
||||
threadId,
|
||||
prNumber: 43,
|
||||
blockersSummary: "",
|
||||
headSha: "def",
|
||||
createdAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel(activeMonitor),
|
||||
}).pipe(Effect.flip);
|
||||
expect(different._tag).toBe("OrchestrationCommandInvariantError");
|
||||
|
||||
const update = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.monitor.update",
|
||||
commandId: commandId("update"),
|
||||
threadId,
|
||||
blockersSummary: "CI",
|
||||
headSha: "def",
|
||||
wakeCount: 1,
|
||||
updatedAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel(activeMonitor),
|
||||
});
|
||||
expect("type" in update ? update.type : update[0]?.type).toBe(
|
||||
"thread.monitor-snapshot-updated",
|
||||
);
|
||||
const end = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.monitor.end",
|
||||
commandId: commandId("end"),
|
||||
threadId,
|
||||
reason: "ready",
|
||||
blockersSummary: "",
|
||||
endedAt: NOW,
|
||||
},
|
||||
readModel: makeReadModel(activeMonitor),
|
||||
});
|
||||
expect("type" in end ? end.type : end[0]?.type).toBe("thread.monitor-ended");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects update/end without an active monitor and settle ends monitoring", () =>
|
||||
Effect.gen(function* () {
|
||||
for (const command of [
|
||||
{
|
||||
type: "thread.monitor.update" as const,
|
||||
commandId: commandId("bad-update"),
|
||||
threadId,
|
||||
blockersSummary: "",
|
||||
headSha: "abc",
|
||||
wakeCount: 0,
|
||||
updatedAt: NOW,
|
||||
},
|
||||
{
|
||||
type: "thread.monitor.end" as const,
|
||||
commandId: commandId("bad-end"),
|
||||
threadId,
|
||||
reason: "stopped" as const,
|
||||
blockersSummary: "",
|
||||
endedAt: NOW,
|
||||
},
|
||||
]) {
|
||||
const error = yield* decideOrchestrationCommand({
|
||||
command,
|
||||
readModel: makeReadModel(),
|
||||
}).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
}
|
||||
const settled = yield* decideOrchestrationCommand({
|
||||
command: { type: "thread.settle", commandId: commandId("settle"), threadId },
|
||||
readModel: makeReadModel(activeMonitor),
|
||||
});
|
||||
expect(Array.isArray(settled) ? settled.map((event) => event.type) : []).toEqual([
|
||||
"thread.monitor-ended",
|
||||
"thread.settled",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -44,6 +44,7 @@ function makeReadModel(
|
||||
archivedAt,
|
||||
settledOverride,
|
||||
settledAt: settledOverride === "settled" ? SETTLED_AT : null,
|
||||
monitor: null,
|
||||
deletedAt: null,
|
||||
messages,
|
||||
proposedPlans: [],
|
||||
|
||||
@@ -487,7 +487,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
// settledAt: the engine rejects zero-event commands, and bulk-settle /
|
||||
// double-click must stay silent no-ops rather than surface errors.
|
||||
const alreadySettled = thread.settledOverride === "settled" && thread.settledAt !== null;
|
||||
return {
|
||||
const settledEvent: PlannedOrchestrationEvent = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
@@ -504,6 +504,142 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
updatedAt: alreadySettled ? thread.updatedAt : occurredAt,
|
||||
},
|
||||
};
|
||||
if (thread.monitor?.status !== "monitoring") return settledEvent;
|
||||
return [
|
||||
{
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.monitor-ended",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: "stopped",
|
||||
blockersSummary: thread.monitor.blockersSummary,
|
||||
endedAt: occurredAt,
|
||||
},
|
||||
},
|
||||
settledEvent,
|
||||
];
|
||||
}
|
||||
|
||||
case "thread.monitor.start": {
|
||||
const thread = yield* requireThreadNotArchived({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
if (thread.monitor?.status === "monitoring" && thread.monitor.prNumber !== command.prNumber) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} is already monitoring PR #${thread.monitor.prNumber}`,
|
||||
});
|
||||
}
|
||||
const monitorStartedEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.monitor-started",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
prNumber: command.prNumber,
|
||||
blockersSummary:
|
||||
thread.monitor?.status === "monitoring"
|
||||
? thread.monitor.blockersSummary
|
||||
: command.blockersSummary,
|
||||
headSha:
|
||||
thread.monitor?.status === "monitoring" ? thread.monitor.headSha : command.headSha,
|
||||
startedAt:
|
||||
thread.monitor?.status === "monitoring" ? thread.monitor.startedAt : command.createdAt,
|
||||
},
|
||||
};
|
||||
// Monitoring holds the thread unsettled (I2). Like turn.start, starting
|
||||
// a monitor is real activity: it must clear any settled override so the
|
||||
// projection can't carry "settled" and "monitoring" simultaneously.
|
||||
if (thread.settledOverride === null) {
|
||||
return monitorStartedEvent;
|
||||
}
|
||||
return [
|
||||
{
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.unsettled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: "activity",
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
},
|
||||
monitorStartedEvent,
|
||||
];
|
||||
}
|
||||
|
||||
case "thread.monitor.update": {
|
||||
const thread = yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
if (thread.monitor?.status !== "monitoring") {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} has no active monitor`,
|
||||
});
|
||||
}
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.updatedAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.monitor-snapshot-updated",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
blockersSummary: command.blockersSummary,
|
||||
headSha: command.headSha,
|
||||
wakeCount: command.wakeCount,
|
||||
updatedAt: command.updatedAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.monitor.end": {
|
||||
const thread = yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
if (thread.monitor?.status !== "monitoring") {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `thread ${command.threadId} has no active monitor`,
|
||||
});
|
||||
}
|
||||
return {
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.endedAt,
|
||||
commandId: command.commandId,
|
||||
})),
|
||||
type: "thread.monitor-ended",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
reason: command.reason,
|
||||
blockersSummary: command.blockersSummary,
|
||||
endedAt: command.endedAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.unsettle": {
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import {
|
||||
CommandId,
|
||||
EventId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type OrchestrationEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { createEmptyReadModel, projectEvent } from "./projector.ts";
|
||||
|
||||
const NOW = "2026-07-23T12:00:00.000Z";
|
||||
const event = (sequence: number, type: OrchestrationEvent["type"], payload: unknown) =>
|
||||
({
|
||||
sequence,
|
||||
eventId: EventId.make(`event-${sequence}`),
|
||||
type,
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-1"),
|
||||
occurredAt: NOW,
|
||||
commandId: CommandId.make(`command-${sequence}`),
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
payload,
|
||||
}) as OrchestrationEvent;
|
||||
|
||||
it.effect("projects the monitor lifecycle without changing settledOverride", () =>
|
||||
Effect.gen(function* () {
|
||||
let model = yield* projectEvent(
|
||||
createEmptyReadModel(NOW),
|
||||
event(1, "thread.created", {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: { provider: "codex", model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
}),
|
||||
);
|
||||
model = yield* projectEvent(
|
||||
model,
|
||||
event(2, "thread.monitor-started", {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
prNumber: 42,
|
||||
blockersSummary: "draft",
|
||||
headSha: "abc",
|
||||
startedAt: NOW,
|
||||
}),
|
||||
);
|
||||
expect(model.threads[0]?.monitor?.status).toBe("monitoring");
|
||||
expect(model.threads[0]?.settledOverride).toBeNull();
|
||||
model = yield* projectEvent(
|
||||
model,
|
||||
event(3, "thread.monitor-snapshot-updated", {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
blockersSummary: "CI",
|
||||
headSha: "def",
|
||||
wakeCount: 2,
|
||||
updatedAt: NOW,
|
||||
}),
|
||||
);
|
||||
expect(model.threads[0]?.monitor?.wakeCount).toBe(2);
|
||||
model = yield* projectEvent(
|
||||
model,
|
||||
event(4, "thread.monitor-ended", {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "ready",
|
||||
blockersSummary: "",
|
||||
endedAt: NOW,
|
||||
}),
|
||||
);
|
||||
expect(model.threads[0]?.monitor?.status).toBe("ready");
|
||||
expect(model.threads[0]?.monitor?.endedReason).toBe("ready");
|
||||
expect(model.threads[0]?.settledOverride).toBeNull();
|
||||
}),
|
||||
);
|
||||
@@ -93,6 +93,7 @@ describe("orchestration projector", () => {
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
monitor: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
|
||||
@@ -20,6 +20,9 @@ import {
|
||||
ThreadDeletedPayload,
|
||||
ThreadInteractionModeSetPayload,
|
||||
ThreadMetaUpdatedPayload,
|
||||
ThreadMonitorEndedPayload,
|
||||
ThreadMonitorSnapshotUpdatedPayload,
|
||||
ThreadMonitorStartedPayload,
|
||||
ThreadProposedPlanUpsertedPayload,
|
||||
ThreadRuntimeModeSetPayload,
|
||||
ThreadSettledPayload,
|
||||
@@ -294,6 +297,7 @@ export function projectEvent(
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
monitor: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
@@ -393,6 +397,79 @@ export function projectEvent(
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.monitor-started":
|
||||
return decodeForEvent(ThreadMonitorStartedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
monitor: {
|
||||
prNumber: payload.prNumber,
|
||||
status: "monitoring",
|
||||
blockersSummary: payload.blockersSummary,
|
||||
headSha: payload.headSha,
|
||||
wakeCount: 0,
|
||||
startedAt: payload.startedAt,
|
||||
endedAt: null,
|
||||
endedReason: null,
|
||||
},
|
||||
updatedAt: payload.startedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.monitor-snapshot-updated":
|
||||
return decodeForEvent(
|
||||
ThreadMonitorSnapshotUpdatedPayload,
|
||||
event.payload,
|
||||
event.type,
|
||||
"payload",
|
||||
).pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: nextBase.threads.map((thread) =>
|
||||
thread.id === payload.threadId && thread.monitor != null
|
||||
? {
|
||||
...thread,
|
||||
monitor: {
|
||||
...thread.monitor,
|
||||
blockersSummary: payload.blockersSummary,
|
||||
headSha: payload.headSha,
|
||||
wakeCount: payload.wakeCount,
|
||||
},
|
||||
updatedAt: payload.updatedAt,
|
||||
}
|
||||
: thread,
|
||||
),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.monitor-ended":
|
||||
return decodeForEvent(ThreadMonitorEndedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: nextBase.threads.map((thread) =>
|
||||
thread.id === payload.threadId && thread.monitor != null
|
||||
? {
|
||||
...thread,
|
||||
monitor: {
|
||||
...thread.monitor,
|
||||
status:
|
||||
payload.reason === "ready"
|
||||
? "ready"
|
||||
: payload.reason === "needs-attention"
|
||||
? "needs-attention"
|
||||
: "stopped",
|
||||
blockersSummary: payload.blockersSummary,
|
||||
endedAt: payload.endedAt,
|
||||
endedReason: payload.reason,
|
||||
},
|
||||
updatedAt: payload.endedAt,
|
||||
}
|
||||
: thread,
|
||||
),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.meta-updated":
|
||||
return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
|
||||
Effect.map((payload) => ({
|
||||
|
||||
@@ -95,6 +95,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
monitor: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
@@ -157,6 +158,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
settledAt: "2026-03-25T00:00:00.000Z",
|
||||
snoozedUntil: "2026-03-26T09:00:00.000Z",
|
||||
snoozedAt: "2026-03-25T00:00:00.000Z",
|
||||
monitor: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
|
||||
@@ -14,11 +14,12 @@ import {
|
||||
ProjectionThreadRepository,
|
||||
type ProjectionThreadRepositoryShape,
|
||||
} from "../Services/ProjectionThreads.ts";
|
||||
import { ModelSelection } from "@t3tools/contracts";
|
||||
import { ModelSelection, OrchestrationThreadMonitor } from "@t3tools/contracts";
|
||||
|
||||
const ProjectionThreadDbRow = ProjectionThread.mapFields(
|
||||
Struct.assign({
|
||||
modelSelection: Schema.fromJsonString(ModelSelection),
|
||||
monitor: Schema.NullOr(Schema.fromJsonString(OrchestrationThreadMonitor)),
|
||||
}),
|
||||
);
|
||||
type ProjectionThreadDbRow = typeof ProjectionThreadDbRow.Type;
|
||||
@@ -47,6 +48,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
settled_at,
|
||||
snoozed_until,
|
||||
snoozed_at,
|
||||
monitor_json,
|
||||
latest_user_message_at,
|
||||
pending_approval_count,
|
||||
pending_user_input_count,
|
||||
@@ -70,6 +72,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.settledAt},
|
||||
${row.snoozedUntil},
|
||||
${row.snoozedAt},
|
||||
${row.monitor === null ? null : JSON.stringify(row.monitor)},
|
||||
${row.latestUserMessageAt},
|
||||
${row.pendingApprovalCount},
|
||||
${row.pendingUserInputCount},
|
||||
@@ -93,6 +96,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
settled_at = excluded.settled_at,
|
||||
snoozed_until = excluded.snoozed_until,
|
||||
snoozed_at = excluded.snoozed_at,
|
||||
monitor_json = excluded.monitor_json,
|
||||
latest_user_message_at = excluded.latest_user_message_at,
|
||||
pending_approval_count = excluded.pending_approval_count,
|
||||
pending_user_input_count = excluded.pending_user_input_count,
|
||||
@@ -123,6 +127,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
monitor_json AS "monitor",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
@@ -155,6 +160,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
settled_at AS "settledAt",
|
||||
snoozed_until AS "snoozedUntil",
|
||||
snoozed_at AS "snoozedAt",
|
||||
monitor_json AS "monitor",
|
||||
latest_user_message_at AS "latestUserMessageAt",
|
||||
pending_approval_count AS "pendingApprovalCount",
|
||||
pending_user_input_count AS "pendingUserInputCount",
|
||||
|
||||
@@ -47,6 +47,7 @@ import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";
|
||||
import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
|
||||
import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts";
|
||||
import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts";
|
||||
import Migration0035 from "./Migrations/035_ProjectionThreadsMonitor.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -93,6 +94,7 @@ export const migrationEntries = [
|
||||
[32, "AuthPairingProofKeyThumbprint", Migration0032],
|
||||
[33, "ProjectionThreadsSettled", Migration0033],
|
||||
[34, "ProjectionThreadsSnoozed", Migration0034],
|
||||
[35, "ProjectionThreadsMonitor", Migration0035],
|
||||
] as const;
|
||||
|
||||
export const makeMigrationLoader = (throughId?: number) =>
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const columns = yield* sql<{ readonly name: string }>`
|
||||
PRAGMA table_info(projection_threads)
|
||||
`;
|
||||
if (!columns.some((column) => column.name === "monitor_json")) {
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN monitor_json TEXT
|
||||
`;
|
||||
}
|
||||
});
|
||||
@@ -9,6 +9,7 @@
|
||||
import {
|
||||
IsoDateTime,
|
||||
ModelSelection,
|
||||
OrchestrationThreadMonitor,
|
||||
NonNegativeInt,
|
||||
ProjectId,
|
||||
ProviderInteractionMode,
|
||||
@@ -40,6 +41,7 @@ export const ProjectionThread = Schema.Struct({
|
||||
settledAt: Schema.NullOr(IsoDateTime),
|
||||
snoozedUntil: Schema.NullOr(IsoDateTime),
|
||||
snoozedAt: Schema.NullOr(IsoDateTime),
|
||||
monitor: Schema.NullOr(OrchestrationThreadMonitor),
|
||||
latestUserMessageAt: Schema.NullOr(IsoDateTime),
|
||||
pendingApprovalCount: NonNegativeInt,
|
||||
pendingUserInputCount: NonNegativeInt,
|
||||
|
||||
@@ -55,6 +55,7 @@ import * as ProviderEventLoggers from "./ProviderEventLoggers.ts";
|
||||
import * as AnalyticsService from "../../telemetry/AnalyticsService.ts";
|
||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||
import * as McpSessionRegistry from "../../mcp/McpSessionRegistry.ts";
|
||||
import * as MonitorRegistry from "../../monitor/MonitorRegistry.ts";
|
||||
const isModelSelection = Schema.is(ModelSelection);
|
||||
|
||||
/**
|
||||
@@ -215,7 +216,8 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) =>
|
||||
McpSessionRegistry.issueActiveMcpCredential({ threadId, providerInstanceId }).pipe(
|
||||
MonitorRegistry.endActiveMonitorForSession(threadId).pipe(
|
||||
Effect.andThen(McpSessionRegistry.issueActiveMcpCredential({ threadId, providerInstanceId })),
|
||||
Effect.tap((credential) =>
|
||||
credential
|
||||
? Effect.sync(() => McpProviderSession.setMcpProviderSession(credential.config))
|
||||
@@ -223,7 +225,8 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
),
|
||||
);
|
||||
const clearMcpSession = (threadId: ThreadId) =>
|
||||
McpSessionRegistry.revokeActiveMcpThread(threadId).pipe(
|
||||
MonitorRegistry.endActiveMonitorForSession(threadId).pipe(
|
||||
Effect.andThen(McpSessionRegistry.revokeActiveMcpThread(threadId)),
|
||||
Effect.tap(() => Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId))),
|
||||
);
|
||||
|
||||
|
||||
@@ -36,6 +36,8 @@ import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/Provide
|
||||
import * as TerminalManager from "./terminal/Manager.ts";
|
||||
import * as McpHttpServer from "./mcp/McpHttpServer.ts";
|
||||
import * as McpSessionRegistry from "./mcp/McpSessionRegistry.ts";
|
||||
import * as MonitorRegistry from "./monitor/MonitorRegistry.ts";
|
||||
import * as PullRequestMonitor from "./monitor/PullRequestMonitor.ts";
|
||||
import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
import * as PortScanner from "./preview/PortScanner.ts";
|
||||
@@ -158,6 +160,12 @@ const PlatformServicesLive = Layer.unwrap(
|
||||
}),
|
||||
);
|
||||
|
||||
const PullRequestMonitorLayerLive = PullRequestMonitor.layer.pipe(
|
||||
Layer.provide(
|
||||
PullRequestMonitor.PullRequestSnapshotFetcherLive.pipe(Layer.provide(GitHubCli.layer)),
|
||||
),
|
||||
);
|
||||
|
||||
const ReactorLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(OrchestrationReactorLive),
|
||||
Layer.provideMerge(ProviderRuntimeIngestionLive),
|
||||
@@ -165,6 +173,11 @@ const ReactorLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(CheckpointReactorLive),
|
||||
Layer.provideMerge(ThreadDeletionReactorLive),
|
||||
Layer.provideMerge(AgentAwarenessRelay.layer.pipe(Layer.provide(ServerSecretStore.layer))),
|
||||
Layer.provideMerge(
|
||||
Layer.effectDiscard(
|
||||
PullRequestMonitor.PullRequestMonitor.pipe(Effect.flatMap((monitor) => monitor.start())),
|
||||
).pipe(Layer.provide(PullRequestMonitorLayerLive)),
|
||||
),
|
||||
Layer.provideMerge(RuntimeReceiptBusLive),
|
||||
);
|
||||
|
||||
@@ -184,6 +197,10 @@ const ProviderLayerLive = ProviderServiceLive.pipe(
|
||||
);
|
||||
|
||||
const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive));
|
||||
// Leave the registry's OrchestrationEngineService requirement open so it is
|
||||
// satisfied by the ambient runtime (and by mocks in tests) — eagerly providing
|
||||
// OrchestrationLayerLive here would build a second engine + DB connection.
|
||||
const MonitorRegistryLayerLive = MonitorRegistry.layer;
|
||||
|
||||
const VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe(
|
||||
Layer.provide(VcsProjectConfig.layer),
|
||||
@@ -295,7 +312,7 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
|
||||
Layer.provideMerge(VcsLayerLive),
|
||||
Layer.provideMerge(ProviderRuntimeLayerLive),
|
||||
Layer.provideMerge(Layer.mergeAll(TerminalLayerLive, PreviewLayerLive)),
|
||||
Layer.provideMerge(PersistenceLayerLive),
|
||||
Layer.provideMerge(Layer.mergeAll(PersistenceLayerLive, MonitorRegistryLayerLive)),
|
||||
Layer.provideMerge(Keybindings.layer),
|
||||
Layer.provideMerge(ProviderRegistryLive),
|
||||
// The instance registry is the new routing keystone — text generation,
|
||||
@@ -363,7 +380,10 @@ export const makeRoutesLayer = Layer.mergeAll(
|
||||
staticAndDevRouteLayer,
|
||||
websocketRpcRouteLayer,
|
||||
),
|
||||
McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)),
|
||||
McpHttpServer.layer.pipe(
|
||||
Layer.provide(McpSessionRegistry.layer),
|
||||
Layer.provide(MonitorRegistryLayerLive),
|
||||
),
|
||||
).pipe(
|
||||
Layer.provide(PreviewAutomationBroker.layer),
|
||||
Layer.provide(ServerSelfUpdate.layer),
|
||||
|
||||
@@ -0,0 +1,429 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
|
||||
import type * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as GitHubCli from "./GitHubCli.ts";
|
||||
|
||||
export interface PullRequestMonitorActor {
|
||||
readonly login: string;
|
||||
readonly type: "app" | "user";
|
||||
}
|
||||
|
||||
export interface PullRequestMonitorReview {
|
||||
readonly id: string;
|
||||
readonly author: PullRequestMonitorActor;
|
||||
readonly state: "approved" | "changes-requested" | "commented" | "dismissed" | "pending";
|
||||
readonly submittedAt: string | null;
|
||||
readonly commitSha: string | null;
|
||||
}
|
||||
|
||||
export interface PullRequestMonitorReviewThread {
|
||||
readonly id: string;
|
||||
readonly author: PullRequestMonitorActor;
|
||||
readonly body: string;
|
||||
readonly path: string | null;
|
||||
readonly line: number | null;
|
||||
readonly createdAt: string;
|
||||
readonly updatedAt: string;
|
||||
readonly resolved: boolean;
|
||||
}
|
||||
|
||||
export interface PullRequestMonitorIssueComment {
|
||||
readonly id: string;
|
||||
readonly author: PullRequestMonitorActor;
|
||||
readonly body: string;
|
||||
readonly createdAt: string;
|
||||
readonly updatedAt: string;
|
||||
}
|
||||
|
||||
export interface PullRequestMonitorCheckRun {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly status: "queued" | "in-progress" | "completed" | "unknown";
|
||||
readonly conclusion:
|
||||
| "success"
|
||||
| "failure"
|
||||
| "neutral"
|
||||
| "cancelled"
|
||||
| "skipped"
|
||||
| "timed-out"
|
||||
| "action-required"
|
||||
| "stale"
|
||||
| null;
|
||||
readonly startedAt: string | null;
|
||||
readonly headSha: string;
|
||||
}
|
||||
|
||||
export interface PullRequestMonitorSnapshot {
|
||||
readonly state: "open" | "closed" | "merged";
|
||||
readonly draft: boolean;
|
||||
readonly headSha: string;
|
||||
readonly mergeability: "mergeable" | "conflicting" | "unknown";
|
||||
readonly behindBaseBy: number | null;
|
||||
readonly requiredChecksKnown: boolean;
|
||||
readonly monitoringStartedAt?: string;
|
||||
readonly reviews: ReadonlyArray<PullRequestMonitorReview>;
|
||||
readonly reviewThreads: ReadonlyArray<PullRequestMonitorReviewThread>;
|
||||
readonly issueComments: ReadonlyArray<PullRequestMonitorIssueComment>;
|
||||
readonly checkRuns: ReadonlyArray<PullRequestMonitorCheckRun>;
|
||||
}
|
||||
|
||||
const ActorSchema = Schema.Struct({
|
||||
login: Schema.String,
|
||||
__typename: Schema.String,
|
||||
});
|
||||
const ReviewSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
author: Schema.NullOr(ActorSchema),
|
||||
state: Schema.String,
|
||||
submittedAt: Schema.NullOr(Schema.String),
|
||||
commit: Schema.NullOr(Schema.Struct({ oid: Schema.String })),
|
||||
});
|
||||
const ThreadSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
isResolved: Schema.Boolean,
|
||||
comments: Schema.Struct({
|
||||
nodes: Schema.Array(
|
||||
Schema.Struct({
|
||||
author: Schema.NullOr(ActorSchema),
|
||||
body: Schema.String,
|
||||
path: Schema.NullOr(Schema.String),
|
||||
line: Schema.NullOr(Schema.Number),
|
||||
createdAt: Schema.String,
|
||||
updatedAt: Schema.String,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
});
|
||||
const PullRequestPageSchema = Schema.Struct({
|
||||
data: Schema.Struct({
|
||||
repository: Schema.Struct({
|
||||
pullRequest: Schema.NullOr(
|
||||
Schema.Struct({
|
||||
state: Schema.String,
|
||||
isDraft: Schema.Boolean,
|
||||
merged: Schema.Boolean,
|
||||
mergeable: Schema.String,
|
||||
headRefOid: Schema.String,
|
||||
reviews: Schema.Struct({
|
||||
nodes: Schema.Array(ReviewSchema),
|
||||
pageInfo: Schema.Struct({
|
||||
hasNextPage: Schema.Boolean,
|
||||
endCursor: Schema.NullOr(Schema.String),
|
||||
}),
|
||||
}),
|
||||
reviewThreads: Schema.Struct({
|
||||
nodes: Schema.Array(ThreadSchema),
|
||||
pageInfo: Schema.Struct({
|
||||
hasNextPage: Schema.Boolean,
|
||||
endCursor: Schema.NullOr(Schema.String),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
const RepoSchema = Schema.Struct({ nameWithOwner: Schema.String });
|
||||
const IssueCommentsSchema = Schema.Array(
|
||||
Schema.Struct({
|
||||
id: Schema.Number,
|
||||
user: Schema.Struct({ login: Schema.String, type: Schema.String }),
|
||||
body: Schema.String,
|
||||
created_at: Schema.String,
|
||||
updated_at: Schema.String,
|
||||
}),
|
||||
);
|
||||
const CheckRunsSchema = Schema.Struct({
|
||||
total_count: Schema.Number,
|
||||
check_runs: Schema.Array(
|
||||
Schema.Struct({
|
||||
id: Schema.Number,
|
||||
name: Schema.String,
|
||||
status: Schema.String,
|
||||
conclusion: Schema.NullOr(Schema.String),
|
||||
started_at: Schema.NullOr(Schema.String),
|
||||
head_sha: Schema.String,
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
export class GitHubPullRequestMonitorDecodeError extends Schema.TaggedErrorClass<GitHubPullRequestMonitorDecodeError>()(
|
||||
"GitHubPullRequestMonitorDecodeError",
|
||||
{
|
||||
command: Schema.Literal("gh"),
|
||||
cwd: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {}
|
||||
|
||||
export type GitHubPullRequestMonitorError =
|
||||
| GitHubCli.GitHubCliError
|
||||
| GitHubPullRequestMonitorDecodeError;
|
||||
|
||||
const decode = <S extends Schema.Codec<unknown, unknown, never, never>>(
|
||||
schema: S,
|
||||
raw: string,
|
||||
cwd: string,
|
||||
detail: string,
|
||||
) =>
|
||||
Effect.sync(() => decodeJsonResult(schema)(raw)).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
Result.isSuccess(result)
|
||||
? Effect.succeed(result.success)
|
||||
: Effect.fail(
|
||||
new GitHubPullRequestMonitorDecodeError({
|
||||
command: "gh",
|
||||
cwd,
|
||||
detail,
|
||||
cause: result.failure,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const actor = (value: Schema.Schema.Type<typeof ActorSchema> | null): PullRequestMonitorActor => ({
|
||||
login: value?.login ?? "ghost",
|
||||
type: value?.__typename === "Bot" ? "app" : "user",
|
||||
});
|
||||
|
||||
const normalizeReviewState = (state: string): PullRequestMonitorReview["state"] => {
|
||||
switch (state.toUpperCase()) {
|
||||
case "APPROVED":
|
||||
return "approved";
|
||||
case "CHANGES_REQUESTED":
|
||||
return "changes-requested";
|
||||
case "DISMISSED":
|
||||
return "dismissed";
|
||||
case "PENDING":
|
||||
return "pending";
|
||||
default:
|
||||
return "commented";
|
||||
}
|
||||
};
|
||||
|
||||
const normalizeCheckStatus = (status: string): PullRequestMonitorCheckRun["status"] => {
|
||||
if (status === "queued" || status === "completed") return status;
|
||||
if (status === "in_progress") return "in-progress";
|
||||
return "unknown";
|
||||
};
|
||||
|
||||
const conclusions = new Set<NonNullable<PullRequestMonitorCheckRun["conclusion"]>>([
|
||||
"success",
|
||||
"failure",
|
||||
"neutral",
|
||||
"cancelled",
|
||||
"skipped",
|
||||
"timed-out",
|
||||
"action-required",
|
||||
"stale",
|
||||
]);
|
||||
|
||||
export const getPullRequestMonitorSnapshot = Effect.fn("getPullRequestMonitorSnapshot")(
|
||||
function* (input: {
|
||||
readonly cwd: string;
|
||||
readonly pullRequestNumber: number;
|
||||
}): Effect.fn.Return<
|
||||
PullRequestMonitorSnapshot,
|
||||
GitHubPullRequestMonitorError,
|
||||
GitHubCli.GitHubCli
|
||||
> {
|
||||
const github = yield* GitHubCli.GitHubCli;
|
||||
const repoResult = yield* github.execute({
|
||||
cwd: input.cwd,
|
||||
args: ["repo", "view", "--json", "nameWithOwner"],
|
||||
});
|
||||
const repo = yield* decode(
|
||||
RepoSchema,
|
||||
repoResult.stdout,
|
||||
input.cwd,
|
||||
"GitHub CLI returned invalid repository JSON.",
|
||||
);
|
||||
const [owner, name] = repo.nameWithOwner.split("/");
|
||||
if (!owner || !name) {
|
||||
return yield* new GitHubPullRequestMonitorDecodeError({
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
detail: "GitHub repository nameWithOwner was invalid.",
|
||||
cause: repo.nameWithOwner,
|
||||
});
|
||||
}
|
||||
|
||||
const reviews = new Map<string, PullRequestMonitorReview>();
|
||||
const reviewThreads = new Map<string, PullRequestMonitorReviewThread>();
|
||||
let reviewCursor: string | null = null;
|
||||
let threadCursor: string | null = null;
|
||||
let reviewsComplete = false;
|
||||
let threadsComplete = false;
|
||||
let metadata:
|
||||
| Pick<PullRequestMonitorSnapshot, "state" | "draft" | "headSha" | "mergeability">
|
||||
| undefined;
|
||||
do {
|
||||
const query = `query($owner:String!,$name:String!,$number:Int!,$reviews:String,$threads:String){repository(owner:$owner,name:$name){pullRequest(number:$number){state isDraft merged mergeable headRefOid reviews(first:100,after:$reviews){nodes{id author{login __typename} state submittedAt commit{oid}} pageInfo{hasNextPage endCursor}} reviewThreads(first:100,after:$threads){nodes{id isResolved comments(last:1){nodes{author{login __typename} body path line createdAt updatedAt}}} pageInfo{hasNextPage endCursor}}}}}`;
|
||||
const result: VcsProcess.VcsProcessOutput = yield* github.execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"api",
|
||||
"graphql",
|
||||
"-f",
|
||||
`query=${query}`,
|
||||
"-F",
|
||||
`owner=${owner}`,
|
||||
"-F",
|
||||
`name=${name}`,
|
||||
"-F",
|
||||
`number=${input.pullRequestNumber}`,
|
||||
...(reviewCursor ? ["-f", `reviews=${reviewCursor}`] : []),
|
||||
...(threadCursor ? ["-f", `threads=${threadCursor}`] : []),
|
||||
],
|
||||
});
|
||||
const page: Schema.Schema.Type<typeof PullRequestPageSchema> = yield* decode(
|
||||
PullRequestPageSchema,
|
||||
result.stdout,
|
||||
input.cwd,
|
||||
"GitHub GraphQL returned invalid pull request monitor JSON.",
|
||||
);
|
||||
const pr: NonNullable<
|
||||
Schema.Schema.Type<typeof PullRequestPageSchema>["data"]["repository"]["pullRequest"]
|
||||
> | null = page.data.repository.pullRequest;
|
||||
if (!pr) {
|
||||
return yield* new GitHubPullRequestMonitorDecodeError({
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
detail: "GitHub pull request was not found.",
|
||||
cause: input.pullRequestNumber,
|
||||
});
|
||||
}
|
||||
metadata ??= {
|
||||
state: pr.merged ? "merged" : pr.state === "CLOSED" ? "closed" : "open",
|
||||
draft: pr.isDraft,
|
||||
headSha: pr.headRefOid,
|
||||
mergeability:
|
||||
pr.mergeable === "MERGEABLE"
|
||||
? "mergeable"
|
||||
: pr.mergeable === "CONFLICTING"
|
||||
? "conflicting"
|
||||
: "unknown",
|
||||
};
|
||||
if (!reviewsComplete) {
|
||||
for (const review of pr.reviews.nodes) {
|
||||
reviews.set(review.id, {
|
||||
id: review.id,
|
||||
author: actor(review.author),
|
||||
state: normalizeReviewState(review.state),
|
||||
submittedAt: review.submittedAt,
|
||||
commitSha: review.commit?.oid ?? null,
|
||||
});
|
||||
}
|
||||
reviewsComplete = !pr.reviews.pageInfo.hasNextPage;
|
||||
reviewCursor = pr.reviews.pageInfo.endCursor;
|
||||
}
|
||||
if (!threadsComplete) {
|
||||
for (const thread of pr.reviewThreads.nodes) {
|
||||
const comment = thread.comments.nodes[0];
|
||||
if (comment) {
|
||||
reviewThreads.set(thread.id, {
|
||||
id: thread.id,
|
||||
author: actor(comment.author),
|
||||
body: comment.body,
|
||||
path: comment.path,
|
||||
line: comment.line,
|
||||
createdAt: comment.createdAt,
|
||||
updatedAt: comment.updatedAt,
|
||||
resolved: thread.isResolved,
|
||||
});
|
||||
}
|
||||
}
|
||||
threadsComplete = !pr.reviewThreads.pageInfo.hasNextPage;
|
||||
threadCursor = pr.reviewThreads.pageInfo.endCursor;
|
||||
}
|
||||
} while (!reviewsComplete || !threadsComplete);
|
||||
|
||||
const issueComments: PullRequestMonitorIssueComment[] = [];
|
||||
for (let page = 1; ; page++) {
|
||||
const result = yield* github.execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"api",
|
||||
"--method",
|
||||
"GET",
|
||||
`repos/${owner}/${name}/issues/${input.pullRequestNumber}/comments`,
|
||||
"-f",
|
||||
"per_page=100",
|
||||
"-f",
|
||||
`page=${page}`,
|
||||
],
|
||||
});
|
||||
const entries = yield* decode(
|
||||
IssueCommentsSchema,
|
||||
result.stdout,
|
||||
input.cwd,
|
||||
"GitHub API returned invalid issue comment JSON.",
|
||||
);
|
||||
issueComments.push(
|
||||
...entries
|
||||
.filter((comment) => comment.user.type === "Bot")
|
||||
.map((comment) => ({
|
||||
id: String(comment.id),
|
||||
author: { login: comment.user.login, type: "app" as const },
|
||||
body: comment.body,
|
||||
createdAt: comment.created_at,
|
||||
updatedAt: comment.updated_at,
|
||||
})),
|
||||
);
|
||||
if (entries.length < 100) break;
|
||||
}
|
||||
|
||||
const checkRuns: PullRequestMonitorCheckRun[] = [];
|
||||
for (let page = 1; ; page++) {
|
||||
const result = yield* github.execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"api",
|
||||
"--method",
|
||||
"GET",
|
||||
`repos/${owner}/${name}/commits/${metadata.headSha}/check-runs`,
|
||||
"-H",
|
||||
"Accept: application/vnd.github+json",
|
||||
"-f",
|
||||
"per_page=100",
|
||||
"-f",
|
||||
`page=${page}`,
|
||||
],
|
||||
});
|
||||
const response = yield* decode(
|
||||
CheckRunsSchema,
|
||||
result.stdout,
|
||||
input.cwd,
|
||||
"GitHub API returned invalid check run JSON.",
|
||||
);
|
||||
checkRuns.push(
|
||||
...response.check_runs.map((check) => ({
|
||||
id: String(check.id),
|
||||
name: check.name,
|
||||
status: normalizeCheckStatus(check.status),
|
||||
conclusion:
|
||||
check.conclusion && conclusions.has(check.conclusion as never)
|
||||
? (check.conclusion as PullRequestMonitorCheckRun["conclusion"])
|
||||
: null,
|
||||
startedAt: check.started_at,
|
||||
headSha: check.head_sha,
|
||||
})),
|
||||
);
|
||||
if (response.check_runs.length < 100) break;
|
||||
}
|
||||
|
||||
return {
|
||||
...metadata,
|
||||
behindBaseBy: null,
|
||||
requiredChecksKnown: false,
|
||||
reviews: [...reviews.values()],
|
||||
reviewThreads: [...reviewThreads.values()],
|
||||
issueComments,
|
||||
checkRuns,
|
||||
};
|
||||
},
|
||||
);
|
||||
Reference in new issue
Block a user