Open History to see the last commit
1import type {
2 ApplicationStoredEvent,
3 OrchestrationProjectShell,
4 OrchestrationV2ArchivedShellStreamItem,
5 OrchestrationV2ShellSnapshot,
6 OrchestrationV2ThreadShell,
7 OrchestrationV2ThreadShellSnapshot,
8 OrchestrationV2ShellStreamItem,
9 OrchestrationV2StoredEvent,
10} from "@t3tools/contracts";
11import {
12 OrchestrationProjectShell as ProjectShellSchema,
13 OrchestrationV2ThreadShell as ThreadShellSchema,
14} from "@t3tools/contracts";
15import * as Clock from "effect/Clock";
16import * as Effect from "effect/Effect";
17import * as Schema from "effect/Schema";
18import type * as SqlClient from "effect/sql/SqlClient";
19import * as Stream from "effect/Stream";
20
21/** Build the regular navigation shell without duplicating the archive dataset. */
22export function buildActiveShellSnapshot(input: {
23 readonly projects: ReadonlyArray<OrchestrationProjectShell>;
24 readonly threads: OrchestrationV2ThreadShellSnapshot;
25 readonly snapshotSequence: number;
26}): OrchestrationV2ShellSnapshot {
27 return {
28 schemaVersion: input.threads.schemaVersion,
29 snapshotSequence: input.snapshotSequence,
30 projects: input.projects,
31 threads: input.threads.threads,
32 archivedThreads: [],
33 };
34}
35
36/**
37 * Loads the thread shell, projects and sequence for the shell snapshots.
38 * One transaction covers the reads so they agree; the threads are decoded
39 * after it commits, because the server shares one SQLite connection and
40 * decoding a large shell takes longer than reading it.
41 */
42export const loadShellSnapshotParts = <E1, E2, E3, E4>(input: {
43 readonly sql: SqlClient.SqlClient;
44 readonly readThreads: Effect.Effect<Effect.Effect<OrchestrationV2ThreadShellSnapshot, E2>, E1>;
45 readonly listProjects: Effect.Effect<ReadonlyArray<OrchestrationProjectShell>, E3>;
46 readonly latestSequence: Effect.Effect<number, E4>;
47}) =>
48 Effect.gen(function* () {
49 const read = yield* input.sql.withTransaction(
50 Effect.all({
51 decodeThreads: input.readThreads,
52 projects: input.listProjects,
53 snapshotSequence: input.latestSequence,
54 }),
55 );
56 return {
57 projects: read.projects,
58 threads: yield* read.decodeThreads,
59 snapshotSequence: read.snapshotSequence,
60 };
61 });
62
63export type ShellApplicationEvent =
64 | Pick<
65 Extract<ApplicationStoredEvent, { readonly aggregateKind: "project" }>,
66 "aggregateKind" | "aggregateId" | "type" | "sequence"
67 >
68 | {
69 readonly sequence: number;
70 readonly event: Pick<OrchestrationV2StoredEvent["event"], "threadId">;
71 };
72
73/** Shell updates refetch an aggregate; drop transcript bodies before retaining an event. */
74export function toShellApplicationEvent(stored: ApplicationStoredEvent): ShellApplicationEvent {
75 return "aggregateKind" in stored
76 ? {
77 aggregateKind: stored.aggregateKind,
78 aggregateId: stored.aggregateId,
79 type: stored.type,
80 sequence: stored.sequence,
81 }
82 : { sequence: stored.sequence, event: { threadId: stored.event.threadId } };
83}
84
85/** Keep only the newest shell-relevant event per project/thread aggregate. */
86export function coalesceShellApplicationEvents<A extends ShellApplicationEvent>(
87 events: ReadonlyArray<A>,
88): ReadonlyArray<A> {
89 const latestByAggregate = new Map<string, A>();
90 for (const stored of events) {
91 const key =
92 "aggregateKind" in stored
93 ? `project:${stored.aggregateId}`
94 : `thread:${stored.event.threadId}`;
95 latestByAggregate.set(key, stored);
96 }
97 return Array.from(latestByAggregate.values()).sort(
98 (left, right) => left.sequence - right.sequence,
99 );
100}
101
102/**
103 * Emit the initial shell prefix strictly first, then merge the post-prefix
104 * tail with enrichment refreshes. Prevents a newer marked enrichment from
105 * landing before the unmarked authoritative initial snapshot.
106 */
107export function composeShellStreamWithEnrichment<A, E, R, A2, E2, R2, A3, E3, R3>(input: {
108 readonly initial: Stream.Stream<A, E, R>;
109 readonly tail: Stream.Stream<A2, E2, R2>;
110 readonly enrichment: Stream.Stream<A3, E3, R3>;
111}): Stream.Stream<A | A2 | A3, E | E2 | E3, R | R2 | R3> {
112 return Stream.concat(input.initial, Stream.merge(input.tail, input.enrichment));
113}
114
115const sameProjects = Schema.toEquivalence(Schema.Array(ProjectShellSchema));
116
117/** Drop repeated metadata refreshes within one subscription, preserving resolution progress. */
118export function dedupeShellEnrichment<E, R>(
119 stream: Stream.Stream<OrchestrationV2ShellStreamItem, E, R>,
120): Stream.Stream<OrchestrationV2ShellStreamItem, E, R> {
121 return Stream.suspend(() => {
122 let previous:
123 | {
124 readonly projects: ReadonlyArray<OrchestrationProjectShell>;
125 readonly roots: ReadonlySet<string>;
126 }
127 | undefined;
128 return stream.pipe(
129 Stream.filter((item) => {
130 if (item.kind !== "snapshot") {
131 // A project delta may change which projects/identities a later refresh repairs.
132 if (item.kind === "project.updated" || item.kind === "project.removed")
133 previous = undefined;
134 return true;
135 }
136 if (
137 item.resolvedRepositoryIdentityRoots === undefined ||
138 item.snapshot.threads.length > 0 ||
139 item.snapshot.archivedThreads.length > 0
140 ) {
141 previous = undefined;
142 return true;
143 }
144 const roots = new Set(item.resolvedRepositoryIdentityRoots);
145 const prior = previous;
146 if (
147 prior !== undefined &&
148 roots.size === prior.roots.size &&
149 [...roots].every((root) => prior.roots.has(root)) &&
150 sameProjects(prior.projects, item.snapshot.projects)
151 )
152 return false;
153 previous = { projects: item.snapshot.projects, roots };
154 return true;
155 }),
156 );
157 });
158}
159
160/** Build a shell snapshot stream item for a batched enrichment completion. */
161export function shellStreamItemFromEnrichmentRefresh(input: {
162 readonly snapshot: OrchestrationV2ShellSnapshot;
163 readonly changes: ReadonlyArray<{ readonly workspaceRoot: string }>;
164}): Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }> {
165 const resolvedRepositoryIdentityRoots = [
166 ...new Set(input.changes.map((change) => change.workspaceRoot)),
167 ];
168 return {
169 kind: "snapshot",
170 snapshot: {
171 ...input.snapshot,
172 projects: input.snapshot.projects.filter((project) =>
173 resolvedRepositoryIdentityRoots.includes(project.workspaceRoot),
174 ),
175 threads: [],
176 archivedThreads: [],
177 },
178 resolvedRepositoryIdentityRoots,
179 };
180}
181
182/**
183 * Initial subscribe frames: always emit the unmarked authoritative snapshot,
184 * then a same-sequence enrichment frame only when some roots already resolved.
185 */
186export function shellStreamItemsFromInitialSnapshot(input: {
187 readonly snapshot: OrchestrationV2ShellSnapshot;
188 readonly resolvedRepositoryIdentityRoots: ReadonlyArray<string>;
189}): ReadonlyArray<Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }>> {
190 const authoritative = {
191 kind: "snapshot" as const,
192 snapshot: input.snapshot,
193 };
194 if (input.resolvedRepositoryIdentityRoots.length === 0) {
195 return [authoritative];
196 }
197 return [
198 authoritative,
199 {
200 kind: "snapshot" as const,
201 snapshot: {
202 ...input.snapshot,
203 projects: input.snapshot.projects.filter((project) =>
204 input.resolvedRepositoryIdentityRoots.includes(project.workspaceRoot),
205 ),
206 threads: [],
207 archivedThreads: [],
208 },
209 resolvedRepositoryIdentityRoots: [...new Set(input.resolvedRepositoryIdentityRoots)],
210 },
211 ];
212}
213
214/** Resume after HTTP/cache hydration with metadata only, never another full shell body. */
215export function shellStreamItemsFromResumeSnapshot(input: {
216 readonly snapshot: OrchestrationV2ShellSnapshot;
217 readonly resolvedRepositoryIdentityRoots: ReadonlyArray<string>;
218}): ReadonlyArray<Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }>> {
219 return shellStreamItemsFromInitialSnapshot(input).filter(
220 (item) => item.resolvedRepositoryIdentityRoots !== undefined,
221 );
222}
223
224const sameThreadShell = Schema.toEquivalence(ThreadShellSchema);
225
226/** How long an unchanged thread shell may go unsent on a live subscription. */
227const UNCHANGED_THREAD_SHELL_RESEND_MS = 5_000;
228
229/**
230 * Drop live `thread.updated` deltas whose shell matches the last one this
231 * subscription sent, apart from `updatedAt`. Every thread event bumps
232 * `updatedAt`, so tool output and streaming text alone used to send the full,
233 * otherwise unchanged shell once per batch.
234 *
235 * A skipped delta leaves the client cursor behind, and a resume replays the
236 * events after that cursor. So an unchanged shell is still sent once its last
237 * send is `UNCHANGED_THREAD_SHELL_RESEND_MS` old. That bounds both the replay
238 * and how stale the client's `updatedAt` can get.
239 */
240export function skipUnchangedThreadShells<A extends OrchestrationV2ShellStreamItem, E, R>(
241 stream: Stream.Stream<A, E, R>,
242): Stream.Stream<A, E, R> {
243 return Stream.suspend(() => {
244 const lastSent = new Map<
245 OrchestrationV2ThreadShell["id"],
246 { readonly thread: OrchestrationV2ThreadShell; readonly sentAt: number }
247 >();
248 return stream.pipe(
249 Stream.filterEffect((item) =>
250 Effect.map(Clock.currentTimeMillis, (now) => {
251 if (item.kind === "thread.removed") {
252 lastSent.delete(item.threadId);
253 return true;
254 }
255 if (item.kind !== "thread.updated") return true;
256 const previous = lastSent.get(item.thread.id);
257 if (
258 previous !== undefined &&
259 now - previous.sentAt < UNCHANGED_THREAD_SHELL_RESEND_MS &&
260 sameThreadShell(
261 { ...item.thread, updatedAt: previous.thread.updatedAt },
262 previous.thread,
263 )
264 ) {
265 return false;
266 }
267 lastSent.set(item.thread.id, { thread: item.thread, sentAt: now });
268 return true;
269 }),
270 ),
271 );
272 });
273}
274
275/** Keep only the newest stored event per thread within a coalescing window. */
276export function coalesceStoredThreadEvents(
277 events: ReadonlyArray<OrchestrationV2StoredEvent>,
278): ReadonlyArray<OrchestrationV2StoredEvent> {
279 const latestByThreadId = new Map<string, OrchestrationV2StoredEvent>();
280 for (const stored of events) {
281 latestByThreadId.set(stored.event.threadId, stored);
282 }
283 return Array.from(latestByThreadId.values()).sort(
284 (left, right) => left.sequence - right.sequence,
285 );
286}
287
288/**
289 * Converts a committed event and the affected thread's current shell into one
290 * delta. `shell` is null when the thread is deleted or unknown.
291 */
292export function shellStreamItemFromThreadShell(input: {
293 readonly stored: Extract<ShellApplicationEvent, { readonly event: unknown }>;
294 readonly shell: OrchestrationV2ThreadShell | null;
295}): Exclude<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }> {
296 if (input.shell !== null) {
297 if (input.shell.archivedAt !== null) {
298 return {
299 kind: "thread.removed",
300 sequence: input.stored.sequence,
301 location: "active",
302 threadId: input.shell.id,
303 };
304 }
305 return {
306 kind: "thread.updated",
307 sequence: input.stored.sequence,
308 location: "active",
309 thread: input.shell,
310 };
311 }
312
313 return {
314 kind: "thread.removed",
315 sequence: input.stored.sequence,
316 location: "active",
317 threadId: input.stored.event.threadId,
318 };
319}
320
321/** Converts a committed event into an archive-only delta when it changes archive membership. */
322export function archivedShellStreamItemFromThreadShell(input: {
323 readonly stored: OrchestrationV2StoredEvent;
324 readonly shell: OrchestrationV2ThreadShell | null;
325}): Exclude<OrchestrationV2ArchivedShellStreamItem, { readonly kind: "snapshot" }> | null {
326 if (input.shell !== null && input.shell.archivedAt !== null) {
327 return {
328 kind: "thread.updated",
329 sequence: input.stored.sequence,
330 thread: input.shell,
331 };
332 }
333 if (
334 input.stored.event.type === "thread.unarchived" ||
335 (input.stored.event.type === "thread.deleted" && input.stored.event.payload.archivedAt !== null)
336 ) {
337 return {
338 kind: "thread.removed",
339 sequence: input.stored.sequence,
340 threadId: input.stored.event.threadId,
341 };
342 }
343 return null;
344}