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 { OrchestrationProjectShell as ProjectShellSchema } from "@t3tools/contracts";
12import * as Schema from "effect/Schema";
13import * as Stream from "effect/Stream";
14
15/** Build the regular navigation shell without duplicating the archive dataset. */
16export function buildActiveShellSnapshot(input: {
17 readonly projects: ReadonlyArray<OrchestrationProjectShell>;
18 readonly threads: OrchestrationV2ThreadShellSnapshot;
19 readonly snapshotSequence: number;
20}): OrchestrationV2ShellSnapshot {
21 return {
22 schemaVersion: input.threads.schemaVersion,
23 snapshotSequence: input.snapshotSequence,
24 projects: input.projects,
25 threads: input.threads.threads,
26 archivedThreads: [],
27 };
28}
29
30export type ShellApplicationEvent =
31 | Pick<
32 Extract<ApplicationStoredEvent, { readonly aggregateKind: "project" }>,
33 "aggregateKind" | "aggregateId" | "type" | "sequence"
34 >
35 | {
36 readonly sequence: number;
37 readonly event: Pick<OrchestrationV2StoredEvent["event"], "threadId">;
38 };
39
40/** Shell updates refetch an aggregate; drop transcript bodies before retaining an event. */
41export function toShellApplicationEvent(stored: ApplicationStoredEvent): ShellApplicationEvent {
42 return "aggregateKind" in stored
43 ? {
44 aggregateKind: stored.aggregateKind,
45 aggregateId: stored.aggregateId,
46 type: stored.type,
47 sequence: stored.sequence,
48 }
49 : { sequence: stored.sequence, event: { threadId: stored.event.threadId } };
50}
51
52/** Keep only the newest shell-relevant event per project/thread aggregate. */
53export function coalesceShellApplicationEvents<A extends ShellApplicationEvent>(
54 events: ReadonlyArray<A>,
55): ReadonlyArray<A> {
56 const latestByAggregate = new Map<string, A>();
57 for (const stored of events) {
58 const key =
59 "aggregateKind" in stored
60 ? `project:${stored.aggregateId}`
61 : `thread:${stored.event.threadId}`;
62 latestByAggregate.set(key, stored);
63 }
64 return Array.from(latestByAggregate.values()).sort(
65 (left, right) => left.sequence - right.sequence,
66 );
67}
68
69/**
70 * Emit the initial shell prefix strictly first, then merge the post-prefix
71 * tail with enrichment refreshes. Prevents a newer marked enrichment from
72 * landing before the unmarked authoritative initial snapshot.
73 */
74export function composeShellStreamWithEnrichment<A, E, R, A2, E2, R2, A3, E3, R3>(input: {
75 readonly initial: Stream.Stream<A, E, R>;
76 readonly tail: Stream.Stream<A2, E2, R2>;
77 readonly enrichment: Stream.Stream<A3, E3, R3>;
78}): Stream.Stream<A | A2 | A3, E | E2 | E3, R | R2 | R3> {
79 return Stream.concat(input.initial, Stream.merge(input.tail, input.enrichment));
80}
81
82const sameProjects = Schema.toEquivalence(Schema.Array(ProjectShellSchema));
83
84/** Drop repeated metadata refreshes within one subscription, preserving resolution progress. */
85export function dedupeShellEnrichment<E, R>(
86 stream: Stream.Stream<OrchestrationV2ShellStreamItem, E, R>,
87): Stream.Stream<OrchestrationV2ShellStreamItem, E, R> {
88 return Stream.suspend(() => {
89 let previous:
90 | {
91 readonly projects: ReadonlyArray<OrchestrationProjectShell>;
92 readonly roots: ReadonlySet<string>;
93 }
94 | undefined;
95 return stream.pipe(
96 Stream.filter((item) => {
97 if (item.kind !== "snapshot") {
98 // A project delta may change which projects/identities a later refresh repairs.
99 if (item.kind === "project.updated" || item.kind === "project.removed")
100 previous = undefined;
101 return true;
102 }
103 if (
104 item.resolvedRepositoryIdentityRoots === undefined ||
105 item.snapshot.threads.length > 0 ||
106 item.snapshot.archivedThreads.length > 0
107 ) {
108 previous = undefined;
109 return true;
110 }
111 const roots = new Set(item.resolvedRepositoryIdentityRoots);
112 const prior = previous;
113 if (
114 prior !== undefined &&
115 roots.size === prior.roots.size &&
116 [...roots].every((root) => prior.roots.has(root)) &&
117 sameProjects(prior.projects, item.snapshot.projects)
118 )
119 return false;
120 previous = { projects: item.snapshot.projects, roots };
121 return true;
122 }),
123 );
124 });
125}
126
127/** Build a shell snapshot stream item for a batched enrichment completion. */
128export function shellStreamItemFromEnrichmentRefresh(input: {
129 readonly snapshot: OrchestrationV2ShellSnapshot;
130 readonly changes: ReadonlyArray<{ readonly workspaceRoot: string }>;
131}): Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }> {
132 const resolvedRepositoryIdentityRoots = [
133 ...new Set(input.changes.map((change) => change.workspaceRoot)),
134 ];
135 return {
136 kind: "snapshot",
137 snapshot: {
138 ...input.snapshot,
139 projects: input.snapshot.projects.filter((project) =>
140 resolvedRepositoryIdentityRoots.includes(project.workspaceRoot),
141 ),
142 threads: [],
143 archivedThreads: [],
144 },
145 resolvedRepositoryIdentityRoots,
146 };
147}
148
149/**
150 * Initial subscribe frames: always emit the unmarked authoritative snapshot,
151 * then a same-sequence enrichment frame only when some roots already resolved.
152 */
153export function shellStreamItemsFromInitialSnapshot(input: {
154 readonly snapshot: OrchestrationV2ShellSnapshot;
155 readonly resolvedRepositoryIdentityRoots: ReadonlyArray<string>;
156}): ReadonlyArray<Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }>> {
157 const authoritative = {
158 kind: "snapshot" as const,
159 snapshot: input.snapshot,
160 };
161 if (input.resolvedRepositoryIdentityRoots.length === 0) {
162 return [authoritative];
163 }
164 return [
165 authoritative,
166 {
167 kind: "snapshot" as const,
168 snapshot: {
169 ...input.snapshot,
170 projects: input.snapshot.projects.filter((project) =>
171 input.resolvedRepositoryIdentityRoots.includes(project.workspaceRoot),
172 ),
173 threads: [],
174 archivedThreads: [],
175 },
176 resolvedRepositoryIdentityRoots: [...new Set(input.resolvedRepositoryIdentityRoots)],
177 },
178 ];
179}
180
181/** Resume after HTTP/cache hydration with metadata only, never another full shell body. */
182export function shellStreamItemsFromResumeSnapshot(input: {
183 readonly snapshot: OrchestrationV2ShellSnapshot;
184 readonly resolvedRepositoryIdentityRoots: ReadonlyArray<string>;
185}): ReadonlyArray<Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }>> {
186 return shellStreamItemsFromInitialSnapshot(input).filter(
187 (item) => item.resolvedRepositoryIdentityRoots !== undefined,
188 );
189}
190
191/** Keep only the newest stored event per thread within a coalescing window. */
192export function coalesceStoredThreadEvents(
193 events: ReadonlyArray<OrchestrationV2StoredEvent>,
194): ReadonlyArray<OrchestrationV2StoredEvent> {
195 const latestByThreadId = new Map<string, OrchestrationV2StoredEvent>();
196 for (const stored of events) {
197 latestByThreadId.set(stored.event.threadId, stored);
198 }
199 return Array.from(latestByThreadId.values()).sort(
200 (left, right) => left.sequence - right.sequence,
201 );
202}
203
204/**
205 * Converts a committed event and the affected thread's current shell into one
206 * delta. `shell` is null when the thread is deleted or unknown.
207 */
208export function shellStreamItemFromThreadShell(input: {
209 readonly stored: Extract<ShellApplicationEvent, { readonly event: unknown }>;
210 readonly shell: OrchestrationV2ThreadShell | null;
211}): Exclude<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }> {
212 if (input.shell !== null) {
213 if (input.shell.archivedAt !== null) {
214 return {
215 kind: "thread.removed",
216 sequence: input.stored.sequence,
217 location: "active",
218 threadId: input.shell.id,
219 };
220 }
221 return {
222 kind: "thread.updated",
223 sequence: input.stored.sequence,
224 location: "active",
225 thread: input.shell,
226 };
227 }
228
229 return {
230 kind: "thread.removed",
231 sequence: input.stored.sequence,
232 location: "active",
233 threadId: input.stored.event.threadId,
234 };
235}
236
237/** Converts a committed event into an archive-only delta when it changes archive membership. */
238export function archivedShellStreamItemFromThreadShell(input: {
239 readonly stored: OrchestrationV2StoredEvent;
240 readonly shell: OrchestrationV2ThreadShell | null;
241}): Exclude<OrchestrationV2ArchivedShellStreamItem, { readonly kind: "snapshot" }> | null {
242 if (input.shell !== null && input.shell.archivedAt !== null) {
243 return {
244 kind: "thread.updated",
245 sequence: input.stored.sequence,
246 thread: input.shell,
247 };
248 }
249 if (
250 input.stored.event.type === "thread.unarchived" ||
251 (input.stored.event.type === "thread.deleted" && input.stored.event.payload.archivedAt !== null)
252 ) {
253 return {
254 kind: "thread.removed",
255 sequence: input.stored.sequence,
256 threadId: input.stored.event.threadId,
257 };
258 }
259 return null;
260}