@swirls/looms 0.9.0 → 0.11.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 (118) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/actor/cell.d.ts +3 -1
  3. package/dist/actor/cell.js +1 -0
  4. package/dist/actor/host.d.ts +3 -1
  5. package/dist/actor/host.js +1 -0
  6. package/dist/actor/routing.js +2 -1
  7. package/dist/agent/debugger/agent-chat.js +6 -5
  8. package/dist/agent/debugger/index.js +2 -1
  9. package/dist/agent/module.d.ts +207 -1
  10. package/dist/agent/module.js +31 -0
  11. package/dist/agent/scope.js +1 -0
  12. package/dist/agent/signals.d.ts +108 -15
  13. package/dist/agent/signals.js +70 -47
  14. package/dist/approval/debugger/approvals-view.js +1 -1
  15. package/dist/approval/index.d.ts +1 -0
  16. package/dist/approval/index.js +1 -0
  17. package/dist/approval/module.d.ts +42 -1
  18. package/dist/approval/module.js +53 -0
  19. package/dist/approval/scope.js +1 -0
  20. package/dist/approval/signals.d.ts +19 -13
  21. package/dist/approval/signals.js +25 -45
  22. package/dist/approval/steps.d.ts +11 -0
  23. package/dist/approval/steps.js +39 -0
  24. package/dist/cli/commands.d.ts +1 -1
  25. package/dist/cli/commands.js +49 -14
  26. package/dist/client/client.d.ts +231 -21
  27. package/dist/client/client.js +20 -2
  28. package/dist/cloudflare/delete-terminal-run-storage.d.ts +39 -0
  29. package/dist/cloudflare/delete-terminal-run-storage.js +98 -0
  30. package/dist/cloudflare/durable-object.d.ts +11 -1
  31. package/dist/cloudflare/durable-object.js +23 -0
  32. package/dist/cloudflare/index.d.ts +1 -0
  33. package/dist/cloudflare/index.js +1 -0
  34. package/dist/core/index.d.ts +1 -0
  35. package/dist/core/index.js +1 -0
  36. package/dist/core/module-scope.d.ts +50 -5
  37. package/dist/core/module-scope.js +22 -2
  38. package/dist/core/module.d.ts +29 -2
  39. package/dist/core/projection.d.ts +1 -0
  40. package/dist/core/published.d.ts +59 -1
  41. package/dist/core/published.js +97 -1
  42. package/dist/core/run-context.d.ts +50 -0
  43. package/dist/core/run-context.js +21 -1
  44. package/dist/core/signals.d.ts +56 -0
  45. package/dist/core/signals.js +93 -0
  46. package/dist/core/validate-event.d.ts +12 -1
  47. package/dist/core/validate-event.js +34 -11
  48. package/dist/debugger/app/assets/index-CO5gIvV8.css +2 -0
  49. package/dist/debugger/app/assets/{index-CMRl_aWQ.js → index-VTotlHcm.js} +2 -2
  50. package/dist/debugger/app/assets/routes-CEdsN9DO.js +47 -0
  51. package/dist/debugger/app/index.html +2 -2
  52. package/dist/debugger/index.d.ts +1 -1
  53. package/dist/debugger/index.js +1 -1
  54. package/dist/debugger/lib/cn.d.ts +1 -1
  55. package/dist/debugger/lib/cn.js +12 -1
  56. package/dist/debugger/plugin.d.ts +11 -1
  57. package/dist/debugger/plugin.js +41 -0
  58. package/dist/debugger/shell/debugger-shell.js +1 -1
  59. package/dist/debugger/shell/form-fields.d.ts +17 -0
  60. package/dist/debugger/shell/form-fields.js +38 -0
  61. package/dist/debugger/shell/run-action.d.ts +6 -0
  62. package/dist/debugger/shell/run-action.js +15 -0
  63. package/dist/debugger/shell/run-controls.js +3 -55
  64. package/dist/debugger/shell/schema-form.d.ts +10 -1
  65. package/dist/debugger/shell/schema-form.js +108 -10
  66. package/dist/debugger/shell/signal-form.d.ts +18 -0
  67. package/dist/debugger/shell/signal-form.js +185 -0
  68. package/dist/debugger/shell/start-form.js +2 -32
  69. package/dist/debugger/shell/use-debounced-preview.d.ts +22 -0
  70. package/dist/debugger/shell/use-debounced-preview.js +68 -0
  71. package/dist/evaluator/index.d.ts +1 -1
  72. package/dist/evaluator/index.js +1 -1
  73. package/dist/evaluator/module.d.ts +8 -1
  74. package/dist/evaluator/module.js +33 -0
  75. package/dist/evaluator/scope.js +1 -0
  76. package/dist/projectors/event-log-ops.d.ts +0 -6
  77. package/dist/projectors/event-log-ops.js +2 -12
  78. package/dist/projectors/event-log.d.ts +10 -5
  79. package/dist/projectors/event-log.js +26 -22
  80. package/dist/projectors/replica/columns.d.ts +41 -0
  81. package/dist/projectors/replica/columns.js +77 -0
  82. package/dist/projectors/replica/drizzle.d.ts +328 -57
  83. package/dist/projectors/replica/drizzle.js +18 -14
  84. package/dist/projectors/replica/migrations.d.ts +25 -5
  85. package/dist/projectors/replica/migrations.js +62 -14
  86. package/dist/projectors/replica/postgres.d.ts +12 -11
  87. package/dist/projectors/replica/postgres.js +12 -26
  88. package/dist/projectors/replica/sqlite-bun.d.ts +3 -1
  89. package/dist/projectors/replica/sqlite-bun.js +6 -2
  90. package/dist/projectors/replica/sqlite-migrations.d.ts +5 -5
  91. package/dist/projectors/replica/sqlite-migrations.js +22 -9
  92. package/dist/projectors/replica/sqlite.d.ts +12 -11
  93. package/dist/projectors/replica/sqlite.js +23 -16
  94. package/dist/runtime/looms.d.ts +27 -36
  95. package/dist/runtime/looms.js +1 -0
  96. package/dist/runtime/runtime.js +7 -1
  97. package/dist/runtime/server/http.js +4 -2
  98. package/dist/runtime/server/routes/definitions.d.ts +1 -1
  99. package/dist/runtime/server/routes/definitions.js +58 -2
  100. package/dist/runtime/server/routes/runs.js +25 -1
  101. package/dist/runtime/types.d.ts +6 -1
  102. package/dist/schedule/module.d.ts +117 -1
  103. package/dist/schedule/module.js +30 -0
  104. package/dist/schedule/scope.js +1 -0
  105. package/dist/schedule/signals.d.ts +59 -7
  106. package/dist/schedule/signals.js +35 -17
  107. package/dist/testing/corpus-module.d.ts +1 -1
  108. package/dist/testing/index.js +2 -1
  109. package/dist/testing/module-examples.d.ts +6 -0
  110. package/dist/testing/module-examples.js +66 -0
  111. package/dist/workflow/module.d.ts +3 -1
  112. package/dist/workflow/module.js +13 -0
  113. package/dist/workflow/scope.js +1 -0
  114. package/package.json +1 -1
  115. package/dist/debugger/app/assets/index-B7GdT1UA.css +0 -2
  116. package/dist/debugger/app/assets/routes-CfXxKG45.js +0 -47
  117. /package/dist/evaluator/{signals.d.ts → steps.d.ts} +0 -0
  118. /package/dist/evaluator/{signals.js → steps.js} +0 -0
