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.
package/dist/main.mjs CHANGED
@@ -6792,6 +6792,8 @@ __export(tokenizer_exports, {
6792
6792
  DEFAULT_STOPWORDS: () => DEFAULT_STOPWORDS,
6793
6793
  MIN_TOKEN_LENGTH: () => MIN_TOKEN_LENGTH,
6794
6794
  cjkBigrams: () => cjkBigrams,
6795
+ literalQueryNeedles: () => literalQueryNeedles,
6796
+ queryBigramNeedles: () => queryBigramNeedles,
6795
6797
  tokenize: () => tokenize,
6796
6798
  tokenizeCjk: () => tokenizeCjk,
6797
6799
  tokenizeToField: () => tokenizeToField
@@ -6826,7 +6828,22 @@ function cjkBigrams(text5) {
6826
6828
  function tokenizeCjk(text5) {
6827
6829
  return [...tokenize(text5), ...cjkBigrams(text5)];
6828
6830
  }
6829
- var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
6831
+ function invisibleCjkNeedles(candidates2) {
6832
+ return [...new Set(candidates2.map((token) => token.trim()))].filter((token) => /^[\u4e00-\u9fff]{2,}$/.test(token) && tokenize(token).length === 0).slice(0, 8);
6833
+ }
6834
+ function literalQueryNeedles(text5) {
6835
+ const chars = shortCjkCharCount(text5);
6836
+ if (!chars || chars > 6) return null;
6837
+ const names = invisibleCjkNeedles(engine().cut(String(text5 ?? ""), true));
6838
+ return names.length ? names : queryBigramNeedles(text5);
6839
+ }
6840
+ function queryBigramNeedles(text5) {
6841
+ const chars = shortCjkCharCount(text5);
6842
+ if (!chars || chars > 6) return null;
6843
+ const grams = [...new Set(cjkBigrams(text5))].slice(0, 8);
6844
+ return grams.length ? grams : null;
6845
+ }
6846
+ var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba, shortCjkCharCount;
6830
6847
  var init_tokenizer = __esm({
6831
6848
  "src/mem7/core/tokenizer.ts"() {
6832
6849
  "use strict";
@@ -6899,6 +6916,7 @@ var init_tokenizer = __esm({
6899
6916
  ]);
6900
6917
  MIN_TOKEN_LENGTH = 2;
6901
6918
  jieba = null;
6919
+ shortCjkCharCount = (text5) => (String(text5 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
6902
6920
  }
6903
6921
  });
6904
6922
 
@@ -7278,12 +7296,6 @@ function loadArrow() {
7278
7296
  }
7279
7297
  return arrowPromise;
7280
7298
  }
7281
- function shortCjkQueryBigrams(text5) {
7282
- const chars = (String(text5 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
7283
- if (!chars || chars > 6) return null;
7284
- const grams = [...new Set(cjkBigrams(text5))].slice(0, 8);
7285
- return grams.length ? grams : null;
7286
- }
7287
7299
  function buildSchemas(arrow) {
7288
7300
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
7289
7301
  const commonFields = () => [
@@ -8016,24 +8028,43 @@ var init_vector_store = __esm({
8016
8028
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
8017
8029
  }
8018
8030
  }
8019
- const grams = shortCjkQueryBigrams(queryText);
8020
- if (grams) {
8031
+ const textCols = BM25_TEXT_FIELDS[kind];
8032
+ const scan = async (terms, op, limit) => {
8033
+ 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 ");
8034
+ const where2 = compileFilter(opts.filter);
8035
+ return await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(limit).toArray();
8036
+ };
8037
+ const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
8038
+ const scoreLiteral = (needles2, rows) => {
8039
+ const terms = [.../* @__PURE__ */ new Set([...needles2, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
8040
+ const occurrences2 = (text5, term) => text5.split(term).length - 1;
8041
+ for (const r of rows) {
8042
+ const rid = String(r.id ?? "");
8043
+ if (!rid) continue;
8044
+ const text5 = textCols.map((col) => String(r[col] ?? "")).join(" ");
8045
+ const matched = terms.filter((term) => text5.includes(term));
8046
+ if (!matched.length || matched.every((term) => !needles2.includes(term))) continue;
8047
+ const full = matched.length === terms.length;
8048
+ const density = matched.reduce((sum, term) => sum + occurrences2(text5, term), 0) / Math.max(text5.length, 1) * 1e3;
8049
+ 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;
8050
+ const cur = best.get(rid);
8051
+ if (cur) {
8052
+ if (full) cur._score = Math.max(Number(cur._score ?? 0), score);
8053
+ } else best.set(rid, { ...r, _score: score });
8054
+ }
8055
+ };
8056
+ const needles = literalQueryNeedles(queryText);
8057
+ if (needles) {
8021
8058
  try {
8022
- const textCols = BM25_TEXT_FIELDS[kind];
8023
- const expr = textCols.map((col) => `(${grams.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
8024
- const where2 = compileFilter(opts.filter);
8025
- const extra = await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(topK * 3).toArray();
8026
- const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
8027
- for (const r of extra) {
8028
- const rid = String(r.id ?? "");
8029
- if (!rid) continue;
8030
- const text5 = textCols.map((col) => String(r[col] ?? "")).join(" ");
8031
- const matched = grams.filter((gram) => text5.includes(gram)).length;
8032
- if (!matched) continue;
8033
- const score = maxScore + matched / grams.length;
8034
- const cur = best.get(rid);
8035
- if (cur) cur._score = Math.max(Number(cur._score ?? 0), score);
8036
- else best.set(rid, { ...r, _score: score });
8059
+ const terms = [.../* @__PURE__ */ new Set([...needles, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
8060
+ const [all, any] = await Promise.all([
8061
+ terms.length > 1 ? scan(terms, "AND", topK * 10) : Promise.resolve([]),
8062
+ scan(needles, "OR", topK * 3)
8063
+ ]);
8064
+ scoreLiteral(needles, [...all, ...any]);
8065
+ if (![...best.values()].some((r) => Number(r._score ?? 0) > maxScore)) {
8066
+ const bigrams = [...new Set(needles.flatMap((name) => queryBigramNeedles(name) ?? []))].slice(0, 8);
8067
+ if (bigrams.length && JSON.stringify(bigrams) !== JSON.stringify(needles)) scoreLiteral(bigrams, await scan(bigrams, "OR", topK * 3));
8037
8068
  }
8038
8069
  } catch {
8039
8070
  }
@@ -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, args2, options = {}) {
49418
49450
  entityRef: args2.entity_ref,
49419
49451
  maxTokens: args2.max_tokens,
49420
49452
  sessionId: args2.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, args2, options) {
49448
49481
  entityRef: args2.entity_ref,
49449
49482
  maxTokens: args2.max_tokens,
49450
49483
  sessionId: args2.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);
@@ -62073,6 +62107,7 @@ var init_validate_import_live = __esm({
62073
62107
  var topics_chunks_exports = {};
62074
62108
  __export(topics_chunks_exports, {
62075
62109
  TOPICS_CHUNK_SESSION: () => TOPICS_CHUNK_SESSION,
62110
+ chunkTimestamp: () => chunkTimestamp,
62076
62111
  chunkTopicsText: () => chunkTopicsText,
62077
62112
  importTopicChunks: () => importTopicChunks
62078
62113
  });
@@ -62135,6 +62170,10 @@ function walk(root) {
62135
62170
  visit(root);
62136
62171
  return out.sort();
62137
62172
  }
62173
+ function chunkTimestamp(meta) {
62174
+ const ms = Date.parse(String(meta.date ?? ""));
62175
+ return new Date(Number.isFinite(ms) ? ms : Date.now());
62176
+ }
62138
62177
  async function importTopicChunks(options) {
62139
62178
  const { stateDir, topicsDir, userId, embed } = options;
62140
62179
  const manifestPath = join110(stateDir, "mem7", "topics-chunks.json");
@@ -62193,7 +62232,7 @@ async function importTopicChunks(options) {
62193
62232
  appId: options.appId ?? "default",
62194
62233
  projectId: options.projectId ?? "default",
62195
62234
  sessionId: TOPICS_CHUNK_SESSION,
62196
- timestamp: new Date(parsed.meta.date || Date.now()),
62235
+ timestamp: chunkTimestamp(parsed.meta),
62197
62236
  parentId,
62198
62237
  text: chunk.text,
62199
62238
  subject: title2,
@@ -62214,7 +62253,7 @@ async function importTopicChunks(options) {
62214
62253
  report.errors.push(`${rel}: ${error instanceof Error ? error.message : String(error)}`);
62215
62254
  }
62216
62255
  }
62217
- for (const rel of Object.keys(manifest)) {
62256
+ if (options.prune !== false) for (const rel of Object.keys(manifest)) {
62218
62257
  if (seen.has(rel)) continue;
62219
62258
  try {
62220
62259
  await table.delete(`parent_id = '${sqlLiteral2(`topic_chunk:${rel}`)}'`);
@@ -1368,6 +1368,8 @@ __export(tokenizer_exports, {
1368
1368
  DEFAULT_STOPWORDS: () => DEFAULT_STOPWORDS,
1369
1369
  MIN_TOKEN_LENGTH: () => MIN_TOKEN_LENGTH,
1370
1370
  cjkBigrams: () => cjkBigrams,
1371
+ literalQueryNeedles: () => literalQueryNeedles,
1372
+ queryBigramNeedles: () => queryBigramNeedles,
1371
1373
  tokenize: () => tokenize,
1372
1374
  tokenizeCjk: () => tokenizeCjk,
1373
1375
  tokenizeToField: () => tokenizeToField
@@ -1402,7 +1404,22 @@ function cjkBigrams(text2) {
1402
1404
  function tokenizeCjk(text2) {
1403
1405
  return [...tokenize(text2), ...cjkBigrams(text2)];
1404
1406
  }
1405
- var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
1407
+ function invisibleCjkNeedles(candidates) {
1408
+ return [...new Set(candidates.map((token) => token.trim()))].filter((token) => /^[\u4e00-\u9fff]{2,}$/.test(token) && tokenize(token).length === 0).slice(0, 8);
1409
+ }
1410
+ function literalQueryNeedles(text2) {
1411
+ const chars = shortCjkCharCount(text2);
1412
+ if (!chars || chars > 6) return null;
1413
+ const names = invisibleCjkNeedles(engine().cut(String(text2 ?? ""), true));
1414
+ return names.length ? names : queryBigramNeedles(text2);
1415
+ }
1416
+ function queryBigramNeedles(text2) {
1417
+ const chars = shortCjkCharCount(text2);
1418
+ if (!chars || chars > 6) return null;
1419
+ const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
1420
+ return grams.length ? grams : null;
1421
+ }
1422
+ var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba, shortCjkCharCount;
1406
1423
  var init_tokenizer = __esm({
1407
1424
  "src/mem7/core/tokenizer.ts"() {
1408
1425
  "use strict";
@@ -1475,6 +1492,7 @@ var init_tokenizer = __esm({
1475
1492
  ]);
1476
1493
  MIN_TOKEN_LENGTH = 2;
1477
1494
  jieba = null;
1495
+ shortCjkCharCount = (text2) => (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
1478
1496
  }
1479
1497
  });
1480
1498
 
@@ -2904,12 +2922,6 @@ function loadArrow() {
2904
2922
  }
2905
2923
  return arrowPromise;
2906
2924
  }
2907
- function shortCjkQueryBigrams(text2) {
2908
- const chars = (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
2909
- if (!chars || chars > 6) return null;
2910
- const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
2911
- return grams.length ? grams : null;
2912
- }
2913
2925
  function buildSchemas(arrow) {
2914
2926
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
2915
2927
  const commonFields = () => [
@@ -3642,24 +3654,43 @@ var init_vector_store = __esm({
3642
3654
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
3643
3655
  }
3644
3656
  }
3645
- const grams = shortCjkQueryBigrams(queryText);
3646
- if (grams) {
3657
+ const textCols = BM25_TEXT_FIELDS[kind];
3658
+ const scan = async (terms, op, limit) => {
3659
+ 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 ");
3660
+ const where2 = compileFilter(opts.filter);
3661
+ return await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(limit).toArray();
3662
+ };
3663
+ const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
3664
+ const scoreLiteral = (needles2, rows) => {
3665
+ const terms = [.../* @__PURE__ */ new Set([...needles2, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
3666
+ const occurrences2 = (text2, term) => text2.split(term).length - 1;
3667
+ for (const r of rows) {
3668
+ const rid = String(r.id ?? "");
3669
+ if (!rid) continue;
3670
+ const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
3671
+ const matched = terms.filter((term) => text2.includes(term));
3672
+ if (!matched.length || matched.every((term) => !needles2.includes(term))) continue;
3673
+ const full = matched.length === terms.length;
3674
+ const density = matched.reduce((sum, term) => sum + occurrences2(text2, term), 0) / Math.max(text2.length, 1) * 1e3;
3675
+ 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;
3676
+ const cur = best.get(rid);
3677
+ if (cur) {
3678
+ if (full) cur._score = Math.max(Number(cur._score ?? 0), score);
3679
+ } else best.set(rid, { ...r, _score: score });
3680
+ }
3681
+ };
3682
+ const needles = literalQueryNeedles(queryText);
3683
+ if (needles) {
3647
3684
  try {
3648
- const textCols = BM25_TEXT_FIELDS[kind];
3649
- const expr = textCols.map((col) => `(${grams.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
3650
- const where2 = compileFilter(opts.filter);
3651
- const extra = await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(topK * 3).toArray();
3652
- const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
3653
- for (const r of extra) {
3654
- const rid = String(r.id ?? "");
3655
- if (!rid) continue;
3656
- const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
3657
- const matched = grams.filter((gram) => text2.includes(gram)).length;
3658
- if (!matched) continue;
3659
- const score = maxScore + matched / grams.length;
3660
- const cur = best.get(rid);
3661
- if (cur) cur._score = Math.max(Number(cur._score ?? 0), score);
3662
- else best.set(rid, { ...r, _score: score });
3685
+ const terms = [.../* @__PURE__ */ new Set([...needles, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
3686
+ const [all, any] = await Promise.all([
3687
+ terms.length > 1 ? scan(terms, "AND", topK * 10) : Promise.resolve([]),
3688
+ scan(needles, "OR", topK * 3)
3689
+ ]);
3690
+ scoreLiteral(needles, [...all, ...any]);
3691
+ if (![...best.values()].some((r) => Number(r._score ?? 0) > maxScore)) {
3692
+ const bigrams = [...new Set(needles.flatMap((name) => queryBigramNeedles(name) ?? []))].slice(0, 8);
3693
+ if (bigrams.length && JSON.stringify(bigrams) !== JSON.stringify(needles)) scoreLiteral(bigrams, await scan(bigrams, "OR", topK * 3));
3663
3694
  }
3664
3695
  } catch {
3665
3696
  }
@@ -15621,7 +15652,8 @@ function buildMemoryContext(store, scope, request, clock = () => (/* @__PURE__ *
15621
15652
  if (!resolved.has(id)) resolved.set(id, store.entities.resolve(scope, id, snapshot.entityRevision, cutoff ?? void 0));
15622
15653
  return resolved.get(id);
15623
15654
  };
15624
- const resolvedSelection = new Set((request.entityRef || matching.length ? matching : entities).map((entity) => resolve13(entity.entityId)?.entityId));
15655
+ const pool = request.entityRef || matching.length ? matching : request.matchedEntitiesOnly ? [] : entities;
15656
+ const resolvedSelection = new Set(pool.map((entity) => resolve13(entity.entityId)?.entityId));
15625
15657
  const selected = new Set(entities.filter((entity) => resolvedSelection.has(resolve13(entity.entityId)?.entityId)).map((entity) => entity.entityId));
15626
15658
  const context = {
15627
15659
  validAt,
@@ -23698,7 +23730,8 @@ async function mem7Search(binding, args, options = {}) {
23698
23730
  entityRef: args.entity_ref,
23699
23731
  maxTokens: args.max_tokens,
23700
23732
  sessionId: args.session_id,
23701
- includeRelationships: false
23733
+ includeRelationships: false,
23734
+ matchedEntitiesOnly: true
23702
23735
  };
23703
23736
  const fresh = service.store.readTransaction(() => JSON.parse(searchResponse(
23704
23737
  service,
@@ -23728,7 +23761,8 @@ async function searchBoundMemory(binding, args, options) {
23728
23761
  entityRef: args.entity_ref,
23729
23762
  maxTokens: args.max_tokens,
23730
23763
  sessionId: args.session_id,
23731
- includeRelationships: false
23764
+ includeRelationships: false,
23765
+ matchedEntitiesOnly: true
23732
23766
  };
23733
23767
  validateMemoryContextRequest(service.store, service.scope, request);
23734
23768
  recordSearchTiming("validate", validationStarted);
@@ -801,7 +801,22 @@ function cjkBigrams(text2) {
801
801
  function tokenizeCjk(text2) {
802
802
  return [...tokenize(text2), ...cjkBigrams(text2)];
803
803
  }
804
- var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
804
+ function invisibleCjkNeedles(candidates) {
805
+ return [...new Set(candidates.map((token) => token.trim()))].filter((token) => /^[\u4e00-\u9fff]{2,}$/.test(token) && tokenize(token).length === 0).slice(0, 8);
806
+ }
807
+ function literalQueryNeedles(text2) {
808
+ const chars = shortCjkCharCount(text2);
809
+ if (!chars || chars > 6) return null;
810
+ const names = invisibleCjkNeedles(engine().cut(String(text2 ?? ""), true));
811
+ return names.length ? names : queryBigramNeedles(text2);
812
+ }
813
+ function queryBigramNeedles(text2) {
814
+ const chars = shortCjkCharCount(text2);
815
+ if (!chars || chars > 6) return null;
816
+ const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
817
+ return grams.length ? grams : null;
818
+ }
819
+ var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba, shortCjkCharCount;
805
820
  var init_tokenizer = __esm({
806
821
  "src/mem7/core/tokenizer.ts"() {
807
822
  "use strict";
@@ -874,6 +889,7 @@ var init_tokenizer = __esm({
874
889
  ]);
875
890
  MIN_TOKEN_LENGTH = 2;
876
891
  jieba = null;
892
+ shortCjkCharCount = (text2) => (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
877
893
  }
878
894
  });
879
895
 
@@ -4331,12 +4347,6 @@ function loadArrow() {
4331
4347
  }
4332
4348
  return arrowPromise;
4333
4349
  }
4334
- function shortCjkQueryBigrams(text2) {
4335
- const chars = (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
4336
- if (!chars || chars > 6) return null;
4337
- const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
4338
- return grams.length ? grams : null;
4339
- }
4340
4350
  function buildSchemas(arrow) {
4341
4351
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
4342
4352
  const commonFields = () => [
@@ -5069,24 +5079,43 @@ var init_vector_store = __esm({
5069
5079
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
5070
5080
  }
5071
5081
  }
5072
- const grams = shortCjkQueryBigrams(queryText);
5073
- if (grams) {
5082
+ const textCols = BM25_TEXT_FIELDS[kind];
5083
+ const scan = async (terms, op, limit) => {
5084
+ 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 ");
5085
+ const where2 = compileFilter(opts.filter);
5086
+ return await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(limit).toArray();
5087
+ };
5088
+ const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
5089
+ const scoreLiteral = (needles2, rows) => {
5090
+ const terms = [.../* @__PURE__ */ new Set([...needles2, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
5091
+ const occurrences2 = (text2, term) => text2.split(term).length - 1;
5092
+ for (const r of rows) {
5093
+ const rid = String(r.id ?? "");
5094
+ if (!rid) continue;
5095
+ const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
5096
+ const matched = terms.filter((term) => text2.includes(term));
5097
+ if (!matched.length || matched.every((term) => !needles2.includes(term))) continue;
5098
+ const full = matched.length === terms.length;
5099
+ const density = matched.reduce((sum, term) => sum + occurrences2(text2, term), 0) / Math.max(text2.length, 1) * 1e3;
5100
+ 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;
5101
+ const cur = best.get(rid);
5102
+ if (cur) {
5103
+ if (full) cur._score = Math.max(Number(cur._score ?? 0), score);
5104
+ } else best.set(rid, { ...r, _score: score });
5105
+ }
5106
+ };
5107
+ const needles = literalQueryNeedles(queryText);
5108
+ if (needles) {
5074
5109
  try {
5075
- const textCols = BM25_TEXT_FIELDS[kind];
5076
- const expr = textCols.map((col) => `(${grams.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
5077
- const where2 = compileFilter(opts.filter);
5078
- const extra = await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(topK * 3).toArray();
5079
- const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
5080
- for (const r of extra) {
5081
- const rid = String(r.id ?? "");
5082
- if (!rid) continue;
5083
- const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
5084
- const matched = grams.filter((gram) => text2.includes(gram)).length;
5085
- if (!matched) continue;
5086
- const score = maxScore + matched / grams.length;
5087
- const cur = best.get(rid);
5088
- if (cur) cur._score = Math.max(Number(cur._score ?? 0), score);
5089
- else best.set(rid, { ...r, _score: score });
5110
+ const terms = [.../* @__PURE__ */ new Set([...needles, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
5111
+ const [all, any] = await Promise.all([
5112
+ terms.length > 1 ? scan(terms, "AND", topK * 10) : Promise.resolve([]),
5113
+ scan(needles, "OR", topK * 3)
5114
+ ]);
5115
+ scoreLiteral(needles, [...all, ...any]);
5116
+ if (![...best.values()].some((r) => Number(r._score ?? 0) > maxScore)) {
5117
+ const bigrams = [...new Set(needles.flatMap((name) => queryBigramNeedles(name) ?? []))].slice(0, 8);
5118
+ if (bigrams.length && JSON.stringify(bigrams) !== JSON.stringify(needles)) scoreLiteral(bigrams, await scan(bigrams, "OR", topK * 3));
5090
5119
  }
5091
5120
  } catch {
5092
5121
  }
@@ -1617,7 +1617,22 @@ function cjkBigrams(text2) {
1617
1617
  }
1618
1618
  return out;
1619
1619
  }
1620
- var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
1620
+ function invisibleCjkNeedles(candidates2) {
1621
+ return [...new Set(candidates2.map((token) => token.trim()))].filter((token) => /^[\u4e00-\u9fff]{2,}$/.test(token) && tokenize(token).length === 0).slice(0, 8);
1622
+ }
1623
+ function literalQueryNeedles(text2) {
1624
+ const chars = shortCjkCharCount(text2);
1625
+ if (!chars || chars > 6) return null;
1626
+ const names = invisibleCjkNeedles(engine().cut(String(text2 ?? ""), true));
1627
+ return names.length ? names : queryBigramNeedles(text2);
1628
+ }
1629
+ function queryBigramNeedles(text2) {
1630
+ const chars = shortCjkCharCount(text2);
1631
+ if (!chars || chars > 6) return null;
1632
+ const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
1633
+ return grams.length ? grams : null;
1634
+ }
1635
+ var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba, shortCjkCharCount;
1621
1636
  var init_tokenizer = __esm({
1622
1637
  "src/mem7/core/tokenizer.ts"() {
1623
1638
  "use strict";
@@ -1690,6 +1705,7 @@ var init_tokenizer = __esm({
1690
1705
  ]);
1691
1706
  MIN_TOKEN_LENGTH = 2;
1692
1707
  jieba = null;
1708
+ shortCjkCharCount = (text2) => (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
1693
1709
  }
1694
1710
  });
1695
1711
 
@@ -3263,12 +3279,6 @@ function loadArrow() {
3263
3279
  }
3264
3280
  return arrowPromise;
3265
3281
  }
3266
- function shortCjkQueryBigrams(text2) {
3267
- const chars = (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
3268
- if (!chars || chars > 6) return null;
3269
- const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
3270
- return grams.length ? grams : null;
3271
- }
3272
3282
  function buildSchemas(arrow) {
3273
3283
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
3274
3284
  const commonFields = () => [
@@ -4001,24 +4011,43 @@ var init_vector_store = __esm({
4001
4011
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
4002
4012
  }
4003
4013
  }
4004
- const grams = shortCjkQueryBigrams(queryText);
4005
- if (grams) {
4014
+ const textCols = BM25_TEXT_FIELDS[kind];
4015
+ const scan = async (terms, op, limit2) => {
4016
+ 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 ");
4017
+ const where2 = compileFilter(opts.filter);
4018
+ return await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(limit2).toArray();
4019
+ };
4020
+ const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
4021
+ const scoreLiteral = (needles2, rows) => {
4022
+ const terms = [.../* @__PURE__ */ new Set([...needles2, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
4023
+ const occurrences2 = (text2, term) => text2.split(term).length - 1;
4024
+ for (const r of rows) {
4025
+ const rid = String(r.id ?? "");
4026
+ if (!rid) continue;
4027
+ const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
4028
+ const matched = terms.filter((term) => text2.includes(term));
4029
+ if (!matched.length || matched.every((term) => !needles2.includes(term))) continue;
4030
+ const full = matched.length === terms.length;
4031
+ const density = matched.reduce((sum, term) => sum + occurrences2(text2, term), 0) / Math.max(text2.length, 1) * 1e3;
4032
+ 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;
4033
+ const cur = best.get(rid);
4034
+ if (cur) {
4035
+ if (full) cur._score = Math.max(Number(cur._score ?? 0), score);
4036
+ } else best.set(rid, { ...r, _score: score });
4037
+ }
4038
+ };
4039
+ const needles = literalQueryNeedles(queryText);
4040
+ if (needles) {
4006
4041
  try {
4007
- const textCols = BM25_TEXT_FIELDS[kind];
4008
- const expr = textCols.map((col) => `(${grams.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
4009
- const where2 = compileFilter(opts.filter);
4010
- const extra = await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(topK * 3).toArray();
4011
- const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
4012
- for (const r of extra) {
4013
- const rid = String(r.id ?? "");
4014
- if (!rid) continue;
4015
- const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
4016
- const matched = grams.filter((gram) => text2.includes(gram)).length;
4017
- if (!matched) continue;
4018
- const score = maxScore + matched / grams.length;
4019
- const cur = best.get(rid);
4020
- if (cur) cur._score = Math.max(Number(cur._score ?? 0), score);
4021
- else best.set(rid, { ...r, _score: score });
4042
+ const terms = [.../* @__PURE__ */ new Set([...needles, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
4043
+ const [all, any] = await Promise.all([
4044
+ terms.length > 1 ? scan(terms, "AND", topK * 10) : Promise.resolve([]),
4045
+ scan(needles, "OR", topK * 3)
4046
+ ]);
4047
+ scoreLiteral(needles, [...all, ...any]);
4048
+ if (![...best.values()].some((r) => Number(r._score ?? 0) > maxScore)) {
4049
+ const bigrams = [...new Set(needles.flatMap((name) => queryBigramNeedles(name) ?? []))].slice(0, 8);
4050
+ if (bigrams.length && JSON.stringify(bigrams) !== JSON.stringify(needles)) scoreLiteral(bigrams, await scan(bigrams, "OR", topK * 3));
4022
4051
  }
4023
4052
  } catch {
4024
4053
  }
@@ -7973,7 +7973,22 @@ function cjkBigrams(text2) {
7973
7973
  }
7974
7974
  return out;
7975
7975
  }
7976
- var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
7976
+ function invisibleCjkNeedles(candidates) {
7977
+ return [...new Set(candidates.map((token) => token.trim()))].filter((token) => /^[\u4e00-\u9fff]{2,}$/.test(token) && tokenize(token).length === 0).slice(0, 8);
7978
+ }
7979
+ function literalQueryNeedles(text2) {
7980
+ const chars = shortCjkCharCount(text2);
7981
+ if (!chars || chars > 6) return null;
7982
+ const names2 = invisibleCjkNeedles(engine().cut(String(text2 ?? ""), true));
7983
+ return names2.length ? names2 : queryBigramNeedles(text2);
7984
+ }
7985
+ function queryBigramNeedles(text2) {
7986
+ const chars = shortCjkCharCount(text2);
7987
+ if (!chars || chars > 6) return null;
7988
+ const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
7989
+ return grams.length ? grams : null;
7990
+ }
7991
+ var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba, shortCjkCharCount;
7977
7992
  var init_tokenizer = __esm({
7978
7993
  "src/mem7/core/tokenizer.ts"() {
7979
7994
  "use strict";
@@ -8046,6 +8061,7 @@ var init_tokenizer = __esm({
8046
8061
  ]);
8047
8062
  MIN_TOKEN_LENGTH = 2;
8048
8063
  jieba = null;
8064
+ shortCjkCharCount = (text2) => (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
8049
8065
  }
8050
8066
  });
8051
8067
 
@@ -12218,12 +12234,6 @@ function loadArrow() {
12218
12234
  }
12219
12235
  return arrowPromise;
12220
12236
  }
12221
- function shortCjkQueryBigrams(text2) {
12222
- const chars = (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
12223
- if (!chars || chars > 6) return null;
12224
- const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
12225
- return grams.length ? grams : null;
12226
- }
12227
12237
  function buildSchemas(arrow) {
12228
12238
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
12229
12239
  const commonFields = () => [
@@ -12956,24 +12966,43 @@ var init_vector_store = __esm({
12956
12966
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
12957
12967
  }
12958
12968
  }
12959
- const grams = shortCjkQueryBigrams(queryText);
12960
- if (grams) {
12969
+ const textCols = BM25_TEXT_FIELDS[kind];
12970
+ const scan = async (terms, op, limit) => {
12971
+ 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 ");
12972
+ const where2 = compileFilter(opts.filter);
12973
+ return await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(limit).toArray();
12974
+ };
12975
+ const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
12976
+ const scoreLiteral = (needles2, rows) => {
12977
+ const terms = [.../* @__PURE__ */ new Set([...needles2, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
12978
+ const occurrences2 = (text2, term) => text2.split(term).length - 1;
12979
+ for (const r of rows) {
12980
+ const rid = String(r.id ?? "");
12981
+ if (!rid) continue;
12982
+ const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
12983
+ const matched = terms.filter((term) => text2.includes(term));
12984
+ if (!matched.length || matched.every((term) => !needles2.includes(term))) continue;
12985
+ const full = matched.length === terms.length;
12986
+ const density = matched.reduce((sum, term) => sum + occurrences2(text2, term), 0) / Math.max(text2.length, 1) * 1e3;
12987
+ 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;
12988
+ const cur = best.get(rid);
12989
+ if (cur) {
12990
+ if (full) cur._score = Math.max(Number(cur._score ?? 0), score);
12991
+ } else best.set(rid, { ...r, _score: score });
12992
+ }
12993
+ };
12994
+ const needles = literalQueryNeedles(queryText);
12995
+ if (needles) {
12961
12996
  try {
12962
- const textCols = BM25_TEXT_FIELDS[kind];
12963
- const expr = textCols.map((col) => `(${grams.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
12964
- const where2 = compileFilter(opts.filter);
12965
- const extra = await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(topK * 3).toArray();
12966
- const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
12967
- for (const r of extra) {
12968
- const rid = String(r.id ?? "");
12969
- if (!rid) continue;
12970
- const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
12971
- const matched = grams.filter((gram) => text2.includes(gram)).length;
12972
- if (!matched) continue;
12973
- const score = maxScore + matched / grams.length;
12974
- const cur = best.get(rid);
12975
- if (cur) cur._score = Math.max(Number(cur._score ?? 0), score);
12976
- else best.set(rid, { ...r, _score: score });
12997
+ const terms = [.../* @__PURE__ */ new Set([...needles, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
12998
+ const [all, any] = await Promise.all([
12999
+ terms.length > 1 ? scan(terms, "AND", topK * 10) : Promise.resolve([]),
13000
+ scan(needles, "OR", topK * 3)
13001
+ ]);
13002
+ scoreLiteral(needles, [...all, ...any]);
13003
+ if (![...best.values()].some((r) => Number(r._score ?? 0) > maxScore)) {
13004
+ const bigrams = [...new Set(needles.flatMap((name) => queryBigramNeedles(name) ?? []))].slice(0, 8);
13005
+ if (bigrams.length && JSON.stringify(bigrams) !== JSON.stringify(needles)) scoreLiteral(bigrams, await scan(bigrams, "OR", topK * 3));
12977
13006
  }
12978
13007
  } catch {
12979
13008
  }