Skip to content

Commit a77a10d

Browse files
committed
fix(server): preserve automatic settlement timestamps
1 parent aab4049 commit a77a10d

14 files changed

Lines changed: 420 additions & 27 deletions

‎apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,7 @@ describe("OrchestrationEngine", () => {
386386
commandId: CommandId.make("cmd-auto-settle-stale-snapshot"),
387387
threadId: guardedThreadId,
388388
snapshotSequence,
389+
settledAt: now(),
389390
})
390391
.pipe(Effect.flip);
391392
expect(staleError._tag).toBe("OrchestrationCommandInvariantError");
@@ -413,6 +414,7 @@ describe("OrchestrationEngine", () => {
413414
commandId: CommandId.make(`cmd-auto-settle-${expectedLiveness}`),
414415
threadId: liveThreadId,
415416
snapshotSequence: livenessSnapshotSequence,
417+
settledAt: now(),
416418
})
417419
.pipe(Effect.flip);
418420
expect(livenessError._tag).toBe("OrchestrationCommandInvariantError");
@@ -425,6 +427,7 @@ describe("OrchestrationEngine", () => {
425427
commandId: CommandId.make("cmd-auto-settle-after-liveness-cleared"),
426428
threadId: liveThreadId,
427429
snapshotSequence: livenessSnapshotSequence,
430+
settledAt: now(),
428431
});
429432

430433
const freshSnapshotSequence = yield* engine.latestSequence;
@@ -439,6 +442,7 @@ describe("OrchestrationEngine", () => {
439442
commandId: CommandId.make("cmd-auto-settle-after-unrelated-update"),
440443
threadId: guardedThreadId,
441444
snapshotSequence: freshSnapshotSequence,
445+
settledAt: now(),
442446
});
443447

444448
const settled = yield* snapshots.getSnapshot();

‎apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3371,6 +3371,7 @@ describe("ProviderCommandReactor", () => {
33713371
commandId: CommandId.make("cmd-auto-settle-with-session"),
33723372
threadId: ThreadId.make("thread-1"),
33733373
snapshotSequence: beforeSettlement.snapshotSequence,
3374+
settledAt: now,
33743375
});
33753376

33763377
yield* Deferred.await(sessionStopped);

‎apps/server/src/orchestration/ThreadSettlementPolicy.test.ts‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import {
66
TurnId,
77
type OrchestrationThreadShell,
88
} from "@t3tools/contracts";
9-
import { shouldAutoSettleThread } from "./ThreadSettlementPolicy.ts";
9+
import { resolveAutoSettlementAt } from "./ThreadSettlementPolicy.ts";
1010

