Skip to content

Commit 78d0c39

Browse files
t3dotggclaude
andcommitted
fix(server): agent-started turns no longer block settle on merge
A merged PR settled a thread only when the merge came after the thread's latest "user" message and latest run. Background command notifications, PR watch wakes, and other agent messages also use the user role, so one arriving after the merge kept the thread active until the inactivity window ran out. The merge anchor now uses only messages the user wrote. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 00eb8f6 commit 78d0c39

5 files changed

Lines changed: 138 additions & 20 deletions

File tree

‎apps/server/src/orchestration-v2/ProjectionSettlement.test.ts‎

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,13 @@ it.effect.each([
278278
};
279279
assert.deepEqual(
280280
resolveAutoSettlementAt({ ...settings, thread: candidate }),
281-
resolveAutoSettlementAt({ ...settings, thread: expected }),
281+
resolveAutoSettlementAt({
282+
...settings,
283+
thread: {
284+
...expected,
285+
latestUserAuthoredMessageAt: candidate.latestUserAuthoredMessageAt,
286+
},
287+
}),
282288
);
283289
}
284290
assert.equal(
@@ -292,6 +298,54 @@ it.effect.each([
292298
}).pipe(Effect.provide(testLayer)),
293299
);
294300

301+
it.effect.each([
302+
["sql", SqlLayer],
303+
["memory", ProjectionStore.layerMemory],
304+
] as const)("%s: the user-authored message time ignores agent notifications", ([, testLayer]) =>
305+
Effect.gen(function* () {
306+
const store = yield* ProjectionStore.ProjectionStoreV2;
307+
const threadId = yield* createThread("agent-woken");
308+
yield* createRun(threadId);
309+
const message = (
310+
id: string,
311+
createdBy: "user" | "agent",
312+
creationSource: "web" | "provider",
313+
at: DateTime.Utc,
314+
) =>
315+
store.apply({
316+
id: EventId.make(`event:settlement:${id}`),
317+
type: "message.updated",
318+
threadId,
319+
occurredAt: at,
320+
payload: {
321+
createdBy,
322+
creationSource,
323+
id: MessageId.make(`message:settlement:${id}`),
324+
threadId,
325+
runId: null,
326+
nodeId: null,
327+
role: "user",
328+
text: id,
329+
attachments: [],
330+
streaming: false,
331+
createdAt: at,
332+
updatedAt: at,
333+
},
334+
});
335+
const written = DateTime.subtract(now, { hours: 2 });
336+
yield* message("written", "user", "web", written);
337+
yield* message("notification", "agent", "provider", now);
338+
339+
const [candidate] = yield* store.getSettlementCandidates(threadId);
340+
assert.isDefined(candidate);
341+
assert.equal(DateTime.formatIso(candidate.latestUserMessageAt!), DateTime.formatIso(now));
342+
assert.equal(
343+
DateTime.formatIso(candidate.latestUserAuthoredMessageAt!),
344+
DateTime.formatIso(written),
345+
);
346+
}).pipe(Effect.provide(testLayer)),
347+
);
348+
295349
const pullRequestLink = (number: number) => ({
296350
host: "github.com",
297351
repository: "owner/repository",

‎apps/server/src/orchestration-v2/ProjectionStore.ts‎

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,13 @@ export type ProjectionThreadPullRequests = Pick<
159159
"id" | "projectId" | "settledOverride" | "settledAt" | "pullRequests"
160160
>;
161161

162-
/** Thread activity needed by settlement, without transcript or fork history. */
162+
/**
163+
* Thread activity needed by settlement, without transcript or fork history.
164+
* `latestUserAuthoredMessageAt` is the last message the user wrote. Agent,
165+
* provider, and server notifications also use the user role, so
166+
* `latestUserMessageAt` moves when background work or a PR watch wakes the
167+
* agent.
168+
*/
163169
export type ProjectionSettlementCandidate = Pick<
164170
OrchestrationV2ThreadShell,
165171
| "id"
@@ -187,7 +193,7 @@ export type ProjectionSettlementCandidate = Pick<
187193
| "activityRunStatus"
188194
| "pendingRuntimeRequest"
189195
| "pendingBackgroundTasks"
190-
>;
196+
> & { readonly latestUserAuthoredMessageAt: DateTime.Utc | null };
191197

192198
const ProjectionCheckpointContext = Schema.Struct({
193199
runs: Schema.Array(
@@ -930,7 +936,7 @@ type SettlementThreadRow = Pick<
930936
| "latest_run_started_at"
931937
| "latest_run_completed_at"
932938
| "latest_user_message_at"
933-
>;
939+
> & { readonly latest_user_authored_message_at: string | null };
934940

935941
type ShellRunItemCountRow = {
936942
readonly thread_id: string;
@@ -5051,7 +5057,15 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
50515057
WHERE message.thread_id = t.thread_id AND message.role = 'user'
50525058
ORDER BY message.updated_at DESC, message.message_id DESC
50535059
LIMIT 1
5054-
) AS latest_user_message_at
5060+
) AS latest_user_message_at,
5061+
(
5062+
SELECT message.updated_at
5063+
FROM orchestration_v2_projection_messages message
5064+
WHERE message.thread_id = t.thread_id AND message.role = 'user'
5065+
AND json_extract(message.payload_json, '$.createdBy') = 'user'
5066+
ORDER BY message.updated_at DESC, message.message_id DESC
5067+
LIMIT 1
5068+
) AS latest_user_authored_message_at
50555069
FROM orchestration_v2_projection_threads t
50565070
LEFT JOIN orchestration_v2_projection_runs r ON r.run_id = (
50575071
SELECT latest.run_id FROM orchestration_v2_projection_runs latest
@@ -5113,6 +5127,10 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
51135127
row.latest_user_message_at === null
51145128
? null
51155129
: DateTime.makeUnsafe(row.latest_user_message_at),
5130+
latestUserAuthoredMessageAt:
5131+
row.latest_user_authored_message_at === null
5132+
? null
5133+
: DateTime.makeUnsafe(row.latest_user_authored_message_at),
51165134
activityRunStatus: null,
51175135
activityRunStartedAt: null,
51185136
pendingRuntimeRequest: null,
@@ -5578,7 +5596,16 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
55785596
!runs.some(isActivityRunForShell) &&
55795597
!runtimeRequests.some((request) => request.status === "pending"),
55805598
)
5581-
.map(threadShellFromProjection)
5599+
.map((projection) => ({
5600+
...threadShellFromProjection(projection),
5601+
latestUserAuthoredMessageAt:
5602+
projection.messages
5603+
.filter((message) => message.role === "user" && message.createdBy === "user")
5604+
.map((message) => message.updatedAt)
5605+
.toSorted(
5606+
(left, right) => DateTime.toEpochMillis(right) - DateTime.toEpochMillis(left),
5607+
)[0] ?? null,
5608+
}))
55825609
.toSorted(
55835610
(left, right) =>
55845611
DateTime.toEpochMillis(left.updatedAt) - DateTime.toEpochMillis(right.updatedAt) ||

‎apps/server/src/orchestration-v2/ThreadSettlementService.test.ts‎

Lines changed: 40 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,12 @@ function at(offsetMs: number): DateTime.Utc {
4646
return DateTime.makeUnsafe(NOW_MS + offsetMs);
4747
}
4848

49-
function shell(overrides: Partial<OrchestrationV2ThreadShell> = {}): OrchestrationV2ThreadShell {
49+
type SettlementShell = OrchestrationV2ThreadShell &
50+
Pick<ProjectionStore.ProjectionSettlementCandidate, "latestUserAuthoredMessageAt">;
51+
52+
// A fixture's user message is one the user wrote unless the test sets
53+
// latestUserAuthoredMessageAt on its own.
54+
function shell(overrides: Partial<SettlementShell> = {}): SettlementShell {
5055
return {
5156
id: ThreadId.make("thread-1"),
5257
projectId: ProjectId.make("project-1"),
@@ -83,6 +88,7 @@ function shell(overrides: Partial<OrchestrationV2ThreadShell> = {}): Orchestrati
8388
latestRunStartedAt: null,
8489
latestRunCompletedAt: null,
8590
latestUserMessageAt: null,
91+
latestUserAuthoredMessageAt: overrides.latestUserMessageAt ?? null,
8692
createdAt: at(-30 * DAY_MS),
8793
updatedAt: at(-10 * DAY_MS),
8894
archivedAt: null,
@@ -292,6 +298,31 @@ describe("resolveAutoSettlementAt", () => {
292298
).toEqual(shell().createdAt);
293299
});
294300

301+
it("settles on merge after agent-started runs, but not after the user writes again", () => {
302+
// A background command stopped after the merge and its notification
303+
// started a run. Only the user's own messages hold a merged thread open.
304+
const woken = shell({
305+
latestUserMessageAt: at(-30 * 60 * 1_000),
306+
latestUserAuthoredMessageAt: at(-2 * 60 * 60 * 1_000),
307+
latestRunRequestedAt: at(-30 * 60 * 1_000),
308+
latestRunCompletedAt: at(-29 * 60 * 1_000),
309+
});
310+
const input = {
311+
thread: woken,
312+
pullRequest: { state: "merged" as const, mergedAt: DateTime.formatIso(at(-60 * 60 * 1_000)) },
313+
nowMs: NOW_MS,
314+
autoSettleAfterDays: null,
315+
autoSettleOnMerge: true,
316+
};
317+
expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toEqual(at(-29 * 60 * 1_000));
318+
expect(
319+
ThreadSettlementService.resolveAutoSettlementAt({
320+
...input,
321+
thread: { ...woken, latestUserAuthoredMessageAt: at(-30 * 60 * 1_000) },
322+
}),
323+
).toBeNull();
324+
});
325+
295326
it("settles inactive threads even when their pull request remains open", () => {
296327
const input = {
297328
thread: shell({ latestUserMessageAt: at(-30 * DAY_MS) }),
@@ -370,10 +401,7 @@ function makeProject(
370401
};
371402
}
372403

373-
function makeThread(
374-
id: string,
375-
overrides: Partial<OrchestrationV2ThreadShell> = {},
376-
): OrchestrationV2ThreadShell {
404+
function makeThread(id: string, overrides: Partial<SettlementShell> = {}): SettlementShell {
377405
return shell({
378406
id: ThreadId.make(id),
379407
projectId: PROJECT_ID,
@@ -385,10 +413,14 @@ function makeThread(
385413
});
386414
}
387415

416+
type SettlementSnapshot = Omit<OrchestrationV2ShellSnapshot, "threads"> & {
417+
readonly threads: ReadonlyArray<SettlementShell>;
418+
};
419+
388420
function makeSnapshot(
389-
threads: ReadonlyArray<OrchestrationV2ThreadShell>,
421+
threads: ReadonlyArray<SettlementShell>,
390422
projects: ReadonlyArray<OrchestrationProjectShell> = [makeProject()],
391-
): OrchestrationV2ShellSnapshot {
423+
): SettlementSnapshot {
392424
return {
393425
schemaVersion: 1,
394426
snapshotSequence: 1,
@@ -435,7 +467,7 @@ function makeBranchPullRequest(state: "open" | "closed" | "merged") {
435467
}
436468

437469
interface HarnessOptions {
438-
readonly snapshot: OrchestrationV2ShellSnapshot;
470+
readonly snapshot: SettlementSnapshot;
439471
readonly settings?: ContractServerSettings;
440472
readonly branchPullRequest?: GitManager.GitManager["Service"]["branchPullRequest"];
441473
readonly pullRequestSummary?: PullRequestService.PullRequestService["Service"]["summary"];

‎apps/server/src/orchestration-v2/ThreadSettlementService.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -105,10 +105,15 @@ export function threadHasQueuedTurnStart(
105105
].every((value) => value === null || value < messageAtMs);
106106
}
107107

108+
/**
109+
* A merged or closed pull request settles the thread unless the user wrote to
110+
* it afterwards. Runs that background work, a PR watch, or another agent
111+
* started do not count, so they cannot hold a merged thread open.
112+
*/
108113
function pullRequestSettles(
109114
thread: Pick<
110-
OrchestrationV2ThreadShell,
111-
"createdAt" | "latestUserMessageAt" | "latestRunRequestedAt"
115+
ProjectionStore.ProjectionSettlementCandidate,
116+
"createdAt" | "latestUserAuthoredMessageAt"
112117
>,
113118
pullRequest: SettlementPullRequest,
114119
autoSettleOnMerge: boolean,
@@ -120,8 +125,7 @@ function pullRequestSettles(
120125
if (terminalAt == null) return false;
121126
const userAnchorMs = latestMillis([
122127
toMillis(thread.createdAt),
123-
toMillis(thread.latestUserMessageAt),
124-
toMillis(thread.latestRunRequestedAt),
128+
toMillis(thread.latestUserAuthoredMessageAt),
125129
]);
126130
if (userAnchorMs === null) return false;
127131
const pullRequestAtMs = Date.parse(terminalAt);
@@ -131,7 +135,7 @@ function pullRequestSettles(
131135

132136
/** Cheap checks that run before any source control lookup. */
133137
export function isAutoSettlementCandidate(
134-
thread: ProjectionStore.ProjectionSettlementCandidate,
138+
thread: Omit<ProjectionStore.ProjectionSettlementCandidate, "latestUserAuthoredMessageAt">,
135139
nowMs: number,
136140
): boolean {
137141
if (thread.archivedAt !== null || thread.settledOverride !== null) return false;

‎docs/user/thread-sidebar.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,8 @@ threads whose pull request merged. A closed pull request can also settle an idle
135135
thread. Work in progress, pending questions or approvals, and live background work
136136
prevent automatic settlement. An open pull request does not prevent inactivity
137137
settlement, but an old closed or merged pull request does not settle work you
138-
resumed after it closed.
138+
resumed after it closed. Only your own messages count as resuming. A turn that
139+
finished background work or a pull request watch starts on its own does not.
139140

140141
To keep one thread out of the settled shelf no matter how long it sits idle, open its menu,
141142
choose **Auto-settle behavior**, and pick **Disabled**. The current option is checked. Pick

0 commit comments

Comments
 (0)