@@ -1,3 +1,7 @@
1
+ import type { Sql, TransactionSql } from 'postgres';
2
+ import type { RunAttributeFields } from '@swirls/looms/core';
3
+ import { type ReplicaMigration, type ResolvedReplicaColumn } from './columns';
4
+ export type { ReplicaMigration };
1
5
  /**
2
6
  * Actors and reviews. Same statements the Postgres index projector has always
3
7
  * applied, so a database created by an older Looms keeps working.
@@ -9,12 +13,26 @@ export declare const POSTGRES_SCHEMA_SQL: string;
9
13
  * `ADD COLUMN IF NOT EXISTS`.
10
14
  */
11
15
  export declare const POSTGRES_EVENT_LOG_SCHEMA_SQL: string;
12
- export interface ReplicaMigration {
13
- readonly id: string;
14
- readonly sql: string;
15
- }
16
- /** Versioned DDL for the Postgres replica. Looms only creates and alters `looms_*` objects. */
16
+ /** Tracks applied Looms migrations, including attribute column migrations. */
17
+ export declare const POSTGRES_SCHEMA_MIGRATIONS_SQL: string;
18
+ /**
19
+ * Adds one attribute column and copies it from `attributes` for runs already in the table.
20
+ * Safe to repeat: the backfill only touches rows that have the attribute and an empty column.
21
+ */
22
+ export declare function postgresColumnSql(column: ResolvedReplicaColumn): string;
23
+ export declare function postgresColumnIndexSql(column: ResolvedReplicaColumn): string;
24
+ /**
25
+ * Attribute column and index migrations for Postgres.
26
+ * Each runs once when recorded in `looms_schema_migrations`, including the backfill UPDATE.
27
+ */
28
+ export declare function postgresAttributeMigrations(additionalFields?: RunAttributeFields): readonly ReplicaMigration[];
29
+ /** Ids recorded in `looms_schema_migrations`, or none when the table does not exist yet. */
30
+ export declare function appliedPostgresMigrationIds(sql: Sql | TransactionSql): Promise<ReadonlySet<string>>;
31
+ /** Applies each migration that is not recorded yet, in order, under one advisory lock. */
32
+ export declare function applyPostgresMigrations(sql: Sql, migrations: readonly ReplicaMigration[]): Promise<void>;
33
+ /** Versioned DDL for the Postgres replica with no attribute columns. Looms only creates and alters `looms_*` objects. */
17
34
  export declare const POSTGRES_REPLICA_MIGRATIONS: readonly ReplicaMigration[];
35
+ export declare function postgresReplicaMigrations(additionalFields?: RunAttributeFields): readonly ReplicaMigration[];
18
36
  export type ReplicaDialect = 'postgres' | 'sqlite';
