1884 lines
75 KiB
TypeScript
1884 lines
75 KiB
TypeScript
import {
|
|
DEFAULT_SERVER_SETTINGS,
|
|
EventId,
|
|
ProjectId,
|
|
ProviderInstanceId,
|
|
ProviderDriverKind,
|
|
PullRequestOperationError,
|
|
ThreadId,
|
|
type OrchestrationCommand,
|
|
type OrchestrationEvent,
|
|
type OrchestrationProjectShell,
|
|
type OrchestrationShellSnapshot,
|
|
type OrchestrationThreadShell,
|
|
type PullRequestSummary,
|
|
type ServerSettings,
|
|
type ServerSettingsPatch,
|
|
} from "@t3tools/contracts";
|
|
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
|
|
import { assert, describe, it } from "@effect/vitest";
|
|
import * as Crypto from "effect/Crypto";
|
|
import * as DateTime from "effect/DateTime";
|
|
import * as Deferred from "effect/Deferred";
|
|
import * as Effect from "effect/Effect";
|
|
import * as Fiber from "effect/Fiber";
|
|
import * as FileSystem from "effect/FileSystem";
|
|
import * as Layer from "effect/Layer";
|
|
import * as PubSub from "effect/PubSub";
|
|
import * as Queue from "effect/Queue";
|
|
import * as Ref from "effect/Ref";
|
|
import * as Stream from "effect/Stream";
|
|
import { TestClock } from "effect/testing";
|
|
|
|
import { GitManager, type GitBranchPullRequest } from "../git/GitManager.ts";
|
|
import {
|
|
PullRequestService,
|
|
type PullRequestMergeEvent,
|
|
} from "../pullRequest/PullRequestService.ts";
|
|
import { ServerActivation } from "../serverActivation.ts";
|
|
import { ServerSettingsService } from "../serverSettings.ts";
|
|
import { OrchestrationCommandInvariantError } from "./Errors.ts";
|
|
import {
|
|
OrchestrationEngineService,
|
|
type OrchestrationEngineShape,
|
|
} from "./Services/OrchestrationEngine.ts";
|
|
import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
|
|
import * as ThreadSettlementReactor from "./ThreadSettlementReactor.ts";
|
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
import * as Path from "effect/Path";
|
|
import { ChildProcessSpawner } from "effect/unstable/process";
|
|
import { ServerConfig } from "../config.ts";
|
|
import * as StorageCleanup from "../storageCleanup.ts";
|
|
import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
|
|
import { TerminalManager } from "../terminal/Manager.ts";
|
|
import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
|
|
import { ThreadDeletionReactor } from "./Services/ThreadDeletionReactor.ts";
|
|
import { ProviderService } from "../provider/Services/ProviderService.ts";
|
|
|
|
const NOW = "2026-08-28T12:00:00.000Z";
|
|
const PROJECT_ID = ProjectId.make("settlement-project");
|
|
const LINKED_PROJECT_ID = ProjectId.make("linked-settlement-project");
|
|
|
|
type AutoSettleCommand = Extract<OrchestrationCommand, { readonly type: "thread.auto-settle" }>;
|
|
|
|
const testCrypto = Crypto.make({
|
|
randomBytes: (size) => new Uint8Array(size).fill(1),
|
|
digest: (_algorithm, data) => Effect.succeed(data),
|
|
});
|
|
|
|
function makeProject(
|
|
id: ProjectId = PROJECT_ID,
|
|
workspaceRoot = "/workspace/project",
|
|
): OrchestrationProjectShell {
|
|
return {
|
|
id,
|
|
title: `Project ${id}`,
|
|
workspaceRoot,
|
|
defaultModelSelection: null,
|
|
scripts: [],
|
|
createdAt: "2026-08-01T00:00:00.000Z",
|
|
updatedAt: NOW,
|
|
};
|
|
}
|
|
|
|
function makeThread(
|
|
id: string,
|
|
overrides: Partial<OrchestrationThreadShell> = {},
|
|
): OrchestrationThreadShell {
|
|
return {
|
|
id: ThreadId.make(id),
|
|
projectId: PROJECT_ID,
|
|
title: id,
|
|
modelSelection: {
|
|
instanceId: ProviderInstanceId.make("codex"),
|
|
model: "gpt-5",
|
|
},
|
|
runtimeMode: "full-access",
|
|
interactionMode: "default",
|
|
pullRequests: [],
|
|
branch: null,
|
|
worktreePath: null,
|
|
latestTurn: null,
|
|
createdAt: "2026-08-01T00:00:00.000Z",
|
|
updatedAt: "2026-08-20T00:00:00.000Z",
|
|
archivedAt: null,
|
|
settledOverride: null,
|
|
settledAt: null,
|
|
session: null,
|
|
latestUserMessageAt: "2026-08-20T00:00:00.000Z",
|
|
hasPendingApprovals: false,
|
|
hasPendingUserInput: false,
|
|
hasActionableProposedPlan: false,
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function makeSnapshot(
|
|
threads: ReadonlyArray<OrchestrationThreadShell>,
|
|
projects: ReadonlyArray<OrchestrationProjectShell> = [makeProject()],
|
|
): OrchestrationShellSnapshot {
|
|
return {
|
|
snapshotSequence: 1,
|
|
projects,
|
|
threads,
|
|
updatedAt: NOW,
|
|
};
|
|
}
|
|
|
|
function makePullRequestSummary(input: {
|
|
readonly projectId: ProjectId;
|
|
readonly repository: string;
|
|
readonly number: number;
|
|
readonly state: "open" | "closed" | "merged";
|
|
readonly updatedAt?: string;
|
|
}): PullRequestSummary {
|
|
return {
|
|
provider: "github",
|
|
projectId: input.projectId,
|
|
repository: input.repository,
|
|
number: input.number,
|
|
title: "Pull request",
|
|
url: `https://example.test/${input.repository}/pull/${input.number}`,
|
|
state: input.state,
|
|
headBranch: "feature",
|
|
baseBranch: "main",
|
|
updatedAt: input.updatedAt ?? NOW,
|
|
closedAt: input.state === "closed" ? (input.updatedAt ?? NOW) : null,
|
|
mergedAt: input.state === "merged" ? (input.updatedAt ?? NOW) : null,
|
|
};
|
|
}
|
|
|
|
function makeBranchPullRequest(
|
|
state: GitBranchPullRequest["state"],
|
|
updatedAt: string | null = NOW,
|
|
): GitBranchPullRequest {
|
|
return {
|
|
number: 42,
|
|
title: "Branch pull request",
|
|
url: "https://example.test/owner/repository/pull/42",
|
|
baseRef: "main",
|
|
headRef: "saved-feature",
|
|
repositoryKey: "example.test/owner/repository",
|
|
state,
|
|
updatedAt,
|
|
closedAt: state === "closed" ? updatedAt : null,
|
|
mergedAt: state === "merged" ? updatedAt : null,
|
|
};
|
|
}
|
|
|
|
interface HarnessOptions {
|
|
readonly snapshot: OrchestrationShellSnapshot;
|
|
readonly settings?: ServerSettings;
|
|
readonly branchPullRequest?: GitManager["Service"]["branchPullRequest"];
|
|
readonly pullRequestSummary?: PullRequestService["Service"]["summary"];
|
|
readonly existingWorktreePaths?: ReadonlyArray<string>;
|
|
readonly onDispatch?: (
|
|
command: AutoSettleCommand,
|
|
) => Effect.Effect<void, OrchestrationCommandInvariantError>;
|
|
}
|
|
|
|
const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: HarnessOptions) {
|
|
const activation = yield* Deferred.make<void>();
|
|
const snapshots = yield* Ref.make(options.snapshot);
|
|
const snapshotReadCount = yield* Ref.make(0);
|
|
const snapshotReads = yield* Queue.unbounded<number>();
|
|
const settings = yield* Ref.make(options.settings ?? DEFAULT_SERVER_SETTINGS);
|
|
const settingsReads = yield* Queue.unbounded<ServerSettings>();
|
|
const settingsChanges = yield* PubSub.unbounded<ServerSettings>();
|
|
const mergedPullRequests = yield* PubSub.unbounded<PullRequestMergeEvent>();
|
|
const domainEvents = yield* PubSub.unbounded<OrchestrationEvent>();
|
|
const commands = yield* Ref.make<ReadonlyArray<AutoSettleCommand>>([]);
|
|
const branchCalls = yield* Ref.make<
|
|
ReadonlyArray<{ readonly cwd: string; readonly branch: string }>
|
|
>([]);
|
|
const summaryCalls = yield* Ref.make<
|
|
ReadonlyArray<{
|
|
readonly projectId: ProjectId;
|
|
readonly repository: string;
|
|
readonly number: number;
|
|
}>
|
|
>([]);
|
|
const summaryRecovery = yield* Ref.make<ReadonlyArray<boolean | undefined>>([]);
|
|
const invalidatedCwds = yield* Ref.make<ReadonlyArray<string>>([]);
|
|
|
|
const updateSettings = (patch: ServerSettingsPatch) =>
|
|
Effect.gen(function* () {
|
|
const next = applyServerSettingsPatch(yield* Ref.get(settings), patch);
|
|
yield* Ref.set(settings, next);
|
|
yield* PubSub.publish(settingsChanges, next);
|
|
return next;
|
|
});
|
|
|
|
const branchPullRequest: GitManager["Service"]["branchPullRequest"] = (input, readOptions) =>
|
|
Ref.update(branchCalls, (calls) => [...calls, input]).pipe(
|
|
Effect.andThen(options.branchPullRequest?.(input, readOptions) ?? Effect.succeed(null)),
|
|
);
|
|
const pullRequestSummary: PullRequestService["Service"]["summary"] = (input, readOptions) =>
|
|
Effect.gen(function* () {
|
|
yield* Ref.update(summaryCalls, (calls) => [...calls, input]);
|
|
yield* Ref.update(summaryRecovery, (values) => [
|
|
...values,
|
|
readOptions?.recoverTransientFailure,
|
|
]);
|
|
return yield* (
|
|
options.pullRequestSummary?.(input, readOptions) ??
|
|
Effect.succeed(
|
|
makePullRequestSummary({
|
|
...input,
|
|
state: "open",
|
|
}),
|
|
)
|
|
);
|
|
});
|
|
|
|
const dispatch: OrchestrationEngineShape["dispatch"] = (command) => {
|
|
if (command.type !== "thread.auto-settle") {
|
|
return Effect.die(new Error(`Unexpected command: ${command.type}`));
|
|
}
|
|
return Ref.update(commands, (recorded) => [...recorded, command]).pipe(
|
|
Effect.andThen(options.onDispatch?.(command) ?? Effect.void),
|
|
Effect.as({ sequence: 1 }),
|
|
);
|
|
};
|
|
|
|
const serverSettings = ServerSettingsService.of({
|
|
start: Effect.void,
|
|
ready: Effect.void,
|
|
getSettings: Ref.get(settings).pipe(Effect.tap((value) => Queue.offer(settingsReads, value))),
|
|
updateSettings,
|
|
streamChanges: Stream.fromPubSub(settingsChanges),
|
|
subscribeChanges: PubSub.subscribe(settingsChanges).pipe(
|
|
Effect.map((subscription) => Stream.fromSubscription(subscription)),
|
|
),
|
|
});
|
|
|
|
const dependencies = Layer.mergeAll(
|
|
Layer.mock(ProjectionSnapshotQuery)({
|
|
getShellSnapshot: () =>
|
|
Ref.updateAndGet(snapshotReadCount, (count) => count + 1).pipe(
|
|
Effect.tap((count) => Queue.offer(snapshotReads, count)),
|
|
Effect.andThen(Ref.get(snapshots)),
|
|
),
|
|
}),
|
|
Layer.mock(GitManager)({
|
|
branchPullRequest,
|
|
invalidateStatus: (cwd) => Ref.update(invalidatedCwds, (cwds) => [...cwds, cwd]),
|
|
}),
|
|
Layer.mock(PullRequestService)({
|
|
summary: pullRequestSummary,
|
|
subscribeMerges: PubSub.subscribe(mergedPullRequests).pipe(
|
|
Effect.map((subscription) => Stream.fromSubscription(subscription)),
|
|
),
|
|
}),
|
|
Layer.mock(OrchestrationEngineService)({
|
|
readEvents: () => Stream.empty,
|
|
dispatch,
|
|
streamDomainEvents: Stream.empty,
|
|
subscribeDomainEvents: PubSub.subscribe(domainEvents).pipe(
|
|
Effect.map((subscription) => Stream.fromSubscription(subscription)),
|
|
),
|
|
latestSequence: Effect.succeed(0),
|
|
}),
|
|
Layer.succeed(ServerSettingsService, serverSettings),
|
|
Layer.succeed(ServerActivation, Deferred.await(activation)),
|
|
Layer.succeed(Crypto.Crypto, testCrypto),
|
|
FileSystem.layerNoop({
|
|
exists: (path) => Effect.succeed(options.existingWorktreePaths?.includes(path) ?? false),
|
|
}),
|
|
);
|
|
|
|
return {
|
|
activation,
|
|
snapshots,
|
|
snapshotReadCount,
|
|
snapshotReads,
|
|
settingsReads,
|
|
commands,
|
|
branchCalls,
|
|
summaryCalls,
|
|
summaryRecovery,
|
|
invalidatedCwds,
|
|
updateSettings,
|
|
publishEvent: (event: OrchestrationEvent) => PubSub.publish(domainEvents, event),
|
|
publishMerge: PubSub.publish(mergedPullRequests, {
|
|
projectId: PROJECT_ID,
|
|
repository: "owner/repository",
|
|
number: 42,
|
|
mergedAt: NOW,
|
|
}),
|
|
layer: ThreadSettlementReactor.layer.pipe(Layer.provide(dependencies)),
|
|
};
|
|
});
|
|
|
|
const startHarness = Effect.fn("startThreadSettlementHarness")(function* (
|
|
reactor: ThreadSettlementReactor.ThreadSettlementReactor["Service"],
|
|
activation: Deferred.Deferred<void>,
|
|
snapshotReads: Queue.Queue<number>,
|
|
) {
|
|
yield* reactor.start();
|
|
yield* Deferred.succeed(activation, undefined);
|
|
yield* Queue.take(snapshotReads);
|
|
yield* reactor.drain;
|
|
});
|
|
|
|
describe("ThreadSettlementReactor", () => {
|
|
it("distinguishes a project that inherits the threshold from one that disables it", () => {
|
|
const inherits = ThreadSettlementReactor.autoSettlementSettingsKey({
|
|
...DEFAULT_SERVER_SETTINGS,
|
|
projectSettingsOverrides: { [PROJECT_ID]: { sidebarAutoSettleOnMerge: true } },
|
|
});
|
|
const never = ThreadSettlementReactor.autoSettlementSettingsKey({
|
|
...DEFAULT_SERVER_SETTINGS,
|
|
projectSettingsOverrides: {
|
|
[PROJECT_ID]: { sidebarAutoSettleOnMerge: true, sidebarAutoSettleAfterDays: null },
|
|
},
|
|
});
|
|
assert.notStrictEqual(inherits, never);
|
|
});
|
|
|
|
it("ignores project overrides that do not touch settlement", () => {
|
|
const base = ThreadSettlementReactor.autoSettlementSettingsKey({
|
|
...DEFAULT_SERVER_SETTINGS,
|
|
projectSettingsOverrides: { [PROJECT_ID]: { sidebarAutoSettleOnMerge: false } },
|
|
});
|
|
const unrelated = ThreadSettlementReactor.autoSettlementSettingsKey({
|
|
...DEFAULT_SERVER_SETTINGS,
|
|
projectSettingsOverrides: {
|
|
[LINKED_PROJECT_ID]: { defaultThreadEnvMode: "worktree" },
|
|
[PROJECT_ID]: { sidebarAutoSettleOnMerge: false, defaultAutoPull: true },
|
|
},
|
|
});
|
|
assert.strictEqual(base, unrelated);
|
|
});
|
|
|
|
it.effect(
|
|
"settles synced terminal links immediately while open, unsynced, or running threads wait",
|
|
() =>
|
|
Effect.scoped(
|
|
Effect.gen(function* () {
|
|
yield* TestClock.setTime(Date.parse(NOW));
|
|
const link = (number: number, state: "open" | "closed" | "merged" | null) => ({
|
|
host: "example.test",
|
|
repository: "owner/repository",
|
|
number,
|
|
url: `https://example.test/owner/repository/pull/${number}`,
|
|
source: "manual" as const,
|
|
linkedAt: NOW,
|
|
stack: null,
|
|
snapshot:
|
|
state === null
|
|
? null
|
|
: {
|
|
state,
|
|
title: "Review",
|
|
headBranch: "feature",
|
|
baseBranch: "main",
|
|
isDraft: false,
|
|
updatedAt: NOW,
|
|
syncedAt: NOW,
|
|
mergedAt: state === "merged" ? NOW : null,
|
|
closedAt: state === "closed" ? NOW : null,
|
|
},
|
|
});
|
|
const runningSession = {
|
|
threadId: ThreadId.make("running"),
|
|
status: "running" as const,
|
|
providerName: "Codex",
|
|
runtimeMode: "full-access" as const,
|
|
activeTurnId: null,
|
|
lastError: null,
|
|
updatedAt: NOW,
|
|
};
|
|
const threads = [
|
|
makeThread("merged", { pullRequests: [link(1, "open"), link(2, "merged")] }),
|
|
makeThread("closed", { pullRequests: [link(1, "open")] }),
|
|
makeThread("open", { pullRequests: [link(1, "open"), link(2, "open")] }),
|
|
makeThread("unsynced", { pullRequests: [link(1, "open"), link(2, null)] }),
|
|
makeThread("running", {
|
|
pullRequests: [link(1, "open")],
|
|
session: runningSession,
|
|
}),
|
|
];
|
|
const fixture = yield* makeHarness({
|
|
snapshot: makeSnapshot(threads),
|
|
settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleOnMerge: true },
|
|
branchPullRequest: () => Effect.die("linked threads must not query the branch"),
|
|
pullRequestSummary: () => Effect.die("linked threads must use their snapshots"),
|
|
});
|
|
yield* Effect.gen(function* () {
|
|
const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
|
|
yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
|
|
assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
|
|
const eventBase = {
|
|
sequence: 2,
|
|
eventId: EventId.make("pull-request-synced"),
|
|
aggregateKind: "thread" as const,
|
|
occurredAt: NOW,
|
|
commandId: null,
|
|
causationEventId: null,
|
|
correlationId: null,
|
|
metadata: {},
|
|
};
|
|
for (const thread of threads) {
|
|
const terminalLink = link(1, thread.id === "closed" ? "closed" : "merged");
|
|
yield* Ref.update(fixture.snapshots, (snapshot) => ({
|
|
...snapshot,
|
|
threads: snapshot.threads.map((current) =>
|
|
current.id === thread.id
|
|
? { ...current, pullRequests: [terminalLink, ...current.pullRequests.slice(1)] }
|
|
: current,
|
|
),
|
|
}));
|
|
yield* fixture.publishEvent({
|
|
...eventBase,
|
|
type: "thread.pull-request-synced",
|
|
aggregateId: thread.id,
|
|
payload: {
|
|
threadId: thread.id,
|
|
host: terminalLink.host,
|
|
repository: terminalLink.repository,
|
|
number: terminalLink.number,
|
|
snapshot: terminalLink.snapshot!,
|
|
stack: null,
|
|
updatedAt: NOW,
|
|
},
|
|
});
|
|
yield* Queue.take(fixture.snapshotReads);
|
|
yield* reactor.drain;
|
|
}
|
|
assert.deepStrictEqual(
|
|
(yield* Ref.get(fixture.commands)).map(({ threadId }) => threadId),
|
|
[ThreadId.make("merged"), ThreadId.make("closed")],
|
|
);
|
|
const readySession = { ...runningSession, status: "ready" as const };
|
|
yield* Ref.update(fixture.snapshots, (snapshot) => ({
|
|
...snapshot,
|
|
threads: snapshot.threads.map((thread) =>
|
|
thread.id === readySession.threadId ? { ...thread, session: readySession } : thread,
|
|
),
|
|
}));
|
|
yield* fixture.publishEvent({
|
|
...eventBase,
|
|
type: "thread.session-set",
|
|
aggregateId: readySession.threadId,
|
|
payload: { threadId: readySession.threadId, session: readySession },
|
|
});
|
|
yield* Queue.take(fixture.snapshotReads);
|
|
yield* reactor.drain;
|
|
assert.deepStrictEqual(
|
|
(yield* Ref.get(fixture.commands)).map(({ threadId }) => threadId),
|
|
[ThreadId.make("merged"), ThreadId.make("closed"), ThreadId.make("running")],
|
|
);
|
|
assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), []);
|
|
assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
|
|
}).pipe(Effect.provide(fixture.layer));
|
|
}),
|
|
),
|
|
);
|
|
it.effect("uses saved PRs without settling resumed threads or branches with newer PRs", () =>
|
|
Effect.scoped(
|
|
Effect.gen(function* () {
|
|
yield* TestClock.setTime(Date.parse(NOW));
|
|
const previous = {
|
|
projectId: PROJECT_ID,
|
|
repository: "owner/repository",
|
|
number: 1,
|
|
url: "https://example.test/owner/repository/pull/1",
|
|
};
|
|
const project = {
|
|
...makeProject(),
|
|
repositoryIdentity: {
|
|
canonicalKey: "example.test/owner/repository",
|
|
rootPath: "/workspace/project",
|
|
displayName: "owner/repository",
|
|
locator: {
|
|
source: "git-remote" as const,
|
|
remoteName: "origin",
|
|
remoteUrl: "https://example.test/owner/repository.git",
|
|
},
|
|
},
|
|
};
|
|
const fixture = yield* makeHarness({
|
|
snapshot: makeSnapshot(
|
|
[
|
|
makeThread("retained-terminal", { branch: "main", branchPullRequest: previous }),
|
|
makeThread("reused-manual", { branch: "reused", linkedPullRequest: previous }),
|
|
makeThread("reused-detected", { branch: "reused", branchPullRequest: previous }),
|
|
makeThread("foreign-branch-pr", { branch: "foreign", linkedPullRequest: previous }),
|
|
makeThread("resumed-manual", {
|
|
branch: "main",
|
|
linkedPullRequest: previous,
|
|
latestUserMessageAt: "2026-08-28T00:00:00.000Z",
|
|
}),
|
|
makeThread("resumed-detected", {
|
|
branch: "main",
|
|
branchPullRequest: previous,
|
|
latestUserMessageAt: "2026-08-28T00:00:00.000Z",
|
|
}),
|
|
],
|
|
[project],
|
|
),
|
|
settings: {
|
|
...DEFAULT_SERVER_SETTINGS,
|
|
sidebarAutoSettleAfterDays: null,
|
|
sidebarAutoSettleOnMerge: true,
|
|
},
|
|
branchPullRequest: ({ branch }, options) =>
|
|
Effect.succeed(
|
|
branch === "reused"
|
|
? makeBranchPullRequest(options?.refresh ? "open" : "merged")
|
|
: branch === "foreign"
|
|
? {
|
|
...makeBranchPullRequest("open"),
|
|
repositoryKey: "example.test/another/repository",
|
|
}
|
|
: null,
|
|
),
|
|
pullRequestSummary: (input) =>
|
|
Effect.succeed({
|
|
...makePullRequestSummary({ ...input, state: "merged" }),
|
|
mergedAt: "2026-08-27T00:00:00.000Z",
|
|
}),
|
|
});
|
|
yield* Effect.gen(function* () {
|
|
const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
|
|
yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
|
|
assert.deepStrictEqual(
|
|
new Set((yield* Ref.get(fixture.commands)).map((command) => command.threadId)),
|
|
new Set([ThreadId.make("retained-terminal"), ThreadId.make("foreign-branch-pr")]),
|
|
);
|
|
}).pipe(Effect.provide(fixture.layer));
|
|
}),
|
|
),
|
|
);
|
|
|
|
it.effect("skips PR work on startup, timer and merge sweeps when settlement is disabled", () =>
|
|
Effect.scoped(
|
|
Effect.gen(function* () {
|
|
yield* TestClock.setTime(Date.parse(NOW));
|
|
const fixture = yield* makeHarness({
|
|
snapshot: makeSnapshot([
|
|
makeThread("branch-thread", { branch: "feature" }),
|
|
makeThread("linked-thread", {
|
|
linkedPullRequest: {
|
|
projectId: PROJECT_ID,
|
|
repository: "owner/repository",
|
|
number: 42,
|
|
url: "https://example.test/owner/repository/pull/42",
|
|
},
|
|
}),
|
|
]),
|
|
settings: {
|
|
...DEFAULT_SERVER_SETTINGS,
|
|
sidebarAutoSettleAfterDays: null,
|
|
sidebarAutoSettleOnMerge: false,
|
|
},
|
|
});
|
|
|
|
yield* Effect.gen(function* () {
|
|
const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
|
|
yield* reactor.start();
|
|
yield* Queue.take(fixture.settingsReads);
|
|
yield* Deferred.succeed(fixture.activation, undefined);
|
|
yield* Queue.take(fixture.settingsReads);
|
|
yield* reactor.drain;
|
|
yield* TestClock.adjust("1 minute");
|
|
yield* Queue.take(fixture.settingsReads);
|
|
yield* reactor.drain;
|
|
yield* fixture.publishMerge;
|
|
yield* Queue.take(fixture.settingsReads);
|
|
yield* reactor.drain;
|
|
|
|
assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), []);
|
|
assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
|
|
assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), []);
|
|
assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
|
|
assert.strictEqual(yield* Ref.get(fixture.snapshotReadCount), 0);
|
|
|
|
yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 1 });
|
|
yield* Queue.take(fixture.snapshotReads);
|
|
yield* reactor.drain;
|
|
// Inactive threads settle without a PR lookup, so only the dispatches prove work resumed.
|
|
assert.deepStrictEqual(
|
|
(yield* Ref.get(fixture.commands)).map((command) => command.threadId).toSorted(),
|
|
[ThreadId.make("branch-thread"), ThreadId.make("linked-thread")],
|
|
);
|
|
}).pipe(Effect.provide(fixture.layer));
|
|
}),
|
|
),
|
|
);
|
|
|
|
it.effect("a project override settles only that project's inactive threads", () =>
|
|
Effect.scoped(
|
|
Effect.gen(function* () {
|
|
yield* TestClock.setTime(Date.parse(NOW));
|
|
const overriddenProject = ProjectId.make("overridden-project");
|
|
const fixture = yield* makeHarness({
|
|
snapshot: makeSnapshot(
|
|
[
|
|
makeThread("inherits-thread"),
|
|
makeThread("overridden-thread", { projectId: overriddenProject }),
|
|
],
|
|
[makeProject(), makeProject(overriddenProject, "/workspace/overridden")],
|
|
),
|
|
settings: {
|
|
...DEFAULT_SERVER_SETTINGS,
|
|
sidebarAutoSettleAfterDays: null,
|
|
sidebarAutoSettleOnMerge: false,
|
|
projectSettingsOverrides: {
|
|
[overriddenProject]: { sidebarAutoSettleAfterDays: 1 },
|
|
},
|
|
},
|
|
});
|
|
|
|
yield* Effect.gen(function* () {
|
|
const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
|
|
yield* reactor.start();
|
|
yield* Queue.take(fixture.settingsReads);
|
|
yield* Deferred.succeed(fixture.activation, undefined);
|
|
yield* Queue.take(fixture.snapshotReads);
|
|
yield* reactor.drain;
|
|
assert.deepStrictEqual(
|
|
(yield* Ref.get(fixture.commands)).map((command) => command.threadId),
|
|
[ThreadId.make("overridden-thread")],
|
|
);
|
|
|
|
// Clearing the override is a settlement change, so the sweep re-arms.
|
|
yield* fixture.updateSettings({
|
|
projectSettingsOverrides: { [overriddenProject]: null },
|
|
sidebarAutoSettleAfterDays: 1,
|
|
});
|
|
yield* Queue.take(fixture.snapshotReads);
|
|
yield* reactor.drain;
|
|
// The static snapshot never records the first settlement, so the
|
|
// second sweep dispatches for both; the inheriting thread is new.
|
|
assert.include(
|
|
(yield* Ref.get(fixture.commands)).map((command) => command.threadId),
|
|
ThreadId.make("inherits-thread"),
|
|
);
|
|
}).pipe(Effect.provide(fixture.layer));
|
|
}),
|
|
),
|
|
);
|
|
|
|
it.effect("starts without clients and skips protected threads before pull request lookup", () =>
|
|
Effect.scoped(
|
|
Effect.gen(function* () {
|
|
yield* TestClock.setTime(Date.parse(NOW));
|
|
const linkedPullRequest = {
|
|
projectId: LINKED_PROJECT_ID,
|
|
repository: "owner/repository",
|
|
number: 42,
|
|
url: "https://example.test/owner/repository/pull/42",
|
|
} as const;
|
|
const skipped = [
|
|
makeThread("pending-approval", {
|
|
branch: "skip-approval",
|
|
hasPendingApprovals: true,
|
|
}),
|
|
makeThread("snoozed", {
|
|
branch: "skip-snoozed",
|
|
snoozedUntil: "2026-08-29T00:00:00.000Z",
|
|
}),
|
|
];
|
|
const fixture = yield* makeHarness({
|
|
snapshot: makeSnapshot(
|
|
[
|
|
makeThread("inactive", { branch: "inactive-feature" }),
|
|
makeThread("closed-pr", {
|
|
linkedPullRequest,
|
|
latestUserMessageAt: "2026-08-27T00:00:00.000Z",
|
|
}),
|
|
...skipped,
|
|
],
|
|
[makeProject(), makeProject(LINKED_PROJECT_ID, "/workspace/linked")],
|
|
),
|
|
branchPullRequest: () => Effect.succeed(null),
|
|
pullRequestSummary: (input) =>
|
|
Effect.succeed(makePullRequestSummary({ ...input, state: "closed" })),
|
|
});
|
|
|
|
yield* Effect.gen(function* () {
|
|
const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
|
|
yield* reactor.start();
|
|
assert.strictEqual(yield* Ref.get(fixture.snapshotReadCount), 0);
|
|
|
|
yield* Deferred.succeed(fixture.activation, undefined);
|
|
yield* Queue.take(fixture.snapshotReads);
|
|
yield* reactor.drain;
|
|
|
|
const commands = yield* Ref.get(fixture.commands);
|
|
assert.deepStrictEqual(
|
|
commands
|
|
.map(({ threadId, snapshotSequence, settledAt }) => ({
|
|
threadId,
|
|
snapshotSequence,
|
|
settledAt,
|
|
}))
|
|
.sort((left, right) => left.threadId.localeCompare(right.threadId)),
|
|
[
|
|
{
|
|
threadId: ThreadId.make("closed-pr"),
|
|
snapshotSequence: 1,
|
|
settledAt: "2026-08-27T00:00:00.000Z",
|
|
},
|
|
{
|
|
threadId: ThreadId.make("inactive"),
|
|
snapshotSequence: 1,
|
|
settledAt: "2026-08-20T00:00:00.000Z",
|
|
},
|
|
],
|
|
);
|
|
assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), []);
|
|
assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
|
|
{ projectId: LINKED_PROJECT_ID, repository: "owner/repository", number: 42 },
|
|
]);
|
|
assert.deepStrictEqual(yield* Ref.get(fixture.summaryRecovery), [false]);
|
|
}).pipe(Effect.provide(fixture.layer));
|
|
}),
|
|
),
|
|
);
|
|
|
|
it.effect("reevaluates inactivity and pull request state once per minute", () =>
|
|
Effect.scoped(
|
|
Effect.gen(function* () {
|
|
yield* TestClock.setTime(Date.parse(NOW));
|
|
const pullRequest = yield* Ref.make<"open" | "merged">("open");
|
|
const fixture = yield* makeHarness({
|
|
snapshot: makeSnapshot([
|
|
makeThread("at-boundary", {
|
|
latestUserMessageAt: "2026-08-25T12:00:00.000Z",
|
|
}),
|
|
makeThread("open-pr", {
|
|
branch: "saved-feature",
|
|
latestUserMessageAt: "2026-08-27T00:00:00.000Z",
|
|
}),
|
|
]),
|
|
branchPullRequest: () =>
|
|
Ref.get(pullRequest).pipe(Effect.map((state) => makeBranchPullRequest(state))),
|
|
});
|
|
|
|
yield* Effect.gen(function* () {
|
|
const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
|
|
yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
|
|
assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
|
|
|
|
yield* Ref.set(pullRequest, "merged");
|
|
yield* TestClock.adjust("1 minute");
|
|
yield* Queue.take(fixture.snapshotReads);
|
|
yield* reactor.drain;
|
|
|
|
assert.deepStrictEqual(
|
|
(yield* Ref.get(fixture.commands))
|
|
.map((command) => command.threadId)
|
|
.sort((left, right) => left.localeCompare(right)),
|
|
[ThreadId.make("at-boundary"), ThreadId.make("open-pr")],
|
|
);
|
|
assert.strictEqual((yield* Ref.get(fixture.branchCalls)).length, 2);
|
|
}).pipe(Effect.provide(fixture.layer));
|
|
}),
|
|
),
|
|
);
|
|
|
|
it.effect("reevaluates immediately after a pull request merge", () =>
|
|
Effect.scoped(
|
|
Effect.gen(function* () {
|
|
yield* TestClock.setTime(Date.parse(NOW));
|
|
const periodicLookupStarted = yield* Deferred.make<void>();
|
|
const releasePeriodicLookup = yield* Deferred.make<void>();
|
|
const mergedThreadSettled = yield* Deferred.make<void>();
|
|
const branchLookupCount = yield* Ref.make(0);
|
|
const fixture = yield* makeHarness({
|
|
snapshot: makeSnapshot([
|
|
makeThread("merged-in-app", {
|
|
latestUserMessageAt: "2026-08-27T00:00:00.000Z",
|
|
linkedPullRequest: {
|
|
projectId: PROJECT_ID,
|
|
repository: "owner/repository",
|
|
number: 42,
|
|
url: "https://example.test/owner/repository/pull/42",
|
|
},
|
|
}),
|
|
makeThread("slow-periodic-lookup", {
|
|
branch: "another-feature",
|
|
latestUserMessageAt: "2026-08-27T00:00:00.000Z",
|
|
}),
|
|
]),
|
|
branchPullRequest: () =>
|
|
Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
|
|
Effect.flatMap((count) =>
|
|
count === 1
|
|
? Effect.succeed(makeBranchPullRequest("open"))
|
|
: Deferred.succeed(periodicLookupStarted, undefined).pipe(
|
|
Effect.andThen(Deferred.await(releasePeriodicLookup)),
|
|
Effect.as(makeBranchPullRequest("open")),
|
|
),
|
|
),
|
|
),
|
|
onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
|
|
});
|
|
|
|
yield* Effect.gen(function* () {
|
|
const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
|
|
yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
|
|
yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
|
|
yield* Deferred.await(periodicLookupStarted);
|
|
|
|
yield* fixture.publishMerge;
|
|
yield* Deferred.await(mergedThreadSettled);
|
|
|
|
assert.deepStrictEqual(
|
|
(yield* Ref.get(fixture.commands)).map((command) => command.threadId),
|
|
[ThreadId.make("merged-in-app")],
|
|
);
|
|
yield* Deferred.succeed(releasePeriodicLookup, undefined);
|
|
yield* reactor.drain;
|
|
}).pipe(Effect.provide(fixture.layer));
|
|
}),
|
|
),
|
|
);
|
|
|
|
it.effect(
|
|
"settles branch threads on a pull request merge without waiting for the next sweep",
|
|
() =>
|
|
Effect.scoped(
|
|
Effect.gen(function* () {
|
|
yield* TestClock.setTime(Date.parse(NOW));
|
|
const state = yield* Ref.make<"open" | "merged">("open");
|
|
const mergedThreadSettled = yield* Deferred.make<void>();
|
|
const fixture = yield* makeHarness({
|
|
snapshot: makeSnapshot([
|
|
makeThread("branch-thread", {
|
|
branch: "saved-feature",
|
|
latestUserMessageAt: "2026-08-27T00:00:00.000Z",
|
|
}),
|
|
]),
|
|
branchPullRequest: () =>
|
|
Ref.get(state).pipe(
|
|
Effect.map((pullRequestState) => makeBranchPullRequest(pullRequestState)),
|
|
),
|
|
onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
|
|
});
|
|
|
|
yield* Effect.gen(function* () {
|
|
const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
|
|
yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
|
|
assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
|
|
assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), []);
|
|
|
|
yield* Ref.set(state, "merged");
|
|
yield* fixture.publishMerge;
|
|
yield* Deferred.await(mergedThreadSettled);
|
|
|
|
assert.deepStrictEqual(
|
|
(yield* Ref.get(fixture.commands)).map((command) => command.threadId),
|
|
[ThreadId.make("branch-thread")],
|
|
);
|
|
assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), ["/workspace/project"]);
|
|
yield* reactor.drain;
|
|
}).pipe(Effect.provide(fixture.layer));
|
|
}),
|
|
),
|
|
);
|
|
|
|
it.effect("a merge does not settle threads linked to an unrelated pull request", () =>
|
|
Effect.scoped(
|
|
Effect.gen(function* () {
|
|
yield* TestClock.setTime(Date.parse(NOW));
|
|
const mergedThreadSettled = yield* Deferred.make<void>();
|
|
const mergeLookupStarted = yield* Deferred.make<void>();
|
|
const releaseMergeLookup = yield* Deferred.make<void>();
|
|
const lookupCount = yield* Ref.make(0);
|
|
const fixture = yield* makeHarness({
|
|
snapshot: makeSnapshot([
|
|
makeThread("merged-in-app", {
|
|
latestUserMessageAt: "2026-08-27T00:00:00.000Z",
|
|
linkedPullRequest: {
|
|
projectId: PROJECT_ID,
|
|
repository: "owner/repository",
|
|
number: 42,
|
|
url: "https://example.test/owner/repository/pull/42",
|
|
},
|
|
}),
|
|
makeThread("unrelated-linked", {
|
|
latestUserMessageAt: "2026-08-27T00:00:00.000Z",
|
|
linkedPullRequest: {
|
|
projectId: PROJECT_ID,
|
|
repository: "owner/repository",
|
|
number: 99,
|
|
url: "https://example.test/owner/repository/pull/99",
|
|
},
|
|
}),
|
|
]),
|
|
pullRequestSummary: (input) =>
|
|
Ref.updateAndGet(lookupCount, (count) => count + 1).pipe(
|
|
// The initial sweep looks up both linked threads; the merge
|
|
// sweep only looks up the unrelated one, since the merged
|
|
// thread settles from the event itself.
|
|
Effect.tap((count) =>
|
|
count === 3 ? Deferred.succeed(mergeLookupStarted, undefined) : Effect.void,
|
|
),
|
|
Effect.tap((count) =>
|
|
count === 3 ? Deferred.await(releaseMergeLookup) : Effect.void,
|
|
),
|
|
Effect.map(() => makePullRequestSummary({ ...input, state: "open" })),
|
|
),
|
|
onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
|
|
});
|
|
|
|
yield* Effect.gen(function* () {
|
|
const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
|
|
yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
|
|
assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
|
|
|
|
yield* fixture.publishMerge;
|
|
yield* Deferred.await(mergeLookupStarted);
|
|
yield* Deferred.await(mergedThreadSettled);
|
|
yield* Deferred.succeed(releaseMergeLookup, undefined);
|
|
yield* reactor.drain;
|
|
|
|
assert.deepStrictEqual(
|
|
(yield* Ref.get(fixture.commands)).map((command) => command.threadId),
|
|
[ThreadId.make("merged-in-app")],
|
|
);
|
|
assert.deepStrictEqual(
|
|
(yield* Ref.get(fixture.summaryCalls))
|
|
.map((call) => call.number)
|
|
.toSorted((left, right) => left - right),
|
|
[42, 99, 99],
|
|
);
|
|
}).pipe(Effect.provide(fixture.layer));
|
|
}),
|
|
),
|
|
);
|
|
|
|
it.effect("uses fresh settlement settings after lookup and ignores unrelated changes", () =>
|
|
Effect.scoped(
|
|
Effect.gen(function* () {
|
|
yield* TestClock.setTime(Date.parse(NOW));
|
|
const state = yield* Ref.make<"merged" | "closed">("merged");
|
|
const firstLookupStarted = yield* Deferred.make<void>();
|
|
const releaseFirstLookup = yield* Deferred.make<void>();
|
|
const laterLookupStarted = yield* Deferred.make<void>();
|
|
const releaseLaterLookup = yield* Deferred.make<void>();
|
|
const lookupCount = yield* Ref.make(0);
|
|
const fixture = yield* makeHarness({
|
|
snapshot: makeSnapshot([
|
|
makeThread("settings-thread", {
|
|
branch: "saved-feature",
|
|
latestUserMessageAt: "2026-08-28T00:00:00.000Z",
|
|
}),
|
|
]),
|
|
settings: {
|
|
...DEFAULT_SERVER_SETTINGS,
|
|
sidebarAutoSettleAfterDays: null,
|
|
sidebarAutoSettleOnMerge: true,
|
|
},
|
|
branchPullRequest: () =>
|
|
Ref.updateAndGet(lookupCount, (count) => count + 1).pipe(
|
|
Effect.tap((count) =>
|
|
count === 1
|
|
? Deferred.succeed(firstLookupStarted, undefined)
|
|
: count === 2
|
|
? Deferred.succeed(laterLookupStarted, undefined)
|
|
: Effect.void,
|
|
),
|
|
Effect.tap((count) =>
|
|
count === 1
|
|
? Deferred.await(releaseFirstLookup)
|
|
: count === 2
|
|
? Deferred.await(releaseLaterLookup)
|
|
: Effect.void,
|
|
),
|
|
Effect.andThen(Ref.get(state)),
|
|
Effect.map((pullRequestState) => makeBranchPullRequest(pullRequestState)),
|
|
),
|
|
});
|
|
|
|
yield* Effect.gen(function* () {
|
|
const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
|
|
yield* reactor.start();
|
|
yield* Deferred.succeed(fixture.activation, undefined);
|
|
yield* Queue.take(fixture.snapshotReads);
|
|
yield* Deferred.await(firstLookupStarted);
|
|
yield* Queue.clear(fixture.settingsReads);
|
|
|
|
yield* fixture.updateSettings({ sidebarAutoSettleOnMerge: false });
|
|
yield* Deferred.succeed(releaseFirstLookup, undefined);
|
|
// The in-flight decision and the newly queued sweep both read the disabled settings.
|
|
yield* Queue.take(fixture.settingsReads);
|
|
yield* Queue.take(fixture.settingsReads);
|
|
yield* reactor.drain;
|
|
assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
|
|
assert.strictEqual(yield* Ref.get(fixture.snapshotReadCount), 1);
|
|
|
|
yield* Ref.set(state, "closed");
|
|
yield* fixture.updateSettings({ enableAgentBrowserAccess: false });
|
|
yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 1 });
|
|
yield* Deferred.await(laterLookupStarted);
|
|
yield* Deferred.succeed(releaseLaterLookup, undefined);
|
|
yield* reactor.drain;
|
|
|
|
assert.strictEqual(yield* Ref.get(fixture.snapshotReadCount), 2);
|
|
assert.strictEqual(yield* Ref.get(lookupCount), 2);
|
|
assert.deepStrictEqual(
|
|
(yield* Ref.get(fixture.commands)).map((command) => command.threadId),
|
|
[ThreadId.make("settings-thread")],
|
|
);
|
|
}).pipe(Effect.provide(fixture.layer));
|
|
}),
|
|
),
|
|
);
|
|
|
|
it.effect("keeps an unknown pull request active and continues with other candidates", () =>
|
|
Effect.scoped(
|
|
Effect.gen(function* () {
|
|
yield* TestClock.setTime(Date.parse(NOW));
|
|
const fixture = yield* makeHarness({
|
|
snapshot: makeSnapshot(
|
|
[
|
|
makeThread("lookup-failed", {
|
|
latestUserMessageAt: "2026-08-27T00:00:00.000Z",
|
|
linkedPullRequest: {
|
|
projectId: LINKED_PROJECT_ID,
|
|
repository: "owner/repository",
|
|
number: 9,
|
|
url: "https://example.test/owner/repository/pull/9",
|
|
},
|
|
}),
|
|
makeThread("inactive-without-pr"),
|
|
],
|
|
[makeProject(), makeProject(LINKED_PROJECT_ID, "/workspace/linked")],
|
|
),
|
|
pullRequestSummary: () =>
|
|
Effect.fail(
|
|
new PullRequestOperationError({
|
|
operation: "summary",
|
|
detail: "host unavailable",
|
|
}),
|
|
),
|
|
});
|
|
|
|
yield* Effect.gen(function* () {
|
|
const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
|
|
yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
|
|
|
|
assert.deepStrictEqual(
|
|
(yield* Ref.get(fixture.commands)).map((command) => command.threadId),
|
|
[ThreadId.make("inactive-without-pr")],
|
|
);
|
|
assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
|
|
}).pipe(Effect.provide(fixture.layer));
|
|
}),
|
|
),
|
|
);
|
|
|
|
it.effect("settles inactive linked and branch threads without reading an unavailable host", () =>
|
|
Effect.scoped(
|
|
Effect.gen(function* () {
|
|
yield* TestClock.setTime(Date.parse(NOW));
|
|
const fixture = yield* makeHarness({
|
|
snapshot: makeSnapshot([
|
|
makeThread("inactive-linked", {
|
|
linkedPullRequest: {
|
|
projectId: PROJECT_ID,
|
|
repository: "owner/repository",
|
|
number: 42,
|
|
url: "https://example.test/owner/repository/pull/42",
|
|
},
|
|
}),
|
|
makeThread("inactive-branch", {
|
|
branch: "saved-feature",
|
|
latestUserMessageAt: "2026-08-21T00:00:00.000Z",
|
|
}),
|
|
]),
|
|
branchPullRequest: () => Effect.die(new Error("host unavailable")),
|
|
pullRequestSummary: () =>
|
|
Effect.fail(
|
|
new PullRequestOperationError({
|
|
operation: "summary",
|
|
detail: "host unavailable",
|
|
}),
|
|
),
|
|
});
|
|
|
|
yield* Effect.gen(function* () {
|
|
const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
|
|
yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
|
|
|
|
assert.deepStrictEqual(
|
|
(yield* Ref.get(fixture.commands))
|
|
.map(({ threadId, snapshotSequence, settledAt }) => ({
|
|
threadId,
|
|
snapshotSequence,
|
|
settledAt,
|
|
}))
|
|
.sort((left, right) => left.threadId.localeCompare(right.threadId)),
|
|
[
|
|
{
|
|
threadId: ThreadId.make("inactive-branch"),
|
|
snapshotSequence: 1,
|
|
settledAt: "2026-08-21T00:00:00.000Z",
|
|
},
|
|
{
|
|
threadId: ThreadId.make("inactive-linked"),
|
|
snapshotSequence: 1,
|
|
settledAt: "2026-08-20T00:00:00.000Z",
|
|
},
|
|
],
|
|
);
|
|
assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
|
|
assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), []);
|
|
}).pipe(Effect.provide(fixture.layer));
|
|
}),
|
|
),
|
|
);
|
|
|
|
it.effect("settles an inactive thread before its shared pull request lookup completes", () =>
|
|
Effect.scoped(
|
|
Effect.gen(function* () {
|
|
yield* TestClock.setTime(Date.parse(NOW));
|
|
const lookupStarted = yield* Deferred.make<void>();
|
|
const releaseLookup = yield* Deferred.make<void>();
|
|
const linkedPullRequest = {
|
|
projectId: PROJECT_ID,
|
|
repository: "owner/repository",
|
|
number: 42,
|
|
url: "https://example.test/owner/repository/pull/42",
|
|
} as const;
|
|
const fixture = yield* makeHarness({
|
|
snapshot: makeSnapshot([
|
|
makeThread("recent-linked", {
|
|
linkedPullRequest,
|
|
latestUserMessageAt: "2026-08-27T00:00:00.000Z",
|
|
}),
|
|
makeThread("inactive-linked", { linkedPullRequest }),
|
|
]),
|
|
pullRequestSummary: () =>
|
|
Deferred.succeed(lookupStarted, undefined).pipe(
|
|
Effect.andThen(Deferred.await(releaseLookup)),
|
|
Effect.andThen(
|
|
Effect.fail(
|
|
new PullRequestOperationError({
|
|
operation: "summary",
|
|
detail: "host unavailable",
|
|
}),
|
|
),
|
|
),
|
|
),
|
|
});
|
|
|
|
yield* Effect.gen(function* () {
|
|
const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
|
|
yield* reactor.start();
|
|
yield* Deferred.succeed(fixture.activation, undefined);
|
|
yield* Deferred.await(lookupStarted);
|
|
|
|
assert.deepStrictEqual(
|
|
(yield* Ref.get(fixture.commands)).map(({ threadId }) => threadId),
|
|
[ThreadId.make("inactive-linked")],
|
|
);
|
|
|
|
yield* Deferred.succeed(releaseLookup, undefined);
|
|
yield* reactor.drain;
|
|
assert.strictEqual((yield* Ref.get(fixture.commands)).length, 1);
|
|
assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
|
|
}).pipe(Effect.provide(fixture.layer));
|
|
}),
|
|
),
|
|
);
|
|
|
|
it.effect("keeps threads active when their pull request project is unavailable", () =>
|
|
Effect.scoped(
|
|
Effect.gen(function* () {
|
|
yield* TestClock.setTime(Date.parse(NOW));
|
|
const linkedPullRequest = {
|
|
projectId: LINKED_PROJECT_ID,
|
|
repository: "owner/repository",
|
|
number: 10,
|
|
url: "https://example.test/owner/repository/pull/10",
|
|
} as const;
|
|
const fixture = yield* makeHarness({
|
|
snapshot: makeSnapshot(
|
|
[
|
|
makeThread("missing-own-project", {
|
|
latestUserMessageAt: "2026-08-27T00:00:00.000Z",
|
|
linkedPullRequest,
|
|
}),
|
|
makeThread("missing-branch-project", {
|
|
branch: "saved-feature",
|
|
latestUserMessageAt: "2026-08-27T00:00:00.000Z",
|
|
}),
|
|
],
|
|
[makeProject(LINKED_PROJECT_ID, "/workspace/linked")],
|
|
),
|
|
pullRequestSummary: (input) =>
|
|
Effect.succeed(makePullRequestSummary({ ...input, state: "open" })),
|
|
});
|
|
|
|
yield* Effect.gen(function* () {
|
|
const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
|
|
yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
|
|
|
|
assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
|
|
assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
|
|
{ projectId: LINKED_PROJECT_ID, repository: "owner/repository", number: 10 },
|
|
]);
|
|
assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), []);
|
|
}).pipe(Effect.provide(fixture.layer));
|
|
}),
|
|
),
|
|
);
|
|
|
|
it.effect("deduplicates saved-branch and linked pull request lookups within a sweep", () =>
|
|
Effect.scoped(
|
|
Effect.gen(function* () {
|
|
yield* TestClock.setTime(Date.parse(NOW));
|
|
const linkedPullRequest = {
|
|
projectId: LINKED_PROJECT_ID,
|
|
repository: "owner/repository",
|
|
number: 77,
|
|
url: "https://example.test/owner/repository/pull/77",
|
|
} as const;
|
|
const fixture = yield* makeHarness({
|
|
snapshot: makeSnapshot(
|
|
[
|
|
makeThread("branch-one", {
|
|
branch: "saved-feature",
|
|
worktreePath: "/deleted/worktree-one",
|
|
latestUserMessageAt: "2026-08-27T00:00:00.000Z",
|
|
}),
|
|
makeThread("branch-two", {
|
|
branch: "saved-feature",
|
|
worktreePath: "/deleted/worktree-two",
|
|
latestUserMessageAt: "2026-08-27T00:00:00.000Z",
|
|
}),
|
|
makeThread("linked-one", {
|
|
linkedPullRequest,
|
|
latestUserMessageAt: "2026-08-27T00:00:00.000Z",
|
|
}),
|
|
makeThread("linked-two", {
|
|
linkedPullRequest,
|
|
latestUserMessageAt: "2026-08-27T00:00:00.000Z",
|
|
}),
|
|
],
|
|
[
|
|
makeProject(PROJECT_ID, "/workspace/project-root"),
|
|
makeProject(LINKED_PROJECT_ID, "/workspace/linked-root"),
|
|
],
|
|
),
|
|
branchPullRequest: () => Effect.succeed(makeBranchPullRequest("closed")),
|
|
pullRequestSummary: (input) =>
|
|
Effect.succeed(makePullRequestSummary({ ...input, state: "merged" })),
|
|
});
|
|
|
|
yield* Effect.gen(function* () {
|
|
const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
|
|
yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
|
|
|
|
assert.deepStrictEqual(yield* Ref.get(fixture.branchCalls), [
|
|
{ cwd: "/workspace/project-root", branch: "saved-feature" },
|
|
]);
|
|
assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
|
|
{ projectId: LINKED_PROJECT_ID, repository: "owner/repository", number: 77 },
|
|
]);
|
|
assert.deepStrictEqual(
|
|
new Set((yield* Ref.get(fixture.commands)).map((command) => command.threadId)),
|
|
new Set([
|
|
ThreadId.make("branch-one"),
|
|
ThreadId.make("branch-two"),
|
|
ThreadId.make("linked-one"),
|
|
ThreadId.make("linked-two"),
|
|
]),
|
|
);
|
|
}).pipe(Effect.provide(fixture.layer));
|
|
}),
|
|
),
|
|
);
|
|
|
|
it.effect("looks up the branch pull request from a thread's live worktree", () =>
|
|
Effect.scoped(
|
|
Effect.gen(function* () {
|
|
yield* TestClock.setTime(Date.parse(NOW));
|
|
const fixture = yield* makeHarness({
|
|
snapshot: makeSnapshot(
|
|
[
|
|
makeThread("live-worktree", {
|
|
branch: "feature/live",
|
|
worktreePath: "/workspace/project-root/.worktrees/live",
|
|
latestUserMessageAt: "2026-08-27T00:00:00.000Z",
|
|
}),
|
|
makeThread("deleted-worktree", {
|
|
branch: "feature/deleted",
|
|
worktreePath: "/workspace/project-root/.worktrees/deleted",
|
|
latestUserMessageAt: "2026-08-27T00:00:00.000Z",
|
|
}),
|
|
],
|
|
[makeProject(PROJECT_ID, "/workspace/project-root")],
|
|
),
|
|
existingWorktreePaths: ["/workspace/project-root/.worktrees/live"],
|
|
});
|
|
|
|
yield* Effect.gen(function* () {
|
|
const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
|
|
yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
|
|
|
|
assert.deepStrictEqual(
|
|
new Set(yield* Ref.get(fixture.branchCalls)),
|
|
new Set([
|
|
{ cwd: "/workspace/project-root/.worktrees/live", branch: "feature/live" },
|
|
{ cwd: "/workspace/project-root", branch: "feature/deleted" },
|
|
]),
|
|
);
|
|
}).pipe(Effect.provide(fixture.layer));
|
|
}),
|
|
),
|
|
);
|
|
|
|
it.effect("carries the snapshot guard and survives a stale dispatch rejection", () =>
|
|
Effect.scoped(
|
|
Effect.gen(function* () {
|
|
yield* TestClock.setTime(Date.parse(NOW));
|
|
const fixture = yield* makeHarness({
|
|
snapshot: makeSnapshot([makeThread("stale"), makeThread("next-candidate")]),
|
|
onDispatch: (command) =>
|
|
command.threadId === ThreadId.make("stale")
|
|
? Effect.fail(
|
|
new OrchestrationCommandInvariantError({
|
|
commandType: command.type,
|
|
detail: "thread changed after settlement evaluation",
|
|
}),
|
|
)
|
|
: Effect.void,
|
|
});
|
|
|
|
yield* Effect.gen(function* () {
|
|
const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;
|
|
yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
|
|
|
|
const firstSweep = yield* Ref.get(fixture.commands);
|
|
assert.strictEqual(
|
|
firstSweep.find((command) => command.threadId === ThreadId.make("stale"))
|
|
?.snapshotSequence,
|
|
1,
|
|
);
|
|
assert.strictEqual(
|
|
firstSweep.some((command) => command.threadId === ThreadId.make("next-candidate")),
|
|
true,
|
|
);
|
|
|
|
yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
|
|
yield* Queue.take(fixture.snapshotReads);
|
|
yield* reactor.drain;
|
|
assert.strictEqual((yield* Ref.get(fixture.commands)).length, 4);
|
|
}).pipe(Effect.provide(fixture.layer));
|
|
}),
|
|
),
|
|
);
|
|
});
|
|
|
|
describe("storage cleanup", () => {
|
|
it.effect("serializes users of one workspace while other workspaces can start", () =>
|
|
Effect.gen(function* () {
|
|
const releaseCleanup = yield* Deferred.make<void>();
|
|
const providerEntered = yield* Deferred.make<void>();
|
|
const cleanup = yield* withWorkspaceLease(
|
|
"/workspace/shared",
|
|
Deferred.await(releaseCleanup),
|
|
).pipe(Effect.forkScoped({ startImmediately: true }));
|
|
const provider = yield* withWorkspaceLease(
|
|
"/workspace/shared",
|
|
Deferred.succeed(providerEntered, undefined),
|
|
).pipe(Effect.forkScoped({ startImmediately: true }));
|
|
assert.strictEqual(yield* Deferred.isDone(providerEntered), false);
|
|
yield* withWorkspaceLease("/workspace/other", Effect.void);
|
|
yield* Deferred.succeed(releaseCleanup, undefined);
|
|
yield* Fiber.join(cleanup);
|
|
yield* Fiber.join(provider);
|
|
assert.strictEqual(yield* Deferred.isDone(providerEntered), true);
|
|
}).pipe(Effect.scoped),
|
|
);
|
|
|
|
for (const protection of [
|
|
"none",
|
|
"dirty",
|
|
"ignored",
|
|
"ignored-directory",
|
|
"shared",
|
|
"project-root",
|
|
"nested-project",
|
|
"new-nested-project",
|
|
"session",
|
|
"terminal-cwd",
|
|
"terminal-worktree",
|
|
"recent",
|
|
"merged",
|
|
"unmerged",
|
|
"unchanged",
|
|
"unchanged-two-worktrees",
|
|
"diverged",
|
|
"head-moved",
|
|
"deleted",
|
|
"deleted-event",
|
|
"deleted-dirty",
|
|
"deleted-ignored",
|
|
"deleted-shared",
|
|
"deleted-project",
|
|
"deleted-owner",
|
|
"deleted-owner-root",
|
|
"deleted-owner-nested",
|
|
"deleted-provider",
|
|
"project-off",
|
|
"project-custom",
|
|
"project-policy-disabled",
|
|
"deleted-project-custom",
|
|
"deleted-project-off",
|
|
"policy-disabled",
|
|
"policy-extended",
|
|
"files-disabled",
|
|
"files-extended",
|
|
] as const) {
|
|
it.effect(
|
|
`retains protected worktrees (${protection}) and expires only old artifacts and rotated logs`,
|
|
() =>
|
|
Effect.gen(function* () {
|
|
yield* TestClock.setTime(Date.parse(NOW));
|
|
const fs = yield* FileSystem.FileSystem;
|
|
const path = yield* Path.Path;
|
|
const config = yield* ServerConfig;
|
|
const worktreePath = path.join(config.worktreesDir, "feature");
|
|
yield* fs.makeDirectory(worktreePath, { recursive: true });
|
|
yield* fs.writeFileString(path.join(worktreePath, ".git"), "gitdir: /test/admin");
|
|
const secondWorktreePath = path.join(config.worktreesDir, "feature-two");
|
|
if (protection === "unchanged-two-worktrees") {
|
|
yield* fs.makeDirectory(secondWorktreePath);
|
|
yield* fs.writeFileString(
|
|
path.join(secondWorktreePath, ".git"),
|
|
"gitdir: /test/admin-two",
|
|
);
|
|
}
|
|
if (protection === "ignored" || protection === "deleted-ignored")
|
|
yield* fs.writeFileString(path.join(worktreePath, ".env"), "secret");
|
|
if (protection === "ignored-directory") {
|
|
yield* fs.makeDirectory(path.join(worktreePath, ".cache"));
|
|
yield* fs.writeFileString(path.join(worktreePath, ".cache", "local-data"), "keep");
|
|
}
|
|
yield* fs.makeDirectory(config.browserArtifactsDir, { recursive: true });
|
|
const oldImage = path.join(config.browserArtifactsDir, "old.png");
|
|
const recentImage = path.join(config.browserArtifactsDir, "recent.png");
|
|
const oldLog = path.join(config.logsDir, "server.log.1");
|
|
const activeLog = path.join(config.logsDir, "server.log");
|
|
const old = DateTime.toDateUtc(DateTime.makeUnsafe("2026-08-01T00:00:00.000Z"));
|
|
for (const file of [oldImage, oldLog, activeLog]) {
|
|
yield* fs.writeFileString(file, "keep or remove");
|
|
yield* fs.utimes(file, old, old);
|
|
}
|
|
yield* fs.writeFileString(recentImage, "recent");
|
|
const recent = DateTime.toDateUtc(DateTime.makeUnsafe(NOW));
|
|
yield* fs.utimes(recentImage, recent, recent);
|
|
const thread = makeThread("storage-thread", {
|
|
branch: "feature",
|
|
worktreePath,
|
|
latestUserMessageAt:
|
|
protection === "recent" ? "2026-08-26T00:00:00.000Z" : "2026-08-01T00:00:00.000Z",
|
|
...(protection === "session"
|
|
? {
|
|
session: {
|
|
threadId: ThreadId.make("storage-thread"),
|
|
status: "ready",
|
|
providerName: "codex",
|
|
runtimeMode: "full-access",
|
|
activeTurnId: null,
|
|
lastError: null,
|
|
updatedAt: NOW,
|
|
},
|
|
}
|
|
: {}),
|
|
});
|
|
const snapshotRead = yield* Deferred.make<void>();
|
|
const deletionStarted = yield* Deferred.make<void>();
|
|
const deletionStopped = yield* Deferred.make<void>();
|
|
if (protection !== "deleted-event") yield* Deferred.succeed(deletionStopped, undefined);
|
|
const domainEvents = yield* PubSub.unbounded<OrchestrationEvent>();
|
|
const deleteRule = protection.startsWith("deleted");
|
|
let tombstoned = deleteRule && protection !== "deleted-event";
|
|
const removals: string[] = [];
|
|
const mergeRule = protection === "merged" || protection === "unmerged";
|
|
const unchangedRule =
|
|
protection === "unchanged" ||
|
|
protection === "unchanged-two-worktrees" ||
|
|
protection === "diverged" ||
|
|
protection === "head-moved";
|
|
let headReads = 0;
|
|
let snapshotReads = 0;
|
|
let defaultRefFetched = false;
|
|
let fetches = 0;
|
|
const settingsService = yield* ServerSettingsService.pipe(
|
|
Effect.provide(
|
|
ServerSettingsService.layerTest({
|
|
projectSettingsOverrides: {
|
|
[PROJECT_ID]:
|
|
protection === "project-off" || protection === "deleted-project-off"
|
|
? { worktreeCleanup: { mode: "off" as const } }
|
|
: protection === "project-custom" || protection === "deleted-project-custom"
|
|
? {
|
|
worktreeCleanup: {
|
|
mode: "custom" as const,
|
|
rules: {
|
|
worktreeAfterDays: protection === "project-custom" ? 8 : null,
|
|
worktreeOnDelete: deleteRule,
|
|
worktreeOnMerge: false,
|
|
worktreeUnchanged: false,
|
|
},
|
|
},
|
|
}
|
|
: {},
|
|
},
|
|
storageCleanup: {
|
|
worktreeAfterDays:
|
|
deleteRule || mergeRule || unchangedRule || protection === "project-custom"
|
|
? null
|
|
: 8,
|
|
worktreeOnDelete: deleteRule && protection !== "deleted-project-custom",
|
|
worktreeOnMerge: mergeRule,
|
|
worktreeUnchanged: unchangedRule,
|
|
browserArtifactsAfterDays: 8,
|
|
logsAfterDays: 8,
|
|
},
|
|
}),
|
|
),
|
|
);
|
|
const cleanup = yield* StorageCleanup.make.pipe(
|
|
Effect.provide(
|
|
Layer.mergeAll(
|
|
Layer.succeed(ServerSettingsService, settingsService),
|
|
Layer.succeed(FileSystem.FileSystem, {
|
|
...fs,
|
|
stat: (target) =>
|
|
fs.stat(target).pipe(
|
|
Effect.tap(() => {
|
|
if (
|
|
!protection.startsWith("files-") ||
|
|
(target !== oldImage && target !== oldLog)
|
|
)
|
|
return Effect.void;
|
|
return settingsService
|
|
.updateSettings({
|
|
storageCleanup: {
|
|
[target === oldImage ? "browserArtifactsAfterDays" : "logsAfterDays"]:
|
|
protection === "files-disabled" ? null : 60,
|
|
},
|
|
})
|
|
.pipe(Effect.orDie);
|
|
}),
|
|
),
|
|
}),
|
|
Layer.mock(ProjectionSnapshotQuery)({
|
|
getDeletedWorktreeThreads: () =>
|
|
Effect.succeed(
|
|
tombstoned
|
|
? [
|
|
{
|
|
id: thread.id,
|
|
projectId: thread.projectId,
|
|
branch: "feature",
|
|
worktreePath,
|
|
workspaceRoot:
|
|
protection === "deleted-owner-root"
|
|
? worktreePath
|
|
: protection === "deleted-owner-nested"
|
|
? path.join(worktreePath, "nested")
|
|
: config.baseDir,
|
|
deletedAt: NOW,
|
|
},
|
|
]
|
|
: [],
|
|
),
|
|
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 2 }),
|
|
getShellSnapshot: () =>
|
|
Deferred.succeed(snapshotRead, undefined).pipe(
|
|
Effect.andThen(
|
|
Effect.sync(() => {
|
|
snapshotReads++;
|
|
const projects =
|
|
protection.startsWith("deleted-owner") ||
|
|
protection === "deleted-project-off" ||
|
|
protection === "deleted-project-custom"
|
|
? []
|
|
: [makeProject(PROJECT_ID, config.baseDir)];
|
|
const threads = tombstoned ? [] : [thread];
|
|
if (protection === "deleted-shared")
|
|
threads.push({ ...thread, id: ThreadId.make("surviving-thread") });
|
|
if (protection === "deleted-project")
|
|
projects.push(makeProject(LINKED_PROJECT_ID, worktreePath));
|
|
if (
|
|
protection === "project-root" ||
|
|
protection === "nested-project" ||
|
|
(protection === "new-nested-project" && snapshotReads > 1)
|
|
) {
|
|
projects.push(
|
|
makeProject(
|
|
LINKED_PROJECT_ID,
|
|
protection === "project-root"
|
|
? worktreePath
|
|
: path.join(worktreePath, "nested"),
|
|
),
|
|
);
|
|
threads.push(
|
|
makeThread("local-project-thread", { projectId: LINKED_PROJECT_ID }),
|
|
);
|
|
}
|
|
if (protection === "unchanged-two-worktrees") {
|
|
threads.push({
|
|
...thread,
|
|
id: ThreadId.make("second-worktree-thread"),
|
|
branch: "feature-two",
|
|
worktreePath: secondWorktreePath,
|
|
});
|
|
}
|
|
return makeSnapshot(threads, projects);
|
|
}),
|
|
),
|
|
),
|
|
getArchivedShellSnapshot: () =>
|
|
Effect.succeed(
|
|
makeSnapshot(
|
|
protection === "shared"
|
|
? [
|
|
{
|
|
...thread,
|
|
id: ThreadId.make("archived-sharing-thread"),
|
|
archivedAt: NOW,
|
|
},
|
|
]
|
|
: [],
|
|
),
|
|
),
|
|
}),
|
|
Layer.mock(GitManager)({
|
|
invalidateStatus: () => Effect.void,
|
|
branchPullRequest: (_input, options) => {
|
|
assert.strictEqual(options?.refresh, true);
|
|
return Effect.succeed(
|
|
makeBranchPullRequest(protection === "unmerged" ? "open" : "merged"),
|
|
);
|
|
},
|
|
}),
|
|
Layer.mock(OrchestrationEngineService)({
|
|
subscribeDomainEvents: PubSub.subscribe(domainEvents).pipe(
|
|
Effect.map((subscription) => Stream.fromSubscription(subscription)),
|
|
),
|
|
}),
|
|
Layer.mock(ThreadDeletionReactor)({
|
|
drainThrough: (sequence) => {
|
|
assert.strictEqual(sequence, 2);
|
|
return Deferred.succeed(deletionStarted, undefined).pipe(
|
|
Effect.andThen(Deferred.await(deletionStopped)),
|
|
);
|
|
},
|
|
}),
|
|
Layer.mock(ProviderService)({
|
|
listSessions: () =>
|
|
Effect.succeed(
|
|
protection === "deleted-provider"
|
|
? [
|
|
{
|
|
threadId: thread.id,
|
|
provider: ProviderDriverKind.make("codex"),
|
|
status: "ready",
|
|
runtimeMode: "full-access",
|
|
cwd: worktreePath,
|
|
createdAt: NOW,
|
|
updatedAt: NOW,
|
|
},
|
|
]
|
|
: [],
|
|
),
|
|
}),
|
|
Layer.mock(GitVcsDriver)({
|
|
resolvePrimaryRemoteName: () => Effect.succeed("origin"),
|
|
resolveDefaultBranchName: () => Effect.succeed("main"),
|
|
fetchRemoteTrackingBranch: (input) =>
|
|
Effect.sync(() => {
|
|
assert.deepStrictEqual(input, {
|
|
cwd: config.baseDir,
|
|
remoteName: "origin",
|
|
remoteBranch: "main",
|
|
});
|
|
defaultRefFetched = true;
|
|
fetches++;
|
|
}),
|
|
resolveCommit: ({ revision }) =>
|
|
Effect.sync(() => {
|
|
if (revision !== "HEAD")
|
|
return { commitSha: (defaultRefFetched ? "b" : "d").repeat(40) };
|
|
headReads++;
|
|
return {
|
|
commitSha:
|
|
protection === "head-moved" && headReads > 1
|
|
? "c".repeat(40)
|
|
: "a".repeat(40),
|
|
};
|
|
}),
|
|
statusDetailsLocal: (cwd) =>
|
|
Effect.succeed({
|
|
isRepo: true,
|
|
hasOriginRemote: false,
|
|
isDefaultBranch: false,
|
|
branch: cwd === secondWorktreePath ? "feature-two" : "feature",
|
|
upstreamRef: null,
|
|
hasWorkingTreeChanges:
|
|
protection === "dirty" || protection === "deleted-dirty",
|
|
workingTree: { files: [], insertions: 0, deletions: 0 },
|
|
hasUpstream: false,
|
|
aheadCount: 0,
|
|
behindCount: 0,
|
|
aheadOfDefaultCount: 0,
|
|
}),
|
|
execute: (input) =>
|
|
Effect.succeed({
|
|
exitCode: ChildProcessSpawner.ExitCode(
|
|
input.operation === "StorageCleanup.integratedBranch" &&
|
|
(protection === "diverged" || input.args.at(-1) !== "b".repeat(40))
|
|
? 1
|
|
: 0,
|
|
),
|
|
stdout:
|
|
protection === "ignored" || protection === "deleted-ignored"
|
|
? ".env\0"
|
|
: protection === "ignored-directory"
|
|
? ".cache/\0"
|
|
: "",
|
|
stderr: "",
|
|
stdoutTruncated: false,
|
|
stderrTruncated: false,
|
|
}).pipe(
|
|
Effect.tap(() =>
|
|
(protection.startsWith("policy-") ||
|
|
protection === "project-policy-disabled") &&
|
|
headReads > 1
|
|
? settingsService
|
|
.updateSettings({
|
|
...(protection === "project-policy-disabled"
|
|
? {
|
|
projectSettingsOverrides: {
|
|
[PROJECT_ID]: { worktreeCleanup: { mode: "off" as const } },
|
|
},
|
|
}
|
|
: {}),
|
|
...(protection === "project-policy-disabled"
|
|
? {}
|
|
: {
|
|
storageCleanup: {
|
|
worktreeAfterDays:
|
|
protection === "policy-disabled" ? null : 60,
|
|
},
|
|
}),
|
|
})
|
|
.pipe(Effect.orDie)
|
|
: Effect.void,
|
|
),
|
|
),
|
|
removeWorktree: (input) => {
|
|
assert.strictEqual(input.force, false);
|
|
removals.push(input.path);
|
|
return fs.remove(input.path, { recursive: true }).pipe(Effect.orDie);
|
|
},
|
|
}),
|
|
Layer.mock(TerminalManager)({
|
|
subscribeMetadata: (listener) =>
|
|
listener({
|
|
type: "snapshot",
|
|
terminals:
|
|
protection === "terminal-cwd" || protection === "terminal-worktree"
|
|
? [
|
|
{
|
|
threadId: "terminal-thread",
|
|
terminalId: "default",
|
|
cwd:
|
|
protection === "terminal-cwd"
|
|
? `${worktreePath}${path.sep}`
|
|
: config.baseDir,
|
|
worktreePath:
|
|
protection === "terminal-worktree"
|
|
? `${worktreePath}${path.sep}`
|
|
: null,
|
|
status: "running",
|
|
pid: 42,
|
|
exitCode: null,
|
|
exitSignal: null,
|
|
hasRunningSubprocess: false,
|
|
label: "shell",
|
|
updatedAt: NOW,
|
|
},
|
|
]
|
|
: [],
|
|
}).pipe(Effect.as(() => {})),
|
|
}),
|
|
),
|
|
),
|
|
);
|
|
yield* cleanup.start();
|
|
yield* Deferred.await(snapshotRead);
|
|
yield* cleanup.drain;
|
|
if (protection === "deleted-event") {
|
|
assert.strictEqual(yield* fs.exists(worktreePath), true);
|
|
tombstoned = true;
|
|
yield* PubSub.publish(domainEvents, {
|
|
type: "thread.deleted",
|
|
sequence: 2,
|
|
eventId: EventId.make("storage-thread-deleted"),
|
|
aggregateKind: "thread",
|
|
aggregateId: thread.id,
|
|
occurredAt: NOW,
|
|
commandId: null,
|
|
causationEventId: null,
|
|
correlationId: null,
|
|
metadata: {},
|
|
payload: { threadId: thread.id, deletedAt: NOW },
|
|
});
|
|
yield* Deferred.await(deletionStarted);
|
|
assert.strictEqual(yield* fs.exists(worktreePath), true);
|
|
yield* Deferred.succeed(deletionStopped, undefined);
|
|
yield* cleanup.drain;
|
|
}
|
|
const removed =
|
|
protection === "project-custom" ||
|
|
protection === "deleted-project-custom" ||
|
|
protection === "none" ||
|
|
protection === "deleted" ||
|
|
protection === "deleted-event" ||
|
|
protection === "deleted-owner" ||
|
|
protection === "files-disabled" ||
|
|
protection === "files-extended" ||
|
|
protection === "merged" ||
|
|
protection === "unchanged" ||
|
|
protection === "unchanged-two-worktrees";
|
|
assert.strictEqual(yield* fs.exists(worktreePath), !removed);
|
|
assert.deepStrictEqual(
|
|
removals,
|
|
protection === "unchanged-two-worktrees"
|
|
? [worktreePath, secondWorktreePath]
|
|
: removed
|
|
? [worktreePath]
|
|
: [],
|
|
);
|
|
assert.strictEqual(fetches, mergeRule || unchangedRule ? 1 : 0);
|
|
assert.strictEqual(thread.worktreePath, worktreePath);
|
|
assert.strictEqual(thread.branch, "feature");
|
|
assert.strictEqual(yield* fs.exists(oldImage), protection.startsWith("files-"));
|
|
assert.strictEqual(yield* fs.exists(recentImage), true);
|
|
assert.strictEqual(yield* fs.exists(oldLog), protection.startsWith("files-"));
|
|
assert.strictEqual(yield* fs.exists(activeLog), true);
|
|
}).pipe(
|
|
Effect.provide(
|
|
ServerConfig.layerTest(process.cwd(), { prefix: "t3-storage-cleanup-" }).pipe(
|
|
Layer.provideMerge(NodeServices.layer),
|
|
),
|
|
),
|
|
Effect.scoped,
|
|
),
|
|
);
|
|
}
|
|
});
|