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.
@@ -3458,7 +3458,7 @@ function invalidateChildren(db, scope, pending, reason) {
3458
3458
  }
3459
3459
  const state = child.deleted ? "deleted" : "needs_revalidation";
3460
3460
  db.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
3461
- 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);
3461
+ 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);
3462
3462
  result.push(child.child_id);
3463
3463
  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" })));
3464
3464
  }
@@ -2750,7 +2750,7 @@ function invalidateChildren(db, scope, pending, reason) {
2750
2750
  }
2751
2751
  const state = child.deleted ? "deleted" : "needs_revalidation";
2752
2752
  db.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
2753
- 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);
2753
+ 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);
2754
2754
  result.push(child.child_id);
2755
2755
  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" })));
2756
2756
  }
@@ -1800,6 +1800,13 @@ function tokenize(text2) {
1800
1800
  function tokenizeToField(text2) {
1801
1801
  return tokenize(text2).join(" ");
1802
1802
  }
1803
+ function cjkBigrams(text2) {
1804
+ const out = [];
1805
+ for (const seg of String(text2 ?? "").match(/[\u4e00-\u9fff]{2,}/g) ?? []) {
1806
+ for (let i = 0; i + 1 < seg.length; i++) out.push(seg.slice(i, i + 2));
1807
+ }
1808
+ return out;
1809
+ }
1803
1810
  var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
1804
1811
  var init_tokenizer = __esm({
1805
1812
  "src/mem7/core/tokenizer.ts"() {
@@ -4734,8 +4741,9 @@ function invalidateDerivedDependencies(db, event) {
4734
4741
  }
4735
4742
  return invalidateChildren(db, event.scopeId, pending, event.kind);
4736
4743
  }
4737
- function invalidateScopeDependencies(db, scope, parent, reason) {
4738
- 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);
4744
+ function invalidateScopeDependencies(db, scope, parent, reason, options = {}) {
4745
+ 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);
4746
+ if (options.skipKinds?.size) children = children.filter((child) => !options.skipKinds.has(child.child_kind));
4739
4747
  invalidateChildren(db, scope, children, reason);
4740
4748
  }
4741
4749
  function invalidateChildren(db, scope, pending, reason) {
@@ -4755,7 +4763,7 @@ function invalidateChildren(db, scope, pending, reason) {
4755
4763
  }
4756
4764
  const state2 = child.deleted ? "deleted" : "needs_revalidation";
4757
4765
  db.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
4758
- 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);
4766
+ 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);
4759
4767
  result.push(child.child_id);
4760
4768
  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" })));
4761
4769
  }
@@ -5387,6 +5395,7 @@ function isConversationScaffold(text2) {
5387
5395
  }
5388
5396
 
5389
5397
  // src/mem7/core/source-store.ts
