Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadSettlementPolicy.ts

140 lines5.5 KB

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;
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<
33 OrchestrationThreadShell,
34 "latestUserMessageAt" | "latestTurn" | "session" | "pendingProviderTurn"
35 >,
36 now: string,
37): boolean {
38 if (thread.pendingProviderTurn != null) return true;
39 if (thread.latestUserMessageAt === null || thread.session?.status === "error") return false;
40 const messageAt = Date.parse(thread.latestUserMessageAt);
41 const age = Date.parse(now) - messageAt;
42 if (Number.isNaN(age) || Math.abs(age) > QUEUED_TURN_START_GRACE_MS) return false;
43 if (thread.latestTurn === null) return true;
44 return [
45 thread.latestTurn.requestedAt,
46 thread.latestTurn.startedAt,
47 thread.latestTurn.completedAt,
48 ].every((value) => value == null || Date.parse(value) < messageAt);
50​
51function pullRequestSettles(
52 thread: Pick<OrchestrationThreadShell, "createdAt" | "latestUserMessageAt" | "latestTurn">,
53 pullRequest: SettlementPullRequest,
54 autoSettleOnMerge: boolean,
55): boolean {
56 if (pullRequest.state !== "closed" && (pullRequest.state !== "merged" || !autoSettleOnMerge)) {
57 return false;
58 }
59 const terminalAt = pullRequest.state === "merged" ? pullRequest.mergedAt : pullRequest.closedAt;
60 if (terminalAt == null) return false;
61 const userAnchor = latestTimestamp([
62 thread.createdAt,
63 thread.latestUserMessageAt,
64 thread.latestTurn?.requestedAt,
65 ]);
66 if (userAnchor === null) return false;
67 const pullRequestAt = Date.parse(terminalAt);
68 const userAnchorAt = Date.parse(userAnchor);
69 if (Number.isNaN(pullRequestAt) || Number.isNaN(userAnchorAt)) return false;
70 return pullRequestAt >= userAnchorAt;
72​
73export function resolveAutoSettlementAt(input: {
74 readonly thread: OrchestrationThreadShell;
75 readonly pullRequest: SettlementPullRequest | null;
76 readonly now: string;
77 readonly autoSettleAfterDays: number | null;
78 readonly autoSettleOnMerge: boolean;
79}): string | null {
80 const { thread } = input;
81 let pullRequest = input.pullRequest;
82 const links = visibleThreadPullRequests(thread.pullRequests);
83 if (links.some((link) => link.snapshot === null || link.snapshot.state === "open")) return null;
84 if (links.length > 0) {
85 const terminalTimestamp = (link: (typeof links)[number]) => {
86 const snapshot = link.snapshot;
87 const value = snapshot?.state === "merged" ? snapshot.mergedAt : snapshot?.closedAt;
88 const timestamp = Date.parse(value ?? "");
89 return Number.isNaN(timestamp) ? Number.NEGATIVE_INFINITY : timestamp;
90 };
91 const latest = links.reduce((current, candidate) =>
92 terminalTimestamp(candidate) > terminalTimestamp(current) ? candidate : current,
93 );
94 pullRequest =
95 latest.snapshot === null
96 ? null
97 : {
98 state: latest.snapshot.state,
99 mergedAt: latest.snapshot.mergedAt ?? null,
100 closedAt: latest.snapshot.closedAt ?? null,
101 };
102 }
103 if (!isAutoSettlementCandidate(thread, input.now)) return null;
104 const activityAt = latestTimestamp([
105 thread.latestUserMessageAt,
106 thread.latestTurn?.requestedAt,
107 thread.latestTurn?.startedAt,
108 thread.latestTurn?.completedAt,
109 ]);
110 if (pullRequest !== null) {
111 if (pullRequestSettles(thread, pullRequest, input.autoSettleOnMerge)) {
112 return activityAt ?? thread.createdAt;
113 }
114 }
115 if (input.autoSettleAfterDays === null || activityAt === null) return null;
116 return Date.parse(activityAt) < Date.parse(input.now) - input.autoSettleAfterDays * DAY_MS
117 ? activityAt
118 : null;
120​
121/** Cheap checks that run before any source control lookup. */
122export function isAutoSettlementCandidate(thread: OrchestrationThreadShell, now: string): boolean {
123 if (thread.archivedAt !== null || thread.settledOverride !== null) return false;
124 if (thread.hasPendingApprovals || thread.hasPendingUserInput) return false;
125 if (thread.session?.status === "starting" || thread.session?.status === "running") return false;
126 if (thread.backgroundLiveness != null) return false;
127 if (threadHasQueuedTurnStart(thread, now)) return false;
128 if (thread.snoozedUntil == null || Date.parse(thread.snoozedUntil) <= Date.parse(now))
129 return true;
130 const wokeOnError =
131 thread.session?.status === "error" &&
132 (thread.snoozedAt == null ||
133 Date.parse(thread.session.updatedAt) > Date.parse(thread.snoozedAt));
134 const wokeOnCompletion =
135 thread.snoozedAt != null &&
136 thread.latestTurn?.state === "completed" &&
137 thread.latestTurn.completedAt != null &&
138 Date.parse(thread.latestTurn.completedAt) > Date.parse(thread.snoozedAt);
139 return wokeOnError || wokeOnCompletion;