engine7 7.1.150 → 7.1.152

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.
@@ -2385,8 +2385,9 @@ function invalidateDerivedDependencies(db, event) {
2385
2385
  }
2386
2386
  return invalidateChildren(db, event.scopeId, pending, event.kind);
2387
2387
  }
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);
2388
+ function invalidateScopeDependencies(db, scope, parent, reason, options = {}) {
2389
+ 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);
2390
+ if (options.skipKinds?.size) children = children.filter((child) => !options.skipKinds.has(child.child_kind));
2390
2391
  invalidateChildren(db, scope, children, reason);
2391
2392
  }
2392
2393
  function invalidateChildren(db, scope, pending, reason) {
@@ -2406,7 +2407,7 @@ function invalidateChildren(db, scope, pending, reason) {
2406
2407
  }
2407
2408
  const state = child.deleted ? "deleted" : "needs_revalidation";
2408
2409
  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);
2410
+ 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
2411
  result.push(child.child_id);
2411
2412
  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
2413
  }
@@ -2903,6 +2904,12 @@ function loadArrow() {
2903
2904
  }
2904
2905
  return arrowPromise;
2905
2906
  }
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
+ }
2906
2913
  function buildSchemas(arrow) {
2907
2914
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
2908
2915
  const commonFields = () => [
@@ -2999,7 +3006,7 @@ function textColumnOf(kind) {
2999
3006
  return "fact";
3000
3007
  }
3001
3008
  }
3002
- var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3009
+ var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, BM25_TEXT_FIELDS, sqlLiteral, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3003
3010
  var init_vector_store = __esm({
3004
3011
  "src/mem7/core/vector-store.ts"() {
3005
3012
  "use strict";
@@ -3030,6 +3037,14 @@ var init_vector_store = __esm({
3030
3037
  agent_case: ["task_intent_tokens", "approach_tokens"],
3031
3038
  agent_skill: ["description_tokens", "content_tokens"]
3032
3039
  };
3040
+ BM25_TEXT_FIELDS = {
3041
+ foresight: ["foresight", "evidence"],
3042
+ episode: ["episode"],
3043
+ atomic_fact: ["fact"],
3044
+ agent_case: ["task_intent", "approach"],
3045
+ agent_skill: ["description", "content"]
3046
+ };
3047
+ sqlLiteral = (value) => value.replace(/'/g, "''");
3033
3048
  RRF_K = 60;
3034
3049
  warnedFts = /* @__PURE__ */ new Set();
3035
3050
  warnedVecIdx = /* @__PURE__ */ new Set();
@@ -3627,6 +3642,28 @@ var init_vector_store = __esm({
3627
3642
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
3628
3643
  }
3629
3644
  }
3645
+ const grams = shortCjkQueryBigrams(queryText);
3646
+ if (grams) {
3647
+ 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 });
3663
+ }
3664
+ } catch {
3665
+ }
3666
+ }
3630
3667
  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
3668
  } catch (err) {
3632
3669
  const msg = String(err?.message ?? err);
@@ -4153,7 +4190,7 @@ import { createHash as createHash6 } from "node:crypto";
4153
4190
  function projectedSourceIdFromScopeId(id, originKey, sourceVersion) {
4154
4191
  return "src_" + digest([id, originKey, sourceVersion]);
4155
4192
  }
4156
- var SOURCE_SCHEMA, SOURCE_ALIAS_SCHEMA, digest, SourceStore;
4193
+ var RECEIVED_INVALIDATION_SKIP, SOURCE_SCHEMA, SOURCE_ALIAS_SCHEMA, digest, SourceStore;
4157
4194
  var init_source_store = __esm({
4158
4195
  "src/mem7/core/source-store.ts"() {
4159
4196
  "use strict";
@@ -4165,6 +4202,7 @@ var init_source_store = __esm({
4165
4202
  init_watermarks();
4166
4203
  init_interpretation_impact();
4167
4204
  init_conversation_text();
4205
+ RECEIVED_INVALIDATION_SKIP = /* @__PURE__ */ new Set(["foresight"]);
4168
4206
  SOURCE_SCHEMA = `
4169
4207
  CREATE TABLE memory_scopes (
4170
4208
  scope_id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, app_id TEXT NOT NULL, project_id TEXT NOT NULL,
@@ -4346,8 +4384,8 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
4346
4384
  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
4385
  if (version !== Number(latest.version ?? 0) + 1) throw new Error("SOURCE_VERSION_CONFLICT: edits must follow the previous version");
4348
4386
  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");
4387
+ invalidateScopeDependencies(this.db, id, "sources", "source.received", { skipKinds: RECEIVED_INVALIDATION_SKIP });
4388
+ invalidateScopeDependencies(this.db, id, "context", "source.received", { skipKinds: RECEIVED_INVALIDATION_SKIP });
4351
4389
  const seq = Number(this.db.prepare("SELECT source_seq FROM memory_scopes WHERE scope_id=?").get(id).source_seq);
4352
4390
  const sourceId = projectedSourceIdFromScopeId(id, input.originKey, version);
4353
4391
  const receiptId = "rcpt_" + digest([id, sourceId]);
@@ -8747,6 +8785,7 @@ __export(topics_history_exports, {
8747
8785
  topicMatchesYear: () => topicMatchesYear,
8748
8786
  topicQueryYear: () => topicQueryYear,
8749
8787
  topicsHistoryNeedsFallback: () => topicsHistoryNeedsFallback,
8788
+ topicsHistoryRefsCurrent: () => topicsHistoryRefsCurrent,
8750
8789
  topicsHistoryRoot: () => topicsHistoryRoot,
8751
8790
  topicsScope: () => topicsScope
8752
8791
  });
@@ -8846,6 +8885,27 @@ function hasTopicsHistory(b) {
8846
8885
  db.close();
8847
8886
  return true;
8848
8887
  }
8888
+ function topicsHistoryRefsCurrent(b) {
8889
+ const db = openIndex(b);
8890
+ if (!db) return false;
8891
+ try {
8892
+ const expected = rootKey(b);
8893
+ const meta = db.prepare("SELECT value FROM metadata WHERE key='rootKey'").get();
8894
+ if (meta) return meta.value === expected;
8895
+ 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();
8896
+ return rows.every((row) => {
8897
+ try {
8898
+ return JSON.parse(row.ref).rootKey === expected;
8899
+ } catch {
8900
+ return false;
8901
+ }
8902
+ });
8903
+ } catch {
8904
+ return false;
8905
+ } finally {
8906
+ db.close();
8907
+ }
8908
+ }
8849
8909
  async function topicsHistoryNeedsFallback(b) {
8850
8910
  const cached = fallbackChecks.get(key3(b));
8851
8911
  if (cached && cached.expiresAt > Date.now()) return cached.value;
@@ -8997,6 +9057,7 @@ async function publishTopicsIndex(bundle, cleaned, b) {
8997
9057
  CREATE VIRTUAL TABLE documents USING fts5(source_path UNINDEXED,original_hash UNINDEXED,terms);
8998
9058
  CREATE VIRTUAL TABLE search USING fts5(id UNINDEXED,terms);`);
8999
9059
  db.prepare("INSERT INTO metadata VALUES(?,?)").run("binding", canonical({ scope: topicsScope(b), root: resolve7(b.topicsDir) }));
9060
+ db.prepare("INSERT INTO metadata VALUES(?,?)").run("rootKey", rootKey(b));
9000
9061
  const sourceInsert = db.prepare("INSERT INTO sources VALUES(?,?,?,?)");
9001
9062
  for (const record of snapshot.manifest.records) sourceInsert.run(record.path, record.sha256, record.bytes, record.mtimeMs);
9002
9063
  const insert = db.prepare("INSERT INTO entries VALUES(?,?,?,?,?,?,?,?,?)"), search = db.prepare("INSERT INTO search VALUES(?,?)");
@@ -11681,7 +11742,7 @@ function contentHash(text2) {
11681
11742
  function mem7Root(stateDir2) {
11682
11743
  return join14(stateDir2, "mem7");
11683
11744
  }
11684
- var STALE_ARTIFACT_FORCE_MS, SCHEMA, AGENT_SCHEMA, Mem7Store;
11745
+ var STALE_ARTIFACT_FORCE_MS, STARVATION_GRACE_MS, SCHEMA, AGENT_SCHEMA, Mem7Store;
11685
11746
  var init_store = __esm({
11686
11747
  "src/mem7/core/store.ts"() {
11687
11748
  "use strict";
@@ -11719,6 +11780,7 @@ var init_store = __esm({
11719
11780
  init_job_retention();
11720
11781
  init_retire_graph_audits();
11721
11782
  STALE_ARTIFACT_FORCE_MS = 2 * 36e5;
11783
+ STARVATION_GRACE_MS = 36e5;
11722
11784
  SCHEMA = `
11723
11785
  CREATE TABLE IF NOT EXISTS memcells (
11724
11786
  id TEXT PRIMARY KEY,
@@ -12809,7 +12871,7 @@ ${e.outcome}
12809
12871
  return this.transaction(() => {
12810
12872
  const kindFilter = options.kinds ? ` AND kind IN (${options.kinds.map(() => "?").join(",")})` : "";
12811
12873
  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"}
12874
+ 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
12875
  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
12876
  AND ((status='pending' AND next_run_at<=?)
12815
12877
  OR (status='running' AND COALESCE(lease_until,0)<=?))${kindFilter}${scopeFilter}
@@ -12829,40 +12891,48 @@ ${e.outcome}
12829
12891
  -- Cognition rebuilds its read set at claim time; delayed old work must not fence fresh judgments.
12830
12892
  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
12893
  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
- });
12894
+ 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)`;
12895
+ const select = (starved2) => {
12896
+ const sql = `${base}${starved2 ? " AND status='pending' AND next_run_at<=?" : ""}
12897
+ ORDER BY priority,next_run_at,id LIMIT ?`;
12898
+ 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];
12899
+ return this.db.prepare(sql).all(...args);
12900
+ };
12901
+ const claim = (rows) => {
12902
+ const claimedScopes = /* @__PURE__ */ new Set();
12903
+ return rows.flatMap((row) => {
12904
+ if (!this.jobProvenance.prepareForClaim(row.id, now2)) return [];
12905
+ const updated = this.db.prepare("SELECT * FROM ome_jobs WHERE id=?").get(row.id);
12906
+ if (updated.scope_id !== row.scope_id && updated.scope_id) {
12907
+ const conflict = this.db.prepare(`SELECT 1 FROM ome_jobs j WHERE j.scope_id=? AND j.id<>?
12908
+ AND (j.status='running' AND j.lease_until>? OR ? LIKE 'resource:%' AND j.id<? AND j.status IN ('pending','running')
12909
+ 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);
12910
+ if (conflict) return [];
12911
+ }
12912
+ return [updated];
12913
+ }).filter((row) => {
12914
+ if (!row.scope_id) return true;
12915
+ if (claimedScopes.has(row.scope_id)) return false;
12916
+ claimedScopes.add(row.scope_id);
12917
+ return true;
12918
+ }).map((row) => {
12919
+ const leaseToken = randomUUID9();
12920
+ this.db.prepare("UPDATE ome_jobs SET status='running',lease_token=?,lease_until=? WHERE id=?").run(leaseToken, now2 + leaseMs, row.id);
12921
+ return {
12922
+ id: row.id,
12923
+ kind: row.kind,
12924
+ payload: JSON.parse(row.payload),
12925
+ attempts: row.attempts,
12926
+ leaseToken,
12927
+ inputVersion: row.input_version,
12928
+ scopeId: row.scope_id ?? void 0,
12929
+ result: row.result_json === null ? void 0 : JSON.parse(row.result_json)
12930
+ };
12931
+ });
12932
+ };
12933
+ if (options.staleOnly) return claim(select(true));
12934
+ const starved = claim(select(true));
12935
+ return starved.length ? starved : claim(select(false));
12866
12936
  });
12867
12937
  }
12868
12938
  /** Compatibility entry point: only expired leases can be recovered. */
@@ -23568,13 +23638,18 @@ async function mem7Search(binding, args, options = {}) {
23568
23638
  const includeTopics = !!binding.topicsDir && !topicsImported(binding) && args.view !== "current" && args.known_at === void 0 && args.known_at_revision === void 0;
23569
23639
  const topics = includeTopics ? readTopicsHistory(binding, String(args.query ?? ""), { limit: 20, signal: options.signal }).catch(() => []) : Promise.resolve([]);
23570
23640
  let nativeHistory = [];
23571
- const result = JSON.parse(await searchBoundMemory(binding, args, { ...options, captureHistory: (episodes2) => {
23572
- nativeHistory = episodes2;
23573
- } }));
23641
+ const result = JSON.parse(await searchBoundMemory(binding, args, {
23642
+ ...options,
23643
+ deferRerankToMerge: includeTopics,
23644
+ captureHistory: (episodes2) => {
23645
+ nativeHistory = episodes2;
23646
+ }
23647
+ }));
23574
23648
  const hits = await topics;
23575
23649
  if (!includeTopics) return JSON.stringify(result);
23576
23650
  const { makeMem7RecallRerank: makeMem7RecallRerank2 } = await Promise.resolve().then(() => (init_findRelevantMemoriesMem7(), findRelevantMemoriesMem7_exports));
23577
23651
  const rerank = await makeMem7RecallRerank2(options.signal);
23652
+ if (!rerank) result.historySearch.rerank = "not_configured";
23578
23653
  const episodes = [...result.episodes, ...hits.map((hit) => ({
23579
23654
  id: hit.path,
23580
23655
  path: hit.path,
@@ -23707,13 +23782,13 @@ async function searchBoundMemory(binding, args, options) {
23707
23782
  let failedScopes = 0;
23708
23783
  assertActive();
23709
23784
  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;
23785
+ const topK = options.deferRerankToMerge || method === "hybrid" ? Math.min(20, Math.max(requestedTopK, 12)) : requestedTopK;
23711
23786
  const search = searchMemoryHistory(service.store, {
23712
23787
  embeddingRaw,
23713
23788
  modelRef,
23714
23789
  resolveModel,
23715
23790
  signal: options.signal,
23716
- historicalRerank: binding.topicsDir ? void 0 : { onStatus: (status) => {
23791
+ historicalRerank: options.deferRerankToMerge ? void 0 : { onStatus: (status) => {
23717
23792
  historySearch.rerank = status;
23718
23793
  } },
23719
23794
  onScopeError: () => {
@@ -23731,6 +23806,7 @@ async function searchBoundMemory(binding, args, options) {
23731
23806
  agenticStrategy: args.strategy
23732
23807
  }, request, assertActive);
23733
23808
  episodes = await search;
23809
+ if (!options.deferRerankToMerge && episodes.length > requestedTopK) episodes = episodes.slice(0, requestedTopK);
23734
23810
  assertActive();
23735
23811
  if (failedScopes) historySearch.status = episodes.length ? "partial" : "unavailable";
23736
23812
  } 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
  }
@@ -2690,6 +2690,7 @@ __export(index_exports, {
2690
2690
  topicMatchesYear: () => topicMatchesYear,
2691
2691
  topicQueryYear: () => topicQueryYear,
2692
2692
  topicsHistoryNeedsFallback: () => topicsHistoryNeedsFallback,
2693
+ topicsHistoryRefsCurrent: () => topicsHistoryRefsCurrent,
2693
2694
  topicsHistoryRoot: () => topicsHistoryRoot,
2694
2695
  topicsScope: () => topicsScope
2695
2696
  });
@@ -2789,6 +2790,27 @@ function hasTopicsHistory(b) {
2789
2790
  db.close();
2790
2791
  return true;
2791
2792
  }
2793
+ function topicsHistoryRefsCurrent(b) {
2794
+ const db = openIndex(b);
2795
+ if (!db) return false;
2796
+ try {
2797
+ const expected = rootKey(b);
2798
+ const meta = db.prepare("SELECT value FROM metadata WHERE key='rootKey'").get();
2799
+ if (meta) return meta.value === expected;
2800
+ 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();
2801
+ return rows.every((row) => {
2802
+ try {
2803
+ return JSON.parse(row.ref).rootKey === expected;
2804
+ } catch {
2805
+ return false;
2806
+ }
2807
+ });
2808
+ } catch {
2809
+ return false;
2810
+ } finally {
2811
+ db.close();
2812
+ }
2813
+ }
2792
2814
  async function topicsHistoryNeedsFallback(b) {
2793
2815
  const cached = fallbackChecks.get(key(b));
2794
2816
  if (cached && cached.expiresAt > Date.now()) return cached.value;
@@ -2940,6 +2962,7 @@ async function publishTopicsIndex(bundle, cleaned, b) {
2940
2962
  CREATE VIRTUAL TABLE documents USING fts5(source_path UNINDEXED,original_hash UNINDEXED,terms);
2941
2963
  CREATE VIRTUAL TABLE search USING fts5(id UNINDEXED,terms);`);
2942
2964
  db.prepare("INSERT INTO metadata VALUES(?,?)").run("binding", canonical({ scope: topicsScope(b), root: resolve6(b.topicsDir) }));
2965
+ db.prepare("INSERT INTO metadata VALUES(?,?)").run("rootKey", rootKey(b));
2943
2966
  const sourceInsert = db.prepare("INSERT INTO sources VALUES(?,?,?,?)");
2944
2967
  for (const record of snapshot.manifest.records) sourceInsert.run(record.path, record.sha256, record.bytes, record.mtimeMs);
2945
2968
  const insert = db.prepare("INSERT INTO entries VALUES(?,?,?,?,?,?,?,?,?)"), search = db.prepare("INSERT INTO search VALUES(?,?)");
@@ -3866,8 +3889,9 @@ function invalidateDerivedDependencies(db, event) {
3866
3889
  }
3867
3890
  return invalidateChildren(db, event.scopeId, pending2, event.kind);
3868
3891
  }
3869
- function invalidateScopeDependencies(db, scope, parent, reason) {
3870
- 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);
3892
+ function invalidateScopeDependencies(db, scope, parent, reason, options = {}) {
3893
+ 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);
3894
+ if (options.skipKinds?.size) children = children.filter((child) => !options.skipKinds.has(child.child_kind));
3871
3895
  invalidateChildren(db, scope, children, reason);
3872
3896
  }
3873
3897
  function invalidateChildren(db, scope, pending2, reason) {
@@ -3887,7 +3911,7 @@ function invalidateChildren(db, scope, pending2, reason) {
3887
3911
  }
3888
3912
  const state = child.deleted ? "deleted" : "needs_revalidation";
3889
3913
  db.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
3890
- 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);
3914
+ 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);
3891
3915
  result.push(child.child_id);
3892
3916
  pending2.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" })));
3893
3917
  }
@@ -4307,6 +4331,12 @@ function loadArrow() {
4307
4331
  }
4308
4332
  return arrowPromise;
4309
4333
  }
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
+ }
4310
4340
  function buildSchemas(arrow) {
4311
4341
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
4312
4342
  const commonFields = () => [
@@ -4403,7 +4433,7 @@ function textColumnOf(kind) {
4403
4433
  return "fact";
4404
4434
  }
4405
4435
  }
4406
- var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
4436
+ var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, BM25_TEXT_FIELDS, sqlLiteral, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
4407
4437
  var init_vector_store = __esm({
4408
4438
  "src/mem7/core/vector-store.ts"() {
4409
4439
  "use strict";
@@ -4434,6 +4464,14 @@ var init_vector_store = __esm({
4434
4464
  agent_case: ["task_intent_tokens", "approach_tokens"],
4435
4465
  agent_skill: ["description_tokens", "content_tokens"]
4436
4466
  };
4467
+ BM25_TEXT_FIELDS = {
4468
+ foresight: ["foresight", "evidence"],
4469
+ episode: ["episode"],
4470
+ atomic_fact: ["fact"],
4471
+ agent_case: ["task_intent", "approach"],
4472
+ agent_skill: ["description", "content"]
4473
+ };
4474
+ sqlLiteral = (value) => value.replace(/'/g, "''");
4437
4475
  RRF_K = 60;
4438
4476
  warnedFts = /* @__PURE__ */ new Set();
4439
4477
  warnedVecIdx = /* @__PURE__ */ new Set();
@@ -5031,6 +5069,28 @@ var init_vector_store = __esm({
5031
5069
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
5032
5070
  }
5033
5071
  }
5072
+ const grams = shortCjkQueryBigrams(queryText);
5073
+ if (grams) {
5074
+ 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 });
5090
+ }
5091
+ } catch {
5092
+ }
5093
+ }
5034
5094
  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) }));
5035
5095
  } catch (err) {
5036
5096
  const msg = String(err?.message ?? err);
@@ -5555,7 +5615,7 @@ import { createHash as createHash8 } from "node:crypto";
5555
5615
  function projectedSourceIdFromScopeId(id, originKey, sourceVersion) {
5556
5616
  return "src_" + digest2([id, originKey, sourceVersion]);
5557
5617
  }
5558
- var SOURCE_SCHEMA, SOURCE_ALIAS_SCHEMA, digest2, SourceStore;
5618
+ var RECEIVED_INVALIDATION_SKIP, SOURCE_SCHEMA, SOURCE_ALIAS_SCHEMA, digest2, SourceStore;
5559
5619
  var init_source_store = __esm({
5560
5620
  "src/mem7/core/source-store.ts"() {
5561
5621
  "use strict";
@@ -5567,6 +5627,7 @@ var init_source_store = __esm({
5567
5627
  init_watermarks();
5568
5628
  init_interpretation_impact();
5569
5629
  init_conversation_text();
5630
+ RECEIVED_INVALIDATION_SKIP = /* @__PURE__ */ new Set(["foresight"]);
5570
5631
  SOURCE_SCHEMA = `
5571
5632
  CREATE TABLE memory_scopes (
5572
5633
  scope_id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, app_id TEXT NOT NULL, project_id TEXT NOT NULL,
@@ -5748,8 +5809,8 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
5748
5809
  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");
5749
5810
  if (version !== Number(latest.version ?? 0) + 1) throw new Error("SOURCE_VERSION_CONFLICT: edits must follow the previous version");
5750
5811
  this.db.prepare("UPDATE memory_scopes SET source_seq=source_seq+1,context_revision=context_revision+1 WHERE scope_id=?").run(id);
5751
- invalidateScopeDependencies(this.db, id, "sources", "source.received");
5752
- invalidateScopeDependencies(this.db, id, "context", "source.received");
5812
+ invalidateScopeDependencies(this.db, id, "sources", "source.received", { skipKinds: RECEIVED_INVALIDATION_SKIP });
5813
+ invalidateScopeDependencies(this.db, id, "context", "source.received", { skipKinds: RECEIVED_INVALIDATION_SKIP });
5753
5814
  const seq = Number(this.db.prepare("SELECT source_seq FROM memory_scopes WHERE scope_id=?").get(id).source_seq);
5754
5815
  const sourceId = projectedSourceIdFromScopeId(id, input.originKey, version);
5755
5816
  const receiptId = "rcpt_" + digest2([id, sourceId]);
@@ -10985,7 +11046,7 @@ function contentHash(text2) {
10985
11046
  function mem7Root(stateDir) {
10986
11047
  return join18(stateDir, "mem7");
10987
11048
  }
10988
- var STALE_ARTIFACT_FORCE_MS, SCHEMA, AGENT_SCHEMA, Mem7Store;
11049
+ var STALE_ARTIFACT_FORCE_MS, STARVATION_GRACE_MS, SCHEMA, AGENT_SCHEMA, Mem7Store;
10989
11050
  var init_store = __esm({
10990
11051
  "src/mem7/core/store.ts"() {
10991
11052
  "use strict";
@@ -11023,6 +11084,7 @@ var init_store = __esm({
11023
11084
  init_job_retention();
11024
11085
  init_retire_graph_audits();
11025
11086
  STALE_ARTIFACT_FORCE_MS = 2 * 36e5;
11087
+ STARVATION_GRACE_MS = 36e5;
11026
11088
  SCHEMA = `
11027
11089
  CREATE TABLE IF NOT EXISTS memcells (
11028
11090
  id TEXT PRIMARY KEY,
@@ -12113,7 +12175,7 @@ ${e.outcome}
12113
12175
  return this.transaction(() => {
12114
12176
  const kindFilter = options.kinds ? ` AND kind IN (${options.kinds.map(() => "?").join(",")})` : "";
12115
12177
  const scopeFilter = options.scopeId !== void 0 ? " AND scope_id=?" : "";
12116
- 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"}
12178
+ 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"}
12117
12179
  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)
12118
12180
  AND ((status='pending' AND next_run_at<=?)
12119
12181
  OR (status='running' AND COALESCE(lease_until,0)<=?))${kindFilter}${scopeFilter}
@@ -12133,40 +12195,48 @@ ${e.outcome}
12133
12195
  -- Cognition rebuilds its read set at claim time; delayed old work must not fence fresh judgments.
12134
12196
  AND (kind IN ('social.interpret','source.interpret','relationship.cognition') OR scope_id NOT LIKE 'resource:%' OR NOT EXISTS (SELECT 1 FROM ome_jobs prior
12135
12197
  WHERE prior.scope_id=j.scope_id AND prior.id<j.id AND prior.status IN ('pending','running')
12136
- 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)
12137
- -- Retrying an old deferred job must not reserve the next stage budget.
12138
- -- Boundary/resource predecessor predicates above still enforce ordering.
12139
- ORDER BY priority,next_run_at,id LIMIT ?`).all(now2, now2, ...options.kinds ?? [], ...options.scopeId !== void 0 ? [options.scopeId] : [], now2, limit);
12140
- const claimedScopes = /* @__PURE__ */ new Set();
12141
- return rows.flatMap((row) => {
12142
- if (!this.jobProvenance.prepareForClaim(row.id, now2)) return [];
12143
- const updated = this.db.prepare("SELECT * FROM ome_jobs WHERE id=?").get(row.id);
12144
- if (updated.scope_id !== row.scope_id && updated.scope_id) {
12145
- const conflict = this.db.prepare(`SELECT 1 FROM ome_jobs j WHERE j.scope_id=? AND j.id<>?
12146
- AND (j.status='running' AND j.lease_until>? OR ? LIKE 'resource:%' AND j.id<? AND j.status IN ('pending','running')
12147
- 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);
12148
- if (conflict) return [];
12149
- }
12150
- return [updated];
12151
- }).filter((row) => {
12152
- if (!row.scope_id) return true;
12153
- if (claimedScopes.has(row.scope_id)) return false;
12154
- claimedScopes.add(row.scope_id);
12155
- return true;
12156
- }).map((row) => {
12157
- const leaseToken = randomUUID13();
12158
- this.db.prepare("UPDATE ome_jobs SET status='running',lease_token=?,lease_until=? WHERE id=?").run(leaseToken, now2 + leaseMs, row.id);
12159
- return {
12160
- id: row.id,
12161
- kind: row.kind,
12162
- payload: JSON.parse(row.payload),
12163
- attempts: row.attempts,
12164
- leaseToken,
12165
- inputVersion: row.input_version,
12166
- scopeId: row.scope_id ?? void 0,
12167
- result: row.result_json === null ? void 0 : JSON.parse(row.result_json)
12168
- };
12169
- });
12198
+ 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)`;
12199
+ const select = (starved2) => {
12200
+ const sql = `${base}${starved2 ? " AND status='pending' AND next_run_at<=?" : ""}
12201
+ ORDER BY priority,next_run_at,id LIMIT ?`;
12202
+ 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];
12203
+ return this.db.prepare(sql).all(...args);
12204
+ };
12205
+ const claim = (rows) => {
12206
+ const claimedScopes = /* @__PURE__ */ new Set();
12207
+ return rows.flatMap((row) => {
12208
+ if (!this.jobProvenance.prepareForClaim(row.id, now2)) return [];
12209
+ const updated = this.db.prepare("SELECT * FROM ome_jobs WHERE id=?").get(row.id);
12210
+ if (updated.scope_id !== row.scope_id && updated.scope_id) {
12211
+ const conflict = this.db.prepare(`SELECT 1 FROM ome_jobs j WHERE j.scope_id=? AND j.id<>?
12212
+ AND (j.status='running' AND j.lease_until>? OR ? LIKE 'resource:%' AND j.id<? AND j.status IN ('pending','running')
12213
+ 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);
12214
+ if (conflict) return [];
12215
+ }
12216
+ return [updated];
12217
+ }).filter((row) => {
12218
+ if (!row.scope_id) return true;
12219
+ if (claimedScopes.has(row.scope_id)) return false;
12220
+ claimedScopes.add(row.scope_id);
12221
+ return true;
12222
+ }).map((row) => {
12223
+ const leaseToken = randomUUID13();
12224
+ this.db.prepare("UPDATE ome_jobs SET status='running',lease_token=?,lease_until=? WHERE id=?").run(leaseToken, now2 + leaseMs, row.id);
12225
+ return {
12226
+ id: row.id,
12227
+ kind: row.kind,
12228
+ payload: JSON.parse(row.payload),
12229
+ attempts: row.attempts,
12230
+ leaseToken,
12231
+ inputVersion: row.input_version,
12232
+ scopeId: row.scope_id ?? void 0,
12233
+ result: row.result_json === null ? void 0 : JSON.parse(row.result_json)
12234
+ };
12235
+ });
12236
+ };
12237
+ if (options.staleOnly) return claim(select(true));
12238
+ const starved = claim(select(true));
12239
+ return starved.length ? starved : claim(select(false));
12170
12240
  });
12171
12241
  }
12172
12242
  /** Compatibility entry point: only expired leases can be recovered. */
@@ -13549,11 +13619,13 @@ function secretsCandidates(stateDir, configName) {
13549
13619
  join(stateDir, "configs", `.env.${configName}`),
13550
13620
  join(stateDir, "configs", ".env")
13551
13621
  ];
13552
- if (isDefaultStateDir(stateDir)) return [shared, ...inState];
13622
+ const travel = join(stateDir, "secrets.env");
13623
+ if (isDefaultStateDir(stateDir)) return [shared, ...inState, travel];
13553
13624
  return [
13554
13625
  join(secretsHome(), ".engine7-secrets", `${configName}-${stateKey(stateDir)}.env`),
13555
13626
  shared,
13556
- ...inState
13627
+ ...inState,
13628
+ travel
13557
13629
  ];
13558
13630
  }
13559
13631
  function readSecretsEntries(stateDir, configName) {
@@ -13951,7 +14023,7 @@ async function runTopicsBackground(options) {
13951
14023
  } catch {
13952
14024
  }
13953
14025
  }
13954
- if (hasTopicsHistory(b)) {
14026
+ if (hasTopicsHistory(b) && topicsHistoryRefsCurrent(b)) {
13955
14027
  topicsBackgroundStatus(b, { phase: "complete", sources: records.length, mem7StartDate: before, version: current2.version, ...droppedStatus() });
13956
14028
  const embedded = await augmentVectors(records.length);
13957
14029
  return { status: "complete", version: current2.version, drained: embedded === 0 };
@@ -3836,7 +3836,7 @@ function invalidateChildren(db, scope, pending, reason) {
3836
3836
  }
3837
3837
  const state2 = child.deleted ? "deleted" : "needs_revalidation";
3838
3838
  db.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
3839
- WHERE scope_id=? AND child_kind=? AND child_id=? AND state IN ('current','needs_revalidation','invalid') AND state<>?`).run(state2, reason, (/* @__PURE__ */ new Date()).toISOString(), scope, child.child_kind, child.child_id, state2);
3839
+ WHERE scope_id=? AND child_kind=? AND child_id=? AND state IN ('current','needs_revalidation') AND state<>?`).run(state2, reason, (/* @__PURE__ */ new Date()).toISOString(), scope, child.child_kind, child.child_id, state2);
3840
3840
  result.push(child.child_id);
3841
3841
  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" })));
3842
3842
  }