@axiom-lattice/local-stores 4.0.7 → 5.0.1

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.
@@ -0,0 +1,510 @@
1
+ /**
2
+ * LocalWorkflowTrackingStore behavior tests.
3
+ *
4
+ * Mirrors the PostgreSQL workflow integration suite: run CRUD, tenant-scoped
5
+ * listings, query filtering/pagination, and step create/upsert/update lookups.
6
+ * Each test uses its own SQLite file because sql.js persists on write.
7
+ */
8
+
9
+ import { afterEach, beforeEach, describe, expect, it, jest } from "@jest/globals";
10
+ import { tmpdir } from "os";
11
+ import path from "path";
12
+ import { randomUUID } from "crypto";
13
+
14
+ import { closeDatabase, initDatabase, type DatabaseWrapper } from "../database";
15
+ import { LocalWorkflowTrackingStore } from "../stores/LocalWorkflowTrackingStore";
16
+
17
+ const nextDbPath = () =>
18
+ path.join(tmpdir(), `lt-workflow-test-${Date.now()}-${Math.random().toString(36).slice(2)}.db`);
19
+
20
+ function topologyEdges() {
21
+ return [
22
+ { from: "input", to: "planner", purpose: "kickoff" },
23
+ { from: "planner", to: "worker", purpose: "delegate" },
24
+ ];
25
+ }
26
+
27
+ describe("LocalWorkflowTrackingStore", () => {
28
+ let db: DatabaseWrapper;
29
+ let store: LocalWorkflowTrackingStore;
30
+
31
+ beforeEach(async () => {
32
+ db = await initDatabase({ dbPath: nextDbPath() });
33
+ store = new LocalWorkflowTrackingStore(db);
34
+ });
35
+
36
+ afterEach(() => {
37
+ closeDatabase();
38
+ });
39
+
40
+ function tenantId(): string {
41
+ return `workflow-${randomUUID()}`;
42
+ }
43
+
44
+ async function createRun(
45
+ tenant: string,
46
+ overrides: {
47
+ threadId?: string;
48
+ assistantId?: string;
49
+ metadata?: Record<string, unknown>;
50
+ } = {},
51
+ ) {
52
+ return store.createWorkflowRun({
53
+ tenantId: tenant,
54
+ assistantId: overrides.assistantId ?? `assistant-${randomUUID()}`,
55
+ threadId: overrides.threadId ?? `thread-${randomUUID()}`,
56
+ topologyEdges: topologyEdges(),
57
+ metadata: overrides.metadata ?? {
58
+ source: "test",
59
+ nested: { workflow: "demo", tags: ["a", "b"] },
60
+ },
61
+ });
62
+ }
63
+
64
+ describe("workflow runs", () => {
65
+ it("creates a run and reads back topology edges and metadata", async () => {
66
+ const tenant = tenantId();
67
+ const threadId = `thread-${randomUUID()}`;
68
+ const assistantId = `assistant-${randomUUID()}`;
69
+
70
+ const run = await store.createWorkflowRun({
71
+ tenantId: tenant,
72
+ assistantId,
73
+ threadId,
74
+ topologyEdges: topologyEdges(),
75
+ metadata: { source: "test", nested: { workflow: "demo", tags: ["a", "b"] } },
76
+ });
77
+
78
+ expect(run).toMatchObject({
79
+ tenantId: tenant,
80
+ assistantId,
81
+ threadId,
82
+ status: "running",
83
+ totalEdges: 2,
84
+ completedEdges: 0,
85
+ });
86
+ expect(run.topologyEdges).toEqual(topologyEdges());
87
+ expect(run.metadata).toEqual({ source: "test", nested: { workflow: "demo", tags: ["a", "b"] } });
88
+ expect(run.startedAt).toBeInstanceOf(Date);
89
+
90
+ const read = await store.getWorkflowRun(run.id);
91
+ expect(read).toMatchObject({ id: run.id, tenantId: tenant, status: "running" });
92
+ expect(read!.topologyEdges).toEqual(topologyEdges());
93
+ expect(read!.metadata).toEqual(run.metadata);
94
+ });
95
+
96
+ it("returns null for an absent run", async () => {
97
+ expect(await store.getWorkflowRun(randomUUID())).toBeNull();
98
+ });
99
+
100
+ it("creates distinct runs for the same thread and timestamp", async () => {
101
+ const tenant = tenantId();
102
+ const threadId = `thread-${randomUUID()}`;
103
+ const assistantId = `assistant-${randomUUID()}`;
104
+ const nowSpy = jest.spyOn(Date, "now").mockReturnValue(1700000000000);
105
+
106
+ try {
107
+ const first = await store.createWorkflowRun({
108
+ tenantId: tenant,
109
+ assistantId,
110
+ threadId,
111
+ topologyEdges: topologyEdges(),
112
+ });
113
+ const second = await store.createWorkflowRun({
114
+ tenantId: tenant,
115
+ assistantId,
116
+ threadId,
117
+ topologyEdges: topologyEdges(),
118
+ });
119
+
120
+ expect(second.id).not.toBe(first.id);
121
+ expect(first.id.startsWith(`${threadId}_`)).toBe(true);
122
+ expect(second.id.startsWith(`${threadId}_`)).toBe(true);
123
+
124
+ const listed = await store.getWorkflowRunsByThreadId(tenant, threadId);
125
+ expect(listed.map((r) => r.id).sort()).toEqual([first.id, second.id].sort());
126
+ } finally {
127
+ nowSpy.mockRestore();
128
+ }
129
+ });
130
+
131
+ it("updates run status, counts, error, completion time, and metadata", async () => {
132
+ const tenant = tenantId();
133
+ const run = await createRun(tenant);
134
+ const completedAt = new Date("2026-02-03T04:05:06.000Z");
135
+
136
+ const updated = await store.updateWorkflowRun(run.id, {
137
+ status: "failed",
138
+ completedEdges: 1,
139
+ errorMessage: "worker exploded",
140
+ completedAt,
141
+ metadata: { failure: { code: "E_WORKER", retryable: false } },
142
+ });
143
+
144
+ expect(updated).toMatchObject({
145
+ id: run.id,
146
+ status: "failed",
147
+ completedEdges: 1,
148
+ totalEdges: 2,
149
+ errorMessage: "worker exploded",
150
+ });
151
+ expect(updated!.completedAt?.toISOString()).toBe(completedAt.toISOString());
152
+ expect(updated!.metadata).toEqual({ failure: { code: "E_WORKER", retryable: false } });
153
+ expect(updated!.topologyEdges).toEqual(topologyEdges());
154
+ });
155
+
156
+ it("returns null when updating an absent run", async () => {
157
+ expect(await store.updateWorkflowRun(randomUUID(), { status: "completed" })).toBeNull();
158
+ });
159
+
160
+ it("deletes a run and treats a repeat delete as a no-op", async () => {
161
+ const tenant = tenantId();
162
+ const run = await createRun(tenant);
163
+
164
+ await store.deleteWorkflowRun(run.id);
165
+ expect(await store.getWorkflowRun(run.id)).toBeNull();
166
+ await expect(store.deleteWorkflowRun(run.id)).resolves.toBeUndefined();
167
+ });
168
+
169
+ it("lists runs by thread, assistant, and tenant with tenant isolation", async () => {
170
+ const tenantA = tenantId();
171
+ const tenantB = tenantId();
172
+ const assistantA = `assistant-${randomUUID()}`;
173
+ const assistantB = `assistant-${randomUUID()}`;
174
+ const threadA1 = `thread-${randomUUID()}`;
175
+ const threadA2 = `thread-${randomUUID()}`;
176
+ const threadA3 = `thread-${randomUUID()}`;
177
+
178
+ const r1 = await createRun(tenantA, { threadId: threadA1, assistantId: assistantA });
179
+ const r2 = await createRun(tenantA, { threadId: threadA2, assistantId: assistantA });
180
+ const r3 = await createRun(tenantA, { threadId: threadA3, assistantId: assistantB });
181
+ const r4 = await createRun(tenantB, { threadId: `thread-${randomUUID()}`, assistantId: assistantA });
182
+
183
+ expect((await store.getWorkflowRunsByThreadId(tenantA, threadA1)).map((r) => r.id)).toEqual([
184
+ r1.id,
185
+ ]);
186
+ expect((await store.getWorkflowRunsByThreadId(tenantA, threadA2)).map((r) => r.id)).toEqual([
187
+ r2.id,
188
+ ]);
189
+ expect((await store.getWorkflowRunsByThreadId(tenantA, threadA3)).map((r) => r.id)).toEqual([
190
+ r3.id,
191
+ ]);
192
+ expect(
193
+ (await store.getWorkflowRunsByAssistantId(tenantA, assistantA)).map((r) => r.id).sort(),
194
+ ).toEqual([r1.id, r2.id].sort());
195
+ expect((await store.getWorkflowRunsByTenantId(tenantA)).map((r) => r.id).sort()).toEqual(
196
+ [r1.id, r2.id, r3.id].sort(),
197
+ );
198
+ expect((await store.getWorkflowRunsByTenantId(tenantB)).map((r) => r.id)).toEqual([r4.id]);
199
+
200
+ expect(await store.getWorkflowRunsByThreadId(tenantB, threadA1)).toEqual([]);
201
+ expect(await store.getWorkflowRunsByAssistantId(tenantB, assistantB)).toEqual([]);
202
+ });
203
+
204
+ it("filters queryWorkflowRuns by status and assistant", async () => {
205
+ const tenant = tenantId();
206
+ const otherTenant = tenantId();
207
+ const assistantA = `assistant-${randomUUID()}`;
208
+ const assistantB = `assistant-${randomUUID()}`;
209
+ const r1 = await createRun(tenant, { assistantId: assistantA });
210
+ const r2 = await createRun(tenant, { assistantId: assistantA });
211
+ const r3 = await createRun(tenant, { assistantId: assistantB });
212
+ await store.updateWorkflowRun(r2.id, { status: "completed" });
213
+
214
+ const running = await store.queryWorkflowRuns(tenant, { status: "running" });
215
+ expect(running.total).toBe(2);
216
+ expect(running.records.map((r) => r.id).sort()).toEqual([r1.id, r3.id].sort());
217
+
218
+ const completed = await store.queryWorkflowRuns(tenant, { status: "completed" });
219
+ expect(completed.total).toBe(1);
220
+ expect(completed.records.map((r) => r.id)).toEqual([r2.id]);
221
+
222
+ const byAssistant = await store.queryWorkflowRuns(tenant, { assistantId: assistantB });
223
+ expect(byAssistant.total).toBe(1);
224
+ expect(byAssistant.records.map((r) => r.id)).toEqual([r3.id]);
225
+
226
+ const combined = await store.queryWorkflowRuns(tenant, {
227
+ status: "running",
228
+ assistantId: assistantA,
229
+ });
230
+ expect(combined.total).toBe(1);
231
+ expect(combined.records.map((r) => r.id)).toEqual([r1.id]);
232
+
233
+ const other = await store.queryWorkflowRuns(otherTenant, { status: "running" });
234
+ expect(other).toEqual({ records: [], total: 0 });
235
+ });
236
+
237
+ it("paginates queryWorkflowRuns while counting all matches", async () => {
238
+ const tenant = tenantId();
239
+ const runs = [await createRun(tenant), await createRun(tenant), await createRun(tenant)];
240
+
241
+ const firstPage = await store.queryWorkflowRuns(tenant, { limit: 2, offset: 0 });
242
+ const secondPage = await store.queryWorkflowRuns(tenant, { limit: 2, offset: 2 });
243
+ const all = await store.queryWorkflowRuns(tenant);
244
+
245
+ expect(firstPage.total).toBe(3);
246
+ expect(secondPage.total).toBe(3);
247
+ expect(firstPage.records).toHaveLength(2);
248
+ expect(secondPage.records).toHaveLength(1);
249
+
250
+ const firstIds = firstPage.records.map((r) => r.id);
251
+ const secondIds = secondPage.records.map((r) => r.id);
252
+ expect(firstIds.filter((id) => secondIds.includes(id))).toEqual([]);
253
+ expect([...firstIds, ...secondIds].sort()).toEqual(runs.map((r) => r.id).sort());
254
+
255
+ expect(all.total).toBe(3);
256
+ expect(all.records).toHaveLength(3);
257
+ });
258
+
259
+ it("falls back to empty metadata when the stored column is null", async () => {
260
+ const tenant = tenantId();
261
+ const run = await createRun(tenant);
262
+
263
+ db.prepare("UPDATE lt_workflow_runs SET metadata = NULL WHERE id = ?").run(run.id);
264
+
265
+ const read = await store.getWorkflowRun(run.id);
266
+ expect(read!.metadata).toEqual({});
267
+ expect(read!.topologyEdges).toEqual(topologyEdges());
268
+ });
269
+ });
270
+
271
+ describe("run steps", () => {
272
+ it("creates a step and reads back input, edge data, and thread id", async () => {
273
+ const tenant = tenantId();
274
+ const run = await createRun(tenant);
275
+ const threadId = `thread-${randomUUID()}`;
276
+
277
+ const step = await store.createRunStep({
278
+ runId: run.id,
279
+ tenantId: tenant,
280
+ stepType: "tool_call",
281
+ stepName: "search",
282
+ threadId,
283
+ edgeFrom: "planner",
284
+ edgeTo: "worker",
285
+ edgePurpose: "delegate",
286
+ input: { query: "weather", nested: { limit: 3 } },
287
+ });
288
+
289
+ expect(step).toMatchObject({
290
+ runId: run.id,
291
+ tenantId: tenant,
292
+ stepType: "tool_call",
293
+ stepName: "search",
294
+ threadId,
295
+ edgeFrom: "planner",
296
+ edgeTo: "worker",
297
+ edgePurpose: "delegate",
298
+ status: "running",
299
+ });
300
+ expect(step.input).toEqual({ query: "weather", nested: { limit: 3 } });
301
+ expect(step.output).toBeUndefined();
302
+ expect(step.startedAt).toBeInstanceOf(Date);
303
+
304
+ const steps = await store.getRunSteps(run.id);
305
+ expect(steps.map((s) => s.id)).toEqual([step.id]);
306
+ expect(steps[0].input).toEqual({ query: "weather", nested: { limit: 3 } });
307
+ });
308
+
309
+ it("upserts by run, step type, and step name", async () => {
310
+ const tenant = tenantId();
311
+ const run = await createRun(tenant);
312
+ const first = await store.createRunStep({
313
+ runId: run.id,
314
+ tenantId: tenant,
315
+ stepType: "agent",
316
+ stepName: "Writer",
317
+ input: { brief: "original" },
318
+ });
319
+
320
+ const upserted = await store.upsertRunStep({
321
+ runId: run.id,
322
+ tenantId: tenant,
323
+ stepType: "agent",
324
+ stepName: "Writer",
325
+ threadId: "sub-thread-1",
326
+ input: { brief: "replacement" },
327
+ });
328
+
329
+ expect(upserted.id).toBe(first.id);
330
+ expect(upserted.threadId).toBe("sub-thread-1");
331
+ expect(upserted.input).toEqual({ brief: "original" });
332
+
333
+ const again = await store.upsertRunStep({
334
+ runId: run.id,
335
+ tenantId: tenant,
336
+ stepType: "agent",
337
+ stepName: "Writer",
338
+ threadId: "sub-thread-2",
339
+ });
340
+ expect(again.id).toBe(first.id);
341
+ expect(again.threadId).toBe("sub-thread-1");
342
+
343
+ const distinct = await store.upsertRunStep({
344
+ runId: run.id,
345
+ tenantId: tenant,
346
+ stepType: "agent",
347
+ stepName: "Reviewer",
348
+ });
349
+ expect(distinct.id).not.toBe(first.id);
350
+ expect(await store.getRunSteps(run.id)).toHaveLength(2);
351
+ });
352
+
353
+ it("updates a step result and returns null for an absent step", async () => {
354
+ const tenant = tenantId();
355
+ const run = await createRun(tenant);
356
+ const step = await store.createRunStep({
357
+ runId: run.id,
358
+ tenantId: tenant,
359
+ stepType: "agent",
360
+ stepName: "Writer",
361
+ });
362
+ const completedAt = new Date("2026-03-04T05:06:07.000Z");
363
+
364
+ const updated = await store.updateRunStep(run.id, step.id, {
365
+ status: "completed",
366
+ output: { draft: "hello", tokens: { input: 10, output: 20 } },
367
+ completedAt,
368
+ durationMs: 1234,
369
+ });
370
+
371
+ expect(updated).toMatchObject({
372
+ id: step.id,
373
+ status: "completed",
374
+ durationMs: 1234,
375
+ });
376
+ expect(updated!.output).toEqual({ draft: "hello", tokens: { input: 10, output: 20 } });
377
+ expect(updated!.completedAt?.toISOString()).toBe(completedAt.toISOString());
378
+
379
+ expect(
380
+ await store.updateRunStep(run.id, randomUUID(), { status: "completed" }),
381
+ ).toBeNull();
382
+ });
383
+
384
+ it("finds steps by type and interrupted steps", async () => {
385
+ const tenant = tenantId();
386
+ const run = await createRun(tenant);
387
+ const toolStep = await store.createRunStep({
388
+ runId: run.id,
389
+ tenantId: tenant,
390
+ stepType: "tool_call",
391
+ stepName: "search",
392
+ });
393
+ const agentStep = await store.createRunStep({
394
+ runId: run.id,
395
+ tenantId: tenant,
396
+ stepType: "agent",
397
+ stepName: "Writer",
398
+ });
399
+ const humanStep = await store.createRunStep({
400
+ runId: run.id,
401
+ tenantId: tenant,
402
+ stepType: "human_in_loop",
403
+ stepName: "approve",
404
+ });
405
+ await store.updateRunStep(run.id, humanStep.id, { status: "interrupted" });
406
+ await store.updateRunStep(run.id, agentStep.id, { status: "completed" });
407
+
408
+ const toolSteps = await store.getRunStepsByType(run.id, "tool_call");
409
+ expect(toolSteps.map((s) => s.id)).toEqual([toolStep.id]);
410
+
411
+ const interrupted = await store.getInterruptedSteps(run.id);
412
+ expect(interrupted.map((s) => s.id)).toEqual([humanStep.id]);
413
+ expect(interrupted[0].status).toBe("interrupted");
414
+ });
415
+
416
+ it("returns empty step lists for an absent run", async () => {
417
+ const missingRun = randomUUID();
418
+
419
+ expect(await store.getRunSteps(missingRun)).toEqual([]);
420
+ expect(await store.getRunStepsByType(missingRun, "agent")).toEqual([]);
421
+ expect(await store.getInterruptedSteps(missingRun)).toEqual([]);
422
+ });
423
+
424
+ it("migrates a legacy steps table that lacks thread_id", async () => {
425
+ closeDatabase();
426
+ const legacyDb = await initDatabase({ dbPath: nextDbPath() });
427
+ // Simulate an install created before `thread_id` existed.
428
+ legacyDb.exec(`
429
+ CREATE TABLE lt_workflow_steps (
430
+ id TEXT NOT NULL,
431
+ run_id TEXT NOT NULL,
432
+ tenant_id TEXT NOT NULL,
433
+ step_type TEXT NOT NULL,
434
+ step_name TEXT NOT NULL,
435
+ edge_from TEXT,
436
+ edge_to TEXT,
437
+ edge_purpose TEXT,
438
+ input TEXT,
439
+ output TEXT,
440
+ status TEXT NOT NULL DEFAULT 'running',
441
+ error_message TEXT,
442
+ started_at TEXT NOT NULL,
443
+ completed_at TEXT,
444
+ duration_ms INTEGER,
445
+ created_at TEXT NOT NULL,
446
+ updated_at TEXT NOT NULL,
447
+ PRIMARY KEY (run_id, id)
448
+ );
449
+ `);
450
+ legacyDb.prepare(
451
+ `INSERT INTO lt_workflow_steps
452
+ (id, run_id, tenant_id, step_type, step_name, status, started_at, created_at, updated_at)
453
+ VALUES (?, ?, ?, ?, ?, 'completed', ?, ?, ?)`,
454
+ ).run(
455
+ "legacy-step",
456
+ "legacy-run",
457
+ "legacy-tenant",
458
+ "agent",
459
+ "Old Step",
460
+ "2026-01-01T00:00:00.000Z",
461
+ "2026-01-01T00:00:00.000Z",
462
+ "2026-01-01T00:00:00.000Z",
463
+ );
464
+
465
+ let migrated!: LocalWorkflowTrackingStore;
466
+ expect(() => {
467
+ migrated = new LocalWorkflowTrackingStore(legacyDb);
468
+ }).not.toThrow();
469
+
470
+ const existing = await migrated.getRunSteps("legacy-run");
471
+ expect(existing).toHaveLength(1);
472
+ expect(existing[0]).toMatchObject({
473
+ id: "legacy-step",
474
+ stepName: "Old Step",
475
+ status: "completed",
476
+ });
477
+ expect(existing[0].threadId).toBeNull();
478
+
479
+ const created = await migrated.createRunStep({
480
+ runId: "legacy-run",
481
+ tenantId: "legacy-tenant",
482
+ stepType: "agent",
483
+ stepName: "New Step",
484
+ threadId: "sub-thread-1",
485
+ });
486
+ expect(created.threadId).toBe("sub-thread-1");
487
+
488
+ const after = await migrated.getRunSteps("legacy-run");
489
+ const newStep = after.find((step) => step.id === created.id);
490
+ expect(newStep?.threadId).toBe("sub-thread-1");
491
+ expect(after).toHaveLength(2);
492
+ });
493
+
494
+ it("falls back to undefined for null step input and output", async () => {
495
+ const tenant = tenantId();
496
+ const run = await createRun(tenant);
497
+ const step = await store.createRunStep({
498
+ runId: run.id,
499
+ tenantId: tenant,
500
+ stepType: "input",
501
+ stepName: "start",
502
+ });
503
+
504
+ const [read] = await store.getRunSteps(run.id);
505
+ expect(read.id).toBe(step.id);
506
+ expect(read.input).toBeUndefined();
507
+ expect(read.output).toBeUndefined();
508
+ });
509
+ });
510
+ });
@@ -8,8 +8,10 @@ import type {
8
8
  MetricsServerConfigEntry,
9
9
  CreateMetricsServerConfigRequest,
10
10
  UpdateMetricsServerConfigRequest,
11
+ MetricsServerConfig,
11
12
  } from "@axiom-lattice/protocols";