5398
+ var RECEIVED_INVALIDATION_SKIP = /* @__PURE__ */ new Set(["foresight"]);
5390
5399
  var SOURCE_SCHEMA = `
5391
5400
  CREATE TABLE memory_scopes (
5392
5401
  scope_id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, app_id TEXT NOT NULL, project_id TEXT NOT NULL,
@@ -5571,8 +5580,8 @@ var SourceStore = class {
5571
5580
  if (this.db.prepare("SELECT 1 FROM memory_sources WHERE scope_id=? AND origin_key=? AND interpretation_status='deleted'").get(id2, input.originKey)) throw new Error("DELETED_EVIDENCE");
5572
5581
  if (version !== Number(latest.version ?? 0) + 1) throw new Error("SOURCE_VERSION_CONFLICT: edits must follow the previous version");
5573
5582
  this.db.prepare("UPDATE memory_scopes SET source_seq=source_seq+1,context_revision=context_revision+1 WHERE scope_id=?").run(id2);
5574
- invalidateScopeDependencies(this.db, id2, "sources", "source.received");
5575
- invalidateScopeDependencies(this.db, id2, "context", "source.received");
5583
+ invalidateScopeDependencies(this.db, id2, "sources", "source.received", { skipKinds: RECEIVED_INVALIDATION_SKIP });
5584
+ invalidateScopeDependencies(this.db, id2, "context", "source.received", { skipKinds: RECEIVED_INVALIDATION_SKIP });
5576
5585
  const seq = Number(this.db.prepare("SELECT source_seq FROM memory_scopes WHERE scope_id=?").get(id2).source_seq);
5577
5586
  const sourceId = projectedSourceIdFromScopeId(id2, input.originKey, version);
5578
5587
  const receiptId = "rcpt_" + digest([id2, sourceId]);
@@ -6931,6 +6940,20 @@ var BM25_FIELDS = {
6931
6940
  agent_case: ["task_intent_tokens", "approach_tokens"],
6932
6941
  agent_skill: ["description_tokens", "content_tokens"]
6933
6942
  };
6943
+ var BM25_TEXT_FIELDS = {
6944
+ foresight: ["foresight", "evidence"],
6945
+ episode: ["episode"],
6946
+ atomic_fact: ["fact"],
6947
+ agent_case: ["task_intent", "approach"],
6948
+ agent_skill: ["description", "content"]
6949
+ };
6950
+ function shortCjkQueryBigrams(text2) {
6951
+ const chars = (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
6952
+ if (!chars || chars > 6) return null;
6953
+ const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
6954
+ return grams.length ? grams : null;
6955
+ }
6956
+ var sqlLiteral = (value2) => value2.replace(/'/g, "''");
6934
6957
  var RRF_K = 60;
6935
6958
  var warnedFts = /* @__PURE__ */ new Set();
6936
6959
  var warnedVecIdx = /* @__PURE__ */ new Set();
@@ -7624,6 +7647,28 @@ var Mem7VectorStore = class {
7624
7647
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
7625
7648
  }
7626
7649
  }
7650
+ const grams = shortCjkQueryBigrams(queryText);
7651
+ if (grams) {
7652
+ try {
7653
+ const textCols = BM25_TEXT_FIELDS[kind];
7654
+ const expr = textCols.map((col) => `(${grams.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
7655
+ const where2 = compileFilter(opts.filter);
7656
+ const extra = await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(topK * 3).toArray();
7657
+ const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
7658
+ for (const r of extra) {
7659
+ const rid = String(r.id ?? "");
7660
+ if (!rid) continue;
7661
+ const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
7662
+ const matched = grams.filter((gram) => text2.includes(gram)).length;
7663
+ if (!matched) continue;
7664
+ const score = maxScore + matched / grams.length;
7665
+ const cur = best.get(rid);
7666
+ if (cur) cur._score = Math.max(Number(cur._score ?? 0), score);
7667
+ else best.set(rid, { ...r, _score: score });
7668
+ }
7669
+ } catch {
7670
+ }
7671
+ }
7627
7672
  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) }));
