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.
@@ -19,14 +19,14 @@ var __export = (target, all) => {
19
19
  import { randomUUID, verify } from "node:crypto";
20
20
  import { constants, closeSync, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync } from "node:fs";
21
21
  import { basename, dirname, join, resolve } from "node:path";
22
- function assertPrivateDirectory(path22) {
23
- const stat3 = lstatSync(path22);
22
+ function assertPrivateDirectory(path23) {
23
+ const stat3 = lstatSync(path23);
24
24
  if (!stat3.isDirectory() || stat3.isSymbolicLink() || process.platform !== "win32" && (stat3.uid !== process.getuid() || stat3.mode & 63)) throw new Error("TRAVEL_PRIVATE_CONTROL_REQUIRED");
25
25
  }
26
- function readPrivateFile(path22, maximum) {
27
- const before = lstatSync(path22);
26
+ function readPrivateFile(path23, maximum) {
27
+ const before = lstatSync(path23);
28
28
  if (!before.isFile() || before.isSymbolicLink() || process.platform !== "win32" && (before.uid !== process.getuid() || before.mode & 63)) throw new Error("TRAVEL_PRIVATE_CONTROL_REQUIRED");
29
- const fd = openSync(path22, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
29
+ const fd = openSync(path23, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
30
30
  try {
31
31
  if (fstatSync(fd).size > maximum) throw new Error("TRAVEL_INVALID_CONTROL");
32
32
  return readFileSync(fd);
@@ -34,12 +34,12 @@ function readPrivateFile(path22, maximum) {
34
34
  closeSync(fd);
35
35
  }
36
36
  }
37
- function writeControl(path22, value) {
38
- const temporary = path22 + "." + randomUUID() + ".tmp";
37
+ function writeControl(path23, value) {
38
+ const temporary = path23 + "." + randomUUID() + ".tmp";
39
39
  writeFileSync(temporary, JSON.stringify(value), { mode: 384, flag: "wx", flush: true });
40
- renameSync(temporary, path22);
40
+ renameSync(temporary, path23);
41
41
  if (process.platform !== "win32") {
42
- const fd = openSync(dirname(path22), "r");
42
+ const fd = openSync(dirname(path23), "r");
43
43
  try {
44
44
  fsyncSync(fd);
45
45
  } finally {
@@ -1127,9 +1127,9 @@ function assertPrivateStat(stat3, directory2) {
1127
1127
  if ((directory2 ? !stat3.isDirectory() : !stat3.isFile()) || process.platform !== "win32" && ((stat3.mode & 63) !== 0 || stat3.uid !== process.getuid?.()))
1128
1128
  throw new Error("KEY_SERVICE_PRIVATE_PATH_REQUIRED");
1129
1129
  }
1130
- function readPrivateFile2(path22, maximumBytes = 65536) {
1131
- assertPrivateStat(lstatSync3(path22), false);
1132
- const fd = openSync3(path22, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
1130
+ function readPrivateFile2(path23, maximumBytes = 65536) {
1131
+ assertPrivateStat(lstatSync3(path23), false);
1132
+ const fd = openSync3(path23, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
1133
1133
  try {
1134
1134
  const stat3 = fstatSync2(fd);
1135
1135
  assertPrivateStat(stat3, false);
@@ -1159,23 +1159,23 @@ import {
1159
1159
  mkdirSync as mkdirSync4
1160
1160
  } from "node:fs";
1161
1161
  import { join as join3, dirname as dirname2, resolve as resolve2 } from "node:path";
1162
- function assertPrivateDirectory2(path22) {
1163
- const info = lstatSync4(path22);
1164
- if (!info.isDirectory() || info.isSymbolicLink() || realpathSync2(path22) !== resolve2(path22) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
1162
+ function assertPrivateDirectory2(path23) {
1163
+ const info = lstatSync4(path23);
1164
+ if (!info.isDirectory() || info.isSymbolicLink() || realpathSync2(path23) !== resolve2(path23) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
1165
1165
  throw new Error("PUBLICATION_PRIVATE_DIRECTORY_REQUIRED");
1166
1166
  }
1167
- function syncDir(path22) {
1167
+ function syncDir(path23) {
1168
1168
  if (process.platform === "win32") return;
1169
- const fd = openSync4(path22, constants4.O_RDONLY);
1169
+ const fd = openSync4(path23, constants4.O_RDONLY);
1170
1170
  try {
1171
1171
  fsyncSync3(fd);
1172
1172
  } finally {
1173
1173
  closeSync4(fd);
1174
1174
  }
1175
1175
  }
1176
- function preparePrivateDirectory(path22) {
1176
+ function preparePrivateDirectory(path23) {
1177
1177
  const missing = [];
1178
- let parent = resolve2(path22);
1178
+ let parent = resolve2(path23);
1179
1179
  for (; ; ) {
1180
1180
  try {
1181
1181
  lstatSync4(parent);
@@ -1196,7 +1196,7 @@ function preparePrivateDirectory(path22) {
1196
1196
  assertPrivateDirectory2(directory2);
1197
1197
  syncDir(dirname2(directory2));
1198
1198
  }
1199
- assertPrivateDirectory2(path22);
1199
+ assertPrivateDirectory2(path23);
1200
1200
  }
1201
1201
  var PUBLICATION_CHUNK_BYTES, MAGIC, INLINE_BYTES, noFollow;
1202
1202
  var init_publication_objects = __esm({
@@ -1316,6 +1316,8 @@ __export(tokenizer_exports, {
1316
1316
  DEFAULT_STOPWORDS: () => DEFAULT_STOPWORDS,
1317
1317
  MIN_TOKEN_LENGTH: () => MIN_TOKEN_LENGTH,
1318
1318
  cjkBigrams: () => cjkBigrams,
1319
+ literalQueryNeedles: () => literalQueryNeedles,
1320
+ queryBigramNeedles: () => queryBigramNeedles,
1319
1321
  tokenize: () => tokenize,
1320
1322
  tokenizeCjk: () => tokenizeCjk,
1321
1323
  tokenizeToField: () => tokenizeToField
@@ -1350,7 +1352,22 @@ function cjkBigrams(text2) {
1350
1352
  function tokenizeCjk(text2) {
1351
1353
  return [...tokenize(text2), ...cjkBigrams(text2)];
1352
1354
  }
1353
- var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba;
1355
+ function invisibleCjkNeedles(candidates) {
1356
+ return [...new Set(candidates.map((token) => token.trim()))].filter((token) => /^[\u4e00-\u9fff]{2,}$/.test(token) && tokenize(token).length === 0).slice(0, 8);
1357
+ }
1358
+ function literalQueryNeedles(text2) {
1359
+ const chars = shortCjkCharCount(text2);
1360
+ if (!chars || chars > 6) return null;
1361
+ const names = invisibleCjkNeedles(engine().cut(String(text2 ?? ""), true));
1362
+ return names.length ? names : queryBigramNeedles(text2);
1363
+ }
1364
+ function queryBigramNeedles(text2) {
1365
+ const chars = shortCjkCharCount(text2);
1366
+ if (!chars || chars > 6) return null;
1367
+ const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
1368
+ return grams.length ? grams : null;
1369
+ }
1370
+ var DEFAULT_STOPWORDS, MIN_TOKEN_LENGTH, jieba, shortCjkCharCount;
1354
1371
  var init_tokenizer = __esm({
1355
1372
  "src/mem7/core/tokenizer.ts"() {
1356
1373
  "use strict";
@@ -1423,6 +1440,7 @@ var init_tokenizer = __esm({
1423
1440
  ]);
1424
1441
  MIN_TOKEN_LENGTH = 2;
1425
1442
  jieba = null;
1443
+ shortCjkCharCount = (text2) => (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
1426
1444
  }
1427
1445
  });
1428
1446
 
@@ -1647,14 +1665,14 @@ var init_live = __esm({
1647
1665
  }
1648
1666
  /** 把改动写回 config 文件对应段(找不到文件路径则只内存生效)。返回是否真的落盘。 */
1649
1667
  async persistToFile(dotPath, val, atomic2 = false) {
1650
- const fs23 = await import("node:fs");
1668
+ const fs24 = await import("node:fs");
1651
1669
  const cfgPath = this.current?._configFilePath;
1652
- if (!cfgPath || !fs23.existsSync(cfgPath)) {
1670
+ if (!cfgPath || !fs24.existsSync(cfgPath)) {
1653
1671
  console.warn(`[liveConfig] set: no config file path, in-memory only (${dotPath})`);
1654
1672
  return false;
1655
1673
  }
1656
1674
  try {
1657
- const raw = JSON.parse(fs23.readFileSync(cfgPath, "utf-8"));
1675
+ const raw = JSON.parse(fs24.readFileSync(cfgPath, "utf-8"));
1658
1676
  const keys = dotPath.split(".");
1659
1677
  let o = raw;
1660
1678
  for (let i = 0; i < keys.length - 1; i++) {
@@ -1664,7 +1682,7 @@ var init_live = __esm({
1664
1682
  o[keys[keys.length - 1]] = val;
1665
1683
  if (atomic2) {
1666
1684
  writeConfigAtomic(cfgPath, raw);
1667
- } else fs23.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
1685
+ } else fs24.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
1668
1686
  const lastKey = keys[keys.length - 1].toLowerCase();
1669
1687
  const looksSecret = /(^|[-_.])(key|token|secret|passwd|password|passphrase|authorization|auth|cred)([-_.]|$)/.test(lastKey);
1670
1688
  const shown = val !== null && typeof val === "object" ? "{\u2026}" : looksSecret ? "{\u2026}" : JSON.stringify(val);
@@ -2461,7 +2479,7 @@ END;
2461
2479
  const memo = /* @__PURE__ */ new Map();
2462
2480
  const sourceRetained = (sourceId) => Boolean(this.db.prepare(`SELECT 1 FROM memory_sources
2463
2481
  WHERE scope_id=? AND source_id=? AND interpretation_status<>'deleted'`).get(scopeKey, sourceId));
2464
- const walk = (kind2, id2, version2) => {
2482
+ const walk2 = (kind2, id2, version2) => {
2465
2483
  checkMemoryReadBudget(visited.size);
2466
2484
  const key5 = basisKey(kind2, id2, version2);
2467
2485
  if (memo.has(key5)) return memo.get(key5);
@@ -2477,7 +2495,7 @@ END;
2477
2495
  if (ref.parentKind === "source") return sourceRetained(ref.parentId);
2478
2496
  if (ref.parentKind === "artifact") {
2479
2497
  const parents = this.db.prepare("SELECT child_kind kind FROM memory_derivations WHERE scope_id=? AND child_id=?").all(scopeKey, ref.parentId);
2480
- return parents.length === 1 && walk(parents[0].kind, ref.parentId, ref.parentVersion);
2498
+ return parents.length === 1 && walk2(parents[0].kind, ref.parentId, ref.parentVersion);
2481
2499
  }
2482
2500
  if (ref.parentKind === "entity") {
2483
2501
  const entity = this.db.prepare("SELECT canonical_name FROM entities WHERE scope_id=? AND entity_id=?").get(scopeKey, ref.parentId);
@@ -2497,7 +2515,7 @@ END;
2497
2515
  visited.delete(key5);
2498
2516
  }
2499
2517
  };
2500
- return walk(kind, id, version);
2518
+ return walk2(kind, id, version);
2501
2519
  }
2502
2520
  evidence(scope, kind, id, version, cutoff) {
2503
2521
  checkMemoryReadBudget();
@@ -2518,7 +2536,7 @@ END;
2518
2536
  });
2519
2537
  return true;
2520
2538
  };
2521
- const walk = (parentKind, parentId, parentVersion, ancestors) => {
2539
+ const walk2 = (parentKind, parentId, parentVersion, ancestors) => {
2522
2540
  checkMemoryReadBudget(ancestors.size);
2523
2541
  const key5 = basisKey(parentKind, parentId, parentVersion);
2524
2542
  if (ancestors.has(key5)) return false;
@@ -2545,7 +2563,7 @@ END;
2545
2563
  if (!addSource(ref.parentId, ref.parentVersion)) return false;
2546
2564
  } else if (ref.parentKind === "artifact") {
2547
2565
  const parents = cutoff ? historicalRows(this.db, scope, "artifact.state", cutoff).filter((row) => row.id === ref.parentId) : this.db.prepare("SELECT child_kind kind FROM memory_derivations WHERE scope_id=? AND child_id=?").all(scopeId(scope), ref.parentId);
2548
- if (parents.length !== 1 || !walk(parents[0].kind, ref.parentId, ref.parentVersion, next)) return false;
2566
+ if (parents.length !== 1 || !walk2(parents[0].kind, ref.parentId, ref.parentVersion, next)) return false;
2549
2567
  } else if (ref.parentKind === "scope" && ref.parentId.startsWith("valid-window:")) {
2550
2568
  const time = cutoff ? cutoff.time ?? this.time(cutoff.historyId) : void 0;
2551
2569
  try {
@@ -2571,7 +2589,7 @@ END;
2571
2589
  }
2572
2590
  return true;
2573
2591
  };
2574
- return walk(kind, id, version, /* @__PURE__ */ new Set()) && sources.size ? [...sources.values()] : null;
2592
+ return walk2(kind, id, version, /* @__PURE__ */ new Set()) && sources.size ? [...sources.values()] : null;
2575
2593
  }
2576
2594
  time(historyId) {
2577
2595
  return this.db.prepare("SELECT recorded_at FROM memory_knowledge_history WHERE history_id=?").get(historyId)?.recorded_at;
@@ -2675,8 +2693,9 @@ function invalidateDerivedDependencies(db2, event2) {
2675
2693
  }
2676
2694
  return invalidateChildren(db2, event2.scopeId, pending2, event2.kind);
2677
2695
  }
2678
- function invalidateScopeDependencies(db2, scope, parent, reason) {
2679
- const children = db2.prepare("SELECT child_kind,child_id FROM memory_dependencies WHERE scope_id=? AND parent_kind='scope' AND parent_id=?").all(scope, parent);
2696
+ function invalidateScopeDependencies(db2, scope, parent, reason, options = {}) {
2697
+ let children = db2.prepare("SELECT child_kind,child_id FROM memory_dependencies WHERE scope_id=? AND parent_kind='scope' AND parent_id=?").all(scope, parent);
2698
+ if (options.skipKinds?.size) children = children.filter((child) => !options.skipKinds.has(child.child_kind));
2680
2699
  invalidateChildren(db2, scope, children, reason);
2681
2700
  }
2682
2701
  function invalidateChildren(db2, scope, pending2, reason) {
@@ -2696,7 +2715,7 @@ function invalidateChildren(db2, scope, pending2, reason) {
2696
2715
  }
2697
2716
  const state = child.deleted ? "deleted" : "needs_revalidation";
2698
2717
  db2.prepare(`UPDATE memory_derivations SET state=?,reason=?,updated_at=?
2699
- 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);
2718
+ 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);
2700
2719
  result.push(child.child_id);
2701
2720
  pending2.push(...db2.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" })));
2702
2721
  }
@@ -3342,7 +3361,7 @@ function textColumnOf(kind) {
3342
3361
  return "fact";
3343
3362
  }
3344
3363
  }
3345
- var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3364
+ var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, BM25_TEXT_FIELDS, sqlLiteral, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3346
3365
  var init_vector_store = __esm({
3347
3366
  "src/mem7/core/vector-store.ts"() {
3348
3367
  "use strict";
@@ -3373,6 +3392,14 @@ var init_vector_store = __esm({
3373
3392
  agent_case: ["task_intent_tokens", "approach_tokens"],
3374
3393
  agent_skill: ["description_tokens", "content_tokens"]
3375
3394
  };
3395
+ BM25_TEXT_FIELDS = {
3396
+ foresight: ["foresight", "evidence"],
3397
+ episode: ["episode"],
3398
+ atomic_fact: ["fact"],
3399
+ agent_case: ["task_intent", "approach"],
3400
+ agent_skill: ["description", "content"]
3401
+ };
3402
+ sqlLiteral = (value) => value.replace(/'/g, "''");
3376
3403
  RRF_K = 60;
3377
3404
  warnedFts = /* @__PURE__ */ new Set();
3378
3405
  warnedVecIdx = /* @__PURE__ */ new Set();
@@ -3970,6 +3997,47 @@ var init_vector_store = __esm({
3970
3997
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
3971
3998
  }
3972
3999
  }
4000
+ const textCols = BM25_TEXT_FIELDS[kind];
4001
+ const scan = async (terms, op, limit) => {
4002
+ const expr = op === "AND" ? terms.map((g) => `(${textCols.map((col) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" AND ") : textCols.map((col) => `(${terms.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
4003
+ const where2 = compileFilter(opts.filter);
4004
+ return await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(limit).toArray();
4005
+ };
4006
+ const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
4007
+ const scoreLiteral = (needles2, rows) => {
4008
+ const terms = [.../* @__PURE__ */ new Set([...needles2, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
4009
+ const occurrences2 = (text2, term) => text2.split(term).length - 1;
4010
+ for (const r of rows) {
4011
+ const rid = String(r.id ?? "");
4012
+ if (!rid) continue;
4013
+ const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
4014
+ const matched = terms.filter((term) => text2.includes(term));
4015
+ if (!matched.length || matched.every((term) => !needles2.includes(term))) continue;
4016
+ const full = matched.length === terms.length;
4017
+ const density = matched.reduce((sum, term) => sum + occurrences2(text2, term), 0) / Math.max(text2.length, 1) * 1e3;
4018
+ const score = full ? maxScore + 1 + Math.min(0.99, density / 10) : maxScore > 0 ? maxScore * (0.5 + 0.5 * matched.length / terms.length) : matched.length / terms.length;
4019
+ const cur = best.get(rid);
4020
+ if (cur) {
4021
+ if (full) cur._score = Math.max(Number(cur._score ?? 0), score);
4022
+ } else best.set(rid, { ...r, _score: score });
4023
+ }
4024
+ };
4025
+ const needles = literalQueryNeedles(queryText);
4026
+ if (needles) {
4027
+ try {
4028
+ const terms = [.../* @__PURE__ */ new Set([...needles, ...tokenizeToField(queryText).split(/\s+/).filter(Boolean)])];
4029
+ const [all, any] = await Promise.all([
4030
+ terms.length > 1 ? scan(terms, "AND", topK * 10) : Promise.resolve([]),
4031
+ scan(needles, "OR", topK * 3)
4032
+ ]);
4033
+ scoreLiteral(needles, [...all, ...any]);
4034
+ if (![...best.values()].some((r) => Number(r._score ?? 0) > maxScore)) {
4035
+ const bigrams = [...new Set(needles.flatMap((name) => queryBigramNeedles(name) ?? []))].slice(0, 8);
4036
+ if (bigrams.length && JSON.stringify(bigrams) !== JSON.stringify(needles)) scoreLiteral(bigrams, await scan(bigrams, "OR", topK * 3));
4037
+ }
4038
+ } catch {
4039
+ }
4040
+ }
3973
4041
  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) }));
3974
4042
  } catch (err) {
3975
4043
  const msg2 = String(err?.message ?? err);
@@ -4549,7 +4617,7 @@ import { createHash as createHash7 } from "node:crypto";
4549
4617
  function projectedSourceIdFromScopeId(id, originKey, sourceVersion) {
4550
4618
  return "src_" + digest([id, originKey, sourceVersion]);
4551
4619
  }
4552
- var SOURCE_SCHEMA, SOURCE_ALIAS_SCHEMA, digest, SourceStore;
4620
+ var RECEIVED_INVALIDATION_SKIP, SOURCE_SCHEMA, SOURCE_ALIAS_SCHEMA, digest, SourceStore;
4553
4621
  var init_source_store = __esm({
4554
4622
  "src/mem7/core/source-store.ts"() {
4555
4623
  "use strict";
@@ -4561,6 +4629,7 @@ var init_source_store = __esm({
4561
4629
  init_watermarks();
4562
4630
  init_interpretation_impact();
4563
4631
  init_conversation_text();
4632
+ RECEIVED_INVALIDATION_SKIP = /* @__PURE__ */ new Set(["foresight"]);
4564
4633
  SOURCE_SCHEMA = `
4565
4634
  CREATE TABLE memory_scopes (
4566
4635
  scope_id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, app_id TEXT NOT NULL, project_id TEXT NOT NULL,
@@ -4742,8 +4811,8 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
4742
4811
  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");
4743
4812
  if (version !== Number(latest.version ?? 0) + 1) throw new Error("SOURCE_VERSION_CONFLICT: edits must follow the previous version");
4744
4813
  this.db.prepare("UPDATE memory_scopes SET source_seq=source_seq+1,context_revision=context_revision+1 WHERE scope_id=?").run(id);
4745
- invalidateScopeDependencies(this.db, id, "sources", "source.received");
4746
- invalidateScopeDependencies(this.db, id, "context", "source.received");
4814
+ invalidateScopeDependencies(this.db, id, "sources", "source.received", { skipKinds: RECEIVED_INVALIDATION_SKIP });
4815
+ invalidateScopeDependencies(this.db, id, "context", "source.received", { skipKinds: RECEIVED_INVALIDATION_SKIP });
4747
4816
  const seq = Number(this.db.prepare("SELECT source_seq FROM memory_scopes WHERE scope_id=?").get(id).source_seq);
4748
4817
  const sourceId = projectedSourceIdFromScopeId(id, input.originKey, version);
4749
4818
  const receiptId = "rcpt_" + digest([id, sourceId]);
@@ -5308,8 +5377,8 @@ function purgeRecoveryEvidence(db2, graph) {
5308
5377
  const blocked = item.table ? values.some((row) => graph.blocks(item.table, row)) : values.some((row) => row.kind === "file") && graph.blocksArtifactPath("file", item.path) !== false && graph.blocksArtifactPath("vector", item.path) !== false;
5309
5378
  if (!blocked) continue;
5310
5379
  for (const value of values) {
5311
- const sha = value.content?.sha256;
5312
- if (sha) db2.prepare("DELETE FROM e7_recovery_objects WHERE sha256=?").run(sha);
5380
+ const sha2 = value.content?.sha256;
5381
+ if (sha2) db2.prepare("DELETE FROM e7_recovery_objects WHERE sha256=?").run(sha2);
5313
5382
  }
5314
5383
  item.state = "DELETED_BLOCKED";
5315
5384
  item.reason = "latest_deletion";
@@ -5435,8 +5504,8 @@ var init_recovery_deletion = __esm({
5435
5504
  const { owners, parents } = this.links(table, row);
5436
5505
  for (const parent of parents) for (const owner of owners) this.edge(parent, owner);
5437
5506
  if (table === "memory_artifact_publications") {
5438
- const medium = text(row, "medium"), path22 = text(row, "path"), physicalId = text(row, "physical_id"), kind = text(row, "kind");
5439
- const identity = medium === "markdown" && path22 ? "file:mem7/" + path22 : medium === "vector" && physicalId && kind ? "vector:" + kind + "/rows/" + createHash9("sha256").update(physicalId).digest("hex") + ".arrow" : void 0;
5507
+ const medium = text(row, "medium"), path23 = text(row, "path"), physicalId = text(row, "physical_id"), kind = text(row, "kind");
5508
+ const identity = medium === "markdown" && path23 ? "file:mem7/" + path23 : medium === "vector" && physicalId && kind ? "vector:" + kind + "/rows/" + createHash9("sha256").update(physicalId).digest("hex") + ".arrow" : void 0;
5440
5509
  if (identity) {
5441
5510
  const rows = this.artifactPaths.get(identity) ?? [];
5442
5511
  rows.push(row);
@@ -5444,8 +5513,8 @@ var init_recovery_deletion = __esm({
5444
5513
  }
5445
5514
  }
5446
5515
  }
5447
- blocksArtifactPath(kind, path22) {
5448
- const rows = this.artifactPaths.get(kind + ":" + path22);
5516
+ blocksArtifactPath(kind, path23) {
5517
+ const rows = this.artifactPaths.get(kind + ":" + path23);
5449
5518
  return rows?.some((row) => this.blocks("memory_artifact_publications", row));
5450
5519
  }
5451
5520
  blocks(table, row) {
@@ -6472,7 +6541,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6472
6541
  };
6473
6542
  const candidates = [];
6474
6543
  const duplicateIds = /* @__PURE__ */ new Set();
6475
- const inside = (path22) => path22 && !isAbsolute(path22) && path22 !== ".." && !path22.startsWith(`..${sep}`);
6544
+ const inside = (path23) => path23 && !isAbsolute(path23) && path23 !== ".." && !path23.startsWith(`..${sep}`);
6476
6545
  for (const relativePath of input.files) {
6477
6546
  const logical = resolve3(root, relativePath);
6478
6547
  let canonical3;
@@ -6486,10 +6555,10 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6486
6555
  gap("projection_path_unverified");
6487
6556
  continue;
6488
6557
  }
6489
- const path22 = relative(root, canonical3).replace(/\\/g, "/");
6558
+ const path23 = relative(root, canonical3).replace(/\\/g, "/");
6490
6559
  const user = `users/${input.scope.ownerId}/`;
6491
6560
  const agent = store.ownerProjectionPath("agents", input.scope.ownerId, input.scope).replace(/\\/g, "/") + "/";
6492
- const kind = path22.startsWith(`${user}episodes/`) && /\/episode-\d{4}-\d{2}-\d{2}\.md$/.test(path22) ? "episode" : path22.startsWith(`${user}.atomic_facts/`) && /\/atomic_fact-\d{4}-\d{2}-\d{2}\.md$/.test(path22) ? "atomic_fact" : path22.startsWith(`${user}.foresights/`) && /\/foresight-\d{4}-\d{2}-\d{2}\.md$/.test(path22) ? "foresight" : path22.startsWith(`${agent}.cases/`) && /\/agent_case-\d{4}-\d{2}-\d{2}\.md$/.test(path22) ? "agent_case" : void 0;
6561
+ const kind = path23.startsWith(`${user}episodes/`) && /\/episode-\d{4}-\d{2}-\d{2}\.md$/.test(path23) ? "episode" : path23.startsWith(`${user}.atomic_facts/`) && /\/atomic_fact-\d{4}-\d{2}-\d{2}\.md$/.test(path23) ? "atomic_fact" : path23.startsWith(`${user}.foresights/`) && /\/foresight-\d{4}-\d{2}-\d{2}\.md$/.test(path23) ? "foresight" : path23.startsWith(`${agent}.cases/`) && /\/agent_case-\d{4}-\d{2}-\d{2}\.md$/.test(path23) ? "agent_case" : void 0;
6493
6562
  if (!kind) {
6494
6563
  gap("projection_kind_or_owner_unverified");
6495
6564
  continue;
@@ -6526,9 +6595,9 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6526
6595
  continue;
6527
6596
  }
6528
6597
  const previous = db2.prepare("SELECT * FROM memory_legacy_projection_maps WHERE scope_id=? AND kind=? AND entry_id=?").get(key5, kind, match[1]);
6529
- const target = join6(store.mem7RootPath(), path22);
6598
+ const target = join6(store.mem7RootPath(), path23);
6530
6599
  if (previous) {
6531
- if (previous.source_file_hash !== fileHash || previous.parent_id !== parent || previous.source_relative_path !== path22 || !store.projectionMatches(input.scope, kind, match[1], target, block)) {
6600
+ if (previous.source_file_hash !== fileHash || previous.parent_id !== parent || previous.source_relative_path !== path23 || !store.projectionMatches(input.scope, kind, match[1], target, block)) {
6532
6601
  gap("projection_mapping_conflict");
6533
6602
  continue;
6534
6603
  }
@@ -6544,7 +6613,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6544
6613
  candidates.push({
6545
6614
  file: canonical3,
6546
6615
  fileHash,
6547
- relativePath: path22,
6616
+ relativePath: path23,
6548
6617
  id: match[1],
6549
6618
  kind,
6550
6619
  parent,
@@ -7827,7 +7896,7 @@ async function drainJobs(store, handlers2, options = {}) {
7827
7896
  let done = 0;
7828
7897
  for (let attempted = 0; attempted < (options.maxJobs ?? 200) && Date.now() < deadline; attempted++) {
7829
7898
  if (options.shouldRun && !options.shouldRun()) break;
7830
- const job = store.claimJobs(1, { leaseMs, kinds: options.kinds, scopeId: options.scopeId })[0];
7899
+ const job = store.claimJobs(1, { leaseMs, kinds: options.kinds, scopeId: options.scopeId, staleOnly: options.staleOnly })[0];
7831
7900
  if (!job) break;
7832
7901
  options.onAttempt?.();
7833
7902
  let heartbeatError;
@@ -8369,11 +8438,11 @@ function applySocialInterpretation(store, scope, result, captured, requestKey, r
8369
8438
  const covers = (evidence, mention) => evidence.sourceId === mention.sourceId && evidence.start <= mention.start && evidence.end >= mention.end;
8370
8439
  const entitySnapshot = store.entities.list(scope);
8371
8440
  for (const mention of ordered) {
8372
- const path22 = mentionPath(mention);
8441
+ const path23 = mentionPath(mention);
8373
8442
  const source = store.sources.get(scope, mention.sourceId);
8374
8443
  if (!source || !captured.sourceIds.includes(mention.sourceId) || !Number.isSafeInteger(mention.start) || !Number.isSafeInteger(mention.end) || mention.start < 0 || mention.end <= mention.start || mention.end > source.text.length || source.text.slice(mention.start, mention.end) !== mention.quote || typeof mention.key !== "string" || ids.has(mention.key) || typeof mention.actual !== "boolean") {
8375
- if (typeof mention.actual !== "boolean") fail2("INVALID_SOCIAL_MENTION", `${path22}.actual`, "\u5FC5\u586B\u5E03\u5C14\u503C\uFF1B\u771F\u5B9E\u4EBA\u7269\u63D0\u53CA\u586B true\uFF0C\u5047\u8BBE\u4EBA\u7269\u586B false\u3002");
8376
- fail2("INVALID_SOCIAL_MENTION", `${path22}.quote/sourceId/start/end`, "quote \u5FC5\u987B\u9010\u5B57\u51FA\u73B0\u5728 sourceId \u5BF9\u5E94\u7684\u539F\u8BDD\u4E2D\uFF1B\u5148 memory_get({source_id:\u8BE5\u6765\u6E90}) \u6838\u5BF9\u3002mention.quote \u53EA\u622A\u4EBA\u540D/\u79F0\u547C\uFF0C\u5B8C\u6574\u540C\u4EBA\u8BF4\u660E\u653E identity.evidence.quote\uFF1B\u552F\u4E00\u5F15\u6587\u53EF\u7701\u7565 start/end\u3002");
8444
+ if (typeof mention.actual !== "boolean") fail2("INVALID_SOCIAL_MENTION", `${path23}.actual`, "\u5FC5\u586B\u5E03\u5C14\u503C\uFF1B\u771F\u5B9E\u4EBA\u7269\u63D0\u53CA\u586B true\uFF0C\u5047\u8BBE\u4EBA\u7269\u586B false\u3002");
8445
+ fail2("INVALID_SOCIAL_MENTION", `${path23}.quote/sourceId/start/end`, "quote \u5FC5\u987B\u9010\u5B57\u51FA\u73B0\u5728 sourceId \u5BF9\u5E94\u7684\u539F\u8BDD\u4E2D\uFF1B\u5148 memory_get({source_id:\u8BE5\u6765\u6E90}) \u6838\u5BF9\u3002mention.quote \u53EA\u622A\u4EBA\u540D/\u79F0\u547C\uFF0C\u5B8C\u6574\u540C\u4EBA\u8BF4\u660E\u653E identity.evidence.quote\uFF1B\u552F\u4E00\u5F15\u6587\u53EF\u7701\u7565 start/end\u3002");
8377
8446
  }
8378
8447
  if (!mention.actual || isAssistantDraft(source)) {
8379
8448
  ids.set(mention.key, null);
@@ -8383,12 +8452,12 @@ function applySocialInterpretation(store, scope, result, captured, requestKey, r
8383
8452
  if (!["existing", "new", "unresolved"].includes(mention.disposition)) throw new Error("INVALID_SOCIAL_DISPOSITION");
8384
8453
  if (!["name", "description", "reference"].includes(mention.mentionKind)) throw new Error("INVALID_SOCIAL_MENTION_KIND");
8385
8454
  let entity = null;
8386
- const basisRefs = references(mention.basisSourceIds, source.sourceId, `${path22}.basisSourceIds`);
8455
+ const basisRefs = references(mention.basisSourceIds, source.sourceId, `${path23}.basisSourceIds`);
8387
8456
  let identityEntity = null;
8388
8457
  if (mention.identity !== void 0) {
8389
8458
  const identity = mention.identity;
8390
8459
  if (!identity || !["same_person", "different_person", "uncertain"].includes(identity.relation)) throw new Error("INVALID_SOCIAL_IDENTITY");
8391
- const evidenceSource = literalSpan(identity.evidence, `${path22}.identity.evidence`);
8460
+ const evidenceSource = literalSpan(identity.evidence, `${path23}.identity.evidence`);
8392
8461
  if (evidenceSource.sourceId !== source.sourceId && !captured.contextRefs?.some((ref) => ref.sourceId === evidenceSource.sourceId)) {
8393
8462
  throw new Error("INVALID_SOCIAL_IDENTITY_EVIDENCE");
8394
8463
  }
@@ -8400,7 +8469,7 @@ function applySocialInterpretation(store, scope, result, captured, requestKey, r
8400
8469
  anchorEntityId = store.entities.speaker(scope, source.sourceId)?.entityId;
8401
8470
  } else {
8402
8471
  const supplied = mentionsByKey.get(identity.anchor);
8403
- if (!supplied || supplied.sourceId !== source.sourceId || supplied.key === mention.key) fail2("INVALID_SOCIAL_IDENTITY_ANCHOR", `${path22}.identity.anchor`, anchorCorrection);
8472
+ if (!supplied || supplied.sourceId !== source.sourceId || supplied.key === mention.key) fail2("INVALID_SOCIAL_IDENTITY_ANCHOR", `${path23}.identity.anchor`, anchorCorrection);
8404
8473
  const anchor = supplied;
8405
8474
  if (!covers(identity.evidence, mention) || mention.mentionKind !== "reference" && !covers(identity.evidence, anchor)) throw new Error("INVALID_SOCIAL_IDENTITY_EVIDENCE");
8406
8475
  anchorEntityId = ids.get(supplied.key);
@@ -8409,25 +8478,25 @@ function applySocialInterpretation(store, scope, result, captured, requestKey, r
8409
8478
  } else {
8410
8479
  const anchor = identity.anchor;
8411
8480
  const authorAnchor = anchor && "author" in anchor;
8412
- const anchorSource = authorAnchor ? store.sources.get(scope, anchor.sourceId) : literalSpan(anchor, `${path22}.identity.anchor`);
8481
+ const anchorSource = authorAnchor ? store.sources.get(scope, anchor.sourceId) : literalSpan(anchor, `${path23}.identity.anchor`);
8413
8482
  if (!anchorSource || !captured.sourceRefs.some((ref) => ref.sourceId === anchorSource.sourceId && ref.sourceVersion === anchorSource.sourceVersion)) {
8414
- fail2("INVALID_SOCIAL_IDENTITY_ANCHOR", `${path22}.identity.anchor`, anchorCorrection);
8483
+ fail2("INVALID_SOCIAL_IDENTITY_ANCHOR", `${path23}.identity.anchor`, anchorCorrection);
8415
8484
  }
8416
8485
  const supplied = authorAnchor ? void 0 : captured.identityMentions?.find((item) => item.sourceId === anchor.sourceId && item.start === anchor.start && item.end === anchor.end && item.quote === anchor.quote);
8417
8486
  const author = ["host_user", "client_reported_user", "assistant"].includes(anchorSource.originClass) ? store.entities.speaker(scope, anchor.sourceId) : null;
8418
8487
  const selected = mention.entityId ? store.entities.resolve(scope, mention.entityId) : null;
8419
8488
  if (authorAnchor || !supplied && author && selected?.entityId === store.entities.resolve(scope, author.entityId)?.entityId) {
8420
- if (!author || "author" in anchor && anchor.author !== true) fail2("INVALID_SOCIAL_IDENTITY_ANCHOR", `${path22}.identity.anchor`, anchorCorrection);
8489
+ if (!author || "author" in anchor && anchor.author !== true) fail2("INVALID_SOCIAL_IDENTITY_ANCHOR", `${path23}.identity.anchor`, anchorCorrection);
8421
8490
  if (selected && selected.entityId !== store.entities.resolve(scope, author.entityId)?.entityId) {
8422
- fail2("SOCIAL_IDENTITY_CONFLICT", `${path22}.identity.anchor`, `\u6765\u6E90\u4F5C\u8005\u4E3A ${author.canonicalName}\uFF0CentityId=${author.entityId}\uFF0C\u4E0E mentions.entityId=${mention.entityId} \u4E0D\u540C\uFF1B\u8BF7\u6838\u5BF9\u76EE\u6807\u4EBA\u7269\uFF0C\u5F15\u7528\u6B63\u786E\u4F5C\u8005\u6216\u6B63\u6587 confirmedMentions\u3002`);
8491
+ fail2("SOCIAL_IDENTITY_CONFLICT", `${path23}.identity.anchor`, `\u6765\u6E90\u4F5C\u8005\u4E3A ${author.canonicalName}\uFF0CentityId=${author.entityId}\uFF0C\u4E0E mentions.entityId=${mention.entityId} \u4E0D\u540C\uFF1B\u8BF7\u6838\u5BF9\u76EE\u6807\u4EBA\u7269\uFF0C\u5F15\u7528\u6B63\u786E\u4F5C\u8005\u6216\u6B63\u6587 confirmedMentions\u3002`);
8423
8492
  }
8424
8493
  if (evidenceSource.sourceId !== source.sourceId || !covers(identity.evidence, mention)) {
8425
- fail2("INVALID_SOCIAL_IDENTITY_EVIDENCE", `${path22}.identity.evidence`, "\u5F15\u7528\u6765\u6E90\u4F5C\u8005\u65F6\uFF0Cevidence \u5E94\u5F15\u7528\u5F53\u524D\u539F\u8BDD\u4E2D\u8BF4\u660E\u8BE5\u4EBA\u7269\u7684\u5B8C\u6574\u53E5\u5B50\uFF0C\u5E76\u5305\u542B mention.quote\u3002");
8494
+ fail2("INVALID_SOCIAL_IDENTITY_EVIDENCE", `${path23}.identity.evidence`, "\u5F15\u7528\u6765\u6E90\u4F5C\u8005\u65F6\uFF0Cevidence \u5E94\u5F15\u7528\u5F53\u524D\u539F\u8BDD\u4E2D\u8BF4\u660E\u8BE5\u4EBA\u7269\u7684\u5B8C\u6574\u53E5\u5B50\uFF0C\u5E76\u5305\u542B mention.quote\u3002");
8426
8495
  }
8427
8496
  anchorEntityId = author.entityId;
8428
8497
  anchorBasis = references([anchor.sourceId], source.sourceId);
8429
8498
  } else {
8430
- if (!supplied || authorAnchor || anchor.sourceId === source.sourceId && anchor.start === mention.start && anchor.end === mention.end) fail2("INVALID_SOCIAL_IDENTITY_ANCHOR", `${path22}.identity.anchor`, anchorCorrection);
8499
+ if (!supplied || authorAnchor || anchor.sourceId === source.sourceId && anchor.start === mention.start && anchor.end === mention.end) fail2("INVALID_SOCIAL_IDENTITY_ANCHOR", `${path23}.identity.anchor`, anchorCorrection);
8431
8500
  if (evidenceSource.sourceId === source.sourceId ? !covers(identity.evidence, mention) : !covers(identity.evidence, anchor)) {
8432
8501
  throw new Error("INVALID_SOCIAL_IDENTITY_EVIDENCE");
8433
8502
  }
@@ -8505,8 +8574,8 @@ function applySocialInterpretation(store, scope, result, captured, requestKey, r
8505
8574
  if (entity) entityBasis.set(entity.entityId, distinctRefs([...entityBasis.get(entity.entityId) || [], ...grounds]));
8506
8575
  }
8507
8576
  for (const [ordinal, relation] of result.relationships.entries()) {
8508
- const path22 = `relationships[${ordinal}]`;
8509
- if (typeof relation?.actual !== "boolean") fail2("INVALID_SOCIAL_RELATION", `${path22}.actual`, "\u5FC5\u586B\u5E03\u5C14\u503C\uFF1B\u7528\u6237\u5B9E\u9645\u8BF4\u660E\u7684\u5173\u7CFB\u586B true\u3002label \u662F\u5F00\u653E\u6587\u672C\uFF0C\u201C\u7236\u5B50\u201D\u53EF\u7528\u3002");
8577
+ const path23 = `relationships[${ordinal}]`;
8578
+ if (typeof relation?.actual !== "boolean") fail2("INVALID_SOCIAL_RELATION", `${path23}.actual`, "\u5FC5\u586B\u5E03\u5C14\u503C\uFF1B\u7528\u6237\u5B9E\u9645\u8BF4\u660E\u7684\u5173\u7CFB\u586B true\u3002label \u662F\u5F00\u653E\u6587\u672C\uFF0C\u201C\u7236\u5B50\u201D\u53EF\u7528\u3002");
8510
8579
  if (!relation.actual) {
8511
8580
  applied.relationships.push({ index: ordinal, label: relation.label, state: "ignored" });
8512
8581
  continue;
@@ -8515,7 +8584,7 @@ function applySocialInterpretation(store, scope, result, captured, requestKey, r
8515
8584
  if (!source || !captured.sourceIds.includes(source.sourceId)) {
8516
8585
  fail2(
8517
8586
  "SOCIAL_SOURCE_NOT_PROVIDED",
8518
- `${path22}.sourceId=${relation.sourceId}`,
8587
+ `${path23}.sourceId=${relation.sourceId}`,
8519
8588
  `${source ? "\u8BE5\u6765\u6E90\u672A\u5217\u5165\u672C\u6B21 sources\uFF1B\u4EC5\u653E context_sources \u53EA\u4F9B\u53C2\u7167\uFF0C\u4E0D\u7528\u4E8E\u63D0\u53D6\u5173\u7CFB\u3002" : "\u672C\u6C60\u8BFB\u4E0D\u5230\u8BE5\u6765\u6E90\u3002"}\u5148 memory_get \u6838\u5BF9\u5173\u7CFB\u539F\u8BDD\uFF0C\u518D\u628A\u539F\u8BDD\u7684 ID \u548C\u7248\u672C\u5217\u5165 sources\uFF1B\u4E0D\u8981\u66FF\u6362\u4E3A\u4E0D\u542B\u8BE5\u4E8B\u5B9E\u7684\u672C\u8F6E\u56DE\u7B54\u3002`
8520
8589
  );
8521
8590
  }
@@ -8525,20 +8594,20 @@ function applySocialInterpretation(store, scope, result, captured, requestKey, r
8525
8594
  }
8526
8595
  for (const field of ["validFrom", "validTo"]) {
8527
8596
  const value = relation[field];
8528
- if (value === void 0) fail2("INVALID_SOCIAL_TIME", `${path22}.${field}`, "\u6B64\u5B57\u6BB5\u5FC5\u586B\uFF1B\u539F\u8BDD\u6CA1\u6709\u8BF4\u660E\u5173\u7CFB\u8D77\u6B62\u65F6\u523B\u65F6\u586B null\uFF0C\u4E0D\u8981\u586B\u8BF4\u8BDD\u65F6\u95F4\u3002");
8597
+ if (value === void 0) fail2("INVALID_SOCIAL_TIME", `${path23}.${field}`, "\u6B64\u5B57\u6BB5\u5FC5\u586B\uFF1B\u539F\u8BDD\u6CA1\u6709\u8BF4\u660E\u5173\u7CFB\u8D77\u6B62\u65F6\u523B\u65F6\u586B null\uFF0C\u4E0D\u8981\u586B\u8BF4\u8BDD\u65F6\u95F4\u3002");
8529
8598
  if (value !== null) {
8530
8599
  try {
8531
8600
  if (typeof value !== "string") throw new Error("INVALID_TIME");
8532
8601
  instant(value);
8533
8602
  } catch {
8534
- fail2("INVALID_SOCIAL_TIME", `${path22}.${field}`, "\u975E null \u65F6\u95F4\u987B\u4E3A\u5B8C\u6574 ISO \u65F6\u523B\uFF0C\u5E26 Z \u6216 +08:00 \u7B49\u660E\u786E UTC \u504F\u79FB\uFF1B\u672A\u77E5\u65F6\u523B\u586B null\uFF0C\u4E0D\u8981\u731C\u6D4B\u3002");
8603
+ fail2("INVALID_SOCIAL_TIME", `${path23}.${field}`, "\u975E null \u65F6\u95F4\u987B\u4E3A\u5B8C\u6574 ISO \u65F6\u523B\uFF0C\u5E26 Z \u6216 +08:00 \u7B49\u660E\u786E UTC \u504F\u79FB\uFF1B\u672A\u77E5\u65F6\u523B\u586B null\uFF0C\u4E0D\u8981\u731C\u6D4B\u3002");
8535
8604
  }
8536
8605
  }
8537
8606
  }
8538
8607
  if (relation.validFrom !== null && relation.validFrom !== void 0) {
8539
8608
  const quote2 = relation.validFromQuote;
8540
8609
  if (!quote2 || !Number.isSafeInteger(quote2.start) || !Number.isSafeInteger(quote2.end) || quote2.start < 0 || quote2.end <= quote2.start || quote2.end > source.text.length || source.text.slice(quote2.start, quote2.end) !== quote2.quote) {
8541
- fail2("INVALID_SOCIAL_VALID_FROM", `${path22}.validFrom/validFromQuote`, "\u5173\u7CFB\u8D77\u59CB\u65F6\u95F4\u9700\u8981\u539F\u8BDD\u4E2D\u7684\u65F6\u95F4\u4F9D\u636E\uFF1B\u53EA\u77E5\u9053\u4ECA\u5929\u8BF4\u4E86\u8FD9\u4EF6\u4E8B\u65F6\uFF0CvalidFrom \u586B null\uFF0C\u4E0D\u8981\u586B\u8BF4\u8BDD\u65F6\u95F4\u3002");
8610
+ fail2("INVALID_SOCIAL_VALID_FROM", `${path23}.validFrom/validFromQuote`, "\u5173\u7CFB\u8D77\u59CB\u65F6\u95F4\u9700\u8981\u539F\u8BDD\u4E2D\u7684\u65F6\u95F4\u4F9D\u636E\uFF1B\u53EA\u77E5\u9053\u4ECA\u5929\u8BF4\u4E86\u8FD9\u4EF6\u4E8B\u65F6\uFF0CvalidFrom \u586B null\uFF0C\u4E0D\u8981\u586B\u8BF4\u8BDD\u65F6\u95F4\u3002");
8542
8611
  }
8543
8612
  }
8544
8613
  const speaker = store.entities.speaker(scope, source.sourceId);
@@ -8559,7 +8628,7 @@ function applySocialInterpretation(store, scope, result, captured, requestKey, r
8559
8628
  if (["attitude", "feeling"].includes(relation.contentKind) && relation.direction !== "directed") throw new Error("INVALID_SOCIAL_RECIPROCITY");
8560
8629
  if (relation.attribution !== void 0 && !["direct", "reported"].includes(relation.attribution)) throw new Error("INVALID_SOCIAL_ATTRIBUTION");
8561
8630
  if (relation.attributionQuote !== void 0 && relation.attribution !== "reported") {
8562
- fail2("INVALID_SOCIAL_ATTRIBUTION", `${path22}.attributionQuote`, "attribution=direct\uFF08\u5305\u62EC\u9ED8\u8BA4\u76F4\u63A5\u9648\u8FF0\uFF09\u65F6\u5220\u9664 attributionQuote\uFF1B\u53EA\u6709\u539F\u8BDD\u660E\u786E\u8F6C\u8FF0\u53E6\u4E00\u4EBA\u7269\u89C2\u70B9\u65F6\u624D\u7528 reported\uFF0C\u5E76\u63D0\u4F9B\u8BE5\u4EBA\u7269\u7684 perspective \u548C\u8F6C\u8FF0\u5F15\u6587\u3002\u4E0D\u8981\u4E3A\u901A\u8FC7\u6821\u9A8C\u6539\u6210\u8F6C\u8FF0\u3002");
8631
+ fail2("INVALID_SOCIAL_ATTRIBUTION", `${path23}.attributionQuote`, "attribution=direct\uFF08\u5305\u62EC\u9ED8\u8BA4\u76F4\u63A5\u9648\u8FF0\uFF09\u65F6\u5220\u9664 attributionQuote\uFF1B\u53EA\u6709\u539F\u8BDD\u660E\u786E\u8F6C\u8FF0\u53E6\u4E00\u4EBA\u7269\u89C2\u70B9\u65F6\u624D\u7528 reported\uFF0C\u5E76\u63D0\u4F9B\u8BE5\u4EBA\u7269\u7684 perspective \u548C\u8F6C\u8FF0\u5F15\u6587\u3002\u4E0D\u8981\u4E3A\u901A\u8FC7\u6821\u9A8C\u6539\u6210\u8F6C\u8FF0\u3002");
8563
8632
  }
8564
8633
  if (relation.realm !== void 0 && !["real", "roleplay", "hypothetical"].includes(relation.realm)) throw new Error("INVALID_SOCIAL_REALM");
8565
8634
  if (relation.sensitivity !== void 0 && !["normal", "sensitive"].includes(relation.sensitivity)) throw new Error("INVALID_SOCIAL_SENSITIVITY");
@@ -8584,7 +8653,7 @@ function applySocialInterpretation(store, scope, result, captured, requestKey, r
8584
8653
  basisRefs: distinctRefs([
8585
8654
  ...metadata2?.basisRefs || [],
8586
8655
  ...store.socialSources.identityRefs(scope, source.sourceId),
8587
- ...references(relation.basisSourceIds, source.sourceId, `${path22}.basisSourceIds`),
8656
+ ...references(relation.basisSourceIds, source.sourceId, `${path23}.basisSourceIds`),
8588
8657
  ...[relation.perspective, relation.subject, relation.object].flatMap((ref) => [...mentionBasis.get(ref) || [], ...entityBasis.get(resolve26(ref)) || []])
8589
8658
  ])
8590
8659
  };
@@ -8962,11 +9031,11 @@ function checkSeal(value) {
8962
9031
  const { digest: actual, ...body } = value ?? {};
8963
9032
  if (actual !== digest3(canonical(body))) throw new Error("MANIFEST_DIGEST_MISMATCH");
8964
9033
  }
8965
- function safeRelative(path22) {
8966
- return typeof path22 === "string" && !!path22 && !isAbsolute2(path22) && !/[:\\\x00-\x1f]/.test(path22) && path22.split("/").every((p) => p && p !== "." && p !== "..");
9034
+ function safeRelative(path23) {
9035
+ return typeof path23 === "string" && !!path23 && !isAbsolute2(path23) && !/[:\\\x00-\x1f]/.test(path23) && path23.split("/").every((p) => p && p !== "." && p !== "..");
8967
9036
  }
8968
- function unlinked(path22) {
8969
- let cursor = resolve4(path22);
9037
+ function unlinked(path23) {
9038
+ let cursor = resolve4(path23);
8970
9039
  for (; ; ) {
8971
9040
  try {
8972
9041
  if (lstatSync6(cursor).isSymbolicLink()) throw new Error("SYMLINK_PATH");
@@ -8974,7 +9043,7 @@ function unlinked(path22) {
8974
9043
  if (e.code !== "ENOENT") throw e;
8975
9044
  }
8976
9045
  const parent = dirname5(cursor);
8977
- if (parent === cursor) return resolve4(path22);
9046
+ if (parent === cursor) return resolve4(path23);
8978
9047
  cursor = parent;
8979
9048
  }
8980
9049
  }
@@ -8987,8 +9056,8 @@ function disjoint(...paths) {
8987
9056
  for (let i = 0; i < p.length; i++) for (let j = i + 1; j < p.length; j++)
8988
9057
  if (contains(p[i], p[j]) || contains(p[j], p[i])) throw new Error("PATH_OVERLAP");
8989
9058
  }
8990
- function readJson(path22) {
8991
- return JSON.parse(readFileSync7(unlinked(path22), "utf8").replace(/^\uFEFF/, ""));
9059
+ function readJson(path23) {
9060
+ return JSON.parse(readFileSync7(unlinked(path23), "utf8").replace(/^\uFEFF/, ""));
8992
9061
  }
8993
9062
  function rawBytes(snapshot, record) {
8994
9063
  if (!/^[a-f0-9]{64}$/.test(record.sha256)) throw new Error("INVALID_OBJECT_REFERENCE");
@@ -9541,9 +9610,9 @@ function normalize3(input) {
9541
9610
  if (!input || !/^[a-f0-9]{64}$/.test(input.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
9542
9611
  return Object.freeze({ binding: normalizeBinding(input.binding), schemaHash: input.schemaHash });
9543
9612
  }
9544
- function directory(path22) {
9545
- const info = lstatSync7(path22);
9546
- if (!info.isDirectory() || info.isSymbolicLink() || realpathSync4(path22) !== resolve5(path22) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
9613
+ function directory(path23) {
9614
+ const info = lstatSync7(path23);
9615
+ if (!info.isDirectory() || info.isSymbolicLink() || realpathSync4(path23) !== resolve5(path23) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
9547
9616
  throw new Error("REPLICATION_REGISTRATION_INVALID");
9548
9617
  }
9549
9618
  function readRuntimeReplicationRegistration(stateDir2, component, key5) {
@@ -10212,6 +10281,7 @@ __export(topics_history_exports, {
10212
10281
  topicMatchesYear: () => topicMatchesYear,
10213
10282
  topicQueryYear: () => topicQueryYear,
10214
10283
  topicsHistoryNeedsFallback: () => topicsHistoryNeedsFallback,
10284
+ topicsHistoryRefsCurrent: () => topicsHistoryRefsCurrent,
10215
10285
  topicsHistoryRoot: () => topicsHistoryRoot,
10216
10286
  topicsScope: () => topicsScope
10217
10287
  });
@@ -10231,10 +10301,10 @@ function topicMatchesYear(dates, year) {
10231
10301
  function topicsHistoryRoot(b) {
10232
10302
  return unlinked(join13(b.stateDir, "topics-history", key3(b)));
10233
10303
  }
10234
- function parseTopicHistoryPath(path22) {
10235
- if (!path22.startsWith("topics-history://") || path22.length > 1e4) throw new Error("INVALID_HISTORY_REFERENCE");
10304
+ function parseTopicHistoryPath(path23) {
10305
+ if (!path23.startsWith("topics-history://") || path23.length > 1e4) throw new Error("INVALID_HISTORY_REFERENCE");
10236
10306
  try {
10237
- return JSON.parse(Buffer.from(path22.slice(17), "base64url").toString("utf8"));
10307
+ return JSON.parse(Buffer.from(path23.slice(17), "base64url").toString("utf8"));
10238
10308
  } catch {
10239
10309
  throw new Error("INVALID_HISTORY_REFERENCE");
10240
10310
  }
@@ -10261,19 +10331,19 @@ async function topicHistoryReadRevision(b, refs) {
10261
10331
  paths.add(join13(resolve7(b.topicsDir), ref.sourcePath));
10262
10332
  paths.add(join13(root, "forgotten", `${digest3(ref.sourcePath)}.json`));
10263
10333
  }
10264
- const stats = await Promise.all([...paths].sort().map(async (path22) => {
10334
+ const stats = await Promise.all([...paths].sort().map(async (path23) => {
10265
10335
  try {
10266
- const stat3 = await fs2.lstat(path22, { bigint: true });
10267
- return [path22, ...[stat3.dev, stat3.ino, stat3.mode, stat3.size, stat3.mtimeNs, stat3.ctimeNs].map(String)];
10336
+ const stat3 = await fs2.lstat(path23, { bigint: true });
10337
+ return [path23, ...[stat3.dev, stat3.ino, stat3.mode, stat3.size, stat3.mtimeNs, stat3.ctimeNs].map(String)];
10268
10338
  } catch (error) {
10269
- if (error.code === "ENOENT") return [path22, null];
10339
+ if (error.code === "ENOENT") return [path23, null];
10270
10340
  throw error;
10271
10341
  }
10272
10342
  }));
10273
10343
  return JSON.stringify([current2, stats]);
10274
10344
  }
10275
- function forgotten(b, path22) {
10276
- return existsSync6(unlinked(join13(topicsHistoryRoot(b), "forgotten", `${digest3(path22)}.json`)));
10345
+ function forgotten(b, path23) {
10346
+ return existsSync6(unlinked(join13(topicsHistoryRoot(b), "forgotten", `${digest3(path23)}.json`)));
10277
10347
  }
10278
10348
  function openIndex(b, version) {
10279
10349
  if (!b.stateDir || !b.topicsDir) return null;
@@ -10311,6 +10381,27 @@ function hasTopicsHistory(b) {
10311
10381
  db2.close();
10312
10382
  return true;
10313
10383
  }
10384
+ function topicsHistoryRefsCurrent(b) {
10385
+ const db2 = openIndex(b);
10386
+ if (!db2) return false;
10387
+ try {
10388
+ const expected = rootKey(b);
10389
+ const meta = db2.prepare("SELECT value FROM metadata WHERE key='rootKey'").get();
10390
+ if (meta) return meta.value === expected;
10391
+ const rows = db2.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();
10392
+ return rows.every((row) => {
10393
+ try {
10394
+ return JSON.parse(row.ref).rootKey === expected;
10395
+ } catch {
10396
+ return false;
10397
+ }
10398
+ });
10399
+ } catch {
10400
+ return false;
10401
+ } finally {
10402
+ db2.close();
10403
+ }
10404
+ }
10314
10405
  async function topicsHistoryNeedsFallback(b) {
10315
10406
  const cached = fallbackChecks.get(key3(b));
10316
10407
  if (cached && cached.expiresAt > Date.now()) return cached.value;
@@ -10326,16 +10417,16 @@ async function walkTopicsNeedsFallback(b) {
10326
10417
  const visit = async (rel) => {
10327
10418
  const entries = await fs2.readdir(unlinked(join13(b.topicsDir, rel)), { withFileTypes: true });
10328
10419
  for (const entry of entries) {
10329
- const path22 = rel ? `${rel}/${entry.name}` : entry.name;
10420
+ const path23 = rel ? `${rel}/${entry.name}` : entry.name;
10330
10421
  if (entry.isSymbolicLink()) continue;
10331
10422
  if (entry.isDirectory()) {
10332
- if (await visit(path22)) return true;
10423
+ if (await visit(path23)) return true;
10333
10424
  continue;
10334
10425
  }
10335
- if (!entry.isFile() || !/\.md$/i.test(path22) || path22.toUpperCase() === "MEMORY.MD" || forgotten(b, path22)) continue;
10336
- const source = sources.get(path22);
10426
+ if (!entry.isFile() || !/\.md$/i.test(path23) || path23.toUpperCase() === "MEMORY.MD" || forgotten(b, path23)) continue;
10427
+ const source = sources.get(path23);
10337
10428
  if (!source) return true;
10338
- const stat3 = await fs2.stat(unlinked(join13(b.topicsDir, path22)));
10429
+ const stat3 = await fs2.stat(unlinked(join13(b.topicsDir, path23)));
10339
10430
  if (stat3.size !== source.bytes || stat3.mtimeMs !== source.mtime_ms) return true;
10340
10431
  }
10341
10432
  return false;
@@ -10462,6 +10553,7 @@ async function publishTopicsIndex(bundle, cleaned, b) {
10462
10553
  CREATE VIRTUAL TABLE documents USING fts5(source_path UNINDEXED,original_hash UNINDEXED,terms);
10463
10554
  CREATE VIRTUAL TABLE search USING fts5(id UNINDEXED,terms);`);
10464
10555
  db2.prepare("INSERT INTO metadata VALUES(?,?)").run("binding", canonical({ scope: topicsScope(b), root: resolve7(b.topicsDir) }));
10556
+ db2.prepare("INSERT INTO metadata VALUES(?,?)").run("rootKey", rootKey(b));
10465
10557
  const sourceInsert = db2.prepare("INSERT INTO sources VALUES(?,?,?,?)");
10466
10558
  for (const record of snapshot.manifest.records) sourceInsert.run(record.path, record.sha256, record.bytes, record.mtimeMs);
10467
10559
  const insert = db2.prepare("INSERT INTO entries VALUES(?,?,?,?,?,?,?,?,?)"), search = db2.prepare("INSERT INTO search VALUES(?,?)");
@@ -11248,7 +11340,7 @@ function readRelationshipContext(store, scope, request, clock = () => (/* @__PUR
11248
11340
  for (const entity of (request.graphEntityIds ?? []).flatMap((id) => resolve26(id) || []).filter((entity2) => !selected.has(entity2.entityId)).slice(0, 4)) {
11249
11341
  if (!context.people.some((person) => person.entityId === entity.entityId)) add("people", entity);
11250
11342
  }
11251
- for (const path22 of (request.graphPaths ?? []).slice(0, 40)) add("paths", path22, [path22.source, path22.target]);
11343
+ for (const path23 of (request.graphPaths ?? []).slice(0, 40)) add("paths", path23, [path23.source, path23.target]);
11252
11344
  const linkedIds = store.entities.list(scope, cutoff).filter((entity) => selected.has(resolve26(entity.entityId)?.entityId || entity.entityId)).map((entity) => entity.entityId);
11253
11345
  const views = recall.entitySources(linkedIds, maxRecords);
11254
11346
  const sourceIds = [.../* @__PURE__ */ new Set([
@@ -13321,23 +13413,23 @@ var init_facts = __esm({
13321
13413
  if ((exception || proposal.changeKind === "exception") && (!exception || schedule.frequency !== "once")) throw new Error("OCCURRENCE_EXCEPTION_REQUIRED");
13322
13414
  }
13323
13415
  for (const [index, evidence] of proposal.evidence.entries()) {
13324
- const path22 = `evidence[${index}]`;
13325
- if (!evidence || typeof evidence !== "object") throw new Error(`INVALID_EVIDENCE_SPAN: ${path22} \u2014 \u6BCF\u6761\u8BC1\u636E\u987B\u662F\u5BF9\u8C61 {sourceId, quote, relation}`);
13416
+ const path23 = `evidence[${index}]`;
13417
+ if (!evidence || typeof evidence !== "object") throw new Error(`INVALID_EVIDENCE_SPAN: ${path23} \u2014 \u6BCF\u6761\u8BC1\u636E\u987B\u662F\u5BF9\u8C61 {sourceId, quote, relation}`);
13326
13418
  const source = this.db.prepare(`SELECT text,role,origin_class,interpretation_status FROM memory_sources s WHERE scope_id=? AND source_id=?
13327
13419
  AND NOT EXISTS (SELECT 1 FROM memory_sources newer WHERE newer.scope_id=s.scope_id
13328
13420
  AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)`).get(scopeId(scope), evidence.sourceId ?? null);
13329
- if (!source || source.interpretation_status === "deleted") throw new Error(`INVALID_EVIDENCE_SPAN: ${path22}.sourceId \u2014 \u672C\u6C60\u8BFB\u4E0D\u5230\u8FD9\u6761\u6765\u6E90\uFF08\u4E0D\u5B58\u5728\u3001\u5DF2\u5220\u9664\u6216\u5DF2\u6709\u65B0\u7248\u672C\uFF09\uFF1B\u7528 memory_get({source_id}) \u6838\u5BF9\u5E76\u590D\u5236\u771F\u5B9E\u6765\u6E90 ID`);
13330
- if (typeof evidence.quote !== "string" || !evidence.quote) throw new Error(`INVALID_EVIDENCE_SPAN: ${path22}.quote \u2014 quote \u5FC5\u586B\uFF0C\u9010\u5B57\u51FA\u81EA\u6765\u6E90\u539F\u6587`);
13421
+ if (!source || source.interpretation_status === "deleted") throw new Error(`INVALID_EVIDENCE_SPAN: ${path23}.sourceId \u2014 \u672C\u6C60\u8BFB\u4E0D\u5230\u8FD9\u6761\u6765\u6E90\uFF08\u4E0D\u5B58\u5728\u3001\u5DF2\u5220\u9664\u6216\u5DF2\u6709\u65B0\u7248\u672C\uFF09\uFF1B\u7528 memory_get({source_id}) \u6838\u5BF9\u5E76\u590D\u5236\u771F\u5B9E\u6765\u6E90 ID`);
13422
+ if (typeof evidence.quote !== "string" || !evidence.quote) throw new Error(`INVALID_EVIDENCE_SPAN: ${path23}.quote \u2014 quote \u5FC5\u586B\uFF0C\u9010\u5B57\u51FA\u81EA\u6765\u6E90\u539F\u6587`);
13331
13423
  if (!Number.isSafeInteger(evidence.start) || !Number.isSafeInteger(evidence.end) || evidence.start < 0 || evidence.end <= evidence.start || evidence.end > source.text.length || source.text.slice(evidence.start, evidence.end) !== evidence.quote) {
13332
13424
  const count = occurrences(source.text, evidence.quote);
13333
- throw new Error(count === 0 ? `INVALID_EVIDENCE_SPAN: ${path22}.quote \u2014 \u5F15\u6587\u5FC5\u987B\u9010\u5B57\u51FA\u81EA\u6765\u6E90\u539F\u6587\uFF08\u539F\u6587\u957F ${source.text.length}\uFF09\uFF1B\u7528 memory_get({source_id}) \u590D\u5236\u539F\u53E5\uFF0C\u4E0D\u8981\u6539\u5199` : `INVALID_EVIDENCE_SPAN: ${path22} \u2014 \u5F15\u6587\u5728\u539F\u6587\u4E2D\u51FA\u73B0 ${count} \u6B21\uFF0C\u8BF7\u7ED9\u51C6\u786E\u7684\u90A3\u4E00\u5904 start/end\uFF08UTF-16 \u4E0B\u6807\uFF0C\u539F\u6587\u957F ${source.text.length}\uFF09`);
13425
+ throw new Error(count === 0 ? `INVALID_EVIDENCE_SPAN: ${path23}.quote \u2014 \u5F15\u6587\u5FC5\u987B\u9010\u5B57\u51FA\u81EA\u6765\u6E90\u539F\u6587\uFF08\u539F\u6587\u957F ${source.text.length}\uFF09\uFF1B\u7528 memory_get({source_id}) \u590D\u5236\u539F\u53E5\uFF0C\u4E0D\u8981\u6539\u5199` : `INVALID_EVIDENCE_SPAN: ${path23} \u2014 \u5F15\u6587\u5728\u539F\u6587\u4E2D\u51FA\u73B0 ${count} \u6B21\uFF0C\u8BF7\u7ED9\u51C6\u786E\u7684\u90A3\u4E00\u5904 start/end\uFF08UTF-16 \u4E0B\u6807\uFF0C\u539F\u6587\u957F ${source.text.length}\uFF09`);
13334
13426
  }
13335
- if (!["supports", "refutes"].includes(evidence.relation)) throw new Error(`INVALID_EVIDENCE_SPAN: ${path22}.relation \u2014 \u53EA\u80FD\u662F supports\uFF08\u652F\u6301\uFF09\u6216 refutes\uFF08\u53CD\u9A73\uFF09`);
13427
+ if (!["supports", "refutes"].includes(evidence.relation)) throw new Error(`INVALID_EVIDENCE_SPAN: ${path23}.relation \u2014 \u53EA\u80FD\u662F supports\uFF08\u652F\u6301\uFF09\u6216 refutes\uFF08\u53CD\u9A73\uFF09`);
13336
13428
  const relationValue = proposal.value;
13337
13429
  if (proposal.predicate === "relation.open" && relationValue?.attribution === "reported" && (proposal.claimKind !== "reported_statement" || !hasReportedAttribution(source.text, relationValue, this.entities.sourceMentions(scope, evidence.sourceId)))) {
13338
13430
  throw new Error("EVIDENCE_REPORTED_ATTRIBUTION_UNGROUNDED: attribution=reported \u65F6 claimKind \u987B\u4E3A reported_statement\uFF0C\u4E14 attributionQuote \u5FC5\u987B\u662F\u539F\u8BDD\u91CC\u9010\u5B57\u7684\u8F6C\u8FF0\u53E5\uFF08\u5982\u300C\u67D0\u67D0\u8BF4\uFF1A\u300D\uFF09");
13339
13431
  }
13340
- const roleMismatch = () => new Error(`EVIDENCE_ROLE_MISMATCH: ${path22} \u7684\u4F5C\u8005/\u89D2\u8272\u4E0E claimKind=${proposal.claimKind} \u4E0D\u7B26\uFF08\u6765\u6E90 role=${source.role}, originClass=${source.origin_class}\uFF09 \u2014 \u7528\u6237\u539F\u8BDD\u914D user_statement\u3001\u5DE5\u5177\u7ED3\u679C\u914D tool_observation\u3001\u8F6C\u8FF0\u4ED6\u4EBA\u914D reported_statement\u3001\u4F60\u81EA\u5DF1\u8BF4\u7684\u8BDD\u914D agent_statement\uFF1B\u6362\u5339\u914D\u7684\u6765\u6E90\u6216\u6539 claimKind`);
13432
+ const roleMismatch = () => new Error(`EVIDENCE_ROLE_MISMATCH: ${path23} \u7684\u4F5C\u8005/\u89D2\u8272\u4E0E claimKind=${proposal.claimKind} \u4E0D\u7B26\uFF08\u6765\u6E90 role=${source.role}, originClass=${source.origin_class}\uFF09 \u2014 \u7528\u6237\u539F\u8BDD\u914D user_statement\u3001\u5DE5\u5177\u7ED3\u679C\u914D tool_observation\u3001\u8F6C\u8FF0\u4ED6\u4EBA\u914D reported_statement\u3001\u4F60\u81EA\u5DF1\u8BF4\u7684\u8BDD\u914D agent_statement\uFF1B\u6362\u5339\u914D\u7684\u6765\u6E90\u6216\u6539 claimKind`);
13341
13433
  if (proposal.claimKind !== "inference") {
13342
13434
  if (proposal.claimKind === "user_statement" && (source.role !== "user" || !["host_user", "client_reported_user"].includes(source.origin_class))) throw roleMismatch();
13343
13435
  if (proposal.claimKind === "tool_observation" && (source.role !== "tool" || source.origin_class !== "tool_observation")) throw roleMismatch();
@@ -13697,7 +13789,7 @@ function contentHash(text2) {
13697
13789
  function mem7Root(stateDir2) {
13698
13790
  return join14(stateDir2, "mem7");
13699
13791
  }
13700
- var STALE_ARTIFACT_FORCE_MS, SCHEMA, AGENT_SCHEMA, Mem7Store;
13792
+ var STALE_ARTIFACT_FORCE_MS, STARVATION_GRACE_MS, SCHEMA, AGENT_SCHEMA, Mem7Store;
13701
13793
  var init_store = __esm({
13702
13794
  "src/mem7/core/store.ts"() {
13703
13795
  "use strict";
@@ -13735,6 +13827,7 @@ var init_store = __esm({
13735
13827
  init_job_retention();
13736
13828
  init_retire_graph_audits();
13737
13829
  STALE_ARTIFACT_FORCE_MS = 2 * 36e5;
13830
+ STARVATION_GRACE_MS = 36e5;
13738
13831
  SCHEMA = `
13739
13832
  CREATE TABLE IF NOT EXISTS memcells (
13740
13833
  id TEXT PRIMARY KEY,
@@ -14328,13 +14421,13 @@ CREATE TABLE IF NOT EXISTS cluster_members (
14328
14421
  const version = expectedVersion ?? this.dependencies.version(scope, kind, id);
14329
14422
  this.dependencies.assertCurrent(scope, kind, id, version);
14330
14423
  const digest7 = createHash20("sha256").update(content.trim()).digest("hex");
14331
- const path22 = relative3(this.root, file2).replace(/\\/g, "/");
14424
+ const path23 = relative3(this.root, file2).replace(/\\/g, "/");
14332
14425
  const previous = this.db.prepare("SELECT version,digest,path FROM memory_projection_entries WHERE scope_id=? AND kind=? AND entry_id=?").get(scopeId(scope), kind, id);
14333
- if (previous?.version === version && (previous.digest !== digest7 || previous.path !== path22)) throw new Error("PROJECTION_PUBLICATION_VERSION_CONFLICT");
14426
+ if (previous?.version === version && (previous.digest !== digest7 || previous.path !== path23)) throw new Error("PROJECTION_PUBLICATION_VERSION_CONFLICT");
14334
14427
  this.db.prepare(`INSERT INTO memory_projection_entries VALUES (?,?,?,?,?,?)
14335
14428
  ON CONFLICT(scope_id,kind,entry_id) DO UPDATE SET path=excluded.path,version=excluded.version,digest=excluded.digest
14336
- WHERE excluded.version>=memory_projection_entries.version`).run(scopeId(scope), kind, id, path22, version, digest7);
14337
- this.artifacts.publish(scope, { ...body, kind, id, version, medium: "markdown", path: path22, markdown: content.trim() });
14429
+ WHERE excluded.version>=memory_projection_entries.version`).run(scopeId(scope), kind, id, path23, version, digest7);
14430
+ this.artifacts.publish(scope, { ...body, kind, id, version, medium: "markdown", path: path23, markdown: content.trim() });
14338
14431
  });
14339
14432
  }
14340
14433
  projectionMatches(scope, kind, id, file2, content) {
@@ -14531,8 +14624,8 @@ CREATE TABLE IF NOT EXISTS cluster_members (
14531
14624
  };
14532
14625
  }
14533
14626
  unscopedProjectionMatches(ownerId, kind, id, file2, content) {
14534
- const path22 = relative3(this.root, file2).replace(/\\/g, "/");
14535
- const mappings = this.db.prepare("SELECT scope_id FROM memory_projection_entries WHERE kind=? AND entry_id=? AND path=?").all(kind, id, path22);
14627
+ const path23 = relative3(this.root, file2).replace(/\\/g, "/");
14628
+ const mappings = this.db.prepare("SELECT scope_id FROM memory_projection_entries WHERE kind=? AND entry_id=? AND path=?").all(kind, id, path23);
14536
14629
  if (mappings.length) {
14537
14630
  if (mappings.length !== 1) return false;
14538
14631
  const scope = this.sources.scope(mappings[0].scope_id);
@@ -14825,7 +14918,7 @@ ${e.outcome}
14825
14918
  return this.transaction(() => {
14826
14919
  const kindFilter = options.kinds ? ` AND kind IN (${options.kinds.map(() => "?").join(",")})` : "";
14827
14920
  const scopeFilter = options.scopeId !== void 0 ? " AND scope_id=?" : "";
14828
- 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"}
14921
+ 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"}
14829
14922
  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)
14830
14923
  AND ((status='pending' AND next_run_at<=?)
14831
14924
  OR (status='running' AND COALESCE(lease_until,0)<=?))${kindFilter}${scopeFilter}
@@ -14845,40 +14938,48 @@ ${e.outcome}
14845
14938
  -- Cognition rebuilds its read set at claim time; delayed old work must not fence fresh judgments.
14846
14939
  AND (kind IN ('social.interpret','source.interpret','relationship.cognition') OR scope_id NOT LIKE 'resource:%' OR NOT EXISTS (SELECT 1 FROM ome_jobs prior
14847
14940
  WHERE prior.scope_id=j.scope_id AND prior.id<j.id AND prior.status IN ('pending','running')
14848
- 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)
14849
- -- Retrying an old deferred job must not reserve the next stage budget.
14850
- -- Boundary/resource predecessor predicates above still enforce ordering.
14851
- ORDER BY priority,next_run_at,id LIMIT ?`).all(now2, now2, ...options.kinds ?? [], ...options.scopeId !== void 0 ? [options.scopeId] : [], now2, limit);
14852
- const claimedScopes = /* @__PURE__ */ new Set();
14853
- return rows.flatMap((row) => {
14854
- if (!this.jobProvenance.prepareForClaim(row.id, now2)) return [];
14855
- const updated = this.db.prepare("SELECT * FROM ome_jobs WHERE id=?").get(row.id);
14856
- if (updated.scope_id !== row.scope_id && updated.scope_id) {
14857
- const conflict = this.db.prepare(`SELECT 1 FROM ome_jobs j WHERE j.scope_id=? AND j.id<>?
14858
- AND (j.status='running' AND j.lease_until>? OR ? LIKE 'resource:%' AND j.id<? AND j.status IN ('pending','running')
14859
- 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);
14860
- if (conflict) return [];
14861
- }
14862
- return [updated];
14863
- }).filter((row) => {
14864
- if (!row.scope_id) return true;
14865
- if (claimedScopes.has(row.scope_id)) return false;
14866
- claimedScopes.add(row.scope_id);
14867
- return true;
14868
- }).map((row) => {
14869
- const leaseToken = randomUUID10();
14870
- this.db.prepare("UPDATE ome_jobs SET status='running',lease_token=?,lease_until=? WHERE id=?").run(leaseToken, now2 + leaseMs, row.id);
14871
- return {
14872
- id: row.id,
14873
- kind: row.kind,
14874
- payload: JSON.parse(row.payload),
14875
- attempts: row.attempts,
14876
- leaseToken,
14877
- inputVersion: row.input_version,
14878
- scopeId: row.scope_id ?? void 0,
14879
- result: row.result_json === null ? void 0 : JSON.parse(row.result_json)
14880
- };
14881
- });
14941
+ 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)`;
14942
+ const select = (starved2) => {
14943
+ const sql = `${base}${starved2 ? " AND status='pending' AND next_run_at<=?" : ""}
14944
+ ORDER BY priority,next_run_at,id LIMIT ?`;
14945
+ const args2 = 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];
14946
+ return this.db.prepare(sql).all(...args2);
14947
+ };
14948
+ const claim = (rows) => {
14949
+ const claimedScopes = /* @__PURE__ */ new Set();
14950
+ return rows.flatMap((row) => {
14951
+ if (!this.jobProvenance.prepareForClaim(row.id, now2)) return [];
14952
+ const updated = this.db.prepare("SELECT * FROM ome_jobs WHERE id=?").get(row.id);
14953
+ if (updated.scope_id !== row.scope_id && updated.scope_id) {
14954
+ const conflict = this.db.prepare(`SELECT 1 FROM ome_jobs j WHERE j.scope_id=? AND j.id<>?
14955
+ AND (j.status='running' AND j.lease_until>? OR ? LIKE 'resource:%' AND j.id<? AND j.status IN ('pending','running')
14956
+ 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);
14957
+ if (conflict) return [];
14958
+ }
14959
+ return [updated];
14960
+ }).filter((row) => {
14961
+ if (!row.scope_id) return true;
14962
+ if (claimedScopes.has(row.scope_id)) return false;
14963
+ claimedScopes.add(row.scope_id);
14964
+ return true;
14965
+ }).map((row) => {
14966
+ const leaseToken = randomUUID10();
14967
+ this.db.prepare("UPDATE ome_jobs SET status='running',lease_token=?,lease_until=? WHERE id=?").run(leaseToken, now2 + leaseMs, row.id);
14968
+ return {
14969
+ id: row.id,
14970
+ kind: row.kind,
14971
+ payload: JSON.parse(row.payload),
14972
+ attempts: row.attempts,
14973
+ leaseToken,
14974
+ inputVersion: row.input_version,
14975
+ scopeId: row.scope_id ?? void 0,
14976
+ result: row.result_json === null ? void 0 : JSON.parse(row.result_json)
14977
+ };
14978
+ });
14979
+ };
14980
+ if (options.staleOnly) return claim(select(true));
14981
+ const starved = claim(select(true));
14982
+ return starved.length ? starved : claim(select(false));
14882
14983
  });
14883
14984
  }
14884
14985
  /** Compatibility entry point: only expired leases can be recovered. */
@@ -15319,19 +15420,19 @@ import { dirname as dirname7, join as join15, resolve as resolve8 } from "node:p
15319
15420
  import { createHash as createHash21, randomUUID as randomUUID11 } from "node:crypto";
15320
15421
  function assertPath(root, rel) {
15321
15422
  if (!safeRel(rel)) throw Error("TRAVEL_UNSAFE_PATH");
15322
- let path22 = root;
15423
+ let path23 = root;
15323
15424
  for (const part of rel.split("/")) {
15324
- path22 = join15(path22, part);
15425
+ path23 = join15(path23, part);
15325
15426
  try {
15326
- if (lstatSync9(path22).isSymbolicLink()) throw Error("TRAVEL_UNSAFE_PATH");
15427
+ if (lstatSync9(path23).isSymbolicLink()) throw Error("TRAVEL_UNSAFE_PATH");
15327
15428
  } catch (e) {
15328
15429
  if (e.code !== "ENOENT") throw e;
15329
15430
  }
15330
15431
  }
15331
- return path22;
15432
+ return path23;
15332
15433
  }
15333
- function atomic(path22, body, exclusive = false) {
15334
- const temp = path22 + "." + randomUUID11() + ".tmp";
15434
+ function atomic(path23, body, exclusive = false) {
15435
+ const temp = path23 + "." + randomUUID11() + ".tmp";
15335
15436
  let fd;
15336
15437
  try {
15337
15438
  fd = openSync7(temp, "wx", 384);
@@ -15339,8 +15440,8 @@ function atomic(path22, body, exclusive = false) {
15339
15440
  fsyncSync6(fd);
15340
15441
  closeSync7(fd);
15341
15442
  fd = void 0;
15342
- if (exclusive) linkSync(temp, path22);
15343
- else renameSync6(temp, path22);
15443
+ if (exclusive) linkSync(temp, path23);
15444
+ else renameSync6(temp, path23);
15344
15445
  } finally {
15345
15446
  if (fd !== void 0) closeSync7(fd);
15346
15447
  rmSync(temp, { force: true });
@@ -15352,16 +15453,16 @@ function read(root) {
15352
15453
  if (value.version !== 1 || value.root !== resolve8(root) || !Number.isSafeInteger(value.pid) || value.pid < 1 || !/^[a-f0-9-]{36}$/.test(value.token) || typeof value.committed !== "boolean" || digest7 !== hash7(JSON.stringify(body)) || !Array.isArray(value.entries) || value.entries.some((e) => !safeRel(e.rel) || e.oldSha !== void 0 && !/^[a-f0-9]{64}$/.test(e.oldSha) || e.newSha !== void 0 && !/^[a-f0-9]{64}$/.test(e.newSha))) throw Error("TRAVEL_APPLY_RECOVERY_INVALID");
15353
15454
  return value;
15354
15455
  }
15355
- function matches(path22, sha) {
15356
- if (!existsSync8(path22)) return false;
15357
- const fd = openSync7(path22, "r"), digest7 = createHash21("sha256"), buffer = Buffer.alloc(1048576);
15456
+ function matches(path23, sha2) {
15457
+ if (!existsSync8(path23)) return false;
15458
+ const fd = openSync7(path23, "r"), digest7 = createHash21("sha256"), buffer = Buffer.alloc(1048576);
15358
15459
  try {
15359
15460
  for (; ; ) {
15360
15461
  const n = readSync2(fd, buffer, 0, buffer.length, null);
15361
15462
  if (!n) break;
15362
15463
  digest7.update(buffer.subarray(0, n));
15363
15464
  }
15364
- return digest7.digest("hex") === sha;
15465
+ return digest7.digest("hex") === sha2;
15365
15466
  } finally {
15366
15467
  closeSync7(fd);
15367
15468
  }
@@ -15469,10 +15570,10 @@ function isCorruption(error) {
15469
15570
  if (code === 11 || code === 26) return true;
15470
15571
  return /database disk image is malformed|file is not a database/i.test(String(error?.message ?? error));
15471
15572
  }
15472
- function healthyDatabase(path22) {
15573
+ function healthyDatabase(path23) {
15473
15574
  let db2;
15474
15575
  try {
15475
- db2 = new DatabaseSync9(path22);
15576
+ db2 = new DatabaseSync9(path23);
15476
15577
  const check = db2.prepare("PRAGMA quick_check").get();
15477
15578
  return check?.quick_check === "ok";
15478
15579
  } catch {
@@ -15894,10 +15995,10 @@ var init_atomic_facts = __esm({
15894
15995
  import { existsSync as existsSync10, readFileSync as readFileSync16, writeFileSync as writeFileSync10, mkdirSync as mkdirSync12, renameSync as renameSync8 } from "node:fs";
15895
15996
  import { join as join19, dirname as dirname10 } from "node:path";
15896
15997
  function readStatusDoc(root, sid) {
15897
- const path22 = docPath(root, sid);
15898
- if (!existsSync10(path22)) return null;
15998
+ const path23 = docPath(root, sid);
15999
+ if (!existsSync10(path23)) return null;
15899
16000
  try {
15900
- const parsed = JSON.parse(readFileSync16(path22, "utf-8"));
16001
+ const parsed = JSON.parse(readFileSync16(path23, "utf-8"));
15901
16002
  if (!parsed || parsed.doc !== null && !validDoc(parsed.doc) || parsed.sourceSeq !== null && (!Number.isSafeInteger(parsed.sourceSeq) || parsed.sourceSeq < 0) || typeof parsed.updatedAt !== "string" || !Number.isFinite(Date.parse(parsed.updatedAt)) || parsed.failedAt !== void 0 && !Number.isFinite(Date.parse(parsed.failedAt))) return null;
15902
16003
  return parsed;
15903
16004
  } catch {
@@ -15975,11 +16076,11 @@ Merge into the status document per the system contract. Return only the JSON obj
15975
16076
  }
15976
16077
  }
15977
16078
  function writeDoc(root, sid, file2) {
15978
- const path22 = docPath(root, sid);
15979
- mkdirSync12(dirname10(path22), { recursive: true });
15980
- const tmp = path22 + ".tmp";
16079
+ const path23 = docPath(root, sid);
16080
+ mkdirSync12(dirname10(path23), { recursive: true });
16081
+ const tmp = path23 + ".tmp";
15981
16082
  writeFileSync10(tmp, JSON.stringify(file2), "utf-8");
15982
- renameSync8(tmp, path22);
16083
+ renameSync8(tmp, path23);
15983
16084
  }
15984
16085
  var MERGE_MIN_INTERVAL_SEQ, MERGE_FAIL_COOLDOWN_MS, dirPath, docPath, MERGE_SYSTEM;
15985
16086
  var init_status_doc = __esm({
@@ -16628,7 +16729,8 @@ function buildMemoryContext(store, scope, request, clock = () => (/* @__PURE__ *
16628
16729
  if (!resolved.has(id)) resolved.set(id, store.entities.resolve(scope, id, snapshot.entityRevision, cutoff ?? void 0));
16629
16730
  return resolved.get(id);
16630
16731
  };
16631
- const resolvedSelection = new Set((request.entityRef || matching.length ? matching : entities).map((entity) => resolve26(entity.entityId)?.entityId));
16732
+ const pool = request.entityRef || matching.length ? matching : request.matchedEntitiesOnly ? [] : entities;
16733
+ const resolvedSelection = new Set(pool.map((entity) => resolve26(entity.entityId)?.entityId));
16632
16734
  const selected = new Set(entities.filter((entity) => resolvedSelection.has(resolve26(entity.entityId)?.entityId)).map((entity) => entity.entityId));
16633
16735
  const context = {
16634
16736
  validAt,
@@ -16987,9 +17089,9 @@ function snapshotFiles(store, request) {
16987
17089
  return { path: relative4(root, file2).replace(/\\/g, "/"), digest: digest7 };
16988
17090
  }).sort((a, b) => a.path.localeCompare(b.path));
16989
17091
  }
16990
- function ownFilePublication(store, request, path22, version) {
17092
+ function ownFilePublication(store, request, path23, version) {
16991
17093
  if (request.kind !== "skills" && request.kind !== "profile") return false;
16992
- const file2 = join25(store.mem7RootPath(), path22);
17094
+ const file2 = join25(store.mem7RootPath(), path23);
16993
17095
  let text2;
16994
17096
  try {
16995
17097
  text2 = readFileSync22(file2, "utf8");
@@ -17019,9 +17121,9 @@ function assertArtifactFileInputs(store, inputs, publicationVersion) {
17019
17121
  const current2 = currentInput(store, input.request);
17020
17122
  const oldFiles = new Map(input.files.map((file2) => [file2.path, file2.digest]));
17021
17123
  const newFiles = new Map(current2.files.map((file2) => [file2.path, file2.digest]));
17022
- for (const path22 of /* @__PURE__ */ new Set([...oldFiles.keys(), ...newFiles.keys()])) {
17023
- if (oldFiles.get(path22) === newFiles.get(path22)) continue;
17024
- if (publicationVersion !== void 0 && ownFilePublication(store, input.request, path22, publicationVersion)) continue;
17124
+ for (const path23 of /* @__PURE__ */ new Set([...oldFiles.keys(), ...newFiles.keys()])) {
17125
+ if (oldFiles.get(path23) === newFiles.get(path23)) continue;
17126
+ if (publicationVersion !== void 0 && ownFilePublication(store, input.request, path23, publicationVersion)) continue;
17025
17127
  throw new SupersededJobError("ARTIFACT_FILE_INPUT_CHANGED");
17026
17128
  }
17027
17129
  const expected = new Map(input.entries.map((entry) => [entry.id, entry.digest]));
@@ -18381,6 +18483,12 @@ async function drainMem7Pipeline(args2) {
18381
18483
  maxJobs,
18382
18484
  afterJob: () => afterBackgroundJob("boundary")
18383
18485
  }));
18486
+ await phase("extraction-urgent", () => drainJobs(store, handlers2, {
18487
+ kinds: memoryKinds,
18488
+ maxJobs: Math.min(maxJobs, 20),
18489
+ budgetMs: 6e4,
18490
+ staleOnly: true
18491
+ }));
18384
18492
  for (const scope of store.sources.scopes()) await interpretPending(scope, args2.interpretationBatches ?? 20);
18385
18493
  for (const scope of store.sources.scopes()) {
18386
18494
  await phase("social-interpretation", () => drainSocialInterpretations({
@@ -25305,7 +25413,7 @@ function listForesightMds(dir) {
25305
25413
  }
25306
25414
  function findForesightFiles(everosRoot) {
25307
25415
  const files = [];
25308
- const walk = (dir, depth) => {
25416
+ const walk2 = (dir, depth) => {
25309
25417
  if (depth > 4) return;
25310
25418
  let entries;
25311
25419
  try {
@@ -25319,12 +25427,12 @@ function findForesightFiles(everosRoot) {
25319
25427
  if (e.name === ".foresights") {
25320
25428
  files.push(...listForesightMds(p));
25321
25429
  } else if (!e.name.startsWith(".") && e.name !== "__pycache__") {
25322
- walk(p, depth + 1);
25430
+ walk2(p, depth + 1);
25323
25431
  }
25324
25432
  }
25325
25433
  }
25326
25434
  };
25327
- walk(everosRoot, 0);
25435
+ walk2(everosRoot, 0);
25328
25436
  return files;
25329
25437
  }
25330
25438
  function opportunityScheduledTime(now2, concrete) {
@@ -26456,8 +26564,10 @@ async function executeOneHook(hook, hookEvent, hookName, hookInput, toolUseID, s
26456
26564
  hookEvent,
26457
26565
  durationMs: durationMs2
26458
26566
  });
26567
+ const output = syncOutput.hookSpecificOutput;
26459
26568
  return {
26460
26569
  ...processed,
26570
+ ...hook.id === "skill-gate-prompt" && output?.hookEventName === "UserPromptSubmit" && output.selectSkill === true ? { selectSkill: true } : {},
26461
26571
  outcome: processed.blockingError ? "blocking" : "success",
26462
26572
  hook
26463
26573
  };
@@ -26559,6 +26669,7 @@ function aggregateResults(results) {
26559
26669
  if (result.permissionBehavior) {
26560
26670
  aggregated.permissionBehavior = result.permissionBehavior;
26561
26671
  }
26672
+ if (result.selectSkill) aggregated.selectSkill = true;
26562
26673
  if (result.additionalContext) {
26563
26674
  aggregated.additionalContexts.push(result.additionalContext);
26564
26675
  }
@@ -29404,9 +29515,9 @@ function buildPlanningContext(calDb, workspace2, memory) {
29404
29515
  function captureScanPlanningContext(workspace2, memory, calDb) {
29405
29516
  const read3 = () => {
29406
29517
  if (calDb !== void 0) return buildPlanningContext(calDb, workspace2, memory);
29407
- const path22 = join32(workspace2, ".calendar", "calendar.db");
29408
- if (!existsSync13(path22)) return buildPlanningContext(null, workspace2, memory);
29409
- const db2 = new DatabaseSync13(path22, { readOnly: true });
29518
+ const path23 = join32(workspace2, ".calendar", "calendar.db");
29519
+ if (!existsSync13(path23)) return buildPlanningContext(null, workspace2, memory);
29520
+ const db2 = new DatabaseSync13(path23, { readOnly: true });
29410
29521
  try {
29411
29522
  return buildPlanningContext(db2, workspace2, memory);
29412
29523
  } finally {
@@ -31826,9 +31937,9 @@ function isAutoMemPath(absolutePath, workspace2) {
31826
31937
  return normalizedPath.startsWith(getAutoMemPath(workspace2));
31827
31938
  }
31828
31939
  async function ensureMemoryDirExists(memoryDir) {
31829
- const fs23 = await import("node:fs");
31940
+ const fs24 = await import("node:fs");
31830
31941
  try {
31831
- await fs23.promises.mkdir(memoryDir, { recursive: true });
31942
+ await fs24.promises.mkdir(memoryDir, { recursive: true });
31832
31943
  } catch (e) {
31833
31944
  const code = e?.code;
31834
31945
  if (code !== "EEXIST") {
@@ -31864,8 +31975,8 @@ function physicalPath(target) {
31864
31975
  }
31865
31976
  return path7.resolve(fs7.realpathSync(ancestor), path7.relative(ancestor, target));
31866
31977
  }
31867
- function withoutRepeatedDirectories(relative11) {
31868
- const parts = relative11.split(path7.sep);
31978
+ function withoutRepeatedDirectories(relative12) {
31979
+ const parts = relative12.split(path7.sep);
31869
31980
  while (parts.length > 1 && parts[0].toLowerCase() === AUTO_MEM_DIRNAME) parts.shift();
31870
31981
  return parts.filter((part, index) => index === parts.length - 1 || index === 0 || part.toLowerCase() !== parts[index - 1].toLowerCase()).join(path7.sep);
31871
31982
  }
@@ -31890,28 +32001,28 @@ function resolveFilePath(requested, context, writing = false) {
31890
32001
  if (!isWithin(root, resolved) || !isWithin(physicalPath(root), physicalPath(resolved))) {
31891
32002
  throw new Error("\u8DEF\u5F84\u8D85\u51FA\u5F53\u524D\u8BB0\u5FC6\u76EE\u5F55\uFF1B\u8BF7\u4F7F\u7528\u76F8\u5BF9\u8BB0\u5FC6\u76EE\u5F55\u7684\u8DEF\u5F84\u3002");
31892
32003
  }
31893
- const relative11 = path7.relative(root, resolved);
32004
+ const relative12 = path7.relative(root, resolved);
31894
32005
  if (writing) {
31895
32006
  if (path7.basename(resolved).toUpperCase() === "MEMORY.MD") {
31896
32007
  const canonicalIndex = path7.join(root, "MEMORY.md");
31897
32008
  const indexNames = fs7.existsSync(root) ? fs7.readdirSync(root).filter((name) => name.toUpperCase() === "MEMORY.MD") : [];
31898
32009
  let sameIndex = false;
31899
- if (path7.dirname(relative11) === "." && indexNames.length === 1 && fs7.existsSync(resolved) && fs7.existsSync(canonicalIndex)) {
32010
+ if (path7.dirname(relative12) === "." && indexNames.length === 1 && fs7.existsSync(resolved) && fs7.existsSync(canonicalIndex)) {
31900
32011
  const requestedEntry = fs7.lstatSync(resolved);
31901
32012
  const canonicalEntry = fs7.lstatSync(canonicalIndex);
31902
32013
  sameIndex = requestedEntry.dev === canonicalEntry.dev && requestedEntry.ino === canonicalEntry.ino;
31903
32014
  }
31904
- if (relative11 !== "MEMORY.md" && !sameIndex || relative11 === "MEMORY.md" && indexNames.length > 0 && !fs7.existsSync(canonicalIndex)) {
32015
+ if (relative12 !== "MEMORY.md" && !sameIndex || relative12 === "MEMORY.md" && indexNames.length > 0 && !fs7.existsSync(canonicalIndex)) {
31905
32016
  throw new Error("\u8BB0\u5FC6\u7D22\u5F15\u53EA\u80FD\u4F7F\u7528\u6839\u76EE\u5F55\u7684 MEMORY.md\uFF0C\u4E0D\u80FD\u521B\u5EFA\u6216\u66F4\u65B0\u7B2C\u4E8C\u4EFD\u7D22\u5F15\u3002");
31906
32017
  }
31907
32018
  }
31908
32019
  if (!fs7.existsSync(resolved)) {
31909
- const parts = relative11.split(path7.sep);
32020
+ const parts = relative12.split(path7.sep);
31910
32021
  if (parts[0].toLowerCase() === AUTO_MEM_DIRNAME || parts.some((part, index) => index > 0 && index < parts.length - 1 && part.toLowerCase() === parts[index - 1].toLowerCase())) {
31911
32022
  throw new Error("\u91CD\u590D\u8BB0\u5FC6\u76EE\u5F55\u524D\u7F00\uFF1B\u8DEF\u5F84\u4ECE\u8BB0\u5FC6\u76EE\u5F55\u5185\u5F00\u59CB\uFF0C\u4F8B\u5982 project/project_YYYY-MM-DD_name.md\u3002");
31912
32023
  }
31913
32024
  if (fs7.existsSync(root)) {
31914
- const existing = fs7.readdirSync(root, { recursive: true }).filter((entry) => typeof entry === "string" && entry.endsWith(".md") && entry !== relative11 && path7.basename(entry).toUpperCase() !== "MEMORY.MD" && withoutRepeatedDirectories(entry) === relative11);
32025
+ const existing = fs7.readdirSync(root, { recursive: true }).filter((entry) => typeof entry === "string" && entry.endsWith(".md") && entry !== relative12 && path7.basename(entry).toUpperCase() !== "MEMORY.MD" && withoutRepeatedDirectories(entry) === relative12);
31915
32026
  if (existing.length > 0) {
31916
32027
  throw new Error(`\u5DF2\u6709\u8BB0\u5FC6\u6587\u4EF6\u4F4D\u4E8E ${existing.map((entry) => entry.replace(/\\/g, "/")).join("\u3001")}\uFF1B\u4E0D\u80FD\u901A\u8FC7\u7F29\u77ED\u65E7\u5206\u53C9\u8DEF\u5F84\u521B\u5EFA\u53E6\u4E00\u4EFD\u6587\u4EF6\u3002\u8BF7\u6309\u539F\u8DEF\u5F84\u8BFB\u53D6\u540E\u66F4\u65B0\u3002`);
31917
32028
  }
@@ -32464,8 +32575,8 @@ function notificationStateChange(route, queueStateDir) {
32464
32575
  function createNotificationStateReader() {
32465
32576
  const databases = /* @__PURE__ */ new Map();
32466
32577
  const checkers = /* @__PURE__ */ new Map();
32467
- const open3 = (path22) => {
32468
- const key5 = resolve13(path22);
32578
+ const open3 = (path23) => {
32579
+ const key5 = resolve13(path23);
32469
32580
  let db2 = databases.get(key5);
32470
32581
  if (!db2) {
32471
32582
  db2 = new DatabaseSync11(key5, { readOnly: true });
@@ -33637,11 +33748,11 @@ var init_execution_guard = __esm({
33637
33748
  // src/memory/proactive/relationship-snapshot.ts
33638
33749
  import { existsSync as existsSync17 } from "node:fs";
33639
33750
  import { DatabaseSync as DatabaseSync15 } from "node:sqlite";
33640
- function readRelationshipGraphSnapshot(path22) {
33641
- if (!path22 || !existsSync17(path22)) return void 0;
33751
+ function readRelationshipGraphSnapshot(path23) {
33752
+ if (!path23 || !existsSync17(path23)) return void 0;
33642
33753
  let db2;
33643
33754
  try {
33644
- db2 = new DatabaseSync15(path22, { readOnly: true });
33755
+ db2 = new DatabaseSync15(path23, { readOnly: true });
33645
33756
  db2.exec("BEGIN");
33646
33757
  const version = readSchemaVersion(db2);
33647
33758
  if (version?.component !== "proactive" || version.version !== PROACTIVE_SCHEMA_VERSION) return void 0;
@@ -34750,8 +34861,8 @@ import { cp, readdir, rm } from "node:fs/promises";
34750
34861
  import { basename as basename8, dirname as dirname24, join as join44, resolve as resolve16 } from "node:path";
34751
34862
  import { fileURLToPath as fileURLToPath12 } from "node:url";
34752
34863
  import { execFile } from "node:child_process";
34753
- function atomicJson(path22, value) {
34754
- const target = unlinked(path22), temp = unlinked(`${target}.${randomUUID18()}.tmp`);
34864
+ function atomicJson(path23, value) {
34865
+ const target = unlinked(path23), temp = unlinked(`${target}.${randomUUID18()}.tmp`);
34755
34866
  try {
34756
34867
  writeFileSync14(temp, JSON.stringify(seal(value)) + "\n", { flag: "wx" });
34757
34868
  renameSync11(temp, target);
@@ -34769,10 +34880,10 @@ function alive2(pid) {
34769
34880
  }
34770
34881
  }
34771
34882
  function importerActive(historyRoot2) {
34772
- const path22 = join44(historyRoot2, ".topics-import.lock");
34773
- if (!existsSync21(path22)) return false;
34883
+ const path23 = join44(historyRoot2, ".topics-import.lock");
34884
+ if (!existsSync21(path23)) return false;
34774
34885
  try {
34775
- return alive2(readJson(path22).pid);
34886
+ return alive2(readJson(path23).pid);
34776
34887
  } catch {
34777
34888
  return true;
34778
34889
  }
@@ -34780,13 +34891,13 @@ function importerActive(historyRoot2) {
34780
34891
  async function withTopicsImportLock(historyRoot2, action) {
34781
34892
  const root = unlinked(historyRoot2);
34782
34893
  mkdirSync20(root, { recursive: true });
34783
- const path22 = unlinked(join44(root, ".topics-import.lock")), token = randomUUID18();
34894
+ const path23 = unlinked(join44(root, ".topics-import.lock")), token = randomUUID18();
34784
34895
  const body = JSON.stringify({ pid: process.pid, token });
34785
34896
  try {
34786
- writeFileSync14(path22, body, { flag: "wx" });
34897
+ writeFileSync14(path23, body, { flag: "wx" });
34787
34898
  } catch (error) {
34788
34899
  if (error.code !== "EEXIST") throw error;
34789
- const original = readFileSync35(path22, "utf8");
34900
+ const original = readFileSync35(path23, "utf8");
34790
34901
  let owner;
34791
34902
  try {
34792
34903
  owner = JSON.parse(original);
@@ -34794,23 +34905,23 @@ async function withTopicsImportLock(historyRoot2, action) {
34794
34905
  throw new Error("TOPICS_IMPORT_BUSY: invalid lock");
34795
34906
  }
34796
34907
  if (alive2(owner.pid)) throw new Error("TOPICS_IMPORT_BUSY");
34797
- if (readFileSync35(path22, "utf8") !== original) throw new Error("TOPICS_IMPORT_BUSY");
34798
- unlinkSync6(path22);
34799
- writeFileSync14(path22, body, { flag: "wx" });
34908
+ if (readFileSync35(path23, "utf8") !== original) throw new Error("TOPICS_IMPORT_BUSY");
34909
+ unlinkSync6(path23);
34910
+ writeFileSync14(path23, body, { flag: "wx" });
34800
34911
  }
34801
34912
  try {
34802
34913
  return await action();
34803
34914
  } finally {
34804
- if (existsSync21(path22) && readFileSync35(path22, "utf8") === body) unlinkSync6(path22);
34915
+ if (existsSync21(path23) && readFileSync35(path23, "utf8") === body) unlinkSync6(path23);
34805
34916
  }
34806
34917
  }
34807
34918
  function registryPath(stateDir2) {
34808
34919
  return join44(stateDir2, "mem7", ".topics-backup-roots.json");
34809
34920
  }
34810
34921
  function backupRoots(stateDir2) {
34811
- const path22 = registryPath(stateDir2);
34812
- if (!existsSync21(path22)) return [join44(stateDir2, "mem7")];
34813
- const value = readJson(path22);
34922
+ const path23 = registryPath(stateDir2);
34923
+ if (!existsSync21(path23)) return [join44(stateDir2, "mem7")];
34924
+ const value = readJson(path23);
34814
34925
  checkSeal(value);
34815
34926
  if (value.version !== 1 || value.stateDir !== stateDir2 || !Array.isArray(value.roots) || value.roots.some((r) => typeof r !== "string" || resolve16(r) !== r)) throw new Error("INVALID_BACKUP_ROOT_REGISTRY");
34816
34927
  return [.../* @__PURE__ */ new Set([join44(stateDir2, "mem7"), ...value.roots])];
@@ -34970,8 +35081,8 @@ async function adoptLegacyBackups(state, root, allowed) {
34970
35081
  const history = unlinked(join44(histories, entry.name));
34971
35082
  if (importerActive(history) || existsSync21(join44(history, pointerName))) continue;
34972
35083
  try {
34973
- const marker = readJson(join44(history, "topics-import.json")), path22 = unlinked(marker.report?.backupPath ?? "");
34974
- if (marker.report?.failed === 0 && Number.isFinite(Date.parse(marker.completedAt)) && dirname24(path22) === root && backupName.test(basename8(path22)) && existsSync21(path22))
35084
+ const marker = readJson(join44(history, "topics-import.json")), path23 = unlinked(marker.report?.backupPath ?? "");
35085
+ if (marker.report?.failed === 0 && Number.isFinite(Date.parse(marker.completedAt)) && dirname24(path23) === root && backupName.test(basename8(path23)) && existsSync21(path23))
34975
35086
  markers.push({ history, marker, hash: digest3(canonical(marker)) });
34976
35087
  } catch {
34977
35088
  }
@@ -35023,10 +35134,10 @@ async function legacyCompletionRoots(state) {
35023
35134
  try {
35024
35135
  const marker = readJson(join44(histories, entry.name, "topics-import.json"));
35025
35136
  if (marker.report?.failed !== 0 || !Number.isFinite(Date.parse(marker.completedAt)) || typeof marker.report.backupPath !== "string") continue;
35026
- const path22 = unlinked(marker.report.backupPath);
35027
- if (!backupName.test(basename8(path22)) || !existsSync21(path22)) continue;
35028
- disjoint(join44(state, "mem7", "index"), join44(state, "mem7", "users"), path22);
35029
- roots.add(dirname24(path22));
35137
+ const path23 = unlinked(marker.report.backupPath);
35138
+ if (!backupName.test(basename8(path23)) || !existsSync21(path23)) continue;
35139
+ disjoint(join44(state, "mem7", "index"), join44(state, "mem7", "users"), path23);
35140
+ roots.add(dirname24(path23));
35030
35141
  } catch {
35031
35142
  }
35032
35143
  }
@@ -35130,10 +35241,10 @@ async function validateLegacyTopicsBackup(state, directory2, history) {
35130
35241
  }
35131
35242
  const readTree = async (root) => {
35132
35243
  for (const entry of await readdir2(unlinked(root), { withFileTypes: true })) {
35133
- const path22 = unlinked(join46(root, entry.name));
35134
- if (entry.isDirectory()) await readTree(path22);
35244
+ const path23 = unlinked(join46(root, entry.name));
35245
+ if (entry.isDirectory()) await readTree(path23);
35135
35246
  else if (entry.isFile()) {
35136
- const file2 = await open(path22, "r");
35247
+ const file2 = await open(path23, "r");
35137
35248
  try {
35138
35249
  const buffer = Buffer.allocUnsafe(64 * 1024);
35139
35250
  while ((await file2.read(buffer)).bytesRead > 0) {
@@ -35202,9 +35313,9 @@ async function validateCompletedTopicsImport(state, history) {
35202
35313
  db2.close();
35203
35314
  }
35204
35315
  const prose = /* @__PURE__ */ new Map(), idsByHash = /* @__PURE__ */ new Map();
35205
- const scan = async (path23) => {
35206
- for (const entry of await readdir3(unlinked(path23), { withFileTypes: true })) {
35207
- const file2 = unlinked(join47(path23, entry.name));
35316
+ const scan = async (path24) => {
35317
+ for (const entry of await readdir3(unlinked(path24), { withFileTypes: true })) {
35318
+ const file2 = unlinked(join47(path24, entry.name));
35208
35319
  if (entry.isDirectory()) await scan(file2);
35209
35320
  else if (entry.isFile() && entry.name.endsWith(".md")) {
35210
35321
  const text2 = await readFile(file2, "utf8");
@@ -35240,9 +35351,9 @@ async function validateCompletedTopicsImport(state, history) {
35240
35351
  }
35241
35352
  }
35242
35353
  const loaded = await import(lanceSpecifierFor(process.platform, process.arch)), lance = loaded.connect ? loaded : loaded.default;
35243
- const path22 = unlinked(join47(root, "index", "lancedb"));
35244
- if (!existsSync22(path22)) throw new Error("TOPICS_IMPORT_LIVE_VECTORS_MISSING");
35245
- const connection = await lance.connect(path22), vectorIds = /* @__PURE__ */ new Set();
35354
+ const path23 = unlinked(join47(root, "index", "lancedb"));
35355
+ if (!existsSync22(path23)) throw new Error("TOPICS_IMPORT_LIVE_VECTORS_MISSING");
35356
+ const connection = await lance.connect(path23), vectorIds = /* @__PURE__ */ new Set();
35246
35357
  try {
35247
35358
  for (const name of await connection.tableNames()) {
35248
35359
  const table = await connection.openTable(name);
@@ -35274,6 +35385,190 @@ var init_validate_import_live = __esm({
35274
35385
  }
35275
35386
  });
35276
35387
 
35388
+ // src/memory/topics-chunks.ts
35389
+ var topics_chunks_exports = {};
35390
+ __export(topics_chunks_exports, {
35391
+ TOPICS_CHUNK_SESSION: () => TOPICS_CHUNK_SESSION,
35392
+ chunkTimestamp: () => chunkTimestamp,
35393
+ chunkTopicsText: () => chunkTopicsText,
35394
+ importTopicChunks: () => importTopicChunks
35395
+ });
35396
+ import { createHash as createHash36 } from "node:crypto";
35397
+ import { readdirSync as readdirSync7, readFileSync as readFileSync37, mkdirSync as mkdirSync21, writeFileSync as writeFileSync16, renameSync as renameSync12, existsSync as existsSync24 } from "node:fs";
35398
+ import { join as join50, relative as relative8 } from "node:path";
35399
+ function parseMd(text2) {
35400
+ const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text2);
35401
+ const meta = {};
35402
+ let body = text2;
35403
+ if (m) {
35404
+ for (const line of m[1].split(/\r?\n/)) {
35405
+ const i = line.indexOf(":");
35406
+ if (i > 0) meta[line.slice(0, i).trim()] = line.slice(i + 1).trim();
35407
+ }
35408
+ body = text2.slice(m[0].length).trim();
35409
+ }
35410
+ return { meta, body };
35411
+ }
35412
+ function chunkTopicsText(text2, rel) {
35413
+ const { meta, body } = parseMd(text2);
35414
+ const title = meta.name || rel.split("/").pop().replace(/\.md$/i, "");
35415
+ const header = `[${meta.type || "topics"}] ${title}${meta.date ? " " + meta.date : ""}
35416
+ \u6765\u6E90\uFF1A${rel}`;
35417
+ const paragraphs = body.split(/\n\s*\n/).map((x) => x.trim()).filter((x) => x.length >= CHUNK_MIN);
35418
+ const out = [];
35419
+ let ordinal = 0;
35420
+ for (const paragraph of paragraphs) {
35421
+ const pieces = [];
35422
+ if (paragraph.length <= CHUNK_MAX) pieces.push(paragraph);
35423
+ else {
35424
+ let rest = paragraph;
35425
+ while (rest.length > CHUNK_MAX) {
35426
+ let cut = rest.lastIndexOf("\u3002", CHUNK_MAX);
35427
+ if (cut < CHUNK_MIN) cut = CHUNK_MAX;
35428
+ pieces.push(rest.slice(0, cut + 1));
35429
+ rest = rest.slice(cut + 1).trim();
35430
+ }
35431
+ if (rest.length >= CHUNK_MIN) pieces.push(rest);
35432
+ }
35433
+ for (const piece of pieces) {
35434
+ if (out.length >= MAX_CHUNKS_PER_FILE) return out;
35435
+ out.push({ ordinal: ordinal++, text: `${header}
35436
+
35437
+ ${piece}` });
35438
+ }
35439
+ }
35440
+ return out;
35441
+ }
35442
+ function walk(root) {
35443
+ const out = [];
35444
+ const visit = (dir) => {
35445
+ for (const entry of readdirSync7(dir, { withFileTypes: true })) {
35446
+ if (entry.isSymbolicLink()) continue;
35447
+ const path23 = join50(dir, entry.name);
35448
+ if (entry.isDirectory()) visit(path23);
35449
+ else if (entry.isFile() && /\.md$/i.test(entry.name) && entry.name.toUpperCase() !== "MEMORY.MD") out.push(path23);
35450
+ }
35451
+ };
35452
+ visit(root);
35453
+ return out.sort();
35454
+ }
35455
+ function chunkTimestamp(meta) {
35456
+ const ms = Date.parse(String(meta.date ?? ""));
35457
+ return new Date(Number.isFinite(ms) ? ms : Date.now());
35458
+ }
35459
+ async function importTopicChunks(options) {
35460
+ const { stateDir: stateDir2, topicsDir, userId, embed } = options;
35461
+ const manifestPath = join50(stateDir2, "mem7", "topics-chunks.json");
35462
+ mkdirSync21(join50(stateDir2, "mem7"), { recursive: true });
35463
+ let manifest = {};
35464
+ try {
35465
+ if (existsSync24(manifestPath)) manifest = JSON.parse(readFileSync37(manifestPath, "utf8"));
35466
+ } catch {
35467
+ manifest = {};
35468
+ }
35469
+ const store = new Mem7VectorStore(stateDir2);
35470
+ const table = await store.table("episode");
35471
+ const report = { files: 0, chunks: 0, embedded: 0, deleted: 0, failed: 0, errors: [] };
35472
+ const save = () => {
35473
+ const tmp = `${manifestPath}.${process.pid}.tmp`;
35474
+ writeFileSync16(tmp, JSON.stringify(manifest));
35475
+ renameSync12(tmp, manifestPath);
35476
+ };
35477
+ const files = walk(topicsDir);
35478
+ const seen = /* @__PURE__ */ new Set();
35479
+ const concurrency = Math.max(1, Math.min(8, options.concurrency ?? 4));
35480
+ for (const file2 of files) {
35481
+ const rel = relative8(topicsDir, file2);
35482
+ seen.add(rel);
35483
+ const bytes2 = readFileSync37(file2);
35484
+ const hash8 = sha(bytes2);
35485
+ const previous = manifest[rel];
35486
+ if (previous?.hash === hash8) continue;
35487
+ try {
35488
+ const parentId = `topic_chunk:${rel}`;
35489
+ await table.delete(`parent_id = '${sqlLiteral2(parentId)}'`);
35490
+ const text2 = bytes2.toString("utf8");
35491
+ const parsed = parseMd(text2);
35492
+ const title = parsed.meta.name || rel.split("/").pop().replace(/\.md$/i, "");
35493
+ const chunks = chunkTopicsText(text2, rel);
35494
+ const vectors = new Array(chunks.length);
35495
+ let next = 0;
35496
+ const worker2 = async () => {
35497
+ while (next < chunks.length) {
35498
+ const start = next;
35499
+ next = Math.min(chunks.length, next + 64);
35500
+ const batch = chunks.slice(start, next);
35501
+ const embedded = await embed(batch.map((chunk) => chunk.text));
35502
+ if (!Array.isArray(embedded) || embedded.length !== batch.length) throw new Error("EMBED_SHAPE_MISMATCH");
35503
+ for (let i = 0; i < batch.length; i++) vectors[start + i] = embedded[i];
35504
+ }
35505
+ };
35506
+ await Promise.all(Array.from({ length: concurrency }, worker2));
35507
+ const rows = chunks.map((chunk, index) => {
35508
+ const id = `tc_${sha(`${rel}:${chunk.ordinal}`).slice(0, 20)}`;
35509
+ return {
35510
+ id,
35511
+ entryId: id,
35512
+ ownerId: userId,
35513
+ ownerType: "user",
35514
+ appId: options.appId ?? "default",
35515
+ projectId: options.projectId ?? "default",
35516
+ sessionId: TOPICS_CHUNK_SESSION,
35517
+ timestamp: chunkTimestamp(parsed.meta),
35518
+ parentId,
35519
+ text: chunk.text,
35520
+ subject: title,
35521
+ summary: chunk.text.split("\n")[0],
35522
+ contentSha256: sha(chunk.text),
35523
+ mdPath: "",
35524
+ vector: vectors[index]
35525
+ };
35526
+ });
35527
+ if (rows.length) await store.insert("episode", rows);
35528
+ manifest[rel] = { hash: hash8, ids: rows.map((row) => row.id), chunks: rows.length };
35529
+ save();
35530
+ report.files++;
35531
+ report.chunks += rows.length;
35532
+ report.embedded += rows.length;
35533
+ } catch (error) {
35534
+ report.failed++;
35535
+ report.errors.push(`${rel}: ${error instanceof Error ? error.message : String(error)}`);
35536
+ }
35537
+ }
35538
+ if (options.prune !== false) for (const rel of Object.keys(manifest)) {
35539
+ if (seen.has(rel)) continue;
35540
+ try {
35541
+ await table.delete(`parent_id = '${sqlLiteral2(`topic_chunk:${rel}`)}'`);
35542
+ delete manifest[rel];
35543
+ report.deleted++;
35544
+ } catch (error) {
35545
+ report.errors.push(`delete ${rel}: ${error instanceof Error ? error.message : String(error)}`);
35546
+ }
35547
+ }
35548
+ save();
35549
+ if ((report.chunks || report.deleted) && options.optimize !== false) {
35550
+ try {
35551
+ await table.optimize();
35552
+ } catch (error) {
35553
+ report.errors.push(`optimize: ${error instanceof Error ? error.message : String(error)}`);
35554
+ }
35555
+ }
35556
+ return report;
35557
+ }
35558
+ var TOPICS_CHUNK_SESSION, CHUNK_MIN, CHUNK_MAX, MAX_CHUNKS_PER_FILE, sha, sqlLiteral2;
35559
+ var init_topics_chunks = __esm({
35560
+ "src/memory/topics-chunks.ts"() {
35561
+ "use strict";
35562
+ init_vector_store();
35563
+ TOPICS_CHUNK_SESSION = "topics-chunks";
35564
+ CHUNK_MIN = 20;
35565
+ CHUNK_MAX = 800;
35566
+ MAX_CHUNKS_PER_FILE = 200;
35567
+ sha = (input) => createHash36("sha256").update(input).digest("hex");
35568
+ sqlLiteral2 = (value) => value.replace(/'/g, "''");
35569
+ }
35570
+ });
35571
+
35277
35572
  // src/mem7/core/context-render.ts
35278
35573
  function renderMemoryContext(context, userLabel = "\u5BF9\u65B9") {
35279
35574
  const lines = [`\uFF08\u5FEB\u7167 rev=${context.snapshot.factRevision}\uFF5C\u72B6\u6001=${context.freshness}\uFF5C\u622A\u81F3=${context.validAt}\uFF09`];
@@ -35499,7 +35794,7 @@ var init_memoryTypes = __esm({
35499
35794
  // src/memory/memdir/memoryScan.ts
35500
35795
  import fs11 from "node:fs/promises";
35501
35796
  import { StringDecoder } from "node:string_decoder";
35502
- import { basename as basename12, join as join50, sep as sep6 } from "node:path";
35797
+ import { basename as basename12, join as join51, sep as sep6 } from "node:path";
35503
35798
  function isArchivedPath(relativePath) {
35504
35799
  return relativePath.split(sep6).includes("archive");
35505
35800
  }
@@ -35574,7 +35869,7 @@ async function scanMemoryFiles(memoryDir, signal, maxFiles) {
35574
35869
  const entries = await fs11.readdir(memoryDir, { recursive: true });
35575
35870
  const files = entries.filter((f) => typeof f === "string" && f.endsWith(".md") && basename12(f) !== "MEMORY.md" && !isArchivedPath(f));
35576
35871
  const candidates = await mapFiles(files, 16, signal, async (filename) => {
35577
- const filePath = join50(memoryDir, filename);
35872
+ const filePath = join51(memoryDir, filename);
35578
35873
  return { filename, filePath, mtimeMs: (await fs11.stat(filePath)).mtimeMs };
35579
35874
  });
35580
35875
  const selected = candidates.sort((a, b) => b.mtimeMs - a.mtimeMs).slice(0, limit);
@@ -35702,7 +35997,7 @@ Return ONLY valid JSON: {"selected_memories": ["filename1.md", "filename2.md"]}`
35702
35997
  });
35703
35998
 
35704
35999
  // src/memory/topics-history/reader.ts
35705
- import { relative as relative8 } from "node:path";
36000
+ import { relative as relative9 } from "node:path";
35706
36001
  async function configuredFallback() {
35707
36002
  const raw = liveConfig.get("topics.recall") ?? {};
35708
36003
  let ref = String(raw.model ?? "");
@@ -35741,7 +36036,7 @@ async function readTopicsHistory(b, query, options = {}) {
35741
36036
  /* @__PURE__ */ new Set(),
35742
36037
  fallback.disableThinking
35743
36038
  );
35744
- selected = files.map((file2) => relative8(b.topicsDir, file2.path).replace(/\\/g, "/"));
36039
+ selected = files.map((file2) => relative9(b.topicsDir, file2.path).replace(/\\/g, "/"));
35745
36040
  }
35746
36041
  }
35747
36042
  } catch {
@@ -35779,11 +36074,11 @@ var init_reader = __esm({
35779
36074
 
35780
36075
  // src/memory/topics-history/import-mem7.ts
35781
36076
  import { DatabaseSync as DatabaseSync21 } from "node:sqlite";
35782
- import { existsSync as existsSync24, readFileSync as readFileSync37, renameSync as renameSync12, statSync as statSync7, writeFileSync as writeFileSync16 } from "node:fs";
35783
- import { join as join51 } from "node:path";
36077
+ import { existsSync as existsSync25, readFileSync as readFileSync38, renameSync as renameSync13, statSync as statSync7, writeFileSync as writeFileSync17 } from "node:fs";
36078
+ import { join as join52 } from "node:path";
35784
36079
  function topicsImported(binding) {
35785
36080
  if (!binding.stateDir) return false;
35786
- const marker = join51(topicsHistoryRoot(binding), "topics-import.json");
36081
+ const marker = join52(topicsHistoryRoot(binding), "topics-import.json");
35787
36082
  let size2 = 0, mtimeMs = 0, ino = 0;
35788
36083
  try {
35789
36084
  const s = statSync7(marker);
@@ -35800,19 +36095,19 @@ function topicsImported(binding) {
35800
36095
  try {
35801
36096
  const done = readJson(marker);
35802
36097
  if (typeof done.rulesVersion === "number" && done.rulesVersion !== TOPIC_DATE_RULES_VERSION) {
35803
- const retired = join51(topicsHistoryRoot(binding), `topics-import.stale-rules-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
35804
- renameSync12(marker, retired);
36098
+ const retired = join52(topicsHistoryRoot(binding), `topics-import.stale-rules-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
36099
+ renameSync13(marker, retired);
35805
36100
  console.warn(`[topics-import] \u65E5\u671F\u89C4\u5219 v${done.rulesVersion}\u2192v${TOPIC_DATE_RULES_VERSION}\uFF0C\u65E7\u6E05\u5355\u4F5C\u5E9F\u91CD\u5F00 \u2192 ${retired}`);
35806
36101
  } else if ((done.report?.total ?? 0) > 0) imported = true;
35807
36102
  else {
35808
- const retired = join51(topicsHistoryRoot(binding), `topics-import.degenerate-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
35809
- renameSync12(marker, retired);
36103
+ const retired = join52(topicsHistoryRoot(binding), `topics-import.degenerate-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
36104
+ renameSync13(marker, retired);
35810
36105
  console.warn(`[topics-import] total=0 \u5B8C\u6210\u6E05\u5355\u4F5C\u5E9F\uFF08\u6E05\u6D17\u9000\u5316\u5047\u5B8C\u6210\uFF0C\u95F8\u95E8\u91CD\u5F00\uFF09\u2192 ${retired}`);
35811
36106
  }
35812
36107
  } catch {
35813
- const retired = join51(topicsHistoryRoot(binding), `topics-import.degenerate-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
36108
+ const retired = join52(topicsHistoryRoot(binding), `topics-import.degenerate-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
35814
36109
  try {
35815
- renameSync12(marker, retired);
36110
+ renameSync13(marker, retired);
35816
36111
  console.warn(`[topics-import] \u6E05\u5355\u635F\u574F\u4F5C\u5E9F\uFF08\u4E0B\u8F6E\u5BFC\u5165\u91CD\u5199\u81EA\u6108\uFF09\u2192 ${retired}`);
35817
36112
  } catch {
35818
36113
  }
@@ -35954,7 +36249,7 @@ __export(findRelevantMemoriesMem7_exports, {
35954
36249
  readMem7CurrentContext: () => readMem7CurrentContext,
35955
36250
  setRecallRerankOverride: () => setRecallRerankOverride
35956
36251
  });
35957
- import { createHash as createHash36 } from "node:crypto";
36252
+ import { createHash as createHash37 } from "node:crypto";
35958
36253
  function contextMemory(context, scope, userLabel, compact = false) {
35959
36254
  const pendingHint = context.pendingSources.some((source) => source.state === "received") ? "\uFF1B\u5F85\u89E3\u91CA\u539F\u8BDD\u53EF\u6309\u4F5C\u8005\u548C\u65F6\u95F4\u590D\u8FF0\uFF0C\u4E0D\u7B49\u4E8E\u5DF2\u786E\u8BA4\u4E8B\u5B9E\uFF1B\u52A9\u624B\u6C47\u62A5\u4E0D\u8BC1\u660E\u73B0\u5B9E\u7ED3\u679C\u5B8C\u6210" : "";
35960
36255
  const reviewHint = context.pendingSources.some((source) => source.state === "needs_review") ? "\uFF1B\u5F85\u786E\u8BA4\u4E8B\u5B9E\u7528\u81EA\u7136\u8BED\u8A00\u6F84\u6E05\uFF1B\u786E\u8BA4\u540E\u7528 memory_get\u3001memory_entity_confirm / memory_correct \u548C memory_retry\uFF08\u5F53\u524D interpretationVersion\uFF09\u6062\u590D\uFF0C\u52FF\u731C\u8EAB\u4EFD\u6216\u53CD\u590D\u91CD\u8BD5" : context.pendingSources.some((source) => source.state === "failed") ? "\uFF1B\u540E\u53F0\u89E3\u91CA\u6280\u672F\u5931\u8D25\uFF0C\u539F\u8BDD\u5DF2\u4FDD\u5B58\uFF1B\u7528 memory_status / memory_get \u6838\u5BF9\u540E\u6309\u5F53\u524D\u89E3\u91CA\u7248\u672C\u91CD\u8BD5" : "";
@@ -36133,7 +36428,7 @@ async function readMem7CurrentContext(stateDir2, scope, request, budget, onReadS
36133
36428
  ...fact,
36134
36429
  basis: { ...fact.basis, validAt: void 0 }
36135
36430
  }));
36136
- const contentKey = createHash36("sha256").update(canonicalJson({
36431
+ const contentKey = createHash37("sha256").update(canonicalJson({
36137
36432
  ...material,
36138
36433
  currentFacts: withoutReadClock(material.currentFacts),
36139
36434
  historicalFacts: withoutReadClock(material.historicalFacts),
@@ -36701,9 +36996,9 @@ function enqueueRelationshipNotifications(store, scope, route, onlyId) {
36701
36996
  }
36702
36997
  async function appendGroupNoticeIntercept(workspace2, entry) {
36703
36998
  const { appendFile, mkdir: mkdir3 } = await import("node:fs/promises");
36704
- const path22 = await import("node:path");
36705
- const file2 = path22.join(workspace2, "memory", "group-routed-notices.md");
36706
- await mkdir3(path22.dirname(file2), { recursive: true });
36999
+ const path23 = await import("node:path");
37000
+ const file2 = path23.join(workspace2, "memory", "group-routed-notices.md");
37001
+ await mkdir3(path23.dirname(file2), { recursive: true });
36707
37002
  await appendFile(file2, `## ${(/* @__PURE__ */ new Date()).toISOString()} ${entry.noticeId}
36708
37003
  - \u6765\u6E90\uFF1A${entry.scopeKey}
36709
37004
  - \u60F3\u6295\u5F80\uFF1A${entry.channel} \u7FA4 ${entry.target}
@@ -36973,7 +37268,7 @@ var init_prompt_history = __esm({
36973
37268
  // src/session/reader.ts
36974
37269
  import * as fs13 from "node:fs";
36975
37270
  import * as readline from "node:readline";
36976
- import { createHash as createHash37 } from "node:crypto";
37271
+ import { createHash as createHash38 } from "node:crypto";
36977
37272
  async function readLargeFilePostBoundary(filePath, visit) {
36978
37273
  const stat3 = fs13.statSync(filePath);
36979
37274
  const fileSize = stat3.size;
@@ -37351,7 +37646,7 @@ function entryToSessionMessage(entry) {
37351
37646
  const inputSource = m.inputSource ?? legacyProactiveInput(m);
37352
37647
  const video = Array.isArray(m.content) && m.content.some((b) => b.type === "video");
37353
37648
  const imageInput = m.imageInput ? { ...m.imageInput } : video ? {
37354
- id: "legacy-video:" + (entry.uuid || createHash37("sha256").update(JSON.stringify(entry.raw)).digest("hex")),
37649
+ id: "legacy-video:" + (entry.uuid || createHash38("sha256").update(JSON.stringify(entry.raw)).digest("hex")),
37355
37650
  observed: false
37356
37651
  } : void 0;
37357
37652
  const text2 = Array.isArray(m.content) && (inputSource?.source === "system" && hasProactiveRules(m.content) || m.content.some((b) => b.type === "image_ref" || b.type === "image" || b.type === "video")) ? m.content : extractText(m.content);
@@ -37683,7 +37978,7 @@ var init_image_input_protection = __esm({
37683
37978
  });
37684
37979
 
37685
37980
  // src/tools/read-result.ts
37686
- import { createHash as createHash38 } from "node:crypto";
37981
+ import { createHash as createHash39 } from "node:crypto";
37687
37982
  function readResultKey(call, content) {
37688
37983
  if (call.function.name !== "read") return null;
37689
37984
  let args2;
@@ -37695,7 +37990,7 @@ function readResultKey(call, content) {
37695
37990
  if (!args2 || typeof args2.path !== "string") return null;
37696
37991
  const body = content.replace(/^\[历史工具观察[^\n]*\]\n/, "").replace(/^(?:⚠️ 你已连续[^\n]*\n\n|⚠️ 重复读取检测:[^\n]*\n\n)+/, "");
37697
37992
  if (!body.includes("\n" + "\u2500".repeat(60) + "\n")) return null;
37698
- return JSON.stringify([args2.path, args2.offset || 1, args2.limit || null]) + ":" + createHash38("sha256").update(body).digest("hex");
37993
+ return JSON.stringify([args2.path, args2.offset || 1, args2.limit || null]) + ":" + createHash39("sha256").update(body).digest("hex");
37699
37994
  }
37700
37995
  function repeatedReadNotice(toolCallId) {
37701
37996
  return `[\u91CD\u590D\u8BFB\u53D6\uFF1A\u76F8\u540C\u7248\u672C\u4E0E\u8303\u56F4\u7684\u6B63\u6587\u89C1\u5DE5\u5177\u7ED3\u679C ${toolCallId}\uFF1B\u539F\u59CB\u7ED3\u679C\u4FDD\u7559\u5728\u4F1A\u8BDD\u8BB0\u5F55\u3002]`;
@@ -37714,7 +38009,7 @@ var init_read_result = __esm({
37714
38009
  });
37715
38010
 
37716
38011
  // src/tools/result-snapshot.ts
37717
- import { createHash as createHash39 } from "node:crypto";
38012
+ import { createHash as createHash40 } from "node:crypto";
37718
38013
  function visibleArchive(message) {
37719
38014
  const a = message.resultArchive;
37720
38015
  if (!a || message.role !== "user" || typeof message.content !== "string" || !Array.isArray(a.entries) || typeof a.sessionId !== "string" || typeof a.id !== "string" || !a.entries.every((e) => e && typeof e.id === "string" && typeof e.index === "string" && typeof e.content === "string") || !message.content.includes(archiveNotice(a)) || archiveId(a.sessionId, a.entries) !== a.id) return;
@@ -37867,7 +38162,7 @@ var init_result_snapshot = __esm({
37867
38162
  init_image_input_protection();
37868
38163
  MIN_SNAPSHOT_CHARS = 8e3;
37869
38164
  URI = /^tool-result:\/\/([a-f0-9]{64})$/;
37870
- digest6 = (sessionId, content) => createHash39("sha256").update(sessionId).update("\0").update(content).digest("hex");
38165
+ digest6 = (sessionId, content) => createHash40("sha256").update(sessionId).update("\0").update(content).digest("hex");
37871
38166
  archiveNotice = (a) => `[\u5386\u53F2\u5DE5\u5177\u539F\u6587\u76EE\u5F55\uFF1Aread tool-result://${a.id}\uFF1B\u5171 ${a.entries.length} \u4EFD\uFF0C\u53EF\u6309\u76EE\u5F55\u4E2D\u7684\u5F15\u7528\u53D6\u56DE\u539F\u6587\u3002\u8FD9\u4E9B\u662F\u5F53\u65F6\u89C2\u5BDF\uFF0C\u4E0D\u4EE3\u8868\u5F53\u524D\u72B6\u6001\u3002]`;
37872
38167
  archiveId = (sessionId, entries) => digest6(sessionId, JSON.stringify(entries.map((e) => [e.id, e.index])));
37873
38168
  }
@@ -38460,7 +38755,7 @@ var init_context_dump = __esm({
38460
38755
  // src/core/steer-mailbox.ts
38461
38756
  import * as fs15 from "node:fs";
38462
38757
  import * as path13 from "node:path";
38463
- import { createHash as createHash40, randomUUID as randomUUID20 } from "node:crypto";
38758
+ import { createHash as createHash41, randomUUID as randomUUID20 } from "node:crypto";
38464
38759
  var MAX_FILE, MAX_PENDING, MAX_PENDING_BYTES, SteerMailbox;
38465
38760
  var init_steer_mailbox = __esm({
38466
38761
  "src/core/steer-mailbox.ts"() {
@@ -38472,7 +38767,7 @@ var init_steer_mailbox = __esm({
38472
38767
  SteerMailbox = class {
38473
38768
  constructor(stateDir2, sessionId) {
38474
38769
  this.sessionId = sessionId;
38475
- const key5 = createHash40("sha256").update(sessionId).digest("hex");
38770
+ const key5 = createHash41("sha256").update(sessionId).digest("hex");
38476
38771
  this.path = path13.join(stateDir2, "steer", `${key5}.json`);
38477
38772
  }
38478
38773
  path;
@@ -38506,7 +38801,7 @@ var init_steer_mailbox = __esm({
38506
38801
  if (input.attachment) this.assertAttachment(input);
38507
38802
  input.images?.forEach(assertImageAssetRef);
38508
38803
  const records = this.list();
38509
- const id = input.messageId ? createHash40("sha256").update(JSON.stringify([
38804
+ const id = input.messageId ? createHash41("sha256").update(JSON.stringify([
38510
38805
  this.sessionId,
38511
38806
  input.channel,
38512
38807
  input.channelTarget ?? "",
@@ -39662,7 +39957,7 @@ var init_compact2 = __esm({
39662
39957
  });
39663
39958
 
39664
39959
  // src/compact/background.ts
39665
- import { createHash as createHash41 } from "node:crypto";
39960
+ import { createHash as createHash42 } from "node:crypto";
39666
39961
  var historyFingerprint;
39667
39962
  var init_background = __esm({
39668
39963
  "src/compact/background.ts"() {
@@ -39672,7 +39967,7 @@ var init_background = __esm({
39672
39967
  init_tokenEstimate();
39673
39968
  init_hooks();
39674
39969
  init_host_turn();
39675
- historyFingerprint = (messages) => createHash41("sha256").update(JSON.stringify(messages)).digest("hex");
39970
+ historyFingerprint = (messages) => createHash42("sha256").update(JSON.stringify(messages)).digest("hex");
39676
39971
  }
39677
39972
  });
39678
39973
 
@@ -39882,6 +40177,199 @@ var init_store2 = __esm({
39882
40177
  }
39883
40178
  });
39884
40179
 
40180
+ // src/skills/recent-user-texts.ts
40181
+ var init_recent_user_texts = __esm({
40182
+ "src/skills/recent-user-texts.ts"() {
40183
+ "use strict";
40184
+ init_strip_injected();
40185
+ }
40186
+ });
40187
+
40188
+ // src/core/query-skill-selection.ts
40189
+ async function selectSkillCall(provider, params, allowedNames, recordUsage) {
40190
+ const timeout = AbortSignal.timeout(5e3);
40191
+ const signal = AbortSignal.any([params.signal, timeout]);
40192
+ const chunks = [];
40193
+ let calledSkill = false;
40194
+ let skillName = "";
40195
+ let requestComplete = false;
40196
+ let otherCut = false;
40197
+ try {
40198
+ for await (const chunk of provider.streamChat({
40199
+ ...params,
40200
+ signal,
40201
+ httpRetry: { maxRetries: 0 }
40202
+ })) {
40203
+ signal.throwIfAborted();
40204
+ if (chunk.type === "error") return { outcome: "upstream-error" };
40205
+ if (chunk.type === "tool_call") {
40206
+ if (calledSkill || !chunk.tool_call?.id || chunk.tool_call.function?.name !== SKILL_TOOL_NAME) return { outcome: "invalid" };
40207
+ let args2;
40208
+ try {
40209
+ args2 = JSON.parse(chunk.tool_call.function.arguments);
40210
+ } catch {
40211
+ return { outcome: "invalid" };
40212
+ }
40213
+ if (typeof args2?.skill !== "string" || !allowedNames.has(args2.skill.trim().replace(/^\//, ""))) return { outcome: "invalid" };
40214
+ calledSkill = true;
40215
+ skillName = args2.skill.trim().replace(/^\//, "");
40216
+ chunks.push(chunk);
40217
+ }
40218
+ if (chunk.type === "done") {
40219
+ if (chunk.usage) recordUsage(chunk.usage);
40220
+ requestComplete ||= chunk.requestComplete === true;
40221
+ otherCut ||= ["incomplete", "content_filter"].includes(chunk.stopReason ?? "");
40222
+ }
40223
+ }
40224
+ } catch (error) {
40225
+ params.signal.throwIfAborted();
40226
+ if (error instanceof Error && /^TRAVEL_/.test(error.message)) throw error;
40227
+ return { outcome: timeout.aborted ? "timeout" : "upstream-error" };
40228
+ }
40229
+ params.signal.throwIfAborted();
40230
+ if (timeout.aborted) return { outcome: "timeout" };
40231
+ if (!requestComplete || otherCut) return { outcome: "incomplete" };
40232
+ return calledSkill ? { outcome: "selected", skill: skillName, chunks } : { outcome: "no-skill" };
40233
+ }
40234
+ var SKILL_SELECTION_PROMPT, SKILL_SELECTION_MAX_TOKENS;
40235
+ var init_query_skill_selection = __esm({
40236
+ "src/core/query-skill-selection.ts"() {
40237
+ "use strict";
40238
+ init_constants3();
40239
+ init_types();
40240
+ init_recent_user_texts();
40241
+ SKILL_SELECTION_PROMPT = "\u6309 currentTask \u7684\u76EE\u6807\u548C\u6240\u5904\u9636\u6BB5\uFF0C\u5224\u65AD\u54EA\u9879\u5DF2\u5B89\u88C5\u6280\u80FD\u80FD\u5207\u5B9E\u5E2E\u52A9\u5B8C\u6210\u8FD9\u8F6E\u4EFB\u52A1\uFF0C\u6D41\u7A0B\u7C7B\u6280\u80FD\u7EA6\u675F\u505A\u6CD5\uFF0C\u6587\u6863\u3001\u8868\u683C\u3001\u53D1\u5E03\u7B49\u9886\u57DF\u7C7B\u6280\u80FD\u63D0\u4F9B\u4E13\u95E8\u80FD\u529B\u3002recentDialogue \u53EA\u7528\u4E8E\u7406\u89E3\u6307\u4EE3\u3002\u4E0B\u9762\u662F\u5DF2\u5B89\u88C5\u6280\u80FD\u7684\u540D\u79F0\u548C\u7528\u9014\u3002\u4F60\u53EA\u8D1F\u8D23\u6311\u9009\u6280\u80FD\uFF0C\u4E0D\u8D1F\u8D23\u56DE\u7B54\u4EFB\u52A1\u672C\u8EAB\uFF1A\u6B63\u5F0F\u56DE\u7B54\u7531\u540E\u7EED\u9636\u6BB5\u5B8C\u6210\uFF0C\u8FD9\u91CC\u4E0D\u8981\u5199\u4EFB\u4F55\u56DE\u7B54\u3002\u9002\u7528\u65F6\u76F4\u63A5\u8C03\u7528\u4E00\u9879\u6700\u5408\u9002\u7684 Skill\uFF0C\u4E0D\u8981\u8F93\u51FA\u4EFB\u4F55\u8BF4\u660E\u6587\u5B57\u3002\u7528\u666E\u901A\u5DE5\u5177\u6216\u53EA\u8BFB\u64CD\u4F5C\u4E5F\u53EF\u4EE5\u9075\u5FAA\u6D41\u7A0B\u3002\u5982\u679C\u5BF9\u65B9\u660E\u786E\u8981\u6C42\u8DF3\u8FC7\u3001\u5F53\u524D\u4EFB\u52A1\u6CA1\u6709\u9002\u7528\u7684\u6280\u80FD\uFF0C\u6216\u7F3A\u5C11\u9009\u51C6\u6240\u9700\u7684\u4FE1\u606F\uFF0C\u4E0D\u8C03\u7528\u4EFB\u4F55\u5DE5\u5177\uFF0C\u4E5F\u4E0D\u5199\u4EFB\u4F55\u5B57\uFF0C\u7ACB\u5373\u7ED3\u675F\u3002\u6B63\u5E38\u5DE5\u4F5C\u9636\u6BB5\u4F1A\u63D0\u4F9B\u5B8C\u6574\u5BF9\u8BDD\u548C\u9879\u76EE\u5DE5\u5177\u3002";
40242
+ SKILL_SELECTION_MAX_TOKENS = 64;
40243
+ }
40244
+ });
40245
+
40246
+ // src/skills/scanner.ts
40247
+ function parseFrontmatter2(content) {
40248
+ const result = {};
40249
+ const match = content.match(/^---\s*\n([\s\S]*?)\n---/);
40250
+ if (!match) return result;
40251
+ const lines = match[1].split("\n");
40252
+ let i = 0;
40253
+ while (i < lines.length) {
40254
+ const line = lines[i];
40255
+ const colonIdx = line.indexOf(":");
40256
+ if (colonIdx === -1) {
40257
+ i++;
40258
+ continue;
40259
+ }
40260
+ const key5 = line.slice(0, colonIdx).trim();
40261
+ let value = line.slice(colonIdx + 1).trim();
40262
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
40263
+ value = value.slice(1, -1);
40264
+ result[key5] = value;
40265
+ i++;
40266
+ continue;
40267
+ } else if (value === "|" || value === ">") {
40268
+ const blockLines = [];
40269
+ i++;
40270
+ while (i < lines.length && lines[i].startsWith(" ")) {
40271
+ blockLines.push(lines[i].slice(2));
40272
+ i++;
40273
+ }
40274
+ result[key5] = blockLines.join("\n").trim();
40275
+ continue;
40276
+ } else if (value.startsWith("[") && value.endsWith("]")) {
40277
+ result[key5] = value.slice(1, -1).split(",").map((s) => s.trim());
40278
+ i++;
40279
+ continue;
40280
+ } else if (value.includes(" ") && !value.startsWith('"')) {
40281
+ result[key5] = value;
40282
+ } else {
40283
+ result[key5] = value;
40284
+ }
40285
+ i++;
40286
+ }
40287
+ return result;
40288
+ }
40289
+ var init_scanner = __esm({
40290
+ "src/skills/scanner.ts"() {
40291
+ "use strict";
40292
+ }
40293
+ });
40294
+
40295
+ // src/tools/SkillTool/SkillTool.ts
40296
+ import { createHash as createHash43 } from "node:crypto";
40297
+ import * as fs17 from "node:fs";
40298
+ import * as path15 from "node:path";
40299
+ function getSkillSelectionCatalog() {
40300
+ return selectionCatalog;
40301
+ }
40302
+ function loadSkillContent(skillsDir, skill) {
40303
+ const skillMdPath = skill.location ? path15.join(skillsDir, skill.location.slice("skills/".length)) : path15.join(skillsDir, skill.name, "SKILL.md");
40304
+ if (!fs17.existsSync(skillMdPath)) return null;
40305
+ const content = fs17.readFileSync(skillMdPath, "utf-8");
40306
+ const dependencies = parseFrontmatter2(content)["requires-tools"];
40307
+ const requiredTools = [...new Set((Array.isArray(dependencies) ? dependencies : typeof dependencies === "string" ? dependencies.split(/[\s,]+/) : []).filter((n) => typeof n === "string").map((n) => n.trim().replace(/^(['"])(.*)\1$/, "$2")).filter(Boolean))];
40308
+ const bodyMatch = content.match(/^---\s*\n[\s\S]*?\n---\s*\n([\s\S]*)/);
40309
+ const body = bodyMatch ? bodyMatch[1] : content;
40310
+ const skillDir = path15.dirname(skillMdPath);
40311
+ const normalizedDir = process.platform === "win32" ? skillDir.replace(/\\/g, "/") : skillDir;
40312
+ let finalContent = `Base directory for this skill: ${normalizedDir}
40313
+
40314
+ ${body}`;
40315
+ finalContent = finalContent.replace(/\$\{CLAUDE_SKILL_DIR\}/g, normalizedDir);
40316
+ finalContent = finalContent.replace(/\$\{CLAUDE_SESSION_ID\}/g, getSessionId());
40317
+ return { content: finalContent, requiredTools };
40318
+ }
40319
+ function getSessionId() {
40320
+ return String(process.pid);
40321
+ }
40322
+ function skillFingerprint(skill, body) {
40323
+ return createHash43("sha256").update(skill.location ?? skill.name).update("\0").update(body).digest("hex").slice(0, 16);
40324
+ }
40325
+ function findLoadedSkill(history, skill, fingerprint2, resolve26) {
40326
+ if (!history) return void 0;
40327
+ for (let i = history.length - 1; i >= 0; i--) {
40328
+ const message = history[i];
40329
+ if (!("role" in message) || message.role !== "tool" || message.is_error || typeof message.content !== "string") continue;
40330
+ let call;
40331
+ for (let j = i - 1; j >= 0 && !call; j--) {
40332
+ const previous = history[j];
40333
+ if ("role" in previous && previous.role === "assistant") call = (previous.tool_calls ?? []).find((c) => c.id === message.tool_call_id && c.function.name === SKILL_TOOL_NAME);
40334
+ }
40335
+ if (!call) continue;
40336
+ let args2 = {};
40337
+ try {
40338
+ args2 = JSON.parse(call.function.arguments);
40339
+ } catch {
40340
+ continue;
40341
+ }
40342
+ if (typeof args2?.skill !== "string" || resolve26(args2.skill.trim().replace(/^\//, "")) !== skill) continue;
40343
+ if (!message.content.includes(SKILL_FINGERPRINT_PREFIX + fingerprint2 + "]")) return void 0;
40344
+ return estimateMessageTokens(history.slice(i + 1)) <= SKILL_RELOAD_DISTANCE_TOKENS ? call.id : void 0;
40345
+ }
40346
+ return void 0;
40347
+ }
40348
+ function findLoadedSkillCall(history, skillName) {
40349
+ const resolve26 = resolveSkillFn;
40350
+ if (!history || !resolve26) return void 0;
40351
+ const skill = resolve26(skillName.trim().replace(/^\//, ""));
40352
+ if (!skill) return void 0;
40353
+ const content = loadSkillContent(skillsDirPath, skill);
40354
+ if (!content) return void 0;
40355
+ return findLoadedSkill(history, skill, skillFingerprint(skill, content.content), resolve26);
40356
+ }
40357
+ var skillsDirPath, selectionCatalog, resolveSkillFn, SKILL_FINGERPRINT_PREFIX, SKILL_RELOAD_DISTANCE_TOKENS;
40358
+ var init_SkillTool = __esm({
40359
+ "src/tools/SkillTool/SkillTool.ts"() {
40360
+ "use strict";
40361
+ init_registry();
40362
+ init_scanner();
40363
+ init_tool_loading();
40364
+ init_tokenEstimate();
40365
+ init_constants3();
40366
+ skillsDirPath = "";
40367
+ selectionCatalog = { entries: [], allowedNames: /* @__PURE__ */ new Set() };
40368
+ SKILL_FINGERPRINT_PREFIX = "[fingerprint ";
40369
+ SKILL_RELOAD_DISTANCE_TOKENS = 16e3;
40370
+ }
40371
+ });
40372
+
39885
40373
  // src/memory/memdir/memdir.ts
39886
40374
  var memdir_exports = {};
39887
40375
  __export(memdir_exports, {
@@ -39894,8 +40382,8 @@ __export(memdir_exports, {
39894
40382
  loadMemoryPrompt: () => loadMemoryPrompt,
39895
40383
  truncateEntrypointContent: () => truncateEntrypointContent
39896
40384
  });
39897
- import { readFileSync as readFileSync39 } from "node:fs";
39898
- import { join as join56 } from "node:path";
40385
+ import { readFileSync as readFileSync41 } from "node:fs";
40386
+ import { join as join58 } from "node:path";
39899
40387
  function truncateEntrypointContent(raw) {
39900
40388
  const trimmed = raw.trim();
39901
40389
  const contentLines = trimmed.split("\n");
@@ -39988,11 +40476,11 @@ function buildMemoryLines(displayName, memoryDir, extraGuidelines, skipIndex = f
39988
40476
  }
39989
40477
  function buildMemoryPrompt(params) {
39990
40478
  const { displayName, memoryDir, extraGuidelines } = params;
39991
- const entrypoint = join56(memoryDir, ENTRYPOINT_NAME);
40479
+ const entrypoint = join58(memoryDir, ENTRYPOINT_NAME);
39992
40480
  let entrypointContent = params.entrypointContent ?? "";
39993
40481
  if (params.entrypointContent === void 0) {
39994
40482
  try {
39995
- entrypointContent = readFileSync39(entrypoint, "utf-8");
40483
+ entrypointContent = readFileSync41(entrypoint, "utf-8");
39996
40484
  } catch {
39997
40485
  }
39998
40486
  }
@@ -40038,8 +40526,8 @@ __export(context_analyzer_exports, {
40038
40526
  formatContextReport: () => formatContextReport,
40039
40527
  scanMemoryFiles: () => scanMemoryFiles2
40040
40528
  });
40041
- import * as fs17 from "node:fs";
40042
- import * as path15 from "node:path";
40529
+ import * as fs18 from "node:fs";
40530
+ import * as path16 from "node:path";
40043
40531
  function estimateMessageTokens2(m) {
40044
40532
  let tokens = 0;
40045
40533
  if (typeof m.content === "string") {
@@ -40149,9 +40637,9 @@ function breakdownMessages(messages) {
40149
40637
  }
40150
40638
  async function scanMemoryFiles2(workspace2) {
40151
40639
  const files = [];
40152
- const soul = readFileIfExists(path15.join(workspace2, "SOUL.md"));
40640
+ const soul = readFileIfExists(path16.join(workspace2, "SOUL.md"));
40153
40641
  if (soul) files.push({ path: "SOUL.md", tokens: roughTokenCountEstimation(soul), stable: true });
40154
- const agents = readFileIfExists(path15.join(workspace2, "AGENTS.md"));
40642
+ const agents = readFileIfExists(path16.join(workspace2, "AGENTS.md"));
40155
40643
  if (agents) files.push({ path: "AGENTS.md", tokens: roughTokenCountEstimation(agents), stable: true });
40156
40644
  try {
40157
40645
  const { buildMemoryPrompt: buildMemoryPrompt2 } = await Promise.resolve().then(() => (init_memdir(), memdir_exports));
@@ -40167,7 +40655,7 @@ async function scanMemoryFiles2(workspace2) {
40167
40655
  }
40168
40656
  function readFileIfExists(filePath) {
40169
40657
  try {
40170
- if (fs17.existsSync(filePath)) return fs17.readFileSync(filePath, "utf-8");
40658
+ if (fs18.existsSync(filePath)) return fs18.readFileSync(filePath, "utf-8");
40171
40659
  } catch {
40172
40660
  }
40173
40661
  return null;
@@ -40438,6 +40926,8 @@ var init_query = __esm({
40438
40926
  init_task_manager();
40439
40927
  init_skill_gate();
40440
40928
  init_skill_gate();
40929
+ init_query_skill_selection();
40930
+ init_SkillTool();
40441
40931
  QueryEngine = class _QueryEngine {
40442
40932
  constructor(provider, options) {
40443
40933
  this.provider = provider;
@@ -40791,6 +41281,7 @@ var init_query = __esm({
40791
41281
  turnCount++;
40792
41282
  const steers = this.pendingSteers.splice(0);
40793
41283
  let steerConsumedThisTurn = false;
41284
+ let userSteerConsumedThisTurn = false;
40794
41285
  if (steers.length > 0) {
40795
41286
  for (const input of steers) {
40796
41287
  if (this.steerHistoryIds.has(input.id)) {
@@ -40822,6 +41313,7 @@ var init_query = __esm({
40822
41313
  if (collectStopEvidence) stopUserMessages.push(input.originalText ?? input.text);
40823
41314
  this.steerHistoryIds.add(input.id);
40824
41315
  steerConsumedThisTurn = true;
41316
+ userSteerConsumedThisTurn = true;
40825
41317
  yield {
40826
41318
  type: "user_input",
40827
41319
  message: steerMsg,
@@ -41077,7 +41569,53 @@ var init_query = __esm({
41077
41569
  let turnAborted = false;
41078
41570
  try {
41079
41571
  wholeQueryAbort.signal.throwIfAborted();
41080
- const view = normalizeMessagesForAPI(currentMessages).map((m) => {
41572
+ const beforeRequest = () => {
41573
+ wholeQueryAbort.signal.throwIfAborted();
41574
+ ac.signal.throwIfAborted();
41575
+ };
41576
+ const startRequest = () => {
41577
+ this.phase = "streaming";
41578
+ assertRuntimeAuthority(void 0, "INPUT");
41579
+ if (perTurnOptions?.onRequestStarted) {
41580
+ const start = perTurnOptions.onRequestStarted;
41581
+ setImmediate(() => {
41582
+ if (!wholeQueryAbort.signal.aborted) start();
41583
+ });
41584
+ }
41585
+ };
41586
+ let selected;
41587
+ const selectionInput = perTurnOptions?.skillSelectionInput;
41588
+ const skill = turnCount === 1 && maxTurns >= 2 && !userSteerConsumedThisTurn && !hasPendingUserInput() && selectionInput ? allToolDefs.find((tool) => tool.function.name === SKILL_TOOL_NAME) : void 0;
41589
+ const catalog = skill ? getSkillSelectionCatalog() : void 0;
41590
+ if (skill && selectionInput && catalog?.entries.length) {
41591
+ const input = normalizeMessagesForAPI([selectionInput]);
41592
+ const started = performance.now();
41593
+ startRequest();
41594
+ const selection = await selectSkillCall(queryProvider, {
41595
+ preferFastFallback,
41596
+ model: queryModel,
41597
+ messages: input,
41598
+ tools: [skill],
41599
+ systemStable: SKILL_SELECTION_PROMPT + "\n\n" + JSON.stringify(catalog.entries),
41600
+ maxTokens: SKILL_SELECTION_MAX_TOKENS,
41601
+ signal: ac.signal,
41602
+ beforeRequest: () => {
41603
+ assertHostTurnCurrent();
41604
+ beforeRequest();
41605
+ },
41606
+ disableThinking: true
41607
+ }, catalog.allowedNames, recordUsage);
41608
+ assertHostTurnCurrent();
41609
+ beforeRequest();
41610
+ console.log(`${this.logPrefix} [skill-selection] ${selection.outcome} ms=${Math.round(performance.now() - started)}`);
41611
+ if (hasPendingUserInput()) continue;
41612
+ if (selection.outcome === "selected") {
41613
+ if (findLoadedSkillCall(currentMessages, selection.skill)) {
41614
+ console.log(`${this.logPrefix} [skill-selection] already-loaded ${selection.skill}`);
41615
+ } else selected = selection.chunks;
41616
+ }
41617
+ }
41618
+ const view = (selected ? [] : normalizeMessagesForAPI(currentMessages)).map((m) => {
41081
41619
  if (!Array.isArray(m.content) || !m.imageInput?.observed || !queryModelRef) return m;
41082
41620
  const blocks = m.content.filter((b) => {
41083
41621
  if (b.type === "image" || b.type === "image_ref") return !!queryInputs?.includes("image");
@@ -41112,7 +41650,7 @@ ${hint}` : [...current2.content, { type: "text", text: hint }] };
41112
41650
  const fullSystemDynamic = deferredHint && perTurnSystemDynamic ? `${deferredHint}
41113
41651
 
41114
41652
  ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
41115
- if ((!this.options.agentLabel || this.options.agentLabel === "main") && isContextDumpEnabled()) {
41653
+ if (!selected && (!this.options.agentLabel || this.options.agentLabel === "main") && isContextDumpEnabled()) {
41116
41654
  try {
41117
41655
  const ws = process.env.ENGINE7_WORKSPACE;
41118
41656
  if (ws) {
@@ -41128,15 +41666,8 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
41128
41666
  } catch {
41129
41667
  }
41130
41668
  }
41131
- this.phase = "streaming";
41132
- assertRuntimeAuthority(void 0, "INPUT");
41133
- if (perTurnOptions?.onRequestStarted) {
41134
- const start = perTurnOptions.onRequestStarted;
41135
- setImmediate(() => {
41136
- if (!wholeQueryAbort.signal.aborted) start();
41137
- });
41138
- }
41139
- for await (const chunk of queryProvider.streamChat({
41669
+ if (!selected) startRequest();
41670
+ for await (const chunk of selected ?? queryProvider.streamChat({
41140
41671
  preferFastFallback,
41141
41672
  model: queryModel,
41142
41673
  messages: apiMessages,
@@ -41149,10 +41680,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
41149
41680
  maxTokens: this.resolveRequestMaxTokens(apiMessages, maxTokensOverride),
41150
41681
  temperature: this.options.temperature,
41151
41682
  signal: ac.signal,
41152
- beforeRequest: () => {
41153
- wholeQueryAbort.signal.throwIfAborted();
41154
- ac.signal.throwIfAborted();
41155
- },
41683
+ beforeRequest,
41156
41684
  disableThinking: this.options.disableThinking || !!perTurnEmotion
41157
41685
  // 情感模式关 thinking(对齐 deskBuddy)
41158
41686
  })) {
@@ -41513,6 +42041,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
41513
42041
  if (vcDelivery) await vcDelivery;
41514
42042
  }
41515
42043
  const { messages: toolResults, summaries } = toolRes;
42044
+ if (selected) console.log(`${this.logPrefix} [skill-selection] ${summaries.length === 1 && !summaries[0].isError ? "loaded" : "load-failed"}`);
41516
42045
  if (collectStopEvidence) stopToolResults.push(...summaries);
41517
42046
  for (const s of summaries) {
41518
42047
  try {
@@ -41861,9 +42390,9 @@ var init_extractPrompts = __esm({
41861
42390
  });
41862
42391
 
41863
42392
  // src/memory/memdir/extractMemories.ts
41864
- import * as fs18 from "fs";
41865
- import * as path16 from "path";
41866
- import { createHash as createHash42 } from "node:crypto";
42393
+ import * as fs19 from "fs";
42394
+ import * as path17 from "path";
42395
+ import { createHash as createHash44 } from "node:crypto";
41867
42396
  function isModelVisibleMessage(message) {
41868
42397
  return message.role === "user" || message.role === "assistant";
41869
42398
  }
@@ -41871,7 +42400,7 @@ function messageText(message) {
41871
42400
  return typeof message.content === "string" ? message.content : message.content.filter((block) => block.type === "text").map((block) => block.text).join("\n");
41872
42401
  }
41873
42402
  function messageKey(message) {
41874
- return createHash42("sha256").update(JSON.stringify([message.role, message.timestamp ?? null, messageText(message)])).digest("hex");
42403
+ return createHash44("sha256").update(JSON.stringify([message.role, message.timestamp ?? null, messageText(message)])).digest("hex");
41875
42404
  }
41876
42405
  function filterNewMessages(messages, lastTs, acknowledged) {
41877
42406
  const newMessages = [];
@@ -41907,20 +42436,20 @@ For this extraction, all paths and search results are relative to the configured
41907
42436
  }));
41908
42437
  }
41909
42438
  function getStatePath(workspace2, topicsDir) {
41910
- return path16.join(topicsDir ?? getAutoMemPath(workspace2), STATE_FILE);
42439
+ return path17.join(topicsDir ?? getAutoMemPath(workspace2), STATE_FILE);
41911
42440
  }
41912
42441
  function loadPersistedState(workspace2, state, topicsDir) {
41913
42442
  try {
41914
42443
  let p = getStatePath(workspace2, topicsDir);
41915
- if (!topicsDir && !fs18.existsSync(p)) {
41916
- const legacy = path16.join(workspace2, STATE_FILE);
41917
- if (fs18.existsSync(legacy)) {
42444
+ if (!topicsDir && !fs19.existsSync(p)) {
42445
+ const legacy = path17.join(workspace2, STATE_FILE);
42446
+ if (fs19.existsSync(legacy)) {
41918
42447
  p = legacy;
41919
42448
  console.log("[memory] \u6C34\u4F4D\u81EA\u65E7\u8DEF\u5F84\uFF08workspace \u6839\uFF09\u8BFB\u5165\uFF0C\u4E0B\u6B21\u843D\u76D8\u8FC1\u79FB\u81F3 memoryDir");
41920
42449
  }
41921
42450
  }
41922
- if (fs18.existsSync(p)) {
41923
- const data = JSON.parse(fs18.readFileSync(p, "utf-8"));
42451
+ if (fs19.existsSync(p)) {
42452
+ const data = JSON.parse(fs19.readFileSync(p, "utf-8"));
41924
42453
  for (const [sid, ts] of Object.entries(data.lastTs ?? {})) {
41925
42454
  state.lastTs.set(sid, ts);
41926
42455
  }
@@ -41945,19 +42474,19 @@ function persistState(workspace2, state, topicsDir) {
41945
42474
  const acknowledged = Object.fromEntries([...state.acknowledged].map(([sid, keys]) => [sid, [...keys]]));
41946
42475
  const data = JSON.stringify({ lastTs, timestamps, acknowledged }, null, 2);
41947
42476
  const target = getStatePath(workspace2, topicsDir);
41948
- fs18.mkdirSync(path16.dirname(target), { recursive: true });
42477
+ fs19.mkdirSync(path17.dirname(target), { recursive: true });
41949
42478
  const temporary = `${target}.${process.pid}.tmp`;
41950
- fs18.writeFileSync(temporary, data, "utf-8");
41951
- fs18.renameSync(temporary, target);
42479
+ fs19.writeFileSync(temporary, data, "utf-8");
42480
+ fs19.renameSync(temporary, target);
41952
42481
  } catch (e) {
41953
42482
  if (topicsDir) throw e;
41954
42483
  console.warn(`[memory] failed to persist extract state: ${e?.message ?? e}`);
41955
42484
  }
41956
42485
  }
41957
42486
  function createMemoryExtractor(workspace2, enabled, topicsDir) {
41958
- workspace2 = fs18.existsSync(workspace2) ? fs18.realpathSync(workspace2) : path16.resolve(workspace2);
41959
- const declaredMemoryDir = path16.resolve(topicsDir ?? getAutoMemPath(workspace2));
41960
- const memoryDir = fs18.existsSync(declaredMemoryDir) ? fs18.realpathSync(declaredMemoryDir) : declaredMemoryDir;
42487
+ workspace2 = fs19.existsSync(workspace2) ? fs19.realpathSync(workspace2) : path17.resolve(workspace2);
42488
+ const declaredMemoryDir = path17.resolve(topicsDir ?? getAutoMemPath(workspace2));
42489
+ const memoryDir = fs19.existsSync(declaredMemoryDir) ? fs19.realpathSync(declaredMemoryDir) : declaredMemoryDir;
41961
42490
  let shared = workspaceStates.get(memoryDir);
41962
42491
  if (!shared) {
41963
42492
  shared = { lastTs: /* @__PURE__ */ new Map(), acknowledged: /* @__PURE__ */ new Map(), lastExtractTime: /* @__PURE__ */ new Map(), generations: /* @__PURE__ */ new Map() };
@@ -42014,11 +42543,11 @@ function createMemoryExtractor(workspace2, enabled, topicsDir) {
42014
42543
  (await scanMemoryFiles(memoryDir, new AbortController().signal)).map((memory) => ({ ...memory, filename: memory.filename.replace(/\\/g, "/") })),
42015
42544
  { maxDescriptionChars: 120, timestamps: false }
42016
42545
  );
42017
- const extractOverridePath = path16.join(workspace2, "prompts", "extract.md");
42546
+ const extractOverridePath = path17.join(workspace2, "prompts", "extract.md");
42018
42547
  let systemPrompt;
42019
42548
  try {
42020
- if (fs18.existsSync(extractOverridePath)) {
42021
- systemPrompt = fs18.readFileSync(extractOverridePath, { encoding: "utf-8" });
42549
+ if (fs19.existsSync(extractOverridePath)) {
42550
+ systemPrompt = fs19.readFileSync(extractOverridePath, { encoding: "utf-8" });
42022
42551
  if (existingMemories.length > 0) {
42023
42552
  systemPrompt += `
42024
42553
 
@@ -42166,7 +42695,7 @@ ${conversationText}`
42166
42695
  if (generation !== (state.generations.get(sessionId) ?? 0)) return false;
42167
42696
  const interval = previous && !alreadyCoolingDown ? 0 : intervalMinutes;
42168
42697
  if (!topicsDir) return extract(snapshot, provider, model, sessionId, disableThinking, interval);
42169
- return withFileTransaction(path16.join(memoryDir, ".extract-lock.sqlite"), () => {
42698
+ return withFileTransaction(path17.join(memoryDir, ".extract-lock.sqlite"), () => {
42170
42699
  loadPersistedState(workspace2, state, memoryDir);
42171
42700
  return extract(snapshot, provider, model, sessionId, disableThinking, interval);
42172
42701
  }, void 0, 12e4);
@@ -42244,11 +42773,11 @@ var init_providers = __esm({
42244
42773
 
42245
42774
  // src/task-sessions/extraction.ts
42246
42775
  import { mkdir as mkdir2, readFile as readFile2, readdir as readdir4, rename, rm as rm2, writeFile } from "node:fs/promises";
42247
- import { basename as basename13, dirname as dirname30, join as join59, resolve as resolve22 } from "node:path";
42776
+ import { basename as basename13, dirname as dirname31, join as join61, resolve as resolve22 } from "node:path";
42248
42777
  function validTaskTopicNotice(stateDir2, notice) {
42249
42778
  if (!notice.topicsDir || !notice.sessionId || !notice.transcriptPath.endsWith(".jsonl")) return false;
42250
- const project = dirname30(resolve22(notice.topicsDir));
42251
- return dirname30(project) === resolve22(stateDir2, "agents", "main", "projects") && resolve22(notice.topicsDir) === join59(project, "topics") && dirname30(resolve22(notice.transcriptPath)) === join59(project, "sessions");
42779
+ const project = dirname31(resolve22(notice.topicsDir));
42780
+ return dirname31(project) === resolve22(stateDir2, "agents", "main", "projects") && resolve22(notice.topicsDir) === join61(project, "topics") && dirname31(resolve22(notice.transcriptPath)) === join61(project, "sessions");
42252
42781
  }
42253
42782
  async function readPendingTaskTopics(stateDir2) {
42254
42783
  const dir = queueDir(stateDir2);
@@ -42262,7 +42791,7 @@ async function readPendingTaskTopics(stateDir2) {
42262
42791
  const items = [];
42263
42792
  for (const name of names) {
42264
42793
  if (!/^[a-f0-9]{64}-[a-f0-9-]{36}\.json$/.test(name)) continue;
42265
- const file2 = join59(dir, name);
42794
+ const file2 = join61(dir, name);
42266
42795
  try {
42267
42796
  const notice = JSON.parse(await readFile2(file2, "utf8"));
42268
42797
  if (validTaskTopicNotice(stateDir2, notice)) items.push({ file: file2, notice });
@@ -42276,8 +42805,8 @@ function acknowledgeTaskTopics(item) {
42276
42805
  return rm2(item.file, { force: true });
42277
42806
  }
42278
42807
  async function markTaskTopicsWorker(stateDir2) {
42279
- const marker = join59(queueDir(stateDir2), "worker.pid");
42280
- await mkdir2(dirname30(marker), { recursive: true });
42808
+ const marker = join61(queueDir(stateDir2), "worker.pid");
42809
+ await mkdir2(dirname31(marker), { recursive: true });
42281
42810
  await writeFile(marker, String(process.pid));
42282
42811
  return async () => {
42283
42812
  if (await readFile2(marker, "utf8").catch(() => "") === String(process.pid)) await rm2(marker, { force: true });
@@ -42291,20 +42820,20 @@ var init_extraction = __esm({
42291
42820
  init_extractMemories();
42292
42821
  init_reader2();
42293
42822
  init_providers();
42294
- queueDir = (stateDir2) => join59(stateDir2, "task-topics-queue");
42823
+ queueDir = (stateDir2) => join61(stateDir2, "task-topics-queue");
42295
42824
  }
42296
42825
  });
42297
42826
 
42298
42827
  // src/tools/read.ts
42299
- import * as fs19 from "node:fs";
42300
- import * as path17 from "node:path";
42828
+ import * as fs20 from "node:fs";
42829
+ import * as path18 from "node:path";
42301
42830
  function isBlockedDevicePath(filePath) {
42302
42831
  if (BLOCKED_DEVICE_PATHS.has(filePath)) return true;
42303
42832
  if (filePath.startsWith("/proc/") && (filePath.endsWith("/fd/0") || filePath.endsWith("/fd/1") || filePath.endsWith("/fd/2"))) return true;
42304
42833
  return false;
42305
42834
  }
42306
42835
  function checkReadLoop(filePath, offset, limit) {
42307
- const stat3 = fs19.statSync(filePath);
42836
+ const stat3 = fs20.statSync(filePath);
42308
42837
  const mtimeMs = stat3.mtimeMs;
42309
42838
  const prev = readHistory.get(filePath);
42310
42839
  if (prev && prev.offset === offset && prev.limit === limit && prev.mtimeMs === mtimeMs) {
@@ -42318,19 +42847,19 @@ function checkReadLoop(filePath, offset, limit) {
42318
42847
  return null;
42319
42848
  }
42320
42849
  function readFileContent(filePath) {
42321
- const fd = fs19.openSync(filePath, "r");
42850
+ const fd = fs20.openSync(filePath, "r");
42322
42851
  const bom = Buffer.alloc(2);
42323
- fs19.readSync(fd, bom, 0, 2, 0);
42324
- fs19.closeSync(fd);
42852
+ fs20.readSync(fd, bom, 0, 2, 0);
42853
+ fs20.closeSync(fd);
42325
42854
  let encoding = "utf8";
42326
42855
  if (bom[0] === 255 && bom[1] === 254) {
42327
42856
  encoding = "utf16le";
42328
42857
  }
42329
- const stat3 = fs19.statSync(filePath);
42858
+ const stat3 = fs20.statSync(filePath);
42330
42859
  if (stat3.size > MAX_FILE_SIZE) {
42331
42860
  throw new Error(`\u6587\u4EF6\u592A\u5927 (${(stat3.size / 1024).toFixed(1)}KB)\uFF0C\u8D85\u8FC7 ${MAX_FILE_SIZE / 1024}KB \u9650\u5236\u3002\u8BF7\u4F7F\u7528 offset + limit \u5206\u6BB5\u8BFB\u53D6\u3002`);
42332
42861
  }
42333
- const raw = fs19.readFileSync(filePath, encoding);
42862
+ const raw = fs20.readFileSync(filePath, encoding);
42334
42863
  const content = raw.toString().replaceAll("\r\n", "\n");
42335
42864
  return { content, encoding };
42336
42865
  }
@@ -42485,11 +43014,11 @@ Usage:
42485
43014
  } catch (e) {
42486
43015
  return { content: e.message, isError: true };
42487
43016
  }
42488
- if (!fs19.existsSync(filePath)) {
43017
+ if (!fs20.existsSync(filePath)) {
42489
43018
  return { content: `\u6587\u4EF6\u4E0D\u5B58\u5728: ${displayFilePath(filePath, ctx)}`, isError: true };
42490
43019
  }
42491
- const stat3 = fs19.statSync(filePath);
42492
- const baseName = path17.basename(filePath).toUpperCase();
43020
+ const stat3 = fs20.statSync(filePath);
43021
+ const baseName = path18.basename(filePath).toUpperCase();
42493
43022
  if (BLOCKED_BASENAMES.has(baseName)) {
42494
43023
  return { content: `\u8BBE\u5907\u6587\u4EF6\u4E0D\u652F\u6301\u8BFB\u53D6: ${displayFilePath(filePath, ctx)}`, isError: true };
42495
43024
  }
@@ -42497,11 +43026,11 @@ Usage:
42497
43026
  return { content: `\u8BBE\u5907\u6587\u4EF6\u4F1A\u963B\u585E\u6216\u4EA7\u751F\u65E0\u9650\u8F93\u51FA: ${displayFilePath(filePath, ctx)}`, isError: true };
42498
43027
  }
42499
43028
  if (stat3.isDirectory()) {
42500
- const entries = fs19.readdirSync(filePath);
43029
+ const entries = fs20.readdirSync(filePath);
42501
43030
  const items = entries.map((e) => {
42502
- const full = path17.join(filePath, e);
43031
+ const full = path18.join(filePath, e);
42503
43032
  try {
42504
- const s = fs19.statSync(full);
43033
+ const s = fs20.statSync(full);
42505
43034
  return s.isDirectory() ? `${e}/` : e;
42506
43035
  } catch {
42507
43036
  return e;
@@ -42510,7 +43039,7 @@ Usage:
42510
43039
  return { content: `\u76EE\u5F55 (${entries.length} \u9879):
42511
43040
  ${items.join("\n")}` };
42512
43041
  }
42513
- const ext = path17.extname(filePath).toLowerCase();
43042
+ const ext = path18.extname(filePath).toLowerCase();
42514
43043
  if (BINARY_EXTENSIONS.has(ext)) {
42515
43044
  const hint = DOC_SKILL_HINTS[ext];
42516
43045
  return {
@@ -42573,9 +43102,9 @@ ${result}` : result };
42573
43102
  });
42574
43103
 
42575
43104
  // src/memory/topics-history/writes.ts
42576
- import { basename as basename15, relative as relative9, isAbsolute as isAbsolute6, sep as sep7 } from "node:path";
43105
+ import { basename as basename15, relative as relative10, isAbsolute as isAbsolute6, sep as sep7 } from "node:path";
42577
43106
  function stampTopicWrite(file2, workspace2, text2, previous, topicsDir, recordedAt) {
42578
- const rel = topicsDir ? relative9(topicsDir, file2) : "";
43107
+ const rel = topicsDir ? relative10(topicsDir, file2) : "";
42579
43108
  const isTopic = topicsDir ? !!rel && !isAbsolute6(rel) && rel !== ".." && !rel.startsWith(".." + sep7) : workspace2 && isAutoMemPath(file2, workspace2);
42580
43109
  if (!isTopic || !/\.md$/i.test(file2) || basename15(file2).toUpperCase() === "MEMORY.MD") return text2;
42581
43110
  const date = /(?<!\d)(\d{4}-\d{2}-\d{2})(?!\d)/.exec(basename15(file2))?.[1];
@@ -42591,22 +43120,22 @@ var init_writes = __esm({
42591
43120
  });
42592
43121
 
42593
43122
  // src/tools/write.ts
42594
- import * as fs20 from "node:fs";
42595
- import * as path18 from "node:path";
43123
+ import * as fs21 from "node:fs";
43124
+ import * as path19 from "node:path";
42596
43125
  function isBlockedPath(filePath, memoryToolRoot) {
42597
43126
  return !memoryToolRoot && /\/root\//i.test(filePath) || BLOCKED_PATTERNS.some((p) => p.test(filePath));
42598
43127
  }
42599
43128
  function atomicWrite(filePath, content) {
42600
43129
  const tmpPath = filePath + ".tmp." + Date.now() + ".write";
42601
- fs20.writeFileSync(tmpPath, content, "utf-8");
43130
+ fs21.writeFileSync(tmpPath, content, "utf-8");
42602
43131
  try {
42603
- fs20.renameSync(tmpPath, filePath);
43132
+ fs21.renameSync(tmpPath, filePath);
42604
43133
  } catch (e) {
42605
43134
  try {
42606
- fs20.unlinkSync(tmpPath);
43135
+ fs21.unlinkSync(tmpPath);
42607
43136
  } catch {
42608
43137
  }
42609
- fs20.writeFileSync(filePath, content, "utf-8");
43138
+ fs21.writeFileSync(filePath, content, "utf-8");
42610
43139
  }
42611
43140
  }
42612
43141
  function simpleDiff(oldContent, newContent) {
@@ -42700,15 +43229,15 @@ Usage:
42700
43229
  }
42701
43230
  const rawContent = args2.content;
42702
43231
  let content = rawContent.replaceAll("\r\n", "\n");
42703
- if (fs20.existsSync(filePath) && fs20.statSync(filePath).isDirectory()) {
43232
+ if (fs21.existsSync(filePath) && fs21.statSync(filePath).isDirectory()) {
42704
43233
  return { content: `\u8DEF\u5F84\u662F\u76EE\u5F55\u4E0D\u662F\u6587\u4EF6: ${displayFilePath(filePath, ctx)}`, isError: true };
42705
43234
  }
42706
43235
  let oldContent = null;
42707
43236
  let isCreate = true;
42708
- if (fs20.existsSync(filePath)) {
43237
+ if (fs21.existsSync(filePath)) {
42709
43238
  isCreate = false;
42710
43239
  try {
42711
- oldContent = fs20.readFileSync(filePath, "utf-8").replaceAll("\r\n", "\n");
43240
+ oldContent = fs21.readFileSync(filePath, "utf-8").replaceAll("\r\n", "\n");
42712
43241
  } catch {
42713
43242
  isCreate = true;
42714
43243
  }
@@ -42724,10 +43253,10 @@ Usage:
42724
43253
  isError: true
42725
43254
  };
42726
43255
  }
42727
- const currentStat = fs20.statSync(filePath);
43256
+ const currentStat = fs21.statSync(filePath);
42728
43257
  const lastWriteTime = Math.floor(currentStat.mtimeMs);
42729
43258
  if (lastWriteTime > readState.timestamp) {
42730
- const currentContent = fs20.readFileSync(filePath, "utf-8").replaceAll("\r\n", "\n");
43259
+ const currentContent = fs21.readFileSync(filePath, "utf-8").replaceAll("\r\n", "\n");
42731
43260
  if (currentContent !== oldContent) {
42732
43261
  return {
42733
43262
  content: `\u6587\u4EF6\u5728\u8BFB\u53D6\u540E\u88AB\u4FEE\u6539\u3002\u8BF7\u5148\u91CD\u65B0\u8BFB\u53D6\u6587\u4EF6\u518D\u5199\u5165: ${displayFilePath(filePath, ctx)}`,
@@ -42736,9 +43265,9 @@ Usage:
42736
43265
  }
42737
43266
  }
42738
43267
  }
42739
- const dir = path18.dirname(filePath);
43268
+ const dir = path19.dirname(filePath);
42740
43269
  try {
42741
- fs20.mkdirSync(dir, { recursive: true });
43270
+ fs21.mkdirSync(dir, { recursive: true });
42742
43271
  } catch (e) {
42743
43272
  return { content: `\u65E0\u6CD5\u521B\u5EFA\u76EE\u5F55: ${dir} \u2014 ${e.message}`, isError: true };
42744
43273
  }
@@ -42749,11 +43278,11 @@ Usage:
42749
43278
  } catch (e) {
42750
43279
  return { content: `\u5199\u5165\u5931\u8D25: ${e.message}`, isError: true };
42751
43280
  }
42752
- readFileState.set(filePath, { timestamp: fs20.statSync(filePath).mtimeMs });
43281
+ readFileState.set(filePath, { timestamp: fs21.statSync(filePath).mtimeMs });
42753
43282
  const action = isCreate ? "\u521B\u5EFA" : "\u66F4\u65B0";
42754
43283
  const lines = content.split("\n").length;
42755
43284
  const chars = content.length;
42756
- const stat3 = fs20.statSync(filePath);
43285
+ const stat3 = fs21.statSync(filePath);
42757
43286
  let diff = "";
42758
43287
  if (!isCreate && oldContent !== null) {
42759
43288
  diff = `
@@ -42772,8 +43301,8 @@ ${simpleDiff(oldContent, content)}`;
42772
43301
  });
42773
43302
 
42774
43303
  // src/tools/edit.ts
42775
- import * as fs21 from "node:fs";
42776
- import * as path19 from "node:path";
43304
+ import * as fs22 from "node:fs";
43305
+ import * as path20 from "node:path";
42777
43306
  function normalizeQuotes(str) {
42778
43307
  return str.replaceAll(LEFT_SINGLE_CURLY, "'").replaceAll(RIGHT_SINGLE_CURLY, "'").replaceAll(LEFT_DOUBLE_CURLY, '"').replaceAll(RIGHT_DOUBLE_CURLY, '"');
42779
43308
  }
@@ -42927,7 +43456,7 @@ Usage:
42927
43456
  }
42928
43457
  let fileContent = null;
42929
43458
  try {
42930
- const stat3 = fs21.statSync(filePath);
43459
+ const stat3 = fs22.statSync(filePath);
42931
43460
  if (stat3.isDirectory()) {
42932
43461
  return { content: `\u8DEF\u5F84\u662F\u76EE\u5F55\u4E0D\u662F\u6587\u4EF6: ${displayFilePath(filePath, ctx)}`, isError: true };
42933
43462
  }
@@ -42937,23 +43466,23 @@ Usage:
42937
43466
  } catch (e) {
42938
43467
  if (e.code === "ENOENT") {
42939
43468
  if (oldString === "") {
42940
- const dir = path19.dirname(filePath);
42941
- fs21.mkdirSync(dir, { recursive: true });
42942
- fs21.writeFileSync(filePath, stampTopicWrite(filePath, ctx.workspace, newString, null, ctx.projectTask?.topicsDir ?? ctx.memoryToolRoot, ctx.topicSourceTime), "utf-8");
43469
+ const dir = path20.dirname(filePath);
43470
+ fs22.mkdirSync(dir, { recursive: true });
43471
+ fs22.writeFileSync(filePath, stampTopicWrite(filePath, ctx.workspace, newString, null, ctx.projectTask?.topicsDir ?? ctx.memoryToolRoot, ctx.topicSourceTime), "utf-8");
42943
43472
  noteTopicWrite(filePath, ctx);
42944
- readFileState.set(filePath, { timestamp: fs21.statSync(filePath).mtimeMs });
43473
+ readFileState.set(filePath, { timestamp: fs22.statSync(filePath).mtimeMs });
42945
43474
  return { content: `\u521B\u5EFA\u6587\u4EF6: ${displayFilePath(filePath, ctx)} (${newString.split("\n").length} \u884C)` };
42946
43475
  }
42947
43476
  return { content: `\u6587\u4EF6\u4E0D\u5B58\u5728: ${displayFilePath(filePath, ctx)}`, isError: true };
42948
43477
  }
42949
43478
  throw e;
42950
43479
  }
42951
- const rawContent = fs21.readFileSync(filePath, "utf-8");
43480
+ const rawContent = fs22.readFileSync(filePath, "utf-8");
42952
43481
  fileContent = rawContent.replaceAll("\r\n", "\n");
42953
43482
  if (oldString === "" && fileContent.trim() === "") {
42954
- fs21.writeFileSync(filePath, stampTopicWrite(filePath, ctx.workspace, newString, fileContent, ctx.projectTask?.topicsDir ?? ctx.memoryToolRoot, ctx.topicSourceTime), "utf-8");
43483
+ fs22.writeFileSync(filePath, stampTopicWrite(filePath, ctx.workspace, newString, fileContent, ctx.projectTask?.topicsDir ?? ctx.memoryToolRoot, ctx.topicSourceTime), "utf-8");
42955
43484
  noteTopicWrite(filePath, ctx);
42956
- readFileState.set(filePath, { timestamp: fs21.statSync(filePath).mtimeMs });
43485
+ readFileState.set(filePath, { timestamp: fs22.statSync(filePath).mtimeMs });
42957
43486
  return { content: `\u5199\u5165\u7A7A\u6587\u4EF6: ${displayFilePath(filePath, ctx)} (${newString.split("\n").length} \u884C)` };
42958
43487
  }
42959
43488
  const readState = readFileState.get(filePath);
@@ -42963,11 +43492,11 @@ Usage:
42963
43492
  isError: true
42964
43493
  };
42965
43494
  }
42966
- const currentStat = fs21.statSync(filePath);
43495
+ const currentStat = fs22.statSync(filePath);
42967
43496
  const lastWriteTime = Math.floor(currentStat.mtimeMs);
42968
43497
  if (lastWriteTime > readState.timestamp) {
42969
43498
  if (fileContent !== rawContent.replaceAll("\r\n", "\n")) {
42970
- if (fileContent !== fs21.readFileSync(filePath, "utf-8").replaceAll("\r\n", "\n")) {
43499
+ if (fileContent !== fs22.readFileSync(filePath, "utf-8").replaceAll("\r\n", "\n")) {
42971
43500
  return {
42972
43501
  content: `\u6587\u4EF6\u5728\u8BFB\u53D6\u540E\u88AB\u4FEE\u6539\u3002\u8BF7\u5148\u91CD\u65B0\u8BFB\u53D6\u6587\u4EF6\u518D\u7F16\u8F91: ${displayFilePath(filePath, ctx)}`,
42973
43502
  isError: true
@@ -43000,9 +43529,9 @@ ${preview}
43000
43529
  const diffView = generateEditDiff(fileContent, actualOldString, actualNewString);
43001
43530
  const newContent = applyEditToFile(fileContent, actualOldString, actualNewString, replaceAll);
43002
43531
  if (newContent === fileContent) return { content: "\u6587\u4EF6\u5185\u5BB9\u672A\u53D8\u5316\uFF0C\u65E0\u987B\u5199\u5165\u3002" };
43003
- fs21.writeFileSync(filePath, stampTopicWrite(filePath, ctx.workspace, newContent, fileContent, ctx.projectTask?.topicsDir ?? ctx.memoryToolRoot, ctx.topicSourceTime), "utf-8");
43532
+ fs22.writeFileSync(filePath, stampTopicWrite(filePath, ctx.workspace, newContent, fileContent, ctx.projectTask?.topicsDir ?? ctx.memoryToolRoot, ctx.topicSourceTime), "utf-8");
43004
43533
  noteTopicWrite(filePath, ctx);
43005
- readFileState.set(filePath, { timestamp: fs21.statSync(filePath).mtimeMs });
43534
+ readFileState.set(filePath, { timestamp: fs22.statSync(filePath).mtimeMs });
43006
43535
  const strategy = actualOldString === oldString ? "\u7CBE\u786E\u5339\u914D" : "\u5F15\u53F7\u89C4\u8303\u5316\u5339\u914D";
43007
43536
  const count = replaceAll ? matchCount : 1;
43008
43537
  const diff = `${oldString.length}\u2192${newString.length}\u5B57\u7B26`;
@@ -43019,8 +43548,8 @@ ${diffView}`
43019
43548
  });
43020
43549
 
43021
43550
  // src/tools/glob.ts
43022
- import * as fs22 from "node:fs";
43023
- import * as path20 from "node:path";
43551
+ import * as fs23 from "node:fs";
43552
+ import * as path21 from "node:path";
43024
43553
  function globMatch(pattern, filename) {
43025
43554
  const regexStr = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "{{GLOBSTAR}}").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]").replace(/\{\{GLOBSTAR\}\}/g, ".*");
43026
43555
  try {
@@ -43032,7 +43561,7 @@ function globMatch(pattern, filename) {
43032
43561
  function findFiles(dir, pattern, limit, baseDir) {
43033
43562
  const results = [];
43034
43563
  let truncated = false;
43035
- function walk(currentDir) {
43564
+ function walk2(currentDir) {
43036
43565
  if (truncated) return;
43037
43566
  if (results.length >= limit * 2) {
43038
43567
  truncated = true;
@@ -43040,18 +43569,18 @@ function findFiles(dir, pattern, limit, baseDir) {
43040
43569
  }
43041
43570
  let entries;
43042
43571
  try {
43043
- entries = fs22.readdirSync(currentDir, { withFileTypes: true });
43572
+ entries = fs23.readdirSync(currentDir, { withFileTypes: true });
43044
43573
  } catch {
43045
43574
  return;
43046
43575
  }
43047
43576
  for (const entry of entries) {
43048
43577
  if (truncated) return;
43049
- const fullPath = path20.join(currentDir, entry.name);
43578
+ const fullPath = path21.join(currentDir, entry.name);
43050
43579
  if (entry.isDirectory()) {
43051
43580
  if (VCS_DIRS.has(entry.name)) continue;
43052
- walk(fullPath);
43581
+ walk2(fullPath);
43053
43582
  } else if (entry.isFile()) {
43054
- const relativePath = path20.relative(baseDir, fullPath).replace(/\\/g, "/");
43583
+ const relativePath = path21.relative(baseDir, fullPath).replace(/\\/g, "/");
43055
43584
  const patternsToTry = [pattern];
43056
43585
  if (pattern.startsWith("**/")) {
43057
43586
  patternsToTry.push(pattern.slice(3));
@@ -43061,7 +43590,7 @@ function findFiles(dir, pattern, limit, baseDir) {
43061
43590
  );
43062
43591
  if (matched) {
43063
43592
  try {
43064
- const stat3 = fs22.statSync(fullPath);
43593
+ const stat3 = fs23.statSync(fullPath);
43065
43594
  results.push({ path: fullPath, mtimeMs: stat3.mtimeMs });
43066
43595
  } catch {
43067
43596
  }
@@ -43069,7 +43598,7 @@ function findFiles(dir, pattern, limit, baseDir) {
43069
43598
  }
43070
43599
  }
43071
43600
  }
43072
- walk(dir);
43601
+ walk2(dir);
43073
43602
  results.sort((a, b) => b.mtimeMs - a.mtimeMs);
43074
43603
  const finalTruncated = truncated || results.length > limit;
43075
43604
  return {
@@ -43078,7 +43607,7 @@ function findFiles(dir, pattern, limit, baseDir) {
43078
43607
  };
43079
43608
  }
43080
43609
  function toRelativePath(absolutePath, cwd) {
43081
- if (absolutePath.startsWith(cwd + path20.sep)) {
43610
+ if (absolutePath.startsWith(cwd + path21.sep)) {
43082
43611
  return absolutePath.slice(cwd.length + 1);
43083
43612
  }
43084
43613
  return absolutePath;
@@ -43111,10 +43640,10 @@ var init_glob = __esm({
43111
43640
  const searchPath = args2.path ? resolveFilePath(args2.path, ctx) : resolveFilePath(".", ctx);
43112
43641
  const pattern = args2.pattern;
43113
43642
  const limit = args2.limit || DEFAULT_LIMIT;
43114
- if (!fs22.existsSync(searchPath)) {
43643
+ if (!fs23.existsSync(searchPath)) {
43115
43644
  return { content: `\u76EE\u5F55\u4E0D\u5B58\u5728: ${displayFilePath(searchPath, ctx)}`, isError: true };
43116
43645
  }
43117
- if (!fs22.statSync(searchPath).isDirectory()) {
43646
+ if (!fs23.statSync(searchPath).isDirectory()) {
43118
43647
  return { content: `\u8DEF\u5F84\u4E0D\u662F\u76EE\u5F55: ${displayFilePath(searchPath, ctx)}`, isError: true };
43119
43648
  }
43120
43649
  const start = Date.now();
@@ -43138,7 +43667,7 @@ ${filenames.join("\n")}${truncatedNote}`
43138
43667
 
43139
43668
  // src/tools/grep.ts
43140
43669
  import { execFile as execFile3 } from "node:child_process";
43141
- import * as path21 from "node:path";
43670
+ import * as path22 from "node:path";
43142
43671
  function ripGrep(args2, searchPath, signal) {
43143
43672
  return new Promise((resolve26) => {
43144
43673
  const fullArgs = [...args2, searchPath];
@@ -43176,7 +43705,7 @@ function applyHeadLimit(items, limit, offset = 0) {
43176
43705
  };
43177
43706
  }
43178
43707
  function toRelativePath2(absolutePath, cwd) {
43179
- if (absolutePath.startsWith(cwd + path21.sep)) {
43708
+ if (absolutePath.startsWith(cwd + path22.sep)) {
43180
43709
  return absolutePath.slice(cwd.length + 1);
43181
43710
  }
43182
43711
  if (absolutePath.startsWith(cwd)) {
@@ -43287,7 +43816,7 @@ var init_grep = __esm({
43287
43816
  if (result.lines.length === 0) {
43288
43817
  return { content: "No files found" };
43289
43818
  }
43290
- const cwd = ctx.memoryToolRoot ? path21.resolve(ctx.memoryToolRoot) : ctx.workspace;
43819
+ const cwd = ctx.memoryToolRoot ? path22.resolve(ctx.memoryToolRoot) : ctx.workspace;
43291
43820
  const lines = result.lines.map((line) => toRelativePath2(line, cwd));
43292
43821
  if (outputMode === "content") {
43293
43822
  const { items: limited2, appliedLimit: appliedLimit2 } = applyHeadLimit(lines, headLimit, offset);
@@ -43355,7 +43884,7 @@ __export(topic_extraction_exports, {
43355
43884
  startTopicExtraction: () => startTopicExtraction
43356
43885
  });
43357
43886
  import { readFile as readFile3, stat as stat2 } from "node:fs/promises";
43358
- import { basename as basename16, join as join62, resolve as resolve24 } from "node:path";
43887
+ import { basename as basename16, join as join64, resolve as resolve24 } from "node:path";
43359
43888
  function startTopicExtraction(config, workspace2, stateDir2, isBusy) {
43360
43889
  const toolConfig = { stateDir: stateDir2, workspace: workspace2 };
43361
43890
  liveConfig.init(toolConfig);
@@ -43481,12 +44010,12 @@ function startTopicExtraction(config, workspace2, stateDir2, isBusy) {
43481
44010
  const recover = async () => {
43482
44011
  if (!enabled()) return;
43483
44012
  try {
43484
- const dir = join62(stateDir2, "agents", "main", "sessions");
43485
- const [platform, index] = await Promise.all(["platform-map.json", "session-index.json"].map((file3) => readFile3(join62(dir, file3), "utf8").then(JSON.parse)));
44013
+ const dir = join64(stateDir2, "agents", "main", "sessions");
44014
+ const [platform, index] = await Promise.all(["platform-map.json", "session-index.json"].map((file3) => readFile3(join64(dir, file3), "utf8").then(JSON.parse)));
43486
44015
  const sessionId = platform["scope:main"], file2 = index[sessionId]?.file;
43487
44016
  if (typeof sessionId === "string" && typeof file2 === "string") {
43488
44017
  const localName = basename16(file2.replace(/\\/g, "/"));
43489
- notify({ sessionId, transcriptPath: join62(dir, localName) });
44018
+ notify({ sessionId, transcriptPath: join64(dir, localName) });
43490
44019
  }
43491
44020
  } catch (error) {
43492
44021
  if (error?.code !== "ENOENT") console.warn(`[bg-worker] topics recovery: ${error?.message ?? error}`);
@@ -43546,7 +44075,7 @@ var init_topic_extraction = __esm({
43546
44075
  });
43547
44076
 
43548
44077
  // src/bg/bg-worker.ts
43549
- import { existsSync as existsSync32 } from "node:fs";
44078
+ import { existsSync as existsSync34 } from "node:fs";
43550
44079
  import { resolve as resolve25 } from "node:path";
43551
44080
 
43552
44081
  // src/bg/host.ts
@@ -43559,8 +44088,8 @@ init_pipeline();
43559
44088
  init_job_runner();
43560
44089
  init_projection_driver();
43561
44090
  import { execFile as execFile2, fork as fork2 } from "node:child_process";
43562
- import { dirname as dirname27, join as join52 } from "node:path";
43563
- import { existsSync as existsSync25 } from "node:fs";
44091
+ import { dirname as dirname27, join as join53 } from "node:path";
44092
+ import { existsSync as existsSync26 } from "node:fs";
43564
44093
  import { fileURLToPath as fileURLToPath14 } from "node:url";
43565
44094
 
43566
44095
  // src/mem7/worker-projection.ts
@@ -43643,9 +44172,9 @@ var diagnosticLimits = /* @__PURE__ */ new Map();
43643
44172
  var operationSequence = 0;
43644
44173
  var fingerprint = (line) => createHash34("sha256").update(line).digest("hex").slice(0, 16);
43645
44174
  var storageCode = (error) => String(error?.code ?? error?.message?.match(/INTAKE_[A-Z_]+/)?.[0] ?? "UNKNOWN");
43646
- function fileBytes(path22) {
44175
+ function fileBytes(path23) {
43647
44176
  try {
43648
- return statSync4(path22).size;
44177
+ return statSync4(path23).size;
43649
44178
  } catch (error) {
43650
44179
  if (error?.code !== "ENOENT") throw error;
43651
44180
  return 0;
@@ -43729,11 +44258,11 @@ function warnIntake(stateDir2, message) {
43729
44258
  }
43730
44259
  warnings.set(key5, { at: now2, suppressed: 0 });
43731
44260
  }
43732
- function lockOwnerState(path22) {
44261
+ function lockOwnerState(path23) {
43733
44262
  let pid;
43734
44263
  try {
43735
- if (fileBytes(path22) > 32) return "alive";
43736
- pid = Number(readFileSync32(path22, "utf8").trim());
44264
+ if (fileBytes(path23) > 32) return "alive";
44265
+ pid = Number(readFileSync32(path23, "utf8").trim());
43737
44266
  } catch (error) {
43738
44267
  if (error?.code === "ENOENT") return "missing";
43739
44268
  throw error;
@@ -43747,15 +44276,15 @@ function lockOwnerState(path22) {
43747
44276
  }
43748
44277
  }
43749
44278
  function withSpoolWriteLock(stateDir2, operation) {
43750
- const path22 = writeLockPath(stateDir2);
43751
- mkdirSync17(dirname21(path22), { recursive: true });
44279
+ const path23 = writeLockPath(stateDir2);
44280
+ mkdirSync17(dirname21(path23), { recursive: true });
43752
44281
  let fd;
43753
44282
  try {
43754
- fd = openSync10(path22, "wx");
44283
+ fd = openSync10(path23, "wx");
43755
44284
  } catch (error) {
43756
44285
  if (error?.code !== "EEXIST") throw error;
43757
- if (lockOwnerState(path22) === "alive") throw Error("INTAKE_WRITER_BUSY: \u5199\u5165\u8005\u6B63\u5728\u64CD\u4F5C\uFF0C\u672A\u5165\u961F\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
43758
- const reaperPath = path22 + ".reap";
44286
+ if (lockOwnerState(path23) === "alive") throw Error("INTAKE_WRITER_BUSY: \u5199\u5165\u8005\u6B63\u5728\u64CD\u4F5C\uFF0C\u672A\u5165\u961F\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
44287
+ const reaperPath = path23 + ".reap";
43759
44288
  let reaper;
43760
44289
  try {
43761
44290
  reaper = openSync10(reaperPath, "wx");
@@ -43764,9 +44293,9 @@ function withSpoolWriteLock(stateDir2, operation) {
43764
44293
  throw Error("INTAKE_WRITER_BUSY: \u5199\u9501\u6062\u590D\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
43765
44294
  }
43766
44295
  try {
43767
- if (lockOwnerState(path22) === "dead") unlinkSync5(path22);
44296
+ if (lockOwnerState(path23) === "dead") unlinkSync5(path23);
43768
44297
  try {
43769
- fd = openSync10(path22, "wx");
44298
+ fd = openSync10(path23, "wx");
43770
44299
  } catch (error2) {
43771
44300
  if (error2?.code !== "EEXIST") throw error2;
43772
44301
  throw Error("INTAKE_WRITER_BUSY: \u5199\u5165\u8005\u6B63\u5728\u64CD\u4F5C\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
@@ -43781,7 +44310,7 @@ function withSpoolWriteLock(stateDir2, operation) {
43781
44310
  return operation();
43782
44311
  } finally {
43783
44312
  closeSync10(fd);
43784
- unlinkSync5(path22);
44313
+ unlinkSync5(path23);
43785
44314
  }
43786
44315
  }
43787
44316
  function* spoolLines(fd, offset, maxEntries) {
@@ -43812,10 +44341,10 @@ function* spoolLines(fd, offset, maxEntries) {
43812
44341
  position += bytes2;
43813
44342
  }
43814
44343
  }
43815
- function readCursor(stateDir2, path22, identity, size2) {
44344
+ function readCursor(stateDir2, path23, identity, size2) {
43816
44345
  try {
43817
- if (fileBytes(path22) > 4096) throw Error("INTAKE_CURSOR_INVALID_SIZE");
43818
- const cursor = JSON.parse(readFileSync32(path22, "utf8"));
44346
+ if (fileBytes(path23) > 4096) throw Error("INTAKE_CURSOR_INVALID_SIZE");
44347
+ const cursor = JSON.parse(readFileSync32(path23, "utf8"));
43819
44348
  if (cursor.dev === identity.dev && cursor.ino === identity.ino && cursor.birthtimeNs === identity.birthtimeNs && Number.isSafeInteger(cursor.offset) && cursor.offset >= 0 && cursor.offset <= size2) return cursor.offset;
43820
44349
  intakeDiagnostic(stateDir2, "cursor.replay", { reason: cursor.dev !== identity.dev || cursor.ino !== identity.ino || cursor.birthtimeNs !== identity.birthtimeNs ? "identity_mismatch" : "invalid_offset", batchBytes: size2, identity });
43821
44350
  } catch (error) {
@@ -43854,21 +44383,21 @@ function drainIntakeSpool(stateDir2, store, maxEntries = 50) {
43854
44383
  } : {},
43855
44384
  elapsedMs: Math.round(performance.now() - started)
43856
44385
  });
43857
- const path22 = spoolPath(stateDir2);
44386
+ const path23 = spoolPath(stateDir2);
43858
44387
  const processing = processingPath(stateDir2);
43859
44388
  const cursorPath = processing + ".cursor";
43860
44389
  try {
43861
44390
  withSpoolWriteLock(stateDir2, () => {
43862
44391
  if (!existsSync19(processing)) {
43863
- if (!existsSync19(path22) || statSync4(path22).size === 0) return;
44392
+ if (!existsSync19(path23) || statSync4(path23).size === 0) return;
43864
44393
  try {
43865
44394
  unlinkSync5(cursorPath);
43866
44395
  } catch (error) {
43867
44396
  if (error?.code !== "ENOENT") throw error;
43868
44397
  }
43869
- renameSync10(path22, processing);
44398
+ renameSync10(path23, processing);
43870
44399
  }
43871
- appendFileSync3(path22, "", "utf8");
44400
+ appendFileSync3(path23, "", "utf8");
43872
44401
  });
43873
44402
  if (!existsSync19(processing)) return 0;
43874
44403
  } catch (error) {
@@ -44121,6 +44650,8 @@ function createMemoryProviderRecovery(now2 = Date.now) {
44121
44650
  // src/bg/host.ts
44122
44651
  init_scope();
44123
44652
  init_import_backups();
44653
+ init_paths();
44654
+ init_embedding();
44124
44655
 
44125
44656
  // src/bg/sqlite-maintenance.ts
44126
44657
  import { fork } from "node:child_process";
@@ -44305,8 +44836,8 @@ function openPhysicalMaintenanceDatabase(file2, stateDir2) {
44305
44836
  }
44306
44837
 
44307
44838
  // src/mem7/sqlite-maintenance-worker.ts
44308
- function intakePendingForDatabase(path22) {
44309
- const spool = join48(dirname26(dirname26(path22)), "spool");
44839
+ function intakePendingForDatabase(path23) {
44840
+ const spool = join48(dirname26(dirname26(path23)), "spool");
44310
44841
  return ["intake.jsonl", "intake.processing.jsonl"].some((name) => {
44311
44842
  try {
44312
44843
  return statSync5(join48(spool, name)).size > 0;
@@ -44316,22 +44847,22 @@ function intakePendingForDatabase(path22) {
44316
44847
  }
44317
44848
  });
44318
44849
  }
44319
- var bytes = (path22) => {
44850
+ var bytes = (path23) => {
44320
44851
  try {
44321
- return statSync5(path22).size;
44852
+ return statSync5(path23).size;
44322
44853
  } catch (e) {
44323
44854
  if (e.code !== "ENOENT") throw e;
44324
44855
  return 0;
44325
44856
  }
44326
44857
  };
44327
- async function runSqlitePhysicalMaintenance(path22, options = {}) {
44858
+ async function runSqlitePhysicalMaintenance(path23, options = {}) {
44328
44859
  const minimum = options.minFreeBytes ?? 32 * 1024 * 1024, ratio = options.minFreeRatio ?? 0.05;
44329
44860
  if (!Number.isFinite(minimum) || minimum < 0 || !Number.isFinite(ratio) || ratio < 0 || ratio > 1) throw new Error("INVALID_SQLITE_RETENTION_THRESHOLD");
44330
- const before = bytes(path22) + bytes(path22 + "-wal"), started = performance.now();
44331
- const allowed = () => options.shouldRun?.() !== false && !intakePendingForDatabase(path22);
44332
- const db2 = openPhysicalMaintenanceDatabase(path22, options.stateDir);
44861
+ const before = bytes(path23) + bytes(path23 + "-wal"), started = performance.now();
44862
+ const allowed = () => options.shouldRun?.() !== false && !intakePendingForDatabase(path23);
44863
+ const db2 = openPhysicalMaintenanceDatabase(path23, options.stateDir);
44333
44864
  let mode = "bootstrap";
44334
- const report = (state) => ({ state, mode, reclaimedBytes: Math.max(0, before - bytes(path22) - bytes(path22 + "-wal")) });
44865
+ const report = (state) => ({ state, mode, reclaimedBytes: Math.max(0, before - bytes(path23) - bytes(path23 + "-wal")) });
44335
44866
  try {
44336
44867
  db2.exec("PRAGMA busy_timeout=0");
44337
44868
  mode = Number(db2.prepare("PRAGMA auto_vacuum").get().auto_vacuum) === 2 ? "incremental" : "bootstrap";
@@ -44341,10 +44872,10 @@ async function runSqlitePhysicalMaintenance(path22, options = {}) {
44341
44872
  const pageSize = Number(db2.prepare("PRAGMA page_size").get().page_size);
44342
44873
  const pages = Number(db2.prepare("PRAGMA page_count").get().page_count);
44343
44874
  const free = Number(db2.prepare("PRAGMA freelist_count").get().freelist_count);
44344
- const oversized = bytes(path22) > pages * pageSize + 1024 * 1024;
44875
+ const oversized = bytes(path23) > pages * pageSize + 1024 * 1024;
44345
44876
  if (!oversized && (free * pageSize < minimum || free / Math.max(1, pages) < ratio)) return report("idle");
44346
44877
  if (mode === "bootstrap" || oversized) {
44347
- const disk = statfsSync2(dirname26(path22));
44878
+ const disk = statfsSync2(dirname26(path23));
44348
44879
  if (disk.bavail * disk.bsize < (pages - free) * pageSize * 2 + 64 * 1024 * 1024) return report("deferred");
44349
44880
  if (!allowed()) return report("deferred");
44350
44881
  options.onPhase?.("vacuum");
@@ -44363,7 +44894,7 @@ async function runSqlitePhysicalMaintenance(path22, options = {}) {
44363
44894
  }
44364
44895
  const finalCheckpoint = db2.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get();
44365
44896
  const finalPages = Number(db2.prepare("PRAGMA page_count").get().page_count);
44366
- if (finalCheckpoint.busy || bytes(path22) > finalPages * pageSize + 1024 * 1024) return report("deferred");
44897
+ if (finalCheckpoint.busy || bytes(path23) > finalPages * pageSize + 1024 * 1024) return report("deferred");
44367
44898
  return report("complete");
44368
44899
  } catch (error) {
44369
44900
  if (/database is locked|SQLITE_BUSY|SQLITE_LOCKED/i.test(String(error))) return report("deferred");
@@ -44374,9 +44905,9 @@ async function runSqlitePhysicalMaintenance(path22, options = {}) {
44374
44905
  }
44375
44906
  if (process.argv.includes("--sqlite-checkpoint")) {
44376
44907
  const flag2 = process.argv.indexOf("--sqlite-checkpoint");
44377
- const path22 = process.argv[flag2 + 1], stateDir2 = process.argv[flag2 + 2];
44908
+ const path23 = process.argv[flag2 + 1], stateDir2 = process.argv[flag2 + 2];
44378
44909
  registerRuntimeWriter(stateDir2, "sqlite-checkpoint");
44379
- const db2 = openPhysicalMaintenanceDatabase(path22, stateDir2);
44910
+ const db2 = openPhysicalMaintenanceDatabase(path23, stateDir2);
44380
44911
  try {
44381
44912
  db2.exec("PRAGMA busy_timeout=15000");
44382
44913
  console.log("wal checkpoint " + JSON.stringify(db2.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get()));
@@ -44388,7 +44919,7 @@ if (process.argv.includes("--sqlite-checkpoint")) {
44388
44919
  }
44389
44920
  }
44390
44921
  if (process.argv.includes("--sqlite-maintenance")) {
44391
- const flag2 = process.argv.indexOf("--sqlite-maintenance"), path22 = resolve20(process.argv[flag2 + 1] ?? "");
44922
+ const flag2 = process.argv.indexOf("--sqlite-maintenance"), path23 = resolve20(process.argv[flag2 + 1] ?? "");
44392
44923
  if (!process.argv[flag2 + 1]) throw new Error("SQLITE_MAINTENANCE_PATH_REQUIRED");
44393
44924
  const config = process.argv[flag2 + 2] ? JSON.parse(process.argv[flag2 + 2]) : {};
44394
44925
  if (!config.stateDir) throw new Error("SQLITE_MAINTENANCE_STATE_DIR_REQUIRED");
@@ -44408,9 +44939,9 @@ if (process.argv.includes("--sqlite-maintenance")) {
44408
44939
  }
44409
44940
  if (cancel) process.kill(process.pid, 'SIGTERM')
44410
44941
  }, 100)
44411
- `, { eval: true, workerData: { path: path22, ownerPid: process.connected ? process.ppid : null } });
44942
+ `, { eval: true, workerData: { path: path23, ownerPid: process.connected ? process.ppid : null } });
44412
44943
  try {
44413
- console.log(JSON.stringify(await runSqlitePhysicalMaintenance(path22, {
44944
+ console.log(JSON.stringify(await runSqlitePhysicalMaintenance(path23, {
44414
44945
  ...config,
44415
44946
  onPhase: (phase) => {
44416
44947
  if (process.connected) process.send?.({ type: "sqliteMaintenancePhase", phase });
@@ -44452,9 +44983,9 @@ if (process.argv.includes("--validate-topics-import-live")) {
44452
44983
  }
44453
44984
 
44454
44985
  // src/bg/sqlite-maintenance.ts
44455
- var size = (path22) => {
44986
+ var size = (path23) => {
44456
44987
  try {
44457
- return statSync6(path22).size;
44988
+ return statSync6(path23).size;
44458
44989
  } catch (error) {
44459
44990
  if (error.code !== "ENOENT") throw error;
44460
44991
  return 0;
@@ -44469,7 +45000,7 @@ function live(pid) {
44469
45000
  }
44470
45001
  }
44471
45002
  function createSqliteMaintenance(stateDir2, options = {}) {
44472
- const path22 = join49(stateDir2, "mem7", "index", "mem7.db"), marker = join49(stateDir2, "mem7", "index", ".sqlite-maintenance.json");
45003
+ const path23 = join49(stateDir2, "mem7", "index", "mem7.db"), marker = join49(stateDir2, "mem7", "index", ".sqlite-maintenance.json");
44473
45004
  let child, completion, timer;
44474
45005
  let nextCheck = Date.now() + (options.firstRunDelayMs ?? 18e4), stopped = false;
44475
45006
  const idle = options.idleMs ?? 6e4;
@@ -44491,12 +45022,12 @@ function createSqliteMaintenance(stateDir2, options = {}) {
44491
45022
  const poll = () => {
44492
45023
  try {
44493
45024
  if (child) {
44494
- if (stopped || intakePendingForDatabase(path22) || options.shouldRun?.() === false) void interrupt();
45025
+ if (stopped || intakePendingForDatabase(path23) || options.shouldRun?.() === false) void interrupt();
44495
45026
  return;
44496
45027
  }
44497
45028
  if (stopped || Date.now() < nextCheck || options.shouldRun?.() === false) return;
44498
45029
  nextCheck = Date.now() + (options.checkIntervalMs ?? 6e4);
44499
- if (!existsSync23(path22) || intakePendingForDatabase(path22)) return;
45030
+ if (!existsSync23(path23) || intakePendingForDatabase(path23)) return;
44500
45031
  if (Date.now() - lastRequest < idle) return;
44501
45032
  if (existsSync23(marker)) {
44502
45033
  let previous;
@@ -44507,14 +45038,14 @@ function createSqliteMaintenance(stateDir2, options = {}) {
44507
45038
  if (Number.isSafeInteger(previous?.pid) && previous.pid > 0 && live(previous.pid) && Number.isSafeInteger(previous.startedAt) && Date.now() - previous.startedAt < 24e4) return;
44508
45039
  unlinkSync7(marker);
44509
45040
  }
44510
- const db2 = new DatabaseSync20(path22, { readOnly: true });
45041
+ const db2 = new DatabaseSync20(path23, { readOnly: true });
44511
45042
  let eligible = false;
44512
45043
  try {
44513
45044
  db2.exec("PRAGMA query_only=ON");
44514
45045
  const pageSize = Number(db2.prepare("PRAGMA page_size").get().page_size);
44515
45046
  const pages = Number(db2.prepare("PRAGMA page_count").get().page_count);
44516
45047
  const free = Number(db2.prepare("PRAGMA freelist_count").get().freelist_count);
44517
- eligible = free * pageSize >= (options.minFreeBytes ?? 32 * 1024 * 1024) && free / Math.max(1, pages) >= 0.05 || size(path22) > pages * pageSize + 1024 * 1024 || size(path22 + "-wal") >= 32 * 1024 * 1024;
45048
+ eligible = free * pageSize >= (options.minFreeBytes ?? 32 * 1024 * 1024) && free / Math.max(1, pages) >= 0.05 || size(path23) > pages * pageSize + 1024 * 1024 || size(path23 + "-wal") >= 32 * 1024 * 1024;
44518
45049
  } finally {
44519
45050
  db2.close();
44520
45051
  }
@@ -44527,7 +45058,7 @@ function createSqliteMaintenance(stateDir2, options = {}) {
44527
45058
  windowsHide: true,
44528
45059
  execArgv: entry.endsWith(".ts") ? ["--import", "tsx"] : []
44529
45060
  };
44530
- child = fork(entry, ["--sqlite-maintenance", path22, JSON.stringify({ stateDir: stateDir2, minFreeBytes: options.minFreeBytes })], launchOptions);
45061
+ child = fork(entry, ["--sqlite-maintenance", path23, JSON.stringify({ stateDir: stateDir2, minFreeBytes: options.minFreeBytes })], launchOptions);
44531
45062
  console.log("[bg-worker] SQLite physical reclaim started");
44532
45063
  const current2 = child;
44533
45064
  let output = "", errors2 = "";
@@ -44612,6 +45143,7 @@ function startMem7Worker(config, fallback, options = {}) {
44612
45143
  let lastPipelineMs = 0;
44613
45144
  let lastCheckpointMs = 0;
44614
45145
  let lastBackupCleanupMs = 0;
45146
+ let lastTopicChunksMs = Date.now() - 36e5 + 5 * 6e4;
44615
45147
  const scanSchedule = createOpportunityScanSchedule(now2());
44616
45148
  const completedScanScopes = /* @__PURE__ */ new Set();
44617
45149
  const scan = async (store, busy = false) => {
@@ -44654,10 +45186,10 @@ function startMem7Worker(config, fallback, options = {}) {
44654
45186
  }
44655
45187
  if (!options.isBusy?.() && Date.now() - lastCheckpointMs >= 6e5) {
44656
45188
  lastCheckpointMs = Date.now();
44657
- const dbPath = join52(mem7Root(stateDir2), "index", "mem7.db");
45189
+ const dbPath = join53(mem7Root(stateDir2), "index", "mem7.db");
44658
45190
  const built = fileURLToPath14(new URL("./sqlite-maintenance-worker.mjs", import.meta.url));
44659
45191
  const source = fileURLToPath14(new URL("../mem7/sqlite-maintenance-worker.ts", import.meta.url));
44660
- const entry = existsSync25(built) ? built : source;
45192
+ const entry = existsSync26(built) ? built : source;
44661
45193
  execFile2(process.execPath, [...entry.endsWith(".ts") ? ["--import", "tsx"] : [], entry, "--sqlite-checkpoint", dbPath, stateDir2], { timeout: 18e4, windowsHide: true }, (error, stdout) => {
44662
45194
  if (error) console.warn(`[bg-worker] wal checkpoint \u8F85\u52A9\u8FDB\u7A0B\u5931\u8D25: ${error.message}`);
44663
45195
  else console.log(`[bg-worker] ${(stdout || "").trim()}`);
@@ -44671,12 +45203,12 @@ function startMem7Worker(config, fallback, options = {}) {
44671
45203
  const recoveredTurns = store.hostTurns.recoverInterrupted();
44672
45204
  if (recoveredTurns) console.log(`[bg-worker] abandoned host turns reconciled=${recoveredTurns}`);
44673
45205
  try {
44674
- const retention = await store.pruneTerminalJobData({ shouldRun: () => !stopping && !options.isBusy?.() && !intakePendingForDatabase(join52(mem7Root(stateDir2), "index", "mem7.db")) && !store.sources.scopes().some((scope) => store.sources.interpretationBatch(scope, 1).length > 0) });
45206
+ const retention = await store.pruneTerminalJobData({ shouldRun: () => !stopping && !options.isBusy?.() && !intakePendingForDatabase(join53(mem7Root(stateDir2), "index", "mem7.db")) && !store.sources.scopes().some((scope) => store.sources.interpretationBatch(scope, 1).length > 0) });
44675
45207
  if (retention.results || retention.payloads) console.log(`[bg-worker] job retention results=${retention.results} inputs=${retention.payloads} archived=${retention.archivedInputs} logicalBytes=${retention.bytesReclaimed}`);
44676
45208
  } catch (error) {
44677
45209
  console.warn(`[bg-worker] job retention deferred: ${error?.message ?? error}`);
44678
45210
  }
44679
- const backupCleanupAllowed = () => !stopping && !options.isBusy?.() && !intakePendingForDatabase(join52(mem7Root(stateDir2), "index", "mem7.db")) && !store.sources.scopes().some((scope) => store.sources.interpretationBatch(scope, 1).length > 0);
45211
+ const backupCleanupAllowed = () => !stopping && !options.isBusy?.() && !intakePendingForDatabase(join53(mem7Root(stateDir2), "index", "mem7.db")) && !store.sources.scopes().some((scope) => store.sources.interpretationBatch(scope, 1).length > 0);
44680
45212
  if (Date.now() - lastBackupCleanupMs >= 36e5 && backupCleanupAllowed()) {
44681
45213
  lastBackupCleanupMs = Date.now();
44682
45214
  try {
@@ -44686,6 +45218,28 @@ function startMem7Worker(config, fallback, options = {}) {
44686
45218
  console.warn(`[bg-worker] backup retention deferred: ${error?.message ?? error}`);
44687
45219
  }
44688
45220
  }
45221
+ if (Date.now() - lastTopicChunksMs >= 36e5 && backupCleanupAllowed()) {
45222
+ lastTopicChunksMs = Date.now();
45223
+ const workspace2 = String(config.get("workspace") ?? "");
45224
+ const topicsDir = workspace2 ? getAutoMemPath(workspace2) : "";
45225
+ const embedding = resolveWorkerEmbedding(config);
45226
+ if (topicsDir && embedding) void (async () => {
45227
+ try {
45228
+ const { importTopicChunks: importTopicChunks2 } = await Promise.resolve().then(() => (init_topics_chunks(), topics_chunks_exports));
45229
+ const report = await importTopicChunks2({
45230
+ stateDir: stateDir2,
45231
+ topicsDir,
45232
+ userId: mem7UserId((key5) => config.get(key5)),
45233
+ embed: (texts) => embedBatch(embedding, texts, { read: true }),
45234
+ concurrency: 2
45235
+ });
45236
+ if (report.failed) console.warn(`[bg-worker] topics chunks failed=${report.failed} errors=${report.errors.slice(0, 2).join(" | ")}`);
45237
+ else if (report.chunks || report.deleted) console.log(`[bg-worker] topics chunks files=${report.files} chunks=${report.chunks} deleted=${report.deleted}`);
45238
+ } catch (error) {
45239
+ console.warn(`[bg-worker] topics chunks deferred: ${error?.message ?? error}`);
45240
+ }
45241
+ })();
45242
+ }
44689
45243
  const cleanupMs = Math.round(performance.now() - started);
44690
45244
  if (cleanupMs >= 1e3) console.log(`[bg-worker] cleanup ${cleanupMs}ms`);
44691
45245
  const agentName = mem7AgentName((key5) => config.get(key5));
@@ -44693,7 +45247,7 @@ function startMem7Worker(config, fallback, options = {}) {
44693
45247
  let relationshipGraph;
44694
45248
  if (config.get("mem7.relationshipCognition") !== false) {
44695
45249
  if (options.relationshipGraphPath) {
44696
- if (existsSync25(options.relationshipGraphPath)) {
45250
+ if (existsSync26(options.relationshipGraphPath)) {
44697
45251
  try {
44698
45252
  relationshipGraph = workerGraph(options.relationshipGraphPath, store).graph;
44699
45253
  relationshipGraph.ensureFresh();
@@ -44781,7 +45335,7 @@ function startMem7Worker(config, fallback, options = {}) {
44781
45335
  if (!store || !stateDir2 || config.get("mem7.enabled") !== true) return;
44782
45336
  try {
44783
45337
  if (physicalMaintenance?.running()) {
44784
- if (!intakePendingForDatabase(join52(mem7Root(stateDir2), "index", "mem7.db"))) return;
45338
+ if (!intakePendingForDatabase(join53(mem7Root(stateDir2), "index", "mem7.db"))) return;
44785
45339
  await physicalMaintenance.interrupt();
44786
45340
  }
44787
45341
  const applied = drainIntakeSpool(stateDir2, store, 50);
@@ -44789,10 +45343,10 @@ function startMem7Worker(config, fallback, options = {}) {
44789
45343
  await physicalMaintenance?.interrupt();
44790
45344
  void pipeline.tick();
44791
45345
  }
44792
- if (!activeStore && !options.isBusy?.() && !intakePendingForDatabase(join52(mem7Root(stateDir2), "index", "mem7.db"))) {
45346
+ if (!activeStore && !options.isBusy?.() && !intakePendingForDatabase(join53(mem7Root(stateDir2), "index", "mem7.db"))) {
44793
45347
  const retired = store.retireGraphPlanAuditsBatch();
44794
45348
  if (retired.plans) console.log(`[bg-worker] unused graph audits retired=${retired.plans}`);
44795
- await store.pruneTerminalJobData({ shouldRun: () => !stopping && !options.isBusy?.() && !activeStore && !intakePendingForDatabase(join52(mem7Root(stateDir2), "index", "mem7.db")) });
45349
+ await store.pruneTerminalJobData({ shouldRun: () => !stopping && !options.isBusy?.() && !activeStore && !intakePendingForDatabase(join53(mem7Root(stateDir2), "index", "mem7.db")) });
44796
45350
  }
44797
45351
  } catch (error) {
44798
45352
  console.warn(`[bg-worker] intake service failed: ${error?.message ?? error}`);
@@ -45188,7 +45742,7 @@ var relationshipGraphPath = graphFlag >= 0 ? resolve25(args[graphFlag + 1]) : vo
45188
45742
  var mainFlag = args.indexOf("--main-model");
45189
45743
  var mainModelRef = mainFlag >= 0 ? args[mainFlag + 1] : void 0;
45190
45744
  var workspaceFlag = args.indexOf("--workspace");
45191
- if (!configPath || !existsSync32(configPath)) {
45745
+ if (!configPath || !existsSync34(configPath)) {
45192
45746
  console.error("[bg-worker] usage: node dist/bg-worker.mjs --engine-config <path>");
45193
45747
  process.exit(1);
45194
45748
  }