engine7 7.1.152 → 7.1.153

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.
@@ -1316,6 +1316,8 @@ __export(tokenizer_exports, {
1316
1316
  DEFAULT_STOPWORDS: () => DEFAULT_STOPWORDS,
1317
1317
  MIN_TOKEN_LENGTH: () => MIN_TOKEN_LENGTH,
1318
1318
  cjkBigrams: () => cjkBigrams,
1319
+ literalQueryNeedles: () => literalQueryNeedles,
1320
+ queryBigramNeedles: () => queryBigramNeedles,
1319
1321
  tokenize: () => tokenize,
1320
1322
  tokenizeCjk: () => tokenizeCjk,
1321
1323
  tokenizeToField: () => tokenizeToField
@@ -1350,7 +1352,22 @@ function cjkBigrams(text2) {
1350
1352
  function tokenizeCjk(text2) {
1351
1353
  return [...tokenize(text2), ...cjkBigrams(text2)];
1352
1354
  }
1353
- var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
1355
+ function invisibleCjkNeedles(candidates) {
1356
+ return [...new Set(candidates.map((token) => token.trim()))].filter((token) => /^[\u4e00-\u9fff]{2,}$/.test(token) && tokenize(token).length === 0).slice(0, 8);
1357
+ }
1358
+ function literalQueryNeedles(text2) {
1359
+ const chars = shortCjkCharCount(text2);
1360
+ if (!chars || chars > 6) return null;
1361
+ const names = invisibleCjkNeedles(engine().cut(String(text2 ?? ""), true));
1362
+ return names.length ? names : queryBigramNeedles(text2);
1363
+ }
1364
+ function queryBigramNeedles(text2) {
1365
+ const chars = shortCjkCharCount(text2);
1366
+ if (!chars || chars > 6) return null;
1367
+ const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
1368
+ return grams.length ? grams : null;
1369
+ }
1370
+ var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba, shortCjkCharCount;
1354
1371
  var init_tokenizer = __esm({
1355
1372
  "src/mem7/core/tokenizer.ts"() {
1356
1373
  "use strict";
@@ -1423,6 +1440,7 @@ var init_tokenizer = __esm({
1423
1440
  ]);
1424
1441
  MIN_TOKEN_LENGTH = 2;
1425
1442
  jieba = null;
1443
+ shortCjkCharCount = (text2) => (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
1426
1444
  }
1427
1445
  });
1428
1446
 
@@ -3247,12 +3265,6 @@ function loadArrow() {
3247
3265
  }
3248
3266
  return arrowPromise;
3249
3267
  }
3250
- function shortCjkQueryBigrams(text2) {
3251
- const chars = (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
3252
- if (!chars || chars > 6) return null;
3253
- const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
3254
- return grams.length ? grams : null;
3255
- }
3256
3268
  function buildSchemas(arrow) {
3257
3269
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
3258
3270
  const commonFields = () => [
@@ -3985,24 +3997,43 @@ var init_vector_store = __esm({
3985
3997
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
3986
3998
  }
3987
3999
  }
3988
- const grams = shortCjkQueryBigrams(queryText);
3989
- if (grams) {
4000
+ const textCols = BM25_TEXT_FIELDS[kind];
4001
+ const scan = async (terms, op, limit) => {
4002
+ const expr = op === "AND" ? terms.map((g) => `(${textCols.map((col) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" AND ") : textCols.map((col) => `(${terms.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
4003
+ const where2 = compileFilter(opts.filter);
4004
+ return await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(limit).toArray();
4005
+ };
4006
+ const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
4007
+ const scoreLiteral = (needles2, rows) => {
4008
+ const terms = [.../* @__PURE__ */ new Set([...needles2, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
4009
+ const occurrences2 = (text2, term) => text2.split(term).length - 1;
4010
+ for (const r of rows) {
4011
+ const rid = String(r.id ?? "");
4012
+ if (!rid) continue;
4013
+ const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
4014
+ const matched = terms.filter((term) => text2.includes(term));
4015
+ if (!matched.length || matched.every((term) => !needles2.includes(term))) continue;
4016
+ const full = matched.length === terms.length;
4017
+ const density = matched.reduce((sum, term) => sum + occurrences2(text2, term), 0) / Math.max(text2.length, 1) * 1e3;
4018
+ const score = full ? maxScore + 1 + Math.min(0.99, density / 10) : maxScore > 0 ? maxScore * (0.5 + 0.5 * matched.length / terms.length) : matched.length / terms.length;
4019
+ const cur = best.get(rid);
4020
+ if (cur) {
4021
+ if (full) cur._score = Math.max(Number(cur._score ?? 0), score);
4022
+ } else best.set(rid, { ...r, _score: score });
4023
+ }
4024
+ };
4025
+ const needles = literalQueryNeedles(queryText);
4026
+ if (needles) {
3990
4027
  try {
3991
- const textCols = BM25_TEXT_FIELDS[kind];
3992
- const expr = textCols.map((col) => `(${grams.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
3993
- const where2 = compileFilter(opts.filter);
3994
- const extra = await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(topK * 3).toArray();
3995
- const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
3996
- for (const r of extra) {
3997
- const rid = String(r.id ?? "");
3998
- if (!rid) continue;
3999
- const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
4000
- const matched = grams.filter((gram) => text2.includes(gram)).length;
4001
- if (!matched) continue;
4002
- const score = maxScore + matched / grams.length;
4003
- const cur = best.get(rid);
4004
- if (cur) cur._score = Math.max(Number(cur._score ?? 0), score);
4005
- else best.set(rid, { ...r, _score: score });
4028
+ const terms = [.../* @__PURE__ */ new Set([...needles, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
4029
+ const [all, any] = await Promise.all([
4030
+ terms.length > 1 ? scan(terms, "AND", topK * 10) : Promise.resolve([]),
4031
+ scan(needles, "OR", topK * 3)
4032
+ ]);
4033
+ scoreLiteral(needles, [...all, ...any]);
4034
+ if (![...best.values()].some((r) => Number(r._score ?? 0) > maxScore)) {
4035
+ const bigrams = [...new Set(needles.flatMap((name) => queryBigramNeedles(name) ?? []))].slice(0, 8);
4036
+ if (bigrams.length && JSON.stringify(bigrams) !== JSON.stringify(needles)) scoreLiteral(bigrams, await scan(bigrams, "OR", topK * 3));
4006
4037
  }
4007
4038
  } catch {
4008
4039
  }
@@ -16698,7 +16729,8 @@ function buildMemoryContext(store, scope, request, clock = () => (/* @__PURE__ *
16698
16729
  if (!resolved.has(id)) resolved.set(id, store.entities.resolve(scope, id, snapshot.entityRevision, cutoff ?? void 0));
16699
16730
  return resolved.get(id);
16700
16731
  };
16701
- const resolvedSelection = new Set((request.entityRef || matching.length ? matching : entities).map((entity) => resolve26(entity.entityId)?.entityId));
16732
+ const pool = request.entityRef || matching.length ? matching : request.matchedEntitiesOnly ? [] : entities;
16733
+ const resolvedSelection = new Set(pool.map((entity) => resolve26(entity.entityId)?.entityId));
16702
16734
  const selected = new Set(entities.filter((entity) => resolvedSelection.has(resolve26(entity.entityId)?.entityId)).map((entity) => entity.entityId));
16703
16735
  const context = {
16704
16736
  validAt,
@@ -35357,6 +35389,7 @@ var init_validate_import_live = __esm({
35357
35389
  var topics_chunks_exports = {};
35358
35390
  __export(topics_chunks_exports, {
35359
35391
  TOPICS_CHUNK_SESSION: () => TOPICS_CHUNK_SESSION,
35392
+ chunkTimestamp: () => chunkTimestamp,
35360
35393
  chunkTopicsText: () => chunkTopicsText,
35361
35394
  importTopicChunks: () => importTopicChunks
35362
35395
  });
@@ -35419,6 +35452,10 @@ function walk(root) {
35419
35452
  visit(root);
35420
35453
  return out.sort();
35421
35454
  }
35455
+ function chunkTimestamp(meta) {
35456
+ const ms = Date.parse(String(meta.date ?? ""));
35457
+ return new Date(Number.isFinite(ms) ? ms : Date.now());
35458
+ }
35422
35459
  async function importTopicChunks(options) {
35423
35460
  const { stateDir: stateDir2, topicsDir, userId, embed } = options;
35424
35461
  const manifestPath = join50(stateDir2, "mem7", "topics-chunks.json");
@@ -35477,7 +35514,7 @@ async function importTopicChunks(options) {
35477
35514
  appId: options.appId ?? "default",
35478
35515
  projectId: options.projectId ?? "default",
35479
35516
  sessionId: TOPICS_CHUNK_SESSION,
35480
- timestamp: new Date(parsed.meta.date || Date.now()),
35517
+ timestamp: chunkTimestamp(parsed.meta),
35481
35518
  parentId,
35482
35519
  text: chunk.text,
35483
35520
  subject: title,
@@ -35498,7 +35535,7 @@ async function importTopicChunks(options) {
35498
35535
  report.errors.push(`${rel}: ${error instanceof Error ? error.message : String(error)}`);
35499
35536
  }
35500
35537
  }
35501
- for (const rel of Object.keys(manifest)) {
35538
+ if (options.prune !== false) for (const rel of Object.keys(manifest)) {
35502
35539
  if (seen.has(rel)) continue;
35503
35540
  try {
35504
35541
  await table.delete(`parent_id = '${sqlLiteral2(`topic_chunk:${rel}`)}'`);
package/dist/cli.mjs CHANGED
@@ -5357,6 +5357,8 @@ __export(tokenizer_exports, {
5357
5357
  DEFAULT_STOPWORDS: () => DEFAULT_STOPWORDS,
5358
5358
  MIN_TOKEN_LENGTH: () => MIN_TOKEN_LENGTH,
5359
5359
  cjkBigrams: () => cjkBigrams,
5360
+ literalQueryNeedles: () => literalQueryNeedles,
5361
+ queryBigramNeedles: () => queryBigramNeedles,
5360
5362
  tokenize: () => tokenize,
5361
5363
  tokenizeCjk: () => tokenizeCjk,
5362
5364
  tokenizeToField: () => tokenizeToField
@@ -5391,7 +5393,22 @@ function cjkBigrams(text4) {
5391
5393
  function tokenizeCjk(text4) {
5392
5394
  return [...tokenize(text4), ...cjkBigrams(text4)];
5393
5395
  }
5394
- var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
5396
+ function invisibleCjkNeedles(candidates2) {
5397
+ return [...new Set(candidates2.map((token) => token.trim()))].filter((token) => /^[\u4e00-\u9fff]{2,}$/.test(token) && tokenize(token).length === 0).slice(0, 8);
5398
+ }
5399
+ function literalQueryNeedles(text4) {
5400
+ const chars = shortCjkCharCount(text4);
5401
+ if (!chars || chars > 6) return null;
5402
+ const names = invisibleCjkNeedles(engine().cut(String(text4 ?? ""), true));
5403
+ return names.length ? names : queryBigramNeedles(text4);
5404
+ }
5405
+ function queryBigramNeedles(text4) {
5406
+ const chars = shortCjkCharCount(text4);
5407
+ if (!chars || chars > 6) return null;
5408
+ const grams = [...new Set(cjkBigrams(text4))].slice(0, 8);
5409
+ return grams.length ? grams : null;
5410
+ }
5411
+ var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba, shortCjkCharCount;
5395
5412
  var init_tokenizer = __esm({
5396
5413
  "src/mem7/core/tokenizer.ts"() {
5397
5414
  "use strict";
@@ -5464,6 +5481,7 @@ var init_tokenizer = __esm({
5464
5481
  ]);
5465
5482
  MIN_TOKEN_LENGTH = 2;
5466
5483
  jieba = null;
5484
+ shortCjkCharCount = (text4) => (String(text4 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
5467
5485
  }
5468
5486
  });
5469
5487
 
@@ -5832,12 +5850,6 @@ function loadArrow() {
5832
5850
  }
5833
5851
  return arrowPromise;
5834
5852
  }
5835
- function shortCjkQueryBigrams(text4) {
5836
- const chars = (String(text4 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
5837
- if (!chars || chars > 6) return null;
5838
- const grams = [...new Set(cjkBigrams(text4))].slice(0, 8);
5839
- return grams.length ? grams : null;
5840
- }
5841
5853
  function buildSchemas(arrow) {
5842
5854
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
5843
5855
  const commonFields = () => [
@@ -6570,24 +6582,43 @@ var init_vector_store = __esm({
6570
6582
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
6571
6583
  }
6572
6584
  }
6573
- const grams = shortCjkQueryBigrams(queryText);
6574
- if (grams) {
6585
+ const textCols = BM25_TEXT_FIELDS[kind];
6586
+ const scan = async (terms, op, limit) => {
6587
+ const expr = op === "AND" ? terms.map((g) => `(${textCols.map((col) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" AND ") : textCols.map((col) => `(${terms.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
6588
+ const where2 = compileFilter(opts.filter);
6589
+ return await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(limit).toArray();
6590
+ };
6591
+ const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
6592
+ const scoreLiteral = (needles2, rows) => {
6593
+ const terms = [.../* @__PURE__ */ new Set([...needles2, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
6594
+ const occurrences2 = (text4, term) => text4.split(term).length - 1;
6595
+ for (const r of rows) {
6596
+ const rid = String(r.id ?? "");
6597
+ if (!rid) continue;
6598
+ const text4 = textCols.map((col) => String(r[col] ?? "")).join(" ");
6599
+ const matched = terms.filter((term) => text4.includes(term));
6600
+ if (!matched.length || matched.every((term) => !needles2.includes(term))) continue;
6601
+ const full = matched.length === terms.length;
6602
+ const density = matched.reduce((sum, term) => sum + occurrences2(text4, term), 0) / Math.max(text4.length, 1) * 1e3;
6603
+ const score = full ? maxScore + 1 + Math.min(0.99, density / 10) : maxScore > 0 ? maxScore * (0.5 + 0.5 * matched.length / terms.length) : matched.length / terms.length;
6604
+ const cur = best.get(rid);
6605
+ if (cur) {
6606
+ if (full) cur._score = Math.max(Number(cur._score ?? 0), score);
6607
+ } else best.set(rid, { ...r, _score: score });
6608
+ }
6609
+ };
6610
+ const needles = literalQueryNeedles(queryText);
6611
+ if (needles) {
6575
6612
  try {
6576
- const textCols = BM25_TEXT_FIELDS[kind];
6577
- const expr = textCols.map((col) => `(${grams.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
6578
- const where2 = compileFilter(opts.filter);
6579
- const extra = await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(topK * 3).toArray();
6580
- const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
6581
- for (const r of extra) {
6582
- const rid = String(r.id ?? "");
6583
- if (!rid) continue;
6584
- const text4 = textCols.map((col) => String(r[col] ?? "")).join(" ");
6585
- const matched = grams.filter((gram) => text4.includes(gram)).length;
6586
- if (!matched) continue;
6587
- const score = maxScore + matched / grams.length;
6588
- const cur = best.get(rid);
6589
- if (cur) cur._score = Math.max(Number(cur._score ?? 0), score);
6590
- else best.set(rid, { ...r, _score: score });
6613
+ const terms = [.../* @__PURE__ */ new Set([...needles, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
6614
+ const [all, any] = await Promise.all([
6615
+ terms.length > 1 ? scan(terms, "AND", topK * 10) : Promise.resolve([]),
6616
+ scan(needles, "OR", topK * 3)
6617
+ ]);
6618
+ scoreLiteral(needles, [...all, ...any]);
6619
+ if (![...best.values()].some((r) => Number(r._score ?? 0) > maxScore)) {
6620
+ const bigrams = [...new Set(needles.flatMap((name) => queryBigramNeedles(name) ?? []))].slice(0, 8);
6621
+ if (bigrams.length && JSON.stringify(bigrams) !== JSON.stringify(needles)) scoreLiteral(bigrams, await scan(bigrams, "OR", topK * 3));
6591
6622
  }
6592
6623
  } catch {
6593
6624
  }
@@ -36448,7 +36479,8 @@ function buildMemoryContext(store, scope, request2, clock = () => (/* @__PURE__
36448
36479
  if (!resolved.has(id2)) resolved.set(id2, store.entities.resolve(scope, id2, snapshot.entityRevision, cutoff ?? void 0));
36449
36480
  return resolved.get(id2);
36450
36481
  };
36451
- const resolvedSelection = new Set((request2.entityRef || matching.length ? matching : entities).map((entity) => resolve53(entity.entityId)?.entityId));
36482
+ const pool = request2.entityRef || matching.length ? matching : request2.matchedEntitiesOnly ? [] : entities;
36483
+ const resolvedSelection = new Set(pool.map((entity) => resolve53(entity.entityId)?.entityId));
36452
36484
  const selected = new Set(entities.filter((entity) => resolvedSelection.has(resolve53(entity.entityId)?.entityId)).map((entity) => entity.entityId));
36453
36485
  const context2 = {
36454
36486
  validAt,
@@ -63322,7 +63354,8 @@ async function mem7Search(binding, args, options = {}) {
63322
63354
  entityRef: args.entity_ref,
63323
63355
  maxTokens: args.max_tokens,
63324
63356
  sessionId: args.session_id,
63325
- includeRelationships: false
63357
+ includeRelationships: false,
63358
+ matchedEntitiesOnly: true
63326
63359
  };
63327
63360
  const fresh = service.store.readTransaction(() => JSON.parse(searchResponse(
63328
63361
  service,
@@ -63352,7 +63385,8 @@ async function searchBoundMemory(binding, args, options) {
63352
63385
  entityRef: args.entity_ref,
63353
63386
  maxTokens: args.max_tokens,
63354
63387
  sessionId: args.session_id,
63355
- includeRelationships: false
63388
+ includeRelationships: false,
63389
+ matchedEntitiesOnly: true
63356
63390
  };
63357
63391
  validateMemoryContextRequest(service.store, service.scope, request2);
63358
63392
  recordSearchTiming("validate", validationStarted);
@@ -5903,6 +5903,8 @@ __export(tokenizer_exports, {
5903
5903
  DEFAULT_STOPWORDS: () => DEFAULT_STOPWORDS,
5904
5904
  MIN_TOKEN_LENGTH: () => MIN_TOKEN_LENGTH,
5905
5905
  cjkBigrams: () => cjkBigrams,
5906
+ literalQueryNeedles: () => literalQueryNeedles,
5907
+ queryBigramNeedles: () => queryBigramNeedles,
5906
5908
  tokenize: () => tokenize,
5907
5909
  tokenizeCjk: () => tokenizeCjk,
5908
5910
  tokenizeToField: () => tokenizeToField
@@ -5937,7 +5939,22 @@ function cjkBigrams(text5) {
5937
5939
  function tokenizeCjk(text5) {
5938
5940
  return [...tokenize(text5), ...cjkBigrams(text5)];
5939
5941
  }
5940
- var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
5942
+ function invisibleCjkNeedles(candidates2) {
5943
+ return [...new Set(candidates2.map((token) => token.trim()))].filter((token) => /^[\u4e00-\u9fff]{2,}$/.test(token) && tokenize(token).length === 0).slice(0, 8);
5944
+ }
5945
+ function literalQueryNeedles(text5) {
5946
+ const chars = shortCjkCharCount(text5);
5947
+ if (!chars || chars > 6) return null;
5948
+ const names = invisibleCjkNeedles(engine().cut(String(text5 ?? ""), true));
5949
+ return names.length ? names : queryBigramNeedles(text5);
5950
+ }
5951
+ function queryBigramNeedles(text5) {
5952
+ const chars = shortCjkCharCount(text5);
5953
+ if (!chars || chars > 6) return null;
5954
+ const grams = [...new Set(cjkBigrams(text5))].slice(0, 8);
5955
+ return grams.length ? grams : null;
5956
+ }
5957
+ var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba, shortCjkCharCount;
5941
5958
  var init_tokenizer = __esm({
5942
5959
  "src/mem7/core/tokenizer.ts"() {
5943
5960
  "use strict";
@@ -6010,6 +6027,7 @@ var init_tokenizer = __esm({
6010
6027
  ]);
6011
6028
  MIN_TOKEN_LENGTH = 2;
6012
6029
  jieba = null;
6030
+ shortCjkCharCount = (text5) => (String(text5 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
6013
6031
  }
6014
6032
  });
6015
6033
 
@@ -6389,12 +6407,6 @@ function loadArrow() {
6389
6407
  }
6390
6408
  return arrowPromise;
6391
6409
  }
6392
- function shortCjkQueryBigrams(text5) {
6393
- const chars = (String(text5 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
6394
- if (!chars || chars > 6) return null;
6395
- const grams = [...new Set(cjkBigrams(text5))].slice(0, 8);
6396
- return grams.length ? grams : null;
6397
- }
6398
6410
  function buildSchemas(arrow) {
6399
6411
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
6400
6412
  const commonFields = () => [
@@ -7127,24 +7139,43 @@ var init_vector_store = __esm({
7127
7139
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
7128
7140
  }
7129
7141
  }
7130
- const grams = shortCjkQueryBigrams(queryText);
7131
- if (grams) {
7142
+ const textCols = BM25_TEXT_FIELDS[kind];
7143
+ const scan = async (terms, op, limit) => {
7144
+ const expr = op === "AND" ? terms.map((g) => `(${textCols.map((col) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" AND ") : textCols.map((col) => `(${terms.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
7145
+ const where2 = compileFilter(opts.filter);
7146
+ return await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(limit).toArray();
7147
+ };
7148
+ const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
7149
+ const scoreLiteral = (needles2, rows) => {
7150
+ const terms = [.../* @__PURE__ */ new Set([...needles2, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
7151
+ const occurrences2 = (text5, term) => text5.split(term).length - 1;
7152
+ for (const r of rows) {
7153
+ const rid = String(r.id ?? "");
7154
+ if (!rid) continue;
7155
+ const text5 = textCols.map((col) => String(r[col] ?? "")).join(" ");
7156
+ const matched = terms.filter((term) => text5.includes(term));
7157
+ if (!matched.length || matched.every((term) => !needles2.includes(term))) continue;
7158
+ const full = matched.length === terms.length;
7159
+ const density = matched.reduce((sum, term) => sum + occurrences2(text5, term), 0) / Math.max(text5.length, 1) * 1e3;
7160
+ const score = full ? maxScore + 1 + Math.min(0.99, density / 10) : maxScore > 0 ? maxScore * (0.5 + 0.5 * matched.length / terms.length) : matched.length / terms.length;
7161
+ const cur = best.get(rid);
7162
+ if (cur) {
7163
+ if (full) cur._score = Math.max(Number(cur._score ?? 0), score);
7164
+ } else best.set(rid, { ...r, _score: score });
7165
+ }
7166
+ };
7167
+ const needles = literalQueryNeedles(queryText);
7168
+ if (needles) {
7132
7169
  try {
7133
- const textCols = BM25_TEXT_FIELDS[kind];
7134
- const expr = textCols.map((col) => `(${grams.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
7135
- const where2 = compileFilter(opts.filter);
7136
- const extra = await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(topK * 3).toArray();
7137
- const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
7138
- for (const r of extra) {
7139
- const rid = String(r.id ?? "");
7140
- if (!rid) continue;
7141
- const text5 = textCols.map((col) => String(r[col] ?? "")).join(" ");
7142
- const matched = grams.filter((gram) => text5.includes(gram)).length;
7143
- if (!matched) continue;
7144
- const score = maxScore + matched / grams.length;
7145
- const cur = best.get(rid);
7146
- if (cur) cur._score = Math.max(Number(cur._score ?? 0), score);
7147
- else best.set(rid, { ...r, _score: score });
7170
+ const terms = [.../* @__PURE__ */ new Set([...needles, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
7171
+ const [all, any] = await Promise.all([
7172
+ terms.length > 1 ? scan(terms, "AND", topK * 10) : Promise.resolve([]),
7173
+ scan(needles, "OR", topK * 3)
7174
+ ]);
7175
+ scoreLiteral(needles, [...all, ...any]);
7176
+ if (![...best.values()].some((r) => Number(r._score ?? 0) > maxScore)) {
7177
+ const bigrams = [...new Set(needles.flatMap((name) => queryBigramNeedles(name) ?? []))].slice(0, 8);
7178
+ if (bigrams.length && JSON.stringify(bigrams) !== JSON.stringify(needles)) scoreLiteral(bigrams, await scan(bigrams, "OR", topK * 3));
7148
7179
  }
7149
7180
  } catch {
7150
7181
  }
@@ -38503,7 +38534,8 @@ function buildMemoryContext(store2, scope, request3, clock = () => (/* @__PURE__
38503
38534
  if (!resolved.has(id3)) resolved.set(id3, store2.entities.resolve(scope, id3, snapshot.entityRevision, cutoff ?? void 0));
38504
38535
  return resolved.get(id3);
38505
38536
  };
38506
- const resolvedSelection = new Set((request3.entityRef || matching.length ? matching : entities).map((entity) => resolve47(entity.entityId)?.entityId));
38537
+ const pool = request3.entityRef || matching.length ? matching : request3.matchedEntitiesOnly ? [] : entities;
38538
+ const resolvedSelection = new Set(pool.map((entity) => resolve47(entity.entityId)?.entityId));
38507
38539
  const selected = new Set(entities.filter((entity) => resolvedSelection.has(resolve47(entity.entityId)?.entityId)).map((entity) => entity.entityId));
38508
38540
  const context = {
38509
38541
  validAt,
@@ -49418,7 +49450,8 @@ async function mem7Search(binding, args, options = {}) {
49418
49450
  entityRef: args.entity_ref,
49419
49451
  maxTokens: args.max_tokens,
49420
49452
  sessionId: args.session_id,
49421
- includeRelationships: false
49453
+ includeRelationships: false,
49454
+ matchedEntitiesOnly: true
49422
49455
  };
49423
49456
  const fresh = service.store.readTransaction(() => JSON.parse(searchResponse(
49424
49457
  service,
@@ -49448,7 +49481,8 @@ async function searchBoundMemory(binding, args, options) {
49448
49481
  entityRef: args.entity_ref,
49449
49482
  maxTokens: args.max_tokens,
49450
49483
  sessionId: args.session_id,
49451
- includeRelationships: false
49484
+ includeRelationships: false,
49485
+ matchedEntitiesOnly: true
49452
49486
  };
49453
49487
  validateMemoryContextRequest(service.store, service.scope, request3);
49454
49488
  recordSearchTiming("validate", validationStarted);
@@ -61939,6 +61973,7 @@ var init_validate_import_live = __esm({
61939
61973
  var topics_chunks_exports = {};
61940
61974
  __export(topics_chunks_exports, {
61941
61975
  TOPICS_CHUNK_SESSION: () => TOPICS_CHUNK_SESSION,
61976
+ chunkTimestamp: () => chunkTimestamp,
61942
61977
  chunkTopicsText: () => chunkTopicsText,
61943
61978
  importTopicChunks: () => importTopicChunks
61944
61979
  });
@@ -62001,6 +62036,10 @@ function walk(root) {
62001
62036
  visit(root);
62002
62037
  return out.sort();
62003
62038
  }
62039
+ function chunkTimestamp(meta) {
62040
+ const ms = Date.parse(String(meta.date ?? ""));
62041
+ return new Date(Number.isFinite(ms) ? ms : Date.now());
62042
+ }
62004
62043
  async function importTopicChunks(options) {
62005
62044
  const { stateDir, topicsDir, userId, embed } = options;
62006
62045
  const manifestPath = join110(stateDir, "mem7", "topics-chunks.json");
@@ -62059,7 +62098,7 @@ async function importTopicChunks(options) {
62059
62098
  appId: options.appId ?? "default",
62060
62099
  projectId: options.projectId ?? "default",
62061
62100
  sessionId: TOPICS_CHUNK_SESSION,
62062
- timestamp: new Date(parsed.meta.date || Date.now()),
62101
+ timestamp: chunkTimestamp(parsed.meta),
62063
62102
  parentId,
62064
62103
  text: chunk.text,
62065
62104
  subject: title2,
@@ -62080,7 +62119,7 @@ async function importTopicChunks(options) {
62080
62119
  report.errors.push(`${rel}: ${error instanceof Error ? error.message : String(error)}`);
62081
62120
  }
62082
62121
  }
62083
- for (const rel of Object.keys(manifest)) {
62122
+ if (options.prune !== false) for (const rel of Object.keys(manifest)) {
62084
62123
  if (seen.has(rel)) continue;
62085
62124
  try {
62086
62125
  await table.delete(`parent_id = '${sqlLiteral2(`topic_chunk:${rel}`)}'`);