@swirls/looms 0.8.0 → 0.10.0

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 (94) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/actor/routing.js +2 -1
  3. package/dist/agent/debugger/agent-chat.js +6 -5
  4. package/dist/agent/debugger/index.js +2 -1
  5. package/dist/agent/module.d.ts +799 -593
  6. package/dist/agent/module.js +31 -0
  7. package/dist/agent/scope.js +1 -0
  8. package/dist/agent/signals.d.ts +108 -15
  9. package/dist/agent/signals.js +70 -47
  10. package/dist/approval/debugger/approvals-view.js +1 -1
  11. package/dist/approval/index.d.ts +1 -0
  12. package/dist/approval/index.js +1 -0
  13. package/dist/approval/module.d.ts +42 -1
  14. package/dist/approval/module.js +53 -0
  15. package/dist/approval/scope.js +1 -0
  16. package/dist/approval/signals.d.ts +19 -13
  17. package/dist/approval/signals.js +25 -45
  18. package/dist/approval/steps.d.ts +11 -0
  19. package/dist/approval/steps.js +39 -0
  20. package/dist/cli/commands.js +87 -16
  21. package/dist/client/client.d.ts +211 -0
  22. package/dist/client/client.js +18 -1
  23. package/dist/core/index.d.ts +1 -0
  24. package/dist/core/index.js +1 -0
  25. package/dist/core/module-scope.d.ts +50 -5
  26. package/dist/core/module-scope.js +22 -2
  27. package/dist/core/module.d.ts +29 -2
  28. package/dist/core/projection.d.ts +1 -0
  29. package/dist/core/published.d.ts +59 -1
  30. package/dist/core/published.js +97 -1
  31. package/dist/core/signals.d.ts +56 -0
  32. package/dist/core/signals.js +93 -0
  33. package/dist/core/validate-event.d.ts +12 -1
  34. package/dist/core/validate-event.js +34 -11
  35. package/dist/debugger/app/assets/index-CO5gIvV8.css +2 -0
  36. package/dist/debugger/app/assets/{index-CMRl_aWQ.js → index-D-2Q7ecG.js} +2 -2
  37. package/dist/debugger/app/assets/routes-lvmllT60.js +47 -0
  38. package/dist/debugger/app/index.html +2 -2
  39. package/dist/debugger/index.d.ts +1 -1
  40. package/dist/debugger/index.js +1 -1
  41. package/dist/debugger/lib/cn.d.ts +1 -1
  42. package/dist/debugger/lib/cn.js +12 -1
  43. package/dist/debugger/plugin.d.ts +11 -1
  44. package/dist/debugger/plugin.js +41 -0
  45. package/dist/debugger/shell/debugger-shell.js +1 -1
  46. package/dist/debugger/shell/form-fields.d.ts +17 -0
  47. package/dist/debugger/shell/form-fields.js +38 -0
  48. package/dist/debugger/shell/run-action.d.ts +6 -0
  49. package/dist/debugger/shell/run-action.js +15 -0
  50. package/dist/debugger/shell/run-controls.js +3 -55
  51. package/dist/debugger/shell/schema-form.d.ts +10 -1
  52. package/dist/debugger/shell/schema-form.js +108 -10
  53. package/dist/debugger/shell/signal-form.d.ts +18 -0
  54. package/dist/debugger/shell/signal-form.js +185 -0
  55. package/dist/debugger/shell/start-form.js +2 -32
  56. package/dist/debugger/shell/use-debounced-preview.d.ts +22 -0
  57. package/dist/debugger/shell/use-debounced-preview.js +68 -0
  58. package/dist/evaluator/index.d.ts +1 -1
  59. package/dist/evaluator/index.js +1 -1
  60. package/dist/evaluator/module.d.ts +8 -1
  61. package/dist/evaluator/module.js +33 -0
  62. package/dist/evaluator/scope.js +1 -0
  63. package/dist/projectors/event-log-ops.d.ts +68 -0
  64. package/dist/projectors/event-log-ops.js +79 -0
  65. package/dist/projectors/event-log.d.ts +4 -68
  66. package/dist/projectors/event-log.js +4 -79
  67. package/dist/projectors/replica/migrations.d.ts +4 -6
  68. package/dist/projectors/replica/migrations.js +18 -1
  69. package/dist/projectors/replica/sqlite-bun.d.ts +5 -0
  70. package/dist/projectors/replica/sqlite-bun.js +39 -0
  71. package/dist/projectors/replica/sqlite-migrations.d.ts +5 -0
  72. package/dist/projectors/replica/sqlite-migrations.js +99 -0
  73. package/dist/projectors/replica/sqlite.d.ts +95 -0
  74. package/dist/projectors/replica/sqlite.js +517 -0
  75. package/dist/runtime/server/routes/definitions.d.ts +1 -1
  76. package/dist/runtime/server/routes/definitions.js +58 -2
  77. package/dist/runtime/server/routes/runs.js +25 -1
  78. package/dist/schedule/module.d.ts +117 -1
  79. package/dist/schedule/module.js +30 -0
  80. package/dist/schedule/scope.js +1 -0
  81. package/dist/schedule/signals.d.ts +59 -7
  82. package/dist/schedule/signals.js +35 -17
  83. package/dist/testing/corpus-module.d.ts +1 -1
  84. package/dist/testing/index.js +2 -1
  85. package/dist/testing/module-examples.d.ts +6 -0
  86. package/dist/testing/module-examples.js +66 -0
  87. package/dist/workflow/module.d.ts +3 -1
  88. package/dist/workflow/module.js +13 -0
  89. package/dist/workflow/scope.js +1 -0
  90. package/package.json +17 -1
  91. package/dist/debugger/app/assets/index-B7GdT1UA.css +0 -2
  92. package/dist/debugger/app/assets/routes-CfXxKG45.js +0 -47
  93. /package/dist/evaluator/{signals.d.ts → steps.d.ts} +0 -0
  94. /package/dist/evaluator/{signals.js → steps.js} +0 -0
