@anuma/sdk 2.4.2 → 2.6.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.
@@ -1871,6 +1871,7 @@ function isOwnedByCtxUser(ctx, record) {
1871
1871
  function baseVaultConditions(ctx, options) {
1872
1872
  return [
1873
1873
  ...options?.includeDeleted ? [] : [Q3.where("is_deleted", false)],
1874
+ ...options?.includeSuperseded ? [] : [Q3.where("superseded_by", null)],
1874
1875
  ...ctx.userId !== void 0 ? [Q3.where("user_id", ctx.userId)] : [],
1875
1876
  ...options?.since ? [Q3.where("updated_at", Q3.gt(options.since.getTime()))] : []
1876
1877
  ];
@@ -1911,6 +1912,9 @@ function vaultMemoryToStoredRaw(memory) {
1911
1912
  eventTimeKind: memory.eventTimeKind ?? null,
1912
1913
  topicsUserManaged: memory.topicsUserManaged ?? false,
1913
1914
  topicsExtractedAt: memory.topicsExtractedAt ?? null,
1915
+ topicsExtractedVersion: memory.topicsExtractedVersion ?? null,
1916
+ supersededBy: memory.supersededBy ?? null,
1917
+ supersededAt: memory.supersededAt ?? null,
1914
1918
  createdAt: memory.createdAt,
1915
1919
  updatedAt: memory.updatedAt,
1916
1920
  isDeleted: memory.isDeleted
@@ -1956,6 +1960,59 @@ async function createVaultMemoryOp(ctx, opts) {
1956
1960
  });
1957
1961
  return vaultMemoryToStored(created, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner);
1958
1962
  }
1963
+ async function createSupersedingMemoryOp(ctx, opts, targetId) {
1964
+ if (!targetId) return { created: null, retired: false };
1965
+ const scope = opts.scope ?? "private";
1966
+ const encryptedContent = ctx.walletAddress && ctx.signMessage ? await encryptVaultMemoryContent(
1967
+ opts.content,
1968
+ ctx.walletAddress,
1969
+ ctx.signMessage,
1970
+ ctx.embeddedWalletSigner
1971
+ ) : opts.content;
1972
+ let createdRecord = null;
1973
+ await ctx.database.write(async () => {
1974
+ let target;
1975
+ try {
1976
+ target = await ctx.vaultMemoryCollection.find(targetId);
1977
+ } catch {
1978
+ return;
1979
+ }
1980
+ if (target.isDeleted || target.supersededBy || !isOwnedByCtxUser(ctx, target)) return;
1981
+ createdRecord = await ctx.vaultMemoryCollection.create((record) => {
1982
+ record._setRaw("content", encryptedContent);
1983
+ record._setRaw("scope", scope);
1984
+ record._setRaw("folder_id", opts.folderId ?? null);
1985
+ record._setRaw("user_id", ctx.userId ?? null);
1986
+ record._setRaw("is_deleted", false);
1987
+ if (opts.embedding !== void 0) {
1988
+ record._setRaw("embedding", opts.embedding);
1989
+ record._setRaw("embedding_model", opts.embeddingModel ?? null);
1990
+ }
1991
+ if (opts.sourceChunkIds !== void 0) {
1992
+ record._setRaw("source_chunk_ids", JSON.stringify(opts.sourceChunkIds));
1993
+ }
1994
+ record._setRaw("proof_count", opts.proofCount ?? 1);
1995
+ record._setRaw("source", opts.source ?? "manual");
1996
+ if (opts.eventTime) {
1997
+ record._setRaw("event_time_start", opts.eventTime.start ?? null);
1998
+ record._setRaw("event_time_end", opts.eventTime.end ?? null);
1999
+ record._setRaw("event_time_kind", opts.eventTime.kind ?? null);
2000
+ }
2001
+ });
2002
+ await target.update((r) => {
2003
+ r._setRaw("superseded_by", createdRecord.id);
2004
+ r._setRaw("superseded_at", Date.now());
2005
+ });
2006
+ });
2007
+ if (!createdRecord) return { created: null, retired: false };
2008
+ const created = await vaultMemoryToStored(
2009
+ createdRecord,
2010
+ ctx.walletAddress,
2011
+ ctx.signMessage,
2012
+ ctx.embeddedWalletSigner
2013
+ );
2014
+ return { created, retired: true };
2015
+ }
1959
2016
  async function getMemoriesByEventTimeOp(ctx, windowStart, windowEnd) {
1960
2017
  const records = await ctx.vaultMemoryCollection.query(
1961
2018
  ...baseVaultConditions(ctx),
@@ -2095,6 +2152,9 @@ function vaultMemoryRawToStoredRaw(raw) {
2095
2152
  // SQLite stores booleans as 0/1, LokiJS as true/false — coerce both.
2096
2153
  topicsUserManaged: raw.topics_user_managed === true || raw.topics_user_managed === 1,
2097
2154
  topicsExtractedAt: raw.topics_extracted_at ?? null,
2155
+ topicsExtractedVersion: raw.topics_extracted_version ?? null,
2156
+ supersededBy: raw.superseded_by ?? null,
2157
+ supersededAt: raw.superseded_at ?? null,
2098
2158
  createdAt: new Date(raw.created_at),
2099
2159
  updatedAt: new Date(raw.updated_at),
2100
2160
  isDeleted: raw.is_deleted === true || raw.is_deleted === 1
@@ -2136,7 +2196,7 @@ async function getAllVaultMemoryContentsOp(ctx, options) {
2136
2196
  async function updateVaultMemoryOp(ctx, id, opts) {
2137
2197
  try {
2138
2198
  const probe = await ctx.vaultMemoryCollection.find(id);
2139
- if (probe.isDeleted || !isOwnedByCtxUser(ctx, probe)) return null;
2199
+ if (probe.isDeleted || probe.supersededBy || !isOwnedByCtxUser(ctx, probe)) return null;
2140
2200
  const encryptedContent = ctx.walletAddress && ctx.signMessage ? await encryptVaultMemoryContent(
2141
2201
  opts.content,
2142
2202
  ctx.walletAddress,
@@ -2147,7 +2207,7 @@ async function updateVaultMemoryOp(ctx, id, opts) {
2147
2207
  const record = probe;
2148
2208
  const originalUpdatedAt = record.updatedAt.getTime();
2149
2209
  await ctx.database.write(async () => {
2150
- if (record.isDeleted || !isOwnedByCtxUser(ctx, record)) {
2210
+ if (record.isDeleted || record.supersededBy || !isOwnedByCtxUser(ctx, record)) {
2151
2211
  stale = true;
2152
2212
  return;
2153
2213
  }
@@ -2225,6 +2285,40 @@ async function deleteVaultMemoryOp(ctx, id) {
2225
2285
  return false;
2226
2286
  }
2227
2287
  }
2288
+ async function supersedeVaultMemoryOp(ctx, id, supersededById) {
2289
+ if (id === supersededById) return false;
2290
+ try {
2291
+ const record = await ctx.vaultMemoryCollection.find(id);
2292
+ if (record.isDeleted || record.supersededBy || !isOwnedByCtxUser(ctx, record)) return false;
2293
+ let successor;
2294
+ try {
2295
+ successor = await ctx.vaultMemoryCollection.find(supersededById);
2296
+ } catch {
2297
+ return false;
2298
+ }
2299
+ if (successor.isDeleted || successor.supersededBy || !isOwnedByCtxUser(ctx, successor)) {
2300
+ return false;
2301
+ }
2302
+ let stale = false;
2303
+ await ctx.database.write(async () => {
2304
+ if (record.isDeleted || record.supersededBy || !isOwnedByCtxUser(ctx, record)) {
2305
+ stale = true;
2306
+ return;
2307
+ }
2308
+ if (successor.isDeleted || successor.supersededBy || !isOwnedByCtxUser(ctx, successor)) {
2309
+ stale = true;
2310
+ return;
2311
+ }
2312
+ await record.update((r) => {
2313
+ r._setRaw("superseded_by", supersededById);
2314
+ r._setRaw("superseded_at", Date.now());
2315
+ });
2316
+ });
2317
+ return !stale;
2318
+ } catch {
2319
+ return false;
2320
+ }
2321
+ }
2228
2322
  async function getUnfiledVaultMemoriesOp(ctx) {
2229
2323
  const conditions = [
2230
2324
  Q3.where("folder_id", null),
@@ -2237,6 +2331,7 @@ async function getUnfiledVaultMemoriesOp(ctx) {
2237
2331
  (record) => vaultMemoryToStored(record, ctx.walletAddress, ctx.signMessage, ctx.embeddedWalletSigner)
2238
2332
  );
2239
2333
  }
2334
+ var TOPICS_EXTRACTION_VERSION = 1;
2240
2335
  async function getMemoriesNeedingTopicExtractionOp(ctx, options) {
2241
2336
  const entityCtx = ctx.entityCtx;
2242
2337
  if (!entityCtx) {
@@ -2255,7 +2350,10 @@ async function getMemoriesNeedingTopicExtractionOp(ctx, options) {
2255
2350
  for (const raw of rows) {
2256
2351
  const stamp = raw.topics_extracted_at ?? null;
2257
2352
  if (stamp !== null) {
2258
- if (raw.updated_at > stamp) stampedPending.push(raw);
2353
+ const version = raw.topics_extracted_version ?? 0;
2354
+ if (raw.updated_at > stamp || version < TOPICS_EXTRACTION_VERSION) {
2355
+ stampedPending.push(raw);
2356
+ }
2259
2357
  } else {
2260
2358
  unstamped.push(raw);
2261
2359
  }
@@ -2285,7 +2383,7 @@ async function getMemoriesNeedingTopicExtractionOp(ctx, options) {
2285
2383
  );
2286
2384
  return { pending, linkedUnstamped };
2287
2385
  }
2288
- async function stampTopicsExtractedAtOp(ctx, memoryIds, extractedAt) {
2386
+ async function stampTopicsExtractedAtOp(ctx, memoryIds, extractedAt, version = TOPICS_EXTRACTION_VERSION) {
2289
2387
  if (memoryIds.length === 0) return [];
2290
2388
  const uniqueIds = Array.from(new Set(memoryIds));
2291
2389
  const CHUNK = 500;
@@ -2308,6 +2406,7 @@ async function stampTopicsExtractedAtOp(ctx, memoryIds, extractedAt) {
2308
2406
  prepared.push(
2309
2407
  record.prepareUpdate((r) => {
2310
2408
  r._setRaw("topics_extracted_at", extractedAt);
2409
+ r._setRaw("topics_extracted_version", version);
2311
2410
  r._setRaw("updated_at", originalUpdatedAt);
2312
2411
  })
2313
2412
  );
@@ -4950,7 +5049,7 @@ function createMemoryVaultSearchTool(vaultCtx, embeddingOptions, cache, searchOp
4950
5049
  legacy.map((r) => ({ id: r.uniqueId, content: r.content, score: r.similarity }))
4951
5050
  );
4952
5051
  }
4953
- const { recall: recall2 } = await import("./recall-HI7VO3VM.mjs");
5052
+ const { recall: recall2 } = await import("./recall-FQU3NUTL.mjs");
4954
5053
  const result = await recall2(
4955
5054
  query,
4956
5055
  { vaultCtx, embeddingOptions, vaultCache: cache },
@@ -5636,13 +5735,16 @@ export {
5636
5735
  replaceMemoryEntitiesGuardedOp,
5637
5736
  vaultMemoryToStored,
5638
5737
  createVaultMemoryOp,
5738
+ createSupersedingMemoryOp,
5639
5739
  createVaultMemoriesBatchOp,
5640
5740
  getVaultMemoryOp,
5641
5741
  getAllVaultMemoriesOp,
5642
5742
  getAllVaultMemoryContentsOp,
5643
5743
  updateVaultMemoryOp,
5644
5744
  deleteVaultMemoryOp,
5745
+ supersedeVaultMemoryOp,
5645
5746
  getUnfiledVaultMemoriesOp,
5747
+ TOPICS_EXTRACTION_VERSION,
5646
5748
  getMemoriesNeedingTopicExtractionOp,
5647
5749
  stampTopicsExtractedAtOp,
5648
5750
  deleteAllVaultMemoriesForUserOp,
@@ -15,10 +15,11 @@ var SYSTEM_PROMPT = `You consolidate a new memory against existing memories from
15
15
 
16
16
  A "memory" is a self-contained natural-language fact about the user. Multiple memories about the same EXACT FACET (the same dimension of the same subject) should never coexist \u2014 they should be merged into one. Different facets on the same subject (e.g. user's dog's name vs user's dog's age) are SEPARATE memories.
17
17
 
18
- Decide one of three actions:
18
+ Decide one of four actions:
19
19
 
20
20
  - "create": the new memory describes a distinct fact not covered by any existing memory. Write it as new.
21
- - "update": the new memory describes the SAME FACET as exactly one existing memory. Either it adds detail, corrects a value, or rephrases the same fact. Return targetId of that existing memory + the consolidated content (richest version of the two).
21
+ - "update": the new memory describes the SAME FACET as exactly one existing memory and is COMPATIBLE with it \u2014 it adds detail, fixes an incomplete value, or rephrases the same still-true fact. Return targetId of that existing memory + the consolidated content (richest version of the two).
22
+ - "supersede": the new memory REPLACES a standing fact whose value has CHANGED and is now INCOMPATIBLE with an existing memory \u2014 the old fact was true before but is false now (a state change). Return targetId of the STALE existing memory to retire + content = the NEW fact. The old memory is kept as history, not overwritten or deleted; do not re-state it.
22
23
  - "noop": the new memory is already fully captured by an existing memory \u2014 same facet, no new information. Skip the write.
23
24
 
24
25
  RULES (carry these strictly):
@@ -26,18 +27,21 @@ RULES (carry these strictly):
26
27
  1. ONE OBSERVATION PER DISTINCT FACET. If the new memory is about "user's aunt's twins" and an existing memory is also about "user's aunt's twins", they are the same facet \u2192 update, never create.
27
28
  2. MATCH BY FACET, NOT TOPIC. Two memories both mentioning "Zara" is not enough to merge \u2014 only merge if they describe the same property (e.g. both about "user's pending Zara boot exchange"). Two memories about Zara on different topics (e.g. "user shops at Zara" + "user returned a sweater to Zara last week") are separate facets.
28
29
  3. NO COMPUTATION. Do not sum counts, decrement quantities, or derive new facts from existing ones. If the new memory says "user spent $200 today" and an existing memory says "user spent $150 yesterday", these are TWO SEPARATE EVENTS \u2014 create.
29
- 4. Events with different occurredAt dates are different memories even if the same activity ("user went to gym Monday" vs "user went to gym Friday" \u2014 separate events).
30
- 5. When in doubt between create and update, choose create. Over-merging loses information; under-merging is recoverable.
30
+ 4. EVENTS vs STANDING STATE.
31
+ - Distinct EVENTS (episodic \u2014 something that happened on a date) are separate memories, even if the same activity: "user went to gym Monday" vs "user went to gym Friday" \u2192 create; keep both.
32
+ - A STANDING ATTRIBUTE (an ongoing state: where the user lives/works, relationship status, current role) has ONE current value. When the new memory changes that value ("Lives in Portland" \u2192 "Lives in San Francisco"; "Works at Google" \u2192 "Works at Riverbend"; "Engaged" \u2192 "Broke up"), the old value is no longer true \u2192 supersede (retire the old, record the new). Do NOT create (that leaves a stale contradiction) and do NOT update (that erases the history that the old value was once true).
33
+ 5. When in doubt between create and update, choose create \u2014 EXCEPT when the new memory directly contradicts the current value of a standing attribute in an existing memory; then choose supersede. Over-merging loses information; a live contradiction is worse than either.
31
34
 
32
35
  OUTPUT \u2014 strict JSON, no prose:
33
36
  {
34
- "action": "create" | "update" | "noop",
35
- "targetId": "<existing memory id, required for update/noop, omit for create>",
36
- "content": "<consolidated content, required for create/update, omit for noop>"
37
+ "action": "create" | "update" | "supersede" | "noop",
38
+ "targetId": "<existing memory id \u2014 required for update/supersede/noop, omit for create>",
39
+ "content": "<content \u2014 required for create/update/supersede, omit for noop>"
37
40
  }
38
41
 
39
42
  For "create": content is the new memory verbatim (or a slight refinement).
40
43
  For "update": content is the merged richest-version, \u226480 words.
44
+ For "supersede": content is the NEW fact only (\u226480 words); targetId is the stale memory being retired.
41
45
  For "noop": no content (existing memory is already correct).`;
42
46
  async function consolidateMemory(newContent, candidates, options) {
43
47
  const fallback = {
@@ -112,7 +116,9 @@ function validate(parsed, newContent, validIds) {
112
116
  if (typeof parsed !== "object" || parsed === null) return null;
113
117
  const obj = parsed;
114
118
  const action = obj.action;
115
- if (action !== "create" && action !== "update" && action !== "noop") return null;
119
+ if (action !== "create" && action !== "update" && action !== "noop" && action !== "supersede") {
120
+ return null;
121
+ }
116
122
  if (action === "create") {
117
123
  const c2 = typeof obj.content === "string" ? obj.content.trim() : "";
118
124
  return { action: "create", content: c2.length > 0 ? c2 : newContent };
@@ -124,7 +130,7 @@ function validate(parsed, newContent, validIds) {
124
130
  }
125
131
  const c = typeof obj.content === "string" ? obj.content.trim() : "";
126
132
  if (c.length === 0) return null;
127
- return { action: "update", targetId, content: c };
133
+ return { action, targetId, content: c };
128
134
  }
129
135
  export {
130
136
  consolidateMemory