TypeScript
perf(server): background sweeps only read threads that can still settle (#13765)
Theo Browne1d6f23b51929
diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.tsindex b80e1372681..cfba9029763 100644--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts@@ -3643,6 +3643,85 @@ it.effect("reads one sweep thread and its projects like the shell snapshot", ()}).pipe(Effect.provide(layer));});+it.effect("reads a full sweep from unsettled threads and every project", () => {+ const resolved: string[] = [];+ const layer = OrchestrationProjectionSnapshotQueryLive.pipe(+ Layer.provide(ThreadBackgroundLiveness.layer),+ Layer.provide(ThreadPlanProgress.layer),+ Layer.provide(+ Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, {+ resolve: (root) =>+ Effect.sync(() => {+ resolved.push(root);+ return null;+ }),+ }),+ ),+ Layer.provideMerge(SqlitePersistenceMemory),+ );+ return Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;+ const query = yield* ProjectionSnapshotQuery;+ yield* sql`INSERT INTO projection_projects (project_id, title, workspace_root, scripts_json, created_at, updated_at)+ VALUES ('p1', 'One', '/one', '[]', '2026-09-01T00:00:00Z', '2026-09-01T00:00:00Z'),+ ('p2', 'Two', '/two', '[]', '2026-09-02T00:00:00Z', '2026-09-02T00:00:00Z'),+ ('p3', 'Three', '/three', '[]', '2026-09-03T00:00:00Z', '2026-09-03T00:00:00Z'),+ ('p4', 'Four', '/four', '[]', '2026-09-04T00:00:00Z', '2026-09-04T00:00:00Z')`;+ yield* sql`INSERT INTO projection_threads (thread_id, project_id, title, model_selection_json, runtime_mode, interaction_mode, branch_pull_request_json, latest_turn_id, created_at, updated_at, archived_at, settled_override, settled_at)+ VALUES+ ('t-open', 'p1', 'Open', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', NULL, 'turn-open', '2026-09-01T00:00:00Z', '2026-09-01T00:00:00Z', NULL, NULL, NULL),+ ('t-resumed', 'p1', 'Resumed', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', NULL, NULL, '2026-09-01T00:00:00Z', '2026-09-01T00:00:00Z', NULL, 'active', NULL),+ ('t-branch', 'p1', 'Branch', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default',+ '{"projectId":"p2","repository":"acme/web","number":8,"url":"https://github.com/acme/web/pull/8"}',+ NULL, '2026-09-01T00:00:00Z', '2026-09-01T00:00:00Z', NULL, NULL, NULL),+ ('t-settled', 'p3', 'Settled', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', NULL, 'turn-settled', '2026-09-01T00:00:00Z', '2026-09-01T00:00:00Z', NULL, 'settled', '2026-09-03T00:00:00Z'),+ ('t-archived', 'p4', 'Archived', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', NULL, NULL, '2026-09-01T00:00:00Z', '2026-09-01T00:00:00Z', '2026-09-04T00:00:00Z', NULL, NULL)`;+ // The open and the settled thread both have a row in each joined table. The+ // settled thread's turn and session are the newest rows, so updatedAt shows+ // whether those two reads skip it.+ yield* sql`INSERT INTO projection_thread_pull_requests (thread_id, host, repository, number, url, source, linked_at)+ VALUES ('t-open', 'github.com', 'acme/web', 7, 'https://github.com/acme/web/pull/7', 'agent', '2026-09-02T00:00:00Z'),+ ('t-settled', 'github.com', 'acme/web', 9, 'https://github.com/acme/web/pull/9', 'agent', '2026-09-02T00:00:00Z')`;+ yield* sql`INSERT INTO projection_turns (thread_id, turn_id, state, requested_at, checkpoint_files_json)+ VALUES ('t-open', 'turn-open', 'completed', '2026-09-02T00:00:00Z', '[]'),+ ('t-settled', 'turn-settled', 'completed', '2026-09-09T00:00:00Z', '[]')`;+ yield* sql`INSERT INTO projection_thread_sessions (thread_id, status, provider_name, active_turn_id, last_error, updated_at)+ VALUES ('t-open', 'ready', 'codex', NULL, NULL, '2026-09-02T00:00:00Z'),+ ('t-settled', 'stopped', 'codex', NULL, NULL, '2026-09-10T00:00:00Z')`;++ const full = yield* query.getShellSnapshot();+ // The settled thread's rows must reach the full read, or skipping them proves nothing.+ const settled = full.threads.find((thread) => thread.id === ThreadId.make("t-settled"));+ assert.strictEqual(settled?.pullRequests[0]?.number, 9);+ assert.strictEqual(settled?.latestTurn?.turnId, asTurnId("turn-settled"));+ assert.strictEqual(settled?.session?.status, "stopped");+ assert.strictEqual(full.updatedAt, "2026-09-10T00:00:00Z");+ resolved.length = 0;++ const sweep = yield* readSweepSnapshot(query, null);+ assert.strictEqual(sweep.snapshotSequence, full.snapshotSequence);+ assert.deepStrictEqual(+ sweep.threads,+ full.threads.filter((thread) => thread.id !== ThreadId.make("t-settled")),+ );+ assert.deepStrictEqual(+ sweep.threads.map((thread) => thread.id),+ ["t-branch", "t-open", "t-resumed"],+ );+ // Like the full read, the sweep resolves every project, so it keeps the+ // repository identity cache warm for client connects.+ assert.deepStrictEqual(sweep.projects, full.projects);+ assert.deepStrictEqual(resolved.toSorted(), ["/four", "/one", "/three", "/two"]);+ // A settled thread's link that no longer decodes breaks the full read, but+ // not the sweep, which never reads it.+ yield* sql`UPDATE projection_thread_pull_requests SET snapshot_json = 'invalid-json' WHERE thread_id = 't-settled'`;+ assert.strictEqual((yield* Effect.exit(query.getShellSnapshot()))._tag, "Failure");+ const unsettled = yield* query.getShellSnapshot({ unsettledOnly: true });+ assert.deepStrictEqual(unsettled.threads, sweep.threads);+ assert.strictEqual(unsettled.updatedAt, "2026-09-04T00:00:00Z");+ }).pipe(Effect.provide(layer));+});+projectionSnapshotLayer("ProjectionSnapshotQuery activities by kind", (it) => {it.effect("lists one kind across active threads only, without hydrating the threads", () =>Effect.gen(function* () {diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.tsindex 71ef1ad9732..07d30e47e27 100644--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts@@ -185,6 +185,7 @@ const EventReplayStatsRowSchema = Schema.Struct({eventCount: Schema.Number,payloadBytes: Schema.Number,});+const ActiveThreadRowsRequest = Schema.Struct({ unsettledOnly: Schema.Boolean });const ProjectionThreadSearchRequest = Schema.Struct({pattern: Schema.String,limit: Schema.Int,@@ -600,10 +601,16 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {`,});+ // Background sweeps skip settled threads, the same check PR discovery makes.+ const unsettledThreadsFilter = (unsettledOnly: boolean) =>+ unsettledOnly+ ? sql`AND threads.settled_at IS NULL AND threads.settled_override IS NOT 'settled'`+ : sql``;+const listActiveThreadRows = SqlSchema.findAll({- Request: Schema.Void,+ Request: ActiveThreadRowsRequest,Result: ProjectionThreadDbRowSchema,- execute: () =>+ execute: (request) =>sql`SELECTthread_id AS "threadId",@@ -637,9 +644,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {pending_user_input_count AS "pendingUserInputCount",has_actionable_proposed_plan AS "hasActionableProposedPlan",deleted_at AS "deletedAt"- FROM projection_threads+ FROM projection_threads threadsWHERE deleted_at IS NULLAND archived_at IS NULL+ ${unsettledThreadsFilter(request.unsettledOnly)}ORDER BY project_id ASC, created_at ASC, thread_id ASC`,});@@ -779,9 +787,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {});const listActiveThreadPullRequestRows = SqlSchema.findAll({- Request: Schema.Void,+ Request: ActiveThreadRowsRequest,Result: ProjectionThreadPullRequestDbRowSchema,- execute: () =>+ execute: (request) =>sql`SELECTlinks.thread_id AS "threadId",@@ -798,6 +806,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {ON threads.thread_id = links.thread_idWHERE threads.deleted_at IS NULLAND threads.archived_at IS NULL+ ${unsettledThreadsFilter(request.unsettledOnly)}ORDER BY links.thread_id ASC, links.linked_at ASC, links.number ASC`,});@@ -907,9 +916,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {});const listActiveThreadSessionRows = SqlSchema.findAll({- Request: Schema.Void,+ Request: ActiveThreadRowsRequest,Result: ProjectionThreadSessionDbRowSchema,- execute: () =>+ execute: (request) =>sql`SELECTsessions.thread_id AS "threadId",@@ -927,6 +936,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {ON threads.thread_id = sessions.thread_idWHERE threads.deleted_at IS NULLAND threads.archived_at IS NULL+ ${unsettledThreadsFilter(request.unsettledOnly)}ORDER BY sessions.thread_id ASC`,});@@ -1001,9 +1011,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {});const listActiveLatestTurnRows = SqlSchema.findAll({- Request: Schema.Void,+ Request: ActiveThreadRowsRequest,Result: ProjectionLatestTurnDbRowSchema,- execute: () =>+ execute: (request) =>sql`SELECTturns.thread_id AS "threadId",@@ -1022,6 +1032,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {WHERE threads.deleted_at IS NULLAND threads.archived_at IS NULLAND threads.latest_turn_id IS NOT NULL+ ${unsettledThreadsFilter(request.unsettledOnly)}ORDER BY turns.thread_id ASC`,});@@ -2654,8 +2665,9 @@ pending_approval_requests AS (}),);- const getShellSnapshot: ProjectionSnapshotQueryShape["getShellSnapshot"] = () =>- sql+ const getShellSnapshot: ProjectionSnapshotQueryShape["getShellSnapshot"] = (options) => {+ const unsettledOnly = options?.unsettledOnly === true;+ return sql.withTransaction(Effect.all([listProjectRows(undefined).pipe(@@ -2666,7 +2678,7 @@ pending_approval_requests AS (),),),- listActiveThreadRows(undefined).pipe(+ listActiveThreadRows({ unsettledOnly }).pipe(Effect.mapError(toPersistenceSqlOrDecodeError("ProjectionSnapshotQuery.getShellSnapshot:listThreads:query",@@ -2674,7 +2686,7 @@ pending_approval_requests AS (),),),- listActiveThreadSessionRows(undefined).pipe(+ listActiveThreadSessionRows({ unsettledOnly }).pipe(Effect.mapError(toPersistenceSqlOrDecodeError("ProjectionSnapshotQuery.getShellSnapshot:listThreadSessions:query",@@ -2682,7 +2694,7 @@ pending_approval_requests AS (),),),- listActiveThreadPullRequestRows(undefined).pipe(+ listActiveThreadPullRequestRows({ unsettledOnly }).pipe(Effect.mapError(toPersistenceSqlOrDecodeError("ProjectionSnapshotQuery.getShellSnapshot:listThreadPullRequests:query",@@ -2690,7 +2702,7 @@ pending_approval_requests AS (),),),- listActiveLatestTurnRows(undefined).pipe(+ listActiveLatestTurnRows({ unsettledOnly }).pipe(Effect.mapError(toPersistenceSqlOrDecodeError("ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:query",@@ -2812,6 +2824,7 @@ pending_approval_requests AS (return toPersistenceSqlError("ProjectionSnapshotQuery.getShellSnapshot:query")(error);}),);+ };const listThreadsWithPullRequests: ProjectionSnapshotQueryShape["listThreadsWithPullRequests"] =() =>diff --git a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.tsindex 48e63d6fc8b..08da6e00940 100644--- a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts+++ b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts@@ -120,11 +120,15 @@ export interface ProjectionSnapshotQueryShape {** Returns only projects and thread shell summaries so clients can bootstrap* lightweight navigation state without hydrating every thread body.+ *+ * `unsettledOnly` is for background sweeps, not clients. It skips settled+ * threads and their sessions, PR links, and turns, and its `updatedAt`+ * ignores those rows. It still resolves every project, which keeps+ * repository identities cached for client connects.*/- readonly getShellSnapshot: () => Effect.Effect<- OrchestrationShellSnapshot,- ProjectionRepositoryError- >;+ readonly getShellSnapshot: (options?: {+ readonly unsettledOnly?: boolean;+ }) => Effect.Effect<OrchestrationShellSnapshot, ProjectionRepositoryError>;/*** Read archived thread shell summaries for the archive page.diff --git a/apps/server/src/orchestration/ThreadPullRequestReactor.test.ts b/apps/server/src/orchestration/ThreadPullRequestReactor.test.tsindex cefd5bcb42b..2a08dd03bc5 100644--- a/apps/server/src/orchestration/ThreadPullRequestReactor.test.ts+++ b/apps/server/src/orchestration/ThreadPullRequestReactor.test.ts@@ -27,13 +27,21 @@ import * as Queue from "effect/Queue";import * as Ref from "effect/Ref";import * as Stream from "effect/Stream";import { TestClock } from "effect/testing";+import * as SqlClient from "effect/unstable/sql/SqlClient";import { GitManager, type GitBranchPullRequest } from "../git/GitManager.ts";+import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";import { PullRequestService } from "../pullRequest/PullRequestService.ts";import { RepositoryIdentityResolver } from "../project/RepositoryIdentityResolver.ts";import { ServerActivation } from "../serverActivation.ts";+import { OrchestrationProjectionSnapshotQueryLive } from "./Layers/ProjectionSnapshotQuery.ts";import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts";-import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";+import {+ ProjectionSnapshotQuery,+ type ProjectionSnapshotQueryShape,+} from "./Services/ProjectionSnapshotQuery.ts";+import * as ThreadBackgroundLiveness from "./ThreadBackgroundLiveness.ts";+import * as ThreadPlanProgress from "./ThreadPlanProgress.ts";import * as ThreadPullRequestReactor from "./ThreadPullRequestReactor.ts";const NOW = "2026-09-01T12:00:00.000Z";@@ -135,6 +143,8 @@ const makeHarness = Effect.fn("makeThreadPullRequestHarness")(function* (optionsreadonly existingWorktrees?: ReadonlyArray<string>;readonly project?: OrchestrationProjectShell;readonly resolveRepositoryIdentity?: RepositoryIdentityResolver["Service"]["resolve"];+ /** Serve full sweep reads from this instead of `threads`. */+ readonly getShellSnapshot?: ProjectionSnapshotQueryShape["getShellSnapshot"];}) {const activation = yield* Deferred.make<void>();const snapshots = yield* Ref.make<OrchestrationShellSnapshot>({@@ -154,7 +164,10 @@ const makeHarness = Effect.fn("makeThreadPullRequestHarness")(function* (optionslet uuid = 0;const dependencies = Layer.mergeAll(Layer.mock(ProjectionSnapshotQuery)({- getShellSnapshot: () => Ref.get(snapshots).pipe(Effect.tap(() => Queue.offer(reads, null))),+ getShellSnapshot: (readOptions) =>+ (options.getShellSnapshot?.(readOptions) ?? Ref.get(snapshots)).pipe(+ Effect.tap(() => Queue.offer(reads, null)),+ ),getSnapshotSequence: () =>Ref.get(snapshots).pipe(Effect.map(({ snapshotSequence }) => ({ snapshotSequence }))),getThreadShellById: (threadId) =>@@ -644,6 +657,113 @@ describe("ThreadPullRequestReactor", () => {),);+ it.effect("discovers the same PRs from the unsettled read as from the full read", () =>+ Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;+ const query = yield* ProjectionSnapshotQuery;+ yield* sql`INSERT INTO projection_projects (project_id, title, workspace_root, scripts_json, created_at, updated_at)+ VALUES ('project', 'Project', '/workspace/project', '[]', ${NOW}, ${NOW}),+ ('dormant', 'Dormant', '/workspace/dormant', '[]', ${NOW}, ${NOW})`;+ yield* sql`INSERT INTO projection_threads (thread_id, project_id, title, model_selection_json, runtime_mode, interaction_mode, branch, branch_pull_request_json, created_at, updated_at, archived_at, settled_override, settled_at)+ VALUES+ ('open', 'project', 'Open', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', 'open', NULL, ${NOW}, ${NOW}, NULL, NULL, NULL),+ ('resumed', 'project', 'Resumed', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', 'resumed', NULL, ${NOW}, ${NOW}, NULL, 'active', NULL),+ ('linked', 'project', 'Linked', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', 'linked', '{"projectId":"project","repository":"owner/repository","number":3,"url":"https://github.com/owner/repository/pull/3"}', ${NOW}, ${NOW}, NULL, NULL, NULL),+ ('settled', 'project', 'Settled', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', 'settled', '{"projectId":"project","repository":"owner/repository","number":4,"url":"https://github.com/owner/repository/pull/4"}', ${NOW}, ${NOW}, NULL, 'settled', ${NOW}),+ ('backfill', 'project', 'Backfill', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', 'backfill', NULL, ${NOW}, ${NOW}, NULL, 'settled', ${NOW}),+ ('imported', 'dormant', 'Imported', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', NULL, NULL, ${NOW}, ${NOW}, NULL, 'settled', ${NOW}),+ ('archived', 'project', 'Archived', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', 'archived', NULL, ${NOW}, ${NOW}, ${NOW}, NULL, NULL)`;+ const numbers = new Map([+ ["open", 1],+ ["resumed", 2],+ ["linked", 3],+ ["settled", 4],+ ["backfill", 5],+ ["archived", 6],+ ]);++ // Startup, then two periodic passes. The startup backfill lookup fails,+ // so the first periodic pass retries it from the full read.+ const discover = (read: ProjectionSnapshotQueryShape["getShellSnapshot"]) =>+ Effect.gen(function* () {+ const online = yield* Ref.make(false);+ const reads: Array<ReadonlyArray<string>> = [];+ const fixture = yield* makeHarness({+ threads: [],+ getShellSnapshot: (options) =>+ read(options).pipe(+ Effect.tap((snapshot) =>+ Effect.sync(() => reads.push(snapshot.threads.map(({ id }) => id).toSorted())),+ ),+ ),+ branchPullRequest: ({ cwd, branch }) =>+ Effect.gen(function* () {+ if (branch === "backfill" && !(yield* Ref.get(online))) {+ return yield* new GitManagerError({+ operation: "branchPullRequest",+ cwd,+ detail: "Offline",+ });+ }+ const number = numbers.get(branch);+ return number === undefined ? null : branchPullRequest(number);+ }),+ });+ return yield* Effect.gen(function* () {+ const reactor = yield* fixture.start();+ const startupCalls = (yield* Ref.get(fixture.branchCalls)).length;+ const startupCommands = (yield* Ref.get(fixture.commands)).length;+ yield* Ref.set(online, true);+ for (let pass = 0; pass < 2; pass++) {+ yield* TestClock.adjust("1 minute");+ yield* Queue.take(fixture.reads);+ yield* reactor.drain;+ }+ return {+ reads,+ branchCalls: (yield* Ref.get(fixture.branchCalls))+ .slice(startupCalls)+ .map(({ branch }) => branch)+ .toSorted(),+ commands: (yield* Ref.get(fixture.commands))+ .slice(startupCommands)+ .map(+ ({ threadId, branchPullRequest }) => `${threadId} ${branchPullRequest?.number}`,+ )+ .toSorted(),+ };+ }).pipe(Effect.provide(fixture.layer));+ }).pipe(Effect.scoped);++ const { reads: unsettledReads, ...unsettled } = yield* discover(query.getShellSnapshot);+ const { reads: fullReads, ...full } = yield* discover(() => query.getShellSnapshot());+ expect(unsettled).toEqual(full);+ expect(unsettled.commands).toEqual([+ "backfill 5",+ "open 1",+ "open 1",+ "resumed 2",+ "resumed 2",+ ]);+ // The last pass has no backfill left, so it reads no settled thread.+ expect(fullReads.at(-1)).toContain("imported");+ expect(unsettledReads.at(-1)).toEqual(["linked", "open", "resumed"]);+ }).pipe(+ Effect.provide(+ OrchestrationProjectionSnapshotQueryLive.pipe(+ Layer.provide(ThreadBackgroundLiveness.layer),+ Layer.provide(ThreadPlanProgress.layer),+ Layer.provide(+ Layer.succeed(RepositoryIdentityResolver, {+ resolve: () => Effect.succeed(project.repositoryIdentity),+ }),+ ),+ Layer.provideMerge(SqlitePersistenceMemory),+ ),+ ),+ ),+ );+it.effect("matches Azure SSH projects to HTTPS PRs with the provider repository selector", () =>Effect.scoped(Effect.gen(function* () {diff --git a/apps/server/src/orchestration/ThreadPullRequestReactor.ts b/apps/server/src/orchestration/ThreadPullRequestReactor.tsindex 2d9d92d6436..66ff81d5a9e 100644--- a/apps/server/src/orchestration/ThreadPullRequestReactor.ts+++ b/apps/server/src/orchestration/ThreadPullRequestReactor.ts@@ -74,7 +74,9 @@ export function pullRequestMatchesProject(/*** Read the shell state for a discovery or settlement sweep. A sweep for one- * thread reads that thread and the projects it names, not every thread.+ * thread reads that thread and the projects it names, not every thread. A+ * sweep over all threads reads only unsettled threads, since both sweeps skip+ * settled ones. Discovery's backfill does its own full read.*/export const readSweepSnapshot = (snapshots: ProjectionSnapshotQuery.ProjectionSnapshotQueryShape,@@ -84,7 +86,7 @@ export const readSweepSnapshot = (ProjectionRepositoryError> =>threadId === null- ? snapshots.getShellSnapshot()+ ? snapshots.getShellSnapshot({ unsettledOnly: true }): Effect.gen(function* () {// Read the sequence first. The thread is then at least this new, so a// command guarded by the sequence is rejected rather than missing a change.@@ -129,7 +131,11 @@ export const make = Effect.gen(function* () {const synchronize = Effect.fn("ThreadPullRequestReactor.synchronize")(function* (request: RefreshRequest,) {- const snapshot = yield* readSweepSnapshot(snapshots, request.threadId);+ // Backfill looks up settled threads, so its passes read every thread.+ const snapshot =+ request.threadId === null && (request.backfill || pendingBackfill.size > 0)+ ? yield* snapshots.getShellSnapshot()+ : yield* readSweepSnapshot(snapshots, request.threadId);const projects = new Map(snapshot.projects.map((project) => [project.id, project]));if (request.backfill) {for (const thread of snapshot.threads) {@@ -141,11 +147,15 @@ export const make = Effect.gen(function* () {}}}- // A single-thread read only shows whether its own thread is gone.- const threadIds = new Set(snapshot.threads.map((thread) => thread.id));+ // A single-thread read only shows whether its own thread is gone. A thread+ // with no branch has nothing to look up, and its entry would keep every+ // periodic pass on the full read.+ const branchThreadIds = new Set(+ snapshot.threads.filter((thread) => thread.branch !== null).map((thread) => thread.id),+ );const checkedIds = request.threadId === null ? pendingBackfill.keys() : [request.threadId];for (const threadId of checkedIds) {- if (!threadIds.has(threadId)) pendingBackfill.delete(threadId);+ if (!branchThreadIds.has(threadId)) pendingBackfill.delete(threadId);}const threads = snapshot.threads.filter((thread) =>diff --git a/apps/server/src/orchestration/ThreadSettlementReactor.test.ts b/apps/server/src/orchestration/ThreadSettlementReactor.test.tsindex bee487ceb72..cad45007665 100644--- a/apps/server/src/orchestration/ThreadSettlementReactor.test.ts+++ b/apps/server/src/orchestration/ThreadSettlementReactor.test.ts@@ -30,8 +30,11 @@ import * as Queue from "effect/Queue";import * as Ref from "effect/Ref";import * as Stream from "effect/Stream";import { TestClock } from "effect/testing";+import * as SqlClient from "effect/unstable/sql/SqlClient";import { GitManager, type GitBranchPullRequest } from "../git/GitManager.ts";+import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";+import { RepositoryIdentityResolver } from "../project/RepositoryIdentityResolver.ts";import {PullRequestService,type PullRequestMergeEvent,@@ -39,11 +42,17 @@ import {import { ServerActivation } from "../serverActivation.ts";import { ServerSettingsService } from "../serverSettings.ts";import { OrchestrationCommandInvariantError } from "./Errors.ts";+import { OrchestrationProjectionSnapshotQueryLive } from "./Layers/ProjectionSnapshotQuery.ts";import {OrchestrationEngineService,type OrchestrationEngineShape,} from "./Services/OrchestrationEngine.ts";-import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";+import {+ ProjectionSnapshotQuery,+ type ProjectionSnapshotQueryShape,+} from "./Services/ProjectionSnapshotQuery.ts";+import * as ThreadBackgroundLiveness from "./ThreadBackgroundLiveness.ts";+import * as ThreadPlanProgress from "./ThreadPlanProgress.ts";import * as ThreadSettlementReactor from "./ThreadSettlementReactor.ts";import * as NodeServices from "@effect/platform-node/NodeServices";import * as Path from "effect/Path";@@ -169,6 +178,8 @@ function makeBranchPullRequest(interface HarnessOptions {readonly snapshot: OrchestrationShellSnapshot;+ /** Serve full sweep reads from this instead of `snapshot`. */+ readonly getShellSnapshot?: ProjectionSnapshotQueryShape["getShellSnapshot"];readonly settings?: ServerSettings;readonly branchPullRequest?: GitManager["Service"]["branchPullRequest"];readonly pullRequestSummary?: PullRequestService["Service"]["summary"];@@ -256,10 +267,10 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:const dependencies = Layer.mergeAll(Layer.mock(ProjectionSnapshotQuery)({- getShellSnapshot: () =>+ getShellSnapshot: (readOptions) =>Ref.update(snapshotReadCount, (count) => count + 1).pipe(Effect.andThen(Queue.offer(snapshotReads, null)),- Effect.andThen(Ref.get(snapshots)),+ Effect.andThen(options.getShellSnapshot?.(readOptions) ?? Ref.get(snapshots)),),getSnapshotSequence: () =>Ref.get(snapshots).pipe(Effect.map(({ snapshotSequence }) => ({ snapshotSequence }))),@@ -1437,6 +1448,88 @@ describe("ThreadSettlementReactor", () => {}),),);++ it.effect("settles the same threads from the unsettled read as from the full read", () =>+ Effect.gen(function* () {+ yield* TestClock.setTime(Date.parse(NOW));+ const sql = yield* SqlClient.SqlClient;+ const query = yield* ProjectionSnapshotQuery;+ yield* sql`INSERT INTO projection_projects (project_id, title, workspace_root, scripts_json, created_at, updated_at)+ VALUES ('settlement-project', 'Project', '/workspace/project', '[]', ${NOW}, ${NOW}),+ ('linked-settlement-project', 'Linked', '/workspace/linked', '[]', ${NOW}, ${NOW}),+ ('dormant-project', 'Dormant', '/workspace/dormant', '[]', ${NOW}, ${NOW})`;+ yield* sql`INSERT INTO projection_threads (thread_id, project_id, title, model_selection_json, runtime_mode, interaction_mode, branch, branch_pull_request_json, latest_user_message_at, created_at, updated_at, archived_at, settled_override, settled_at)+ VALUES+ ('idle', 'settlement-project', 'Idle', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', NULL, NULL, '2026-08-20T00:00:00.000Z', '2026-08-01T00:00:00.000Z', ${NOW}, NULL, NULL, NULL),+ ('merged', 'settlement-project', 'Merged', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', 'feature',+ '{"projectId":"linked-settlement-project","repository":"owner/repository","number":42,"url":"https://example.test/owner/repository/pull/42"}',+ '2026-08-27T00:00:00.000Z', '2026-08-01T00:00:00.000Z', ${NOW}, NULL, NULL, NULL),+ ('linked', 'settlement-project', 'Linked', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', NULL, NULL, '2026-08-27T00:00:00.000Z', '2026-08-01T00:00:00.000Z', ${NOW}, NULL, NULL, NULL),+ ('open', 'settlement-project', 'Open', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', 'open-feature', NULL, '2026-08-27T00:00:00.000Z', '2026-08-01T00:00:00.000Z', ${NOW}, NULL, NULL, NULL),+ ('resumed', 'settlement-project', 'Resumed', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', NULL, NULL, '2026-08-20T00:00:00.000Z', '2026-08-01T00:00:00.000Z', ${NOW}, NULL, 'active', NULL),+ ('settled', 'dormant-project', 'Settled', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', 'done', NULL, '2026-08-20T00:00:00.000Z', '2026-08-01T00:00:00.000Z', ${NOW}, NULL, 'settled', '2026-08-21T00:00:00.000Z'),+ ('archived', 'settlement-project', 'Archived', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', NULL, NULL, '2026-08-20T00:00:00.000Z', '2026-08-01T00:00:00.000Z', ${NOW}, ${NOW}, NULL, NULL)`;+ yield* sql`INSERT INTO projection_thread_pull_requests (thread_id, host, repository, number, url, source, linked_at, snapshot_json)+ VALUES ('linked', 'example.test', 'owner/repository', 7, 'https://example.test/owner/repository/pull/7', 'manual', ${NOW},+ '{"state":"merged","title":"Review","headBranch":"linked","baseBranch":"main","isDraft":false,"updatedAt":"2026-08-28T12:00:00.000Z","syncedAt":"2026-08-28T12:00:00.000Z","mergedAt":"2026-08-28T12:00:00.000Z","closedAt":null}')`;++ const sweep = (read: ProjectionSnapshotQueryShape["getShellSnapshot"]) =>+ Effect.gen(function* () {+ const readThreadIds: Array<string> = [];+ const fixture = yield* makeHarness({+ snapshot: makeSnapshot([]),+ getShellSnapshot: (options) =>+ read(options).pipe(+ Effect.tap((snapshot) =>+ Effect.sync(() => readThreadIds.push(...snapshot.threads.map(({ id }) => id))),+ ),+ ),+ branchPullRequest: ({ branch }) =>+ Effect.succeed(branch === "open-feature" ? makeBranchPullRequest("open") : null),+ pullRequestSummary: (input) =>+ Effect.succeed(makePullRequestSummary({ ...input, state: "merged" })),+ });+ return yield* Effect.gen(function* () {+ const reactor = yield* ThreadSettlementReactor.ThreadSettlementReactor;+ yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);+ return {+ readThreadIds: readThreadIds.toSorted(),+ commands: (yield* Ref.get(fixture.commands))+ .map(({ threadId, settledAt }) => `${threadId} ${settledAt}`)+ .toSorted(),+ branchCalls: (yield* Ref.get(fixture.branchCalls))+ .map(({ branch }) => branch)+ .toSorted(),+ summaryCalls: yield* Ref.get(fixture.summaryCalls),+ };+ }).pipe(Effect.provide(fixture.layer));+ }).pipe(Effect.scoped);++ const { readThreadIds: unsettledReads, ...unsettled } = yield* sweep(query.getShellSnapshot);+ const { readThreadIds: fullReads, ...full } = yield* sweep(() => query.getShellSnapshot());+ assert.deepStrictEqual(unsettled, full);+ // A settle for inactivity, for a synced merged link, and for a saved+ // branch PR whose project only that PR names.+ assert.deepStrictEqual(unsettled.commands, [+ "idle 2026-08-20T00:00:00.000Z",+ "linked 2026-08-27T00:00:00.000Z",+ "merged 2026-08-27T00:00:00.000Z",+ ]);+ assert.deepStrictEqual(fullReads, [...unsettledReads, "settled"].toSorted());+ assert.deepStrictEqual(unsettledReads, ["idle", "linked", "merged", "open", "resumed"]);+ }).pipe(+ Effect.provide(+ OrchestrationProjectionSnapshotQueryLive.pipe(+ Layer.provide(ThreadBackgroundLiveness.layer),+ Layer.provide(ThreadPlanProgress.layer),+ Layer.provide(+ Layer.succeed(RepositoryIdentityResolver, { resolve: () => Effect.succeed(null) }),+ ),+ Layer.provideMerge(SqlitePersistenceMemory),+ ),+ ),+ ),+ );});describe("storage cleanup", () => {