12
13
  import { ensureTable, nowISO, parseISO } from "../database";
14
+ import { encrypt, isEncryptedValue, safeDecrypt } from "@axiom-lattice/core";
13
15
 
14
16
  const DDL = `
15
17
  CREATE TABLE IF NOT EXISTS lt_metrics_configs (
@@ -89,7 +91,7 @@ export class LocalMetricsServerConfigStore implements MetricsServerConfigStore {
89
91
  description = excluded.description,
90
92
  config = excluded.config,
91
93
  updated_at = excluded.updated_at`,
92
- ).run(id, tenantId, data.key, data.name || null, data.description || null, JSON.stringify(data.config), now, now);
94
+ ).run(id, tenantId, data.key, data.name || null, data.description || null, JSON.stringify(encryptSecretsInConfig(data.config)), now, now);
93
95
 
94
96
  return {
95
97
  id,
@@ -117,7 +119,7 @@ export class LocalMetricsServerConfigStore implements MetricsServerConfigStore {
117
119
  if (updates.key !== undefined) { setClauses.push("key = ?"); values.push(updates.key); }
118
120
  if (updates.name !== undefined) { setClauses.push("name = ?"); values.push(updates.name || null); }
119
121
  if (updates.description !== undefined) { setClauses.push("description = ?"); values.push(updates.description || null); }
120
- if (updates.config !== undefined) { setClauses.push("config = ?"); values.push(JSON.stringify(updates.config)); }
122
+ if (updates.config !== undefined) { setClauses.push("config = ?"); values.push(JSON.stringify(encryptSecretsInConfig(updates.config))); }
121
123
 
122
124
  if (setClauses.length === 0) return existing;
123
125
 
@@ -153,10 +155,40 @@ function mapRowToEntry(row: ConfigRow): MetricsServerConfigEntry {
153
155
  id: row.id,
154
156
  tenantId: row.tenant_id,
155
157
  key: row.key,
156
- config: JSON.parse(row.config),
158
+ config: decryptSecretsInConfig(JSON.parse(row.config) as MetricsServerConfig),
157
159
  name: row.name || undefined,
158
160
  description: row.description || undefined,
159
161
  createdAt: parseISO(row.created_at),
160
162
  updatedAt: parseISO(row.updated_at),
161
163
  };
162
164
  }
165
+
166
+ /**
167
+ * Encrypt apiKey and password before storing. Shallow copy so callers' config
168
+ * objects are never mutated.
169
+ */
170
+ function encryptSecretsInConfig(config: MetricsServerConfig): MetricsServerConfig {
171
+ const configCopy = { ...config };
172
+ if (configCopy.apiKey) configCopy.apiKey = encrypt(configCopy.apiKey);
173
+ if (configCopy.password) configCopy.password = encrypt(configCopy.password);
174
+ return configCopy;
175
+ }
176
+
177
+ /**
178
+ * Decrypt stored secrets.
179
+ *
180
+ * Only values that look like our ciphertext are decrypted. Local installs may
181
+ * predate encryption and still hold plaintext, so those are left untouched
182
+ * (they are encrypted on the next config write). A value that looks encrypted
183
+ * but cannot be decrypted with the current key degrades to `""` via
184
+ * `safeDecrypt`, so stored ciphertext is never surfaced as plaintext.
185
+ */
186
+ function decryptSecretsInConfig(config: MetricsServerConfig): MetricsServerConfig {
187
+ if (config.apiKey && isEncryptedValue(config.apiKey)) {
188
+ config.apiKey = safeDecrypt(config.apiKey);
189
+ }
190
+ if (config.password && isEncryptedValue(config.password)) {
191
+ config.password = safeDecrypt(config.password);
192
+ }
193
+ return config;
194
+ }
@@ -243,7 +243,12 @@ export class LocalScheduleStorage implements ScheduleStorage {
243
243
  if (conditions.length > 0) query += ` WHERE ${conditions.join(" AND ")}`;
244
244
  query += ` ORDER BY created_at DESC`;
245
245
 
246
- if (filters?.limit !== undefined) { query += ` LIMIT ?`; values.push(filters.limit); }
246
+ if (filters?.limit !== undefined) {
247
+ query += ` LIMIT ?`;
248
+ values.push(filters.limit);
249
+ } else if (filters?.offset !== undefined) {
250
+ query += ` LIMIT -1`; // SQLite requires LIMIT before OFFSET
251
+ }
247
252
  if (filters?.offset !== undefined) { query += ` OFFSET ?`; values.push(filters.offset); }
248
253
 
249
254
  const rows = this.db.prepare(query).all(...values) as unknown as TaskRow[];
@@ -2,6 +2,7 @@
2
2
  * Local SQLite implementation of WorkflowTrackingStore.
3
3
  */
4
4
 
5
+ import { randomUUID } from "node:crypto";
5
6
  import { DatabaseWrapper } from "../database";
6
7
  import type {
7
8
  WorkflowTrackingStore,
@@ -61,8 +62,6 @@ CREATE TABLE IF NOT EXISTS lt_workflow_steps (
61
62
  PRIMARY KEY (run_id, id)
62
63
  );
63
64
  CREATE INDEX IF NOT EXISTS idx_lt_ws_type ON lt_workflow_steps(run_id, step_type);
64
- -- Backfill for existing databases that don't have the column
65
- ALTER TABLE lt_workflow_steps ADD COLUMN IF NOT EXISTS thread_id TEXT;
66
65
  `;
67
66
 
68
67
  interface RunRow {
@@ -109,11 +108,22 @@ export class LocalWorkflowTrackingStore implements WorkflowTrackingStore {
109
108
  constructor(db: DatabaseWrapper) {
110
109
  this.db = db;
111
110
  ensureTable(db, DDL);
111
+ // Backfill for existing databases that don't have the column. SQLite has no
112
+ // `ADD COLUMN IF NOT EXISTS`, so check via PRAGMA instead.
113
+ this.ensureColumn("lt_workflow_steps", "thread_id", "thread_id TEXT");
114
+ }
115
+
116
+ /** Add a column if it does not exist (SQLite version compatible). */
117
+ private ensureColumn(table: string, column: string, ddl: string): void {
118
+ const cols = this.db.prepare(`PRAGMA table_info(${table})`).all() as unknown as Array<{ name: string }>;
119
+ if (!cols.some((c) => c.name === column)) {
120
+ this.db.exec(`ALTER TABLE ${table} ADD COLUMN ${ddl}`);
121
+ }
112
122
  }
113
123
 
114
124
  async createWorkflowRun(request: CreateWorkflowRunRequest): Promise<WorkflowRun> {
115
125
  const now = nowISO();
116
- const id = `${request.threadId}_${Date.now()}`;
126
+ const id = `${request.threadId}_${Date.now()}_${randomUUID()}`;
117
127
 
118
128
  this.db.prepare(
119
129
  `INSERT INTO lt_workflow_runs (id, tenant_id, assistant_id, thread_id, status, topology_edges, total_edges, completed_edges, metadata, started_at, created_at, updated_at)