1111
const NOW = "2026-08-28T12:00:00.000Z";
1212
const makeThread = (
@@ -39,15 +39,36 @@ const decide = (
3939
pullRequest: { state: "open" | "closed" | "merged"; updatedAt: string | null } | null = null,
4040
settings: { days?: number | null; merge?: boolean } = {},
4141
) =>
42-
shouldAutoSettleThread({
42+
resolveAutoSettlementAt({
4343
thread,
4444
pullRequest,
4545
now: NOW,
4646
autoSettleAfterDays: settings.days === undefined ? 3 : settings.days,
4747
autoSettleOnMerge: settings.merge ?? true,
48+
}) !== null;
49+
50+
describe("resolveAutoSettlementAt", () => {
51+
it("returns the last activity time for persisted settlement", () => {
52+
expect(
53+
resolveAutoSettlementAt({
54+
thread: makeThread({
55+
latestTurn: {
56+
turnId: TurnId.make("turn-terminal"),
57+
state: "completed",
58+
requestedAt: "2026-08-19T00:00:00.000Z",
59+
startedAt: "2026-08-19T00:01:00.000Z",
60+
completedAt: "2026-08-21T00:00:00.000Z",
61+
assistantMessageId: null,
62+
},
63+
}),
64+
pullRequest: null,
65+
now: NOW,
66+
autoSettleAfterDays: 3,
67+
autoSettleOnMerge: true,
68+
}),
69+
).toBe("2026-08-21T00:00:00.000Z");
4870
});
4971

50-
describe("shouldAutoSettleThread", () => {
5172
it("settles inactive threads and leaves never-used threads active", () => {
5273
expect(decide(makeThread())).toBe(true);
5374
expect(decide(makeThread({ latestUserMessageAt: null }))).toBe(false);

‎apps/server/src/orchestration/ThreadSettlementPolicy.ts‎

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -62,28 +62,31 @@ function pullRequestSettles(
6262
return pullRequestAt >= userAnchorAt;
6363
}
6464

65-
export function shouldAutoSettleThread(input: {
65+
export function resolveAutoSettlementAt(input: {
6666
readonly thread: OrchestrationThreadShell;
6767
readonly pullRequest: SettlementPullRequest | null;
6868
readonly now: string;
6969
readonly autoSettleAfterDays: number | null;
7070
readonly autoSettleOnMerge: boolean;
71-
}): boolean {
71+
}): string | null {
7272
const { thread, pullRequest } = input;
73-
if (!isAutoSettlementCandidate(thread, input.now)) return false;
74-
if (pullRequest !== null) {
75-
if (pullRequestSettles(thread, pullRequest, input.autoSettleOnMerge)) return true;
76-
if (pullRequest.state === "open") return false;
77-
}
78-
if (input.autoSettleAfterDays === null) return false;
73+
if (!isAutoSettlementCandidate(thread, input.now)) return null;
7974
const activityAt = latestTimestamp([
8075
thread.latestUserMessageAt,
8176
thread.latestTurn?.requestedAt,
8277
thread.latestTurn?.startedAt,
8378
thread.latestTurn?.completedAt,
8479
]);
85-
if (activityAt === null) return false;
86-
return Date.parse(activityAt) < Date.parse(input.now) - input.autoSettleAfterDays * DAY_MS;
80+
if (pullRequest !== null) {
81+
if (pullRequestSettles(thread, pullRequest, input.autoSettleOnMerge)) {
82+
return activityAt ?? thread.updatedAt;
83+
}
84+
if (pullRequest.state === "open") return null;
85+
}
86+
if (input.autoSettleAfterDays === null || activityAt === null) return null;
87+
return Date.parse(activityAt) < Date.parse(input.now) - input.autoSettleAfterDays * DAY_MS
88+
? activityAt
89+
: null;
8790
}
8891

8992
/** Cheap checks that run before any source control lookup. */

‎apps/server/src/orchestration/ThreadSettlementReactor.test.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -301,16 +301,22 @@ describe("ThreadSettlementReactor", () => {
301301
const commands = yield* Ref.get(fixture.commands);
302302
assert.deepStrictEqual(
303303
commands
304-
.map(({ threadId, snapshotSequence }) => ({ threadId, snapshotSequence }))
304+
.map(({ threadId, snapshotSequence, settledAt }) => ({
305+
threadId,
306+
snapshotSequence,
307+
settledAt,
308+
}))
305309
.sort((left, right) => left.threadId.localeCompare(right.threadId)),
306310
[
307311
{
308312
threadId: ThreadId.make("closed-pr"),
309313
snapshotSequence: 1,
314+
settledAt: "2026-08-20T00:00:00.000Z",
310315
},
311316
{
312317
threadId: ThreadId.make("inactive"),
313318
snapshotSequence: 1,
319+
settledAt: "2026-08-20T00:00:00.000Z",
314320
},
315321
],
316322
);

‎apps/server/src/orchestration/ThreadSettlementReactor.ts‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import * as OrchestrationEngine from "./Services/OrchestrationEngine.ts";
1818
import * as ProjectionSnapshotQuery from "./Services/ProjectionSnapshotQuery.ts";
1919
import {
2020
isAutoSettlementCandidate,
21-
shouldAutoSettleThread,
21+
resolveAutoSettlementAt,
2222
type SettlementPullRequest,
2323
} from "./ThreadSettlementPolicy.ts";
2424

@@ -101,15 +101,14 @@ export const make = Effect.gen(function* () {
101101
Effect.gen(function* () {
102102
const settings = yield* settingsService.getSettings;
103103
const decisionNow = DateTime.formatIso(yield* DateTime.now);
104-
if (
105-
!shouldAutoSettleThread({
106-
thread,
107-
pullRequest,
108-
now: decisionNow,
109-
autoSettleAfterDays: settings.sidebarAutoSettleAfterDays,
110-
autoSettleOnMerge: settings.sidebarAutoSettleOnMerge,
111-
})
112-
) {
104+
const settledAt = resolveAutoSettlementAt({
105+
thread,
106+
pullRequest,
107+
now: decisionNow,
108+
autoSettleAfterDays: settings.sidebarAutoSettleAfterDays,
109+
autoSettleOnMerge: settings.sidebarAutoSettleOnMerge,
110+
});
111+
if (settledAt === null) {
113112
return;
114113
}
115114
const uuid = yield* crypto.randomUUIDv4;
@@ -118,6 +117,7 @@ export const make = Effect.gen(function* () {
118117
commandId: CommandId.make(`server:auto-settle:${thread.id}:${uuid}`),
119118
threadId: thread.id,
120119
snapshotSequence: snapshot.snapshotSequence,
120+
settledAt,
121121
});
122122
}).pipe(
123123
Effect.catchCause((cause) =>

‎apps/server/src/orchestration/decider.settled.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,13 +81,33 @@ function makeSession(status: OrchestrationSession["status"]): OrchestrationSessi
8181
}
8282

8383
it.layer(NodeServices.layer)("settled thread decider", (it) => {
84+
it.effect("preserves the activity stamp when automatically settling", () =>
85+
Effect.gen(function* () {
86+
const result = yield* decideOrchestrationCommand({
87+
command: {
88+
type: "thread.auto-settle",
89+
commandId: CommandId.make("cmd-auto-settle-inactive"),
90+
threadId: ThreadId.make("thread-1"),
91+
snapshotSequence: 0,
92+
settledAt: SETTLED_AT,
93+
},
94+
readModel: makeReadModel(null),
95+
});
96+
const events = Array.isArray(result) ? result : [result];
97+
const settled = events.find((event) => event.type === "thread.settled");
98+
expect(settled?.payload.settledAt).toBe(SETTLED_AT);
99+
expect(settled?.payload.updatedAt).not.toBe(SETTLED_AT);
100+
}),
101+
);
102+
84103
it.effect("rejects an automatic settle when the thread is pinned active", () =>
85104
Effect.gen(function* () {
86105
const command = {
87106
type: "thread.auto-settle" as const,
88107
commandId: CommandId.make("cmd-auto-settle"),
89108
threadId: ThreadId.make("thread-1"),
90109
snapshotSequence: 0,
110+
settledAt: SETTLED_AT,
91111
};
92112
const pinnedActive = yield* decideOrchestrationCommand({
93113
command,

‎apps/server/src/orchestration/decider.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -468,7 +468,11 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
468468
type: "thread.settled" as const,
469469
payload: {
470470
threadId: command.threadId,
471-
settledAt: alreadySettled ? thread.settledAt : occurredAt,
471+
settledAt: alreadySettled
472+
? thread.settledAt
473+
: command.type === "thread.auto-settle"
474+
? command.settledAt
475+
: occurredAt,
472476
// A re-emission is a projected no-op: keep the existing updatedAt
473477
// so duplicate settles neither rewind nor churn ordering. A fresh
474478
// settle stamps the command time.

‎apps/server/src/persistence/Migrations.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ import Migration0041 from "./Migrations/041_AuthSessionClientConnection.ts";
5656
import Migration0042 from "./Migrations/042_ProjectionThreadLinkedPullRequest.ts";
5757
import Migration0043 from "./Migrations/043_ProjectionThreadsUnsettledAt.ts";
5858
import Migration0044 from "./Migrations/044_ClearAutomaticProjectModelDefaults.ts";
59+
import Migration0045 from "./Migrations/045_RepairAutomaticSettlementTimestamps.ts";
5960

6061
/**
6162
* Migration loader with all migrations defined inline.
@@ -112,6 +113,7 @@ export const migrationEntries = [
112113
[42, "ProjectionThreadLinkedPullRequest", Migration0042],
113114
[43, "ProjectionThreadsUnsettledAt", Migration0043],
114115
[44, "ClearAutomaticProjectModelDefaults", Migration0044],
116+
[45, "RepairAutomaticSettlementTimestamps", Migration0045],
115117
] as const;
116118

117119
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);

0 commit comments

Comments
 (0)