@anuma/sdk 6.21.1 → 6.23.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 (32) hide show
  1. package/dist/expo/{chunk-CIMZZ7GQ.mjs → chunk-6BULYLRY.mjs} +92 -8
  2. package/dist/expo/index.cjs +761 -162
  3. package/dist/expo/index.d.mts +151 -9
  4. package/dist/expo/index.d.ts +151 -9
  5. package/dist/expo/index.mjs +516 -14
  6. package/dist/{react/recall-7Q3V337H.mjs → expo/recall-CUTJWQDQ.mjs} +1 -1
  7. package/dist/memory/context.cjs +183 -0
  8. package/dist/memory/context.d.mts +936 -0
  9. package/dist/memory/context.d.ts +936 -0
  10. package/dist/memory/context.mjs +157 -0
  11. package/dist/react/{chunk-AVYB5IXC.mjs → chunk-GPLMMMZN.mjs} +1 -1
  12. package/dist/react/{chunk-JRVAUZHM.mjs → chunk-K4N52PSK.mjs} +93 -9
  13. package/dist/react/{consolidate-URHGJT7I.mjs → consolidate-XKS6IZFC.mjs} +2 -2
  14. package/dist/react/index.cjs +876 -270
  15. package/dist/react/index.d.mts +209 -9
  16. package/dist/react/index.d.ts +209 -9
  17. package/dist/react/index.mjs +569 -65
  18. package/dist/{expo/recall-FQQGE6A2.mjs → react/recall-LFHIWONV.mjs} +2 -2
  19. package/dist/server/{chunk-4DSDATYG.mjs → chunk-FEDRFVHD.mjs} +182 -98
  20. package/dist/server/index.cjs +815 -216
  21. package/dist/server/index.d.mts +150 -5
  22. package/dist/server/index.d.ts +150 -5
  23. package/dist/server/index.mjs +509 -7
  24. package/dist/server/{recall-HA4UX4BB.mjs → recall-Z2WJGXOL.mjs} +1 -1
  25. package/dist/telemetry/index.d.mts +7 -1
  26. package/dist/telemetry/index.d.ts +7 -1
  27. package/dist/tools/index.cjs +347 -1
  28. package/dist/tools/index.d.mts +167 -1
  29. package/dist/tools/index.d.ts +167 -1
  30. package/dist/tools/index.mjs +343 -1
  31. package/package.json +8 -1
  32. package/dist/react/{chunk-WUG6GTHO.mjs → chunk-MHZB6KIX.mjs} +8 -8
