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, 04:45 UTC
| 1 | import * as DateTime from "effect/DateTime"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import * as Option from "effect/Option"; |
| 4 | import * as SqlClient from "effect/sql/SqlClient"; |
| 5 | |
| 6 | const timestamp = (value: string | null) => |
| 7 | value === null ? undefined : Option.getOrUndefined(DateTime.make(value)); |
| 8 | |
| 9 | export default Effect.gen(function* () { |
| 10 | const sql = yield* SqlClient.SqlClient; |
| 11 | // Manual settles have the same shape; only the affected builds' dense sweeps qualify. |
| 12 | const settlements = yield* sql<{ readonly thread_id: string; readonly occurred_at: string }>` |
| 13 | WITH |
| 14 | legacy_settlements AS ( |
| 15 | SELECT |
| 16 | stream_id AS thread_id, |
| 17 | occurred_at, |
| 18 | unixepoch(occurred_at, 'subsec') AS occurred_seconds |
| 19 | FROM orchestration_events |
| 20 | WHERE aggregate_kind = 'thread' |
| 21 | AND event_type = 'thread.settled' |
| 22 | AND actor_kind = 'client' |
| 23 | AND application_event_version = 1 |
| 24 | AND json_type(payload_json, '$.settledAt') = 'text' |
| 25 | AND json_extract(payload_json, '$.settledAt') = occurred_at |
| 26 | AND json_extract(metadata_json, '$.origin.appVersion') IN ('0.0.35', '0.0.36', '0.0.37', '0.0.38') |
| 27 | AND julianday(occurred_at) < julianday('2026-09-05T00:00:00.000Z') |
| 28 | ), |
| 29 | ordered AS ( |
| 30 | SELECT |
| 31 | thread_id, |
| 32 | occurred_at, |
| 33 | occurred_seconds, |
| 34 | occurred_seconds - LAG(occurred_seconds) OVER (ORDER BY occurred_seconds, thread_id) |
| 35 | AS gap_seconds |
| 36 | FROM legacy_settlements |
| 37 | ), |
| 38 | clustered AS ( |
| 39 | SELECT |
| 40 | thread_id, |
| 41 | occurred_at, |
| 42 | occurred_seconds, |
| 43 | SUM(CASE WHEN gap_seconds IS NULL OR gap_seconds > 30 THEN 1 ELSE 0 END) |
| 44 | OVER (ORDER BY occurred_seconds, thread_id) AS cluster_id |
| 45 | FROM ordered |
| 46 | ), |
| 47 | burst_clusters AS ( |
| 48 | SELECT |
| 49 | cluster_id, |
| 50 | COUNT(DISTINCT thread_id) AS distinct_thread_count, |
| 51 | MAX(occurred_seconds) - MIN(occurred_seconds) AS span_seconds |
| 52 | FROM clustered |
| 53 | GROUP BY cluster_id |
| 54 | ), |
| 55 | automatic_settlements AS ( |
| 56 | SELECT clustered.thread_id, clustered.occurred_at |
| 57 | FROM clustered |
| 58 | JOIN burst_clusters ON burst_clusters.cluster_id = clustered.cluster_id |
| 59 | WHERE burst_clusters.distinct_thread_count >= 10 |
| 60 | AND burst_clusters.span_seconds <= 120 |
| 61 | ) |
| 62 | SELECT DISTINCT thread_id, occurred_at FROM automatic_settlements |
| 63 | ORDER BY thread_id, occurred_at |
| 64 | `; |
| 65 | const byThread = Map.groupBy(settlements, (settlement) => settlement.thread_id); |
| 66 | |
| 67 | for (const [threadId, sweeps] of byThread) { |
| 68 | const repairs = sweeps.map((sweep) => ({ |
| 69 | occurredAt: sweep.occurred_at, |
| 70 | cutoff: DateTime.toEpochMillis(DateTime.makeUnsafe(sweep.occurred_at)), |
| 71 | activityAt: null as string | null, |
| 72 | activityTime: -Infinity, |
| 73 | })); |
| 74 | const recordActivity = (value: string | null) => { |
| 75 | const date = timestamp(value); |
| 76 | if (date === undefined) return; |
| 77 | const time = DateTime.toEpochMillis(date); |
| 78 | for (const repair of repairs) { |
| 79 | if (time <= repair.cutoff && time > repair.activityTime) { |
| 80 | repair.activityAt = value; |
| 81 | repair.activityTime = time; |
| 82 | } |
| 83 | } |
| 84 | }; |
| 85 | |
| 86 | for (const repair of repairs) { |
| 87 | const messages = yield* sql<{ readonly created_at: string }>` |
| 88 | SELECT created_at FROM projection_thread_messages |
| 89 | WHERE thread_id = ${threadId} AND role = 'user' |
| 90 | AND julianday(created_at) <= julianday(${repair.occurredAt}) |
| 91 | ORDER BY julianday(created_at) DESC LIMIT 1 |
| 92 | `; |
| 93 | recordActivity(messages[0]?.created_at ?? null); |
| 94 | } |
| 95 | |
| 96 | // 063 dropped projection_turns. Track open turns from retained V1 events so an |
| 97 | // idle session stopping cannot masquerade as a turn finishing. |
| 98 | const turns = new Map< |
| 99 | string, |
| 100 | { state: "running" | "completed" | "interrupted" | "error"; checkpoint: number | null } |
| 101 | >(); |
| 102 | const runningTurnIds = new Set<string>(); |
| 103 | let activeTurnId: string | null = null; |
| 104 | let afterSequence = 0; |
| 105 | const pageSize = 500; |
| 106 | while (true) { |
| 107 | const events = yield* sql<{ |
| 108 | readonly sequence: number; |
| 109 | readonly event_type: string; |
| 110 | readonly occurred_at: string; |
| 111 | readonly turn_id: string | null; |
| 112 | readonly created_at: string | null; |
| 113 | readonly updated_at: string | null; |
| 114 | readonly completed_at: string | null; |
| 115 | readonly role: string | null; |
| 116 | readonly streaming: number | null; |
| 117 | readonly status: string | null; |
| 118 | readonly session_turn_id: string | null; |
| 119 | readonly session_updated_at: string | null; |
| 120 | readonly checkpoint: number | null; |
| 121 | readonly turn_count: number | null; |
| 122 | }>` |
| 123 | SELECT sequence, event_type, occurred_at, |
| 124 | json_extract(payload_json, '$.turnId') AS turn_id, |
| 125 | json_extract(payload_json, '$.createdAt') AS created_at, |
| 126 | json_extract(payload_json, '$.updatedAt') AS updated_at, |
| 127 | json_extract(payload_json, '$.completedAt') AS completed_at, |
| 128 | json_extract(payload_json, '$.role') AS role, |
| 129 | json_extract(payload_json, '$.streaming') AS streaming, |
| 130 | json_extract(payload_json, '$.session.status') AS status, |
| 131 | json_extract(payload_json, '$.session.activeTurnId') AS session_turn_id, |
| 132 | json_extract(payload_json, '$.session.updatedAt') AS session_updated_at, |
| 133 | json_extract(payload_json, '$.checkpointTurnCount') AS checkpoint, |
| 134 | json_extract(payload_json, '$.turnCount') AS turn_count |
| 135 | FROM orchestration_events INDEXED BY idx_orch_events_stream_sequence |
| 136 | WHERE aggregate_kind = 'thread' AND stream_id = ${threadId} |
| 137 | AND application_event_version = 1 AND sequence > ${afterSequence} |
| 138 | AND event_type IN ( |
| 139 | 'thread.created', 'thread.turn-start-requested', 'thread.session-set', |
| 140 | 'thread.message-sent', 'thread.turn-interrupt-requested', |
| 141 | 'thread.turn-diff-completed', 'thread.reverted' |
| 142 | ) |
| 143 | ORDER BY sequence LIMIT ${pageSize} |
| 144 | `; |
| 145 | for (const event of events) { |
| 146 | const turn = event.turn_id === null ? undefined : turns.get(event.turn_id); |
| 147 | switch (event.event_type) { |
| 148 | case "thread.created": |
| 149 | turns.clear(); |
| 150 | runningTurnIds.clear(); |
| 151 | activeTurnId = null; |
| 152 | break; |
| 153 | case "thread.turn-start-requested": |
| 154 | recordActivity(event.created_at); |
| 155 | break; |
| 156 | case "thread.session-set": { |
| 157 | activeTurnId = event.status === "running" ? event.session_turn_id : null; |
| 158 | const endedAt = timestamp(event.session_updated_at) |
| 159 | ? event.session_updated_at |
| 160 | : event.occurred_at; |
| 161 | if (activeTurnId !== null) { |
| 162 | for (const id of runningTurnIds) { |
| 163 | if (id !== activeTurnId) { |
| 164 | turns.get(id)!.state = "completed"; |
| 165 | runningTurnIds.delete(id); |
| 166 | recordActivity(endedAt); |
| 167 | } |
| 168 | } |
| 169 | const active = turns.get(activeTurnId); |
| 170 | if (active === undefined) { |
| 171 | turns.set(activeTurnId, { state: "running", checkpoint: null }); |
| 172 | runningTurnIds.add(activeTurnId); |
| 173 | recordActivity(event.occurred_at); |
| 174 | } else if (active.state === "interrupted") { |
| 175 | active.state = "running"; |
| 176 | runningTurnIds.add(activeTurnId); |
| 177 | } |
| 178 | } else if ( |
| 179 | event.status === "idle" || |
| 180 | event.status === "ready" || |
| 181 | event.status === "error" || |
| 182 | event.status === "interrupted" || |
| 183 | event.status === "stopped" |
| 184 | ) { |
| 185 | for (const id of runningTurnIds) { |
| 186 | const running = turns.get(id)!; |
| 187 | running.state = |
| 188 | event.status === "error" |
| 189 | ? "error" |
| 190 | : event.status === "interrupted" || event.status === "stopped" |
| 191 | ? "interrupted" |
| 192 | : "completed"; |
| 193 | recordActivity(endedAt); |
| 194 | } |
| 195 | runningTurnIds.clear(); |
| 196 | } |
| 197 | break; |
| 198 | } |
| 199 | case "thread.message-sent": |
| 200 | if (event.role !== "assistant" || event.turn_id === null) break; |
| 201 | recordActivity(event.created_at); |
| 202 | if (event.streaming === 0 && activeTurnId !== event.turn_id) { |
| 203 | if (turn === undefined || turn.state === "running") recordActivity(event.updated_at); |
| 204 | if (turn === undefined) { |
| 205 | turns.set(event.turn_id, { state: "completed", checkpoint: null }); |
| 206 | } else if (turn.state === "running") { |
| 207 | turn.state = "completed"; |
| 208 | } |
| 209 | runningTurnIds.delete(event.turn_id); |
| 210 | } else if (turn === undefined) { |
| 211 | turns.set(event.turn_id, { state: "running", checkpoint: null }); |
| 212 | runningTurnIds.add(event.turn_id); |
| 213 | } |
| 214 | break; |
| 215 | case "thread.turn-interrupt-requested": |
| 216 | if (event.turn_id === null) break; |
| 217 | recordActivity(event.created_at); |
| 218 | turns.set(event.turn_id, { |
| 219 | state: "interrupted", |
| 220 | checkpoint: turn?.checkpoint ?? null, |
| 221 | }); |
| 222 | runningTurnIds.delete(event.turn_id); |
| 223 | break; |
| 224 | case "thread.turn-diff-completed": |
| 225 | if (event.turn_id === null) break; |
| 226 | recordActivity(event.completed_at); |
| 227 | turns.set(event.turn_id, { |
| 228 | state: |
| 229 | activeTurnId === event.turn_id |
| 230 | ? (turn?.state ?? "running") |
| 231 | : turn?.state === "interrupted" |
| 232 | ? "interrupted" |
| 233 | : "completed", |
| 234 | checkpoint: event.checkpoint, |
| 235 | }); |
| 236 | if (turns.get(event.turn_id)!.state === "running") { |
| 237 | runningTurnIds.add(event.turn_id); |
| 238 | } else { |
| 239 | runningTurnIds.delete(event.turn_id); |
| 240 | } |
| 241 | break; |
| 242 | case "thread.reverted": |
| 243 | for (const [id, previous] of turns) { |
| 244 | if (previous.checkpoint === null || previous.checkpoint > (event.turn_count ?? 0)) { |
| 245 | turns.delete(id); |
| 246 | runningTurnIds.delete(id); |
| 247 | } |
| 248 | } |
| 249 | break; |
| 250 | } |
| 251 | } |
| 252 | if (events.length < pageSize) break; |
| 253 | afterSequence = events.at(-1)!.sequence; |
| 254 | } |
| 255 | |
| 256 | for (const repair of repairs) { |
| 257 | yield* sql` |
| 258 | UPDATE projection_threads |
| 259 | SET settled_at = COALESCE(${repair.activityAt}, created_at) |
| 260 | WHERE thread_id = ${threadId} AND settled_override = 'settled' |
| 261 | AND settled_at = ${repair.occurredAt} |
| 262 | `; |
| 263 | yield* sql` |
| 264 | UPDATE orchestration_v2_projection_threads |
| 265 | SET payload_json = json_set(payload_json, '$.settledAt', |
| 266 | COALESCE(${repair.activityAt}, json_extract(payload_json, '$.createdAt'))) |
| 267 | WHERE thread_id = ${threadId} |
| 268 | AND json_extract(payload_json, '$.settledOverride') = 'settled' |
| 269 | AND json_extract(payload_json, '$.settledAt') = ${repair.occurredAt} |
| 270 | `; |
| 271 | // V2 snapshots must retain the repair after a rebuild; V1 history stays immutable. |
| 272 | yield* sql` |
| 273 | UPDATE orchestration_events |
| 274 | SET payload_json = json_set(payload_json, '$.settledAt', |
| 275 | COALESCE(${repair.activityAt}, json_extract(payload_json, '$.createdAt'), |
| 276 | json_extract(payload_json, '$.settledAt'))) |
| 277 | WHERE aggregate_kind = 'thread' AND stream_id = ${threadId} |
| 278 | AND application_event_version = 2 |
| 279 | AND json_extract(payload_json, '$.settledOverride') = 'settled' |
| 280 | AND json_extract(payload_json, '$.settledAt') = ${repair.occurredAt} |
| 281 | `; |
| 282 | } |
| 283 | } |
| 284 | }); |