engine7 7.1.151 → 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.
@@ -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
 
@@ -2385,8 +2403,9 @@ function invalidateDerivedDependencies(db, event) {
2385
2403
  }
2386
2404
  return invalidateChildren(db, event.scopeId, pending, event.kind);
2387
2405
  }
2388
- function invalidateScopeDependencies(db, scope, parent, reason) {
2389
- const children = db.prepare("SELECT child_kind,child_id FROM memory_dependencies WHERE scope_id=? AND parent_kind='scope' AND parent_id=?").all(scope, parent);
2406
+ function invalidateScopeDependencies(db, scope, parent, reason, options = {}) {
2407
+ let children = db.prepare("SELECT child_kind,child_id FROM memory_dependencies WHERE scope_id=? AND parent_kind='scope' AND parent_id=?").all(scope, parent);
2408
+ if (options.skipKinds?.size) children = children.filter((child) => !options.skipKinds.has(child.child_kind));
2390
2409
  invalidateChildren(db, scope, children, reason);
2391
2410
  }
2392
2411
  function invalidateChildren(db, scope, pending, reason) {
@@ -2406,7 +2425,7 @@ function invalidateChildren(db, scope, pending, reason) {
2406
2425
  }
2407
2426
  const state = child.deleted ? "deleted" : "needs_revalidation";
2408
2427
  db.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
2409
- WHERE scope_id=? AND child_kind=? AND child_id=? AND state IN ('current','needs_revalidation','invalid') AND state<>?`).run(state, reason, (/* @__PURE__ */ new Date()).toISOString(), scope, child.child_kind, child.child_id, state);
2428
+ WHERE scope_id=? AND child_kind=? AND child_id=? AND state IN ('current','needs_revalidation') AND state<>?`).run(state, reason, (/* @__PURE__ */ new Date()).toISOString(), scope, child.child_kind, child.child_id, state);
2410
2429
  result.push(child.child_id);
2411
2430
  pending.push(...db.prepare("SELECT child_kind,child_id,role FROM memory_dependencies WHERE scope_id=? AND parent_kind='artifact' AND parent_id=?").all(scope, child.child_id).map((row) => ({ ...row, deleted: child.deleted && row.role === "supports" })));
2412
2431
  }
@@ -2999,7 +3018,7 @@ function textColumnOf(kind) {
2999
3018
  return "fact";
3000
3019
  }
3001
3020
  }