@@ -13924,8 +13924,8 @@ var require_Model = __commonJS({
13924
13924
  function associations(...associationList) {
13925
13925
  return (0, _fromPairs.default)(associationList);
13926
13926
  }
13927
- var Model = exports.default = /* @__PURE__ */ (function() {
13928
- function Model2(collection, raw) {
13927
+ var Model2 = exports.default = /* @__PURE__ */ (function() {
13928
+ function Model3(collection, raw) {
13929
13929
  this._isEditing = false;
13930
13930
  this._preparedState = null;
13931
13931
  this.__changes = null;
@@ -13933,7 +13933,7 @@ var require_Model = __commonJS({
13933
13933
  this.collection = collection;
13934
13934
  this._raw = raw;
13935
13935
  }
13936
- var _proto = Model2.prototype;
13936
+ var _proto = Model3.prototype;
13937
13937
  _proto._getChanges = function() {
13938
13938
  if (!this.__changes) {
13939
13939
  this.__changes = new _rx.BehaviorSubject(this);
@@ -14078,7 +14078,7 @@ var require_Model = __commonJS({
14078
14078
  _proto.callReader = function(action) {
14079
14079
  return this.db._workQueue.subAction(action);
14080
14080
  };
14081
- Model2._prepareCreate = function(collection, recordBuilder) {
14081
+ Model3._prepareCreate = function(collection, recordBuilder) {
14082
14082
  var record = new this(
14083
14083
  collection,
14084
14084
  // sanitizedRaw sets id
@@ -14091,13 +14091,13 @@ var require_Model = __commonJS({
14091
14091
  record.__logVerbose("prepareCreate");
14092
14092
  return record;
14093
14093
  };
14094
- Model2._prepareCreateFromDirtyRaw = function(collection, dirtyRaw) {
14094
+ Model3._prepareCreateFromDirtyRaw = function(collection, dirtyRaw) {
14095
14095
  var record = new this(collection, (0, _RawRecord.sanitizedRaw)(dirtyRaw, collection.schema));
14096
14096
  record._preparedState = "create";
14097
14097
  record.__logVerbose("prepareCreateFromDirtyRaw");
14098
14098
  return record;
14099
14099
  };
14100
- Model2._disposableFromDirtyRaw = function(collection, dirtyRaw) {
14100
+ Model3._disposableFromDirtyRaw = function(collection, dirtyRaw) {
14101
14101
  var record = new this(collection, (0, _RawRecord.sanitizedRaw)(dirtyRaw, collection.schema));
14102
14102
  record._raw._status = "disposable";
14103
14103
  record.__logVerbose("disposableFromDirtyRaw");
@@ -14155,7 +14155,7 @@ var require_Model = __commonJS({
14155
14155
  _logger.default.debug("".concat(debugName, ": ").concat(this.__debugName));
14156
14156
  }
14157
14157
  };
14158
- return (0, _createClass2.default)(Model2, [{
14158
+ return (0, _createClass2.default)(Model3, [{
14159
14159
  key: "id",
14160
14160
  get: function get() {
14161
14161
  return this._raw.id;
@@ -14217,8 +14217,8 @@ var require_Model = __commonJS({
14217
14217
  }
14218
14218
  }]);
14219
14219
  })();
14220
- Model.associations = {};
14221
- Model._wmelonTag = "model";
14220
+ Model2.associations = {};
14221
+ Model2._wmelonTag = "model";
14222
14222
  }
14223
14223
  });
14224
14224
 
@@ -14272,7 +14272,7 @@ var require_watermelondb = __commonJS({
14272
14272
  });
14273
14273
 
14274
14274
  // src/lib/db/chat/operations.ts
14275
- var import_watermelondb = __toESM(require_watermelondb());
14275
+ var import_watermelondb2 = __toESM(require_watermelondb());
14276
14276
  import { v7 as uuidv72 } from "uuid";
14277
14277
 
14278
14278
  // src/react/useEncryption.ts
@@ -15262,6 +15262,12 @@ async function decryptJsonField(value, address) {
15262
15262
  }
15263
15263
  }
15264
15264
 
15265
+ // src/lib/db/extractionJobs/models.ts
15266
+ var import_watermelondb = __toESM(require_watermelondb());
15267
+ var ExtractionJob = class extends import_watermelondb.Model {
15268
+ };
15269
+ ExtractionJob.table = "memory_extraction_jobs";
15270
+
15265
15271
  // src/lib/db/chat/conversationEncryption.ts
15266
15272
  async function encryptConversationFields(conversation, address, signMessage, embeddedWalletSigner) {
15267
15273
  if (!address || !signMessage) {
@@ -15702,7 +15708,7 @@ async function createConversationOp(ctx, opts, defaultTitle = "New Conversation"
15702
15708
  );
15703
15709
  }
15704
15710
  async function getConversationOp(ctx, id) {
15705
- const results = await ctx.conversationsCollection.query(import_watermelondb.Q.where("conversation_id", id), import_watermelondb.Q.where("is_deleted", false)).fetch();
15711
+ const results = await ctx.conversationsCollection.query(import_watermelondb2.Q.where("conversation_id", id), import_watermelondb2.Q.where("is_deleted", false)).fetch();
15706
15712
  return results.length > 0 ? await conversationToStored(
15707
15713
  results[0],
15708
15714
  ctx.walletAddress,
@@ -15711,7 +15717,7 @@ async function getConversationOp(ctx, id) {
15711
15717
  ) : null;
15712
15718
  }
15713
15719
  async function getConversationsOp(ctx) {
15714
- const results = await ctx.conversationsCollection.query(import_watermelondb.Q.where("is_deleted", false), import_watermelondb.Q.sortBy("created_at", import_watermelondb.Q.desc)).unsafeFetchRaw();
15720
+ const results = await ctx.conversationsCollection.query(import_watermelondb2.Q.where("is_deleted", false), import_watermelondb2.Q.sortBy("created_at", import_watermelondb2.Q.desc)).unsafeFetchRaw();
15715
15721
  return Promise.all(
15716
15722
  results.map(
15717
15723
  (raw) => conversationRawToStored(raw, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner)
@@ -15732,33 +15738,33 @@ function conversationRawToLazyStored(raw) {
15732
15738
  };
15733
15739
  }
15734
15740
  async function getConversationsLazyOp(ctx) {
15735
- const results = await ctx.conversationsCollection.query(import_watermelondb.Q.where("is_deleted", false), import_watermelondb.Q.sortBy("created_at", import_watermelondb.Q.desc)).unsafeFetchRaw();
15741
+ const results = await ctx.conversationsCollection.query(import_watermelondb2.Q.where("is_deleted", false), import_watermelondb2.Q.sortBy("created_at", import_watermelondb2.Q.desc)).unsafeFetchRaw();
15736
15742
  return results.map(conversationRawToLazyStored);
15737
15743
  }
15738
15744
  async function getConversationsPageOp(ctx, options) {
15739
15745
  const limit = Math.floor(options?.limit ?? 200);
15740
15746
  if (!Number.isFinite(limit) || limit < 1) return [];
15741
15747
  const exclude = new Set(options?.boundaryExcludeUniqueIds ?? []);
15742
- const clauses = [import_watermelondb.Q.where("is_deleted", false)];
15748
+ const clauses = [import_watermelondb2.Q.where("is_deleted", false)];
15743
15749
  if (options?.before !== void 0) {
15744
15750
  clauses.push(
15745
- exclude.size > 0 ? import_watermelondb.Q.where("created_at", import_watermelondb.Q.lte(options.before)) : import_watermelondb.Q.where("created_at", import_watermelondb.Q.lt(options.before))
15751
+ exclude.size > 0 ? import_watermelondb2.Q.where("created_at", import_watermelondb2.Q.lte(options.before)) : import_watermelondb2.Q.where("created_at", import_watermelondb2.Q.lt(options.before))
15746
15752
  );
15747
15753
  }
15748
- const fetched = await ctx.conversationsCollection.query(...clauses, import_watermelondb.Q.sortBy("created_at", import_watermelondb.Q.desc), import_watermelondb.Q.take(limit + exclude.size)).unsafeFetchRaw();
15754
+ const fetched = await ctx.conversationsCollection.query(...clauses, import_watermelondb2.Q.sortBy("created_at", import_watermelondb2.Q.desc), import_watermelondb2.Q.take(limit + exclude.size)).unsafeFetchRaw();
15749
15755
  const results = exclude.size > 0 ? fetched.filter((raw) => !exclude.has(raw.id)) : fetched;
15750
15756
  return results.slice(0, limit).map(conversationRawToLazyStored);
15751
15757
  }
15752
15758
  async function getConversationsByProjectLazyOp(ctx, projectId) {
15753
15759
  const results = await ctx.conversationsCollection.query(
15754
- import_watermelondb.Q.where("project_id", projectId === null ? "" : projectId),
15755
- import_watermelondb.Q.where("is_deleted", false),
15756
- import_watermelondb.Q.sortBy("created_at", import_watermelondb.Q.desc)
15760
+ import_watermelondb2.Q.where("project_id", projectId === null ? "" : projectId),
15761
+ import_watermelondb2.Q.where("is_deleted", false),
15762
+ import_watermelondb2.Q.sortBy("created_at", import_watermelondb2.Q.desc)
15757
15763
  ).unsafeFetchRaw();
15758
15764
  return results.map(conversationRawToLazyStored);
15759
15765
  }
15760
15766
  async function updateConversationTitleOp(ctx, id, title) {
15761
- const results = await ctx.conversationsCollection.query(import_watermelondb.Q.where("conversation_id", id), import_watermelondb.Q.where("is_deleted", false)).fetch();
15767
+ const results = await ctx.conversationsCollection.query(import_watermelondb2.Q.where("conversation_id", id), import_watermelondb2.Q.where("is_deleted", false)).fetch();
15762
15768
  if (results.length > 0) {
15763
15769
  const encryptedOpts = ctx.walletAddress && ctx.signMessage ? await encryptConversationFields(
15764
15770
  { title },
@@ -15777,19 +15783,21 @@ async function updateConversationTitleOp(ctx, id, title) {
15777
15783
  return false;
15778
15784
  }
15779
15785
  async function deleteConversationOp(ctx, id) {
15780
- const results = await ctx.conversationsCollection.query(import_watermelondb.Q.where("conversation_id", id), import_watermelondb.Q.where("is_deleted", false)).fetch();
15786
+ const results = await ctx.conversationsCollection.query(import_watermelondb2.Q.where("conversation_id", id), import_watermelondb2.Q.where("is_deleted", false)).fetch();
15781
15787
  if (results.length > 0) {
15782
15788
  await ctx.database.write(async () => {
15783
15789
  await results[0].update((conv) => {
15784
15790
  conv._setRaw("is_deleted", true);
15785
15791
  });
15792
+ const jobs = ctx.database.schema?.tables[ExtractionJob.table] ? await ctx.database.get(ExtractionJob.table).query(import_watermelondb2.Q.where("conversation_id", id)).fetch() : [];
15793
+ for (const job of jobs) await job.destroyPermanently();
15786
15794
  });
15787
15795
  return true;
15788
15796
  }
15789
15797
  return false;
15790
15798
  }
15791
15799
  async function updateConversationProjectOp(ctx, id, projectId) {
15792
- const results = await ctx.conversationsCollection.query(import_watermelondb.Q.where("conversation_id", id), import_watermelondb.Q.where("is_deleted", false)).fetch();
15800
+ const results = await ctx.conversationsCollection.query(import_watermelondb2.Q.where("conversation_id", id), import_watermelondb2.Q.where("is_deleted", false)).fetch();
15793
15801
  if (results.length > 0) {
15794
15802
  await ctx.database.write(async () => {
15795
15803
  await results[0].update((conv) => {
@@ -15802,9 +15810,9 @@ async function updateConversationProjectOp(ctx, id, projectId) {
15802
15810
  }
15803
15811
  async function getConversationsByProjectOp(ctx, projectId) {
15804
15812
  const results = await ctx.conversationsCollection.query(
15805
- import_watermelondb.Q.where("project_id", projectId === null ? "" : projectId),
15806
- import_watermelondb.Q.where("is_deleted", false),
15807
- import_watermelondb.Q.sortBy("created_at", import_watermelondb.Q.desc)
15813
+ import_watermelondb2.Q.where("project_id", projectId === null ? "" : projectId),
15814
+ import_watermelondb2.Q.where("is_deleted", false),
15815
+ import_watermelondb2.Q.sortBy("created_at", import_watermelondb2.Q.desc)
15808
15816
  ).unsafeFetchRaw();
15809
15817
  return Promise.all(
15810
15818
  results.map(
@@ -15813,7 +15821,7 @@ async function getConversationsByProjectOp(ctx, projectId) {
15813
15821
  );
15814
15822
  }
15815
15823
  async function getMessagesOp(ctx, convId) {
15816
- const results = await ctx.messagesCollection.query(import_watermelondb.Q.where("conversation_id", convId), import_watermelondb.Q.sortBy("message_id", import_watermelondb.Q.asc)).unsafeFetchRaw();
15824
+ const results = await ctx.messagesCollection.query(import_watermelondb2.Q.where("conversation_id", convId), import_watermelondb2.Q.sortBy("message_id", import_watermelondb2.Q.asc)).unsafeFetchRaw();
15817
15825
  return Promise.all(
15818
15826
  results.map(
15819
15827
  (raw) => messageRawToStored(raw, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner)
@@ -15821,8 +15829,16 @@ async function getMessagesOp(ctx, convId) {
15821
15829
  );
15822
15830
  }
15823
15831
  async function clearMessagesOp(ctx, convId) {
15824
- const messages = await ctx.messagesCollection.query(import_watermelondb.Q.where("conversation_id", convId)).fetch();
15825
15832
  await ctx.database.write(async () => {
15833
+ const messages = await ctx.messagesCollection.query(import_watermelondb2.Q.where("conversation_id", convId)).fetch();
15834
+ const jobs = ctx.database.schema?.tables[ExtractionJob.table] ? await ctx.database.get(ExtractionJob.table).query(import_watermelondb2.Q.where("conversation_id", convId)).fetch() : [];
15835
+ for (const job of jobs) {
15836
+ await job.update((row) => {
15837
+ row._setRaw("message_ids", "[]");
15838
+ row._setRaw("watermark", null);
15839
+ row._setRaw("watermark_seq", null);
15840
+ });
15841
+ }
15826
15842
  for (const message of messages) {
15827
15843
  await message.update((msg) => {
15828
15844
  msg._setRaw("file_ids", null);
@@ -15832,6 +15848,30 @@ async function clearMessagesOp(ctx, convId) {
15832
15848
  }
15833
15849
  });
15834
15850
  }
15851
+ async function deleteMessageOp(ctx, uniqueId) {
15852
+ let message;
15853
+ try {
15854
+ message = await ctx.messagesCollection.find(uniqueId);
15855
+ } catch {
15856
+ return null;
15857
+ }
15858
+ await ctx.database.write(async () => {
15859
+ const jobs = ctx.database.schema?.tables[ExtractionJob.table] ? await ctx.database.get(ExtractionJob.table).query(import_watermelondb2.Q.where("conversation_id", message.conversationId)).fetch() : [];
15860
+ for (const job of jobs) {
15861
+ const ids = JSON.parse(String(job._getRaw("message_ids")));
15862
+ await job.update((row) => {
15863
+ row._setRaw("message_ids", JSON.stringify(ids.filter((id) => id !== uniqueId)));
15864
+ if (row._getRaw("watermark") === uniqueId) row._setRaw("watermark", null);
15865
+ });
15866
+ }
15867
+ await message.update((msg) => {
15868
+ msg._setRaw("file_ids", null);
15869
+ msg._setRaw("files", null);
15870
+ });
15871
+ await message.destroyPermanently();
15872
+ });
15873
+ return uniqueId;
15874
+ }
15835
15875
  async function encryptMessageOptsIfNeeded(ctx, opts) {
15836
15876
  return ctx.walletAddress && ctx.signMessage ? await encryptMessageFields(opts, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner) : opts;
15837
15877
  }
@@ -15889,9 +15929,9 @@ async function createMessageOp(ctx, opts) {
15889
15929
  }
15890
15930
  }
15891
15931
  const newest = await ctx.messagesCollection.query(
15892
- import_watermelondb.Q.where("conversation_id", opts.conversationId),
15893
- import_watermelondb.Q.sortBy("message_id", import_watermelondb.Q.desc),
15894
- import_watermelondb.Q.take(1)
15932
+ import_watermelondb2.Q.where("conversation_id", opts.conversationId),
15933
+ import_watermelondb2.Q.sortBy("message_id", import_watermelondb2.Q.desc),
15934
+ import_watermelondb2.Q.take(1)
15895
15935
  ).fetch();
15896
15936
  const messageId = (newest[0]?.messageId ?? 0) + 1;
15897
15937
  const encryptedOpts = await encryptMessageOptsIfNeeded(ctx, opts);
@@ -15905,7 +15945,7 @@ async function createMessageOp(ctx, opts) {
15905
15945
  return messageToStored(created, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner);
15906
15946
  }
15907
15947
  async function upsertMessageOp(ctx, opts) {
15908
- const results = await ctx.messagesCollection.query(import_watermelondb.Q.where("id", opts.uniqueId)).fetch();
15948
+ const results = await ctx.messagesCollection.query(import_watermelondb2.Q.where("id", opts.uniqueId)).fetch();
15909
15949
  const existing = results.length > 0 ? results[0] : null;
15910
15950
  if (!existing) {
15911
15951
  return createMessageOp(ctx, opts);
@@ -16086,12 +16126,12 @@ async function readRawJsonField(raw, column, walletAddress) {
16086
16126
  }
16087
16127
  async function searchMessagesOp(ctx, queryVector, options) {
16088
16128
  const { limit = 10, minSimilarity = 0.5, conversationId } = options || {};
16089
- const activeConversations = await ctx.conversationsCollection.query(import_watermelondb.Q.where("is_deleted", false)).fetch();
16129
+ const activeConversations = await ctx.conversationsCollection.query(import_watermelondb2.Q.where("is_deleted", false)).fetch();
16090
16130
  const activeConversationIds = new Set(
16091
16131
  // Use _getRaw for reliable raw column access
16092
16132
  activeConversations.map((c) => String(c._getRaw("conversation_id")))
16093
16133
  );
16094
- const queryConditions = conversationId ? [import_watermelondb.Q.where("conversation_id", conversationId)] : [];
16134
+ const queryConditions = conversationId ? [import_watermelondb2.Q.where("conversation_id", conversationId)] : [];
16095
16135
  const messages = await ctx.messagesCollection.query(...queryConditions).unsafeFetchRaw();
16096
16136
  const candidates = [];
16097
16137
  for (const message of messages) {
@@ -16125,12 +16165,12 @@ async function searchChunksOp(ctx, queryVector, options) {
16125
16165
  embeddingModel,
16126
16166
  chunkCache
16127
16167
  } = options || {};
16128
- const activeConversations = await ctx.conversationsCollection.query(import_watermelondb.Q.where("is_deleted", false)).fetch();
16168
+ const activeConversations = await ctx.conversationsCollection.query(import_watermelondb2.Q.where("is_deleted", false)).fetch();
16129
16169
  const activeConversationIds = new Set(
16130
16170
  // Use _getRaw for reliable raw column access
16131
16171
  activeConversations.map((c) => String(c._getRaw("conversation_id")))
16132
16172
  );
16133
- const queryConditions = conversationId ? [import_watermelondb.Q.where("conversation_id", conversationId)] : [];
16173
+ const queryConditions = conversationId ? [import_watermelondb2.Q.where("conversation_id", conversationId)] : [];
16134
16174
  const messages = await ctx.messagesCollection.query(...queryConditions).unsafeFetchRaw();
16135
16175
  const candidates = [];
16136
16176
  let staleSkipped = 0;
@@ -16256,13 +16296,13 @@ async function searchChunksOp(ctx, queryVector, options) {
16256
16296
  }
16257
16297
  async function getAllFilesOp(ctx, options) {
16258
16298
  const { conversationId, limit } = options || {};
16259
- const activeConversations = await ctx.conversationsCollection.query(import_watermelondb.Q.where("is_deleted", false)).fetch();
16299
+ const activeConversations = await ctx.conversationsCollection.query(import_watermelondb2.Q.where("is_deleted", false)).fetch();
16260
16300
  const activeConversationIds = new Set(
16261
16301
  // Use _getRaw for reliable raw column access
16262
16302
  activeConversations.map((c) => String(c._getRaw("conversation_id")))
16263
16303
  );
16264
- const queryConditions = conversationId ? [import_watermelondb.Q.where("conversation_id", conversationId)] : [];
16265
- const messages = await ctx.messagesCollection.query(...queryConditions, import_watermelondb.Q.sortBy("created_at", import_watermelondb.Q.desc)).fetch();
16304
+ const queryConditions = conversationId ? [import_watermelondb2.Q.where("conversation_id", conversationId)] : [];
16305
+ const messages = await ctx.messagesCollection.query(...queryConditions, import_watermelondb2.Q.sortBy("created_at", import_watermelondb2.Q.desc)).fetch();
16266
16306
  const filesWithContext = [];
16267
16307
  for (const message of messages) {
16268
16308
  const msgConvId = String(message._getRaw("conversation_id"));
@@ -16325,7 +16365,7 @@ function makeSyntheticStoredConversation(opts, defaultTitle) {
16325
16365
  }
16326
16366
 
16327
16367
  // src/lib/db/entities/operations.ts
16328
- var import_watermelondb2 = __toESM(require_watermelondb());
16368
+ var import_watermelondb3 = __toESM(require_watermelondb());
16329
16369
 
16330
16370
  // src/lib/db/entities/types.ts
16331
16371
  var ENTITY_KINDS = [
@@ -16392,7 +16432,7 @@ async function upsertEntitiesInWrite(ctx, entities) {
16392
16432
  const unique = Array.from(kindByName.keys());
16393
16433
  const out = /* @__PURE__ */ new Map();
16394
16434
  if (unique.length === 0) return { entities: out, operations: [], kindBackfills: [] };
16395
- const existing = await ctx.entityCollection.query(import_watermelondb2.Q.where("canonical_name", import_watermelondb2.Q.oneOf(unique))).fetch();
16435
+ const existing = await ctx.entityCollection.query(import_watermelondb3.Q.where("canonical_name", import_watermelondb3.Q.oneOf(unique))).fetch();
16396
16436
  const existingNames = new Set(existing.map((e) => e.canonicalName));
16397
16437
  const kindBackfills = existing.filter((e) => {
16398
16438
  const incoming = kindByName.get(e.canonicalName);
@@ -16422,7 +16462,7 @@ function prepareKindBackfills(backfills) {
16422
16462
  }
16423
16463
  async function findVaultRowInWrite(ctx, memoryId) {
16424
16464
  try {
16425
- const rows = await ctx.database.get("memory_vault").query(import_watermelondb2.Q.where("id", memoryId)).fetch();
16465
+ const rows = await ctx.database.get("memory_vault").query(import_watermelondb3.Q.where("id", memoryId)).fetch();
16426
16466
  return rows[0] ?? null;
16427
16467
  } catch {
16428
16468
  return null;
@@ -16497,7 +16537,7 @@ async function linkMemoryEntitiesOp(ctx, memoryId, entityInputs, options) {
16497
16537
  return;
16498
16538
  }
16499
16539
  if (entities.length === 0) return;
16500
- const existingLinks = await ctx.memoryEntityCollection.query(import_watermelondb2.Q.where("memory_id", memoryId)).fetch();
16540
+ const existingLinks = await ctx.memoryEntityCollection.query(import_watermelondb3.Q.where("memory_id", memoryId)).fetch();
16501
16541
  const existingEntityIds = new Set(existingLinks.map((l) => String(l.entityId)));
16502
16542
  const toCreate = entities.filter((e) => !existingEntityIds.has(e.uniqueId));
16503
16543
  const keptIds = entities.map((e) => e.uniqueId);
@@ -16532,7 +16572,7 @@ async function linkMemoryEntitiesOp(ctx, memoryId, entityInputs, options) {
16532
16572
  }
16533
16573
  async function resolveEntitiesByIds(ctx, entityIds) {
16534
16574
  if (entityIds.length === 0) return [];
16535
- const rows = await ctx.entityCollection.query(import_watermelondb2.Q.where("id", import_watermelondb2.Q.oneOf(Array.from(entityIds)))).fetch();
16575
+ const rows = await ctx.entityCollection.query(import_watermelondb3.Q.where("id", import_watermelondb3.Q.oneOf(Array.from(entityIds)))).fetch();
16536
16576
  return rows.map(entityToStored);
16537
16577
  }
16538
16578
  function autoLinkBlocked(row) {
@@ -16567,7 +16607,7 @@ async function replaceMemoryEntities(ctx, memoryId, entityInputs, options) {
16567
16607
  kindBackfills
16568
16608
  } = await upsertEntitiesInWrite(ctx, normalized);
16569
16609
  entities = Array.from(byName.values());
16570
- const existingLinks = await ctx.memoryEntityCollection.query(import_watermelondb2.Q.where("memory_id", memoryId)).fetch();
16610
+ const existingLinks = await ctx.memoryEntityCollection.query(import_watermelondb3.Q.where("memory_id", memoryId)).fetch();
16571
16611
  const keep = new Set(entities.map((e) => e.uniqueId));
16572
16612
  const existingEntityIds = new Set(existingLinks.map((l) => String(l.entityId)));
16573
16613
  const toCreate = entities.filter((e) => !existingEntityIds.has(e.uniqueId));
@@ -16602,17 +16642,17 @@ async function replaceMemoryEntities(ctx, memoryId, entityInputs, options) {
16602
16642
  async function findOrphanedEntities(ctx, memoryId, toDestroy) {
16603
16643
  const candidateIds = [...new Set(toDestroy.map((l) => String(l.entityId)))];
16604
16644
  if (candidateIds.length === 0) return [];
16605
- const links = await ctx.memoryEntityCollection.query(import_watermelondb2.Q.where("entity_id", import_watermelondb2.Q.oneOf(candidateIds))).fetch();
16645
+ const links = await ctx.memoryEntityCollection.query(import_watermelondb3.Q.where("entity_id", import_watermelondb3.Q.oneOf(candidateIds))).fetch();
16606
16646
  const stillLinked = new Set(
16607
16647
  links.filter((l) => String(l.memoryId) !== memoryId).map((l) => String(l.entityId))
16608
16648
  );
16609
16649
  const orphanIds = candidateIds.filter((id) => !stillLinked.has(id));
16610
16650
  if (orphanIds.length === 0) return [];
16611
- return await ctx.entityCollection.query(import_watermelondb2.Q.where("id", import_watermelondb2.Q.oneOf(orphanIds))).fetch();
16651
+ return await ctx.entityCollection.query(import_watermelondb3.Q.where("id", import_watermelondb3.Q.oneOf(orphanIds))).fetch();
16612
16652
  }
16613
16653
  async function unlinkMemoryEntitiesOp(ctx, memoryIds) {
16614
16654
  if (memoryIds.length === 0) return;
16615
- const links = await ctx.memoryEntityCollection.query(import_watermelondb2.Q.where("memory_id", import_watermelondb2.Q.oneOf(Array.from(memoryIds)))).fetch();
16655
+ const links = await ctx.memoryEntityCollection.query(import_watermelondb3.Q.where("memory_id", import_watermelondb3.Q.oneOf(Array.from(memoryIds)))).fetch();
16616
16656
  if (links.length === 0) return;
16617
16657
  await ctx.database.write(async () => {
16618
16658
  await ctx.database.batch(...links.map((l) => l.prepareDestroyPermanently()));
@@ -16620,7 +16660,7 @@ async function unlinkMemoryEntitiesOp(ctx, memoryIds) {
16620
16660
  }
16621
16661
  async function unlinkAllMemoryEntitiesForUserOp(ctx, userId) {
16622
16662
  if (!userId) return;
16623
- const links = await ctx.memoryEntityCollection.query(import_watermelondb2.Q.where("user_id", userId)).fetch();
16663
+ const links = await ctx.memoryEntityCollection.query(import_watermelondb3.Q.where("user_id", userId)).fetch();
16624
16664
  if (links.length === 0) return;
16625
16665
  await ctx.database.write(async () => {
16626
16666
  await ctx.database.batch(...links.map((l) => l.prepareDestroyPermanently()));
@@ -16629,15 +16669,15 @@ async function unlinkAllMemoryEntitiesForUserOp(ctx, userId) {
16629
16669
  async function getMemoriesByEntityNamesOp(ctx, entityNames) {
16630
16670
  const unique = Array.from(new Set(entityNames.map(normalizeEntityName).filter((n) => n.length > 0)));
16631
16671
  if (unique.length === 0) return /* @__PURE__ */ new Map();
16632
- const entityRows = await ctx.entityCollection.query(import_watermelondb2.Q.where("canonical_name", import_watermelondb2.Q.oneOf(unique))).fetch();
16672
+ const entityRows = await ctx.entityCollection.query(import_watermelondb3.Q.where("canonical_name", import_watermelondb3.Q.oneOf(unique))).fetch();
16633
16673
  if (entityRows.length === 0) return /* @__PURE__ */ new Map();
16634
16674
  const entityIdToName = new Map(entityRows.map((e) => [e.id, e.canonicalName]));
16635
- const linkConditions = [import_watermelondb2.Q.where("entity_id", import_watermelondb2.Q.oneOf(entityRows.map((e) => e.id)))];
16675
+ const linkConditions = [import_watermelondb3.Q.where("entity_id", import_watermelondb3.Q.oneOf(entityRows.map((e) => e.id)))];
16636
16676
  if (ctx.userId !== void 0) {
16637
16677
  if (ctx.allowUnscopedRows) {
16638
- linkConditions.push(import_watermelondb2.Q.or(import_watermelondb2.Q.where("user_id", ctx.userId), import_watermelondb2.Q.where("user_id", null)));
16678
+ linkConditions.push(import_watermelondb3.Q.or(import_watermelondb3.Q.where("user_id", ctx.userId), import_watermelondb3.Q.where("user_id", null)));
16639
16679
  } else {
16640
- linkConditions.push(import_watermelondb2.Q.where("user_id", ctx.userId));
16680
+ linkConditions.push(import_watermelondb3.Q.where("user_id", ctx.userId));
16641
16681
  }
16642
16682
  }
16643
16683
  const links = await ctx.memoryEntityCollection.query(...linkConditions).fetch();
@@ -16658,18 +16698,18 @@ async function getMemoriesByEntityNamesOp(ctx, entityNames) {
16658
16698
  async function getEntitiesByMemoryIdsOp(ctx, memoryIds) {
16659
16699
  const unique = Array.from(new Set(memoryIds.filter((id) => id.length > 0)));
16660
16700
  if (unique.length === 0) return /* @__PURE__ */ new Map();
16661
- const linkConditions = [import_watermelondb2.Q.where("memory_id", import_watermelondb2.Q.oneOf(unique))];
16701
+ const linkConditions = [import_watermelondb3.Q.where("memory_id", import_watermelondb3.Q.oneOf(unique))];
16662
16702
  if (ctx.userId !== void 0) {
16663
16703
  if (ctx.allowUnscopedRows) {
16664
- linkConditions.push(import_watermelondb2.Q.or(import_watermelondb2.Q.where("user_id", ctx.userId), import_watermelondb2.Q.where("user_id", null)));
16704
+ linkConditions.push(import_watermelondb3.Q.or(import_watermelondb3.Q.where("user_id", ctx.userId), import_watermelondb3.Q.where("user_id", null)));
16665
16705
  } else {
16666
- linkConditions.push(import_watermelondb2.Q.where("user_id", ctx.userId));
16706
+ linkConditions.push(import_watermelondb3.Q.where("user_id", ctx.userId));
16667
16707
  }
16668
16708
  }
16669
16709
  const links = await ctx.memoryEntityCollection.query(...linkConditions).fetch();
16670
16710
  if (links.length === 0) return /* @__PURE__ */ new Map();
16671
16711
  const entityIds = Array.from(new Set(links.map((l) => String(l.entityId))));
16672
- const entityRows = await ctx.entityCollection.query(import_watermelondb2.Q.where("id", import_watermelondb2.Q.oneOf(entityIds))).fetch();
16712
+ const entityRows = await ctx.entityCollection.query(import_watermelondb3.Q.where("id", import_watermelondb3.Q.oneOf(entityIds))).fetch();
16673
16713
  const entityIdToName = new Map(entityRows.map((e) => [e.id, e.canonicalName]));
16674
16714
  const out = /* @__PURE__ */ new Map();
16675
16715
  for (const link of links) {
@@ -16687,7 +16727,7 @@ async function getEntitiesByMemoryIdsOp(ctx, memoryIds) {
16687
16727
  }
16688
16728
 
16689
16729
  // src/lib/db/memoryVault/operations.ts
16690
- var import_watermelondb3 = __toESM(require_watermelondb());
16730
+ var import_watermelondb4 = __toESM(require_watermelondb());
16691
16731
 
16692
16732
  // src/lib/db/memoryVault/encryption.ts
16693
16733
  async function encryptVaultMemoryContent(content, address, signMessage, embeddedWalletSigner) {
@@ -16739,23 +16779,24 @@ var NON_PRIVATE_VISIBILITIES = ["public"];
16739
16779
  function visibilityConditions(requested) {
16740
16780
  if (!requested?.length) return [];
16741
16781
  if (!requested.includes("private")) {
16742
- return [import_watermelondb3.Q.where("visibility", import_watermelondb3.Q.oneOf([...requested]))];
16782
+ return [import_watermelondb4.Q.where("visibility", import_watermelondb4.Q.oneOf([...requested]))];
16743
16783
  }
16744
16784
  const excluded = NON_PRIVATE_VISIBILITIES.filter((v) => !requested.includes(v));
16745
16785
  if (excluded.length === 0) return [];
16746
- return [import_watermelondb3.Q.or(import_watermelondb3.Q.where("visibility", null), import_watermelondb3.Q.where("visibility", import_watermelondb3.Q.notIn(excluded)))];
16786
+ return [import_watermelondb4.Q.or(import_watermelondb4.Q.where("visibility", null), import_watermelondb4.Q.where("visibility", import_watermelondb4.Q.notIn(excluded)))];
16747
16787
  }
16748
16788
  function isOwnedByCtxUser(ctx, record) {
16749
16789
  return ctx.userId === void 0 || record.userId === ctx.userId;
16750
16790
  }
16751
16791
  function baseVaultConditions(ctx, options) {
16752
16792
  return [
16753
- ...options?.includeDeleted ? [] : [import_watermelondb3.Q.where("is_deleted", false)],
16754
- ...options?.includeArchived ? [] : [import_watermelondb3.Q.where("archived_at", import_watermelondb3.Q.eq(null))],
16755
- ...options?.includeQuarantined ? [] : [import_watermelondb3.Q.where("trust_tier", import_watermelondb3.Q.notEq("quarantined"))],
16756
- ...options?.includeSuperseded ? [] : [import_watermelondb3.Q.where("superseded_by", null)],
16757
- ...ctx.userId !== void 0 ? [import_watermelondb3.Q.where("user_id", ctx.userId)] : [],
16758
- ...options?.since ? [import_watermelondb3.Q.where("updated_at", import_watermelondb3.Q.gt(options.since.getTime()))] : []
16793
+ ...options?.memoryIds !== void 0 ? [import_watermelondb4.Q.where("id", import_watermelondb4.Q.oneOf(options.memoryIds))] : [],
16794
+ ...options?.includeDeleted ? [] : [import_watermelondb4.Q.where("is_deleted", false)],
16795
+ ...options?.includeArchived ? [] : [import_watermelondb4.Q.where("archived_at", import_watermelondb4.Q.eq(null))],
16796
+ ...options?.includeQuarantined ? [] : [import_watermelondb4.Q.where("trust_tier", import_watermelondb4.Q.notEq("quarantined"))],
16797
+ ...options?.includeSuperseded ? [] : [import_watermelondb4.Q.where("superseded_by", null)],
16798
+ ...ctx.userId !== void 0 ? [import_watermelondb4.Q.where("user_id", ctx.userId)] : [],
16799
+ ...options?.since ? [import_watermelondb4.Q.where("updated_at", import_watermelondb4.Q.gt(options.since.getTime()))] : []
16759
16800
  ];
16760
16801
  }
16761
16802
  var KNOWN_TRUST_TIERS = /* @__PURE__ */ new Set(["quarantined", "trusted"]);
@@ -16834,6 +16875,8 @@ async function createVaultMemoryOp(ctx, opts) {
16834
16875
  ctx.embeddedWalletSigner
16835
16876
  ) : opts.content;
16836
16877
  const created = await ctx.database.write(async () => {
16878
+ if (ctx.canWrite && !await ctx.canWrite())
16879
+ throw new Error("Memory source is no longer eligible");
16837
16880
  return ctx.vaultMemoryCollection.create((record) => {
16838
16881
  record._setRaw("content", encryptedContent);
16839
16882
  record._setRaw("scope", scope);
@@ -16883,6 +16926,8 @@ async function createSupersedingMemoryOp(ctx, opts, targetId) {
16883
16926
  ) : opts.content;
16884
16927
  let createdRecord = null;
16885
16928
  await ctx.database.write(async () => {
16929
+ if (ctx.canWrite && !await ctx.canWrite())
16930
+ throw new Error("Memory source is no longer eligible");
16886
16931
  let target;
16887
16932
  try {
16888
16933
  target = await ctx.vaultMemoryCollection.find(targetId);
@@ -16928,11 +16973,11 @@ async function createSupersedingMemoryOp(ctx, opts, targetId) {
16928
16973
  async function getMemoriesByEventTimeOp(ctx, windowStart, windowEnd) {
16929
16974
  const records = await ctx.vaultMemoryCollection.query(
16930
16975
  ...baseVaultConditions(ctx),
16931
- import_watermelondb3.Q.where("event_time_start", import_watermelondb3.Q.notEq(null)),
16932
- import_watermelondb3.Q.where("event_time_start", import_watermelondb3.Q.lte(windowEnd)),
16933
- import_watermelondb3.Q.or(
16934
- import_watermelondb3.Q.where("event_time_start", import_watermelondb3.Q.gte(windowStart)),
16935
- import_watermelondb3.Q.where("event_time_kind", import_watermelondb3.Q.oneOf(["range", "ongoing"]))
16976
+ import_watermelondb4.Q.where("event_time_start", import_watermelondb4.Q.notEq(null)),
16977
+ import_watermelondb4.Q.where("event_time_start", import_watermelondb4.Q.lte(windowEnd)),
16978
+ import_watermelondb4.Q.or(
16979
+ import_watermelondb4.Q.where("event_time_start", import_watermelondb4.Q.gte(windowStart)),
16980
+ import_watermelondb4.Q.where("event_time_kind", import_watermelondb4.Q.oneOf(["range", "ongoing"]))
16936
16981
  )
16937
16982
  ).fetch();
16938
16983
  const out = [];
@@ -16987,6 +17032,8 @@ async function createVaultMemoriesBatchOp(ctx, optionsArray) {
16987
17032
  })
16988
17033
  );
16989
17034
  const created = await ctx.database.write(async () => {
17035
+ if (ctx.canWrite && !await ctx.canWrite())
17036
+ throw new Error("Memory source is no longer eligible");
16990
17037
  const prepared = optionsArray.map(
16991
17038
  (opts, i) => ctx.vaultMemoryCollection.prepareCreate((record) => {
16992
17039
  record._setRaw("content", encryptedContents[i]);
@@ -17107,12 +17154,12 @@ async function vaultMemoryRawToStored(raw, walletAddress, signMessage, embeddedW
17107
17154
  async function getAllVaultMemoriesOp(ctx, options) {
17108
17155
  const conditions = [
17109
17156
  ...baseVaultConditions(ctx, options),
17110
- ...options?.scopes?.length ? [import_watermelondb3.Q.where("scope", import_watermelondb3.Q.oneOf(options.scopes))] : [],
17157
+ ...options?.scopes?.length ? [import_watermelondb4.Q.where("scope", import_watermelondb4.Q.oneOf(options.scopes))] : [],
17111
17158
  ...visibilityConditions(options?.visibility),
17112
- ...options?.folderId !== void 0 ? [import_watermelondb3.Q.where("folder_id", options.folderId)] : [],
17113
- ...options?.factTypes?.length ? [import_watermelondb3.Q.where("fact_type", import_watermelondb3.Q.oneOf(options.factTypes))] : [],
17114
- import_watermelondb3.Q.sortBy(options?.since ? "updated_at" : "created_at", import_watermelondb3.Q.desc),
17115
- ...options?.limit !== null && options?.limit !== void 0 && options.limit > 0 ? [import_watermelondb3.Q.take(options.limit)] : []
17159
+ ...options?.folderId !== void 0 ? [import_watermelondb4.Q.where("folder_id", options.folderId)] : [],
17160
+ ...options?.factTypes?.length ? [import_watermelondb4.Q.where("fact_type", import_watermelondb4.Q.oneOf(options.factTypes))] : [],
17161
+ import_watermelondb4.Q.sortBy(options?.since ? "updated_at" : "created_at", import_watermelondb4.Q.desc),
17162
+ ...options?.limit !== null && options?.limit !== void 0 && options.limit > 0 ? [import_watermelondb4.Q.take(options.limit)] : []
17116
17163
  ];
17117
17164
  const results = await ctx.vaultMemoryCollection.query(...conditions).unsafeFetchRaw();
17118
17165
  return mapInBatches(
@@ -17150,6 +17197,11 @@ async function getVaultCandidateKeysOp(ctx, options) {
17150
17197
  });
17151
17198
  const clauses = [base.sql];
17152
17199
  const args = [...base.args];
17200
+ if (options?.memoryIds !== void 0) {
17201
+ if (options.memoryIds.length === 0) return [];
17202
+ clauses.push(`"id" in (${options.memoryIds.map(() => "?").join(",")})`);
17203
+ args.push(...options.memoryIds);
17204
+ }
17153
17205
  if (options?.scopes?.length) {
17154
17206
  clauses.push(`"scope" in (${options.scopes.map(() => "?").join(",")})`);
17155
17207
  args.push(...options.scopes);
@@ -17163,7 +17215,7 @@ async function getVaultCandidateKeysOp(ctx, options) {
17163
17215
  args.push(...options.factTypes);
17164
17216
  }
17165
17217
  const sql = `select "id", "scope", "folder_id", "embedding_model", "updated_at" from "memory_vault" where ${clauses.join(" and ")}`;
17166
- const rows = await ctx.vaultMemoryCollection.query(import_watermelondb3.Q.unsafeSqlQuery(sql, args)).unsafeFetchRaw();
17218
+ const rows = await ctx.vaultMemoryCollection.query(import_watermelondb4.Q.unsafeSqlQuery(sql, args)).unsafeFetchRaw();
17167
17219
  return rows.map(mapRaw);
17168
17220
  } catch (err) {
17169
17221
  getLogger().debug(
@@ -17171,11 +17223,12 @@ async function getVaultCandidateKeysOp(ctx, options) {
17171
17223
  );
17172
17224
  const conditions = [
17173
17225
  ...baseVaultConditions(ctx, {
17226
+ memoryIds: options?.memoryIds,
17174
17227
  ...options?.includeArchived !== void 0 && { includeArchived: options.includeArchived }
17175
17228
  }),
17176
- ...options?.scopes?.length ? [import_watermelondb3.Q.where("scope", import_watermelondb3.Q.oneOf(options.scopes))] : [],
17177
- ...options?.folderId !== void 0 ? [import_watermelondb3.Q.where("folder_id", options.folderId)] : [],
17178
- ...options?.factTypes?.length ? [import_watermelondb3.Q.where("fact_type", import_watermelondb3.Q.oneOf(options.factTypes))] : []
17229
+ ...options?.scopes?.length ? [import_watermelondb4.Q.where("scope", import_watermelondb4.Q.oneOf(options.scopes))] : [],
17230
+ ...options?.folderId !== void 0 ? [import_watermelondb4.Q.where("folder_id", options.folderId)] : [],
17231
+ ...options?.factTypes?.length ? [import_watermelondb4.Q.where("fact_type", import_watermelondb4.Q.oneOf(options.factTypes))] : []
17179
17232
  ];
17180
17233
  const rows = await ctx.vaultMemoryCollection.query(...conditions).unsafeFetchRaw();
17181
17234
  return rows.map(mapRaw);
@@ -17193,7 +17246,7 @@ async function getVaultEmbeddingsByIdsOp(ctx, ids, options) {
17193
17246
  ...options?.includeArchived !== void 0 && { includeArchived: options.includeArchived }
17194
17247
  });
17195
17248
  const sql = `select "id", "embedding", "embedding_model" from "memory_vault" where ${base.sql} and "id" in (${ids.map(() => "?").join(",")})`;
17196
- const rows = await ctx.vaultMemoryCollection.query(import_watermelondb3.Q.unsafeSqlQuery(sql, [...base.args, ...ids])).unsafeFetchRaw();
17249
+ const rows = await ctx.vaultMemoryCollection.query(import_watermelondb4.Q.unsafeSqlQuery(sql, [...base.args, ...ids])).unsafeFetchRaw();
17197
17250
  return rows.map(mapRaw);
17198
17251
  } catch (err) {
17199
17252
  getLogger().debug(
@@ -17205,7 +17258,7 @@ async function getVaultEmbeddingsByIdsOp(ctx, ids, options) {
17205
17258
  includeArchived: options.includeArchived
17206
17259
  }
17207
17260
  }),
17208
- import_watermelondb3.Q.where("id", import_watermelondb3.Q.oneOf(ids))
17261
+ import_watermelondb4.Q.where("id", import_watermelondb4.Q.oneOf(ids))
17209
17262
  ).unsafeFetchRaw();
17210
17263
  return rows.map(mapRaw);
17211
17264
  }
@@ -17216,7 +17269,7 @@ async function getVaultMemoriesByIdsOp(ctx, ids, options) {
17216
17269
  ...baseVaultConditions(ctx, {
17217
17270
  ...options?.includeArchived !== void 0 && { includeArchived: options.includeArchived }
17218
17271
  }),
17219
- import_watermelondb3.Q.where("id", import_watermelondb3.Q.oneOf(ids))
17272
+ import_watermelondb4.Q.where("id", import_watermelondb4.Q.oneOf(ids))
17220
17273
  ];
17221
17274
  const results = await ctx.vaultMemoryCollection.query(...conditions).unsafeFetchRaw();
17222
17275
  return mapInBatches(
@@ -17241,7 +17294,7 @@ async function countActiveVaultMemoriesOp(ctx) {
17241
17294
  }
17242
17295
  async function getActiveVaultMemoryIdsOp(ctx, ids) {
17243
17296
  if (ids.length === 0) return /* @__PURE__ */ new Set();
17244
- const rows = await ctx.vaultMemoryCollection.query(...baseVaultConditions(ctx), import_watermelondb3.Q.where("id", import_watermelondb3.Q.oneOf(ids))).unsafeFetchRaw();
17297
+ const rows = await ctx.vaultMemoryCollection.query(...baseVaultConditions(ctx), import_watermelondb4.Q.where("id", import_watermelondb4.Q.oneOf(ids))).unsafeFetchRaw();
17245
17298
  return new Set(rows.map((r) => r.id));
17246
17299
  }
17247
17300
  async function updateVaultMemoryOp(ctx, id, opts) {
@@ -17258,10 +17311,23 @@ async function updateVaultMemoryOp(ctx, id, opts) {
17258
17311
  const record = probe;
17259
17312
  const originalUpdatedAt = record.updatedAt.getTime();
17260
17313
  await ctx.database.write(async () => {
17314
+ if (ctx.canWrite && !await ctx.canWrite())
17315
+ throw new Error("Memory source is no longer eligible");
17261
17316
  if (record.isDeleted || record.supersededBy || !isOwnedByCtxUser(ctx, record)) {
17262
17317
  stale = true;
17263
17318
  return;
17264
17319
  }
17320
+ let observedSources = [];
17321
+ let replayedObservation = false;
17322
+ if (opts.observationSourceIds?.length) {
17323
+ try {
17324
+ const parsed = JSON.parse(record.sourceChunkIds ?? "[]");
17325
+ if (Array.isArray(parsed))
17326
+ observedSources = parsed.filter((id2) => typeof id2 === "string");
17327
+ } catch {
17328
+ }
17329
+ replayedObservation = opts.observationSourceIds.every((id2) => observedSources.includes(id2));
17330
+ }
17265
17331
  await record.update((r) => {
17266
17332
  r._setRaw("content", encryptedContent);
17267
17333
  if (opts.scope !== void 0) {
@@ -17275,9 +17341,15 @@ async function updateVaultMemoryOp(ctx, id, opts) {
17275
17341
  r._setRaw("embedding_model", opts.embeddingModel ?? null);
17276
17342
  }
17277
17343
  if (opts.sourceChunkIds !== void 0) {
17278
- r._setRaw("source_chunk_ids", JSON.stringify(opts.sourceChunkIds));
17344
+ r._setRaw(
17345
+ "source_chunk_ids",
17346
+ JSON.stringify(
17347
+ opts.observationSourceIds?.length ? [.../* @__PURE__ */ new Set([...observedSources, ...opts.sourceChunkIds])] : opts.sourceChunkIds
17348
+ )
17349
+ );
17279
17350
  }
17280
- if (opts.proofCountIncrement !== void 0) {
17351
+ if (replayedObservation) {
17352
+ } else if (opts.proofCountIncrement !== void 0) {
17281
17353
  const current = r.proofCount ?? 1;
17282
17354
  r._setRaw("proof_count", current + opts.proofCountIncrement);
17283
17355
  } else if (opts.proofCount !== void 0) {
@@ -17294,7 +17366,7 @@ async function updateVaultMemoryOp(ctx, id, opts) {
17294
17366
  if (opts.topicsUserManaged !== void 0) {
17295
17367
  r._setRaw("topics_user_managed", opts.topicsUserManaged);
17296
17368
  }
17297
- if (opts.lastObservedAt !== void 0) {
17369
+ if (opts.lastObservedAt !== void 0 && !replayedObservation) {
17298
17370
  r._setRaw("last_observed_at", opts.lastObservedAt);
17299
17371
  }
17300
17372
  if (opts.factType !== void 0) {
@@ -17420,6 +17492,8 @@ async function supersedeVaultMemoryOp(ctx, id, supersededById) {
17420
17492
  }
17421
17493
  let stale = false;
17422
17494
  await ctx.database.write(async () => {
17495
+ if (ctx.canWrite && !await ctx.canWrite())
17496
+ throw new Error("Memory source is no longer eligible");
17423
17497
  if (record.isDeleted || record.supersededBy || !isOwnedByCtxUser(ctx, record)) {
17424
17498
  stale = true;
17425
17499
  return;
@@ -17440,9 +17514,9 @@ async function supersedeVaultMemoryOp(ctx, id, supersededById) {
17440
17514
  }
17441
17515
  async function getUnfiledVaultMemoriesOp(ctx) {
17442
17516
  const conditions = [
17443
- import_watermelondb3.Q.where("folder_id", null),
17517
+ import_watermelondb4.Q.where("folder_id", null),
17444
17518
  ...baseVaultConditions(ctx),
17445
- import_watermelondb3.Q.sortBy("created_at", import_watermelondb3.Q.desc)
17519
+ import_watermelondb4.Q.sortBy("created_at", import_watermelondb4.Q.desc)
17446
17520
  ];
17447
17521
  const results = await ctx.vaultMemoryCollection.query(...conditions).fetch();
17448
17522
  return mapInBatches(
@@ -17456,7 +17530,7 @@ async function linkedEntityNamesByMemory(entityCtx, memoryIds) {
17456
17530
  const entityIdByMemory = /* @__PURE__ */ new Map();
17457
17531
  const allEntityIds = /* @__PURE__ */ new Set();
17458
17532
  for (let i = 0; i < memoryIds.length; i += CHUNK) {
17459
- const links = await entityCtx.memoryEntityCollection.query(import_watermelondb3.Q.where("memory_id", import_watermelondb3.Q.oneOf(memoryIds.slice(i, i + CHUNK)))).unsafeFetchRaw();
17533
+ const links = await entityCtx.memoryEntityCollection.query(import_watermelondb4.Q.where("memory_id", import_watermelondb4.Q.oneOf(memoryIds.slice(i, i + CHUNK)))).unsafeFetchRaw();
17460
17534
  for (const link of links) {
17461
17535
  const memoryId = String(link.memory_id);
17462
17536
  const entityId = String(link.entity_id);
@@ -17472,7 +17546,7 @@ async function linkedEntityNamesByMemory(entityCtx, memoryIds) {
17472
17546
  const entityIds = Array.from(allEntityIds);
17473
17547
  const nameById = /* @__PURE__ */ new Map();
17474
17548
  for (let i = 0; i < entityIds.length; i += CHUNK) {
17475
- const entities = await entityCtx.entityCollection.query(import_watermelondb3.Q.where("id", import_watermelondb3.Q.oneOf(entityIds.slice(i, i + CHUNK)))).unsafeFetchRaw();
17549
+ const entities = await entityCtx.entityCollection.query(import_watermelondb4.Q.where("id", import_watermelondb4.Q.oneOf(entityIds.slice(i, i + CHUNK)))).unsafeFetchRaw();
17476
17550
  for (const e of entities) {
17477
17551
  if (typeof e.canonical_name === "string") nameById.set(String(e.id), e.canonical_name);
17478
17552
  }
@@ -17501,7 +17575,7 @@ async function getMemoriesNeedingTopicExtractionOp(ctx, options) {
17501
17575
  if (!entityCtx) {
17502
17576
  throw new Error("getMemoriesNeedingTopicExtractionOp requires ctx.entityCtx");
17503
17577
  }
17504
- const conditions = [...baseVaultConditions(ctx), import_watermelondb3.Q.sortBy("created_at", import_watermelondb3.Q.desc)];
17578
+ const conditions = [...baseVaultConditions(ctx), import_watermelondb4.Q.sortBy("created_at", import_watermelondb4.Q.desc)];
17505
17579
  const rows = await ctx.vaultMemoryCollection.query(...conditions).unsafeFetchRaw();
17506
17580
  const linkedNames = await linkedEntityNamesByMemory(
17507
17581
  entityCtx,
@@ -17652,10 +17726,10 @@ async function backfillMemoryTopicsOp(ctx, memoryIds) {
17652
17726
  }
17653
17727
  if (record.isDeleted || !isOwnedByCtxUser(ctx, record)) continue;
17654
17728
  if (parseTopics(record.topics) !== null) continue;
17655
- const links = await entityCtx.memoryEntityCollection.query(import_watermelondb3.Q.where("memory_id", id)).unsafeFetchRaw();
17729
+ const links = await entityCtx.memoryEntityCollection.query(import_watermelondb4.Q.where("memory_id", id)).unsafeFetchRaw();
17656
17730
  const entityIds = links.map((l) => String(l.entity_id));
17657
17731
  if (entityIds.length === 0) continue;
17658
- const entities = await entityCtx.entityCollection.query(import_watermelondb3.Q.where("id", import_watermelondb3.Q.oneOf(entityIds))).fetch();
17732
+ const entities = await entityCtx.entityCollection.query(import_watermelondb4.Q.where("id", import_watermelondb4.Q.oneOf(entityIds))).fetch();
17659
17733
  if (entities.length === 0) continue;
17660
17734
  const source = record.topicsUserManaged ? "user" : "auto";
17661
17735
  const write = await resolveMemoryTopicsWrite(entityCtx, id, entities, [], source);
@@ -17671,7 +17745,7 @@ async function backfillMemoryTopicsOp(ctx, memoryIds) {
17671
17745
  }
17672
17746
  async function deleteAllVaultMemoriesForUserOp(ctx, userId) {
17673
17747
  if (ctx.userId !== void 0 && ctx.userId !== userId) return 0;
17674
- const records = await ctx.vaultMemoryCollection.query(import_watermelondb3.Q.where("user_id", userId), import_watermelondb3.Q.where("is_deleted", false)).fetch();
17748
+ const records = await ctx.vaultMemoryCollection.query(import_watermelondb4.Q.where("user_id", userId), import_watermelondb4.Q.where("is_deleted", false)).fetch();
17675
17749
  if (records.length === 0) return 0;
17676
17750
  await ctx.database.write(async () => {
17677
17751
  const prepared = records.map(
@@ -17712,6 +17786,7 @@ async function getDecayCandidatesRawOp(ctx) {
17712
17786
  eventTimeEnd: raw.event_time_end ?? null,
17713
17787
  eventTimeKind: raw.event_time_kind ?? null,
17714
17788
  updatedAt: raw.updated_at,
17789
+ lastObservedAt: raw.last_observed_at ?? null,
17715
17790
  archivedAt: raw.archived_at ?? null,
17716
17791
  source: raw.source ?? null,
17717
17792
  trustTier: raw.trust_tier ?? null
@@ -17728,7 +17803,7 @@ async function archiveVaultMemoryOp(ctx, id, opts) {
17728
17803
  stale = true;
17729
17804
  return;
17730
17805
  }
17731
- if (opts?.expectedUpdatedAt !== void 0 && record.updatedAt.getTime() !== opts.expectedUpdatedAt) {
17806
+ if (opts?.expectedUpdatedAt !== void 0 && record.updatedAt.getTime() !== opts.expectedUpdatedAt || opts?.expectedLastObservedAt !== void 0 && (record.lastObservedAt ?? null) !== opts.expectedLastObservedAt) {
17732
17807
  stale = true;
17733
17808
  return;
17734
17809
  }
@@ -20403,6 +20478,7 @@ async function prepareVaultCandidates(query, vaultCtx, embeddingOptions, cache,
20403
20478
  const scopes = searchOptions?.scopes;
20404
20479
  const folderId = searchOptions?.folderId;
20405
20480
  const queryOpts = {};
20481
+ if (searchOptions?.memoryIds !== void 0) queryOpts.memoryIds = searchOptions.memoryIds;
20406
20482
  if (scopes?.length) queryOpts.scopes = scopes;
20407
20483
  if (folderId !== void 0) queryOpts.folderId = folderId;
20408
20484
  if (searchOptions?.factTypes?.length) queryOpts.factTypes = searchOptions.factTypes;
@@ -20927,7 +21003,7 @@ function createMemoryVaultSearchTool(vaultCtx, embeddingOptions, cache, searchOp
20927
21003
  subQueries = decomp.subQueries;
20928
21004
  }
20929
21005
  }
20930
- const { recall: recall2 } = await import("./recall-HA4UX4BB.mjs");
21006
+ const { recall: recall2 } = await import("./recall-Z2WJGXOL.mjs");
20931
21007
  let recallDegraded = [];
20932
21008
  const result = await recall2(
20933
21009
  query,
@@ -21494,7 +21570,9 @@ function dedupeBy(items, ...keys) {
21494
21570
  return out;
21495
21571
  }
21496
21572
  async function recall(query, ctx, options = {}) {
21497
- const types = options.types ?? ["fact"];
21573
+ const requestedTypes = options.types ?? ["fact"];
21574
+ const chunksScopeRestricted = options.memoryIds !== void 0 && requestedTypes.includes("chunk");
21575
+ const types = options.memoryIds !== void 0 ? requestedTypes.filter((kind) => kind === "fact") : requestedTypes;
21498
21576
  const limit = options.limit ?? DEFAULT_LIMIT;
21499
21577
  const usedBudget = options.budget ?? DEFAULT_BUDGET;
21500
21578
  const flags = flagsForBudget(usedBudget);
@@ -21546,7 +21624,10 @@ async function recall(query, ctx, options = {}) {
21546
21624
  if (embeddingsUnavailable) degraded.push("embeddings-unavailable");
21547
21625
  if (graphLaneFailed) degraded.push("graph-lane-failed");
21548
21626
  if (temporalLaneFailed) degraded.push("temporal-lane-failed");
21549
- const laneRan = types.includes("fact") && !!ctx.vaultCtx && !!ctx.vaultCache || types.includes("chunk") && !!ctx.storageCtx;
21627
+ if (chunksScopeRestricted) degraded.push("chunks-scope-restricted");
21628
+ const laneRan = types.includes("fact") && !!ctx.vaultCtx && !!ctx.vaultCache || types.includes("chunk") && !!ctx.storageCtx || // The chunk lane was wired and deliberately dropped for the scope, which
21629
+ // is not the "requested kinds have no store" wiring bug `no-lanes` means.
21630
+ chunksScopeRestricted && !!ctx.storageCtx;
21550
21631
  const scores = admitted.map((m) => m.score);
21551
21632
  const minScoreApplied = factResults.length > 0 ? factFloor : chunkResults.length > 0 ? chunkFloor : factFloor >= 0 ? factFloor : chunkFloor;
21552
21633
  const diagnostics = {
@@ -21691,6 +21772,7 @@ async function recall(query, ctx, options = {}) {
21691
21772
  ...options.scopes && { scopes: options.scopes },
21692
21773
  ...options.folderId !== void 0 && { folderId: options.folderId },
21693
21774
  ...options.factTypes?.length && { factTypes: options.factTypes },
21775
+ ...options.memoryIds !== void 0 && { memoryIds: options.memoryIds },
21694
21776
  ...options.factTypeWeights && { factTypeWeights: options.factTypeWeights },
21695
21777
  ...entityRanking.length > 0 && { entityRanking },
21696
21778
  ...temporalRanking.length > 0 && { temporalRanking }
@@ -21945,6 +22027,7 @@ export {
21945
22027
  require_logError,
21946
22028
  require_Relation,
21947
22029
  require_watermelondb,
22030
+ ExtractionJob,
21948
22031
  EncryptionKeyMissingError,
21949
22032
  onClearAllEncryptionState,
21950
22033
  onKeyAvailable,
@@ -21993,6 +22076,7 @@ export {
21993
22076
  getConversationsByProjectOp,
21994
22077
  getMessagesOp,
21995
22078
  clearMessagesOp,
22079
+ deleteMessageOp,
21996
22080
  createMessageOp,
21997
22081
  upsertMessageOp,
21998
22082
  getMessageOp,