@@ -0,0 +1,517 @@
1
+ import { Effect, Predicate, Schema, Stream } from 'effect';
2
+ import { EventOriginSchema, EventStoreError, JsonValueSchema, foldRun, } from '@swirls/looms/core';
3
+ import { eventLogOps } from '../event-log-ops.js';
4
+ import { indexOpsFor } from '../index-model.js';
5
+ import { ReplicaGapError } from '../projector.js';
6
+ import { SQLITE_REPLICA_MIGRATIONS } from './sqlite-migrations.js';
7
+ const REPLICA_NAME = 'sqlite-replica';
8
+ const REPLICA_VERSION = '1';
9
+ const READ_PAGE = 500;
10
+ /** D1 batches are capped. Statements are idempotent and the cursor update is last, so a split batch resumes. */
11
+ const D1_BATCH = 100;
12
+ const terminalStatuses = new Set(['completed', 'failed', 'cancelled']);
13
+ /**
14
+ * Adapts Cloudflare D1.
15
+ * The statement type is inferred from `prepare().bind()` so `D1Database` itself is accepted:
16
+ * D1's `batch` only takes the statements its own `prepare` returns.
17
+ */
18
+ export function d1ReplicaDatabase(d1) {
19
+ const bound = (sql, params = []) => d1.prepare(sql).bind(...params);
20
+ return {
21
+ exec: (sql) => d1.exec(sql).then(() => undefined),
22
+ get: (sql, params) => bound(sql, params).first(),
23
+ all: async (sql, params = []) => {
24
+ const result = await bound(sql, params).all();
25
+ return result.results ?? [];
26
+ },
27
+ batch: async (statements) => {
28
+ for (let index = 0; index < statements.length; index += D1_BATCH) {
29
+ const slice = statements.slice(index, index + D1_BATCH);
30
+ if (slice.length === 0) {
31
+ continue;
32
+ }
33
+ await d1.batch(slice.map((statement) => bound(statement.sql, statement.params)));
34
+ }
35
+ },
36
+ };
37
+ }
38
+ const decodeJson = Schema.decodeUnknownSync(JsonValueSchema);
39
+ const decodeOrigin = Schema.decodeUnknownSync(EventOriginSchema);
40
+ function asNumber(value) {
41
+ if (Predicate.isNumber(value)) {
42
+ return value;
43
+ }
44
+ if (Predicate.isString(value)) {
45
+ return Number(value);
46
+ }
47
+ return Number(value);
48
+ }
49
+ function jsonText(value) {
50
+ return JSON.stringify(value) ?? 'null';
51
+ }
52
+ function parseJson(text) {
53
+ // SAFETY: payload and origin columns are JSON text written by jsonText.
54
+ const parsed = JSON.parse(text);
55
+ return decodeJson(parsed);
56
+ }
57
+ function isEphemeral(value) {
58
+ if (Predicate.isBoolean(value)) {
59
+ return value;
60
+ }
61
+ if (Predicate.isNumber(value)) {
62
+ return value !== 0;
63
+ }
64
+ return value === '1';
65
+ }
66
+ function epochOrNull(value) {
67
+ if (value === null) {
68
+ return null;
69
+ }
70
+ return asNumber(value);
71
+ }
72
+ function envelope(row) {
73
+ const event = {
74
+ id: row.event_id,
75
+ runId: row.run_id,
76
+ seq: asNumber(row.seq),
77
+ ts: asNumber(row.ts),
78
+ type: row.type,
79
+ payload: parseJson(row.payload),
80
+ threadId: row.thread_id,
81
+ parentThreadId: row.parent_thread_id,
82
+ origin: decodeOrigin(parseJson(row.origin)),
83
+ idempotencyKey: row.idempotency_key,
84
+ };
85
+ if (row.causation_id !== null) {
86
+ event.causationId = row.causation_id;
87
+ }
88
+ if (row.correlation_id !== null) {
89
+ event.correlationId = row.correlation_id;
90
+ }
91
+ if (row.effect_id !== null) {
92
+ event.effectId = row.effect_id;
93
+ }
94
+ if (isEphemeral(row.ephemeral)) {
95
+ event.ephemeral = true;
96
+ }
97
+ return event;
98
+ }
99
+ function groups(events) {
100
+ const byRun = new Map();
101
+ for (const event of events) {
102
+ const batch = byRun.get(event.runId);
103
+ if (batch) {
104
+ batch.push(event);
105
+ }
106
+ else {
107
+ byRun.set(event.runId, [event]);
108
+ }
109
+ }
110
+ for (const batch of byRun.values()) {
111
+ batch.sort((left, right) => left.seq - right.seq);
112
+ }
113
+ return byRun;
114
+ }
115
+ /** Sequence through which `events` extends `replicatedSeq` with no hole. Redelivered seqs are ignored. */
116
+ function contiguousSeq(runId, replicatedSeq, events) {
117
+ let cursor = replicatedSeq;
118
+ for (const event of events) {
119
+ if (event.seq <= cursor) {
120
+ continue;
121
+ }
122
+ if (event.seq !== cursor + 1) {
123
+ throw new ReplicaGapError({ runId, replicatedSeq, batchFrom: event.seq });
124
+ }
125
+ cursor = event.seq;
126
+ }
127
+ return cursor;
128
+ }
129
+ function sqlStatement(sql, params) {
130
+ return { sql, params };
131
+ }
132
+ function insertEvents(events) {
133
+ return events.map((event) => sqlStatement(`INSERT INTO looms_run_events (
134
+ run_id, seq, event_id, ts, type, payload, thread_id, parent_thread_id,
135
+ causation_id, correlation_id, effect_id, origin, idempotency_key, ephemeral
136
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
137
+ ON CONFLICT (run_id, seq) DO NOTHING`, [
138
+ event.runId,
139
+ event.seq,
140
+ event.id,
141
+ event.ts,
142
+ event.type,
143
+ jsonText(event.payload),
144
+ event.threadId,
145
+ event.parentThreadId ?? null,
146
+ event.causationId ?? null,
147
+ event.correlationId ?? null,
148
+ event.effectId ?? null,
149
+ jsonText(event.origin),
150
+ event.idempotencyKey ?? null,
151
+ event.ephemeral === true ? 1 : 0,
152
+ ]));
153
+ }
154
+ function runIndexPatches(ops) {
155
+ const patches = new Map();
156
+ for (const op of ops) {
157
+ if (op.type === 'insert') {
158
+ continue;
159
+ }
160
+ const patch = patches.get(op.runId) ?? {
161
+ runId: op.runId,
162
+ start: null,
163
+ finish: null,
164
+ completedAt: null,
165
+ updatedAt: op.at,
166
+ };
167
+ patch.updatedAt = Math.max(patch.updatedAt, op.at);
168
+ if (op.type === 'start') {
169
+ patch.start ??= op;
170
+ }
171
+ if (op.type === 'finish') {
172
+ patch.finish = op;
173
+ patch.completedAt ??= op.at;
174
+ }
175
+ patches.set(op.runId, patch);
176
+ }
177
+ return [...patches.values()];
178
+ }
179
+ function upsertRun(patch) {
180
+ const start = patch.start;
181
+ return sqlStatement(`INSERT INTO looms_run_index (
182
+ run_id, status, kind, definition_name, definition_version, root_thread_id,
183
+ parent_run_id, launched_by_effect_id, correlation_id, attributes,
184
+ tenant, project, org, started_at, updated_at, completed_at
185
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
186
+ ON CONFLICT (run_id) DO UPDATE SET
187
+ status = CASE
188
+ WHEN excluded.completed_at IS NOT NULL THEN excluded.status
189
+ WHEN looms_run_index.status IN ('completed', 'failed', 'cancelled') THEN looms_run_index.status
190
+ ELSE excluded.status
191
+ END,
192
+ kind = COALESCE(looms_run_index.kind, excluded.kind),
193
+ definition_name = COALESCE(looms_run_index.definition_name, excluded.definition_name),
194
+ definition_version = COALESCE(looms_run_index.definition_version, excluded.definition_version),
195
+ root_thread_id = COALESCE(looms_run_index.root_thread_id, excluded.root_thread_id),
196
+ parent_run_id = COALESCE(looms_run_index.parent_run_id, excluded.parent_run_id),
197
+ launched_by_effect_id = COALESCE(looms_run_index.launched_by_effect_id, excluded.launched_by_effect_id),
198
+ correlation_id = COALESCE(looms_run_index.correlation_id, excluded.correlation_id),
199
+ attributes = CASE
200
+ WHEN looms_run_index.attributes = '{}' THEN excluded.attributes
201
+ ELSE looms_run_index.attributes
202
+ END,
203
+ tenant = COALESCE(looms_run_index.tenant, excluded.tenant),
204
+ project = COALESCE(looms_run_index.project, excluded.project),
205
+ org = COALESCE(looms_run_index.org, excluded.org),
206
+ started_at = COALESCE(looms_run_index.started_at, excluded.started_at),
207
+ updated_at = MAX(looms_run_index.updated_at, excluded.updated_at),
208
+ completed_at = COALESCE(looms_run_index.completed_at, excluded.completed_at)`, [
209
+ patch.runId,
210
+ patch.finish?.status ?? 'running',
211
+ start?.kind ?? null,
212
+ start?.definitionName ?? null,
213
+ start?.definitionVersion ?? null,
214
+ start?.rootThreadId ?? null,
215
+ start?.parentRunId ?? null,
216
+ start?.launchedByEffectId ?? null,
217
+ start?.correlationId ?? null,
218
+ jsonText(start?.attributes ?? {}),
219
+ start?.tenant ?? null,
220
+ start?.project ?? null,
221
+ start?.org ?? null,
222
+ start ? start.at : null,
223
+ patch.updatedAt,
224
+ patch.completedAt,
225
+ ]);
226
+ }
227
+ function runIndexStatements(ops) {
228
+ const statements = [];
229
+ for (const patch of runIndexPatches(ops)) {
230
+ if (patch.start || patch.finish) {
231
+ statements.push(upsertRun(patch));
232
+ continue;
233
+ }
234
+ statements.push(sqlStatement(`UPDATE looms_run_index SET updated_at = MAX(updated_at, ?) WHERE run_id = ?`, [
235
+ patch.updatedAt,
236
+ patch.runId,
237
+ ]));
238
+ }
239
+ return statements;
240
+ }
241
+ function indexStatements(ops) {
242
+ return ops.map((op) => {
243
+ switch (op.type) {
244
+ case 'upsertActor':
245
+ return sqlStatement(`INSERT INTO looms_run_actors (
246
+ run_id, actor_id, kind, status, definition_name, parent_actor_id,
247
+ launched_by_run_id, launched_by_effect_id, correlation_id, updated_at
248
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
249
+ ON CONFLICT (run_id, actor_id) DO UPDATE SET
250
+ kind = excluded.kind,
251
+ status = excluded.status,
252
+ definition_name = excluded.definition_name,
253
+ parent_actor_id = excluded.parent_actor_id,
254
+ launched_by_run_id = excluded.launched_by_run_id,
255
+ launched_by_effect_id = excluded.launched_by_effect_id,
256
+ correlation_id = excluded.correlation_id,
257
+ updated_at = excluded.updated_at`, [
258
+ op.runId,
259
+ op.actorId,
260
+ op.kind,
261
+ op.status,
262
+ op.definitionName,
263
+ op.parentActorId,
264
+ op.launchedByRunId,
265
+ op.launchedByEffectId,
266
+ op.correlationId,
267
+ op.updatedAt,
268
+ ]);
269
+ case 'setActorStatus':
270
+ return sqlStatement(`INSERT INTO looms_run_actors (run_id, actor_id, status, updated_at)
271
+ VALUES (?, ?, ?, ?)
272
+ ON CONFLICT (run_id, actor_id) DO UPDATE SET
273
+ status = excluded.status,
274
+ updated_at = excluded.updated_at`, [op.runId, op.actorId, op.status, op.updatedAt]);
275
+ case 'upsertReview':
276
+ return sqlStatement(`INSERT INTO looms_run_reviews (run_id, review_id, status, title, updated_at)
277
+ VALUES (?, ?, ?, ?, ?)
278
+ ON CONFLICT (run_id, review_id) DO UPDATE SET
279
+ status = excluded.status,
280
+ updated_at = excluded.updated_at`, [op.runId, op.reviewId, op.status, op.title, op.updatedAt]);
281
+ case 'setReviewStatus':
282
+ return sqlStatement(`UPDATE looms_run_reviews SET status = ?, updated_at = ? WHERE run_id = ? AND review_id = ?`, [op.status, op.updatedAt, op.runId, op.reviewId]);
283
+ default: {
284
+ const unexpected = op;
285
+ return unexpected;
286
+ }
287
+ }
288
+ });
289
+ }
290
+ export function sqliteReplica(options) {
291
+ const database = options.database;
292
+ let ready;
293
+ const appliedMigrationIds = async () => {
294
+ const table = await database.get(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'looms_schema_migrations'`);
295
+ if (!table) {
296
+ return new Set();
297
+ }
298
+ const rows = await database.all(`SELECT id FROM looms_schema_migrations`);
299
+ return new Set(rows.map((row) => row.id));
300
+ };
301
+ const pendingMigrations = async () => {
302
+ const applied = await appliedMigrationIds();
303
+ return SQLITE_REPLICA_MIGRATIONS.filter((migration) => !applied.has(migration.id)).map((migration) => migration.id);
304
+ };
305
+ const migrate = async () => {
306
+ const applied = await appliedMigrationIds();
307
+ for (const migration of SQLITE_REPLICA_MIGRATIONS) {
308
+ if (!applied.has(migration.id)) {
309
+ await database.exec(migration.sql);
310
+ }
311
+ }
312
+ };
313
+ const verify = async () => {
314
+ const pending = await pendingMigrations();
315
+ if (pending.length > 0) {
316
+ throw new Error(`Looms replica is missing migrations: ${pending.join(', ')}. Generate them with \`looms replica generate --dialect sqlite\` and apply the files before starting.`);
317
+ }
318
+ };
319
+ const init = () => {
320
+ ready ??= (options.migrate === 'verify' ? verify() : migrate()).catch((cause) => {
321
+ ready = undefined;
322
+ throw cause;
323
+ });
324
+ return ready;
325
+ };
326
+ const project = async (events) => {
327
+ await init();
328
+ if (events.length === 0) {
329
+ return;
330
+ }
331
+ const statements = [];
332
+ for (const [runId, batch] of groups(events)) {
333
+ const progress = await database.get(`SELECT replicated_seq, purged_at FROM looms_run_index WHERE run_id = ?`, [runId]);
334
+ if (progress?.purged_at != null) {
335
+ continue;
336
+ }
337
+ const replicatedSeq = progress ? asNumber(progress.replicated_seq) : 0;
338
+ const next = contiguousSeq(runId, replicatedSeq, batch);
339
+ const durable = batch.filter((event) => !event.ephemeral);
340
+ const last = batch.at(-1);
341
+ statements.push(...insertEvents(batch));
342
+ statements.push(...runIndexStatements(durable.flatMap((event) => eventLogOps(event))));
343
+ statements.push(...indexStatements(durable.flatMap(indexOpsFor)));
344
+ if (next === replicatedSeq || !last) {
345
+ continue;
346
+ }
347
+ statements.push(sqlStatement(`INSERT INTO looms_run_index (run_id, status, updated_at, replicated_seq)
348
+ VALUES (?, 'running', ?, ?)
349
+ ON CONFLICT (run_id) DO UPDATE SET
350
+ replicated_seq = MAX(looms_run_index.replicated_seq, excluded.replicated_seq)
351
+ WHERE looms_run_index.purged_at IS NULL`, [runId, last.ts, next]));
352
+ }
353
+ await database.batch(statements);
354
+ };
355
+ const position = async (runId) => {
356
+ const row = await database.get(`SELECT replicated_seq, purged_at FROM looms_run_index WHERE run_id = ?`, [runId]);
357
+ if (!row) {
358
+ return 0;
359
+ }
360
+ if (row.purged_at != null) {
361
+ return null;
362
+ }
363
+ return asNumber(row.replicated_seq);
364
+ };
365
+ const readPage = async (runId, fromSeq, limit) => {
366
+ const rows = await database.all(`SELECT run_id, seq, event_id, ts, type, payload, thread_id, parent_thread_id,
367
+ causation_id, correlation_id, effect_id, origin, idempotency_key, ephemeral
368
+ FROM looms_run_events
369
+ WHERE run_id = ? AND seq >= ?
370
+ ORDER BY seq
371
+ LIMIT ?`, [runId, fromSeq, limit]);
372
+ return rows.map(envelope);
373
+ };
374
+ const readEvents = (runId, readOptions) => Effect.tryPromise({
375
+ try: async () => {
376
+ const fromSeq = readOptions?.fromSeq ?? 1;
377
+ const events = [];
378
+ let cursor = fromSeq;
379
+ let remaining = readOptions?.limit;
380
+ while (remaining === undefined || remaining > 0) {
381
+ const take = remaining === undefined ? READ_PAGE : Math.min(READ_PAGE, remaining);
382
+ const page = await readPage(runId, cursor, take);
383
+ events.push(...page);
384
+ if (remaining !== undefined) {
385
+ remaining -= page.length;
386
+ }
387
+ const last = page.at(-1);
388
+ if (!last || page.length < take) {
389
+ break;
390
+ }
391
+ cursor = last.seq + 1;
392
+ }
393
+ return events;
394
+ },
395
+ catch: (cause) => new EventStoreError('Replica read failed', cause),
396
+ });
397
+ const store = {
398
+ append: () => Effect.fail(new EventStoreError('The SQLite replica is read-only')),
399
+ read: readEvents,
400
+ readStream: (runId, readOptions) => Stream.fromIterableEffect(readEvents(runId, readOptions)),
401
+ tail: (runId) => Effect.tryPromise({
402
+ try: async () => {
403
+ const row = await database.get(`SELECT replicated_seq FROM looms_run_index WHERE run_id = ?`, [runId]);
404
+ return row ? asNumber(row.replicated_seq) : 0;
405
+ },
406
+ catch: (cause) => new EventStoreError('Replica tail failed', cause),
407
+ }),
408
+ bounds: (runId) => Effect.tryPromise({
409
+ try: async () => {
410
+ const row = await database.get(`SELECT replicated_seq,
411
+ (SELECT MIN(seq) FROM looms_run_events event WHERE event.run_id = run.run_id) AS head
412
+ FROM looms_run_index run
413
+ WHERE run.run_id = ?`, [runId]);
414
+ if (!row) {
415
+ return { head: 1, tail: 0 };
416
+ }
417
+ const tail = asNumber(row.replicated_seq);
418
+ const head = row.head === null ? tail + 1 : asNumber(row.head);
419
+ return { head, tail };
420
+ },
421
+ catch: (cause) => new EventStoreError('Replica bounds failed', cause),
422
+ }),
423
+ trim: () => Effect.fail(new EventStoreError('Trim a replica with purge()')),
424
+ subscribe: (runId, readOptions) => Stream.fromIterableEffect(readEvents(runId, readOptions)),
425
+ listRuns: Effect.tryPromise({
426
+ try: async () => {
427
+ const rows = await database.all(`SELECT run_id FROM looms_run_index WHERE purged_at IS NULL ORDER BY run_id`);
428
+ return rows.map((row) => row.run_id);
429
+ },
430
+ catch: (cause) => new EventStoreError('Replica listRuns failed', cause),
431
+ }),
432
+ };
433
+ const loadRun = async (runId, registry) => {
434
+ const events = await Effect.runPromise(readEvents(runId));
435
+ return foldRun(events, registry, { runId });
436
+ };
437
+ const status = async (runId) => {
438
+ const row = await database.get(`SELECT run.replicated_seq,
439
+ run.status,
440
+ run.purged_at,
441
+ (SELECT MAX(seq) FROM looms_run_events event WHERE event.run_id = run.run_id) AS max_seq
442
+ FROM looms_run_index run
443
+ WHERE run.run_id = ?`, [runId]);
444
+ if (!row) {
445
+ return null;
446
+ }
447
+ const replicatedSeq = asNumber(row.replicated_seq);
448
+ const finished = terminalStatuses.has(row.status);
449
+ const purgedAt = epochOrNull(row.purged_at);
450
+ const maxSeq = row.max_seq === null ? null : asNumber(row.max_seq);
451
+ const copiedThroughFinish = purgedAt !== null || (maxSeq !== null && maxSeq === replicatedSeq && replicatedSeq > 0);
452
+ return {
453
+ replicatedSeq,
454
+ finished,
455
+ complete: finished && copiedThroughFinish,
456
+ purgedAt,
457
+ };
458
+ };
459
+ const purge = async (purgeOptions) => {
460
+ const keepIndex = purgeOptions.keepIndex !== false;
461
+ const doomed = await database.all(`SELECT run_id FROM looms_run_index
462
+ WHERE purged_at IS NULL
463
+ AND status IN ('completed', 'failed', 'cancelled')
464
+ AND completed_at IS NOT NULL
465
+ AND completed_at < ?`, [purgeOptions.finishedBefore]);
466
+ if (doomed.length === 0) {
467
+ return { runs: 0 };
468
+ }
469
+ const purgedAt = Date.now();
470
+ const statements = [];
471
+ for (const row of doomed) {
472
+ statements.push(sqlStatement(`UPDATE looms_run_index SET purged_at = ? WHERE run_id = ? AND purged_at IS NULL`, [purgedAt, row.run_id]), sqlStatement(`DELETE FROM looms_run_events WHERE run_id = ?`, [row.run_id]));
473
+ if (!keepIndex) {
474
+ statements.push(sqlStatement(`DELETE FROM looms_run_actors WHERE run_id = ?`, [row.run_id]), sqlStatement(`DELETE FROM looms_run_reviews WHERE run_id = ?`, [row.run_id]), sqlStatement(`DELETE FROM looms_run_index WHERE run_id = ?`, [row.run_id]));
475
+ }
476
+ }
477
+ await database.batch(statements);
478
+ return { runs: doomed.length };
479
+ };
480
+ const rebuild = async (source) => {
481
+ await init();
482
+ const runIds = await Effect.runPromise(source.listRuns);
483
+ let copied = 0;
484
+ for (const runId of runIds) {
485
+ let fromSeq = 1;
486
+ while (true) {
487
+ const events = await Effect.runPromise(source.read(runId, { fromSeq, limit: READ_PAGE }));
488
+ if (events.length === 0) {
489
+ break;
490
+ }
491
+ await project(events);
492
+ copied += events.length;
493
+ const last = events.at(-1);
494
+ if (!last || events.length < READ_PAGE) {
495
+ break;
496
+ }
497
+ fromSeq = last.seq + 1;
498
+ }
499
+ }
500
+ return copied;
501
+ };
502
+ return {
503
+ name: REPLICA_NAME,
504
+ version: REPLICA_VERSION,
505
+ init,
506
+ position,
507
+ project,
508
+ migrate,
509
+ pendingMigrations,
510
+ eventStore: () => store,
511
+ loadRun,
512
+ status,
513
+ purge,
514
+ rebuild,
515
+ };
516
+ }
517
+ export { ReplicaGapError };
@@ -1,3 +1,3 @@
1
- import type { RouteOptions } from '../http';
1
+ import { type RouteOptions } from '../http';
2
2
  import { type Route } from '../route-table';
