fix(server): preserve PR lookup backoff
This commit is contained in:
17 files changed
+582
-314
No files matched your search
@@ -316,6 +316,8 @@ describe("CheckpointReactor", () => {
|
||||
});
|
||||
const vcsStatusBroadcasterLayer = Layer.succeed(VcsStatusBroadcaster, {
|
||||
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
||||
peekStatus: () => Effect.die("peekStatus should not be called in this test"),
|
||||
pollStatus: () => Effect.die("pollStatus should not be called in this test"),
|
||||
refreshLocalStatus: (cwd: string) =>
|
||||
Effect.sync(() => {
|
||||
options?.gitStatusRefreshCalls?.push(cwd);
|
||||
|
||||
@@ -400,6 +400,8 @@ describe("ProviderCommandReactor", () => {
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(VcsStatusBroadcaster, {
|
||||
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
||||
peekStatus: () => Effect.die("peekStatus should not be called in this test"),
|
||||
pollStatus: () => Effect.die("pollStatus should not be called in this test"),
|
||||
refreshLocalStatus: () =>
|
||||
Effect.die("refreshLocalStatus should not be called in this test"),
|
||||
refreshStatus,
|
||||
|
||||
@@ -1,26 +1,25 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
GitManagerError,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
SourceControlProviderError,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type ChangeRequest,
|
||||
type OrchestrationCommand,
|
||||
type OrchestrationProjectShell,
|
||||
type OrchestrationShellSnapshot,
|
||||
type OrchestrationThreadShell,
|
||||
type VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
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 BackgroundPolicy from "../background/BackgroundPolicy.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import * as SourceControlProvider from "../sourceControl/SourceControlProvider.ts";
|
||||
import { SourceControlProviderRegistry } from "../sourceControl/SourceControlProviderRegistry.ts";
|
||||
import { VcsStatusBroadcaster } from "../vcs/VcsStatusBroadcaster.ts";
|
||||
import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
@@ -44,7 +43,8 @@ const project: OrchestrationProjectShell = {
|
||||
|
||||
function makeThread(input: {
|
||||
readonly id: string;
|
||||
readonly branch: string;
|
||||
readonly branch?: string | null;
|
||||
readonly cwd?: string;
|
||||
readonly pinned?: boolean;
|
||||
}): OrchestrationThreadShell {
|
||||
const threadId = ThreadId.make(input.id);
|
||||
@@ -55,8 +55,8 @@ function makeThread(input: {
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: input.branch,
|
||||
worktreePath: null,
|
||||
branch: input.branch ?? null,
|
||||
worktreePath: input.cwd ?? null,
|
||||
latestTurn: {
|
||||
turnId: TurnId.make(`turn-${input.id}`),
|
||||
state: "completed",
|
||||
@@ -80,144 +80,228 @@ function makeThread(input: {
|
||||
};
|
||||
}
|
||||
|
||||
function changeRequest(headRefName: string, state: ChangeRequest["state"]): ChangeRequest {
|
||||
function vcsStatus(
|
||||
branch: string,
|
||||
state: "open" | "closed" | "merged" | null,
|
||||
headRef = branch,
|
||||
): VcsStatusResult {
|
||||
return {
|
||||
provider: "github",
|
||||
number: 1,
|
||||
title: headRefName,
|
||||
url: `https://example.test/${headRefName}`,
|
||||
baseRefName: "main",
|
||||
headRefName,
|
||||
state,
|
||||
updatedAt: Option.none(),
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: true,
|
||||
isDefaultRef: false,
|
||||
refName: branch,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr:
|
||||
state === null
|
||||
? null
|
||||
: {
|
||||
number: 1,
|
||||
title: branch,
|
||||
url: `https://example.test/${branch}`,
|
||||
baseRef: "main",
|
||||
headRef,
|
||||
state,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
it.effect(
|
||||
"persists inactivity and merged-PR settlement while leaving pinned closed PRs alone",
|
||||
() =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const inactivity = makeThread({ id: "inactivity", branch: "feature/inactivity" });
|
||||
const pinnedClosed = makeThread({
|
||||
id: "pinned-closed",
|
||||
branch: "feature/closed",
|
||||
pinned: true,
|
||||
});
|
||||
const pinnedMerged = makeThread({
|
||||
id: "pinned-merged",
|
||||
branch: "feature/merged",
|
||||
pinned: true,
|
||||
});
|
||||
const pinnedMixed = makeThread({
|
||||
id: "pinned-mixed",
|
||||
branch: "feature/mixed",
|
||||
pinned: true,
|
||||
});
|
||||
const snapshot = {
|
||||
snapshotSequence: 1,
|
||||
projects: [project],
|
||||
threads: [inactivity, pinnedClosed, pinnedMerged, pinnedMixed],
|
||||
updatedAt: "2020-01-02T00:00:00.000Z",
|
||||
} satisfies OrchestrationShellSnapshot;
|
||||
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
|
||||
|
||||
const provider = {
|
||||
listChangeRequests: (
|
||||
input: Parameters<
|
||||
SourceControlProvider.SourceControlProvider["Service"]["listChangeRequests"]
|
||||
>[0],
|
||||
) =>
|
||||
Effect.succeed(
|
||||
input.headSelector === pinnedClosed.branch
|
||||
? [changeRequest(input.headSelector, "closed")]
|
||||
: input.headSelector === pinnedMerged.branch
|
||||
? [changeRequest(input.headSelector, "merged")]
|
||||
: input.headSelector === pinnedMixed.branch
|
||||
? [
|
||||
changeRequest(input.headSelector, "closed"),
|
||||
changeRequest(input.headSelector, "merged"),
|
||||
]
|
||||
: [],
|
||||
),
|
||||
} as unknown as SourceControlProvider.SourceControlProvider["Service"];
|
||||
|
||||
const dependencies = Layer.mergeAll(
|
||||
Layer.succeed(OrchestrationEngineService, {
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatched, (commands) => [...commands, command]).pipe(
|
||||
Effect.as({ sequence: 1 }),
|
||||
),
|
||||
streamDomainEvents: Stream.empty,
|
||||
latestSequence: Effect.succeed(0),
|
||||
} satisfies OrchestrationEngineShape),
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getShellSnapshot: () => Effect.succeed(snapshot),
|
||||
} as unknown as ProjectionSnapshotQueryShape),
|
||||
ServerSettingsService.layerTest(),
|
||||
Layer.mock(SourceControlProviderRegistry)({
|
||||
resolve: () => Effect.succeed(provider),
|
||||
}),
|
||||
NodeServices.layer,
|
||||
);
|
||||
|
||||
const reactor = yield* make.pipe(Effect.provide(dependencies));
|
||||
yield* reactor.start();
|
||||
yield* reactor.drain;
|
||||
|
||||
const settledThreadIds = (yield* Ref.get(dispatched))
|
||||
.filter((command) => command.type === "thread.settle")
|
||||
.map((command) => command.threadId)
|
||||
.sort();
|
||||
expect(settledThreadIds).toEqual([inactivity.id, pinnedMerged.id, pinnedMixed.id].sort());
|
||||
function makeHarness(input: {
|
||||
readonly threads: ReadonlyArray<OrchestrationThreadShell>;
|
||||
readonly peekStatus?: VcsStatusBroadcaster["Service"]["peekStatus"];
|
||||
readonly pollStatus?: VcsStatusBroadcaster["Service"]["pollStatus"];
|
||||
readonly opportunisticWork?: boolean;
|
||||
readonly autoSettleOnMerge?: boolean;
|
||||
}) {
|
||||
return Effect.gen(function* () {
|
||||
const snapshot = {
|
||||
snapshotSequence: 1,
|
||||
projects: [project],
|
||||
threads: input.threads,
|
||||
updatedAt: "2020-01-02T00:00:00.000Z",
|
||||
} satisfies OrchestrationShellSnapshot;
|
||||
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
|
||||
const dependencies = Layer.mergeAll(
|
||||
Layer.succeed(OrchestrationEngineService, {
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatched, (commands) => [...commands, command]).pipe(
|
||||
Effect.as({ sequence: 1 }),
|
||||
),
|
||||
streamDomainEvents: Stream.empty,
|
||||
latestSequence: Effect.succeed(0),
|
||||
} satisfies OrchestrationEngineShape),
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getShellSnapshot: () => Effect.succeed(snapshot),
|
||||
} as unknown as ProjectionSnapshotQueryShape),
|
||||
ServerSettingsService.layerTest({
|
||||
threadAutoSettleOnMerge: input.autoSettleOnMerge ?? true,
|
||||
}),
|
||||
),
|
||||
);
|
||||
Layer.succeed(VcsStatusBroadcaster, {
|
||||
getStatus: () => Effect.die("getStatus should not be called"),
|
||||
peekStatus: input.peekStatus ?? (() => Effect.succeed(null)),
|
||||
pollStatus: input.pollStatus ?? (() => Effect.die("pollStatus should not be called")),
|
||||
refreshLocalStatus: () => Effect.die("refreshLocalStatus should not be called"),
|
||||
refreshStatus: () => Effect.die("refreshStatus should not be called"),
|
||||
streamStatus: () => Stream.empty,
|
||||
}),
|
||||
Layer.mock(BackgroundPolicy.BackgroundPolicy)({
|
||||
shouldRunOpportunisticWork: Effect.succeed(input.opportunisticWork ?? false),
|
||||
}),
|
||||
NodeServices.layer,
|
||||
);
|
||||
const reactor = yield* make.pipe(Effect.provide(dependencies));
|
||||
return { reactor, dispatched };
|
||||
});
|
||||
}
|
||||
|
||||
it.effect("does not settle a stale thread when its PR state lookup fails", () =>
|
||||
it.effect("persists inactivity and merged-PR settlement while leaving other pins alone", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const thread = makeThread({ id: "lookup-failed", branch: "feature/open-pr" });
|
||||
const snapshot = {
|
||||
snapshotSequence: 1,
|
||||
projects: [project],
|
||||
threads: [thread],
|
||||
updatedAt: "2020-01-02T00:00:00.000Z",
|
||||
} satisfies OrchestrationShellSnapshot;
|
||||
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
|
||||
const provider = {
|
||||
listChangeRequests: () =>
|
||||
Effect.fail(
|
||||
new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation: "listChangeRequests",
|
||||
cwd: project.workspaceRoot,
|
||||
detail: "temporary lookup failure",
|
||||
}),
|
||||
),
|
||||
} as unknown as SourceControlProvider.SourceControlProvider["Service"];
|
||||
const dependencies = Layer.mergeAll(
|
||||
Layer.succeed(OrchestrationEngineService, {
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatched, (commands) => [...commands, command]).pipe(
|
||||
Effect.as({ sequence: 1 }),
|
||||
),
|
||||
streamDomainEvents: Stream.empty,
|
||||
latestSequence: Effect.succeed(0),
|
||||
} satisfies OrchestrationEngineShape),
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getShellSnapshot: () => Effect.succeed(snapshot),
|
||||
} as unknown as ProjectionSnapshotQueryShape),
|
||||
ServerSettingsService.layerTest(),
|
||||
Layer.mock(SourceControlProviderRegistry)({
|
||||
resolve: () => Effect.succeed(provider),
|
||||
}),
|
||||
NodeServices.layer,
|
||||
);
|
||||
const inactivity = makeThread({ id: "inactivity" });
|
||||
const pinnedClosed = makeThread({
|
||||
id: "pinned-closed",
|
||||
branch: "feature/closed",
|
||||
cwd: "/repo/closed",
|
||||
pinned: true,
|
||||
});
|
||||
const pinnedOpen = makeThread({
|
||||
id: "pinned-open",
|
||||
branch: "feature/open",
|
||||
cwd: "/repo/open",
|
||||
pinned: true,
|
||||
});
|
||||
const pinnedMerged = makeThread({
|
||||
id: "pinned-merged",
|
||||
branch: "feature/merged",
|
||||
cwd: "/repo/merged",
|
||||
pinned: true,
|
||||
});
|
||||
const byCwd = new Map([
|
||||
[pinnedClosed.worktreePath, vcsStatus(pinnedClosed.branch!, "closed")],
|
||||
[pinnedOpen.worktreePath, vcsStatus(pinnedOpen.branch!, "open")],
|
||||
[pinnedMerged.worktreePath, vcsStatus(pinnedMerged.branch!, "merged")],
|
||||
]);
|
||||
const { reactor, dispatched } = yield* makeHarness({
|
||||
threads: [inactivity, pinnedClosed, pinnedOpen, pinnedMerged],
|
||||
peekStatus: ({ cwd }) => Effect.succeed(byCwd.get(cwd) ?? null),
|
||||
pollStatus: (cwd) => Effect.succeed(byCwd.get(cwd)!),
|
||||
opportunisticWork: true,
|
||||
});
|
||||
|
||||
yield* reactor.start();
|
||||
yield* reactor.drain;
|
||||
|
||||
const settledThreadIds = (yield* Ref.get(dispatched))
|
||||
.filter((command) => command.type === "thread.settle")
|
||||
.map((command) => command.threadId)
|
||||
.sort();
|
||||
expect(settledThreadIds).toEqual([inactivity.id, pinnedMerged.id].sort());
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("re-verifies cached PR state and settles a pin only after merge", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const thread = makeThread({
|
||||
id: "pinned-merged-after-cache",
|
||||
branch: "feature/merge-later",
|
||||
cwd: "/repo/merge-later",
|
||||
pinned: true,
|
||||
});
|
||||
const pollCalls = yield* Ref.make(0);
|
||||
const { reactor, dispatched } = yield* makeHarness({
|
||||
threads: [thread],
|
||||
peekStatus: () => Effect.succeed(vcsStatus(thread.branch!, "open")),
|
||||
pollStatus: () =>
|
||||
Ref.update(pollCalls, (count) => count + 1).pipe(
|
||||
Effect.as(vcsStatus(thread.branch!, "merged")),
|
||||
),
|
||||
opportunisticWork: true,
|
||||
});
|
||||
|
||||
yield* reactor.start();
|
||||
yield* reactor.drain;
|
||||
|
||||
expect(yield* Ref.get(pollCalls)).toBe(1);
|
||||
expect(
|
||||
(yield* Ref.get(dispatched)).map((command) =>
|
||||
command.type === "thread.settle" ? command.threadId : null,
|
||||
),
|
||||
).toEqual([thread.id]);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("keeps merged pinned threads active when merge settlement is disabled", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const thread = makeThread({
|
||||
id: "pinned-merged-disabled",
|
||||
branch: "feature/merged-disabled",
|
||||
cwd: "/repo/merged-disabled",
|
||||
pinned: true,
|
||||
});
|
||||
const pollCalls = yield* Ref.make(0);
|
||||
const { reactor, dispatched } = yield* makeHarness({
|
||||
threads: [thread],
|
||||
peekStatus: () => Effect.succeed(vcsStatus(thread.branch!, "open")),
|
||||
pollStatus: () =>
|
||||
Ref.update(pollCalls, (count) => count + 1).pipe(
|
||||
Effect.as(vcsStatus(thread.branch!, "merged")),
|
||||
),
|
||||
opportunisticWork: true,
|
||||
autoSettleOnMerge: false,
|
||||
});
|
||||
|
||||
yield* reactor.start();
|
||||
yield* reactor.drain;
|
||||
|
||||
expect(yield* Ref.get(pollCalls)).toBe(0);
|
||||
expect(yield* Ref.get(dispatched)).toEqual([]);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not settle when PR verification fails or belongs to another branch", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const lookupFailed = makeThread({
|
||||
id: "lookup-failed",
|
||||
branch: "feature/open-pr",
|
||||
cwd: "/repo/lookup-failed",
|
||||
});
|
||||
const mismatchedMerge = makeThread({
|
||||
id: "mismatched-merge",
|
||||
branch: "feature/current",
|
||||
cwd: "/repo/mismatched",
|
||||
pinned: true,
|
||||
});
|
||||
const { reactor, dispatched } = yield* makeHarness({
|
||||
threads: [lookupFailed, mismatchedMerge],
|
||||
peekStatus: ({ cwd }) =>
|
||||
Effect.succeed(
|
||||
cwd === mismatchedMerge.worktreePath
|
||||
? vcsStatus(mismatchedMerge.branch!, "merged", "feature/other")
|
||||
: null,
|
||||
),
|
||||
pollStatus: (cwd) =>
|
||||
cwd === lookupFailed.worktreePath
|
||||
? Effect.fail(
|
||||
new GitManagerError({
|
||||
operation: "ThreadSettlementReactor.test",
|
||||
cwd,
|
||||
detail: "temporary lookup failure",
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(vcsStatus(mismatchedMerge.branch!, "merged", "feature/other")),
|
||||
opportunisticWork: true,
|
||||
});
|
||||
|
||||
const reactor = yield* make.pipe(Effect.provide(dependencies));
|
||||
yield* reactor.start();
|
||||
yield* reactor.drain;
|
||||
|
||||
@@ -225,3 +309,37 @@ it.effect("does not settle a stale thread when its PR state lookup fails", () =>
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("bounds live verification and lets cooldown-skipped entries yield the next batch", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const threads = Array.from({ length: 7 }, (_, index) =>
|
||||
makeThread({
|
||||
id: `pinned-${index}`,
|
||||
branch: `feature/${index}`,
|
||||
cwd: `/repo/${index}`,
|
||||
pinned: true,
|
||||
}),
|
||||
);
|
||||
const branchByCwd = new Map(threads.map((thread) => [thread.worktreePath, thread.branch!]));
|
||||
const polledCwds = yield* Ref.make<ReadonlyArray<string>>([]);
|
||||
const { reactor, dispatched } = yield* makeHarness({
|
||||
threads,
|
||||
pollStatus: (cwd) =>
|
||||
Ref.update(polledCwds, (values) => [...values, cwd]).pipe(
|
||||
Effect.as(vcsStatus(branchByCwd.get(cwd)!, "open")),
|
||||
),
|
||||
opportunisticWork: true,
|
||||
});
|
||||
|
||||
yield* reactor.start();
|
||||
yield* reactor.drain;
|
||||
expect(yield* Ref.get(polledCwds)).toHaveLength(5);
|
||||
|
||||
yield* reactor.start();
|
||||
yield* reactor.drain;
|
||||
expect(new Set(yield* Ref.get(polledCwds))).toEqual(new Set(branchByCwd.keys()));
|
||||
expect(yield* Ref.get(dispatched)).toEqual([]);
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -1,37 +1,37 @@
|
||||
import {
|
||||
CommandId,
|
||||
type ChangeRequestState,
|
||||
type OrchestrationProjectShell,
|
||||
type OrchestrationThreadShell,
|
||||
type VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
import * as Cache from "effect/Cache";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Clock from "effect/Clock";
|
||||
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 Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
|
||||
import { resolveThreadWorkspaceCwd } from "../checkpointing/Utils.ts";
|
||||
import { forkParked } from "../serverActivation.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import { normalizeSourceBranch } from "../sourceControl/SourceControlProvider.ts";
|
||||
import { SourceControlProviderRegistry } from "../sourceControl/SourceControlProviderRegistry.ts";
|
||||
import { VcsStatusBroadcaster } from "../vcs/VcsStatusBroadcaster.ts";
|
||||
import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
|
||||
import { resolveAutomaticSettlementReason } from "./threadSettlement.ts";
|
||||
import {
|
||||
type AutomaticSettlementChangeRequestState,
|
||||
resolveAutomaticSettlementVerdict,
|
||||
} from "./threadSettlement.ts";
|
||||
|
||||
const RECONCILE_INTERVAL = Duration.minutes(1);
|
||||
const CHANGE_REQUEST_LOOKUP_TTL = Duration.minutes(2);
|
||||
const CHANGE_REQUEST_LOOKUP_FAILURE_TTL = Duration.seconds(20);
|
||||
const MAX_BRANCH_LOOKUPS_PER_RECONCILE = 20;
|
||||
const CHANGE_REQUEST_LOOKUP_FAILED = Symbol("CHANGE_REQUEST_LOOKUP_FAILED");
|
||||
const PR_VERIFY_COOLDOWN_MS = Duration.toMillis(Duration.minutes(30));
|
||||
const MAX_PR_VERIFICATIONS_PER_RECONCILE = 5;
|
||||
|
||||
export class ThreadSettlementReactor extends Context.Service<
|
||||
ThreadSettlementReactor,
|
||||
@@ -51,8 +51,25 @@ function workspaceCwd(
|
||||
return resolveThreadWorkspaceCwd({ thread, projects });
|
||||
}
|
||||
|
||||
function refsMatch(left: string, right: string): boolean {
|
||||
return normalizeSourceBranch(left) === normalizeSourceBranch(right);
|
||||
function cachedChangeRequestState(
|
||||
thread: Pick<OrchestrationThreadShell, "branch">,
|
||||
status: VcsStatusResult | null,
|
||||
): AutomaticSettlementChangeRequestState {
|
||||
if (thread.branch === null) return null;
|
||||
if (status === null || status.refName !== thread.branch) return "unknown";
|
||||
if (status.pr === null || status.pr.headRef !== thread.branch) return "unknown";
|
||||
if (status.pr.state === "open") return "open-cached";
|
||||
if (status.pr.state === "closed") return "closed-cached";
|
||||
return "merged";
|
||||
}
|
||||
|
||||
function liveChangeRequestState(
|
||||
thread: Pick<OrchestrationThreadShell, "branch">,
|
||||
status: VcsStatusResult,
|
||||
): AutomaticSettlementChangeRequestState {
|
||||
if (thread.branch === null) return null;
|
||||
if (status.refName !== thread.branch || status.pr?.headRef !== thread.branch) return null;
|
||||
return status.pr.state;
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
@@ -60,40 +77,9 @@ export const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const sourceControlProviders = yield* SourceControlProviderRegistry;
|
||||
const branchCursor = yield* Ref.make(0);
|
||||
|
||||
const branchLookupCache = yield* Cache.makeWith(
|
||||
(key: string) => {
|
||||
const [cwd = "", branch = ""] = key.split("\u0000");
|
||||
return sourceControlProviders.resolve({ cwd }).pipe(
|
||||
Effect.flatMap((provider) =>
|
||||
provider.listChangeRequests({
|
||||
cwd,
|
||||
headSelector: branch,
|
||||
state: "all",
|
||||
limit: 20,
|
||||
}),
|
||||
),
|
||||
Effect.map((changeRequests): ChangeRequestState | null => {
|
||||
const matching = changeRequests.filter((changeRequest) =>
|
||||
refsMatch(changeRequest.headRefName, branch),
|
||||
);
|
||||
return (
|
||||
matching.find((changeRequest) => changeRequest.state === "open")?.state ??
|
||||
matching.find((changeRequest) => changeRequest.state === "merged")?.state ??
|
||||
matching[0]?.state ??
|
||||
null
|
||||
);
|
||||
}),
|
||||
);
|
||||
},
|
||||
{
|
||||
capacity: 2_048,
|
||||
timeToLive: (exit) =>
|
||||
Exit.isSuccess(exit) ? CHANGE_REQUEST_LOOKUP_TTL : CHANGE_REQUEST_LOOKUP_FAILURE_TTL,
|
||||
},
|
||||
);
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
const lastPrVerifyAtByCwd = yield* Ref.make(new Map<string, number>());
|
||||
|
||||
const dispatchSettlement = Effect.fn("ThreadSettlementReactor.dispatchSettlement")(function* (
|
||||
thread: OrchestrationThreadShell,
|
||||
@@ -124,97 +110,84 @@ export const make = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
const lookupBranchChangeRequestState = (cwd: string, branch: string) =>
|
||||
Cache.get(branchLookupCache, `${cwd}\u0000${branch}`).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logDebug("automatic thread settlement could not read change request state", {
|
||||
cwdLength: cwd.length,
|
||||
branch,
|
||||
errorTag: error._tag,
|
||||
}).pipe(Effect.as(CHANGE_REQUEST_LOOKUP_FAILED)),
|
||||
),
|
||||
);
|
||||
const verifyChangeRequestState = Effect.fn("ThreadSettlementReactor.verifyChangeRequestState")(
|
||||
function* (input: {
|
||||
readonly thread: OrchestrationThreadShell;
|
||||
readonly cwd: string;
|
||||
}): Effect.fn.Return<{
|
||||
readonly state: AutomaticSettlementChangeRequestState;
|
||||
readonly verified: boolean;
|
||||
}> {
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
const mayVerify = yield* Ref.modify(lastPrVerifyAtByCwd, (byCwd) => {
|
||||
const lastAt = byCwd.get(input.cwd);
|
||||
if (lastAt !== undefined && now - lastAt < PR_VERIFY_COOLDOWN_MS) {
|
||||
return [false, byCwd] as const;
|
||||
}
|
||||
const next = new Map(byCwd);
|
||||
next.set(input.cwd, now);
|
||||
return [true, next] as const;
|
||||
});
|
||||
if (!mayVerify) return { state: "unknown", verified: false };
|
||||
|
||||
const resolveThreadChangeRequestState = Effect.fn(
|
||||
"ThreadSettlementReactor.resolveThreadChangeRequestState",
|
||||
)(function* (input: {
|
||||
readonly thread: OrchestrationThreadShell;
|
||||
readonly cwd: string | undefined;
|
||||
}): Effect.fn.Return<ChangeRequestState | null | typeof CHANGE_REQUEST_LOOKUP_FAILED> {
|
||||
const branch = input.thread.branch;
|
||||
if (branch === null || input.cwd === undefined) return null;
|
||||
return yield* lookupBranchChangeRequestState(input.cwd, branch);
|
||||
});
|
||||
const status = yield* vcsStatusBroadcaster.pollStatus(input.cwd).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logDebug("automatic thread settlement could not verify change request state", {
|
||||
threadId: input.thread.id,
|
||||
cwdLength: input.cwd.length,
|
||||
errorTag: error._tag,
|
||||
}).pipe(Effect.as(null)),
|
||||
),
|
||||
);
|
||||
return status === null
|
||||
? { state: "unknown", verified: true }
|
||||
: { state: liveChangeRequestState(input.thread, status), verified: true };
|
||||
},
|
||||
);
|
||||
|
||||
const reconcile = Effect.fn("ThreadSettlementReactor.reconcile")(function* () {
|
||||
const [snapshot, settings, now] = yield* Effect.all([
|
||||
const [snapshot, settings, now, mayVerifyPr] = yield* Effect.all([
|
||||
projectionSnapshotQuery.getShellSnapshot(),
|
||||
serverSettings.getSettings,
|
||||
DateTime.now,
|
||||
backgroundPolicy.shouldRunOpportunisticWork,
|
||||
]);
|
||||
const nowIso = DateTime.formatIso(now);
|
||||
const eligibleThreads = snapshot.threads.filter((thread) => thread.settledOverride === null);
|
||||
const cwdByThreadId = new Map(
|
||||
eligibleThreads.map(
|
||||
(thread) => [thread.id, workspaceCwd(thread, snapshot.projects)] as const,
|
||||
),
|
||||
);
|
||||
const threadsWithoutChangeRequestLookup = eligibleThreads.filter(
|
||||
(thread) => thread.branch === null || cwdByThreadId.get(thread.id) === undefined,
|
||||
);
|
||||
const branchThreads = eligibleThreads.filter(
|
||||
(thread) => thread.branch !== null && cwdByThreadId.get(thread.id) !== undefined,
|
||||
);
|
||||
const branchStart =
|
||||
branchThreads.length === 0 ? 0 : (yield* Ref.get(branchCursor)) % branchThreads.length;
|
||||
const branchCount = Math.min(MAX_BRANCH_LOOKUPS_PER_RECONCILE, branchThreads.length);
|
||||
const selectedBranchThreads = Array.from(
|
||||
{ length: branchCount },
|
||||
(_, offset) => branchThreads[(branchStart + offset) % branchThreads.length]!,
|
||||
);
|
||||
if (branchThreads.length > 0) {
|
||||
yield* Ref.set(branchCursor, (branchStart + branchCount) % branchThreads.length);
|
||||
let verifyBudget = MAX_PR_VERIFICATIONS_PER_RECONCILE;
|
||||
|
||||
for (const thread of snapshot.threads) {
|
||||
const cwd = workspaceCwd(thread, snapshot.projects);
|
||||
const changeRequestState =
|
||||
thread.branch === null
|
||||
? null
|
||||
: cwd === undefined
|
||||
? "unknown"
|
||||
: cachedChangeRequestState(thread, yield* vcsStatusBroadcaster.peekStatus({ cwd }));
|
||||
const verdict = resolveAutomaticSettlementVerdict(thread, {
|
||||
now: nowIso,
|
||||
autoSettleAfterDays: settings.threadAutoSettleAfterDays,
|
||||
autoSettleOnMerge: settings.threadAutoSettleOnMerge,
|
||||
changeRequestState,
|
||||
});
|
||||
if (verdict.kind === "skip") continue;
|
||||
if (verdict.kind === "settle") {
|
||||
yield* dispatchSettlementSafely(thread, verdict.reason);
|
||||
continue;
|
||||
}
|
||||
if (!mayVerifyPr || cwd === undefined || verifyBudget <= 0) continue;
|
||||
|
||||
const verification = yield* verifyChangeRequestState({ thread, cwd });
|
||||
if (verification.verified) verifyBudget -= 1;
|
||||
const verifiedVerdict = resolveAutomaticSettlementVerdict(thread, {
|
||||
now: nowIso,
|
||||
autoSettleAfterDays: settings.threadAutoSettleAfterDays,
|
||||
autoSettleOnMerge: settings.threadAutoSettleOnMerge,
|
||||
changeRequestState: verification.state,
|
||||
});
|
||||
if (verifiedVerdict.kind === "settle") {
|
||||
yield* dispatchSettlementSafely(thread, verifiedVerdict.reason);
|
||||
}
|
||||
}
|
||||
|
||||
yield* Effect.forEach(
|
||||
threadsWithoutChangeRequestLookup,
|
||||
(thread) => {
|
||||
const reason = resolveAutomaticSettlementReason(thread, {
|
||||
now: nowIso,
|
||||
autoSettleAfterDays: settings.threadAutoSettleAfterDays,
|
||||
autoSettleOnMerge: settings.threadAutoSettleOnMerge,
|
||||
changeRequestState: null,
|
||||
});
|
||||
return reason === null ? Effect.void : dispatchSettlementSafely(thread, reason);
|
||||
},
|
||||
{ concurrency: 4, discard: true },
|
||||
);
|
||||
|
||||
// Branch state is remote provider work. Bound each pass and rotate the
|
||||
// cursor so a large first-run history converges without launching one CLI
|
||||
// process per thread at startup.
|
||||
yield* Effect.forEach(
|
||||
selectedBranchThreads,
|
||||
(thread) =>
|
||||
resolveThreadChangeRequestState({
|
||||
thread,
|
||||
cwd: cwdByThreadId.get(thread.id),
|
||||
}).pipe(
|
||||
Effect.flatMap((changeRequestState) => {
|
||||
// A failed lookup is unknown, not evidence that no PR exists.
|
||||
// Fail closed so a transient provider outage cannot hide live work.
|
||||
if (changeRequestState === CHANGE_REQUEST_LOOKUP_FAILED) return Effect.void;
|
||||
const reason = resolveAutomaticSettlementReason(thread, {
|
||||
now: nowIso,
|
||||
autoSettleAfterDays: settings.threadAutoSettleAfterDays,
|
||||
autoSettleOnMerge: settings.threadAutoSettleOnMerge,
|
||||
changeRequestState,
|
||||
});
|
||||
return reason === null ? Effect.void : dispatchSettlementSafely(thread, reason);
|
||||
}),
|
||||
),
|
||||
{ concurrency: 4, discard: true },
|
||||
);
|
||||
});
|
||||
|
||||
const reconcileSafely = reconcile().pipe(
|
||||
|
||||
@@ -9,6 +9,7 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
resolveAutomaticSettlementReason,
|
||||
resolveAutomaticSettlementVerdict,
|
||||
shellHasQueuedTurnStart,
|
||||
threadLastActivityAt,
|
||||
} from "./threadSettlement.ts";
|
||||
@@ -102,9 +103,7 @@ describe("resolveAutomaticSettlementReason", () => {
|
||||
expect(resolve(pinned, { changeRequestState: "open" })).toBeNull();
|
||||
expect(resolve(pinned, { changeRequestState: "closed" })).toBeNull();
|
||||
expect(resolve(pinned, { changeRequestState: "merged" })).toBe("pr-merged");
|
||||
expect(
|
||||
resolve(pinned, { changeRequestState: "merged", autoSettleOnMerge: false }),
|
||||
).toBeNull();
|
||||
expect(resolve(pinned, { changeRequestState: "merged", autoSettleOnMerge: false })).toBeNull();
|
||||
});
|
||||
|
||||
it("does not treat a closed PR as an immediate settlement signal", () => {
|
||||
@@ -165,6 +164,74 @@ describe("resolveAutomaticSettlementReason", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveAutomaticSettlementVerdict", () => {
|
||||
it("re-verifies cached or unknown PR state even for pinned threads", () => {
|
||||
const pinned = makeShell({
|
||||
activityAt: FRESH,
|
||||
pinnedAt: "2026-04-07T00:00:00.000Z",
|
||||
});
|
||||
|
||||
for (const changeRequestState of ["unknown", "open-cached", "closed-cached"] as const) {
|
||||
expect(
|
||||
resolveAutomaticSettlementVerdict(pinned, {
|
||||
now: NOW,
|
||||
autoSettleAfterDays: 3,
|
||||
autoSettleOnMerge: true,
|
||||
changeRequestState,
|
||||
}),
|
||||
).toEqual({ kind: "verify-pr" });
|
||||
}
|
||||
});
|
||||
|
||||
it("does not look up PR state for pins when merge settlement is disabled", () => {
|
||||
const pinned = makeShell({
|
||||
activityAt: FRESH,
|
||||
pinnedAt: "2026-04-07T00:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveAutomaticSettlementVerdict(pinned, {
|
||||
now: NOW,
|
||||
autoSettleAfterDays: 3,
|
||||
autoSettleOnMerge: false,
|
||||
changeRequestState: "open-cached",
|
||||
}),
|
||||
).toEqual({ kind: "skip" });
|
||||
});
|
||||
|
||||
it("does not re-verify terminal live states", () => {
|
||||
const pinned = makeShell({
|
||||
activityAt: STALE,
|
||||
pinnedAt: "2026-04-07T00:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveAutomaticSettlementVerdict(pinned, {
|
||||
now: NOW,
|
||||
autoSettleAfterDays: 3,
|
||||
autoSettleOnMerge: true,
|
||||
changeRequestState: "closed",
|
||||
}),
|
||||
).toEqual({ kind: "skip" });
|
||||
expect(
|
||||
resolveAutomaticSettlementVerdict(pinned, {
|
||||
now: NOW,
|
||||
autoSettleAfterDays: 3,
|
||||
autoSettleOnMerge: true,
|
||||
changeRequestState: "merged",
|
||||
}),
|
||||
).toEqual({ kind: "settle", reason: "pr-merged" });
|
||||
expect(
|
||||
resolveAutomaticSettlementVerdict(pinned, {
|
||||
now: NOW,
|
||||
autoSettleAfterDays: 3,
|
||||
autoSettleOnMerge: false,
|
||||
changeRequestState: "merged",
|
||||
}),
|
||||
).toEqual({ kind: "skip" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("server settlement activity guards", () => {
|
||||
it("uses the latest user or turn activity timestamp", () => {
|
||||
const shell = makeShell({
|
||||
|
||||
@@ -11,6 +11,16 @@ const DAY_MS = 24 * 60 * 60 * 1_000;
|
||||
export const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
|
||||
|
||||
export type AutomaticSettlementReason = "inactivity" | "pr-merged";
|
||||
export type AutomaticSettlementChangeRequestState =
|
||||
| ChangeRequestState
|
||||
| "open-cached"
|
||||
| "closed-cached"
|
||||
| "unknown"
|
||||
| null;
|
||||
export type AutomaticSettlementVerdict =
|
||||
| { readonly kind: "skip" }
|
||||
| { readonly kind: "verify-pr" }
|
||||
| { readonly kind: "settle"; readonly reason: AutomaticSettlementReason };
|
||||
|
||||
export function threadLastActivityAt(shell: OrchestrationThreadShell): string | null {
|
||||
const candidates = [
|
||||
@@ -57,6 +67,46 @@ export function shellHasQueuedTurnStart(
|
||||
* inactivity only. A merged PR is the one automatic signal allowed to settle
|
||||
* and unpin a pinned thread.
|
||||
*/
|
||||
export function resolveAutomaticSettlementVerdict(
|
||||
shell: OrchestrationThreadShell,
|
||||
options: {
|
||||
readonly now: string;
|
||||
readonly autoSettleAfterDays: ThreadAutoSettleAfterDays | null;
|
||||
readonly autoSettleOnMerge: boolean;
|
||||
readonly changeRequestState: AutomaticSettlementChangeRequestState;
|
||||
},
|
||||
): AutomaticSettlementVerdict {
|
||||
if (shell.settledOverride !== null) return { kind: "skip" };
|
||||
if (shell.hasPendingApprovals || shell.hasPendingUserInput) return { kind: "skip" };
|
||||
if (shell.session?.status === "starting" || shell.session?.status === "running") {
|
||||
return { kind: "skip" };
|
||||
}
|
||||
if (shellHasQueuedTurnStart(shell, options.now)) return { kind: "skip" };
|
||||
|
||||
if (shell.pinnedAt != null && !options.autoSettleOnMerge) return { kind: "skip" };
|
||||
if (options.changeRequestState === "merged" && options.autoSettleOnMerge) {
|
||||
return { kind: "settle", reason: "pr-merged" };
|
||||
}
|
||||
// Cached non-terminal states can hide a later merge. Re-verify them on the
|
||||
// reactor's bounded cooldown even for fresh or pinned threads.
|
||||
if (
|
||||
options.changeRequestState === "unknown" ||
|
||||
options.changeRequestState === "open-cached" ||
|
||||
options.changeRequestState === "closed-cached"
|
||||
) {
|
||||
return { kind: "verify-pr" };
|
||||
}
|
||||
if (shell.pinnedAt != null) return { kind: "skip" };
|
||||
if (options.changeRequestState === "open") return { kind: "skip" };
|
||||
if (options.autoSettleAfterDays === null) return { kind: "skip" };
|
||||
|
||||
const lastActivityAt = threadLastActivityAt(shell);
|
||||
if (lastActivityAt === null) return { kind: "skip" };
|
||||
return Date.parse(lastActivityAt) < Date.parse(options.now) - options.autoSettleAfterDays * DAY_MS
|
||||
? { kind: "settle", reason: "inactivity" }
|
||||
: { kind: "skip" };
|
||||
}
|
||||
|
||||
export function resolveAutomaticSettlementReason(
|
||||
shell: OrchestrationThreadShell,
|
||||
options: {
|
||||
@@ -66,19 +116,6 @@ export function resolveAutomaticSettlementReason(
|
||||
readonly changeRequestState: ChangeRequestState | null;
|
||||
},
|
||||
): AutomaticSettlementReason | null {
|
||||
if (shell.settledOverride !== null) return null;
|
||||
if (shell.hasPendingApprovals || shell.hasPendingUserInput) return null;
|
||||
if (shell.session?.status === "starting" || shell.session?.status === "running") return null;
|
||||
if (shellHasQueuedTurnStart(shell, options.now)) return null;
|
||||
|
||||
if (options.changeRequestState === "merged" && options.autoSettleOnMerge) return "pr-merged";
|
||||
if (shell.pinnedAt != null) return null;
|
||||
if (options.changeRequestState === "open") return null;
|
||||
if (options.autoSettleAfterDays === null) return null;
|
||||
|
||||
const lastActivityAt = threadLastActivityAt(shell);
|
||||
if (lastActivityAt === null) return null;
|
||||
return Date.parse(lastActivityAt) < Date.parse(options.now) - options.autoSettleAfterDays * DAY_MS
|
||||
? "inactivity"
|
||||
: null;
|
||||
const verdict = resolveAutomaticSettlementVerdict(shell, options);
|
||||
return verdict.kind === "settle" ? verdict.reason : null;
|
||||
}
|
||||
Reference in new issue
Block a user