19
37
  export interface GenerateReplicaMigrationsOptions {
20
38
  /** Directory of SQL migrations the host already applies. */
@@ -25,6 +43,8 @@ export interface GenerateReplicaMigrationsOptions {
25
43
  readonly check?: boolean;
26
44
  /** Which replica DDL to write. Defaults to Postgres. */
27
45
  readonly dialect?: ReplicaDialect;
46
+ /** Declared run attributes. Pass the same declaration the replica uses. */
47
+ readonly additionalFields?: RunAttributeFields;
28
48
  }
29
49
  export interface GenerateReplicaMigrationsResult {
30
50
  readonly written: readonly string[];
@@ -1,7 +1,8 @@
1
1
  import { readdir, readFile, writeFile, mkdir } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
3
  import { Predicate } from 'effect';
4
- import { SQLITE_REPLICA_MIGRATIONS } from './sqlite-migrations.js';
4
+ import { columnMigrations, sqlStringLiteral, } from './columns.js';
5
+ import { sqliteReplicaMigrations } from './sqlite-migrations.js';
5
6
  /**
6
7
  * Actors and reviews. Same statements the Postgres index projector has always
7
8
  * applied, so a database created by an older Looms keeps working.
@@ -76,9 +77,6 @@ CREATE TABLE IF NOT EXISTS looms_run_index (
76
77
  launched_by_effect_id TEXT,
77
78
  correlation_id TEXT,
78
79
  attributes JSONB NOT NULL DEFAULT '{}'::jsonb,
79
- tenant TEXT,
80
- project TEXT,
81
- org TEXT,
82
80
  started_at TIMESTAMPTZ,
83
81
  updated_at TIMESTAMPTZ NOT NULL,
84
82
  completed_at TIMESTAMPTZ,
@@ -89,13 +87,11 @@ CREATE TABLE IF NOT EXISTS looms_run_index (
89
87
  ALTER TABLE looms_run_index ADD COLUMN IF NOT EXISTS replicated_seq BIGINT NOT NULL DEFAULT 0;
90
88
  ALTER TABLE looms_run_index ADD COLUMN IF NOT EXISTS purged_at TIMESTAMPTZ;
91
89
 
92
- CREATE INDEX IF NOT EXISTS looms_run_index_tenant ON looms_run_index (tenant);
93
- CREATE INDEX IF NOT EXISTS looms_run_index_project ON looms_run_index (project);
94
- CREATE INDEX IF NOT EXISTS looms_run_index_org ON looms_run_index (org);
95
90
  CREATE INDEX IF NOT EXISTS looms_run_index_parent ON looms_run_index (parent_run_id);
96
91
  CREATE INDEX IF NOT EXISTS looms_run_index_status ON looms_run_index (status);
97
92
  `.trim();
98
- const POSTGRES_REPLICA_BOOKKEEPING_SQL = `
93
+ /** Tracks applied Looms migrations, including attribute column migrations. */
94
+ export const POSTGRES_SCHEMA_MIGRATIONS_SQL = `
99
95
  CREATE TABLE IF NOT EXISTS looms_schema_migrations (
100
96
  id TEXT PRIMARY KEY,
101
97
  applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
@@ -110,14 +106,66 @@ function replicaMigration(id, statements) {
110
106
  ].join('\n\n'),
111
107
  };
112
108
  }
113
- /** Versioned DDL for the Postgres replica. Looms only creates and alters `looms_*` objects. */
109
+ /**
110
+ * Adds one attribute column and copies it from `attributes` for runs already in the table.
111
+ * Safe to repeat: the backfill only touches rows that have the attribute and an empty column.
112
+ */
113
+ export function postgresColumnSql(column) {
114
+ const name = `"${column.name}"`;
115
+ const attribute = sqlStringLiteral(column.key);
116
+ return `
117
+ ALTER TABLE looms_run_index ADD COLUMN IF NOT EXISTS ${name} TEXT;
118
+
119
+ UPDATE looms_run_index SET ${name} = attributes ->> ${attribute}
120
+ WHERE ${name} IS NULL AND attributes ? ${attribute};
121
+ `.trim();
122
+ }
123
+ export function postgresColumnIndexSql(column) {
124
+ return `CREATE INDEX IF NOT EXISTS looms_run_index_${column.name} ON looms_run_index ("${column.name}");`;
125
+ }
126
+ /**
127
+ * Attribute column and index migrations for Postgres.
128
+ * Each runs once when recorded in `looms_schema_migrations`, including the backfill UPDATE.
129
+ */
130
+ export function postgresAttributeMigrations(additionalFields) {
131
+ return columnMigrations(additionalFields, (id, sql) => replicaMigration(id, [sql]), postgresColumnSql, postgresColumnIndexSql);
132
+ }
133
+ /** Serializes Looms migrations across processes that share one database. */
134
+ const MIGRATION_LOCK_KEY = 814_764;
135
+ /** Ids recorded in `looms_schema_migrations`, or none when the table does not exist yet. */
136
+ export async function appliedPostgresMigrationIds(sql) {
137
+ const [table] = await sql `
138
+ SELECT to_regclass('public.looms_schema_migrations') AS name
139
+ `;
140
+ if (!table?.name) {
141
+ return new Set();
142
+ }
143
+ const rows = await sql `SELECT id FROM looms_schema_migrations`;
144
+ return new Set(rows.map((row) => row.id));
145
+ }
146
+ /** Applies each migration that is not recorded yet, in order, under one advisory lock. */
147
+ export async function applyPostgresMigrations(sql, migrations) {
148
+ await sql.begin(async (tx) => {
149
+ await tx `SELECT pg_advisory_xact_lock(${MIGRATION_LOCK_KEY})`;
150
+ const applied = await appliedPostgresMigrationIds(tx);
151
+ for (const migration of migrations) {
152
+ if (!applied.has(migration.id)) {
153
+ await tx.unsafe(migration.sql);
154
+ }
155
+ }
156
+ });
157
+ }
158
+ /** Versioned DDL for the Postgres replica with no attribute columns. Looms only creates and alters `looms_*` objects. */
114
159
  export const POSTGRES_REPLICA_MIGRATIONS = [
115
160
  replicaMigration('0001_replica', [
116
161
  POSTGRES_SCHEMA_SQL,
117
162
  POSTGRES_EVENT_LOG_SCHEMA_SQL,
118
- POSTGRES_REPLICA_BOOKKEEPING_SQL,
163
+ POSTGRES_SCHEMA_MIGRATIONS_SQL,
119
164
  ]),
120
165
  ];
166
+ export function postgresReplicaMigrations(additionalFields) {
167
+ return [...POSTGRES_REPLICA_MIGRATIONS, ...postgresAttributeMigrations(additionalFields)];
168
+ }
121
169
  const MIGRATION_HEADER = /^-- looms-migration:\s+(\S+)/m;
122
170
  async function recordedMigrationIds(directory) {
123
171
  let names;
@@ -201,12 +249,12 @@ async function appendDrizzleJournal(directory, tags) {
201
249
  * A file counts as applied when it contains `-- looms-migration: <id>`.
202
250
  * The numeric prefix continues after the highest `NNNN_` file already in `out`.
203
251
  */
204
- function migrationsFor(dialect) {
252
+ function migrationsFor(dialect, additionalFields) {
205
253
  switch (dialect) {
206
254
  case 'postgres':
207
- return POSTGRES_REPLICA_MIGRATIONS;
255
+ return postgresReplicaMigrations(additionalFields);
208
256
  case 'sqlite':
209
- return SQLITE_REPLICA_MIGRATIONS;
257
+ return sqliteReplicaMigrations(additionalFields);
210
258
  default: {
211
259
  const unexpected = dialect;
212
260
  return unexpected;
@@ -219,7 +267,7 @@ export async function generateReplicaMigrations(options) {
219
267
  throw new Error('Drizzle journal output is only supported for the Postgres replica.');
220
268
  }
221
269
  const recorded = await recordedMigrationIds(options.out);
222
- const pending = migrationsFor(dialect).filter((migration) => !recorded.has(migration.id));
270
+ const pending = migrationsFor(dialect, options.additionalFields).filter((migration) => !recorded.has(migration.id));
223
271
  if (options.check || pending.length === 0) {
224
272
  return { written: [], pending: pending.map((migration) => migration.id) };
225
273
  }
@@ -1,6 +1,8 @@
1
1
  import { type Sql } from 'postgres';
2
- import { type EventStore, type FoldRegistry, type RunState } from '@swirls/looms/core';
2
+ import { type EventStore, type FoldRegistry, type RunAttributeFields, type RunState } from '@swirls/looms/core';
3
3
  import { ReplicaGapError, type Projector } from '../projector';
4
+ import { type NoAdditionalFields, type ReplicaPurgeOptions } from './columns';
5
+ export type { NoAdditionalFields, ReplicaPurgeOptions } from './columns';
4
6
  export interface ReplicaStatus {
5
7
  /** Highest sequence copied with no hole in front of it. */
6
8
  readonly replicatedSeq: number;
@@ -11,17 +13,11 @@ export interface ReplicaStatus {
11
13
  /** Set once retention has deleted the event copy. */
12
14
  readonly purgedAt: number | null;
13
15
  }
14
- export interface ReplicaPurgeOptions {
15
- /** Delete event copies for runs that finished before this epoch millisecond. */
16
- readonly finishedBefore: number;
17
- /** Keep the run summary row. Defaults to true. */
18
- readonly keepIndex?: boolean;
19
- }
20
16
  export interface ReplicaPurgeResult {
21
17
  readonly runs: number;
22
18
  }
23
19
  export type PostgresReplicaMigrate = 'auto' | 'verify';
24
- export type PostgresReplicaOptions = ({
20
+ export type PostgresReplicaOptions<Fields extends RunAttributeFields = NoAdditionalFields> = ({
25
21
  readonly url: string;
26
22
  } | {
27
23
  readonly sql: Sql;
@@ -32,12 +28,17 @@ export type PostgresReplicaOptions = ({
32
28
  * `looms replica generate` so the host can commit the SQL.
33
29
  */
34
30
  readonly migrate: PostgresReplicaMigrate;
31
+ /**
32
+ * Declared run attributes, from `defineRunAttributes`. Each one is a `looms_run_index`
33
+ * column, and each column and index is its own migration. `purge({ where })` filters on them.
34
+ */
35
+ readonly additionalFields?: Fields;
35
36
  };
36
37
  /**
37
38
  * A complete, gap-checked copy of every run, plus the run summary folded in the same transaction.
38
39
  * Reading an event back returns the envelope the source returned.
39
40
  */
40
- export interface PostgresReplica extends Projector {
41
+ export interface PostgresReplica<Fields extends RunAttributeFields = NoAdditionalFields> extends Projector {
41
42
  readonly position: (runId: string) => Promise<number | null>;
42
43
  /** Apply pending migrations. `init` does this only when `migrate` is `auto`. */
43
44
  readonly migrate: () => Promise<void>;
@@ -49,9 +50,9 @@ export interface PostgresReplica extends Projector {
49
50
  /** How far the copy has got, and whether it is safe to treat as complete. */
50
51
  readonly status: (runId: string) => Promise<ReplicaStatus | null>;
51
52
  /** Delete event copies for finished runs. Later deliveries for those runs are skipped. */
52
- readonly purge: (options: ReplicaPurgeOptions) => Promise<ReplicaPurgeResult>;
53
+ readonly purge: (options: ReplicaPurgeOptions<Fields>) => Promise<ReplicaPurgeResult>;
53
54
  /** Copy every run in `source`. Purged runs are left alone. */
54
55
  readonly rebuild: (source: EventStore) => Promise<number>;
55
56
  }
56
- export declare function postgresReplica(options: PostgresReplicaOptions): PostgresReplica;
57
+ export declare function postgresReplica<const Fields extends RunAttributeFields = NoAdditionalFields>(options: PostgresReplicaOptions<Fields>): PostgresReplica<Fields>;
57
58
  export { ReplicaGapError };
@@ -5,10 +5,10 @@ import { applyRunIndexOps, eventLogOps, insertRunEvents } from '../event-log.js'
5
5
  import { indexOpsFor } from '../index-model.js';
6
6
  import { applyIndexOps } from '../postgres.js';
7
7
  import { ReplicaGapError } from '../projector.js';
8
- import { POSTGRES_REPLICA_MIGRATIONS } from './migrations.js';
8
+ import { purgeFilters, resolveReplicaColumns, } from './columns.js';
9
+ import { appliedPostgresMigrationIds, applyPostgresMigrations, postgresReplicaMigrations, } from './migrations.js';
9
10
  const REPLICA_NAME = 'postgres-replica';
10
11
  const REPLICA_VERSION = '1';
11
- const ADVISORY_LOCK_KEY = 814_764;
12
12
  const READ_PAGE = 500;
13
13
  const terminalStatuses = new Set(['completed', 'failed', 'cancelled']);
14
14
  function replicaClient(options) {
@@ -92,16 +92,6 @@ function contiguousSeq(runId, replicatedSeq, events) {
92
92
  }
93
93
  return cursor;
94
94
  }
95
- async function appliedMigrationIds(sql) {
96
- const [table] = await sql `
97
- SELECT to_regclass('public.looms_schema_migrations') AS name
98
- `;
99
- if (!table?.name) {
100
- return new Set();
101
- }
102
- const rows = await sql `SELECT id FROM looms_schema_migrations`;
103
- return new Set(rows.map((row) => row.id));
104
- }
105
95
  async function readPage(sql, runId, fromSeq, limit) {
106
96
  const rows = await sql `
107
97
  SELECT run_id, seq, event_id, ts, type, payload, thread_id, parent_thread_id,
@@ -114,23 +104,17 @@ async function readPage(sql, runId, fromSeq, limit) {
114
104
  return rows.map(envelope);
115
105
  }
116
106
  export function postgresReplica(options) {
107
+ const columns = resolveReplicaColumns(options.additionalFields);
108
+ const migrations = postgresReplicaMigrations(options.additionalFields);
117
109
  const { sql, owned } = replicaClient(options);
118
110
  let ready;
119
111
  const pendingMigrations = async () => {
120
- const applied = await appliedMigrationIds(sql);
121
- return POSTGRES_REPLICA_MIGRATIONS.filter((migration) => !applied.has(migration.id)).map((migration) => migration.id);
122
- };
123
- const migrate = async () => {
124
- await sql.begin(async (tx) => {
125
- await tx `SELECT pg_advisory_xact_lock(${ADVISORY_LOCK_KEY})`;
126
- const applied = await appliedMigrationIds(tx);
127
- for (const migration of POSTGRES_REPLICA_MIGRATIONS) {
128
- if (!applied.has(migration.id)) {
129
- await tx.unsafe(migration.sql);
130
- }
131
- }
132
- });
112
+ const applied = await appliedPostgresMigrationIds(sql);
113
+ return migrations
114
+ .filter((migration) => !applied.has(migration.id))
115
+ .map((migration) => migration.id);
133
116
  };
117
+ const migrate = () => applyPostgresMigrations(sql, migrations);
134
118
  const init = () => {
135
119
  ready ??= (options.migrate === 'verify' ? verify() : migrate()).catch((cause) => {
136
120
  ready = undefined;
@@ -165,7 +149,7 @@ export function postgresReplica(options) {
165
149
  const durable = batch.filter((event) => !event.ephemeral);
166
150
  const last = batch.at(-1);
167
151
  await insertRunEvents(tx, batch);
168
- await applyRunIndexOps(tx, durable.flatMap((event) => eventLogOps(event)));
152
+ await applyRunIndexOps(tx, durable.flatMap((event) => eventLogOps(event)), columns);
169
153
  await applyIndexOps(tx, durable.flatMap(indexOpsFor));
170
154
  if (next === replicatedSeq || !last) {
171
155
  continue;
@@ -292,6 +276,7 @@ export function postgresReplica(options) {
292
276
  const purge = async (purgeOptions) => {
293
277
  const cutoff = utcDate(purgeOptions.finishedBefore);
294
278
  const keepIndex = purgeOptions.keepIndex !== false;
279
+ const filters = purgeFilters(columns, purgeOptions.where);
295
280
  return sql.begin(async (tx) => {
296
281
  const doomed = await tx `
297
282
  UPDATE looms_run_index
@@ -300,6 +285,7 @@ export function postgresReplica(options) {
300
285
  AND status IN ('completed', 'failed', 'cancelled')
301
286
  AND completed_at IS NOT NULL
302
287
  AND completed_at < ${cutoff}
288
+ ${filters.reduce((clause, filter) => tx `${clause} AND ${tx(filter.column)} = ${filter.value}`, tx ``)}
303
289
  RETURNING run_id
304
290
  `;
305
291
  const ids = doomed.map((row) => row.run_id);
@@ -1,5 +1,7 @@
1
1
  import { Database } from 'bun:sqlite';
2
+ import type { RunAttributeFields } from '@swirls/looms/core';
3
+ import type { NoAdditionalFields } from './columns';
2
4
  import { type SqliteReplica, type SqliteReplicaDatabase, type SqliteReplicaMigrate } from './sqlite';
3
5
  /** Opens a SQLite file. The replica closes it on `dispose`. */
4
- export declare function openSqliteReplicaFile(filename: string, migrate: SqliteReplicaMigrate): SqliteReplica;
6
+ export declare function openSqliteReplicaFile<const Fields extends RunAttributeFields = NoAdditionalFields>(filename: string, migrate: SqliteReplicaMigrate, additionalFields?: Fields): SqliteReplica<Fields>;
5
7
  export declare function bunSqliteReplicaDatabase(db: Database): SqliteReplicaDatabase;
@@ -1,9 +1,13 @@
1
1
  import { Database } from 'bun:sqlite';
2
2
  import { sqliteReplica, } from './sqlite.js';
3
3
  /** Opens a SQLite file. The replica closes it on `dispose`. */
4
- export function openSqliteReplicaFile(filename, migrate) {
4
+ export function openSqliteReplicaFile(filename, migrate, additionalFields) {
5
5
  const db = new Database(filename);
6
- const replica = sqliteReplica({ database: bunSqliteReplicaDatabase(db), migrate });
6
+ const replica = sqliteReplica({
7
+ database: bunSqliteReplicaDatabase(db),
8
+ migrate,
9
+ additionalFields,
10
+ });
7
11
  return {
8
12
  ...replica,
9
13
  dispose: () => {
@@ -1,5 +1,5 @@
1
- /** Versioned DDL for the SQLite replica, including D1. Looms only creates `looms_*` objects. */
2
- export declare const SQLITE_REPLICA_MIGRATIONS: {
3
- id: string;
4
- sql: string;
5
- }[];
1
+ import type { RunAttributeFields } from '@swirls/looms/core';
2
+ import { type ReplicaMigration } from './columns';
3
+ /** Versioned DDL for the SQLite replica with no attribute columns, including D1. Looms only creates `looms_*` objects. */
4
+ export declare const SQLITE_REPLICA_MIGRATIONS: readonly ReplicaMigration[];
5
+ export declare function sqliteReplicaMigrations(additionalFields?: RunAttributeFields): readonly ReplicaMigration[];
@@ -1,9 +1,9 @@
1
+ import { columnMigrations, sqlStringLiteral, } from './columns.js';
1
2
  /**
2
3
  * Same tables as the Postgres replica, in SQLite types.
3
4
  * Timestamps are epoch milliseconds. JSON is text. Booleans are 0 or 1.
4
5
  * A fresh database gets every column from `CREATE TABLE`. SQLite has no
5
- * `ADD COLUMN IF NOT EXISTS` we want to depend on, so later migrations should
6
- * add columns the way the index projector does: read `PRAGMA table_info` first.
6
+ * `ADD COLUMN IF NOT EXISTS`, so an attribute column is added once, by its own migration.
7
7
  */
8
8
  const SQLITE_REPLICA_SCHEMA_SQL = `
9
9
  CREATE TABLE IF NOT EXISTS looms_run_actors (
@@ -63,9 +63,6 @@ CREATE TABLE IF NOT EXISTS looms_run_index (
63
63
  launched_by_effect_id TEXT,
64
64
  correlation_id TEXT,
65
65
  attributes TEXT NOT NULL DEFAULT '{}',
66
- tenant TEXT,
67
- project TEXT,
68
- org TEXT,
69
66
  started_at INTEGER,
70
67
  updated_at INTEGER NOT NULL,
71
68
  completed_at INTEGER,
@@ -73,9 +70,6 @@ CREATE TABLE IF NOT EXISTS looms_run_index (
73
70
  purged_at INTEGER
74
71
  );
75
72
 
76
- CREATE INDEX IF NOT EXISTS looms_run_index_tenant ON looms_run_index (tenant);
77
- CREATE INDEX IF NOT EXISTS looms_run_index_project ON looms_run_index (project);
78
- CREATE INDEX IF NOT EXISTS looms_run_index_org ON looms_run_index (org);
79
73
  CREATE INDEX IF NOT EXISTS looms_run_index_parent ON looms_run_index (parent_run_id);
80
74
  CREATE INDEX IF NOT EXISTS looms_run_index_status ON looms_run_index (status);
81
75
 
@@ -93,7 +87,26 @@ function sqliteReplicaMigration(id, sql) {
93
87
  ].join('\n\n'),
94
88
  };
95
89
  }
96
- /** Versioned DDL for the SQLite replica, including D1. Looms only creates `looms_*` objects. */
90
+ function sqliteColumnSql(column) {
91
+ const name = `"${column.name}"`;
92
+ const value = `(SELECT value FROM json_each(looms_run_index.attributes) WHERE key = ${sqlStringLiteral(column.key)})`;
93
+ return `
94
+ ALTER TABLE looms_run_index ADD COLUMN ${name} TEXT;
95
+
96
+ UPDATE looms_run_index SET ${name} = ${value}
97
+ WHERE ${name} IS NULL AND ${value} IS NOT NULL;
98
+ `.trim();
99
+ }
100
+ function sqliteColumnIndexSql(column) {
101
+ return `CREATE INDEX IF NOT EXISTS looms_run_index_${column.name} ON looms_run_index ("${column.name}");`;
102
+ }
103
+ /** Versioned DDL for the SQLite replica with no attribute columns, including D1. Looms only creates `looms_*` objects. */
97
104
  export const SQLITE_REPLICA_MIGRATIONS = [
98
105
  sqliteReplicaMigration('0001_replica', SQLITE_REPLICA_SCHEMA_SQL),
99
106
  ];
107
+ export function sqliteReplicaMigrations(additionalFields) {
108
+ return [
109
+ ...SQLITE_REPLICA_MIGRATIONS,
110
+ ...columnMigrations(additionalFields, sqliteReplicaMigration, sqliteColumnSql, sqliteColumnIndexSql),
111
+ ];
112
+ }
@@ -1,5 +1,7 @@
1
- import { type EventStore, type FoldRegistry, type RunState } from '@swirls/looms/core';
1
+ import { type EventStore, type FoldRegistry, type RunAttributeFields, type RunState } from '@swirls/looms/core';
2
2
  import { ReplicaGapError, type Projector } from '../projector';
3
+ import { type NoAdditionalFields, type ReplicaPurgeOptions } from './columns';
4
+ export type { NoAdditionalFields, ReplicaPurgeOptions } from './columns';
3
5
  export interface ReplicaStatus {
4
6
  /** Highest sequence copied with no hole in front of it. */
5
7
  readonly replicatedSeq: number;
@@ -10,12 +12,6 @@ export interface ReplicaStatus {
10
12
  /** Set once retention has deleted the event copy. */
11
13
  readonly purgedAt: number | null;
12
14
  }
13
- export interface ReplicaPurgeOptions {
14
- /** Delete event copies for runs that finished before this epoch millisecond. */
15
- readonly finishedBefore: number;
16
- /** Keep the run summary row. Defaults to true. */
17
- readonly keepIndex?: boolean;
18
- }
19
15
  export interface ReplicaPurgeResult {
20
16
  readonly runs: number;
21
17
  }
@@ -46,7 +42,7 @@ export interface D1BoundStatement {
46
42
  }>;
47
43
  first<T>(): Promise<T | null>;
48
44
  }
49
- export type SqliteReplicaOptions = {
45
+ export type SqliteReplicaOptions<Fields extends RunAttributeFields = NoAdditionalFields> = {
50
46
  readonly database: SqliteReplicaDatabase;
51
47
  /**
52
48
  * `auto` applies pending migrations on init.
@@ -54,6 +50,11 @@ export type SqliteReplicaOptions = {
54
50
  * `looms replica generate --dialect sqlite` so the host can commit the SQL.
55
51
  */
56
52
  readonly migrate: SqliteReplicaMigrate;
53
+ /**
54
+ * Declared run attributes, from `defineRunAttributes`. Each one is a `looms_run_index`
55
+ * column, and each column and index is its own migration. `purge({ where })` filters on them.
56
+ */
57
+ readonly additionalFields?: Fields;
57
58
  };
58
59
  /**
59
60
  * Adapts Cloudflare D1.
@@ -75,7 +76,7 @@ export declare function d1ReplicaDatabase<Statement extends D1BoundStatement>(d1
75
76
  * Reading an event back returns the envelope the source returned.
76
77
  * Targets a shared SQLite database or D1, not the per-run actor store.
77
78
  */
78
- export interface SqliteReplica extends Projector {
79
+ export interface SqliteReplica<Fields extends RunAttributeFields = NoAdditionalFields> extends Projector {
79
80
  readonly position: (runId: string) => Promise<number | null>;
80
81
  /** Apply pending migrations. `init` does this only when `migrate` is `auto`. */
81
82
  readonly migrate: () => Promise<void>;
@@ -87,9 +88,9 @@ export interface SqliteReplica extends Projector {
87
88
  /** How far the copy has got, and whether it is safe to treat as complete. */
88
89
  readonly status: (runId: string) => Promise<ReplicaStatus | null>;
89
90
  /** Delete event copies for finished runs. Later deliveries for those runs are skipped. */
90
- readonly purge: (options: ReplicaPurgeOptions) => Promise<ReplicaPurgeResult>;
91
+ readonly purge: (options: ReplicaPurgeOptions<Fields>) => Promise<ReplicaPurgeResult>;
91
92
  /** Copy every run in `source`. Purged runs are left alone. */
92
93
  readonly rebuild: (source: EventStore) => Promise<number>;
93
94
  }
94
- export declare function sqliteReplica(options: SqliteReplicaOptions): SqliteReplica;
95
+ export declare function sqliteReplica<const Fields extends RunAttributeFields = NoAdditionalFields>(options: SqliteReplicaOptions<Fields>): SqliteReplica<Fields>;
95
96
  export { ReplicaGapError };
@@ -3,7 +3,8 @@ import { EventOriginSchema, EventStoreError, JsonValueSchema, foldRun, } from '@
3
3
  import { eventLogOps } from '../event-log-ops.js';
4
4
  import { indexOpsFor } from '../index-model.js';
5
5
  import { ReplicaGapError } from '../projector.js';
6
- import { SQLITE_REPLICA_MIGRATIONS } from './sqlite-migrations.js';
6
+ import { columnValues, purgeFilters, resolveReplicaColumns, } from './columns.js';
7
+ import { sqliteReplicaMigrations } from './sqlite-migrations.js';
7
8
  const REPLICA_NAME = 'sqlite-replica';
8
9
  const REPLICA_VERSION = '1';
9
10
  const READ_PAGE = 500;
@@ -176,13 +177,15 @@ function runIndexPatches(ops) {
176
177
  }
177
178
  return [...patches.values()];
178
179
  }
179
- function upsertRun(patch) {
180
+ function upsertRun(patch, columns) {
180
181
  const start = patch.start;
182
+ const hostNames = columns.map((column) => `"${column.name}"`);
183
+ const hostSet = hostNames.map((name) => `${name} = COALESCE(looms_run_index.${name}, excluded.${name}),`);
181
184
  return sqlStatement(`INSERT INTO looms_run_index (
182
185
  run_id, status, kind, definition_name, definition_version, root_thread_id,
183
186
  parent_run_id, launched_by_effect_id, correlation_id, attributes,
184
- tenant, project, org, started_at, updated_at, completed_at
185
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
187
+ started_at, updated_at, completed_at${hostNames.map((name) => `, ${name}`).join('')}
188
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${', ?'.repeat(columns.length)})
186
189
  ON CONFLICT (run_id) DO UPDATE SET
187
190
  status = CASE
188
191
  WHEN excluded.completed_at IS NOT NULL THEN excluded.status
@@ -200,9 +203,7 @@ function upsertRun(patch) {
200
203
  WHEN looms_run_index.attributes = '{}' THEN excluded.attributes
201
204
  ELSE looms_run_index.attributes
202
205
  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
+ ${hostSet.join('\n ')}
206
207
  started_at = COALESCE(looms_run_index.started_at, excluded.started_at),
207
208
  updated_at = MAX(looms_run_index.updated_at, excluded.updated_at),
208
209
  completed_at = COALESCE(looms_run_index.completed_at, excluded.completed_at)`, [
@@ -216,19 +217,17 @@ function upsertRun(patch) {
216
217
  start?.launchedByEffectId ?? null,
217
218
  start?.correlationId ?? null,
218
219
  jsonText(start?.attributes ?? {}),
219
- start?.tenant ?? null,
220
- start?.project ?? null,
221
- start?.org ?? null,
222
220
  start ? start.at : null,
223
221
  patch.updatedAt,
224
222
  patch.completedAt,
223
+ ...columnValues(columns, start?.attributes),
225
224
  ]);
226
225
  }
227
- function runIndexStatements(ops) {
226
+ function runIndexStatements(ops, columns) {
228
227
  const statements = [];
229
228
  for (const patch of runIndexPatches(ops)) {
230
229
  if (patch.start || patch.finish) {
231
- statements.push(upsertRun(patch));
230
+ statements.push(upsertRun(patch, columns));
232
231
  continue;
233
232
  }
234
233
  statements.push(sqlStatement(`UPDATE looms_run_index SET updated_at = MAX(updated_at, ?) WHERE run_id = ?`, [
@@ -289,6 +288,8 @@ function indexStatements(ops) {
289
288
  }
290
289
  export function sqliteReplica(options) {
291
290
  const database = options.database;
291
+ const columns = resolveReplicaColumns(options.additionalFields);
292
+ const migrations = sqliteReplicaMigrations(options.additionalFields);
292
293
  let ready;
293
294
  const appliedMigrationIds = async () => {
294
295
  const table = await database.get(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'looms_schema_migrations'`);
@@ -300,11 +301,13 @@ export function sqliteReplica(options) {
300
301
  };
301
302
  const pendingMigrations = async () => {
302
303
  const applied = await appliedMigrationIds();
303
- return SQLITE_REPLICA_MIGRATIONS.filter((migration) => !applied.has(migration.id)).map((migration) => migration.id);
304
+ return migrations
305
+ .filter((migration) => !applied.has(migration.id))
306
+ .map((migration) => migration.id);
304
307
  };
305
308
  const migrate = async () => {
306
309
  const applied = await appliedMigrationIds();
307
- for (const migration of SQLITE_REPLICA_MIGRATIONS) {
310
+ for (const migration of migrations) {
308
311
  if (!applied.has(migration.id)) {
309
312
  await database.exec(migration.sql);
310
313
  }
@@ -339,7 +342,7 @@ export function sqliteReplica(options) {
339
342
  const durable = batch.filter((event) => !event.ephemeral);
340
343
  const last = batch.at(-1);
341
344
  statements.push(...insertEvents(batch));
342
- statements.push(...runIndexStatements(durable.flatMap((event) => eventLogOps(event))));
345
+ statements.push(...runIndexStatements(durable.flatMap((event) => eventLogOps(event)), columns));
343
346
  statements.push(...indexStatements(durable.flatMap(indexOpsFor)));
344
347
  if (next === replicatedSeq || !last) {
345
348
  continue;
@@ -458,11 +461,15 @@ export function sqliteReplica(options) {
458
461
  };
459
462
  const purge = async (purgeOptions) => {
460
463
  const keepIndex = purgeOptions.keepIndex !== false;
464
+ const filters = purgeFilters(columns, purgeOptions.where);
465
+ const filterSql = filters.map((filter) => `AND "${filter.column}" = ?`).join(' ');
466
+ const filterParams = filters.map((filter) => filter.value);
461
467
  const doomed = await database.all(`SELECT run_id FROM looms_run_index
462
468
  WHERE purged_at IS NULL
463
469
  AND status IN ('completed', 'failed', 'cancelled')
464
470
  AND completed_at IS NOT NULL
465
- AND completed_at < ?`, [purgeOptions.finishedBefore]);
471
+ AND completed_at < ?
472
+ ${filterSql}`, [purgeOptions.finishedBefore, ...filterParams]);
466
473
  if (doomed.length === 0) {
467
474
  return { runs: 0 };
468
475
  }