3
3
  export declare function definitionRoutes({ runtime }: RouteOptions): readonly Route[];
@@ -1,6 +1,14 @@
1
- import { Effect } from 'effect';
2
- import { publishDefinition, publishEffects } from '@swirls/looms/core';
1
+ import { Effect, Schema } from 'effect';
2
+ import { findSignal, JsonValueSchema, publishDefinition, publishEffects, publishEvents, publishModules, publishSignals, runSignal, validateEventInput, } from '@swirls/looms/core';
3
+ import { EventInputBodySchema, readJson } from '../http.js';
3
4
  import { route } from '../route-table.js';
5
+ const PreviewSignalBodySchema = Schema.Struct({
6
+ input: Schema.optional(JsonValueSchema),
7
+ threadId: Schema.optional(Schema.String),
8
+ });
9
+ const PreviewEventsBodySchema = Schema.Struct({
10
+ events: Schema.Array(EventInputBodySchema),
11
+ });
4
12
  export function definitionRoutes({ runtime }) {
5
13
  return [
6
14
  route({
@@ -12,6 +20,7 @@ export function definitionRoutes({ runtime }) {
12
20
  const catalog = {
13
21
  definitions: runtime.registry.definitions.map(publishDefinition),
14
22
  projections: [...runtime.registry.projections.keys()],
23
+ modules: publishModules(runtime.registry.modules),
15
24
  };
16
25
  return Effect.succeed(Response.json(catalog));
17
26
  },
@@ -23,5 +32,52 @@ export function definitionRoutes({ runtime }) {
23
32
  access: 'read',
24
33
  handle: () => Effect.succeed(Response.json({ effects: publishEffects(runtime.registry.effects.values()) })),
25
34
  }),
35
+ route({
36
+ method: 'GET',
37
+ path: '/definitions/signals',
38
+ name: 'definitions.signals',
39
+ access: 'read',
40
+ handle: () => Effect.succeed(Response.json({ signals: publishSignals(runtime.registry.modules) })),
41
+ }),
42
+ route({
43
+ method: 'GET',
44
+ path: '/definitions/events',
45
+ name: 'definitions.events',
46
+ access: 'read',
47
+ handle: () => Effect.succeed(Response.json({ events: publishEvents(runtime.registry.modules) })),
48
+ }),
49
+ route({
50
+ method: 'POST',
51
+ path: '/definitions/signals/:namespace/:name/preview',
52
+ name: 'definitions.signals.preview',
53
+ access: 'read',
54
+ handle: ({ req, params }) =>
55
+ // SAFETY: Effect.gen residual R is never here; Schema.decode errors become RequestBodyError via toErrorResponse.
56
+ Effect.gen(function* () {
57
+ const definition = findSignal(runtime.registry.modules, params.namespace, params.name);
58
+ if (!definition) {
59
+ return Response.json({ error: `Unknown signal ${params.namespace}.${params.name}` }, { status: 404 });
60
+ }
61
+ const body = yield* readJson(req).pipe(Effect.flatMap(Schema.decodeUnknownEffect(PreviewSignalBodySchema)));
62
+ const events = yield* runSignal(definition, body.input ?? null, body.threadId);
63
+ return Response.json({ events });
64
+ }),
65
+ }),
66
+ route({
67
+ method: 'POST',
68
+ path: '/definitions/events/preview',
69
+ name: 'definitions.events.preview',
70
+ access: 'read',
71
+ handle: ({ req }) =>
72
+ // SAFETY: Effect.gen residual R is never here; validateEventInput failures are already in the Error channel.
73
+ Effect.gen(function* () {
74
+ const body = yield* readJson(req).pipe(Effect.flatMap(Schema.decodeUnknownEffect(PreviewEventsBodySchema)));
75
+ const events = [];
76
+ for (const input of body.events) {
77
+ events.push(yield* validateEventInput(runtime.registry.catalogs, input));
78
+ }
79
+ return Response.json({ events });
80
+ }),
81
+ }),
26
82
  ];
27
83
  }
@@ -1,5 +1,5 @@
1
1
  import { Effect, Schema } from 'effect';
2
- import { createRunId, EventStoreTag, JsonValueSchema, RunAttributesSchema, readTraceHeaders, SecretContextSchema, stringifyJson, subscriptionFilter, subscriptionFromSeq, } from '@swirls/looms/core';
2
+ import { createRunId, EventStoreTag, findSignal, JsonValueSchema, RunAttributesSchema, readTraceHeaders, runSignal, SecretContextSchema, stringifyJson, subscriptionFilter, subscriptionFromSeq, } from '@swirls/looms/core';
3
3
  import { createEventStreamResponse } from '../../sse.js';
4
4
  import { acceptsEventStream, EventInputBodySchema, extractIdempotencyKey, provideStore, readIntegerQuery, readJson, readOptionalJson, RequestQueryError, } from '../http.js';
5
5
  import { route } from '../route-table.js';
@@ -21,6 +21,11 @@ const SignalBodySchema = Schema.Struct({
21
21
  threadId: Schema.optional(Schema.NullOr(Schema.String)),
22
22
  idempotencyKey: Schema.optional(Schema.String),
23
23
  });
24
+ const NamedSignalBodySchema = Schema.Struct({
25
+ input: Schema.optional(JsonValueSchema),
26
+ threadId: Schema.optional(Schema.String),
27
+ idempotencyKey: Schema.optional(Schema.String),
28
+ });
24
29
  const CancelBodySchema = Schema.Struct({
25
30
  threadId: Schema.optional(Schema.String),
26
31
  });
@@ -194,6 +199,25 @@ export function runRoutes({ runtime, store }) {
194
199
  return Response.json({ runId: params.runId, state });
195
200
  }),
196
201
  }),
202
+ route({
203
+ method: 'POST',
204
+ path: '/runs/:runId/signals/:namespace/:name',
205
+ name: 'runs.signal.named',
206
+ access: 'write',
207
+ handle: ({ req, params }) =>
208
+ // SAFETY: Effect.gen residual R is never here; decode/run errors map to Error via route handlers.
209
+ Effect.gen(function* () {
210
+ const definition = findSignal(runtime.registry.modules, params.namespace, params.name);
211
+ if (!definition) {
212
+ return Response.json({ error: `Unknown signal ${params.namespace}.${params.name}` }, { status: 404 });
213
+ }
214
+ const body = yield* readJson(req).pipe(Effect.flatMap(Schema.decodeUnknownEffect(NamedSignalBodySchema)));
215
+ const events = yield* runSignal(definition, body.input ?? null, body.threadId);
216
+ const idempotencyKey = extractIdempotencyKey(req, body.idempotencyKey);
217
+ const state = yield* provideStore(runtime.signal(params.runId, events, { idempotencyKey }), store);
218
+ return Response.json({ runId: params.runId, state });
219
+ }),
220
+ }),
197
221
  route({
198
222
  method: 'POST',
199
223
  path: '/runs/:runId/wake',