7628
7673
  } catch (err) {
7629
7674
  const msg = String(err?.message ?? err);
@@ -10408,6 +10453,7 @@ function mem7Root(stateDir) {
10408
10453
  return join15(stateDir, "mem7");
10409
10454
  }
10410
10455
  var STALE_ARTIFACT_FORCE_MS = 2 * 36e5;
10456
+ var STARVATION_GRACE_MS = 36e5;
10411
10457
  var SCHEMA = `
10412
10458
  CREATE TABLE IF NOT EXISTS memcells (
10413
10459
  id TEXT PRIMARY KEY,
@@ -11498,7 +11544,7 @@ ${e.outcome}
11498
11544
  return this.transaction(() => {
11499
11545
  const kindFilter = options.kinds ? ` AND kind IN (${options.kinds.map(() => "?").join(",")})` : "";
11500
11546
  const scopeFilter = options.scopeId !== void 0 ? " AND scope_id=?" : "";
11501
- 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"}
11547
+ 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"}
11502
11548
  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)
11503
11549
  AND ((status='pending' AND next_run_at<=?)
11504
11550
  OR (status='running' AND COALESCE(lease_until,0)<=?))${kindFilter}${scopeFilter}
@@ -11518,40 +11564,48 @@ ${e.outcome}
11518
11564
  -- Cognition rebuilds its read set at claim time; delayed old work must not fence fresh judgments.
11519
11565
  AND (kind IN ('social.interpret','source.interpret','relationship.cognition') OR scope_id NOT LIKE 'resource:%' OR NOT EXISTS (SELECT 1 FROM ome_jobs prior
11520
11566
  WHERE prior.scope_id=j.scope_id AND prior.id<j.id AND prior.status IN ('pending','running')
11521
- 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)
11522
- -- Retrying an old deferred job must not reserve the next stage budget.
11523
- -- Boundary/resource predecessor predicates above still enforce ordering.
11524
- ORDER BY priority,next_run_at,id LIMIT ?`).all(now2, now2, ...options.kinds ?? [], ...options.scopeId !== void 0 ? [options.scopeId] : [], now2, limit);
11525
- const claimedScopes = /* @__PURE__ */ new Set();
11526
- return rows.flatMap((row) => {
11527
- if (!this.jobProvenance.prepareForClaim(row.id, now2)) return [];
11528
- const updated = this.db.prepare("SELECT * FROM ome_jobs WHERE id=?").get(row.id);
11529
- if (updated.scope_id !== row.scope_id && updated.scope_id) {
11530
- const conflict = this.db.prepare(`SELECT 1 FROM ome_jobs j WHERE j.scope_id=? AND j.id<>?
11531
- AND (j.status='running' AND j.lease_until>? OR ? LIKE 'resource:%' AND j.id<? AND j.status IN ('pending','running')
11532
- 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);
11533
- if (conflict) return [];
11534
- }
11535
- return [updated];
11536
- }).filter((row) => {
11537
- if (!row.scope_id) return true;
11538
- if (claimedScopes.has(row.scope_id)) return false;
11539
- claimedScopes.add(row.scope_id);
11540
- return true;
11541
- }).map((row) => {
11542
- const leaseToken = randomUUID9();
11543
- this.db.prepare("UPDATE ome_jobs SET status='running',lease_token=?,lease_until=? WHERE id=?").run(leaseToken, now2 + leaseMs, row.id);
11544
- return {
11545
- id: row.id,
11546
- kind: row.kind,
11547
- payload: JSON.parse(row.payload),
11548
- attempts: row.attempts,
11549
- leaseToken,
11550
- inputVersion: row.input_version,
11551
- scopeId: row.scope_id ?? void 0,
11552
- result: row.result_json === null ? void 0 : JSON.parse(row.result_json)
11553
- };
11554
- });
11567
+ 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)`;
11568
+ const select = (starved2) => {
11569
+ const sql = `${base}${starved2 ? " AND status='pending' AND next_run_at<=?" : ""}
11570
+ ORDER BY priority,next_run_at,id LIMIT ?`;
11571
+ 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];
11572
+ return this.db.prepare(sql).all(...args);
11573
+ };
11574
+ const claim = (rows) => {
11575
+ const claimedScopes = /* @__PURE__ */ new Set();
11576
+ return rows.flatMap((row) => {
11577
+ if (!this.jobProvenance.prepareForClaim(row.id, now2)) return [];
11578
+ const updated = this.db.prepare("SELECT * FROM ome_jobs WHERE id=?").get(row.id);
11579
+ if (updated.scope_id !== row.scope_id && updated.scope_id) {
11580
+ const conflict = this.db.prepare(`SELECT 1 FROM ome_jobs j WHERE j.scope_id=? AND j.id<>?
11581
+ AND (j.status='running' AND j.lease_until>? OR ? LIKE 'resource:%' AND j.id<? AND j.status IN ('pending','running')
11582
+ 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);
11583
+ if (conflict) return [];
11584
+ }
11585
+ return [updated];
11586
+ }).filter((row) => {
11587
+ if (!row.scope_id) return true;
11588
+ if (claimedScopes.has(row.scope_id)) return false;
11589
+ claimedScopes.add(row.scope_id);
11590
+ return true;
11591
+ }).map((row) => {
11592
+ const leaseToken = randomUUID9();
11593
+ this.db.prepare("UPDATE ome_jobs SET status='running',lease_token=?,lease_until=? WHERE id=?").run(leaseToken, now2 + leaseMs, row.id);
11594
+ return {
11595
+ id: row.id,
11596
+ kind: row.kind,
11597
+ payload: JSON.parse(row.payload),
11598
+ attempts: row.attempts,
11599
+ leaseToken,
11600
+ inputVersion: row.input_version,
11601
+ scopeId: row.scope_id ?? void 0,
11602
+ result: row.result_json === null ? void 0 : JSON.parse(row.result_json)
11603
+ };
11604
+ });
11605
+ };
11606
+ if (options.staleOnly) return claim(select(true));
11607
+ const starved = claim(select(true));
11608
+ return starved.length ? starved : claim(select(false));
11555
11609
  });
11556
11610
  }
11557
11611
  /** Compatibility entry point: only expired leases can be recovered. */
@@ -2833,11 +2833,13 @@ function secretsCandidates(stateDir, configName) {
2833
2833
  join4(stateDir, "configs", `.env.${configName}`),
2834
2834
  join4(stateDir, "configs", ".env")
2835
2835
  ];
2836
- if (isDefaultStateDir(stateDir)) return [shared, ...inState];
2836
+ const travel = join4(stateDir, "secrets.env");
2837
+ if (isDefaultStateDir(stateDir)) return [shared, ...inState, travel];
2837
2838
  return [
2838
2839
  join4(secretsHome(), ".engine7-secrets", `${configName}-${stateKey(stateDir)}.env`),
2839
2840
  shared,
2840
- ...inState
2841
+ ...inState,
2842
+ travel
2841
2843
  ];
2842
2844
  }
2843
2845
  function readSecretsEntries(stateDir, configName) {