@vibefield/rosetta-room 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.md +82 -4
  2. package/dist/HistoryRoom.d.ts +15 -2
  3. package/dist/HistoryRoom.js +84 -27
  4. package/dist/TranscriptReader.d.ts +7 -0
  5. package/dist/TranscriptReader.js +4 -4
  6. package/dist/components/ColdStart.js +1 -1
  7. package/dist/components/IngestStatus.d.ts +13 -0
  8. package/dist/components/IngestStatus.js +40 -3
  9. package/dist/components/IngestionControls.d.ts +6 -0
  10. package/dist/components/IngestionControls.js +75 -0
  11. package/dist/components/ListActivityNotice.d.ts +9 -1
  12. package/dist/components/ListActivityNotice.js +9 -2
  13. package/dist/components/SummaryPanels.d.ts +5 -0
  14. package/dist/components/SummaryPanels.js +16 -5
  15. package/dist/components/Transcript.d.ts +5 -0
  16. package/dist/components/Transcript.js +20 -5
  17. package/dist/components/artifacts/ArtifactLibrary.d.ts +14 -0
  18. package/dist/components/artifacts/ArtifactLibrary.js +156 -0
  19. package/dist/components/artifacts/content.d.ts +8 -0
  20. package/dist/components/artifacts/content.js +27 -0
  21. package/dist/components/artifacts/load-all.d.ts +5 -0
  22. package/dist/components/artifacts/load-all.js +31 -0
  23. package/dist/components/artifacts/preview.d.ts +4 -0
  24. package/dist/components/artifacts/preview.js +37 -0
  25. package/dist/components/artifacts/thumbnails.d.ts +13 -0
  26. package/dist/components/artifacts/thumbnails.js +43 -0
  27. package/dist/components/projects/ProjectList.d.ts +9 -3
  28. package/dist/components/projects/ProjectList.js +3 -3
  29. package/dist/components/projects/ProjectListItem.d.ts +9 -3
  30. package/dist/components/projects/ProjectListItem.js +18 -12
  31. package/dist/components/projects/ProjectsColumn.d.ts +4 -1
  32. package/dist/components/projects/ProjectsColumn.js +23 -9
  33. package/dist/components/search/SearchSheet.d.ts +39 -2
  34. package/dist/components/search/SearchSheet.js +82 -17
  35. package/dist/components/sessions/SessionList.d.ts +6 -1
  36. package/dist/components/sessions/SessionList.js +50 -20
  37. package/dist/components/sessions/SessionListItem.d.ts +3 -1
  38. package/dist/components/sessions/SessionListItem.js +17 -7
  39. package/dist/components/sessions/SessionsColumn.d.ts +3 -1
  40. package/dist/components/sessions/SessionsColumn.js +2 -2
  41. package/dist/components/sessions/session-display.d.ts +4 -1
  42. package/dist/components/sessions/session-display.js +13 -2
  43. package/dist/components/transcript/Attachments.js +6 -1
  44. package/dist/components/transcript/Document.d.ts +6 -1
  45. package/dist/components/transcript/Document.js +19 -6
  46. package/dist/components/transcript/ImportState.d.ts +35 -0
  47. package/dist/components/transcript/ImportState.js +86 -0
  48. package/dist/components/transcript/TranscriptLoading.js +15 -5
  49. package/dist/components/transcript/attachment-file-source.d.ts +2 -0
  50. package/dist/components/transcript/attachment-file-source.js +6 -6
  51. package/dist/components/transcript/attachment-gallery.d.ts +2 -1
  52. package/dist/components/transcript/attachment-gallery.js +2 -1
  53. package/dist/components/transcript/detail-parts.js +7 -6
  54. package/dist/components/transcript/timeline-meta-file-source.d.ts +2 -1
  55. package/dist/components/transcript/timeline-meta-file-source.js +45 -5
  56. package/dist/components/ui/EmptyState.d.ts +5 -1
  57. package/dist/components/ui/EmptyState.js +2 -2
  58. package/dist/components/ui/Meter.d.ts +8 -0
  59. package/dist/components/ui/Meter.js +9 -0
  60. package/dist/components/ui/SegmentedControl.d.ts +2 -0
  61. package/dist/components/ui/SegmentedControl.js +1 -1
  62. package/dist/components/ui/Veil.d.ts +2 -1
  63. package/dist/components/ui/Veil.js +9 -2
  64. package/dist/components/ui/index.d.ts +2 -0
  65. package/dist/components/ui/index.js +1 -0
  66. package/dist/fixtures/cold-import-corpus.d.ts +76 -0
  67. package/dist/fixtures/cold-import-corpus.js +349 -0
  68. package/dist/fixtures/cold-import-daemon.d.ts +25 -0
  69. package/dist/fixtures/cold-import-daemon.js +82 -0
  70. package/dist/fixtures/cold-import-schedule.d.ts +74 -0
  71. package/dist/fixtures/cold-import-schedule.js +191 -0
  72. package/dist/fixtures/cold-import.d.ts +151 -0
  73. package/dist/fixtures/cold-import.js +786 -0
  74. package/dist/fixtures/index.d.ts +2 -0
  75. package/dist/fixtures/index.js +21 -2
  76. package/dist/index.d.ts +1 -1
  77. package/dist/index.js +5 -0
  78. package/dist/lib/activity-order.d.ts +15 -0
  79. package/dist/lib/activity-order.js +24 -1
  80. package/dist/lib/conversation-readiness.d.ts +48 -0
  81. package/dist/lib/conversation-readiness.js +149 -0
  82. package/dist/lib/figure-order.d.ts +35 -0
  83. package/dist/lib/figure-order.js +68 -0
  84. package/dist/lib/hooks.d.ts +32 -10
  85. package/dist/lib/hooks.js +122 -55
  86. package/dist/lib/image-media.d.ts +12 -2
  87. package/dist/lib/image-media.js +40 -6
  88. package/dist/lib/import-state.d.ts +98 -0
  89. package/dist/lib/import-state.js +129 -0
  90. package/dist/lib/ingest-activity.d.ts +52 -0
  91. package/dist/lib/ingest-activity.js +127 -12
  92. package/dist/lib/ingest.d.ts +3 -0
  93. package/dist/lib/ingest.js +10 -0
  94. package/dist/lib/model.d.ts +16 -0
  95. package/dist/lib/model.js +27 -1
  96. package/dist/lib/search-sheet.d.ts +43 -0
  97. package/dist/lib/search-sheet.js +56 -7
  98. package/dist/lib/session-activity.d.ts +4 -1
  99. package/dist/lib/session-activity.js +4 -1
  100. package/dist/lib/title-search.d.ts +82 -0
  101. package/dist/lib/title-search.js +194 -0
  102. package/dist/lib/transcript/images.js +2 -2
  103. package/dist/lib/use-deferred-list-order.d.ts +6 -0
  104. package/dist/lib/use-deferred-list-order.js +8 -1
  105. package/dist/lib/use-ingest-activity.d.ts +5 -1
  106. package/dist/lib/use-ingest-activity.js +56 -20
  107. package/dist/ports.d.ts +21 -2
  108. package/dist/room-context.d.ts +1 -0
  109. package/dist/room-context.js +3 -2
  110. package/dist/styles/artifacts.css +66 -0
  111. package/dist/styles/history-room.css +1 -0
  112. package/dist/styles/ingest.css +32 -3
  113. package/dist/styles/room.css +15 -0
  114. package/dist/styles/search.css +17 -0
  115. package/package.json +2 -2
