@axiom-lattice/local-stores 3.1.12 → 3.1.13

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@axiom-lattice/local-stores",
3
- "version": "3.1.12",
3
+ "version": "3.1.13",
4
4
  "description": "Local SQLite-based stores for Axiom Lattice framework",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -25,7 +25,7 @@
25
25
  "@types/sql.js": "^1.4.11",
26
26
  "sql.js": "^1.14.1",
27
27
  "uuid": "^14.0.1",
28
- "@axiom-lattice/core": "4.2.12",
28
+ "@axiom-lattice/core": "4.2.13",
29
29
  "@axiom-lattice/protocols": "4.2.3"
30
30
  },
31
31
  "devDependencies": {
@@ -316,6 +316,23 @@ describe("local project room stores", () => {
316
316
  expect(await reopened.messages.list({ tenantId: "t1", roomId: "r1", before: { createdAt: second.createdAt, id: second.id }, limit: 10 })).toEqual([first]);
317
317
  });
318
318
 
319
+ it("deletes old chat messages in bounded batches while retaining task events", async () => {
320
+ const store = new LocalProjectRoomMessageStore(await initDatabase({ dbPath }));
321
+ const base = { tenantId: "t1", workspaceId: "w1", projectId: "p1", roomId: "r1", content: { type: "text" as const, text: "x" }, mentions: [] };
322
+ await store.create({ ...base, id: "user-1", author: { type: "human", userId: "u1" }, source: "user" });
323
+ await store.create({ ...base, id: "agent-1", author: { type: "bot", membershipId: "bot", assistantId: "a1" }, source: "agent" });
324
+ await store.create({ ...base, id: "task-1", author: { type: "system" }, source: "task" });
325
+ const horizon = new Date(Date.now() + 60_000);
326
+
327
+ await expect(store.deleteChatOlderThan({ before: horizon, limit: 1 })).resolves.toBe(1);
328
+ await expect(store.deleteChatOlderThan({ before: horizon, limit: 1 })).resolves.toBe(1);
329
+ await expect(store.deleteChatOlderThan({ before: horizon, limit: 1 })).resolves.toBe(0);
330
+ await expect(store.findById("t1", "task-1")).resolves.toMatchObject({ id: "task-1" });
331
+ await expect(store.findById("t1", "user-1")).resolves.toBeNull();
332
+ await expect(store.findById("t1", "agent-1")).resolves.toBeNull();
333
+ await expect(store.deleteChatOlderThan({ before: new Date("invalid"), limit: 1 })).rejects.toBeInstanceOf(RangeError);
334
+ });
335
+
319
336
  it("round-trips cloned message JSON, maps uniqueness, idempotency, and exact descending cursors", async () => {
320
337
  const store = new LocalProjectRoomMessageStore(await initDatabase({ dbPath }));
321
338
  const message = { id: "m1", tenantId: "t1", workspaceId: "w1", projectId: "p1", roomId: "r1", author: { type: "human" as const, userId: "u1" }, content: { type: "text" as const, text: "hello" }, mentions: [{ type: "team" as const }], source: "user" as const, idempotencyKey: "key-1" };
@@ -74,6 +74,25 @@ export class LocalProjectRoomMessageStore implements ProjectRoomMessageStore {
74
74
  return !(record(parsed) && parsed.type === "human" && parsed.userId === input.excludeAuthorUserId);
75
75
  }).length;
76
76
  }
77
+ /**
78
+ * Deletes one bounded batch of chat messages older than a horizon.
79
+ *
80
+ * @param input Exclusive upper time bound and requested batch size (clamped to 1..1000).
81
+ * @returns The number of deleted rows.
82
+ * @remarks Only `source: "user" | "agent"` rows are eligible; task/system events are retained.
83
+ */
84
+ async deleteChatOlderThan(input: { before: Date; limit: number }): Promise<number> {
85
+ if (!validDate(input.before)) throw new RangeError("Project room message retention horizon date is invalid");
86
+ const limit = Math.min(1_000, Math.max(1, Math.trunc(Number.isFinite(input.limit) ? input.limit : 1)));
87
+ return transaction(this.db, () => write(this.db,
88
+ `DELETE FROM lt_project_room_messages WHERE rowid IN (
89
+ SELECT rowid FROM lt_project_room_messages
90
+ WHERE created_at < ? AND source IN ('user','agent')
91
+ ORDER BY created_at ASC LIMIT ?
92
+ )`,
93
+ [input.before.toISOString(), limit]));
94
+ }
95
+
77
96
  private insert(input: Omit<ProjectRoomMessage, "createdAt">, idempotent: boolean): ProjectRoomMessage {
78
97
  return transaction(this.db, () => {
79
98
  if (idempotent && input.idempotencyKey) { const canonical = this.byKey(input.tenantId, input.roomId, input.idempotencyKey); if (canonical) return mapRow(canonical); }
@@ -49,6 +49,8 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_lt_project_room_messages_idempotency
49
49
  ON lt_project_room_messages (tenant_id, room_id, idempotency_key) WHERE idempotency_key IS NOT NULL;
50
50
  CREATE INDEX IF NOT EXISTS idx_lt_project_room_messages_room_created
51
51
  ON lt_project_room_messages (tenant_id, room_id, created_at DESC, id DESC);
52
+ CREATE INDEX IF NOT EXISTS idx_lt_project_room_messages_chat_created
53
+ ON lt_project_room_messages (created_at) WHERE source IN ('user','agent');
52
54
  CREATE TABLE IF NOT EXISTS lt_project_room_read_states (
53
55
  tenant_id TEXT NOT NULL, room_id TEXT NOT NULL, user_id TEXT NOT NULL,
54
56
  last_read_at TEXT NOT NULL, updated_at TEXT NOT NULL,
@@ -210,6 +212,20 @@ export function ensureProjectRoomSchema(db: DatabaseWrapper): void {
210
212
  }
211
213
  }
212
214
  validateProjectRoomSchema(db);
215
+ const hasRetentionIndex = rows(db, "SELECT name FROM sqlite_master WHERE type = 'index' AND name = 'idx_lt_project_room_messages_chat_created'").length > 0;
216
+ if (!hasRetentionIndex) {
217
+ raw.exec("BEGIN IMMEDIATE");
218
+ try {
219
+ raw.exec("CREATE INDEX IF NOT EXISTS idx_lt_project_room_messages_chat_created ON lt_project_room_messages (created_at) WHERE source IN ('user','agent');");
220
+ raw.run("INSERT INTO lattice_schema_migrations (store_name, name, version, applied_at) VALUES (?, ?, ?, ?)",
221
+ ["project_room", "add_project_room_message_retention_index", 3, new Date().toISOString()]);
222
+ raw.exec("COMMIT");
223
+ db.save();
224
+ } catch (error) {
225
+ try { raw.exec("ROLLBACK"); } catch { /* preserve the schema failure */ }
226
+ throw error;
227
+ }
228
+ }
213
229
  marked[schemaMarker] = true;
214
230
  return;
215
231
  }