3002
- var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3021
+ var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, BM25_TEXT_FIELDS, sqlLiteral, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3003
3022
  var init_vector_store = __esm({
3004
3023
  "src/mem7/core/vector-store.ts"() {
3005
3024
  "use strict";
@@ -3030,6 +3049,14 @@ var init_vector_store = __esm({
3030
3049
  agent_case: ["task_intent_tokens", "approach_tokens"],
3031
3050
  agent_skill: ["description_tokens", "content_tokens"]
3032
3051
  };
3052
+ BM25_TEXT_FIELDS = {
3053
+ foresight: ["foresight", "evidence"],
3054
+ episode: ["episode"],
3055
+ atomic_fact: ["fact"],
3056
+ agent_case: ["task_intent", "approach"],
3057
+ agent_skill: ["description", "content"]
3058
+ };
3059
+ sqlLiteral = (value) => value.replace(/'/g, "''");
3033
3060
  RRF_K = 60;
3034
3061
  warnedFts = /* @__PURE__ */ new Set();
3035
3062
  warnedVecIdx = /* @__PURE__ */ new Set();
@@ -3627,6 +3654,47 @@ var init_vector_store = __esm({
3627
3654
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
3628
3655
  }
3629
3656
  }
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) {
3684
+ try {
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));
3694
+ }
3695
+ } catch {
3696
+ }
3697
+ }
3630
3698
  return this.visibleRows(kind, [...best.values()]).filter((r) => Number(r._score ?? 0) > 0).sort((a, b) => Number(b._score ?? 0) - Number(a._score ?? 0)).slice(0, topK).map((r) => ({ ...this.toHit(kind, r), distance: 0, score: Number(r._score ?? 0) }));
3631
3699
  } catch (err) {
3632
3700
  const msg = String(err?.message ?? err);
@@ -4153,7 +4221,7 @@ import { createHash as createHash6 } from "node:crypto";
4153
4221
  function projectedSourceIdFromScopeId(id, originKey, sourceVersion) {
4154
4222
  return "src_" + digest([id, originKey, sourceVersion]);
4155
4223
  }
4156
- var SOURCE_SCHEMA, SOURCE_ALIAS_SCHEMA, digest, SourceStore;
4224
+ var RECEIVED_INVALIDATION_SKIP, SOURCE_SCHEMA, SOURCE_ALIAS_SCHEMA, digest, SourceStore;
4157
4225
  var init_source_store = __esm({
4158
4226
  "src/mem7/core/source-store.ts"() {
4159
4227
  "use strict";
@@ -4165,6 +4233,7 @@ var init_source_store = __esm({
4165
4233
  init_watermarks();
4166
4234
  init_interpretation_impact();
4167
4235
  init_conversation_text();
4236
+ RECEIVED_INVALIDATION_SKIP = /* @__PURE__ */ new Set(["foresight"]);
4168
4237
  SOURCE_SCHEMA = `
4169
4238
  CREATE TABLE memory_scopes (
4170
4239
  scope_id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, app_id TEXT NOT NULL, project_id TEXT NOT NULL,
@@ -4346,8 +4415,8 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
4346
4415
  if (this.db.prepare("SELECT 1 FROM memory_sources WHERE scope_id=? AND origin_key=? AND interpretation_status='deleted'").get(id, input.originKey)) throw new Error("DELETED_EVIDENCE");
4347
4416
  if (version !== Number(latest.version ?? 0) + 1) throw new Error("SOURCE_VERSION_CONFLICT: edits must follow the previous version");
4348
4417
  this.db.prepare("UPDATE memory_scopes SET source_seq=source_seq+1,context_revision=context_revision+1 WHERE scope_id=?").run(id);
4349
- invalidateScopeDependencies(this.db, id, "sources", "source.received");
4350
- invalidateScopeDependencies(this.db, id, "context", "source.received");
4418
+ invalidateScopeDependencies(this.db, id, "sources", "source.received", { skipKinds: RECEIVED_INVALIDATION_SKIP });
4419
+ invalidateScopeDependencies(this.db, id, "context", "source.received", { skipKinds: RECEIVED_INVALIDATION_SKIP });
4351
4420
  const seq = Number(this.db.prepare("SELECT source_seq FROM memory_scopes WHERE scope_id=?").get(id).source_seq);
4352
4421
  const sourceId = projectedSourceIdFromScopeId(id, input.originKey, version);
4353
4422
  const receiptId = "rcpt_" + digest([id, sourceId]);
@@ -8747,6 +8816,7 @@ __export(topics_history_exports, {
8747
8816
  topicMatchesYear: () => topicMatchesYear,
8748
8817
  topicQueryYear: () => topicQueryYear,
8749
8818
  topicsHistoryNeedsFallback: () => topicsHistoryNeedsFallback,
8819
+ topicsHistoryRefsCurrent: () => topicsHistoryRefsCurrent,
8750
8820
  topicsHistoryRoot: () => topicsHistoryRoot,
8751
8821
  topicsScope: () => topicsScope
8752
8822
  });
@@ -8846,6 +8916,27 @@ function hasTopicsHistory(b) {
8846
8916
  db.close();
8847
8917
  return true;
8848
8918
  }
8919
+ function topicsHistoryRefsCurrent(b) {
8920
+ const db = openIndex(b);
8921
+ if (!db) return false;
8922
+ try {
8923
+ const expected = rootKey(b);
8924
+ const meta = db.prepare("SELECT value FROM metadata WHERE key='rootKey'").get();
8925
+ if (meta) return meta.value === expected;
8926
+ const rows = db.prepare("SELECT ref FROM (SELECT ref,id FROM entries ORDER BY id LIMIT 1) UNION ALL SELECT ref FROM (SELECT ref,id FROM entries ORDER BY id DESC LIMIT 1)").all();
8927
+ return rows.every((row) => {
8928
+ try {
8929
+ return JSON.parse(row.ref).rootKey === expected;
8930
+ } catch {
8931
+ return false;
8932
+ }
8933
+ });
8934
+ } catch {
8935
+ return false;
8936
+ } finally {
8937
+ db.close();
8938
+ }
8939
+ }
8849
8940
  async function topicsHistoryNeedsFallback(b) {
8850
8941
  const cached = fallbackChecks.get(key3(b));
8851
8942
  if (cached && cached.expiresAt > Date.now()) return cached.value;
@@ -8997,6 +9088,7 @@ async function publishTopicsIndex(bundle, cleaned, b) {
8997
9088
  CREATE VIRTUAL TABLE documents USING fts5(source_path UNINDEXED,original_hash UNINDEXED,terms);
8998
9089
  CREATE VIRTUAL TABLE search USING fts5(id UNINDEXED,terms);`);
8999
9090
  db.prepare("INSERT INTO metadata VALUES(?,?)").run("binding", canonical({ scope: topicsScope(b), root: resolve7(b.topicsDir) }));
9091
+ db.prepare("INSERT INTO metadata VALUES(?,?)").run("rootKey", rootKey(b));
9000
9092
  const sourceInsert = db.prepare("INSERT INTO sources VALUES(?,?,?,?)");
9001
9093
  for (const record of snapshot.manifest.records) sourceInsert.run(record.path, record.sha256, record.bytes, record.mtimeMs);
9002
9094
  const insert = db.prepare("INSERT INTO entries VALUES(?,?,?,?,?,?,?,?,?)"), search = db.prepare("INSERT INTO search VALUES(?,?)");
@@ -11681,7 +11773,7 @@ function contentHash(text2) {
11681
11773
  function mem7Root(stateDir2) {
11682
11774
  return join14(stateDir2, "mem7");
11683
11775
  }
11684
- var STALE_ARTIFACT_FORCE_MS, SCHEMA, AGENT_SCHEMA, Mem7Store;
11776
+ var STALE_ARTIFACT_FORCE_MS, STARVATION_GRACE_MS, SCHEMA, AGENT_SCHEMA, Mem7Store;
11685
11777
  var init_store = __esm({
11686
11778
  "src/mem7/core/store.ts"() {
11687
11779
  "use strict";
@@ -11719,6 +11811,7 @@ var init_store = __esm({
11719
11811
  init_job_retention();
11720
11812
  init_retire_graph_audits();
11721
11813
  STALE_ARTIFACT_FORCE_MS = 2 * 36e5;
11814
+ STARVATION_GRACE_MS = 36e5;
11722
11815
  SCHEMA = `
11723
11816
  CREATE TABLE IF NOT EXISTS memcells (
11724
11817
  id TEXT PRIMARY KEY,
@@ -12809,7 +12902,7 @@ ${e.outcome}
12809
12902
  return this.transaction(() => {
12810
12903
  const kindFilter = options.kinds ? ` AND kind IN (${options.kinds.map(() => "?").join(",")})` : "";
12811
12904
  const scopeFilter = options.scopeId !== void 0 ? " AND scope_id=?" : "";
12812
- const rows = this.db.prepare(`SELECT * FROM ome_jobs j INDEXED BY ${options.scopeId !== void 0 && options.kinds?.length === 1 ? "idx_jobs_scope_priority" : "idx_jobs_runnable_priority"}
12905
+ const base = `SELECT * FROM ome_jobs j INDEXED BY ${options.scopeId !== void 0 && options.kinds?.length === 1 ? "idx_jobs_scope_priority" : "idx_jobs_runnable_priority"}
12813
12906
  WHERE status IN ('pending','running') AND NOT EXISTS (SELECT 1 FROM memory_job_holds h WHERE h.job_id=j.id AND h.released_at IS NULL)
12814
12907
  AND ((status='pending' AND next_run_at<=?)
12815
12908
  OR (status='running' AND COALESCE(lease_until,0)<=?))${kindFilter}${scopeFilter}
@@ -12829,40 +12922,48 @@ ${e.outcome}
12829
12922
  -- Cognition rebuilds its read set at claim time; delayed old work must not fence fresh judgments.
12830
12923
  AND (kind IN ('social.interpret','source.interpret','relationship.cognition') OR scope_id NOT LIKE 'resource:%' OR NOT EXISTS (SELECT 1 FROM ome_jobs prior
12831
12924
  WHERE prior.scope_id=j.scope_id AND prior.id<j.id AND prior.status IN ('pending','running')
12832
- AND NOT EXISTS (SELECT 1 FROM memory_job_holds h WHERE h.job_id=prior.id AND h.released_at IS NULL)) OR scope_id IS NULL)
12833
- -- Retrying an old deferred job must not reserve the next stage budget.
12834
- -- Boundary/resource predecessor predicates above still enforce ordering.
12835
- ORDER BY priority,next_run_at,id LIMIT ?`).all(now2, now2, ...options.kinds ?? [], ...options.scopeId !== void 0 ? [options.scopeId] : [], now2, limit);
12836
- const claimedScopes = /* @__PURE__ */ new Set();
12837
- return rows.flatMap((row) => {
12838
- if (!this.jobProvenance.prepareForClaim(row.id, now2)) return [];
12839
- const updated = this.db.prepare("SELECT * FROM ome_jobs WHERE id=?").get(row.id);
12840
- if (updated.scope_id !== row.scope_id && updated.scope_id) {
12841
- const conflict = this.db.prepare(`SELECT 1 FROM ome_jobs j WHERE j.scope_id=? AND j.id<>?
12842
- AND (j.status='running' AND j.lease_until>? OR ? LIKE 'resource:%' AND j.id<? AND j.status IN ('pending','running')
12843
- AND NOT EXISTS (SELECT 1 FROM memory_job_holds h WHERE h.job_id=j.id AND h.released_at IS NULL))`).get(updated.scope_id, updated.id, now2, updated.scope_id, updated.id);
12844
- if (conflict) return [];
12845
- }
12846
- return [updated];
12847
- }).filter((row) => {
12848
- if (!row.scope_id) return true;
12849
- if (claimedScopes.has(row.scope_id)) return false;
12850
- claimedScopes.add(row.scope_id);
12851
- return true;
12852
- }).map((row) => {
12853
- const leaseToken = randomUUID9();
12854
- this.db.prepare("UPDATE ome_jobs SET status='running',lease_token=?,lease_until=? WHERE id=?").run(leaseToken, now2 + leaseMs, row.id);
12855
- return {
12856
- id: row.id,
12857
- kind: row.kind,
12858
- payload: JSON.parse(row.payload),
12859
- attempts: row.attempts,
12860
- leaseToken,
12861
- inputVersion: row.input_version,
12862
- scopeId: row.scope_id ?? void 0,
12863
- result: row.result_json === null ? void 0 : JSON.parse(row.result_json)
12864
- };
12865
- });
12925
+ AND NOT EXISTS (SELECT 1 FROM memory_job_holds h WHERE h.job_id=prior.id AND h.released_at IS NULL)) OR scope_id IS NULL)`;
12926
+ const select = (starved2) => {
12927
+ const sql = `${base}${starved2 ? " AND status='pending' AND next_run_at<=?" : ""}
12928
+ ORDER BY priority,next_run_at,id LIMIT ?`;
12929
+ const args = starved2 ? [now2, now2, ...options.kinds ?? [], ...options.scopeId !== void 0 ? [options.scopeId] : [], now2, now2 - STARVATION_GRACE_MS, limit] : [now2, now2, ...options.kinds ?? [], ...options.scopeId !== void 0 ? [options.scopeId] : [], now2, limit];
12930
+ return this.db.prepare(sql).all(...args);
12931
+ };
12932
+ const claim = (rows) => {
12933
+ const claimedScopes = /* @__PURE__ */ new Set();
12934
+ return rows.flatMap((row) => {
12935
+ if (!this.jobProvenance.prepareForClaim(row.id, now2)) return [];
12936
+ const updated = this.db.prepare("SELECT * FROM ome_jobs WHERE id=?").get(row.id);
12937
+ if (updated.scope_id !== row.scope_id && updated.scope_id) {
12938
+ const conflict = this.db.prepare(`SELECT 1 FROM ome_jobs j WHERE j.scope_id=? AND j.id<>?
12939
+ AND (j.status='running' AND j.lease_until>? OR ? LIKE 'resource:%' AND j.id<? AND j.status IN ('pending','running')
12940
+ AND NOT EXISTS (SELECT 1 FROM memory_job_holds h WHERE h.job_id=j.id AND h.released_at IS NULL))`).get(updated.scope_id, updated.id, now2, updated.scope_id, updated.id);
12941
+ if (conflict) return [];
12942
+ }
12943
+ return [updated];
12944
+ }).filter((row) => {
12945
+ if (!row.scope_id) return true;
12946
+ if (claimedScopes.has(row.scope_id)) return false;
12947
+ claimedScopes.add(row.scope_id);
12948
+ return true;
12949
+ }).map((row) => {
12950
+ const leaseToken = randomUUID9();
12951
+ this.db.prepare("UPDATE ome_jobs SET status='running',lease_token=?,lease_until=? WHERE id=?").run(leaseToken, now2 + leaseMs, row.id);
12952
+ return {
12953
+ id: row.id,
12954
+ kind: row.kind,
12955
+ payload: JSON.parse(row.payload),
12956
+ attempts: row.attempts,
12957
+ leaseToken,
12958
+ inputVersion: row.input_version,
12959
+ scopeId: row.scope_id ?? void 0,
12960
+ result: row.result_json === null ? void 0 : JSON.parse(row.result_json)
12961
+ };
12962
+ });
12963
+ };
12964
+ if (options.staleOnly) return claim(select(true));
12965
+ const starved = claim(select(true));
12966
+ return starved.length ? starved : claim(select(false));
12866
12967
  });
12867
12968
  }
12868
12969
  /** Compatibility entry point: only expired leases can be recovered. */
@@ -15551,7 +15652,8 @@ function buildMemoryContext(store, scope, request, clock = () => (/* @__PURE__ *
15551
15652
  if (!resolved.has(id)) resolved.set(id, store.entities.resolve(scope, id, snapshot.entityRevision, cutoff ?? void 0));
15552
15653
  return resolved.get(id);
15553
15654
  };
15554
- 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));
15555
15657
  const selected = new Set(entities.filter((entity) => resolvedSelection.has(resolve13(entity.entityId)?.entityId)).map((entity) => entity.entityId));
15556
15658
  const context = {
15557
15659
  validAt,
@@ -23568,13 +23670,18 @@ async function mem7Search(binding, args, options = {}) {
23568
23670
  const includeTopics = !!binding.topicsDir && !topicsImported(binding) && args.view !== "current" && args.known_at === void 0 && args.known_at_revision === void 0;
23569
23671
  const topics = includeTopics ? readTopicsHistory(binding, String(args.query ?? ""), { limit: 20, signal: options.signal }).catch(() => []) : Promise.resolve([]);
23570
23672
  let nativeHistory = [];
23571
- const result = JSON.parse(await searchBoundMemory(binding, args, { ...options, captureHistory: (episodes2) => {
23572
- nativeHistory = episodes2;
23573
- } }));
23673
+ const result = JSON.parse(await searchBoundMemory(binding, args, {
23674
+ ...options,
23675
+ deferRerankToMerge: includeTopics,
23676
+ captureHistory: (episodes2) => {
23677
+ nativeHistory = episodes2;
23678
+ }
23679
+ }));
23574
23680
  const hits = await topics;
23575
23681
  if (!includeTopics) return JSON.stringify(result);
23576
23682
  const { makeMem7RecallRerank: makeMem7RecallRerank2 } = await Promise.resolve().then(() => (init_findRelevantMemoriesMem7(), findRelevantMemoriesMem7_exports));
23577
23683
  const rerank = await makeMem7RecallRerank2(options.signal);
23684
+ if (!rerank) result.historySearch.rerank = "not_configured";
23578
23685
  const episodes = [...result.episodes, ...hits.map((hit) => ({
23579
23686
  id: hit.path,
23580
23687
  path: hit.path,
@@ -23623,7 +23730,8 @@ async function mem7Search(binding, args, options = {}) {
23623
23730
  entityRef: args.entity_ref,
23624
23731
  maxTokens: args.max_tokens,
23625
23732
  sessionId: args.session_id,
23626
- includeRelationships: false
23733
+ includeRelationships: false,
23734
+ matchedEntitiesOnly: true
23627
23735
  };
23628
23736
  const fresh = service.store.readTransaction(() => JSON.parse(searchResponse(
23629
23737
  service,
@@ -23653,7 +23761,8 @@ async function searchBoundMemory(binding, args, options) {
23653
23761
  entityRef: args.entity_ref,
23654
23762
  maxTokens: args.max_tokens,
23655
23763
  sessionId: args.session_id,
23656
- includeRelationships: false
23764
+ includeRelationships: false,
23765
+ matchedEntitiesOnly: true
23657
23766
  };
23658
23767
  validateMemoryContextRequest(service.store, service.scope, request);
23659
23768
  recordSearchTiming("validate", validationStarted);
@@ -23707,13 +23816,13 @@ async function searchBoundMemory(binding, args, options) {
23707
23816
  let failedScopes = 0;
23708
23817
  assertActive();
23709
23818
  const requestedTopK = Math.min(20, Math.max(1, Number(args.maxResults) || 5));
23710
- const topK = binding.topicsDir ? Math.min(20, Math.max(requestedTopK, 12)) : requestedTopK;
23819
+ const topK = options.deferRerankToMerge || method === "hybrid" ? Math.min(20, Math.max(requestedTopK, 12)) : requestedTopK;
23711
23820
  const search = searchMemoryHistory(service.store, {
23712
23821
  embeddingRaw,
23713
23822
  modelRef,
23714
23823
  resolveModel,
23715
23824
  signal: options.signal,
23716
- historicalRerank: binding.topicsDir ? void 0 : { onStatus: (status) => {
23825
+ historicalRerank: options.deferRerankToMerge ? void 0 : { onStatus: (status) => {
23717
23826
  historySearch.rerank = status;
23718
23827
  } },
23719
23828
  onScopeError: () => {
@@ -23731,6 +23840,7 @@ async function searchBoundMemory(binding, args, options) {
23731
23840
  agenticStrategy: args.strategy
23732
23841
  }, request, assertActive);
23733
23842
  episodes = await search;
23843
+ if (!options.deferRerankToMerge && episodes.length > requestedTopK) episodes = episodes.slice(0, requestedTopK);
23734
23844
  assertActive();
23735
23845
  if (failedScopes) historySearch.status = episodes.length ? "partial" : "unavailable";
23736
23846
  } catch (error) {
@@ -1040,7 +1040,7 @@ function invalidateChildren(db, scope, pending, reason) {
1040
1040
  }
1041
1041
  const state = child.deleted ? "deleted" : "needs_revalidation";
1042
1042
  db.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
1043
- WHERE scope_id=? AND child_kind=? AND child_id=? AND state IN ('current','needs_revalidation','invalid') AND state<>?`).run(state, reason, (/* @__PURE__ */ new Date()).toISOString(), scope, child.child_kind, child.child_id, state);
1043
+ WHERE scope_id=? AND child_kind=? AND child_id=? AND state IN ('current','needs_revalidation') AND state<>?`).run(state, reason, (/* @__PURE__ */ new Date()).toISOString(), scope, child.child_kind, child.child_id, state);
1044
1044
  result.push(child.child_id);
1045
1045
  pending.push(...db.prepare("SELECT child_kind,child_id,role FROM memory_dependencies WHERE scope_id=? AND parent_kind='artifact' AND parent_id=?").all(scope, child.child_id).map((row) => ({ ...row, deleted: child.deleted && row.role === "supports" })));
1046
1046
  }