@@ -0,0 +1,786 @@
1
+ // A cold import, simulated: the ports a host hands the room (`RoomPorts`)
2
+ // over a seeded synthetic archive (`cold-import-corpus.ts`), the same
3
+ // daemon's REST doors for a host that builds its ports over a RosettaClient
4
+ // (`cold-import-daemon.ts`), and a controller a test drives through simulated
5
+ // time. It is STEP-DRIVEN: nothing here owns a timer or reads a clock.
6
+ // `advanceTo(ms)` delivers, in order, every metadata change and session
7
+ // resync the daemon would have made by then (`cold-import-schedule.ts` says
8
+ // when, citing rosettad), and every ask answers with the state at the current
9
+ // simulated time. The room keeps its own timers (the status poll, the card's
10
+ // second hand, ALL SET's five seconds, the not-imported face's retry), so a
11
+ // test sees exactly what the room does with what the daemon says, and never
12
+ // measures time with it.
13
+ //
14
+ // What the daemon's surfaces say, and where:
15
+ // - /ws/meta: the mirror withholds a Pending session's activity and stops
16
+ // every family rollup at a Pending member while the admission barrier holds
17
+ // (crates/store/src/hot.rs:591-641; crates/store/src/activity.rs:61-75). A
18
+ // delivery over the hub's 1,024-item queue trips one resync barrier and the
19
+ // client re-reads a snapshot (crates/server/src/hub.rs:44, 627-655). A
20
+ // fresh build lifts the barrier with `reveal_pending`, which re-reads the
21
+ // still-Pending rows and their ancestors (hub.rs:295-307); a resume with
22
+ // `rewarm`, one whole-surface diff that also carries every flip.
23
+ // - Session sockets: a Pending session's snapshot is authoritative and empty
24
+ // (crates/server/src/http.rs:1030-1036); a resync barrier makes the client
25
+ // reset and re-read it (clients/ts/client.ts:1005-1016, 1063-1067;
26
+ // crates/server/src/ws.rs:437-452). Snapshots read the store, which a
27
+ // resume's withheld commit reaches before the hub does. A first snapshot
28
+ // the shared-cache lock refuses ends the socket with a `not_ready` error
29
+ // frame (ws.rs `snapshot_failure`; crates/server/src/http/shared_reads.rs),
30
+ // and the SDK reconnects with backoff (client.ts `retry`).
31
+ // - /api/status: phases, runtime meters, each runtime's admission course
32
+ // (fresh `per_tree`, or `at_runtime_close` for one admitted whole; resumed
33
+ // `at_publication`) and the progress board
34
+ // (crates/server/src/health.rs:208-366; crates/server/src/board.rs:63-140),
35
+ // canonical readiness only once the read router is published (http.rs:821).
36
+ // - Before publication every cross-session aggregate answers `not_ready`
37
+ // (http.rs:510-518) and search answers no hits while it builds
38
+ // (http.rs:1198-1203); the detached index keeps answering none until its
39
+ // first generation (crates/search/src/sidecar.rs:485-490). A boost is
40
+ // recorded and does nothing: a fresh RAM build attaches no boost queue
41
+ // (crates/rosettad/src/serve.rs:375-379).
42
+ import { ApiRequestError, PROTOCOL_VERSION } from "@vibefield/rosetta-protocol";
43
+ import { catalogStatusOf } from "../lib/catalog-status.js";
44
+ import { UNASSIGNED_PROJECT_ID } from "../lib/model.js";
45
+ import { createColdCorpus } from "./cold-import-corpus.js";
46
+ import { ColdWireError, aborted, fetchOver } from "./cold-import-daemon.js";
47
+ import { DISCOVERY_MS, SUBSCRIBER_QUEUE, planSchedule } from "./cold-import-schedule.js";
48
+ /** The store's schema version, which /api/status reports (crates/store/src/schema.rs:12). */
49
+ const SCHEMA_VERSION = 29;
50
+ /* ── synthetic transcripts ──────────────────────────────────────────────── */
51
+ const PROVENANCE = { agent_version: null, src_cursor: null, src_offset: null };
52
+ const NO_USAGE = {
53
+ input: null, output: null, cache_read: null, cache_write: null, thinking: null, cache_write_1h: null,
54
+ web_searches: null, service_tier: null, route: null, billed_pico_usd: null, scope: "request", requests: null,
55
+ };
56
+ const EMPTY_META = { tasks: [], workflows: [], plans: [], artifacts: [] };
57
+ /** A readable session's rows: a few turns inside its recorded bounds, the
58
+ * title's words in the prompt so full text can find it after publication. */
59
+ function transcriptOf(row, activity) {
60
+ const count = 3 + (Number.parseInt(row.id.slice(0, 2), 16) % 6);
61
+ const words = row.title ?? "a delegated task";
62
+ return Array.from({ length: count }, (_, i) => {
63
+ const ordinal = i + 1;
64
+ const user = i % 2 === 0;
65
+ const text = user ? `Please ${words} and keep the change small.` : `Done: ${words}. The tests pass and the diff is short.`;
66
+ return {
67
+ timeline_id: `${row.id.slice(0, 16)}-t${ordinal}`, session_id: row.id, ordinal,
68
+ group: { id: `${row.id.slice(0, 16)}-g${Math.floor(i / 2)}`, kind: user ? "human_turn" : "agent_cycle", derivation: "native" },
69
+ response: null, block_index: null, native_id: null, parent_native_id: null,
70
+ at: Math.round(activity.first_at + ((activity.last_at - activity.first_at) * i) / Math.max(1, count - 1)),
71
+ model: user ? null : "claude-opus-5-5", effort: null,
72
+ body: user
73
+ ? { type: "user", text: { type: "inline", text }, attachments: [] }
74
+ : { type: "agent", text: { type: "inline", text }, attachments: [], citations: [] },
75
+ parent_tool_native_id: null, usage: NO_USAGE, provenance: PROVENANCE,
76
+ };
77
+ });
78
+ }
79
+ const notReady = (what) => new ColdWireError(503, "not_ready", `${what} waits for canonical publication`);
80
+ /** A wire refusal as the SDK raises it, for a host that takes the ports. */
81
+ function asPort(answer) {
82
+ try {
83
+ return Promise.resolve(answer());
84
+ }
85
+ catch (error) {
86
+ return Promise.reject(error instanceof ColdWireError ? new ApiRequestError(error.status, error.code, error.message) : error);
87
+ }
88
+ }
89
+ const records = (bytes) => Math.round(bytes / 3_800);
90
+ export function createColdImport(options) {
91
+ const corpus = createColdCorpus(options);
92
+ const course = options.course ?? "fresh";
93
+ const now = corpus.now;
94
+ const log = {
95
+ status: [], projectStats: [], usage: [], dayUsage: [], search: [], boosts: [], opened: [], closed: [],
96
+ subscribed: [], enabled: [], meta: [], resyncs: [], trail: [],
97
+ };
98
+ let clock = 0;
99
+ let seq = 0;
100
+ const mark = (what, detail = null) => {
101
+ seq += 1;
102
+ log.trail.push({ seq, at: clock, what, detail });
103
+ return seq;
104
+ };
105
+ // A resume always has consent; a fresh build waits for the roll call
106
+ // unless told consent was given before.
107
+ const rollCall = course === "fresh" && (options.consent ?? "awaiting") === "awaiting";
108
+ const whole = new Set(corpus.runtimes.filter((r) => options.wholeRuntimes?.includes(r.kind)).map((r) => r.id));
109
+ let schedule = rollCall ? null : planSchedule(corpus, corpus.runtimes, DISCOVERY_MS, course, whole);
110
+ let runOverride = null;
111
+ let resyncMode = "immediate";
112
+ let revealed = false;
113
+ /** The mirror: sessions out of Pending, and which of them Streaming. */
114
+ const flipped = new Set();
115
+ const streaming = new Set();
116
+ /** The store: sessions whose snapshot reads rows. A fresh flip commits and
117
+ * publishes at once; a resume commits before the hub hears. */
118
+ const committed = new Set();
119
+ const publicRuntimes = new Set();
120
+ const metaSubs = new Set();
121
+ const sessionSubs = new Map();
122
+ const heldResyncs = [];
123
+ let refuseNext = false;
124
+ const refused = [];
125
+ const heldStatus = [];
126
+ let holding = false;
127
+ const kindOf = (id) => corpus.kind.get(id) ?? null;
128
+ const byId = new Map(corpus.sessions.map((row) => [row.id, row]));
129
+ // The SDK's order for sessions: updated_at descending, then id (client.ts:1206-1209).
130
+ const sessionOrder = [...corpus.sessions].sort((a, b) => b.updated_at - a.updated_at || a.id.localeCompare(b.id));
131
+ const rostered = corpus.trees.flatMap((tree) => tree.members);
132
+ /* ── the mirror: what a session row says at this moment ─────────────── */
133
+ /** The family rollup, behind the barrier until publication: a Pending
134
+ * member and everything under it are left out (activity.rs:61-75). */
135
+ const activityOf = (id, hide) => {
136
+ if (hide && !flipped.has(id))
137
+ return null;
138
+ let first = Number.POSITIVE_INFINITY;
139
+ let last = Number.NEGATIVE_INFINITY;
140
+ const visit = (member) => {
141
+ if (hide && !flipped.has(member))
142
+ return;
143
+ const own = flipped.has(member) ? corpus.own.get(member) : undefined;
144
+ if (own !== undefined) {
145
+ first = Math.min(first, own.first_at);
146
+ last = Math.max(last, own.last_at);
147
+ }
148
+ for (const child of corpus.children.get(member) ?? [])
149
+ visit(child);
150
+ };
151
+ visit(id);
152
+ return Number.isFinite(first) ? { first_at: first, last_at: last } : null;
153
+ };
154
+ const rowNow = (identity) => ({
155
+ ...identity,
156
+ activity: activityOf(identity.id, !revealed),
157
+ stream_state: !flipped.has(identity.id) ? "pending" : streaming.has(identity.id) ? "streaming" : "indexed",
158
+ });
159
+ const rows = new Map();
160
+ const isPublic = (row) => publicRuntimes.has(row.runtime_id);
161
+ const state = () => {
162
+ const runtimes = corpus.runtimes.filter((r) => publicRuntimes.has(r.id)).sort((a, b) => a.id.localeCompare(b.id));
163
+ const sessions = sessionOrder.filter(isPublic).map((row) => rows.get(row.id) ?? row);
164
+ const named = new Set(sessions.map((row) => row.project_id));
165
+ const projects = corpus.projects.filter((p) => named.has(p.id))
166
+ .sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
167
+ return { runtimes, projects, sessions };
168
+ };
169
+ /** Re-read the named rows and their ancestors; returns how many changed. */
170
+ const refresh = (ids) => {
171
+ const affected = new Set();
172
+ for (const id of ids) {
173
+ for (let at = id; at !== null && !affected.has(at); at = byId.get(at)?.parent_session_id ?? null)
174
+ affected.add(at);
175
+ }
176
+ let changed = 0;
177
+ for (const id of affected) {
178
+ const identity = byId.get(id);
179
+ if (identity === undefined || !isPublic(identity))
180
+ continue;
181
+ const before = rows.get(id) ?? identity;
182
+ const after = rowNow(identity);
183
+ if (before.stream_state !== after.stream_state || before.activity?.first_at !== after.activity?.first_at ||
184
+ before.activity?.last_at !== after.activity?.last_at) {
185
+ rows.set(id, after);
186
+ changed += 1;
187
+ }
188
+ }
189
+ return changed;
190
+ };
191
+ const publishMeta = (events, why) => {
192
+ if (events === 0)
193
+ return;
194
+ const snapshot = events > SUBSCRIBER_QUEUE;
195
+ log.meta.push({ seq: mark("meta", why), at: clock, source: snapshot ? "snapshot" : "mutation", rows: events, why });
196
+ for (const sub of [...metaSubs]) {
197
+ if (!sub.open)
198
+ continue;
199
+ if (snapshot) {
200
+ // The barrier: one resync, then the client re-reads the mirror.
201
+ sub.handlers.onStatus?.("resyncing");
202
+ sub.handlers.onStatus?.("live");
203
+ sub.handlers.onChange?.(state(), "snapshot");
204
+ }
205
+ else {
206
+ sub.handlers.onChange?.(state(), "mutation");
207
+ }
208
+ }
209
+ };
210
+ const subscribeMeta = (handlers) => {
211
+ const sub = { handlers, open: true };
212
+ metaSubs.add(sub);
213
+ queueMicrotask(() => {
214
+ if (!sub.open)
215
+ return;
216
+ handlers.onStatus?.("live");
217
+ handlers.onChange?.(state(), "snapshot");
218
+ });
219
+ return { close: () => { sub.open = false; metaSubs.delete(sub); } };
220
+ };
221
+ /* ── session sockets ─────────────────────────────────────────────────── */
222
+ const snapshotOf = (sessionId) => {
223
+ const identity = byId.get(sessionId);
224
+ const own = corpus.own.get(sessionId);
225
+ if (identity === undefined || own === undefined || !committed.has(sessionId))
226
+ return [];
227
+ return transcriptOf(identity, own);
228
+ };
229
+ let watermark = 0;
230
+ const deliverSnapshot = (sub) => {
231
+ if (!sub.open)
232
+ return;
233
+ sub.rows = snapshotOf(sub.sessionId);
234
+ sub.hadSnapshot = true;
235
+ watermark += 1;
236
+ sub.handlers.onSnapshot?.({ entries: sub.rows, cursor: null, watermark: String(watermark) });
237
+ sub.handlers.onStatus?.("live");
238
+ sub.handlers.onChange?.(sub.rows);
239
+ sub.handlers.onTimelineMetaChange?.(EMPTY_META);
240
+ };
241
+ /** The SDK's handling of a resync frame, then the daemon's re-read snapshot. */
242
+ const resync = (sub) => {
243
+ if (!sub.open)
244
+ return;
245
+ log.resyncs.push({ seq: mark("resync", sub.sessionId), sessionId: sub.sessionId, at: clock, delivered: true });
246
+ if (sub.hadSnapshot)
247
+ sub.handlers.onReset?.();
248
+ sub.hadSnapshot = false;
249
+ sub.handlers.onStatus?.("resyncing");
250
+ deliverSnapshot(sub);
251
+ };
252
+ /** Raise the barrier on the open subscriptions of `ids`, as `resyncMode` says. */
253
+ const barrier = (ids) => {
254
+ for (const id of ids) {
255
+ for (const sub of sessionSubs.get(id) ?? []) {
256
+ if (resyncMode === "immediate")
257
+ resync(sub);
258
+ else if (resyncMode === "manual")
259
+ heldResyncs.push(sub);
260
+ else
261
+ log.resyncs.push({ seq: mark("resync-lost", id), sessionId: id, at: clock, delivered: false });
262
+ }
263
+ }
264
+ };
265
+ const sessionClient = {
266
+ subscribeSession(sessionId, handlers) {
267
+ const sub = { sessionId, handlers, open: true, hadSnapshot: false, rows: [] };
268
+ log.subscribed.push({ sessionId, at: clock });
269
+ const subs = sessionSubs.get(sessionId) ?? new Set();
270
+ subs.add(sub);
271
+ sessionSubs.set(sessionId, subs);
272
+ if (refuseNext) {
273
+ refuseNext = false;
274
+ refused.push(sub);
275
+ mark("snapshot-refused", sessionId);
276
+ // The SDK's view of the error frame, then of the closed socket.
277
+ queueMicrotask(() => {
278
+ if (!sub.open)
279
+ return;
280
+ sub.handlers.onError?.({ code: "not_ready", message: "the canonical RAM view is momentarily locked; retry" });
281
+ sub.handlers.onStatus?.("connecting");
282
+ });
283
+ }
284
+ else {
285
+ queueMicrotask(() => deliverSnapshot(sub));
286
+ }
287
+ return {
288
+ entries: () => sub.rows,
289
+ fetchPage: async () => ({ entries: [], cursor: null, watermark: String(watermark) }),
290
+ reveal: () => { },
291
+ loadEntry: async (timelineId) => sub.rows.some((row) => row.timeline_id === timelineId),
292
+ close: () => {
293
+ sub.open = false;
294
+ subs.delete(sub);
295
+ },
296
+ };
297
+ },
298
+ subscribeCollaboration: () => ({ close() { }, restart() { } }),
299
+ timelineEntry: async (sessionId, timelineId) => {
300
+ const row = snapshotOf(sessionId).find((entry) => entry.timeline_id === timelineId);
301
+ if (row === undefined)
302
+ throw new ApiRequestError(404, "not_found", "no such message");
303
+ return row;
304
+ },
305
+ reportWork: async () => [],
306
+ command: async () => ({ command: "" }),
307
+ readFileTarget: () => Promise.reject(new Error("The simulated archive keeps no files")),
308
+ readPlan: () => Promise.reject(new Error("The simulated archive keeps no plans")),
309
+ readTextAsset: () => Promise.reject(new Error("The simulated archive keeps no assets")),
310
+ readAsset: () => Promise.reject(new Error("The simulated archive keeps no assets")),
311
+ };
312
+ const sessions = {
313
+ open: (id) => {
314
+ log.opened.push(id);
315
+ return sessionClient;
316
+ },
317
+ close: (id) => {
318
+ log.closed.push(id);
319
+ },
320
+ };
321
+ /* ── applying the schedule ──────────────────────────────────────────── */
322
+ const leavePending = (batch) => {
323
+ for (const id of batch.sessions) {
324
+ flipped.add(id);
325
+ committed.add(id);
326
+ }
327
+ for (const tree of batch.trees)
328
+ if (tree.dirty && !tree.placeholderRoot)
329
+ streaming.add(tree.id);
330
+ };
331
+ /** A fresh flip: the watched sessions' barriers, then the metadata
332
+ * (crates/rosettad/src/cold_stream/flips.rs:9-11; crates/rosettad/src/engine.rs:207-226). */
333
+ const applyBatch = (batch) => {
334
+ leavePending(batch);
335
+ barrier(batch.sessions);
336
+ publishMeta(refresh(batch.sessions), batch.kind === "close" ? "close" : "flip");
337
+ };
338
+ const publishRuntime = (times) => {
339
+ const projectsBefore = state().projects.length;
340
+ publicRuntimes.add(times.runtime.id);
341
+ for (const row of corpus.sessions)
342
+ if (row.runtime_id === times.runtime.id)
343
+ rows.set(row.id, rowNow(row));
344
+ publishMeta(1 + (state().projects.length - projectsBefore) + times.sessions, "metadata");
345
+ };
346
+ /** A fresh build's `reveal_pending`: the still-Pending rows' rollups. */
347
+ const revealPending = () => {
348
+ revealed = true;
349
+ const pending = corpus.sessions.filter((row) => !flipped.has(row.id) && isPublic(row)).map((row) => row.id);
350
+ publishMeta(refresh(pending), "reveal");
351
+ };
352
+ /** A resumed runtime's end: its watched sessions resync and read the
353
+ * store, which still holds them Pending (serve.rs:1329-1336). */
354
+ const closeResumedRuntime = (times) => {
355
+ barrier(corpus.sessions.filter((row) => row.runtime_id === times.runtime.id).map((row) => row.id));
356
+ };
357
+ /** A resume's withheld commit: the store only (serve.rs:1929-1934). */
358
+ const commitResume = () => {
359
+ for (const id of rostered)
360
+ committed.add(id);
361
+ };
362
+ /** A resume's publication: the barrier lifts and one whole-surface diff
363
+ * carries every flip and every revealed rollup, then every watched session
364
+ * resyncs (serve.rs:1397-1407). */
365
+ const publishResume = (batch) => {
366
+ leavePending(batch);
367
+ revealed = true;
368
+ publishMeta(refresh(corpus.sessions.filter(isPublic).map((row) => row.id)), "publication");
369
+ barrier(corpus.sessions.map((row) => row.id));
370
+ };
371
+ const events = () => {
372
+ if (schedule === null)
373
+ return [];
374
+ const list = [];
375
+ for (const times of schedule.runtimes)
376
+ list.push({ at: times.metaPublic, run: () => publishRuntime(times) });
377
+ if (schedule.course === "fresh") {
378
+ for (const batch of schedule.batches)
379
+ list.push({ at: batch.at, run: () => applyBatch(batch) });
380
+ list.push({ at: schedule.phases.get("reveal"), run: revealPending });
381
+ }
382
+ else {
383
+ for (const times of schedule.runtimes)
384
+ list.push({ at: times.close, run: () => closeResumedRuntime(times) });
385
+ list.push({ at: schedule.commitAt, run: commitResume });
386
+ for (const batch of schedule.batches)
387
+ list.push({ at: batch.at, run: () => publishResume(batch) });
388
+ }
389
+ // Stable: same-ms events keep the order they were listed in.
390
+ return list.sort((a, b) => a.at - b.at);
391
+ };
392
+ let pendingEvents = [];
393
+ let nextEvent = 0;
394
+ const replan = () => {
395
+ pendingEvents = events();
396
+ nextEvent = 0;
397
+ };
398
+ replan();
399
+ const advanceTo = (ms) => {
400
+ if (ms < clock)
401
+ throw new Error(`The simulated clock only moves forward (at ${clock}, asked ${ms})`);
402
+ while (nextEvent < pendingEvents.length && pendingEvents[nextEvent].at <= ms) {
403
+ const event = pendingEvents[nextEvent];
404
+ clock = Math.max(clock, event.at);
405
+ nextEvent += 1;
406
+ event.run();
407
+ }
408
+ clock = ms;
409
+ };
410
+ /* ── /api/status at this moment ─────────────────────────────────────── */
411
+ const laneBytesAt = (lane, t) => t <= lane.start ? 0 : t >= lane.end ? lane.bytes : (lane.bytes * (t - lane.start)) / (lane.end - lane.start);
412
+ const at = (name) => schedule?.phases.get(name) ?? Number.POSITIVE_INFINITY;
413
+ const phaseOf = (t) => {
414
+ if (schedule === null)
415
+ return t < DISCOVERY_MS ? "discovering" : "awaiting_consent";
416
+ if (t >= at("live"))
417
+ return "live";
418
+ if (t >= at("publishing"))
419
+ return "publishing";
420
+ if (t >= at("finalizing"))
421
+ return "finalizing";
422
+ if (t < schedule.consentAt)
423
+ return "discovering";
424
+ if (schedule.course === "resumed") {
425
+ // Each runtime's replay says restoring; its skim says backfilling again.
426
+ return schedule.runtimes.some((r) => r.replay !== null && t >= r.replay.start && t < r.replay.end) ? "restoring" : "backfilling";
427
+ }
428
+ // The grant registers each runtime queued; its skim moves the phase on
429
+ // (health.rs:161-189). Consent given earlier never waits.
430
+ if (t < Math.min(...schedule.runtimes.map((r) => r.skimStart)))
431
+ return rollCall ? "awaiting_consent" : "discovering";
432
+ return "backfilling";
433
+ };
434
+ const freshRow = (times, t) => {
435
+ const streamed = times.lanes.reduce((sum, lane) => sum + laneBytesAt(lane, t), 0);
436
+ const stage = t >= times.close ? "done" : t >= (times.applying ?? Infinity) ? "applying" : t >= times.readEnd ? "preparing"
437
+ : t >= times.metaPublic ? "streaming" : t >= times.metaPublic - 20 ? "queued" : t >= times.skimStart ? "skimming" : "queued";
438
+ const skimmed = t >= times.metaPublic - 20 ? 1
439
+ : stage === "skimming" ? (t - times.skimStart) / Math.max(1, times.metaPublic - 20 - times.skimStart) : 0;
440
+ return {
441
+ kind: times.runtime.kind, runtime_id: times.runtime.id, label: null, state: stage,
442
+ files_total: times.files, bytes_total: times.bytes, files_skimmed: Math.round(times.files * Math.min(1, skimmed)),
443
+ bytes_streamed: Math.round(stage === "done" ? times.bytes : streamed),
444
+ sessions_total: Math.round(times.sessions * Math.min(1, skimmed)), records: records(streamed),
445
+ admission_course: schedule?.whole.has(times.runtime.id) ? "at_runtime_close" : "per_tree",
446
+ };
447
+ };
448
+ /** A resumed runtime: queued, its replay streaming, its skim, then its
449
+ * catch-up with no byte total (crates/rosettad/src/cold_progress.rs:37-46),
450
+ * then done. */
451
+ const resumedRow = (times, t) => {
452
+ const replay = times.replay;
453
+ const caughtUp = times.lanes.reduce((sum, lane) => sum + laneBytesAt(lane, t), 0);
454
+ // A resumed attempt opens nothing new before it publishes (serve.rs
455
+ // `run_resumed_fresh_serve`).
456
+ const base = { kind: times.runtime.kind, runtime_id: times.runtime.id, label: null, files_total: times.files,
457
+ admission_course: "at_publication" };
458
+ if (t >= times.metaPublic) {
459
+ const stage = t >= times.close ? "done" : t >= times.readEnd ? "preparing" : "streaming";
460
+ return { ...base, state: stage, bytes_total: 0, files_skimmed: times.files, sessions_total: times.sessions,
461
+ bytes_streamed: Math.round(caughtUp), records: records(caughtUp) };
462
+ }
463
+ if (t >= times.skimStart) {
464
+ const share = (t - times.skimStart) / Math.max(1, times.metaPublic - times.skimStart);
465
+ return { ...base, state: "skimming", bytes_total: times.bytes, files_skimmed: Math.round(times.files * share),
466
+ sessions_total: Math.round(times.sessions * share), bytes_streamed: 0, records: 0 };
467
+ }
468
+ const restored = t >= replay.start ? (replay.bytes * (t - replay.start)) / Math.max(1, replay.end - replay.start) : 0;
469
+ return { ...base, state: t >= replay.start ? "streaming" : "queued", bytes_total: times.bytes, files_skimmed: 0,
470
+ sessions_total: 0, bytes_streamed: Math.round(restored), records: records(restored) };
471
+ };
472
+ const board = (t) => {
473
+ if (schedule === null)
474
+ return [];
475
+ const resumed = schedule.course === "resumed";
476
+ // Seeded per planned (rostered) session under its owner, children
477
+ // included; a session counts done once it is out of Pending in the
478
+ // catalog. A resume knows no byte totals (board.rs:51-57, 127-131).
479
+ const byProject = new Map();
480
+ const seed = (id, streamed) => {
481
+ const projectId = byId.get(id).project_id;
482
+ const entry = byProject.get(projectId) ?? { project_id: projectId, sessions_total: 0, sessions_done: 0, bytes_total: 0, bytes_streamed: 0 };
483
+ byProject.set(projectId, {
484
+ ...entry,
485
+ sessions_total: entry.sessions_total + 1,
486
+ sessions_done: entry.sessions_done + (flipped.has(id) ? 1 : 0),
487
+ bytes_total: resumed ? 0 : entry.bytes_total + (corpus.bytesOf.get(id) ?? 0),
488
+ bytes_streamed: entry.bytes_streamed + Math.round(streamed),
489
+ });
490
+ };
491
+ for (const times of schedule.runtimes) {
492
+ if (t < times.metaPublic)
493
+ continue;
494
+ const read = new Map();
495
+ for (const lane of times.lanes) {
496
+ for (const span of lane.spans) {
497
+ const streamed = Math.max(0, Math.min(span.to, laneBytesAt(lane, t)) - span.from);
498
+ for (const id of span.tree.members)
499
+ read.set(id, (streamed * (corpus.bytesOf.get(id) ?? 0)) / Math.max(1, span.tree.bytes));
500
+ }
501
+ }
502
+ for (const tree of times.trees)
503
+ for (const id of tree.members)
504
+ seed(id, read.get(id) ?? 0);
505
+ }
506
+ // Largest plans first, ties by id (board.rs:121-140).
507
+ return [...byProject.values()].sort((a, b) => b.bytes_total - a.bytes_total || (a.project_id ?? "").localeCompare(b.project_id ?? ""));
508
+ };
509
+ /** The control's run: running, then succeeded once publication is
510
+ * revealed (serve.rs:1605-1607, 1408). */
511
+ const runAt = (t, phase) => {
512
+ const done = t >= at("reveal");
513
+ const runState = runOverride ?? (done ? "succeeded" : "running");
514
+ const runPhase = done ? null
515
+ : phase === "finalizing" || phase === "publishing" || phase === "restoring" ? phase
516
+ : phase === "discovering" || phase === "awaiting_consent" ? "discovering" : "capturing";
517
+ return {
518
+ id: "ing_cold_import", index_id: "idx_cold_import", revision: done ? 3 : schedule === null ? 1 : 2, state: runState,
519
+ phase: runPhase, created_at: now, updated_at: now + t,
520
+ progress_epoch: course === "resumed" ? "epoch-resumed" : "epoch-fresh",
521
+ runtime_ids: schedule === null ? [] : schedule.runtimes.map((r) => r.runtime.id),
522
+ allowed_actions: runState === "running" ? ["pause"] : runState === "paused" ? ["resume"] : [], error: null,
523
+ };
524
+ };
525
+ const published = () => clock >= at("canonical");
526
+ const failingFigures = new Set();
527
+ const searchAt = (t) => {
528
+ const total = Math.max(1, Math.round(899_402 * corpus.scale));
529
+ const building = (progress) => ({
530
+ readiness: "building", progress, projection_epoch: published() ? "epoch-sim" : null, revision: null,
531
+ });
532
+ if (t >= at("search-ready"))
533
+ return { readiness: "ready", progress: null, projection_epoch: "epoch-sim", revision: 1 };
534
+ for (const stage of ["publishing", "validating", "optimizing"]) {
535
+ if (t >= at(`search-${stage}`))
536
+ return building({ stage, documents_done: total, documents_total: total });
537
+ }
538
+ if (t >= at("search-indexing")) {
539
+ const share = (t - at("search-indexing")) / (at("search-optimizing") - at("search-indexing"));
540
+ return building({ stage: "indexing", documents_done: Math.round(total * share), documents_total: total });
541
+ }
542
+ return building(null);
543
+ };
544
+ const statusResponse = () => {
545
+ const t = clock;
546
+ const phase = phaseOf(t);
547
+ const metadataReady = schedule?.phases.get("metadata") ?? null;
548
+ const ingest = {
549
+ phase, run: runAt(t, phase),
550
+ metadata_ready_at: metadataReady !== null && t >= metadataReady ? now + metadataReady : null,
551
+ runtimes: schedule === null ? [] : schedule.runtimes.filter((r) => t >= r.register)
552
+ .map((r) => (schedule.course === "resumed" ? resumedRow(r, t) : freshRow(r, t))),
553
+ projects: board(t),
554
+ };
555
+ return {
556
+ protocol_version: PROTOCOL_VERSION, schema_version: SCHEMA_VERSION, canonical_ready: published(), search: searchAt(t),
557
+ daemon: {
558
+ started_at: now, uptime_ms: t, runtimes: [], ingest,
559
+ hub: { subscribers: metaSubs.size, rings: 0, session_mutations: 0, meta_events: log.meta.length, resyncs: log.resyncs.length,
560
+ rings_evicted: 0, overflow_rewarms: 0 },
561
+ },
562
+ };
563
+ };
564
+ /* ── the daemon's answers, route by route ───────────────────────────── */
565
+ const rootsOf = (projectId) => state().sessions
566
+ .filter((row) => row.parent_session_id === null && (row.project_id ?? UNASSIGNED_PROJECT_ID) === projectId);
567
+ const wire = {
568
+ status(signal) {
569
+ log.status.push(clock);
570
+ mark("status-ask");
571
+ if (signal?.aborted) {
572
+ mark("status-abort");
573
+ return Promise.reject(aborted());
574
+ }
575
+ if (!holding) {
576
+ mark("status-answer");
577
+ return Promise.resolve(statusResponse());
578
+ }
579
+ return new Promise((resolve, reject) => {
580
+ const held = { resolve };
581
+ heldStatus.push(held);
582
+ signal?.addEventListener("abort", () => {
583
+ const index = heldStatus.indexOf(held);
584
+ if (index < 0)
585
+ return;
586
+ heldStatus.splice(index, 1);
587
+ mark("status-abort");
588
+ reject(aborted());
589
+ }, { once: true });
590
+ });
591
+ },
592
+ discoveries() {
593
+ return {
594
+ discoveries: [
595
+ ...corpus.runtimes.map((runtime) => {
596
+ const trees = corpus.trees.filter((tree) => tree.runtimeId === runtime.id);
597
+ const count = corpus.sessions.filter((row) => row.runtime_id === runtime.id).length;
598
+ return {
599
+ kind: runtime.kind, data_root: runtime.data_root, installed: true, files: count, sessions: count,
600
+ bytes: trees.reduce((sum, tree) => sum + tree.bytes, 0),
601
+ newest_modified_ms: Math.max(...trees.map((tree) => tree.recency)), enabled: schedule !== null,
602
+ };
603
+ }),
604
+ { kind: "gemini", data_root: "~/.gemini", installed: false, files: 0, sessions: 0, bytes: 0, newest_modified_ms: 0, enabled: false },
605
+ ],
606
+ };
607
+ },
608
+ enableRuntimes(kinds) {
609
+ log.enabled.push({ kinds: [...kinds], at: clock });
610
+ if (schedule !== null)
611
+ throw new ColdWireError(409, "invalid_transition", "consent was already granted");
612
+ const enrolled = corpus.runtimes.filter((runtime) => kinds.includes(runtime.kind));
613
+ if (enrolled.length === 0)
614
+ throw new ColdWireError(400, "bad_request", "no installed agent was named");
615
+ schedule = planSchedule(corpus, enrolled, Math.max(clock, DISCOVERY_MS), course, whole);
616
+ replan();
617
+ mark("grant", enrolled.map((runtime) => runtime.kind).join(","));
618
+ return { enabled: enrolled.map((runtime) => runtime.kind) };
619
+ },
620
+ heatmap(projectId) {
621
+ log.projectStats.push({ projectId, at: clock });
622
+ if (!published())
623
+ throw notReady("Project figures");
624
+ if (failingFigures.has(projectId))
625
+ throw new ColdWireError(500, "internal", "Project figures failed");
626
+ return { days: [] };
627
+ },
628
+ contribution(projectId) {
629
+ if (!published())
630
+ throw notReady("Project figures");
631
+ return {
632
+ rows: rootsOf(projectId).filter((row) => row.stream_state !== "pending").map((row) => {
633
+ const tokens = 20_000 + (Number.parseInt(row.id.slice(2, 6), 16) % 400) * 1_000;
634
+ return { session_id: row.id, project_id: row.project_id, tokens, commits: 0, edits: 0, loc: 0,
635
+ messages: 3 + (Number.parseInt(row.id.slice(0, 2), 16) % 6), cost_micro_usd: tokens * 3, billed_micro_usd: null,
636
+ unpriced_tokens: 0, unrecorded_output: 0, reported_cost_adjustment_micro_usd: 0 };
637
+ }),
638
+ };
639
+ },
640
+ usage() {
641
+ log.usage.push(clock);
642
+ if (!published())
643
+ throw notReady("Model usage");
644
+ return { models: [], hours: [] };
645
+ },
646
+ dayUsage(_projectId, day) {
647
+ log.dayUsage.push(clock);
648
+ if (!published())
649
+ throw notReady("Day usage");
650
+ return { day, models: [] };
651
+ },
652
+ search(request, signal) {
653
+ log.search.push({ q: request.q, at: clock });
654
+ if (signal?.aborted)
655
+ throw aborted();
656
+ const answered = searchAt(clock);
657
+ if (answered.readiness !== "ready")
658
+ return { state: answered, hits: [] };
659
+ const q = request.q.trim().toLowerCase();
660
+ const hits = [];
661
+ for (const row of state().sessions) {
662
+ if (hits.length >= request.limit)
663
+ break;
664
+ const title = row.title?.toLowerCase() ?? "";
665
+ if (q === "" || !title.includes(q) || row.stream_state === "pending")
666
+ continue;
667
+ const entry = snapshotOf(row.id)[0];
668
+ if (entry === undefined)
669
+ continue;
670
+ hits.push({ timeline_id: entry.timeline_id, session_id: row.id, kind: entry.body.type, at: entry.at,
671
+ snippet: `Please [${request.q.trim()}] and keep the change small.`, score: -1 });
672
+ }
673
+ return { state: answered, hits };
674
+ },
675
+ boost(sessionId) {
676
+ log.boosts.push({ sessionId, at: clock });
677
+ return { queued: false };
678
+ },
679
+ artifacts() {
680
+ return { entries: [], next_cursor: null, canonical_ready: published() };
681
+ },
682
+ };
683
+ /* ── the room's ports ───────────────────────────────────────────────── */
684
+ const connection = new Set();
685
+ const catalog = {
686
+ subscribeMeta,
687
+ status: async (signal) => catalogStatusOf(await wire.status(signal)),
688
+ // A host fires this when its route to the daemon changes
689
+ // (clients/app/renderer/src/host/rosetta-ports.ts:24-31).
690
+ onConnectionChange(listener) {
691
+ const heard = () => {
692
+ mark("connection-change");
693
+ listener();
694
+ };
695
+ connection.add(heard);
696
+ return () => connection.delete(heard);
697
+ },
698
+ projectStats: (projectId) => asPort(() => ({ heat: wire.heatmap(projectId).days, contribution: wire.contribution(projectId).rows })),
699
+ usage: (projectId) => asPort(() => wire.usage(projectId)),
700
+ dayUsage: (projectId, day) => asPort(() => wire.dayUsage(projectId, day)),
701
+ search: (request, signal) => asPort(() => wire.search(request, signal)),
702
+ boost: (sessionId) => asPort(() => wire.boost(sessionId)),
703
+ };
704
+ const assets = {
705
+ imageAssetUrl: () => null,
706
+ attachmentAssetUrl: (asset) => asset.url,
707
+ };
708
+ const consent = {
709
+ discoveries: () => asPort(() => wire.discoveries()),
710
+ enableRuntimes: (kinds) => asPort(() => wire.enableRuntimes(kinds)),
711
+ };
712
+ /* ── the controller ─────────────────────────────────────────────────── */
713
+ const controller = {
714
+ corpus, now, course, log,
715
+ get clock() { return clock; },
716
+ get resyncMode() { return resyncMode; },
717
+ set resyncMode(mode) { resyncMode = mode; },
718
+ phaseAt: (phase) => schedule?.phases.get(phase) ?? null,
719
+ runtimeAt: (runtimeId) => schedule?.runtimes.find((r) => r.runtime.id === runtimeId) ?? null,
720
+ flipAt: (sessionId) => {
721
+ const tree = corpus.treeOf.get(sessionId) ?? corpus.trees.find((t) => t.id === sessionId);
722
+ return tree === undefined ? null : (schedule?.flipAt.get(tree.id) ?? null);
723
+ },
724
+ kindOf,
725
+ treeOf: (sessionId) => corpus.treeOf.get(sessionId) ?? corpus.trees.find((t) => t.id === sessionId) ?? null,
726
+ batches: () => schedule?.batches ?? [],
727
+ advanceTo,
728
+ advanceToPhase(phase) {
729
+ const when = schedule?.phases.get(phase);
730
+ if (when === undefined)
731
+ throw new Error(`No ${phase} phase is scheduled${schedule === null ? " before consent" : ` for a ${course} import`}`);
732
+ advanceTo(Math.max(clock, when));
733
+ },
734
+ meta: state,
735
+ streamState: (sessionId) => {
736
+ const identity = byId.get(sessionId);
737
+ return identity === undefined || !isPublic(identity) ? null : (rows.get(sessionId) ?? identity).stream_state;
738
+ },
739
+ status: () => catalogStatusOf(statusResponse()),
740
+ statusResponse,
741
+ phase: () => phaseOf(clock),
742
+ holdStatus() { holding = true; },
743
+ releaseStatus() {
744
+ holding = false;
745
+ const waiting = heldStatus.splice(0);
746
+ for (const held of waiting) {
747
+ mark("status-answer");
748
+ held.resolve(statusResponse());
749
+ }
750
+ return waiting.length;
751
+ },
752
+ heldStatus: () => heldStatus.length,
753
+ deliverResyncs() {
754
+ const waiting = heldResyncs.splice(0);
755
+ for (const sub of waiting)
756
+ resync(sub);
757
+ return waiting.length;
758
+ },
759
+ refuseNextSnapshot() { refuseNext = true; },
760
+ retryRefused() {
761
+ const waiting = refused.splice(0);
762
+ for (const sub of waiting)
763
+ deliverSnapshot(sub);
764
+ return waiting.length;
765
+ },
766
+ setRunState(next) { runOverride = next === "running" ? null : next; },
767
+ connectionChange() {
768
+ const listeners = [...connection];
769
+ for (const listener of listeners)
770
+ listener();
771
+ return listeners.length;
772
+ },
773
+ mark(what, detail) { mark(what, detail ?? null); },
774
+ failFigures(projectId, failing) {
775
+ if (failing)
776
+ failingFigures.add(projectId);
777
+ else
778
+ failingFigures.delete(projectId);
779
+ },
780
+ };
781
+ return {
782
+ ports: { catalog, sessions, assets }, consent,
783
+ daemon: { fetch: fetchOver(wire), subscribeMeta },
784
+ controller,
785
+ };
786
+ }