Open History to see the last commit
1import type { OrchestrationThreadShell } from "@t3tools/contracts";
2import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
3
4export interface SettlementPullRequest {
5 readonly state: "open" | "closed" | "merged";
6 readonly closedAt?: string | null;
7 readonly mergedAt?: string | null;
8 readonly updatedAt?: string | null;
9}
10
11const DAY_MS = 24 * 60 * 60 * 1_000;
12const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
13
14function latestTimestamp(values: ReadonlyArray<string | null | undefined>): string | null {
15 let latest: string | null = null;
16 let latestMs = Number.NEGATIVE_INFINITY;
17 for (const value of values) {
18 if (value == null) continue;
19 const valueMs = Date.parse(value);
20 if (valueMs > latestMs) {
21 latest = value;
22 latestMs = valueMs;
23 }
24 }
25 return latest;
26}
27
28/** A recent user message stays queued until a turn adopts its timestamp.
29 * Absolute age bounds client clock skew in both directions and stops stale
30 * pre-adoption data from blocking the thread forever. */
31export function threadHasQueuedTurnStart(
32 thread: Pick<OrchestrationThreadShell, "latestUserMessageAt" | "latestTurn" | "session">,
33 now: string,
34): boolean {
35 if (thread.latestUserMessageAt === null || thread.session?.status === "error") return false;
36 const messageAt = Date.parse(thread.latestUserMessageAt);
37 const age = Date.parse(now) - messageAt;
38 if (Number.isNaN(age) || Math.abs(age) > QUEUED_TURN_START_GRACE_MS) return false;
39 if (thread.latestTurn === null) return true;
40 return [
41 thread.latestTurn.requestedAt,
42 thread.latestTurn.startedAt,
43 thread.latestTurn.completedAt,
44 ].every((value) => value == null || Date.parse(value) < messageAt);
45}
46
47function pullRequestSettles(
48 thread: Pick<OrchestrationThreadShell, "createdAt" | "latestUserMessageAt" | "latestTurn">,
49 pullRequest: SettlementPullRequest,
50 autoSettleOnMerge: boolean,
51): boolean {
52 if (pullRequest.state !== "closed" && (pullRequest.state !== "merged" || !autoSettleOnMerge)) {
53 return false;
54 }
55 const terminalAt = pullRequest.state === "merged" ? pullRequest.mergedAt : pullRequest.closedAt;
56 if (terminalAt == null) return false;
57 const userAnchor = latestTimestamp([
58 thread.createdAt,
59 thread.latestUserMessageAt,
60 thread.latestTurn?.requestedAt,
61 ]);
62 if (userAnchor === null) return false;
63 const pullRequestAt = Date.parse(terminalAt);
64 const userAnchorAt = Date.parse(userAnchor);
65 if (Number.isNaN(pullRequestAt) || Number.isNaN(userAnchorAt)) return false;
66 return pullRequestAt >= userAnchorAt;
67}
68
69export function resolveAutoSettlementAt(input: {
70 readonly thread: OrchestrationThreadShell;
71 readonly pullRequest: SettlementPullRequest | null;
72 readonly now: string;
73 readonly autoSettleAfterDays: number | null;
74 readonly autoSettleOnMerge: boolean;
75}): string | null {
76 const { thread } = input;
77 let pullRequest = input.pullRequest;
78 const links = visibleThreadPullRequests(thread.pullRequests);
79 if (links.some((link) => link.snapshot === null || link.snapshot.state === "open")) return null;
80 if (links.length > 0) {
81 const terminalTimestamp = (link: (typeof links)[number]) => {
82 const snapshot = link.snapshot;
83 const value = snapshot?.state === "merged" ? snapshot.mergedAt : snapshot?.closedAt;
84 const timestamp = Date.parse(value ?? "");
85 return Number.isNaN(timestamp) ? Number.NEGATIVE_INFINITY : timestamp;
86 };
87 const latest = links.reduce((current, candidate) =>
88 terminalTimestamp(candidate) > terminalTimestamp(current) ? candidate : current,
89 );
90 pullRequest =
91 latest.snapshot === null
92 ? null
93 : {
94 state: latest.snapshot.state,
95 mergedAt: latest.snapshot.mergedAt ?? null,
96 closedAt: latest.snapshot.closedAt ?? null,
97 };
98 }
99 if (!isAutoSettlementCandidate(thread, input.now)) return null;
100 const activityAt = latestTimestamp([
101 thread.latestUserMessageAt,
102 thread.latestTurn?.requestedAt,
103 thread.latestTurn?.startedAt,
104 thread.latestTurn?.completedAt,
105 ]);
106 if (pullRequest !== null) {
107 if (pullRequestSettles(thread, pullRequest, input.autoSettleOnMerge)) {
108 return activityAt ?? thread.createdAt;
109 }
110 }
111 if (input.autoSettleAfterDays === null || activityAt === null) return null;
112 return Date.parse(activityAt) < Date.parse(input.now) - input.autoSettleAfterDays * DAY_MS
113 ? activityAt
114 : null;
115}
116
117/** Cheap checks that run before any source control lookup. */
118export function isAutoSettlementCandidate(thread: OrchestrationThreadShell, now: string): boolean {
119 if (thread.archivedAt !== null || thread.settledOverride !== null) return false;
120 if (thread.autoSettleDisabledAt != null) return false;
121 if (thread.hasPendingApprovals || thread.hasPendingUserInput) return false;
122 if (thread.session?.status === "starting" || thread.session?.status === "running") return false;
123 if (thread.backgroundLiveness != null) return false;
124 if (threadHasQueuedTurnStart(thread, now)) return false;
125 if (thread.snoozedUntil == null || Date.parse(thread.snoozedUntil) <= Date.parse(now))
126 return true;
127 const wokeOnError =
128 thread.session?.status === "error" &&
129 (thread.snoozedAt == null ||
130 Date.parse(thread.session.updatedAt) > Date.parse(thread.snoozedAt));
131 const wokeOnCompletion =
132 thread.snoozedAt != null &&
133 thread.latestTurn?.state === "completed" &&
134 thread.latestTurn.completedAt != null &&
135 Date.parse(thread.latestTurn.completedAt) > Date.parse(thread.snoozedAt);
136 return wokeOnError || wokeOnCompletion;
137}