@devries-cameron20 / t3code Mirror · read-only / commits / 20081ef95f
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 23:30 UTC

fix(server): subagent threads settle with their parent instead of sweeping on their own (#19665)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Michael Huo committed Nov 11, 2026 at 14:54 UTC 20081ef95f78b17c1f0e8d9be8bacf28b191bdc9
5 files changed +556 -53
apps/server/src/orchestration-v2/ProjectionSettlement.test.ts
+42
@@ -478,3 +478,45 @@ it.effect("sql: an unsettled-only shell read skips settled threads", () =>
478 assert.equal(all.threads.length, 4);
479 }).pipe(Effect.provide(layerSql)),
480 );
481 +
482 +it.effect("sql: a subagent thread becomes a candidate once its parent is done", () =>
483 + Effect.gen(function* () {
484 + const store = yield* ProjectionStore.ProjectionStoreV2;
485 + const parent = yield* createThread("subagent-parent");
486 + const child = yield* createThread("subagent-child", {
487 + lineage: { parentThreadId: parent, relationshipToParent: "subagent", rootThreadId: parent },
488 + });
489 + const ids = () =>
490 + store.getSettlementCandidates().pipe(Effect.map((rows) => rows.map((row) => row.id)));
491 + assert.deepEqual(yield* ids(), [parent]);
492 +
493 + const parentThread = yield* store.getThread(parent);
494 + for (const [type, overrides] of [
495 + ["thread.settled", { settledOverride: "settled", settledAt: now }],
496 + ["thread.archived", { archivedAt: now }],
497 + ["thread.deleted", { deletedAt: now }],
498 + ] satisfies ReadonlyArray<
499 + readonly [
500 + "thread.settled" | "thread.archived" | "thread.deleted",
501 + Partial<OrchestrationV2AppThread>,
502 + ]
503 + >) {
504 + yield* store.apply({
505 + id: EventId.make(`event:settlement:subagent-parent:${type}`),
506 + type,
507 + threadId: parent,
508 + occurredAt: now,
509 + payload: { ...parentThread, ...overrides, updatedAt: now },
510 + });
511 + assert.deepEqual(yield* ids(), [child]);
512 + }
513 + const orphan = yield* createThread("orphan", {
514 + lineage: {
515 + parentThreadId: ThreadId.make("missing-parent"),
516 + relationshipToParent: "subagent",
517 + rootThreadId: parent,
518 + },
519 + });
520 + assert.deepEqual(new Set(yield* ids()), new Set([child, orphan]));
521 + }).pipe(Effect.provide(layerSql)),
522 +);
apps/server/src/orchestration-v2/ProjectionStore.ts
+11
@@ -202,6 +202,7 @@ export type ProjectionSettlementCandidate = Pick<
202 | "projectId"
203 | "branch"
204 | "worktreePath"
205 + | "lineage"
206 | "pullRequests"
207 | "linkedPullRequest"
208 | "branchPullRequest"
@@ -6757,6 +6758,16 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6758 AND json_extract(t.payload_json, '$.settledOverride') IS NULL
6759 AND json_extract(t.payload_json, '$.pinnedAt') IS NULL
6760 AND json_extract(t.payload_json, '$.autoSettleDisabledAt') IS NULL
6761 + AND (
6762 + json_extract(t.payload_json, '$.lineage.relationshipToParent') IS NOT 'subagent'
6763 + OR NOT EXISTS (
6764 + SELECT 1 FROM orchestration_v2_projection_threads parent
6765 + WHERE parent.thread_id = json_extract(t.payload_json, '$.lineage.parentThreadId')
6766 + AND parent.deleted_at IS NULL
6767 + AND json_extract(parent.payload_json, '$.archivedAt') IS NULL
6768 + AND json_extract(parent.payload_json, '$.settledOverride') IS NOT 'settled'
6769 + )
6770 + )
6771 AND NOT EXISTS (
6772 SELECT 1 FROM orchestration_v2_projection_runs active
6773 WHERE active.thread_id = t.thread_id
apps/server/src/orchestration-v2/SubagentProjection.test.ts
+16 -1
@@ -126,7 +126,7 @@ it("keeps a subagent child awake when its parent thread is snoozed", () => {
126 });
127
128 it.effect.each(["provider", "mcp"] as const)(
129 - "a %s child does not inherit parent settlement protections and settles once idle",
129 + "a %s child does not inherit parent settlement protections and settles once its parent settles",
130 (creationSource) =>
131 Effect.gen(function* () {
132 const store = yield* ProjectionStore.ProjectionStoreV2;
@@ -168,6 +168,21 @@ it.effect.each(["provider", "mcp"] as const)(
168 assert.deepEqual(savedParent.pinnedAt, parentCreatedAt);
169 assert.equal(savedParent.pinOrderKey, "a0");
170 assert.deepEqual(savedParent.autoSettleDisabledAt, parentCreatedAt);
171 + // A subagent child waits for its parent, so settle the pinned parent first.
172 + assert.deepEqual(yield* store.getSettlementCandidates(), []);
173 + yield* store.apply({
174 + id: EventId.make(`event:${parentThreadId}:settled`),
175 + type: "thread.settled",
176 + threadId: parentThreadId,
177 + occurredAt: childCreatedAt,
178 + payload: {
179 + ...savedParent,
180 + settledOverride: "settled",
181 + settledAt: childCreatedAt,
182 + pinnedAt: null,
183 + pinOrderKey: null,
184 + },
185 + });
186 const candidates = yield* store.getSettlementCandidates();
187 assert.deepEqual(
188 candidates.map((candidate) => candidate.id),
apps/server/src/orchestration-v2/ThreadSettlementService.test.ts
+437 -44
@@ -6,8 +6,10 @@ import {
6 ProjectId,
7 EventId,
8 ProviderInstanceId,
9 + MessageId,
10 RuntimeRequestId,
11 RunId,
12 + type OrchestrationV2Run,
13 ThreadId,
14 TurnItemId,
15 type OrchestrationProjectShell,
@@ -35,6 +37,7 @@ import * as Stream from "effect/Stream";
37 import { TestClock } from "effect/testing";
38
39 import * as GitManager from "../git/GitManager.ts";
40 +import * as SqlitePersistence from "../persistence/Sqlite.ts";
41 import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
42 import * as PullRequestService from "../pullRequest/PullRequestService.ts";
43 import * as ServerActivation from "../serverActivation.ts";
@@ -563,6 +566,7 @@ interface HarnessOptions {
566 ) => Effect.Effect<void>;
567 readonly onCloseIdle?: () => Effect.Effect<void>;
568 readonly currentThreads?: ReadonlyArray<OrchestrationV2AppThread>;
569 + readonly projections?: ProjectionStore.ProjectionStoreV2Shape;
570 }
571
572 const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: HarnessOptions) {
@@ -589,6 +593,7 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:
593 const summaryRecovery = yield* Ref.make<ReadonlyArray<boolean | undefined>>([]);
594 const invalidatedCwds = yield* Ref.make<ReadonlyArray<string>>([]);
595 const domainEvents = yield* PubSub.unbounded<OrchestrationV2DomainEvent>();
596 + const observedEvents = yield* Queue.unbounded<EventId>();
597 const closedIdle = yield* Queue.unbounded<{ readonly threadId: string }>();
598 const scriptRuns =
599 yield* Queue.unbounded<ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput>();
@@ -659,18 +664,24 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:
664 listShells: () => Ref.get(snapshots).pipe(Effect.map((snapshot) => snapshot.projects)),
665 }),
666 Layer.mock(ProjectionStore.ProjectionStoreV2)({
667 + ...options.projections,
668 getSettlementCandidates: (threadId) =>
669 Ref.update(candidateReads, (reads) => [...reads, threadId]).pipe(
670 Effect.andThen(Ref.updateAndGet(snapshotReadCount, (count) => count + 1)),
671 Effect.tap((count) => Queue.offer(snapshotReads, count)),
666 - Effect.andThen(Ref.get(snapshots)),
667 - Effect.map((snapshot) =>
668 - threadId === undefined
669 - ? snapshot.threads
670 - : snapshot.threads.filter((thread) => thread.id === threadId),
672 + Effect.andThen(
673 + options.projections?.getSettlementCandidates(threadId) ??
674 + Ref.get(snapshots).pipe(
675 + Effect.map((snapshot) =>
676 + threadId === undefined
677 + ? snapshot.threads
678 + : snapshot.threads.filter((thread) => thread.id === threadId),
679 + ),
680 + ),
681 ),
682 ),
683 getThread: (threadId) => {
684 + if (options.projections) return options.projections.getThread(threadId);
685 const thread = options.currentThreads?.find((candidate) => candidate.id === threadId);
686 return thread
687 ? Effect.succeed(thread)
@@ -678,7 +689,9 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:
689 },
690 }),
691 Layer.mock(Orchestrator.OrchestratorV2)({
681 - streamDomainEvents: Stream.fromPubSub(domainEvents),
692 + streamDomainEvents: Stream.fromPubSub(domainEvents).pipe(
693 + Stream.tap((event) => Queue.offer(observedEvents, event.id)),
694 + ),
695 dispatch,
696 }),
697 Layer.mock(TerminalManager.TerminalManager)({
@@ -723,6 +736,7 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:
736
737 return {
738 activation,
739 + settings,
740 snapshots,
741 snapshotReadCount,
742 settingsReadCount,
@@ -735,6 +749,7 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:
749 invalidatedCwds,
750 closedIdle,
751 scriptRuns,
752 + observedEvents,
753 publishEvent: (event: OrchestrationV2DomainEvent) => PubSub.publish(domainEvents, event),
754 updateSettings,
755 publishMerge: PubSub.publish(mergedPullRequests, {
@@ -761,6 +776,48 @@ const startHarness = Effect.fn("startThreadSettlementHarness")(function* (
776 yield* reactor.drain;
777 });
778
779 +const projectionStoreSql = ProjectionStore.layer.pipe(
780 + Layer.provideMerge(SqlitePersistence.layerMemory),
781 +);
782 +
783 +const appThread = (
784 + id: string,
785 + settledOverride: OrchestrationV2AppThread["settledOverride"],
786 + worktreePath: string | null = null,
787 +): OrchestrationV2AppThread => {
788 + const threadId = ThreadId.make(id);
789 + return {
790 + createdBy: "user",
791 + creationSource: "web",
792 + id: threadId,
793 + projectId: PROJECT_ID,
794 + title: id,
795 + providerInstanceId: ProviderInstanceId.make("codex"),
796 + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
797 + runtimeMode: "full-access",
798 + interactionMode: "default",
799 + branch: null,
800 + worktreePath,
801 + activeProviderThreadId: null,
802 + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
803 + forkedFrom: null,
804 + createdAt: DateTime.makeUnsafe(NOW),
805 + updatedAt: DateTime.makeUnsafe(NOW),
806 + archivedAt: null,
807 + settledOverride,
808 + settledAt: settledOverride === "settled" ? DateTime.makeUnsafe(NOW) : null,
809 + lastVisitedAt: null,
810 + deletedAt: null,
811 + };
812 +};
813 +const settledEvent = (thread: OrchestrationV2AppThread): OrchestrationV2DomainEvent => ({
814 + type: "thread.settled",
815 + id: EventId.make(`event:settled:${thread.id}`),
816 + threadId: thread.id,
817 + occurredAt: DateTime.makeUnsafe(NOW),
818 + payload: thread,
819 +});
820 +
821 describe("ThreadSettlementServiceV2 worker", () => {
822 it.effect("skips settings and PR decisions for recent branchless threads", () =>
823 Effect.scoped(
@@ -912,6 +969,345 @@ describe("ThreadSettlementServiceV2 worker", () => {
969 ),
970 );
971
972 + it.effect(
973 + "drains idle subagents of a settled parent and retries busy children without PR lookups",
974 + () =>
975 + Effect.scoped(
976 + Effect.gen(function* () {
977 + yield* TestClock.setTime(Date.parse(NOW));
978 + const store = yield* ProjectionStore.ProjectionStoreV2;
979 + const parent = appThread("subagent-parent", "settled");
980 + const child = (id: string, overrides: Partial<OrchestrationV2AppThread> = {}) => ({
981 + ...appThread(id, null),
982 + branch: "feature",
983 + lineage: {
984 + rootThreadId: parent.id,
985 + parentThreadId: parent.id,
986 + relationshipToParent: "subagent" as const,
987 + },
988 + ...overrides,
989 + });
990 + const empty = child("empty");
991 + const recent = child("recent");
992 + const busy = child("busy");
993 + const marker = appThread("marker", "settled");
994 + for (const thread of [
995 + parent,
996 + empty,
997 + recent,
998 + busy,
999 + marker,
1000 + child("pinned", { pinnedAt: DateTime.makeUnsafe(NOW) }),
1001 + child("opted-out", { autoSettleDisabledAt: DateTime.makeUnsafe(NOW) }),
1002 + ]) {
1003 + yield* store.apply({
1004 + type: "thread.created",
1005 + id: EventId.make(`created:${thread.id}`),
1006 + threadId: thread.id,
1007 + occurredAt: thread.createdAt,
1008 + payload: thread,
1009 + });
1010 + }
1011 + const run = (
1012 + threadId: ThreadId,
1013 + status: "running" | "completed",
1014 + ): OrchestrationV2Run => ({
1015 + id: RunId.make(`run:${threadId}`),
1016 + threadId,
1017 + ordinal: 1,
1018 + providerInstanceId: parent.providerInstanceId,
1019 + modelSelection: parent.modelSelection,
1020 + providerThreadId: null,
1021 + userMessageId: MessageId.make(`message:${threadId}`),
1022 + rootNodeId: null,
1023 + activeAttemptId: null,
1024 + status,
1025 + requestedAt: DateTime.makeUnsafe(NOW),
1026 + startedAt: DateTime.makeUnsafe(NOW),
1027 + completedAt: status === "completed" ? DateTime.makeUnsafe(NOW) : null,
1028 + checkpointId: null,
1029 + contextHandoffId: null,
1030 + });
1031 + for (const payload of [run(recent.id, "completed"), run(busy.id, "running")]) {
1032 + yield* store.apply({
1033 + type: "run.created",
1034 + id: EventId.make(`created:${payload.id}`),
1035 + threadId: payload.threadId,
1036 + occurredAt: DateTime.makeUnsafe(NOW),
1037 + payload,
1038 + });
1039 + }
1040 + const fixture = yield* makeHarness({
1041 + snapshot: makeSnapshot([]),
1042 + projections: store,
1043 + settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 2 },
1044 + onDispatch: (command) =>
1045 + store.getThread(command.threadId).pipe(
1046 + Effect.flatMap((thread) =>
1047 + store.apply(
1048 + settledEvent({
1049 + ...thread,
1050 + settledOverride: "settled",
1051 + settledAt: DateTime.makeUnsafe(NOW),
1052 + }),
1053 + ),
1054 + ),
1055 + Effect.orDie,
1056 + ),
1057 + });
1058 + yield* Effect.gen(function* () {
1059 + const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1060 + yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1061 + const commands = yield* Ref.get(fixture.commands);
1062 + expect(commands.map((command) => command.threadId).toSorted()).toEqual([
1063 + empty.id,
1064 + recent.id,
1065 + ]);
1066 + for (const command of commands) {
1067 + expect(command.snapshotAt).toEqual(DateTime.makeUnsafe(NOW));
1068 + expect(command.settledAt).toBeUndefined();
1069 + }
1070 + const finished: OrchestrationV2DomainEvent = {
1071 + type: "run.updated",
1072 + id: EventId.make("busy:completed"),
1073 + threadId: busy.id,
1074 + occurredAt: DateTime.makeUnsafe(NOW),
1075 + payload: run(busy.id, "completed"),
1076 + };
1077 + yield* store.apply(finished);
1078 + yield* fixture.publishEvent(finished);
1079 + // Cleanup of the following event marks delivery of the run event before draining.
1080 + yield* fixture.publishEvent(settledEvent(marker));
1081 + expect(yield* Queue.take(fixture.closedIdle)).toEqual({ threadId: marker.id });
1082 + yield* service.drain;
1083 + expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
1084 + empty.id,
1085 + recent.id,
1086 + busy.id,
1087 + ]);
1088 + expect(yield* Ref.get(fixture.branchCalls)).toEqual([]);
1089 + expect(yield* Ref.get(fixture.summaryCalls)).toEqual([]);
1090 + }).pipe(Effect.provide(fixture.layer));
1091 + }).pipe(Effect.provide(projectionStoreSql)),
1092 + ),
1093 + );
1094 +
1095 + it.effect(
1096 + "manual parent settlement drains hidden children with automatic settlement disabled",
1097 + () =>
1098 + Effect.scoped(
1099 + Effect.gen(function* () {
1100 + yield* TestClock.setTime(Date.parse(NOW));
1101 + const store = yield* ProjectionStore.ProjectionStoreV2;
1102 + const parent = appThread("manual-parent", null);
1103 + const child = {
1104 + ...appThread("manual-child", null),
1105 + branch: "feature",
1106 + lineage: {
1107 + rootThreadId: parent.id,
1108 + parentThreadId: parent.id,
1109 + relationshipToParent: "subagent" as const,
1110 + },
1111 + };
1112 + const marker = appThread("marker", "settled");
1113 + for (const thread of [parent, child, marker]) {
1114 + yield* store.apply({
1115 + type: "thread.created",
1116 + id: EventId.make(`created:${thread.id}`),
1117 + threadId: thread.id,
1118 + occurredAt: thread.createdAt,
1119 + payload: thread,
1120 + });
1121 + }
1122 + const fixture = yield* makeHarness({
1123 + snapshot: makeSnapshot([]),
1124 + projections: store,
1125 + settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 2 },
1126 + onDispatch: (command) =>
1127 + store.getThread(command.threadId).pipe(
1128 + Effect.flatMap((thread) =>
1129 + store.apply(
1130 + settledEvent({
1131 + ...thread,
1132 + settledOverride: "settled",
1133 + settledAt: DateTime.makeUnsafe(NOW),
1134 + }),
1135 + ),
1136 + ),
1137 + Effect.orDie,
1138 + ),
1139 + });
1140 + yield* Effect.gen(function* () {
1141 + const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1142 + yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1143 + expect(yield* Ref.get(fixture.commands)).toEqual([]);
1144 + expect(yield* Ref.get(fixture.branchCalls)).toEqual([]);
1145 + // Avoid a settings-change sweep: the parent event must trigger the child dispatch.
1146 + yield* Ref.set(fixture.settings, {
1147 + ...DEFAULT_SERVER_SETTINGS,
1148 + sidebarAutoSettleAfterDays: null,
1149 + sidebarAutoSettleOnMerge: false,
1150 + });
1151 + const event = settledEvent({
1152 + ...parent,
1153 + settledOverride: "settled",
1154 + settledAt: DateTime.makeUnsafe(NOW),
1155 + });
1156 + yield* store.apply(event);
1157 + yield* fixture.publishEvent(event);
1158 + yield* fixture.publishEvent(settledEvent(marker));
1159 + expect(yield* Queue.take(fixture.closedIdle)).toEqual({ threadId: parent.id });
1160 + expect(yield* Queue.take(fixture.closedIdle)).toEqual({ threadId: marker.id });
1161 + yield* service.drain;
1162 + expect(yield* Ref.get(fixture.commands)).toEqual([
1163 + expect.objectContaining({
1164 + type: "thread.auto-settle",
1165 + threadId: child.id,
1166 + snapshotAt: child.updatedAt,
1167 + }),
1168 + ]);
1169 + expect(yield* Ref.get(fixture.branchCalls)).toEqual([]);
1170 + expect(yield* Ref.get(fixture.summaryCalls)).toEqual([]);
1171 + }).pipe(Effect.provide(fixture.layer));
1172 + }).pipe(Effect.provide(projectionStoreSql)),
1173 + ),
1174 + );
1175 +
1176 + it.effect(
1177 + "coalesces bulk cleanup wakes and still drains children discovered during a sweep",
1178 + () =>
1179 + Effect.scoped(
1180 + Effect.gen(function* () {
1181 + yield* TestClock.setTime(Date.parse(NOW));
1182 + const store = yield* ProjectionStore.ProjectionStoreV2;
1183 + const sweepStarted = yield* Deferred.make<void>();
1184 + const releaseSweep = yield* Deferred.make<void>();
1185 + const childSettled = yield* Deferred.make<void>();
1186 + const parent = appThread("bulk-parent", null);
1187 + const child = {
1188 + ...appThread("bulk-child", null),
1189 + lineage: {
1190 + parentThreadId: parent.id,
1191 + rootThreadId: parent.id,
1192 + relationshipToParent: "subagent" as const,
1193 + },
1194 + };
1195 + const marker = appThread("bulk-marker", "settled");
1196 + const parents = [
1197 + parent,
1198 + ...Array.from({ length: 233 }, (_, i) => appThread(`bulk-parent-${i}`, null)),
1199 + ];
1200 + for (const thread of [...parents, child, marker]) {
1201 + yield* store.apply({
1202 + type: "thread.created",
1203 + id: EventId.make(`created:${thread.id}`),
1204 + threadId: thread.id,
1205 + occurredAt: thread.createdAt,
1206 + payload: thread,
1207 + });
1208 + }
1209 + let blockNextSweep = false;
1210 + const fixture = yield* makeHarness({
1211 + snapshot: makeSnapshot([]),
1212 + settings: {
1213 + ...DEFAULT_SERVER_SETTINGS,
1214 + sidebarAutoSettleAfterDays: null,
1215 + sidebarAutoSettleOnMerge: false,
1216 + },
1217 + projections: {
1218 + ...store,
1219 + getSettlementCandidates: (threadId) =>
1220 + Effect.gen(function* () {
1221 + const candidates = yield* store.getSettlementCandidates(threadId);
1222 + if (blockNextSweep) {
1223 + blockNextSweep = false;
1224 + yield* Deferred.succeed(sweepStarted, undefined);
1225 + yield* Deferred.await(releaseSweep);
1226 + }
1227 + return candidates;
1228 + }),
1229 + },
1230 + onDispatch: (command): Effect.Effect<void> =>
1231 + Effect.gen(function* () {
1232 + const thread = yield* store.getThread(command.threadId);
1233 + const event = settledEvent({
1234 + ...thread,
1235 + settledOverride: "settled",
1236 + settledAt: DateTime.makeUnsafe(NOW),
1237 + });
1238 + yield* store.apply(event);
1239 + yield* fixture.publishEvent(event);
1240 + yield* Deferred.succeed(childSettled, undefined);
1241 + }).pipe(Effect.orDie),
1242 + });
1243 + yield* Effect.gen(function* () {
1244 + const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1245 + yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1246 + yield* Ref.set(fixture.candidateReads, []);
1247 + blockNextSweep = true;
1248 + yield* fixture.publishEvent(settledEvent(marker));
1249 + yield* Deferred.await(sweepStarted);
1250 +
1251 + for (const [i, thread] of parents.entries()) {
1252 + const type = (["thread.settled", "thread.archived", "thread.deleted"] as const)[
1253 + i % 3
1254 + ]!;
1255 + const event: OrchestrationV2DomainEvent = {
1256 + type,
1257 + id: EventId.make(`bulk:${thread.id}`),
1258 + threadId: thread.id,
1259 + occurredAt: DateTime.makeUnsafe(NOW),
1260 + payload: {
1261 + ...thread,
1262 + ...(type === "thread.settled"
1263 + ? { settledOverride: "settled" as const, settledAt: DateTime.makeUnsafe(NOW) }
1264 + : type === "thread.archived"
1265 + ? { archivedAt: DateTime.makeUnsafe(NOW) }
1266 + : { deletedAt: DateTime.makeUnsafe(NOW) }),
1267 + },
1268 + };
1269 + yield* store.apply(event);
1270 + yield* fixture.publishEvent(event);
1271 + }
1272 + const markDelivery = (id: string) =>
1273 + fixture
1274 + .publishEvent({
1275 + type: "thread.created",
1276 + id: EventId.make(id),
1277 + threadId: marker.id,
1278 + occurredAt: marker.createdAt,
1279 + payload: marker,
1280 + })
1281 + .pipe(
1282 + // The next event is observed only after the previous handler has finished enqueueing.
1283 + Effect.andThen(
1284 + Queue.take(fixture.observedEvents).pipe(
1285 + Effect.repeat({ until: (seen) => seen === id }),
1286 + ),
1287 + ),
1288 + );
1289 + yield* markDelivery("bulk-delivered");
1290 + yield* Deferred.succeed(releaseSweep, undefined);
1291 + yield* Deferred.await(childSettled);
1292 + yield* markDelivery("child-delivered");
1293 + yield* service.drain;
1294 +
1295 + expect(yield* Ref.get(fixture.candidateReads)).toEqual([
1296 + undefined,
1297 + undefined,
1298 + undefined,
1299 + ]);
1300 + expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
1301 + child.id,
1302 + ]);
1303 + expect((yield* store.getThread(child.id)).settledOverride).toBe("settled");
1304 + expect(yield* Ref.get(fixture.branchCalls)).toEqual([]);
1305 + expect(yield* Ref.get(fixture.summaryCalls)).toEqual([]);
1306 + }).pipe(Effect.provide(fixture.layer));
1307 + }).pipe(Effect.provide(projectionStoreSql)),
1308 + ),
1309 + );
1310 +
1311 it.effect("looks up a branch in its worktree only while the worktree has .git", () =>
1312 Effect.scoped(
1313 Effect.gen(function* () {
@@ -1418,44 +1814,6 @@ describe("ThreadSettlementServiceV2 worker", () => {
1814 });
1815
1816 describe("ThreadSettlementServiceV2 terminals", () => {
1421 - const appThread = (
1422 - id: string,
1423 - settledOverride: OrchestrationV2AppThread["settledOverride"],
1424 - worktreePath: string | null = null,
1425 - ): OrchestrationV2AppThread => {
1426 - const threadId = ThreadId.make(id);
1427 - return {
1428 - createdBy: "user",
1429 - creationSource: "web",
1430 - id: threadId,
1431 - projectId: PROJECT_ID,
1432 - title: id,
1433 - providerInstanceId: ProviderInstanceId.make("codex"),
1434 - modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
1435 - runtimeMode: "full-access",
1436 - interactionMode: "default",
1437 - branch: null,
1438 - worktreePath,
1439 - activeProviderThreadId: null,
1440 - lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
1441 - forkedFrom: null,
1442 - createdAt: DateTime.makeUnsafe(NOW),
1443 - updatedAt: DateTime.makeUnsafe(NOW),
1444 - archivedAt: null,
1445 - settledOverride,
1446 - settledAt: settledOverride === "settled" ? DateTime.makeUnsafe(NOW) : null,
1447 - lastVisitedAt: null,
1448 - deletedAt: null,
1449 - };
1450 - };
1451 - const settledEvent = (thread: OrchestrationV2AppThread): OrchestrationV2DomainEvent => ({
1452 - type: "thread.settled",
1453 - id: EventId.make(`event:settled:${thread.id}`),
1454 - threadId: thread.id,
1455 - occurredAt: DateTime.makeUnsafe(NOW),
1456 - payload: thread,
1457 - });
1458 -
1817 it.effect("keeps the terminals of a thread re-engaged before the event ran", () =>
1818 Effect.scoped(
1819 Effect.gen(function* () {
@@ -1532,6 +1890,41 @@ describe("ThreadSettlementServiceV2 terminals", () => {
1890 ),
1891 );
1892
1893 + it.effect("skips the settle script for a subagent in its parent's worktree", () =>
1894 + Effect.scoped(
1895 + Effect.gen(function* () {
1896 + const parent = appThread("subagent-parent", "settled", "/worktrees/parent");
1897 + const subagent = (id: string, worktreePath: string) => ({
1898 + ...appThread(id, "settled", worktreePath),
1899 + lineage: {
1900 + parentThreadId: parent.id,
1901 + relationshipToParent: "subagent" as const,
1902 + rootThreadId: parent.id,
1903 + },
1904 + });
1905 + const shared = subagent("subagent-shared", "/worktrees/parent");
1906 + const own = subagent("subagent-own", "/worktrees/own");
1907 + const fixture = yield* makeHarness({
1908 + snapshot: makeSnapshot([]),
1909 + currentThreads: [parent, shared, own],
1910 + existingWorktreePaths: ["/worktrees/parent", "/worktrees/own"],
1911 + });
1912 +
1913 + yield* Effect.gen(function* () {
1914 + const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1915 + yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1916 + // Events run in order, so the first run belongs to the second event
1917 + // only if the shared-worktree child was skipped. Both still close.
1918 + yield* fixture.publishEvent(settledEvent(shared));
1919 + yield* fixture.publishEvent(settledEvent(own));
1920 + assert.deepStrictEqual(yield* Queue.take(fixture.closedIdle), { threadId: shared.id });
1921 + assert.deepStrictEqual(yield* Queue.take(fixture.closedIdle), { threadId: own.id });
1922 + assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, own.id);
1923 + }).pipe(Effect.provide(fixture.layer));
1924 + }),
1925 + ),
1926 + );
1927 +
1928 it.effect("runs the settle script once when a settlement is re-emitted", () =>
1929 Effect.scoped(
1930 Effect.gen(function* () {
apps/server/src/orchestration-v2/ThreadSettlementService.ts
+50 -8
@@ -320,20 +320,34 @@ export const make = Effect.gen(function* () {
320 threadId?: ThreadId,
321 ) {
322 const settings = yield* settingsService.getSettings;
323 - if (!autoSettlementConfigured(settings)) {
324 - return;
325 - }
323 + const automaticSettlementEnabled = autoSettlementConfigured(settings);
324 const threads = yield* projections.getSettlementCandidates(threadId);
325 if (threads.length === 0) return;
326 const projectShells = yield* projectStore.listShells();
327 const nowMs = DateTime.toEpochMillis(yield* DateTime.now);
328 const projects = new Map(projectShells.map((project) => [project.id, project]));
329 // Merge events resweep all candidates because unlinked threads settle through branch lookup.
332 - const candidates = threads.filter((thread) => isAutoSettlementCandidate(thread, nowMs));
330 + const candidates = threads.filter(
331 + (thread) =>
332 + (automaticSettlementEnabled || thread.lineage.relationshipToParent === "subagent") &&
333 + isAutoSettlementCandidate(thread, nowMs),
334 + );
335
336 // Runs per candidate thread, thousands per sweep on busy servers; the sweep owns the span.
337 const settleThread = Effect.fnUntraced(
338 function* (thread: (typeof candidates)[number], pullRequest: SettlementPullRequest | null) {
339 + if (thread.lineage.relationshipToParent === "subagent") {
340 + // The store returns a subagent only once its parent is done, so it
341 + // settles with the parent and never runs its own lookup.
342 + const uuid = yield* random.uuidV4();
343 + yield* orchestrator.dispatch({
344 + type: "thread.auto-settle",
345 + commandId: CommandId.make(`server:auto-settle:${thread.id}:${uuid}`),
346 + threadId: thread.id,
347 + snapshotAt: thread.updatedAt,
348 + });
349 + return null;
350 + }
351 // thread.auto-settle does not recheck settings, so read them per decision; reads are cached.
352 const currentSettings = resolveProjectSettings(
353 yield* settingsService.getSettings,
@@ -375,6 +389,7 @@ export const make = Effect.gen(function* () {
389 const lookupCandidates = (yield* Effect.forEach(
390 candidates,
391 (thread) => {
392 + if (thread.lineage.relationshipToParent === "subagent") return settleThread(thread, null);
393 const projectSettings = resolveProjectSettings(settings, thread.projectId).settings;
394 // Skip no-op decisions; actual settlement still reads fresh settings before dispatch.
395 const settledAt = resolveAutoSettlementAt({
@@ -566,9 +581,20 @@ export const make = Effect.gen(function* () {
581 }),
582 ),
583 );
584 + let fullSweepPending = false;
585 // A thread that just stopped must not wait behind a full sweep or another thread's host
586 // reads: clients hold it in Working only briefly, so a late settle makes it appear and then vanish.
571 - const fullSweeps = yield* makeDrainableWorker(() => runSweep(null));
587 + const fullSweeps = yield* makeDrainableWorker(() => {
588 + // Clear at the start so events during this sweep can request one follow-up.
589 + fullSweepPending = false;
590 + return runSweep(null);
591 + });
592 + const enqueueFullSweep = () =>
593 + Effect.suspend(() => {
594 + if (fullSweepPending) return Effect.void;
595 + fullSweepPending = true;
596 + return fullSweeps.enqueue(undefined);
597 + });
598 const threadSweeps = yield* FiberSet.make<void>();
599 const threadSweepSlots = yield* Semaphore.make(8);
600 // One sweep per thread at a time; events during a running sweep coalesce into one more pass.
@@ -609,6 +635,19 @@ export const make = Effect.gen(function* () {
635 if (thread.settledOverride !== "settled") return;
636 const settledAtMs = toMillis(thread.settledAt);
637 if (settledAtMs === null || settleActionRunAt.get(threadId) === settledAtMs) return;
638 + // The parent's worktree belongs to the parent; shared-worktree children
639 + // skip duplicate cleanup there.
640 + if (
641 + thread.lineage.relationshipToParent === "subagent" &&
642 + thread.lineage.parentThreadId !== null
643 + ) {
644 + const parent = yield* projections.getThread(thread.lineage.parentThreadId).pipe(
645 + Effect.catchTags({
646 + ProjectionStoreThreadNotFoundError: () => Effect.succeed(null),
647 + }),
648 + );
649 + if (parent?.worktreePath === worktreePath) return;
650 + }
651 const run = yield* projectScripts.runForThread({
652 threadId,
653 projectId: thread.projectId,
@@ -637,7 +676,10 @@ export const make = Effect.gen(function* () {
676 const processEvent = (event: OrchestrationV2DomainEvent) => {
677 switch (event.type) {
678 case "thread.settled":
640 - return cleanUpSettledThread(event.threadId);
679 + return cleanUpSettledThread(event.threadId).pipe(Effect.andThen(enqueueFullSweep()));
680 + case "thread.archived":
681 + case "thread.deleted":
682 + return enqueueFullSweep();
683 case "thread.pull-request-link-updated":
684 case "thread.pull-request-synced":
685 case "provider-session.detached":
@@ -692,7 +734,7 @@ export const make = Effect.gen(function* () {
734 let lastSettlementSettings = autoSettlementSettingsKey(initialSettings);
735 yield* forkParked(
736 Effect.gen(function* () {
695 - yield* fullSweeps.enqueue(undefined);
737 + yield* enqueueFullSweep();
738 yield* fullSweeps.drain;
739 }).pipe(Effect.repeat(Schedule.spaced("1 minute")), Effect.asVoid),
740 );
@@ -703,7 +745,7 @@ export const make = Effect.gen(function* () {
745 return Effect.void;
746 }
747 lastSettlementSettings = key;
706 - return fullSweeps.enqueue(undefined);
748 + return enqueueFullSweep();
749 }),
750 );
751 yield* forkParked(Stream.runForEach(mergedPullRequests, (event) => runSweep(event)));