engine7 7.1.151 → 7.1.152

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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({
@@ -1647,14 +1647,14 @@ var init_live = __esm({
1647
1647
  }
1648
1648
  /** 把改动写回 config 文件对应段(找不到文件路径则只内存生效)。返回是否真的落盘。 */
1649
1649
  async persistToFile(dotPath, val, atomic2 = false) {
1650
- const fs23 = await import("node:fs");
1650
+ const fs24 = await import("node:fs");
1651
1651
  const cfgPath = this.current?._configFilePath;
1652
- if (!cfgPath || !fs23.existsSync(cfgPath)) {
1652
+ if (!cfgPath || !fs24.existsSync(cfgPath)) {
1653
1653
  console.warn(`[liveConfig] set: no config file path, in-memory only (${dotPath})`);
1654
1654
  return false;
1655
1655
  }
1656
1656
  try {
1657
- const raw = JSON.parse(fs23.readFileSync(cfgPath, "utf-8"));
1657
+ const raw = JSON.parse(fs24.readFileSync(cfgPath, "utf-8"));
1658
1658
  const keys = dotPath.split(".");
1659
1659
  let o = raw;
1660
1660
  for (let i = 0; i < keys.length - 1; i++) {
@@ -1664,7 +1664,7 @@ var init_live = __esm({
1664
1664
  o[keys[keys.length - 1]] = val;
1665
1665
  if (atomic2) {
1666
1666
  writeConfigAtomic(cfgPath, raw);
1667
- } else fs23.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
1667
+ } else fs24.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
1668
1668
  const lastKey = keys[keys.length - 1].toLowerCase();
1669
1669
  const looksSecret = /(^|[-_.])(key|token|secret|passwd|password|passphrase|authorization|auth|cred)([-_.]|$)/.test(lastKey);
1670
1670
  const shown = val !== null && typeof val === "object" ? "{\u2026}" : looksSecret ? "{\u2026}" : JSON.stringify(val);
@@ -2461,7 +2461,7 @@ END;
2461
2461
  const memo = /* @__PURE__ */ new Map();
2462
2462
  const sourceRetained = (sourceId) => Boolean(this.db.prepare(`SELECT 1 FROM memory_sources
2463
2463
  WHERE scope_id=? AND source_id=? AND interpretation_status<>'deleted'`).get(scopeKey, sourceId));
2464
- const walk = (kind2, id2, version2) => {
2464
+ const walk2 = (kind2, id2, version2) => {
2465
2465
  checkMemoryReadBudget(visited.size);
2466
2466
  const key5 = basisKey(kind2, id2, version2);
2467
2467
  if (memo.has(key5)) return memo.get(key5);
@@ -2477,7 +2477,7 @@ END;
2477
2477
  if (ref.parentKind === "source") return sourceRetained(ref.parentId);
2478
2478
  if (ref.parentKind === "artifact") {
2479
2479
  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);
2480
+ return parents.length === 1 && walk2(parents[0].kind, ref.parentId, ref.parentVersion);
2481
2481
  }
2482
2482
  if (ref.parentKind === "entity") {
2483
2483
  const entity = this.db.prepare("SELECT canonical_name FROM entities WHERE scope_id=? AND entity_id=?").get(scopeKey, ref.parentId);
@@ -2497,7 +2497,7 @@ END;
2497
2497
  visited.delete(key5);
2498
2498
  }
2499
2499
  };
2500
- return walk(kind, id, version);
2500
+ return walk2(kind, id, version);
2501
2501
  }
2502
2502
  evidence(scope, kind, id, version, cutoff) {
2503
2503
  checkMemoryReadBudget();
@@ -2518,7 +2518,7 @@ END;
2518
2518
  });
2519
2519
  return true;
2520
2520
  };
2521
- const walk = (parentKind, parentId, parentVersion, ancestors) => {
2521
+ const walk2 = (parentKind, parentId, parentVersion, ancestors) => {
2522
2522
  checkMemoryReadBudget(ancestors.size);
2523
2523
  const key5 = basisKey(parentKind, parentId, parentVersion);
2524
2524
  if (ancestors.has(key5)) return false;
@@ -2545,7 +2545,7 @@ END;
2545
2545
  if (!addSource(ref.parentId, ref.parentVersion)) return false;
2546
2546
  } else if (ref.parentKind === "artifact") {
2547
2547
  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;
2548
+ if (parents.length !== 1 || !walk2(parents[0].kind, ref.parentId, ref.parentVersion, next)) return false;
2549
2549
  } else if (ref.parentKind === "scope" && ref.parentId.startsWith("valid-window:")) {
2550
2550
  const time = cutoff ? cutoff.time ?? this.time(cutoff.historyId) : void 0;
2551
2551
  try {
@@ -2571,7 +2571,7 @@ END;
2571
2571
  }
2572
2572
  return true;
2573
2573
  };
2574
- return walk(kind, id, version, /* @__PURE__ */ new Set()) && sources.size ? [...sources.values()] : null;
2574
+ return walk2(kind, id, version, /* @__PURE__ */ new Set()) && sources.size ? [...sources.values()] : null;
2575
2575
  }
2576
2576
  time(historyId) {
2577
2577
  return this.db.prepare("SELECT recorded_at FROM memory_knowledge_history WHERE history_id=?").get(historyId)?.recorded_at;
@@ -2675,8 +2675,9 @@ function invalidateDerivedDependencies(db2, event2) {
2675
2675
  }
2676
2676
  return invalidateChildren(db2, event2.scopeId, pending2, event2.kind);
2677
2677
  }
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);
2678
+ function invalidateScopeDependencies(db2, scope, parent, reason, options = {}) {
2679
+ 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);
2680
+ if (options.skipKinds?.size) children = children.filter((child) => !options.skipKinds.has(child.child_kind));
2680
2681
  invalidateChildren(db2, scope, children, reason);
2681
2682
  }
2682
2683
  function invalidateChildren(db2, scope, pending2, reason) {
@@ -2696,7 +2697,7 @@ function invalidateChildren(db2, scope, pending2, reason) {
2696
2697
  }
2697
2698
  const state = child.deleted ? "deleted" : "needs_revalidation";
2698
2699
  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);
2700
+ 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
2701
  result.push(child.child_id);
2701
2702
  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
2703
  }
@@ -3246,6 +3247,12 @@ function loadArrow() {
3246
3247
  }
3247
3248
  return arrowPromise;
3248
3249
  }
3250
+ function shortCjkQueryBigrams(text2) {
3251
+ const chars = (String(text2 ?? "").match(/[\u4e00-\u9fff]/g) ?? []).length;
3252
+ if (!chars || chars > 6) return null;
3253
+ const grams = [...new Set(cjkBigrams(text2))].slice(0, 8);
3254
+ return grams.length ? grams : null;
3255
+ }
3249
3256
  function buildSchemas(arrow) {
3250
3257
  const vecField = () => new arrow.Field("vector", new arrow.FixedSizeList(VECTOR_DIM, new arrow.Field("item", new arrow.Float32(), true)), true);
3251
3258
  const commonFields = () => [
@@ -3342,7 +3349,7 @@ function textColumnOf(kind) {
3342
3349
  return "fact";
3343
3350
  }
3344
3351
  }
3345
- var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3352
+ var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, BM25_TEXT_FIELDS, sqlLiteral, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
3346
3353
  var init_vector_store = __esm({
3347
3354
  "src/mem7/core/vector-store.ts"() {
3348
3355
  "use strict";
@@ -3373,6 +3380,14 @@ var init_vector_store = __esm({
3373
3380
  agent_case: ["task_intent_tokens", "approach_tokens"],
3374
3381
  agent_skill: ["description_tokens", "content_tokens"]
3375
3382
  };
3383
+ BM25_TEXT_FIELDS = {
3384
+ foresight: ["foresight", "evidence"],
3385
+ episode: ["episode"],
3386
+ atomic_fact: ["fact"],
3387
+ agent_case: ["task_intent", "approach"],
3388
+ agent_skill: ["description", "content"]
3389
+ };
3390
+ sqlLiteral = (value) => value.replace(/'/g, "''");
3376
3391
  RRF_K = 60;
3377
3392
  warnedFts = /* @__PURE__ */ new Set();
3378
3393
  warnedVecIdx = /* @__PURE__ */ new Set();
@@ -3970,6 +3985,28 @@ var init_vector_store = __esm({
3970
3985
  if (!cur || score > Number(cur._score ?? 0)) best.set(rid, r);
3971
3986
  }
3972
3987
  }
3988
+ const grams = shortCjkQueryBigrams(queryText);
3989
+ if (grams) {
3990
+ try {
3991
+ const textCols = BM25_TEXT_FIELDS[kind];
3992
+ const expr = textCols.map((col) => `(${grams.map((g) => `contains(${col}, '${sqlLiteral(g)}')`).join(" OR ")})`).join(" OR ");
3993
+ const where2 = compileFilter(opts.filter);
3994
+ const extra = await tbl.query().where(where2 ? `(${where2}) AND (${expr})` : expr).limit(topK * 3).toArray();
3995
+ const maxScore = [...best.values()].reduce((max, r) => Math.max(max, Number(r._score ?? 0)), 0);
3996
+ for (const r of extra) {
3997
+ const rid = String(r.id ?? "");
3998
+ if (!rid) continue;
3999
+ const text2 = textCols.map((col) => String(r[col] ?? "")).join(" ");
4000
+ const matched = grams.filter((gram) => text2.includes(gram)).length;
4001
+ if (!matched) continue;
4002
+ const score = maxScore + matched / grams.length;
4003
+ const cur = best.get(rid);
4004
+ if (cur) cur._score = Math.max(Number(cur._score ?? 0), score);
4005
+ else best.set(rid, { ...r, _score: score });
4006
+ }
4007
+ } catch {
4008
+ }
4009
+ }
3973
4010
  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
4011
  } catch (err) {
3975
4012
  const msg2 = String(err?.message ?? err);
@@ -4549,7 +4586,7 @@ import { createHash as createHash7 } from "node:crypto";
4549
4586
  function projectedSourceIdFromScopeId(id, originKey, sourceVersion) {
4550
4587
  return "src_" + digest([id, originKey, sourceVersion]);
4551
4588
  }
4552
- var SOURCE_SCHEMA, SOURCE_ALIAS_SCHEMA, digest, SourceStore;
4589
+ var RECEIVED_INVALIDATION_SKIP, SOURCE_SCHEMA, SOURCE_ALIAS_SCHEMA, digest, SourceStore;
4553
4590
  var init_source_store = __esm({
4554
4591
  "src/mem7/core/source-store.ts"() {
4555
4592
  "use strict";
@@ -4561,6 +4598,7 @@ var init_source_store = __esm({
4561
4598
  init_watermarks();
4562
4599
  init_interpretation_impact();
4563
4600
  init_conversation_text();
4601
+ RECEIVED_INVALIDATION_SKIP = /* @__PURE__ */ new Set(["foresight"]);
4564
4602
  SOURCE_SCHEMA = `
4565
4603
  CREATE TABLE memory_scopes (
4566
4604
  scope_id TEXT PRIMARY KEY, owner_id TEXT NOT NULL, app_id TEXT NOT NULL, project_id TEXT NOT NULL,
@@ -4742,8 +4780,8 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
4742
4780
  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
4781
  if (version !== Number(latest.version ?? 0) + 1) throw new Error("SOURCE_VERSION_CONFLICT: edits must follow the previous version");
4744
4782
  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");
4783
+ invalidateScopeDependencies(this.db, id, "sources", "source.received", { skipKinds: RECEIVED_INVALIDATION_SKIP });
4784
+ invalidateScopeDependencies(this.db, id, "context", "source.received", { skipKinds: RECEIVED_INVALIDATION_SKIP });
4747
4785
  const seq = Number(this.db.prepare("SELECT source_seq FROM memory_scopes WHERE scope_id=?").get(id).source_seq);
4748
4786
  const sourceId = projectedSourceIdFromScopeId(id, input.originKey, version);
4749
4787
  const receiptId = "rcpt_" + digest([id, sourceId]);
@@ -5308,8 +5346,8 @@ function purgeRecoveryEvidence(db2, graph) {
5308
5346
  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
5347
  if (!blocked) continue;
5310
5348
  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);
5349
+ const sha2 = value.content?.sha256;
5350
+ if (sha2) db2.prepare("DELETE FROM e7_recovery_objects WHERE sha256=?").run(sha2);
5313
5351
  }
5314
5352
  item.state = "DELETED_BLOCKED";
5315
5353
  item.reason = "latest_deletion";
@@ -5435,8 +5473,8 @@ var init_recovery_deletion = __esm({
5435
5473
  const { owners, parents } = this.links(table, row);
5436
5474
  for (const parent of parents) for (const owner of owners) this.edge(parent, owner);
5437
5475
  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;
5476
+ const medium = text(row, "medium"), path23 = text(row, "path"), physicalId = text(row, "physical_id"), kind = text(row, "kind");
5477
+ 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
5478
  if (identity) {
5441
5479
  const rows = this.artifactPaths.get(identity) ?? [];
5442
5480
  rows.push(row);
@@ -5444,8 +5482,8 @@ var init_recovery_deletion = __esm({
5444
5482
  }
5445
5483
  }
5446
5484
  }
5447
- blocksArtifactPath(kind, path22) {
5448
- const rows = this.artifactPaths.get(kind + ":" + path22);
5485
+ blocksArtifactPath(kind, path23) {
5486
+ const rows = this.artifactPaths.get(kind + ":" + path23);
5449
5487
  return rows?.some((row) => this.blocks("memory_artifact_publications", row));
5450
5488
  }
5451
5489
  blocks(table, row) {
@@ -6472,7 +6510,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6472
6510
  };
6473
6511
  const candidates = [];
6474
6512
  const duplicateIds = /* @__PURE__ */ new Set();
6475
- const inside = (path22) => path22 && !isAbsolute(path22) && path22 !== ".." && !path22.startsWith(`..${sep}`);
6513
+ const inside = (path23) => path23 && !isAbsolute(path23) && path23 !== ".." && !path23.startsWith(`..${sep}`);
6476
6514
  for (const relativePath of input.files) {
6477
6515
  const logical = resolve3(root, relativePath);
6478
6516
  let canonical3;
@@ -6486,10 +6524,10 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6486
6524
  gap("projection_path_unverified");
6487
6525
  continue;
6488
6526
  }
6489
- const path22 = relative(root, canonical3).replace(/\\/g, "/");
6527
+ const path23 = relative(root, canonical3).replace(/\\/g, "/");
6490
6528
  const user = `users/${input.scope.ownerId}/`;
6491
6529
  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;
6530
+ 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
6531
  if (!kind) {
6494
6532
  gap("projection_kind_or_owner_unverified");
6495
6533
  continue;
@@ -6526,9 +6564,9 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6526
6564
  continue;
6527
6565
  }
6528
6566
  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);
6567
+ const target = join6(store.mem7RootPath(), path23);
6530
6568
  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)) {
6569
+ 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
6570
  gap("projection_mapping_conflict");
6533
6571
  continue;
6534
6572
  }
@@ -6544,7 +6582,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6544
6582
  candidates.push({
6545
6583
  file: canonical3,
6546
6584
  fileHash,
6547
- relativePath: path22,
6585
+ relativePath: path23,
6548
6586
  id: match[1],
6549
6587
  kind,
6550
6588
  parent,
@@ -7827,7 +7865,7 @@ async function drainJobs(store, handlers2, options = {}) {
7827
7865
  let done = 0;
7828
7866
  for (let attempted = 0; attempted < (options.maxJobs ?? 200) && Date.now() < deadline; attempted++) {
7829
7867
  if (options.shouldRun && !options.shouldRun()) break;
7830
- const job = store.claimJobs(1, { leaseMs, kinds: options.kinds, scopeId: options.scopeId })[0];
7868
+ const job = store.claimJobs(1, { leaseMs, kinds: options.kinds, scopeId: options.scopeId, staleOnly: options.staleOnly })[0];
7831
7869
  if (!job) break;
7832
7870
  options.onAttempt?.();
7833
7871
  let heartbeatError;
@@ -8369,11 +8407,11 @@ function applySocialInterpretation(store, scope, result, captured, requestKey, r
8369
8407
  const covers = (evidence, mention) => evidence.sourceId === mention.sourceId && evidence.start <= mention.start && evidence.end >= mention.end;
8370
8408
  const entitySnapshot = store.entities.list(scope);
8371
8409
  for (const mention of ordered) {
8372
- const path22 = mentionPath(mention);
8410
+ const path23 = mentionPath(mention);
8373
8411
  const source = store.sources.get(scope, mention.sourceId);
8374
8412
  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");
8413
+ 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");
8414
+ 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
8415
  }
8378
8416
  if (!mention.actual || isAssistantDraft(source)) {
8379
8417
  ids.set(mention.key, null);
@@ -8383,12 +8421,12 @@ function applySocialInterpretation(store, scope, result, captured, requestKey, r
8383
8421
  if (!["existing", "new", "unresolved"].includes(mention.disposition)) throw new Error("INVALID_SOCIAL_DISPOSITION");
8384
8422
  if (!["name", "description", "reference"].includes(mention.mentionKind)) throw new Error("INVALID_SOCIAL_MENTION_KIND");
8385
8423
  let entity = null;
8386
- const basisRefs = references(mention.basisSourceIds, source.sourceId, `${path22}.basisSourceIds`);
8424
+ const basisRefs = references(mention.basisSourceIds, source.sourceId, `${path23}.basisSourceIds`);
8387
8425
  let identityEntity = null;
8388
8426
  if (mention.identity !== void 0) {
8389
8427
  const identity = mention.identity;
8390
8428
  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`);
8429
+ const evidenceSource = literalSpan(identity.evidence, `${path23}.identity.evidence`);
8392
8430
  if (evidenceSource.sourceId !== source.sourceId && !captured.contextRefs?.some((ref) => ref.sourceId === evidenceSource.sourceId)) {
8393
8431
  throw new Error("INVALID_SOCIAL_IDENTITY_EVIDENCE");
8394
8432
  }
@@ -8400,7 +8438,7 @@ function applySocialInterpretation(store, scope, result, captured, requestKey, r
8400
8438
  anchorEntityId = store.entities.speaker(scope, source.sourceId)?.entityId;
8401
8439
  } else {
8402
8440
  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);
8441
+ if (!supplied || supplied.sourceId !== source.sourceId || supplied.key === mention.key) fail2("INVALID_SOCIAL_IDENTITY_ANCHOR", `${path23}.identity.anchor`, anchorCorrection);
8404
8442
  const anchor = supplied;
8405
8443
  if (!covers(identity.evidence, mention) || mention.mentionKind !== "reference" && !covers(identity.evidence, anchor)) throw new Error("INVALID_SOCIAL_IDENTITY_EVIDENCE");
8406
8444
  anchorEntityId = ids.get(supplied.key);
@@ -8409,25 +8447,25 @@ function applySocialInterpretation(store, scope, result, captured, requestKey, r
8409
8447
  } else {
8410
8448
  const anchor = identity.anchor;
8411
8449
  const authorAnchor = anchor && "author" in anchor;
8412
- const anchorSource = authorAnchor ? store.sources.get(scope, anchor.sourceId) : literalSpan(anchor, `${path22}.identity.anchor`);
8450
+ const anchorSource = authorAnchor ? store.sources.get(scope, anchor.sourceId) : literalSpan(anchor, `${path23}.identity.anchor`);
8413
8451
  if (!anchorSource || !captured.sourceRefs.some((ref) => ref.sourceId === anchorSource.sourceId && ref.sourceVersion === anchorSource.sourceVersion)) {
8414
- fail2("INVALID_SOCIAL_IDENTITY_ANCHOR", `${path22}.identity.anchor`, anchorCorrection);
8452
+ fail2("INVALID_SOCIAL_IDENTITY_ANCHOR", `${path23}.identity.anchor`, anchorCorrection);
8415
8453
  }
8416
8454
  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
8455
  const author = ["host_user", "client_reported_user", "assistant"].includes(anchorSource.originClass) ? store.entities.speaker(scope, anchor.sourceId) : null;
8418
8456
  const selected = mention.entityId ? store.entities.resolve(scope, mention.entityId) : null;
8419
8457
  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);
8458
+ if (!author || "author" in anchor && anchor.author !== true) fail2("INVALID_SOCIAL_IDENTITY_ANCHOR", `${path23}.identity.anchor`, anchorCorrection);
8421
8459
  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`);
8460
+ 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
8461
  }
8424
8462
  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");
8463
+ 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
8464
  }
8427
8465
  anchorEntityId = author.entityId;
8428
8466
  anchorBasis = references([anchor.sourceId], source.sourceId);
8429
8467
  } 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);
8468
+ 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
8469
  if (evidenceSource.sourceId === source.sourceId ? !covers(identity.evidence, mention) : !covers(identity.evidence, anchor)) {
8432
8470
  throw new Error("INVALID_SOCIAL_IDENTITY_EVIDENCE");
8433
8471
  }
@@ -8505,8 +8543,8 @@ function applySocialInterpretation(store, scope, result, captured, requestKey, r
8505
8543
  if (entity) entityBasis.set(entity.entityId, distinctRefs([...entityBasis.get(entity.entityId) || [], ...grounds]));
8506
8544
  }
8507
8545
  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");
8546
+ const path23 = `relationships[${ordinal}]`;
8547
+ 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
8548
  if (!relation.actual) {
8511
8549
  applied.relationships.push({ index: ordinal, label: relation.label, state: "ignored" });
8512
8550
  continue;
@@ -8515,7 +8553,7 @@ function applySocialInterpretation(store, scope, result, captured, requestKey, r
8515
8553
  if (!source || !captured.sourceIds.includes(source.sourceId)) {
8516
8554
  fail2(
8517
8555
  "SOCIAL_SOURCE_NOT_PROVIDED",
8518
- `${path22}.sourceId=${relation.sourceId}`,
8556
+ `${path23}.sourceId=${relation.sourceId}`,
8519
8557
  `${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
8558
  );
8521
8559
  }
@@ -8525,20 +8563,20 @@ function applySocialInterpretation(store, scope, result, captured, requestKey, r
8525
8563
  }
8526
8564
  for (const field of ["validFrom", "validTo"]) {
8527
8565
  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");
8566
+ 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
8567
  if (value !== null) {
8530
8568
  try {
8531
8569
  if (typeof value !== "string") throw new Error("INVALID_TIME");
8532
8570
  instant(value);
8533
8571
  } 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");
8572
+ 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
8573
  }
8536
8574
  }
8537
8575
  }
8538
8576
  if (relation.validFrom !== null && relation.validFrom !== void 0) {
8539
8577
  const quote2 = relation.validFromQuote;
8540
8578
  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");
8579
+ 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
8580
  }
8543
8581
  }
8544
8582
  const speaker = store.entities.speaker(scope, source.sourceId);
@@ -8559,7 +8597,7 @@ function applySocialInterpretation(store, scope, result, captured, requestKey, r
8559
8597
  if (["attitude", "feeling"].includes(relation.contentKind) && relation.direction !== "directed") throw new Error("INVALID_SOCIAL_RECIPROCITY");
8560
8598
  if (relation.attribution !== void 0 && !["direct", "reported"].includes(relation.attribution)) throw new Error("INVALID_SOCIAL_ATTRIBUTION");
8561
8599
  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");
8600
+ 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
8601
  }
8564
8602
  if (relation.realm !== void 0 && !["real", "roleplay", "hypothetical"].includes(relation.realm)) throw new Error("INVALID_SOCIAL_REALM");
8565
8603
  if (relation.sensitivity !== void 0 && !["normal", "sensitive"].includes(relation.sensitivity)) throw new Error("INVALID_SOCIAL_SENSITIVITY");
@@ -8584,7 +8622,7 @@ function applySocialInterpretation(store, scope, result, captured, requestKey, r
8584
8622
  basisRefs: distinctRefs([
8585
8623
  ...metadata2?.basisRefs || [],
8586
8624
  ...store.socialSources.identityRefs(scope, source.sourceId),
8587
- ...references(relation.basisSourceIds, source.sourceId, `${path22}.basisSourceIds`),
8625
+ ...references(relation.basisSourceIds, source.sourceId, `${path23}.basisSourceIds`),
8588
8626
  ...[relation.perspective, relation.subject, relation.object].flatMap((ref) => [...mentionBasis.get(ref) || [], ...entityBasis.get(resolve26(ref)) || []])
8589
8627
  ])
8590
8628
  };
@@ -8962,11 +9000,11 @@ function checkSeal(value) {
8962
9000
  const { digest: actual, ...body } = value ?? {};
8963
9001
  if (actual !== digest3(canonical(body))) throw new Error("MANIFEST_DIGEST_MISMATCH");
8964
9002
  }
8965
- function safeRelative(path22) {
8966
- return typeof path22 === "string" && !!path22 && !isAbsolute2(path22) && !/[:\\\x00-\x1f]/.test(path22) && path22.split("/").every((p) => p && p !== "." && p !== "..");
9003
+ function safeRelative(path23) {
9004
+ return typeof path23 === "string" && !!path23 && !isAbsolute2(path23) && !/[:\\\x00-\x1f]/.test(path23) && path23.split("/").every((p) => p && p !== "." && p !== "..");
8967
9005
  }
8968
- function unlinked(path22) {
8969
- let cursor = resolve4(path22);
9006
+ function unlinked(path23) {
9007
+ let cursor = resolve4(path23);
8970
9008
  for (; ; ) {
8971
9009
  try {
8972
9010
  if (lstatSync6(cursor).isSymbolicLink()) throw new Error("SYMLINK_PATH");
@@ -8974,7 +9012,7 @@ function unlinked(path22) {
8974
9012
  if (e.code !== "ENOENT") throw e;
8975
9013
  }
8976
9014
  const parent = dirname5(cursor);
8977
- if (parent === cursor) return resolve4(path22);
9015
+ if (parent === cursor) return resolve4(path23);
8978
9016
  cursor = parent;
8979
9017
  }
8980
9018
  }
@@ -8987,8 +9025,8 @@ function disjoint(...paths) {
8987
9025
  for (let i = 0; i < p.length; i++) for (let j = i + 1; j < p.length; j++)
8988
9026
  if (contains(p[i], p[j]) || contains(p[j], p[i])) throw new Error("PATH_OVERLAP");
8989
9027
  }
8990
- function readJson(path22) {
8991
- return JSON.parse(readFileSync7(unlinked(path22), "utf8").replace(/^\uFEFF/, ""));
9028
+ function readJson(path23) {
9029
+ return JSON.parse(readFileSync7(unlinked(path23), "utf8").replace(/^\uFEFF/, ""));
8992
9030
  }
8993
9031
  function rawBytes(snapshot, record) {
8994
9032
  if (!/^[a-f0-9]{64}$/.test(record.sha256)) throw new Error("INVALID_OBJECT_REFERENCE");
@@ -9541,9 +9579,9 @@ function normalize3(input) {
9541
9579
  if (!input || !/^[a-f0-9]{64}$/.test(input.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
9542
9580
  return Object.freeze({ binding: normalizeBinding(input.binding), schemaHash: input.schemaHash });
9543
9581
  }
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()))
9582
+ function directory(path23) {
9583
+ const info = lstatSync7(path23);
9584
+ if (!info.isDirectory() || info.isSymbolicLink() || realpathSync4(path23) !== resolve5(path23) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
9547
9585
  throw new Error("REPLICATION_REGISTRATION_INVALID");
9548
9586
  }
9549
9587
  function readRuntimeReplicationRegistration(stateDir2, component, key5) {
@@ -10212,6 +10250,7 @@ __export(topics_history_exports, {
10212
10250
  topicMatchesYear: () => topicMatchesYear,
10213
10251
  topicQueryYear: () => topicQueryYear,
10214
10252
  topicsHistoryNeedsFallback: () => topicsHistoryNeedsFallback,
10253
+ topicsHistoryRefsCurrent: () => topicsHistoryRefsCurrent,
10215
10254
  topicsHistoryRoot: () => topicsHistoryRoot,
10216
10255
  topicsScope: () => topicsScope
10217
10256
  });
@@ -10231,10 +10270,10 @@ function topicMatchesYear(dates, year) {
10231
10270
  function topicsHistoryRoot(b) {
10232
10271
  return unlinked(join13(b.stateDir, "topics-history", key3(b)));
10233
10272
  }
10234
- function parseTopicHistoryPath(path22) {
10235
- if (!path22.startsWith("topics-history://") || path22.length > 1e4) throw new Error("INVALID_HISTORY_REFERENCE");
10273
+ function parseTopicHistoryPath(path23) {
10274
+ if (!path23.startsWith("topics-history://") || path23.length > 1e4) throw new Error("INVALID_HISTORY_REFERENCE");
10236
10275
  try {
10237
- return JSON.parse(Buffer.from(path22.slice(17), "base64url").toString("utf8"));
10276
+ return JSON.parse(Buffer.from(path23.slice(17), "base64url").toString("utf8"));
10238
10277
  } catch {
10239
10278
  throw new Error("INVALID_HISTORY_REFERENCE");
10240
10279
  }
@@ -10261,19 +10300,19 @@ async function topicHistoryReadRevision(b, refs) {
10261
10300
  paths.add(join13(resolve7(b.topicsDir), ref.sourcePath));
10262
10301
  paths.add(join13(root, "forgotten", `${digest3(ref.sourcePath)}.json`));
10263
10302
  }
10264
- const stats = await Promise.all([...paths].sort().map(async (path22) => {
10303
+ const stats = await Promise.all([...paths].sort().map(async (path23) => {
10265
10304
  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)];
10305
+ const stat3 = await fs2.lstat(path23, { bigint: true });
10306
+ return [path23, ...[stat3.dev, stat3.ino, stat3.mode, stat3.size, stat3.mtimeNs, stat3.ctimeNs].map(String)];
10268
10307
  } catch (error) {
10269
- if (error.code === "ENOENT") return [path22, null];
10308
+ if (error.code === "ENOENT") return [path23, null];
10270
10309
  throw error;
10271
10310
  }
10272
10311
  }));
10273
10312
  return JSON.stringify([current2, stats]);
10274
10313
  }
10275
- function forgotten(b, path22) {
10276
- return existsSync6(unlinked(join13(topicsHistoryRoot(b), "forgotten", `${digest3(path22)}.json`)));
10314
+ function forgotten(b, path23) {
10315
+ return existsSync6(unlinked(join13(topicsHistoryRoot(b), "forgotten", `${digest3(path23)}.json`)));
10277
10316
  }
10278
10317
  function openIndex(b, version) {
10279
10318
  if (!b.stateDir || !b.topicsDir) return null;
@@ -10311,6 +10350,27 @@ function hasTopicsHistory(b) {
10311
10350
  db2.close();
10312
10351
  return true;
10313
10352
  }
10353
+ function topicsHistoryRefsCurrent(b) {
10354
+ const db2 = openIndex(b);
10355
+ if (!db2) return false;
10356
+ try {
10357
+ const expected = rootKey(b);
10358
+ const meta = db2.prepare("SELECT value FROM metadata WHERE key='rootKey'").get();
10359
+ if (meta) return meta.value === expected;
10360
+ 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();
10361
+ return rows.every((row) => {
10362
+ try {
10363
+ return JSON.parse(row.ref).rootKey === expected;
10364
+ } catch {
10365
+ return false;
10366
+ }
10367
+ });
10368
+ } catch {
10369
+ return false;
10370
+ } finally {
10371
+ db2.close();
10372
+ }
10373
+ }
10314
10374
  async function topicsHistoryNeedsFallback(b) {
10315
10375
  const cached = fallbackChecks.get(key3(b));
10316
10376
  if (cached && cached.expiresAt > Date.now()) return cached.value;
@@ -10326,16 +10386,16 @@ async function walkTopicsNeedsFallback(b) {
10326
10386
  const visit = async (rel) => {
10327
10387
  const entries = await fs2.readdir(unlinked(join13(b.topicsDir, rel)), { withFileTypes: true });
10328
10388
  for (const entry of entries) {
10329
- const path22 = rel ? `${rel}/${entry.name}` : entry.name;
10389
+ const path23 = rel ? `${rel}/${entry.name}` : entry.name;
10330
10390
  if (entry.isSymbolicLink()) continue;
10331
10391
  if (entry.isDirectory()) {
10332
- if (await visit(path22)) return true;
10392
+ if (await visit(path23)) return true;
10333
10393
  continue;
10334
10394
  }
10335
- if (!entry.isFile() || !/\.md$/i.test(path22) || path22.toUpperCase() === "MEMORY.MD" || forgotten(b, path22)) continue;
10336
- const source = sources.get(path22);
10395
+ if (!entry.isFile() || !/\.md$/i.test(path23) || path23.toUpperCase() === "MEMORY.MD" || forgotten(b, path23)) continue;
10396
+ const source = sources.get(path23);
10337
10397
  if (!source) return true;
10338
- const stat3 = await fs2.stat(unlinked(join13(b.topicsDir, path22)));
10398
+ const stat3 = await fs2.stat(unlinked(join13(b.topicsDir, path23)));
10339
10399
  if (stat3.size !== source.bytes || stat3.mtimeMs !== source.mtime_ms) return true;
10340
10400
  }
10341
10401
  return false;
@@ -10462,6 +10522,7 @@ async function publishTopicsIndex(bundle, cleaned, b) {
10462
10522
  CREATE VIRTUAL TABLE documents USING fts5(source_path UNINDEXED,original_hash UNINDEXED,terms);
10463
10523
  CREATE VIRTUAL TABLE search USING fts5(id UNINDEXED,terms);`);
10464
10524
  db2.prepare("INSERT INTO metadata VALUES(?,?)").run("binding", canonical({ scope: topicsScope(b), root: resolve7(b.topicsDir) }));
10525
+ db2.prepare("INSERT INTO metadata VALUES(?,?)").run("rootKey", rootKey(b));
10465
10526
  const sourceInsert = db2.prepare("INSERT INTO sources VALUES(?,?,?,?)");
10466
10527
  for (const record of snapshot.manifest.records) sourceInsert.run(record.path, record.sha256, record.bytes, record.mtimeMs);
10467
10528
  const insert = db2.prepare("INSERT INTO entries VALUES(?,?,?,?,?,?,?,?,?)"), search = db2.prepare("INSERT INTO search VALUES(?,?)");
@@ -11248,7 +11309,7 @@ function readRelationshipContext(store, scope, request, clock = () => (/* @__PUR
11248
11309
  for (const entity of (request.graphEntityIds ?? []).flatMap((id) => resolve26(id) || []).filter((entity2) => !selected.has(entity2.entityId)).slice(0, 4)) {
11249
11310
  if (!context.people.some((person) => person.entityId === entity.entityId)) add("people", entity);
11250
11311
  }
11251
- for (const path22 of (request.graphPaths ?? []).slice(0, 40)) add("paths", path22, [path22.source, path22.target]);
11312
+ for (const path23 of (request.graphPaths ?? []).slice(0, 40)) add("paths", path23, [path23.source, path23.target]);
11252
11313
  const linkedIds = store.entities.list(scope, cutoff).filter((entity) => selected.has(resolve26(entity.entityId)?.entityId || entity.entityId)).map((entity) => entity.entityId);
11253
11314
  const views = recall.entitySources(linkedIds, maxRecords);
11254
11315
  const sourceIds = [.../* @__PURE__ */ new Set([
@@ -13321,23 +13382,23 @@ var init_facts = __esm({
13321
13382
  if ((exception || proposal.changeKind === "exception") && (!exception || schedule.frequency !== "once")) throw new Error("OCCURRENCE_EXCEPTION_REQUIRED");
13322
13383
  }
13323
13384
  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}`);
13385
+ const path23 = `evidence[${index}]`;
13386
+ 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
13387
  const source = this.db.prepare(`SELECT text,role,origin_class,interpretation_status FROM memory_sources s WHERE scope_id=? AND source_id=?
13327
13388
  AND NOT EXISTS (SELECT 1 FROM memory_sources newer WHERE newer.scope_id=s.scope_id
13328
13389
  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`);
13390
+ 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`);
13391
+ 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
13392
  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
13393
  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`);
13394
+ 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
13395
  }
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`);
13396
+ 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
13397
  const relationValue = proposal.value;
13337
13398
  if (proposal.predicate === "relation.open" && relationValue?.attribution === "reported" && (proposal.claimKind !== "reported_statement" || !hasReportedAttribution(source.text, relationValue, this.entities.sourceMentions(scope, evidence.sourceId)))) {
13338
13399
  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
13400
  }
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`);
13401
+ 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
13402
  if (proposal.claimKind !== "inference") {
13342
13403
  if (proposal.claimKind === "user_statement" && (source.role !== "user" || !["host_user", "client_reported_user"].includes(source.origin_class))) throw roleMismatch();
13343
13404
  if (proposal.claimKind === "tool_observation" && (source.role !== "tool" || source.origin_class !== "tool_observation")) throw roleMismatch();
@@ -13697,7 +13758,7 @@ function contentHash(text2) {
13697
13758
  function mem7Root(stateDir2) {
13698
13759
  return join14(stateDir2, "mem7");
13699
13760
  }
13700
- var STALE_ARTIFACT_FORCE_MS, SCHEMA, AGENT_SCHEMA, Mem7Store;
13761
+ var STALE_ARTIFACT_FORCE_MS, STARVATION_GRACE_MS, SCHEMA, AGENT_SCHEMA, Mem7Store;
13701
13762
  var init_store = __esm({
13702
13763
  "src/mem7/core/store.ts"() {
13703
13764
  "use strict";
@@ -13735,6 +13796,7 @@ var init_store = __esm({
13735
13796
  init_job_retention();
13736
13797
  init_retire_graph_audits();
13737
13798
  STALE_ARTIFACT_FORCE_MS = 2 * 36e5;
13799
+ STARVATION_GRACE_MS = 36e5;
13738
13800
  SCHEMA = `
13739
13801
  CREATE TABLE IF NOT EXISTS memcells (
13740
13802
  id TEXT PRIMARY KEY,
@@ -14328,13 +14390,13 @@ CREATE TABLE IF NOT EXISTS cluster_members (
14328
14390
  const version = expectedVersion ?? this.dependencies.version(scope, kind, id);
14329
14391
  this.dependencies.assertCurrent(scope, kind, id, version);
14330
14392
  const digest7 = createHash20("sha256").update(content.trim()).digest("hex");
14331
- const path22 = relative3(this.root, file2).replace(/\\/g, "/");
14393
+ const path23 = relative3(this.root, file2).replace(/\\/g, "/");
14332
14394
  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");
14395
+ if (previous?.version === version && (previous.digest !== digest7 || previous.path !== path23)) throw new Error("PROJECTION_PUBLICATION_VERSION_CONFLICT");
14334
14396
  this.db.prepare(`INSERT INTO memory_projection_entries VALUES (?,?,?,?,?,?)
14335
14397
  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() });
14398
+ WHERE excluded.version>=memory_projection_entries.version`).run(scopeId(scope), kind, id, path23, version, digest7);
14399
+ this.artifacts.publish(scope, { ...body, kind, id, version, medium: "markdown", path: path23, markdown: content.trim() });
14338
14400
  });
14339
14401
  }
14340
14402
  projectionMatches(scope, kind, id, file2, content) {
@@ -14531,8 +14593,8 @@ CREATE TABLE IF NOT EXISTS cluster_members (
14531
14593
  };
14532
14594
  }
14533
14595
  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);
14596
+ const path23 = relative3(this.root, file2).replace(/\\/g, "/");
14597
+ const mappings = this.db.prepare("SELECT scope_id FROM memory_projection_entries WHERE kind=? AND entry_id=? AND path=?").all(kind, id, path23);
14536
14598
  if (mappings.length) {
14537
14599
  if (mappings.length !== 1) return false;
14538
14600
  const scope = this.sources.scope(mappings[0].scope_id);
@@ -14825,7 +14887,7 @@ ${e.outcome}
14825
14887
  return this.transaction(() => {
14826
14888
  const kindFilter = options.kinds ? ` AND kind IN (${options.kinds.map(() => "?").join(",")})` : "";
14827
14889
  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"}
14890
+ 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
14891
  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
14892
  AND ((status='pending' AND next_run_at<=?)
14831
14893
  OR (status='running' AND COALESCE(lease_until,0)<=?))${kindFilter}${scopeFilter}
@@ -14845,40 +14907,48 @@ ${e.outcome}
14845
14907
  -- Cognition rebuilds its read set at claim time; delayed old work must not fence fresh judgments.
14846
14908
  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
14909
  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
- });
14910
+ 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)`;
14911
+ const select = (starved2) => {
14912
+ const sql = `${base}${starved2 ? " AND status='pending' AND next_run_at<=?" : ""}
14913
+ ORDER BY priority,next_run_at,id LIMIT ?`;
14914
+ 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];
14915
+ return this.db.prepare(sql).all(...args2);
14916
+ };
14917
+ const claim = (rows) => {
14918
+ const claimedScopes = /* @__PURE__ */ new Set();
14919
+ return rows.flatMap((row) => {
14920
+ if (!this.jobProvenance.prepareForClaim(row.id, now2)) return [];
14921
+ const updated = this.db.prepare("SELECT * FROM ome_jobs WHERE id=?").get(row.id);
14922
+ if (updated.scope_id !== row.scope_id && updated.scope_id) {
14923
+ const conflict = this.db.prepare(`SELECT 1 FROM ome_jobs j WHERE j.scope_id=? AND j.id<>?
14924
+ AND (j.status='running' AND j.lease_until>? OR ? LIKE 'resource:%' AND j.id<? AND j.status IN ('pending','running')
14925
+ 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);
14926
+ if (conflict) return [];
14927
+ }
14928
+ return [updated];
14929
+ }).filter((row) => {
14930
+ if (!row.scope_id) return true;
14931
+ if (claimedScopes.has(row.scope_id)) return false;
14932
+ claimedScopes.add(row.scope_id);
14933
+ return true;
14934
+ }).map((row) => {
14935
+ const leaseToken = randomUUID10();
14936
+ this.db.prepare("UPDATE ome_jobs SET status='running',lease_token=?,lease_until=? WHERE id=?").run(leaseToken, now2 + leaseMs, row.id);
14937
+ return {
14938
+ id: row.id,
14939
+ kind: row.kind,
14940
+ payload: JSON.parse(row.payload),
14941
+ attempts: row.attempts,
14942
+ leaseToken,
14943
+ inputVersion: row.input_version,
14944
+ scopeId: row.scope_id ?? void 0,
14945
+ result: row.result_json === null ? void 0 : JSON.parse(row.result_json)
14946
+ };
14947
+ });
14948
+ };
14949
+ if (options.staleOnly) return claim(select(true));
14950
+ const starved = claim(select(true));
14951
+ return starved.length ? starved : claim(select(false));
14882
14952
  });
14883
14953
  }
14884
14954
  /** Compatibility entry point: only expired leases can be recovered. */
@@ -15319,19 +15389,19 @@ import { dirname as dirname7, join as join15, resolve as resolve8 } from "node:p
15319
15389
  import { createHash as createHash21, randomUUID as randomUUID11 } from "node:crypto";
15320
15390
  function assertPath(root, rel) {
15321
15391
  if (!safeRel(rel)) throw Error("TRAVEL_UNSAFE_PATH");
15322
- let path22 = root;
15392
+ let path23 = root;
15323
15393
  for (const part of rel.split("/")) {
15324
- path22 = join15(path22, part);
15394
+ path23 = join15(path23, part);
15325
15395
  try {
15326
- if (lstatSync9(path22).isSymbolicLink()) throw Error("TRAVEL_UNSAFE_PATH");
15396
+ if (lstatSync9(path23).isSymbolicLink()) throw Error("TRAVEL_UNSAFE_PATH");
15327
15397
  } catch (e) {
15328
15398
  if (e.code !== "ENOENT") throw e;
15329
15399
  }
15330
15400
  }
15331
- return path22;
15401
+ return path23;
15332
15402
  }
15333
- function atomic(path22, body, exclusive = false) {
15334
- const temp = path22 + "." + randomUUID11() + ".tmp";
15403
+ function atomic(path23, body, exclusive = false) {
15404
+ const temp = path23 + "." + randomUUID11() + ".tmp";
15335
15405
  let fd;
15336
15406
  try {
15337
15407
  fd = openSync7(temp, "wx", 384);
@@ -15339,8 +15409,8 @@ function atomic(path22, body, exclusive = false) {
15339
15409
  fsyncSync6(fd);
15340
15410
  closeSync7(fd);
15341
15411
  fd = void 0;
15342
- if (exclusive) linkSync(temp, path22);
15343
- else renameSync6(temp, path22);
15412
+ if (exclusive) linkSync(temp, path23);
15413
+ else renameSync6(temp, path23);
15344
15414
  } finally {
15345
15415
  if (fd !== void 0) closeSync7(fd);
15346
15416
  rmSync(temp, { force: true });
@@ -15352,16 +15422,16 @@ function read(root) {
15352
15422
  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
15423
  return value;
15354
15424
  }
15355
- function matches(path22, sha) {
15356
- if (!existsSync8(path22)) return false;
15357
- const fd = openSync7(path22, "r"), digest7 = createHash21("sha256"), buffer = Buffer.alloc(1048576);
15425
+ function matches(path23, sha2) {
15426
+ if (!existsSync8(path23)) return false;
15427
+ const fd = openSync7(path23, "r"), digest7 = createHash21("sha256"), buffer = Buffer.alloc(1048576);
15358
15428
  try {
15359
15429
  for (; ; ) {
15360
15430
  const n = readSync2(fd, buffer, 0, buffer.length, null);
15361
15431
  if (!n) break;
15362
15432
  digest7.update(buffer.subarray(0, n));
15363
15433
  }
15364
- return digest7.digest("hex") === sha;
15434
+ return digest7.digest("hex") === sha2;
15365
15435
  } finally {
15366
15436
  closeSync7(fd);
15367
15437
  }
@@ -15469,10 +15539,10 @@ function isCorruption(error) {
15469
15539
  if (code === 11 || code === 26) return true;
15470
15540
  return /database disk image is malformed|file is not a database/i.test(String(error?.message ?? error));
15471
15541
  }
15472
- function healthyDatabase(path22) {
15542
+ function healthyDatabase(path23) {
15473
15543
  let db2;
15474
15544
  try {
15475
- db2 = new DatabaseSync9(path22);
15545
+ db2 = new DatabaseSync9(path23);
15476
15546
  const check = db2.prepare("PRAGMA quick_check").get();
15477
15547
  return check?.quick_check === "ok";
15478
15548
  } catch {
@@ -15894,10 +15964,10 @@ var init_atomic_facts = __esm({
15894
15964
  import { existsSync as existsSync10, readFileSync as readFileSync16, writeFileSync as writeFileSync10, mkdirSync as mkdirSync12, renameSync as renameSync8 } from "node:fs";
15895
15965
  import { join as join19, dirname as dirname10 } from "node:path";
15896
15966
  function readStatusDoc(root, sid) {
15897
- const path22 = docPath(root, sid);
15898
- if (!existsSync10(path22)) return null;
15967
+ const path23 = docPath(root, sid);
15968
+ if (!existsSync10(path23)) return null;
15899
15969
  try {
15900
- const parsed = JSON.parse(readFileSync16(path22, "utf-8"));
15970
+ const parsed = JSON.parse(readFileSync16(path23, "utf-8"));
15901
15971
  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
15972
  return parsed;
15903
15973
  } catch {
@@ -15975,11 +16045,11 @@ Merge into the status document per the system contract. Return only the JSON obj
15975
16045
  }
15976
16046
  }
15977
16047
  function writeDoc(root, sid, file2) {
15978
- const path22 = docPath(root, sid);
15979
- mkdirSync12(dirname10(path22), { recursive: true });
15980
- const tmp = path22 + ".tmp";
16048
+ const path23 = docPath(root, sid);
16049
+ mkdirSync12(dirname10(path23), { recursive: true });
16050
+ const tmp = path23 + ".tmp";
15981
16051
  writeFileSync10(tmp, JSON.stringify(file2), "utf-8");
15982
- renameSync8(tmp, path22);
16052
+ renameSync8(tmp, path23);
15983
16053
  }
15984
16054
  var MERGE_MIN_INTERVAL_SEQ, MERGE_FAIL_COOLDOWN_MS, dirPath, docPath, MERGE_SYSTEM;
15985
16055
  var init_status_doc = __esm({
@@ -16987,9 +17057,9 @@ function snapshotFiles(store, request) {
16987
17057
  return { path: relative4(root, file2).replace(/\\/g, "/"), digest: digest7 };
16988
17058
  }).sort((a, b) => a.path.localeCompare(b.path));
16989
17059
  }
16990
- function ownFilePublication(store, request, path22, version) {
17060
+ function ownFilePublication(store, request, path23, version) {
16991
17061
  if (request.kind !== "skills" && request.kind !== "profile") return false;
16992
- const file2 = join25(store.mem7RootPath(), path22);
17062
+ const file2 = join25(store.mem7RootPath(), path23);
16993
17063
  let text2;
16994
17064
  try {
16995
17065
  text2 = readFileSync22(file2, "utf8");
@@ -17019,9 +17089,9 @@ function assertArtifactFileInputs(store, inputs, publicationVersion) {
17019
17089
  const current2 = currentInput(store, input.request);
17020
17090
  const oldFiles = new Map(input.files.map((file2) => [file2.path, file2.digest]));
17021
17091
  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;
17092
+ for (const path23 of /* @__PURE__ */ new Set([...oldFiles.keys(), ...newFiles.keys()])) {
17093
+ if (oldFiles.get(path23) === newFiles.get(path23)) continue;
17094
+ if (publicationVersion !== void 0 && ownFilePublication(store, input.request, path23, publicationVersion)) continue;
17025
17095
  throw new SupersededJobError("ARTIFACT_FILE_INPUT_CHANGED");
17026
17096
  }
17027
17097
  const expected = new Map(input.entries.map((entry) => [entry.id, entry.digest]));
@@ -18381,6 +18451,12 @@ async function drainMem7Pipeline(args2) {
18381
18451
  maxJobs,
18382
18452
  afterJob: () => afterBackgroundJob("boundary")
18383
18453
  }));
18454
+ await phase("extraction-urgent", () => drainJobs(store, handlers2, {
18455
+ kinds: memoryKinds,
18456
+ maxJobs: Math.min(maxJobs, 20),
18457
+ budgetMs: 6e4,
18458
+ staleOnly: true
18459
+ }));
18384
18460
  for (const scope of store.sources.scopes()) await interpretPending(scope, args2.interpretationBatches ?? 20);
18385
18461
  for (const scope of store.sources.scopes()) {
18386
18462
  await phase("social-interpretation", () => drainSocialInterpretations({
@@ -25305,7 +25381,7 @@ function listForesightMds(dir) {
25305
25381
  }
25306
25382
  function findForesightFiles(everosRoot) {
25307
25383
  const files = [];
25308
- const walk = (dir, depth) => {
25384
+ const walk2 = (dir, depth) => {
25309
25385
  if (depth > 4) return;
25310
25386
  let entries;
25311
25387
  try {
@@ -25319,12 +25395,12 @@ function findForesightFiles(everosRoot) {
25319
25395
  if (e.name === ".foresights") {
25320
25396
  files.push(...listForesightMds(p));
25321
25397
  } else if (!e.name.startsWith(".") && e.name !== "__pycache__") {
25322
- walk(p, depth + 1);
25398
+ walk2(p, depth + 1);
25323
25399
  }
25324
25400
  }
25325
25401
  }
25326
25402
  };
25327
- walk(everosRoot, 0);
25403
+ walk2(everosRoot, 0);
25328
25404
  return files;
25329
25405
  }
25330
25406
  function opportunityScheduledTime(now2, concrete) {
@@ -26456,8 +26532,10 @@ async function executeOneHook(hook, hookEvent, hookName, hookInput, toolUseID, s
26456
26532
  hookEvent,
26457
26533
  durationMs: durationMs2
26458
26534
  });
26535
+ const output = syncOutput.hookSpecificOutput;
26459
26536
  return {
26460
26537
  ...processed,
26538
+ ...hook.id === "skill-gate-prompt" && output?.hookEventName === "UserPromptSubmit" && output.selectSkill === true ? { selectSkill: true } : {},
26461
26539
  outcome: processed.blockingError ? "blocking" : "success",
26462
26540
  hook
26463
26541
  };
@@ -26559,6 +26637,7 @@ function aggregateResults(results) {
26559
26637
  if (result.permissionBehavior) {
26560
26638
  aggregated.permissionBehavior = result.permissionBehavior;
26561
26639
  }
26640
+ if (result.selectSkill) aggregated.selectSkill = true;
26562
26641
  if (result.additionalContext) {
26563
26642
  aggregated.additionalContexts.push(result.additionalContext);
26564
26643
  }
@@ -29404,9 +29483,9 @@ function buildPlanningContext(calDb, workspace2, memory) {
29404
29483
  function captureScanPlanningContext(workspace2, memory, calDb) {
29405
29484
  const read3 = () => {
29406
29485
  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 });
29486
+ const path23 = join32(workspace2, ".calendar", "calendar.db");
29487
+ if (!existsSync13(path23)) return buildPlanningContext(null, workspace2, memory);
29488
+ const db2 = new DatabaseSync13(path23, { readOnly: true });
29410
29489
  try {
29411
29490
  return buildPlanningContext(db2, workspace2, memory);
29412
29491
  } finally {
@@ -31826,9 +31905,9 @@ function isAutoMemPath(absolutePath, workspace2) {
31826
31905
  return normalizedPath.startsWith(getAutoMemPath(workspace2));
31827
31906
  }
31828
31907
  async function ensureMemoryDirExists(memoryDir) {
31829
- const fs23 = await import("node:fs");
31908
+ const fs24 = await import("node:fs");
31830
31909
  try {
31831
- await fs23.promises.mkdir(memoryDir, { recursive: true });
31910
+ await fs24.promises.mkdir(memoryDir, { recursive: true });
31832
31911
  } catch (e) {
31833
31912
  const code = e?.code;
31834
31913
  if (code !== "EEXIST") {
@@ -31864,8 +31943,8 @@ function physicalPath(target) {
31864
31943
  }
31865
31944
  return path7.resolve(fs7.realpathSync(ancestor), path7.relative(ancestor, target));
31866
31945
  }
31867
- function withoutRepeatedDirectories(relative11) {
31868
- const parts = relative11.split(path7.sep);
31946
+ function withoutRepeatedDirectories(relative12) {
31947
+ const parts = relative12.split(path7.sep);
31869
31948
  while (parts.length > 1 && parts[0].toLowerCase() === AUTO_MEM_DIRNAME) parts.shift();
31870
31949
  return parts.filter((part, index) => index === parts.length - 1 || index === 0 || part.toLowerCase() !== parts[index - 1].toLowerCase()).join(path7.sep);
31871
31950
  }
@@ -31890,28 +31969,28 @@ function resolveFilePath(requested, context, writing = false) {
31890
31969
  if (!isWithin(root, resolved) || !isWithin(physicalPath(root), physicalPath(resolved))) {
31891
31970
  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
31971
  }
31893
- const relative11 = path7.relative(root, resolved);
31972
+ const relative12 = path7.relative(root, resolved);
31894
31973
  if (writing) {
31895
31974
  if (path7.basename(resolved).toUpperCase() === "MEMORY.MD") {
31896
31975
  const canonicalIndex = path7.join(root, "MEMORY.md");
31897
31976
  const indexNames = fs7.existsSync(root) ? fs7.readdirSync(root).filter((name) => name.toUpperCase() === "MEMORY.MD") : [];
31898
31977
  let sameIndex = false;
31899
- if (path7.dirname(relative11) === "." && indexNames.length === 1 && fs7.existsSync(resolved) && fs7.existsSync(canonicalIndex)) {
31978
+ if (path7.dirname(relative12) === "." && indexNames.length === 1 && fs7.existsSync(resolved) && fs7.existsSync(canonicalIndex)) {
31900
31979
  const requestedEntry = fs7.lstatSync(resolved);
31901
31980
  const canonicalEntry = fs7.lstatSync(canonicalIndex);
31902
31981
  sameIndex = requestedEntry.dev === canonicalEntry.dev && requestedEntry.ino === canonicalEntry.ino;
31903
31982
  }
31904
- if (relative11 !== "MEMORY.md" && !sameIndex || relative11 === "MEMORY.md" && indexNames.length > 0 && !fs7.existsSync(canonicalIndex)) {
31983
+ if (relative12 !== "MEMORY.md" && !sameIndex || relative12 === "MEMORY.md" && indexNames.length > 0 && !fs7.existsSync(canonicalIndex)) {
31905
31984
  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
31985
  }
31907
31986
  }
31908
31987
  if (!fs7.existsSync(resolved)) {
31909
- const parts = relative11.split(path7.sep);
31988
+ const parts = relative12.split(path7.sep);
31910
31989
  if (parts[0].toLowerCase() === AUTO_MEM_DIRNAME || parts.some((part, index) => index > 0 && index < parts.length - 1 && part.toLowerCase() === parts[index - 1].toLowerCase())) {
31911
31990
  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
31991
  }
31913
31992
  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);
31993
+ 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
31994
  if (existing.length > 0) {
31916
31995
  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
31996
  }
@@ -32464,8 +32543,8 @@ function notificationStateChange(route, queueStateDir) {
32464
32543
  function createNotificationStateReader() {
32465
32544
  const databases = /* @__PURE__ */ new Map();
32466
32545
  const checkers = /* @__PURE__ */ new Map();
32467
- const open3 = (path22) => {
32468
- const key5 = resolve13(path22);
32546
+ const open3 = (path23) => {
32547
+ const key5 = resolve13(path23);
32469
32548
  let db2 = databases.get(key5);
32470
32549
  if (!db2) {
32471
32550
  db2 = new DatabaseSync11(key5, { readOnly: true });
@@ -33637,11 +33716,11 @@ var init_execution_guard = __esm({
33637
33716
  // src/memory/proactive/relationship-snapshot.ts
33638
33717
  import { existsSync as existsSync17 } from "node:fs";
33639
33718
  import { DatabaseSync as DatabaseSync15 } from "node:sqlite";
33640
- function readRelationshipGraphSnapshot(path22) {
33641
- if (!path22 || !existsSync17(path22)) return void 0;
33719
+ function readRelationshipGraphSnapshot(path23) {
33720
+ if (!path23 || !existsSync17(path23)) return void 0;
33642
33721
  let db2;
33643
33722
  try {
33644
- db2 = new DatabaseSync15(path22, { readOnly: true });
33723
+ db2 = new DatabaseSync15(path23, { readOnly: true });
33645
33724
  db2.exec("BEGIN");
33646
33725
  const version = readSchemaVersion(db2);
33647
33726
  if (version?.component !== "proactive" || version.version !== PROACTIVE_SCHEMA_VERSION) return void 0;
@@ -34750,8 +34829,8 @@ import { cp, readdir, rm } from "node:fs/promises";
34750
34829
  import { basename as basename8, dirname as dirname24, join as join44, resolve as resolve16 } from "node:path";
34751
34830
  import { fileURLToPath as fileURLToPath12 } from "node:url";
34752
34831
  import { execFile } from "node:child_process";
34753
- function atomicJson(path22, value) {
34754
- const target = unlinked(path22), temp = unlinked(`${target}.${randomUUID18()}.tmp`);
34832
+ function atomicJson(path23, value) {
34833
+ const target = unlinked(path23), temp = unlinked(`${target}.${randomUUID18()}.tmp`);
34755
34834
  try {
34756
34835
  writeFileSync14(temp, JSON.stringify(seal(value)) + "\n", { flag: "wx" });
34757
34836
  renameSync11(temp, target);
@@ -34769,10 +34848,10 @@ function alive2(pid) {
34769
34848
  }
34770
34849
  }
34771
34850
  function importerActive(historyRoot2) {
34772
- const path22 = join44(historyRoot2, ".topics-import.lock");
34773
- if (!existsSync21(path22)) return false;
34851
+ const path23 = join44(historyRoot2, ".topics-import.lock");
34852
+ if (!existsSync21(path23)) return false;
34774
34853
  try {
34775
- return alive2(readJson(path22).pid);
34854
+ return alive2(readJson(path23).pid);
34776
34855
  } catch {
34777
34856
  return true;
34778
34857
  }
@@ -34780,13 +34859,13 @@ function importerActive(historyRoot2) {
34780
34859
  async function withTopicsImportLock(historyRoot2, action) {
34781
34860
  const root = unlinked(historyRoot2);
34782
34861
  mkdirSync20(root, { recursive: true });
34783
- const path22 = unlinked(join44(root, ".topics-import.lock")), token = randomUUID18();
34862
+ const path23 = unlinked(join44(root, ".topics-import.lock")), token = randomUUID18();
34784
34863
  const body = JSON.stringify({ pid: process.pid, token });
34785
34864
  try {
34786
- writeFileSync14(path22, body, { flag: "wx" });
34865
+ writeFileSync14(path23, body, { flag: "wx" });
34787
34866
  } catch (error) {
34788
34867
  if (error.code !== "EEXIST") throw error;
34789
- const original = readFileSync35(path22, "utf8");
34868
+ const original = readFileSync35(path23, "utf8");
34790
34869
  let owner;
34791
34870
  try {
34792
34871
  owner = JSON.parse(original);
@@ -34794,23 +34873,23 @@ async function withTopicsImportLock(historyRoot2, action) {
34794
34873
  throw new Error("TOPICS_IMPORT_BUSY: invalid lock");
34795
34874
  }
34796
34875
  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" });
34876
+ if (readFileSync35(path23, "utf8") !== original) throw new Error("TOPICS_IMPORT_BUSY");
34877
+ unlinkSync6(path23);
34878
+ writeFileSync14(path23, body, { flag: "wx" });
34800
34879
  }
34801
34880
  try {
34802
34881
  return await action();
34803
34882
  } finally {
34804
- if (existsSync21(path22) && readFileSync35(path22, "utf8") === body) unlinkSync6(path22);
34883
+ if (existsSync21(path23) && readFileSync35(path23, "utf8") === body) unlinkSync6(path23);
34805
34884
  }
34806
34885
  }
34807
34886
  function registryPath(stateDir2) {
34808
34887
  return join44(stateDir2, "mem7", ".topics-backup-roots.json");
34809
34888
  }
34810
34889
  function backupRoots(stateDir2) {
34811
- const path22 = registryPath(stateDir2);
34812
- if (!existsSync21(path22)) return [join44(stateDir2, "mem7")];
34813
- const value = readJson(path22);
34890
+ const path23 = registryPath(stateDir2);
34891
+ if (!existsSync21(path23)) return [join44(stateDir2, "mem7")];
34892
+ const value = readJson(path23);
34814
34893
  checkSeal(value);
34815
34894
  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
34895
  return [.../* @__PURE__ */ new Set([join44(stateDir2, "mem7"), ...value.roots])];
@@ -34970,8 +35049,8 @@ async function adoptLegacyBackups(state, root, allowed) {
34970
35049
  const history = unlinked(join44(histories, entry.name));
34971
35050
  if (importerActive(history) || existsSync21(join44(history, pointerName))) continue;
34972
35051
  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))
35052
+ const marker = readJson(join44(history, "topics-import.json")), path23 = unlinked(marker.report?.backupPath ?? "");
35053
+ if (marker.report?.failed === 0 && Number.isFinite(Date.parse(marker.completedAt)) && dirname24(path23) === root && backupName.test(basename8(path23)) && existsSync21(path23))
34975
35054
  markers.push({ history, marker, hash: digest3(canonical(marker)) });
34976
35055
  } catch {
34977
35056
  }
@@ -35023,10 +35102,10 @@ async function legacyCompletionRoots(state) {
35023
35102
  try {
35024
35103
  const marker = readJson(join44(histories, entry.name, "topics-import.json"));
35025
35104
  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));
35105
+ const path23 = unlinked(marker.report.backupPath);
35106
+ if (!backupName.test(basename8(path23)) || !existsSync21(path23)) continue;
35107
+ disjoint(join44(state, "mem7", "index"), join44(state, "mem7", "users"), path23);
35108
+ roots.add(dirname24(path23));
35030
35109
  } catch {
35031
35110
  }
35032
35111
  }
@@ -35130,10 +35209,10 @@ async function validateLegacyTopicsBackup(state, directory2, history) {
35130
35209
  }
35131
35210
  const readTree = async (root) => {
35132
35211
  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);
35212
+ const path23 = unlinked(join46(root, entry.name));
35213
+ if (entry.isDirectory()) await readTree(path23);
35135
35214
  else if (entry.isFile()) {
35136
- const file2 = await open(path22, "r");
35215
+ const file2 = await open(path23, "r");
35137
35216
  try {
35138
35217
  const buffer = Buffer.allocUnsafe(64 * 1024);
35139
35218
  while ((await file2.read(buffer)).bytesRead > 0) {
@@ -35202,9 +35281,9 @@ async function validateCompletedTopicsImport(state, history) {
35202
35281
  db2.close();
35203
35282
  }
35204
35283
  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));
35284
+ const scan = async (path24) => {
35285
+ for (const entry of await readdir3(unlinked(path24), { withFileTypes: true })) {
35286
+ const file2 = unlinked(join47(path24, entry.name));
35208
35287
  if (entry.isDirectory()) await scan(file2);
35209
35288
  else if (entry.isFile() && entry.name.endsWith(".md")) {
35210
35289
  const text2 = await readFile(file2, "utf8");
@@ -35240,9 +35319,9 @@ async function validateCompletedTopicsImport(state, history) {
35240
35319
  }
35241
35320
  }
35242
35321
  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();
35322
+ const path23 = unlinked(join47(root, "index", "lancedb"));
35323
+ if (!existsSync22(path23)) throw new Error("TOPICS_IMPORT_LIVE_VECTORS_MISSING");
35324
+ const connection = await lance.connect(path23), vectorIds = /* @__PURE__ */ new Set();
35246
35325
  try {
35247
35326
  for (const name of await connection.tableNames()) {
35248
35327
  const table = await connection.openTable(name);
@@ -35274,6 +35353,185 @@ var init_validate_import_live = __esm({
35274
35353
  }
35275
35354
  });
35276
35355
 
35356
+ // src/memory/topics-chunks.ts
35357
+ var topics_chunks_exports = {};
35358
+ __export(topics_chunks_exports, {
35359
+ TOPICS_CHUNK_SESSION: () => TOPICS_CHUNK_SESSION,
35360
+ chunkTopicsText: () => chunkTopicsText,
35361
+ importTopicChunks: () => importTopicChunks
35362
+ });
35363
+ import { createHash as createHash36 } from "node:crypto";
35364
+ import { readdirSync as readdirSync7, readFileSync as readFileSync37, mkdirSync as mkdirSync21, writeFileSync as writeFileSync16, renameSync as renameSync12, existsSync as existsSync24 } from "node:fs";
35365
+ import { join as join50, relative as relative8 } from "node:path";
35366
+ function parseMd(text2) {
35367
+ const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text2);
35368
+ const meta = {};
35369
+ let body = text2;
35370
+ if (m) {
35371
+ for (const line of m[1].split(/\r?\n/)) {
35372
+ const i = line.indexOf(":");
35373
+ if (i > 0) meta[line.slice(0, i).trim()] = line.slice(i + 1).trim();
35374
+ }
35375
+ body = text2.slice(m[0].length).trim();
35376
+ }
35377
+ return { meta, body };
35378
+ }
35379
+ function chunkTopicsText(text2, rel) {
35380
+ const { meta, body } = parseMd(text2);
35381
+ const title = meta.name || rel.split("/").pop().replace(/\.md$/i, "");
35382
+ const header = `[${meta.type || "topics"}] ${title}${meta.date ? " " + meta.date : ""}
35383
+ \u6765\u6E90\uFF1A${rel}`;
35384
+ const paragraphs = body.split(/\n\s*\n/).map((x) => x.trim()).filter((x) => x.length >= CHUNK_MIN);
35385
+ const out = [];
35386
+ let ordinal = 0;
35387
+ for (const paragraph of paragraphs) {
35388
+ const pieces = [];
35389
+ if (paragraph.length <= CHUNK_MAX) pieces.push(paragraph);
35390
+ else {
35391
+ let rest = paragraph;
35392
+ while (rest.length > CHUNK_MAX) {
35393
+ let cut = rest.lastIndexOf("\u3002", CHUNK_MAX);
35394
+ if (cut < CHUNK_MIN) cut = CHUNK_MAX;
35395
+ pieces.push(rest.slice(0, cut + 1));
35396
+ rest = rest.slice(cut + 1).trim();
35397
+ }
35398
+ if (rest.length >= CHUNK_MIN) pieces.push(rest);
35399
+ }
35400
+ for (const piece of pieces) {
35401
+ if (out.length >= MAX_CHUNKS_PER_FILE) return out;
35402
+ out.push({ ordinal: ordinal++, text: `${header}
35403
+
35404
+ ${piece}` });
35405
+ }
35406
+ }
35407
+ return out;
35408
+ }
35409
+ function walk(root) {
35410
+ const out = [];
35411
+ const visit = (dir) => {
35412
+ for (const entry of readdirSync7(dir, { withFileTypes: true })) {
35413
+ if (entry.isSymbolicLink()) continue;
35414
+ const path23 = join50(dir, entry.name);
35415
+ if (entry.isDirectory()) visit(path23);
35416
+ else if (entry.isFile() && /\.md$/i.test(entry.name) && entry.name.toUpperCase() !== "MEMORY.MD") out.push(path23);
35417
+ }
35418
+ };
35419
+ visit(root);
35420
+ return out.sort();
35421
+ }
35422
+ async function importTopicChunks(options) {
35423
+ const { stateDir: stateDir2, topicsDir, userId, embed } = options;
35424
+ const manifestPath = join50(stateDir2, "mem7", "topics-chunks.json");
35425
+ mkdirSync21(join50(stateDir2, "mem7"), { recursive: true });
35426
+ let manifest = {};
35427
+ try {
35428
+ if (existsSync24(manifestPath)) manifest = JSON.parse(readFileSync37(manifestPath, "utf8"));
35429
+ } catch {
35430
+ manifest = {};
35431
+ }
35432
+ const store = new Mem7VectorStore(stateDir2);
35433
+ const table = await store.table("episode");
35434
+ const report = { files: 0, chunks: 0, embedded: 0, deleted: 0, failed: 0, errors: [] };
35435
+ const save = () => {
35436
+ const tmp = `${manifestPath}.${process.pid}.tmp`;
35437
+ writeFileSync16(tmp, JSON.stringify(manifest));
35438
+ renameSync12(tmp, manifestPath);
35439
+ };
35440
+ const files = walk(topicsDir);
35441
+ const seen = /* @__PURE__ */ new Set();
35442
+ const concurrency = Math.max(1, Math.min(8, options.concurrency ?? 4));
35443
+ for (const file2 of files) {
35444
+ const rel = relative8(topicsDir, file2);
35445
+ seen.add(rel);
35446
+ const bytes2 = readFileSync37(file2);
35447
+ const hash8 = sha(bytes2);
35448
+ const previous = manifest[rel];
35449
+ if (previous?.hash === hash8) continue;
35450
+ try {
35451
+ const parentId = `topic_chunk:${rel}`;
35452
+ await table.delete(`parent_id = '${sqlLiteral2(parentId)}'`);
35453
+ const text2 = bytes2.toString("utf8");
35454
+ const parsed = parseMd(text2);
35455
+ const title = parsed.meta.name || rel.split("/").pop().replace(/\.md$/i, "");
35456
+ const chunks = chunkTopicsText(text2, rel);
35457
+ const vectors = new Array(chunks.length);
35458
+ let next = 0;
35459
+ const worker2 = async () => {
35460
+ while (next < chunks.length) {
35461
+ const start = next;
35462
+ next = Math.min(chunks.length, next + 64);
35463
+ const batch = chunks.slice(start, next);
35464
+ const embedded = await embed(batch.map((chunk) => chunk.text));
35465
+ if (!Array.isArray(embedded) || embedded.length !== batch.length) throw new Error("EMBED_SHAPE_MISMATCH");
35466
+ for (let i = 0; i < batch.length; i++) vectors[start + i] = embedded[i];
35467
+ }
35468
+ };
35469
+ await Promise.all(Array.from({ length: concurrency }, worker2));
35470
+ const rows = chunks.map((chunk, index) => {
35471
+ const id = `tc_${sha(`${rel}:${chunk.ordinal}`).slice(0, 20)}`;
35472
+ return {
35473
+ id,
35474
+ entryId: id,
35475
+ ownerId: userId,
35476
+ ownerType: "user",
35477
+ appId: options.appId ?? "default",
35478
+ projectId: options.projectId ?? "default",
35479
+ sessionId: TOPICS_CHUNK_SESSION,
35480
+ timestamp: new Date(parsed.meta.date || Date.now()),
35481
+ parentId,
35482
+ text: chunk.text,
35483
+ subject: title,
35484
+ summary: chunk.text.split("\n")[0],
35485
+ contentSha256: sha(chunk.text),
35486
+ mdPath: "",
35487
+ vector: vectors[index]
35488
+ };
35489
+ });
35490
+ if (rows.length) await store.insert("episode", rows);
35491
+ manifest[rel] = { hash: hash8, ids: rows.map((row) => row.id), chunks: rows.length };
35492
+ save();
35493
+ report.files++;
35494
+ report.chunks += rows.length;
35495
+ report.embedded += rows.length;
35496
+ } catch (error) {
35497
+ report.failed++;
35498
+ report.errors.push(`${rel}: ${error instanceof Error ? error.message : String(error)}`);
35499
+ }
35500
+ }
35501
+ for (const rel of Object.keys(manifest)) {
35502
+ if (seen.has(rel)) continue;
35503
+ try {
35504
+ await table.delete(`parent_id = '${sqlLiteral2(`topic_chunk:${rel}`)}'`);
35505
+ delete manifest[rel];
35506
+ report.deleted++;
35507
+ } catch (error) {
35508
+ report.errors.push(`delete ${rel}: ${error instanceof Error ? error.message : String(error)}`);
35509
+ }
35510
+ }
35511
+ save();
35512
+ if ((report.chunks || report.deleted) && options.optimize !== false) {
35513
+ try {
35514
+ await table.optimize();
35515
+ } catch (error) {
35516
+ report.errors.push(`optimize: ${error instanceof Error ? error.message : String(error)}`);
35517
+ }
35518
+ }
35519
+ return report;
35520
+ }
35521
+ var TOPICS_CHUNK_SESSION, CHUNK_MIN, CHUNK_MAX, MAX_CHUNKS_PER_FILE, sha, sqlLiteral2;
35522
+ var init_topics_chunks = __esm({
35523
+ "src/memory/topics-chunks.ts"() {
35524
+ "use strict";
35525
+ init_vector_store();
35526
+ TOPICS_CHUNK_SESSION = "topics-chunks";
35527
+ CHUNK_MIN = 20;
35528
+ CHUNK_MAX = 800;
35529
+ MAX_CHUNKS_PER_FILE = 200;
35530
+ sha = (input) => createHash36("sha256").update(input).digest("hex");
35531
+ sqlLiteral2 = (value) => value.replace(/'/g, "''");
35532
+ }
35533
+ });
35534
+
35277
35535
  // src/mem7/core/context-render.ts
35278
35536
  function renderMemoryContext(context, userLabel = "\u5BF9\u65B9") {
35279
35537
  const lines = [`\uFF08\u5FEB\u7167 rev=${context.snapshot.factRevision}\uFF5C\u72B6\u6001=${context.freshness}\uFF5C\u622A\u81F3=${context.validAt}\uFF09`];
@@ -35499,7 +35757,7 @@ var init_memoryTypes = __esm({
35499
35757
  // src/memory/memdir/memoryScan.ts
35500
35758
  import fs11 from "node:fs/promises";
35501
35759
  import { StringDecoder } from "node:string_decoder";
35502
- import { basename as basename12, join as join50, sep as sep6 } from "node:path";
35760
+ import { basename as basename12, join as join51, sep as sep6 } from "node:path";
35503
35761
  function isArchivedPath(relativePath) {
35504
35762
  return relativePath.split(sep6).includes("archive");
35505
35763
  }
@@ -35574,7 +35832,7 @@ async function scanMemoryFiles(memoryDir, signal, maxFiles) {
35574
35832
  const entries = await fs11.readdir(memoryDir, { recursive: true });
35575
35833
  const files = entries.filter((f) => typeof f === "string" && f.endsWith(".md") && basename12(f) !== "MEMORY.md" && !isArchivedPath(f));
35576
35834
  const candidates = await mapFiles(files, 16, signal, async (filename) => {
35577
- const filePath = join50(memoryDir, filename);
35835
+ const filePath = join51(memoryDir, filename);
35578
35836
  return { filename, filePath, mtimeMs: (await fs11.stat(filePath)).mtimeMs };
35579
35837
  });
35580
35838
  const selected = candidates.sort((a, b) => b.mtimeMs - a.mtimeMs).slice(0, limit);
@@ -35702,7 +35960,7 @@ Return ONLY valid JSON: {"selected_memories": ["filename1.md", "filename2.md"]}`
35702
35960
  });
35703
35961
 
35704
35962
  // src/memory/topics-history/reader.ts
35705
- import { relative as relative8 } from "node:path";
35963
+ import { relative as relative9 } from "node:path";
35706
35964
  async function configuredFallback() {
35707
35965
  const raw = liveConfig.get("topics.recall") ?? {};
35708
35966
  let ref = String(raw.model ?? "");
@@ -35741,7 +35999,7 @@ async function readTopicsHistory(b, query, options = {}) {
35741
35999
  /* @__PURE__ */ new Set(),
35742
36000
  fallback.disableThinking
35743
36001
  );
35744
- selected = files.map((file2) => relative8(b.topicsDir, file2.path).replace(/\\/g, "/"));
36002
+ selected = files.map((file2) => relative9(b.topicsDir, file2.path).replace(/\\/g, "/"));
35745
36003
  }
35746
36004
  }
35747
36005
  } catch {
@@ -35779,11 +36037,11 @@ var init_reader = __esm({
35779
36037
 
35780
36038
  // src/memory/topics-history/import-mem7.ts
35781
36039
  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";
36040
+ import { existsSync as existsSync25, readFileSync as readFileSync38, renameSync as renameSync13, statSync as statSync7, writeFileSync as writeFileSync17 } from "node:fs";
36041
+ import { join as join52 } from "node:path";
35784
36042
  function topicsImported(binding) {
35785
36043
  if (!binding.stateDir) return false;
35786
- const marker = join51(topicsHistoryRoot(binding), "topics-import.json");
36044
+ const marker = join52(topicsHistoryRoot(binding), "topics-import.json");
35787
36045
  let size2 = 0, mtimeMs = 0, ino = 0;
35788
36046
  try {
35789
36047
  const s = statSync7(marker);
@@ -35800,19 +36058,19 @@ function topicsImported(binding) {
35800
36058
  try {
35801
36059
  const done = readJson(marker);
35802
36060
  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);
36061
+ const retired = join52(topicsHistoryRoot(binding), `topics-import.stale-rules-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
36062
+ renameSync13(marker, retired);
35805
36063
  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
36064
  } else if ((done.report?.total ?? 0) > 0) imported = true;
35807
36065
  else {
35808
- const retired = join51(topicsHistoryRoot(binding), `topics-import.degenerate-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
35809
- renameSync12(marker, retired);
36066
+ const retired = join52(topicsHistoryRoot(binding), `topics-import.degenerate-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
36067
+ renameSync13(marker, retired);
35810
36068
  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
36069
  }
35812
36070
  } catch {
35813
- const retired = join51(topicsHistoryRoot(binding), `topics-import.degenerate-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
36071
+ const retired = join52(topicsHistoryRoot(binding), `topics-import.degenerate-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.json`);
35814
36072
  try {
35815
- renameSync12(marker, retired);
36073
+ renameSync13(marker, retired);
35816
36074
  console.warn(`[topics-import] \u6E05\u5355\u635F\u574F\u4F5C\u5E9F\uFF08\u4E0B\u8F6E\u5BFC\u5165\u91CD\u5199\u81EA\u6108\uFF09\u2192 ${retired}`);
35817
36075
  } catch {
35818
36076
  }
@@ -35954,7 +36212,7 @@ __export(findRelevantMemoriesMem7_exports, {
35954
36212
  readMem7CurrentContext: () => readMem7CurrentContext,
35955
36213
  setRecallRerankOverride: () => setRecallRerankOverride
35956
36214
  });
35957
- import { createHash as createHash36 } from "node:crypto";
36215
+ import { createHash as createHash37 } from "node:crypto";
35958
36216
  function contextMemory(context, scope, userLabel, compact = false) {
35959
36217
  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
36218
  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 +36391,7 @@ async function readMem7CurrentContext(stateDir2, scope, request, budget, onReadS
36133
36391
  ...fact,
36134
36392
  basis: { ...fact.basis, validAt: void 0 }
36135
36393
  }));
36136
- const contentKey = createHash36("sha256").update(canonicalJson({
36394
+ const contentKey = createHash37("sha256").update(canonicalJson({
36137
36395
  ...material,
36138
36396
  currentFacts: withoutReadClock(material.currentFacts),
36139
36397
  historicalFacts: withoutReadClock(material.historicalFacts),
@@ -36701,9 +36959,9 @@ function enqueueRelationshipNotifications(store, scope, route, onlyId) {
36701
36959
  }
36702
36960
  async function appendGroupNoticeIntercept(workspace2, entry) {
36703
36961
  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 });
36962
+ const path23 = await import("node:path");
36963
+ const file2 = path23.join(workspace2, "memory", "group-routed-notices.md");
36964
+ await mkdir3(path23.dirname(file2), { recursive: true });
36707
36965
  await appendFile(file2, `## ${(/* @__PURE__ */ new Date()).toISOString()} ${entry.noticeId}
36708
36966
  - \u6765\u6E90\uFF1A${entry.scopeKey}
36709
36967
  - \u60F3\u6295\u5F80\uFF1A${entry.channel} \u7FA4 ${entry.target}
@@ -36973,7 +37231,7 @@ var init_prompt_history = __esm({
36973
37231
  // src/session/reader.ts
36974
37232
  import * as fs13 from "node:fs";
36975
37233
  import * as readline from "node:readline";
36976
- import { createHash as createHash37 } from "node:crypto";
37234
+ import { createHash as createHash38 } from "node:crypto";
36977
37235
  async function readLargeFilePostBoundary(filePath, visit) {
36978
37236
  const stat3 = fs13.statSync(filePath);
36979
37237
  const fileSize = stat3.size;
@@ -37351,7 +37609,7 @@ function entryToSessionMessage(entry) {
37351
37609
  const inputSource = m.inputSource ?? legacyProactiveInput(m);
37352
37610
  const video = Array.isArray(m.content) && m.content.some((b) => b.type === "video");
37353
37611
  const imageInput = m.imageInput ? { ...m.imageInput } : video ? {
37354
- id: "legacy-video:" + (entry.uuid || createHash37("sha256").update(JSON.stringify(entry.raw)).digest("hex")),
37612
+ id: "legacy-video:" + (entry.uuid || createHash38("sha256").update(JSON.stringify(entry.raw)).digest("hex")),
37355
37613
  observed: false
37356
37614
  } : void 0;
37357
37615
  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 +37941,7 @@ var init_image_input_protection = __esm({
37683
37941
  });
37684
37942
 
37685
37943
  // src/tools/read-result.ts
37686
- import { createHash as createHash38 } from "node:crypto";
37944
+ import { createHash as createHash39 } from "node:crypto";
37687
37945
  function readResultKey(call, content) {
37688
37946
  if (call.function.name !== "read") return null;
37689
37947
  let args2;
@@ -37695,7 +37953,7 @@ function readResultKey(call, content) {
37695
37953
  if (!args2 || typeof args2.path !== "string") return null;
37696
37954
  const body = content.replace(/^\[历史工具观察[^\n]*\]\n/, "").replace(/^(?:⚠️ 你已连续[^\n]*\n\n|⚠️ 重复读取检测:[^\n]*\n\n)+/, "");
37697
37955
  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");
37956
+ return JSON.stringify([args2.path, args2.offset || 1, args2.limit || null]) + ":" + createHash39("sha256").update(body).digest("hex");
37699
37957
  }
37700
37958
  function repeatedReadNotice(toolCallId) {
37701
37959
  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 +37972,7 @@ var init_read_result = __esm({
37714
37972
  });
37715
37973
 
37716
37974
  // src/tools/result-snapshot.ts
37717
- import { createHash as createHash39 } from "node:crypto";
37975
+ import { createHash as createHash40 } from "node:crypto";
37718
37976
  function visibleArchive(message) {
37719
37977
  const a = message.resultArchive;
37720
37978
  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 +38125,7 @@ var init_result_snapshot = __esm({
37867
38125
  init_image_input_protection();
37868
38126
  MIN_SNAPSHOT_CHARS = 8e3;
37869
38127
  URI = /^tool-result:\/\/([a-f0-9]{64})$/;
37870
- digest6 = (sessionId, content) => createHash39("sha256").update(sessionId).update("\0").update(content).digest("hex");
38128
+ digest6 = (sessionId, content) => createHash40("sha256").update(sessionId).update("\0").update(content).digest("hex");
37871
38129
  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
38130
  archiveId = (sessionId, entries) => digest6(sessionId, JSON.stringify(entries.map((e) => [e.id, e.index])));
37873
38131
  }
@@ -38460,7 +38718,7 @@ var init_context_dump = __esm({
38460
38718
  // src/core/steer-mailbox.ts
38461
38719
  import * as fs15 from "node:fs";
38462
38720
  import * as path13 from "node:path";
38463
- import { createHash as createHash40, randomUUID as randomUUID20 } from "node:crypto";
38721
+ import { createHash as createHash41, randomUUID as randomUUID20 } from "node:crypto";
38464
38722
  var MAX_FILE, MAX_PENDING, MAX_PENDING_BYTES, SteerMailbox;
38465
38723
  var init_steer_mailbox = __esm({
38466
38724
  "src/core/steer-mailbox.ts"() {
@@ -38472,7 +38730,7 @@ var init_steer_mailbox = __esm({
38472
38730
  SteerMailbox = class {
38473
38731
  constructor(stateDir2, sessionId) {
38474
38732
  this.sessionId = sessionId;
38475
- const key5 = createHash40("sha256").update(sessionId).digest("hex");
38733
+ const key5 = createHash41("sha256").update(sessionId).digest("hex");
38476
38734
  this.path = path13.join(stateDir2, "steer", `${key5}.json`);
38477
38735
  }
38478
38736
  path;
@@ -38506,7 +38764,7 @@ var init_steer_mailbox = __esm({
38506
38764
  if (input.attachment) this.assertAttachment(input);
38507
38765
  input.images?.forEach(assertImageAssetRef);
38508
38766
  const records = this.list();
38509
- const id = input.messageId ? createHash40("sha256").update(JSON.stringify([
38767
+ const id = input.messageId ? createHash41("sha256").update(JSON.stringify([
38510
38768
  this.sessionId,
38511
38769
  input.channel,
38512
38770
  input.channelTarget ?? "",
@@ -39662,7 +39920,7 @@ var init_compact2 = __esm({
39662
39920
  });
39663
39921
 
39664
39922
  // src/compact/background.ts
39665
- import { createHash as createHash41 } from "node:crypto";
39923
+ import { createHash as createHash42 } from "node:crypto";
39666
39924
  var historyFingerprint;
39667
39925
  var init_background = __esm({
39668
39926
  "src/compact/background.ts"() {
@@ -39672,7 +39930,7 @@ var init_background = __esm({
39672
39930
  init_tokenEstimate();
39673
39931
  init_hooks();
39674
39932
  init_host_turn();
39675
- historyFingerprint = (messages) => createHash41("sha256").update(JSON.stringify(messages)).digest("hex");
39933
+ historyFingerprint = (messages) => createHash42("sha256").update(JSON.stringify(messages)).digest("hex");
39676
39934
  }
39677
39935
  });
39678
39936
 
@@ -39882,6 +40140,199 @@ var init_store2 = __esm({
39882
40140
  }
39883
40141
  });
39884
40142
 
40143
+ // src/skills/recent-user-texts.ts
40144
+ var init_recent_user_texts = __esm({
40145
+ "src/skills/recent-user-texts.ts"() {
40146
+ "use strict";
40147
+ init_strip_injected();
40148
+ }
40149
+ });
40150
+
40151
+ // src/core/query-skill-selection.ts
40152
+ async function selectSkillCall(provider, params, allowedNames, recordUsage) {
40153
+ const timeout = AbortSignal.timeout(5e3);
40154
+ const signal = AbortSignal.any([params.signal, timeout]);
40155
+ const chunks = [];
40156
+ let calledSkill = false;
40157
+ let skillName = "";
40158
+ let requestComplete = false;
40159
+ let otherCut = false;
40160
+ try {
40161
+ for await (const chunk of provider.streamChat({
40162
+ ...params,
40163
+ signal,
40164
+ httpRetry: { maxRetries: 0 }
40165
+ })) {
40166
+ signal.throwIfAborted();
40167
+ if (chunk.type === "error") return { outcome: "upstream-error" };
40168
+ if (chunk.type === "tool_call") {
40169
+ if (calledSkill || !chunk.tool_call?.id || chunk.tool_call.function?.name !== SKILL_TOOL_NAME) return { outcome: "invalid" };
40170
+ let args2;
40171
+ try {
40172
+ args2 = JSON.parse(chunk.tool_call.function.arguments);
40173
+ } catch {
40174
+ return { outcome: "invalid" };
40175
+ }
40176
+ if (typeof args2?.skill !== "string" || !allowedNames.has(args2.skill.trim().replace(/^\//, ""))) return { outcome: "invalid" };
40177
+ calledSkill = true;
40178
+ skillName = args2.skill.trim().replace(/^\//, "");
40179
+ chunks.push(chunk);
40180
+ }
40181
+ if (chunk.type === "done") {
40182
+ if (chunk.usage) recordUsage(chunk.usage);
40183
+ requestComplete ||= chunk.requestComplete === true;
40184
+ otherCut ||= ["incomplete", "content_filter"].includes(chunk.stopReason ?? "");
40185
+ }
40186
+ }
40187
+ } catch (error) {
40188
+ params.signal.throwIfAborted();
40189
+ if (error instanceof Error && /^TRAVEL_/.test(error.message)) throw error;
40190
+ return { outcome: timeout.aborted ? "timeout" : "upstream-error" };
40191
+ }
40192
+ params.signal.throwIfAborted();
40193
+ if (timeout.aborted) return { outcome: "timeout" };
40194
+ if (!requestComplete || otherCut) return { outcome: "incomplete" };
40195
+ return calledSkill ? { outcome: "selected", skill: skillName, chunks } : { outcome: "no-skill" };
40196
+ }
40197
+ var SKILL_SELECTION_PROMPT, SKILL_SELECTION_MAX_TOKENS;
40198
+ var init_query_skill_selection = __esm({
40199
+ "src/core/query-skill-selection.ts"() {
40200
+ "use strict";
40201
+ init_constants3();
40202
+ init_types();
40203
+ init_recent_user_texts();
40204
+ 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";
40205
+ SKILL_SELECTION_MAX_TOKENS = 64;
40206
+ }
40207
+ });
40208
+
40209
+ // src/skills/scanner.ts
40210
+ function parseFrontmatter2(content) {
40211
+ const result = {};
40212
+ const match = content.match(/^---\s*\n([\s\S]*?)\n---/);
40213
+ if (!match) return result;
40214
+ const lines = match[1].split("\n");
40215
+ let i = 0;
40216
+ while (i < lines.length) {
40217
+ const line = lines[i];
40218
+ const colonIdx = line.indexOf(":");
40219
+ if (colonIdx === -1) {
40220
+ i++;
40221
+ continue;
40222
+ }
40223
+ const key5 = line.slice(0, colonIdx).trim();
40224
+ let value = line.slice(colonIdx + 1).trim();
40225
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
40226
+ value = value.slice(1, -1);
40227
+ result[key5] = value;
40228
+ i++;
40229
+ continue;
40230
+ } else if (value === "|" || value === ">") {
40231
+ const blockLines = [];
40232
+ i++;
40233
+ while (i < lines.length && lines[i].startsWith(" ")) {
40234
+ blockLines.push(lines[i].slice(2));
40235
+ i++;
40236
+ }
40237
+ result[key5] = blockLines.join("\n").trim();
40238
+ continue;
40239
+ } else if (value.startsWith("[") && value.endsWith("]")) {
40240
+ result[key5] = value.slice(1, -1).split(",").map((s) => s.trim());
40241
+ i++;
40242
+ continue;
40243
+ } else if (value.includes(" ") && !value.startsWith('"')) {
40244
+ result[key5] = value;
40245
+ } else {
40246
+ result[key5] = value;
40247
+ }
40248
+ i++;
40249
+ }
40250
+ return result;
40251
+ }
40252
+ var init_scanner = __esm({
40253
+ "src/skills/scanner.ts"() {
40254
+ "use strict";
40255
+ }
40256
+ });
40257
+
40258
+ // src/tools/SkillTool/SkillTool.ts
40259
+ import { createHash as createHash43 } from "node:crypto";
40260
+ import * as fs17 from "node:fs";
40261
+ import * as path15 from "node:path";
40262
+ function getSkillSelectionCatalog() {
40263
+ return selectionCatalog;
40264
+ }
40265
+ function loadSkillContent(skillsDir, skill) {
40266
+ const skillMdPath = skill.location ? path15.join(skillsDir, skill.location.slice("skills/".length)) : path15.join(skillsDir, skill.name, "SKILL.md");
40267
+ if (!fs17.existsSync(skillMdPath)) return null;
40268
+ const content = fs17.readFileSync(skillMdPath, "utf-8");
40269
+ const dependencies = parseFrontmatter2(content)["requires-tools"];
40270
+ 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))];
40271
+ const bodyMatch = content.match(/^---\s*\n[\s\S]*?\n---\s*\n([\s\S]*)/);
40272
+ const body = bodyMatch ? bodyMatch[1] : content;
40273
+ const skillDir = path15.dirname(skillMdPath);
40274
+ const normalizedDir = process.platform === "win32" ? skillDir.replace(/\\/g, "/") : skillDir;
40275
+ let finalContent = `Base directory for this skill: ${normalizedDir}
40276
+
40277
+ ${body}`;
40278
+ finalContent = finalContent.replace(/\$\{CLAUDE_SKILL_DIR\}/g, normalizedDir);
40279
+ finalContent = finalContent.replace(/\$\{CLAUDE_SESSION_ID\}/g, getSessionId());
40280
+ return { content: finalContent, requiredTools };
40281
+ }
40282
+ function getSessionId() {
40283
+ return String(process.pid);
40284
+ }
40285
+ function skillFingerprint(skill, body) {
40286
+ return createHash43("sha256").update(skill.location ?? skill.name).update("\0").update(body).digest("hex").slice(0, 16);
40287
+ }
40288
+ function findLoadedSkill(history, skill, fingerprint2, resolve26) {
40289
+ if (!history) return void 0;
40290
+ for (let i = history.length - 1; i >= 0; i--) {
40291
+ const message = history[i];
40292
+ if (!("role" in message) || message.role !== "tool" || message.is_error || typeof message.content !== "string") continue;
40293
+ let call;
40294
+ for (let j = i - 1; j >= 0 && !call; j--) {
40295
+ const previous = history[j];
40296
+ 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);
40297
+ }
40298
+ if (!call) continue;
40299
+ let args2 = {};
40300
+ try {
40301
+ args2 = JSON.parse(call.function.arguments);
40302
+ } catch {
40303
+ continue;
40304
+ }
40305
+ if (typeof args2?.skill !== "string" || resolve26(args2.skill.trim().replace(/^\//, "")) !== skill) continue;
40306
+ if (!message.content.includes(SKILL_FINGERPRINT_PREFIX + fingerprint2 + "]")) return void 0;
40307
+ return estimateMessageTokens(history.slice(i + 1)) <= SKILL_RELOAD_DISTANCE_TOKENS ? call.id : void 0;
40308
+ }
40309
+ return void 0;
40310
+ }
40311
+ function findLoadedSkillCall(history, skillName) {
40312
+ const resolve26 = resolveSkillFn;
40313
+ if (!history || !resolve26) return void 0;
40314
+ const skill = resolve26(skillName.trim().replace(/^\//, ""));
40315
+ if (!skill) return void 0;
40316
+ const content = loadSkillContent(skillsDirPath, skill);
40317
+ if (!content) return void 0;
40318
+ return findLoadedSkill(history, skill, skillFingerprint(skill, content.content), resolve26);
40319
+ }
40320
+ var skillsDirPath, selectionCatalog, resolveSkillFn, SKILL_FINGERPRINT_PREFIX, SKILL_RELOAD_DISTANCE_TOKENS;
40321
+ var init_SkillTool = __esm({
40322
+ "src/tools/SkillTool/SkillTool.ts"() {
40323
+ "use strict";
40324
+ init_registry();
40325
+ init_scanner();
40326
+ init_tool_loading();
40327
+ init_tokenEstimate();
40328
+ init_constants3();
40329
+ skillsDirPath = "";
40330
+ selectionCatalog = { entries: [], allowedNames: /* @__PURE__ */ new Set() };
40331
+ SKILL_FINGERPRINT_PREFIX = "[fingerprint ";
40332
+ SKILL_RELOAD_DISTANCE_TOKENS = 16e3;
40333
+ }
40334
+ });
40335
+
39885
40336
  // src/memory/memdir/memdir.ts
39886
40337
  var memdir_exports = {};
39887
40338
  __export(memdir_exports, {
@@ -39894,8 +40345,8 @@ __export(memdir_exports, {
39894
40345
  loadMemoryPrompt: () => loadMemoryPrompt,
39895
40346
  truncateEntrypointContent: () => truncateEntrypointContent
39896
40347
  });
39897
- import { readFileSync as readFileSync39 } from "node:fs";
39898
- import { join as join56 } from "node:path";
40348
+ import { readFileSync as readFileSync41 } from "node:fs";
40349
+ import { join as join58 } from "node:path";
39899
40350
  function truncateEntrypointContent(raw) {
39900
40351
  const trimmed = raw.trim();
39901
40352
  const contentLines = trimmed.split("\n");
@@ -39988,11 +40439,11 @@ function buildMemoryLines(displayName, memoryDir, extraGuidelines, skipIndex = f
39988
40439
  }
39989
40440
  function buildMemoryPrompt(params) {
39990
40441
  const { displayName, memoryDir, extraGuidelines } = params;
39991
- const entrypoint = join56(memoryDir, ENTRYPOINT_NAME);
40442
+ const entrypoint = join58(memoryDir, ENTRYPOINT_NAME);
39992
40443
  let entrypointContent = params.entrypointContent ?? "";
39993
40444
  if (params.entrypointContent === void 0) {
39994
40445
  try {
39995
- entrypointContent = readFileSync39(entrypoint, "utf-8");
40446
+ entrypointContent = readFileSync41(entrypoint, "utf-8");
39996
40447
  } catch {
39997
40448
  }
39998
40449
  }
@@ -40038,8 +40489,8 @@ __export(context_analyzer_exports, {
40038
40489
  formatContextReport: () => formatContextReport,
40039
40490
  scanMemoryFiles: () => scanMemoryFiles2
40040
40491
  });
40041
- import * as fs17 from "node:fs";
40042
- import * as path15 from "node:path";
40492
+ import * as fs18 from "node:fs";
40493
+ import * as path16 from "node:path";
40043
40494
  function estimateMessageTokens2(m) {
40044
40495
  let tokens = 0;
40045
40496
  if (typeof m.content === "string") {
@@ -40149,9 +40600,9 @@ function breakdownMessages(messages) {
40149
40600
  }
40150
40601
  async function scanMemoryFiles2(workspace2) {
40151
40602
  const files = [];
40152
- const soul = readFileIfExists(path15.join(workspace2, "SOUL.md"));
40603
+ const soul = readFileIfExists(path16.join(workspace2, "SOUL.md"));
40153
40604
  if (soul) files.push({ path: "SOUL.md", tokens: roughTokenCountEstimation(soul), stable: true });
40154
- const agents = readFileIfExists(path15.join(workspace2, "AGENTS.md"));
40605
+ const agents = readFileIfExists(path16.join(workspace2, "AGENTS.md"));
40155
40606
  if (agents) files.push({ path: "AGENTS.md", tokens: roughTokenCountEstimation(agents), stable: true });
40156
40607
  try {
40157
40608
  const { buildMemoryPrompt: buildMemoryPrompt2 } = await Promise.resolve().then(() => (init_memdir(), memdir_exports));
@@ -40167,7 +40618,7 @@ async function scanMemoryFiles2(workspace2) {
40167
40618
  }
40168
40619
  function readFileIfExists(filePath) {
40169
40620
  try {
40170
- if (fs17.existsSync(filePath)) return fs17.readFileSync(filePath, "utf-8");
40621
+ if (fs18.existsSync(filePath)) return fs18.readFileSync(filePath, "utf-8");
40171
40622
  } catch {
40172
40623
  }
40173
40624
  return null;
@@ -40438,6 +40889,8 @@ var init_query = __esm({
40438
40889
  init_task_manager();
40439
40890
  init_skill_gate();
40440
40891
  init_skill_gate();
40892
+ init_query_skill_selection();
40893
+ init_SkillTool();
40441
40894
  QueryEngine = class _QueryEngine {
40442
40895
  constructor(provider, options) {
40443
40896
  this.provider = provider;
@@ -40791,6 +41244,7 @@ var init_query = __esm({
40791
41244
  turnCount++;
40792
41245
  const steers = this.pendingSteers.splice(0);
40793
41246
  let steerConsumedThisTurn = false;
41247
+ let userSteerConsumedThisTurn = false;
40794
41248
  if (steers.length > 0) {
40795
41249
  for (const input of steers) {
40796
41250
  if (this.steerHistoryIds.has(input.id)) {
@@ -40822,6 +41276,7 @@ var init_query = __esm({
40822
41276
  if (collectStopEvidence) stopUserMessages.push(input.originalText ?? input.text);
40823
41277
  this.steerHistoryIds.add(input.id);
40824
41278
  steerConsumedThisTurn = true;
41279
+ userSteerConsumedThisTurn = true;
40825
41280
  yield {
40826
41281
  type: "user_input",
40827
41282
  message: steerMsg,
@@ -41077,7 +41532,53 @@ var init_query = __esm({
41077
41532
  let turnAborted = false;
41078
41533
  try {
41079
41534
  wholeQueryAbort.signal.throwIfAborted();
41080
- const view = normalizeMessagesForAPI(currentMessages).map((m) => {
41535
+ const beforeRequest = () => {
41536
+ wholeQueryAbort.signal.throwIfAborted();
41537
+ ac.signal.throwIfAborted();
41538
+ };
41539
+ const startRequest = () => {
41540
+ this.phase = "streaming";
41541
+ assertRuntimeAuthority(void 0, "INPUT");
41542
+ if (perTurnOptions?.onRequestStarted) {
41543
+ const start = perTurnOptions.onRequestStarted;
41544
+ setImmediate(() => {
41545
+ if (!wholeQueryAbort.signal.aborted) start();
41546
+ });
41547
+ }
41548
+ };
41549
+ let selected;
41550
+ const selectionInput = perTurnOptions?.skillSelectionInput;
41551
+ const skill = turnCount === 1 && maxTurns >= 2 && !userSteerConsumedThisTurn && !hasPendingUserInput() && selectionInput ? allToolDefs.find((tool) => tool.function.name === SKILL_TOOL_NAME) : void 0;
41552
+ const catalog = skill ? getSkillSelectionCatalog() : void 0;
41553
+ if (skill && selectionInput && catalog?.entries.length) {
41554
+ const input = normalizeMessagesForAPI([selectionInput]);
41555
+ const started = performance.now();
41556
+ startRequest();
41557
+ const selection = await selectSkillCall(queryProvider, {
41558
+ preferFastFallback,
41559
+ model: queryModel,
41560
+ messages: input,
41561
+ tools: [skill],
41562
+ systemStable: SKILL_SELECTION_PROMPT + "\n\n" + JSON.stringify(catalog.entries),
41563
+ maxTokens: SKILL_SELECTION_MAX_TOKENS,
41564
+ signal: ac.signal,
41565
+ beforeRequest: () => {
41566
+ assertHostTurnCurrent();
41567
+ beforeRequest();
41568
+ },
41569
+ disableThinking: true
41570
+ }, catalog.allowedNames, recordUsage);
41571
+ assertHostTurnCurrent();
41572
+ beforeRequest();
41573
+ console.log(`${this.logPrefix} [skill-selection] ${selection.outcome} ms=${Math.round(performance.now() - started)}`);
41574
+ if (hasPendingUserInput()) continue;
41575
+ if (selection.outcome === "selected") {
41576
+ if (findLoadedSkillCall(currentMessages, selection.skill)) {
41577
+ console.log(`${this.logPrefix} [skill-selection] already-loaded ${selection.skill}`);
41578
+ } else selected = selection.chunks;
41579
+ }
41580
+ }
41581
+ const view = (selected ? [] : normalizeMessagesForAPI(currentMessages)).map((m) => {
41081
41582
  if (!Array.isArray(m.content) || !m.imageInput?.observed || !queryModelRef) return m;
41082
41583
  const blocks = m.content.filter((b) => {
41083
41584
  if (b.type === "image" || b.type === "image_ref") return !!queryInputs?.includes("image");
@@ -41112,7 +41613,7 @@ ${hint}` : [...current2.content, { type: "text", text: hint }] };
41112
41613
  const fullSystemDynamic = deferredHint && perTurnSystemDynamic ? `${deferredHint}
41113
41614
 
41114
41615
  ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
41115
- if ((!this.options.agentLabel || this.options.agentLabel === "main") && isContextDumpEnabled()) {
41616
+ if (!selected && (!this.options.agentLabel || this.options.agentLabel === "main") && isContextDumpEnabled()) {
41116
41617
  try {
41117
41618
  const ws = process.env.ENGINE7_WORKSPACE;
41118
41619
  if (ws) {
@@ -41128,15 +41629,8 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
41128
41629
  } catch {
41129
41630
  }
41130
41631
  }
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({
41632
+ if (!selected) startRequest();
41633
+ for await (const chunk of selected ?? queryProvider.streamChat({
41140
41634
  preferFastFallback,
41141
41635
  model: queryModel,
41142
41636
  messages: apiMessages,
@@ -41149,10 +41643,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
41149
41643
  maxTokens: this.resolveRequestMaxTokens(apiMessages, maxTokensOverride),
41150
41644
  temperature: this.options.temperature,
41151
41645
  signal: ac.signal,
41152
- beforeRequest: () => {
41153
- wholeQueryAbort.signal.throwIfAborted();
41154
- ac.signal.throwIfAborted();
41155
- },
41646
+ beforeRequest,
41156
41647
  disableThinking: this.options.disableThinking || !!perTurnEmotion
41157
41648
  // 情感模式关 thinking(对齐 deskBuddy)
41158
41649
  })) {
@@ -41513,6 +42004,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
41513
42004
  if (vcDelivery) await vcDelivery;
41514
42005
  }
41515
42006
  const { messages: toolResults, summaries } = toolRes;
42007
+ if (selected) console.log(`${this.logPrefix} [skill-selection] ${summaries.length === 1 && !summaries[0].isError ? "loaded" : "load-failed"}`);
41516
42008
  if (collectStopEvidence) stopToolResults.push(...summaries);
41517
42009
  for (const s of summaries) {
41518
42010
  try {
@@ -41861,9 +42353,9 @@ var init_extractPrompts = __esm({
41861
42353
  });
41862
42354
 
41863
42355
  // 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";
42356
+ import * as fs19 from "fs";
42357
+ import * as path17 from "path";
42358
+ import { createHash as createHash44 } from "node:crypto";
41867
42359
  function isModelVisibleMessage(message) {
41868
42360
  return message.role === "user" || message.role === "assistant";
41869
42361
  }
@@ -41871,7 +42363,7 @@ function messageText(message) {
41871
42363
  return typeof message.content === "string" ? message.content : message.content.filter((block) => block.type === "text").map((block) => block.text).join("\n");
41872
42364
  }
41873
42365
  function messageKey(message) {
41874
- return createHash42("sha256").update(JSON.stringify([message.role, message.timestamp ?? null, messageText(message)])).digest("hex");
42366
+ return createHash44("sha256").update(JSON.stringify([message.role, message.timestamp ?? null, messageText(message)])).digest("hex");
41875
42367
  }
41876
42368
  function filterNewMessages(messages, lastTs, acknowledged) {
41877
42369
  const newMessages = [];
@@ -41907,20 +42399,20 @@ For this extraction, all paths and search results are relative to the configured
41907
42399
  }));
41908
42400
  }
41909
42401
  function getStatePath(workspace2, topicsDir) {
41910
- return path16.join(topicsDir ?? getAutoMemPath(workspace2), STATE_FILE);
42402
+ return path17.join(topicsDir ?? getAutoMemPath(workspace2), STATE_FILE);
41911
42403
  }
41912
42404
  function loadPersistedState(workspace2, state, topicsDir) {
41913
42405
  try {
41914
42406
  let p = getStatePath(workspace2, topicsDir);
41915
- if (!topicsDir && !fs18.existsSync(p)) {
41916
- const legacy = path16.join(workspace2, STATE_FILE);
41917
- if (fs18.existsSync(legacy)) {
42407
+ if (!topicsDir && !fs19.existsSync(p)) {
42408
+ const legacy = path17.join(workspace2, STATE_FILE);
42409
+ if (fs19.existsSync(legacy)) {
41918
42410
  p = legacy;
41919
42411
  console.log("[memory] \u6C34\u4F4D\u81EA\u65E7\u8DEF\u5F84\uFF08workspace \u6839\uFF09\u8BFB\u5165\uFF0C\u4E0B\u6B21\u843D\u76D8\u8FC1\u79FB\u81F3 memoryDir");
41920
42412
  }
41921
42413
  }
41922
- if (fs18.existsSync(p)) {
41923
- const data = JSON.parse(fs18.readFileSync(p, "utf-8"));
42414
+ if (fs19.existsSync(p)) {
42415
+ const data = JSON.parse(fs19.readFileSync(p, "utf-8"));
41924
42416
  for (const [sid, ts] of Object.entries(data.lastTs ?? {})) {
41925
42417
  state.lastTs.set(sid, ts);
41926
42418
  }
@@ -41945,19 +42437,19 @@ function persistState(workspace2, state, topicsDir) {
41945
42437
  const acknowledged = Object.fromEntries([...state.acknowledged].map(([sid, keys]) => [sid, [...keys]]));
41946
42438
  const data = JSON.stringify({ lastTs, timestamps, acknowledged }, null, 2);
41947
42439
  const target = getStatePath(workspace2, topicsDir);
41948
- fs18.mkdirSync(path16.dirname(target), { recursive: true });
42440
+ fs19.mkdirSync(path17.dirname(target), { recursive: true });
41949
42441
  const temporary = `${target}.${process.pid}.tmp`;
41950
- fs18.writeFileSync(temporary, data, "utf-8");
41951
- fs18.renameSync(temporary, target);
42442
+ fs19.writeFileSync(temporary, data, "utf-8");
42443
+ fs19.renameSync(temporary, target);
41952
42444
  } catch (e) {
41953
42445
  if (topicsDir) throw e;
41954
42446
  console.warn(`[memory] failed to persist extract state: ${e?.message ?? e}`);
41955
42447
  }
41956
42448
  }
41957
42449
  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;
42450
+ workspace2 = fs19.existsSync(workspace2) ? fs19.realpathSync(workspace2) : path17.resolve(workspace2);
42451
+ const declaredMemoryDir = path17.resolve(topicsDir ?? getAutoMemPath(workspace2));
42452
+ const memoryDir = fs19.existsSync(declaredMemoryDir) ? fs19.realpathSync(declaredMemoryDir) : declaredMemoryDir;
41961
42453
  let shared = workspaceStates.get(memoryDir);
41962
42454
  if (!shared) {
41963
42455
  shared = { lastTs: /* @__PURE__ */ new Map(), acknowledged: /* @__PURE__ */ new Map(), lastExtractTime: /* @__PURE__ */ new Map(), generations: /* @__PURE__ */ new Map() };
@@ -42014,11 +42506,11 @@ function createMemoryExtractor(workspace2, enabled, topicsDir) {
42014
42506
  (await scanMemoryFiles(memoryDir, new AbortController().signal)).map((memory) => ({ ...memory, filename: memory.filename.replace(/\\/g, "/") })),
42015
42507
  { maxDescriptionChars: 120, timestamps: false }
42016
42508
  );
42017
- const extractOverridePath = path16.join(workspace2, "prompts", "extract.md");
42509
+ const extractOverridePath = path17.join(workspace2, "prompts", "extract.md");
42018
42510
  let systemPrompt;
42019
42511
  try {
42020
- if (fs18.existsSync(extractOverridePath)) {
42021
- systemPrompt = fs18.readFileSync(extractOverridePath, { encoding: "utf-8" });
42512
+ if (fs19.existsSync(extractOverridePath)) {
42513
+ systemPrompt = fs19.readFileSync(extractOverridePath, { encoding: "utf-8" });
42022
42514
  if (existingMemories.length > 0) {
42023
42515
  systemPrompt += `
42024
42516
 
@@ -42166,7 +42658,7 @@ ${conversationText}`
42166
42658
  if (generation !== (state.generations.get(sessionId) ?? 0)) return false;
42167
42659
  const interval = previous && !alreadyCoolingDown ? 0 : intervalMinutes;
42168
42660
  if (!topicsDir) return extract(snapshot, provider, model, sessionId, disableThinking, interval);
42169
- return withFileTransaction(path16.join(memoryDir, ".extract-lock.sqlite"), () => {
42661
+ return withFileTransaction(path17.join(memoryDir, ".extract-lock.sqlite"), () => {
42170
42662
  loadPersistedState(workspace2, state, memoryDir);
42171
42663
  return extract(snapshot, provider, model, sessionId, disableThinking, interval);
42172
42664
  }, void 0, 12e4);
@@ -42244,11 +42736,11 @@ var init_providers = __esm({
42244
42736
 
42245
42737
  // src/task-sessions/extraction.ts
42246
42738
  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";
42739
+ import { basename as basename13, dirname as dirname31, join as join61, resolve as resolve22 } from "node:path";
42248
42740
  function validTaskTopicNotice(stateDir2, notice) {
42249
42741
  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");
42742
+ const project = dirname31(resolve22(notice.topicsDir));
42743
+ return dirname31(project) === resolve22(stateDir2, "agents", "main", "projects") && resolve22(notice.topicsDir) === join61(project, "topics") && dirname31(resolve22(notice.transcriptPath)) === join61(project, "sessions");
42252
42744
  }
42253
42745
  async function readPendingTaskTopics(stateDir2) {
42254
42746
  const dir = queueDir(stateDir2);
@@ -42262,7 +42754,7 @@ async function readPendingTaskTopics(stateDir2) {
42262
42754
  const items = [];
42263
42755
  for (const name of names) {
42264
42756
  if (!/^[a-f0-9]{64}-[a-f0-9-]{36}\.json$/.test(name)) continue;
42265
- const file2 = join59(dir, name);
42757
+ const file2 = join61(dir, name);
42266
42758
  try {
42267
42759
  const notice = JSON.parse(await readFile2(file2, "utf8"));
42268
42760
  if (validTaskTopicNotice(stateDir2, notice)) items.push({ file: file2, notice });
@@ -42276,8 +42768,8 @@ function acknowledgeTaskTopics(item) {
42276
42768
  return rm2(item.file, { force: true });
42277
42769
  }
42278
42770
  async function markTaskTopicsWorker(stateDir2) {
42279
- const marker = join59(queueDir(stateDir2), "worker.pid");
42280
- await mkdir2(dirname30(marker), { recursive: true });
42771
+ const marker = join61(queueDir(stateDir2), "worker.pid");
42772
+ await mkdir2(dirname31(marker), { recursive: true });
42281
42773
  await writeFile(marker, String(process.pid));
42282
42774
  return async () => {
42283
42775
  if (await readFile2(marker, "utf8").catch(() => "") === String(process.pid)) await rm2(marker, { force: true });
@@ -42291,20 +42783,20 @@ var init_extraction = __esm({
42291
42783
  init_extractMemories();
42292
42784
  init_reader2();
42293
42785
  init_providers();
42294
- queueDir = (stateDir2) => join59(stateDir2, "task-topics-queue");
42786
+ queueDir = (stateDir2) => join61(stateDir2, "task-topics-queue");
42295
42787
  }
42296
42788
  });
42297
42789
 
42298
42790
  // src/tools/read.ts
42299
- import * as fs19 from "node:fs";
42300
- import * as path17 from "node:path";
42791
+ import * as fs20 from "node:fs";
42792
+ import * as path18 from "node:path";
42301
42793
  function isBlockedDevicePath(filePath) {
42302
42794
  if (BLOCKED_DEVICE_PATHS.has(filePath)) return true;
42303
42795
  if (filePath.startsWith("/proc/") && (filePath.endsWith("/fd/0") || filePath.endsWith("/fd/1") || filePath.endsWith("/fd/2"))) return true;
42304
42796
  return false;
42305
42797
  }
42306
42798
  function checkReadLoop(filePath, offset, limit) {
42307
- const stat3 = fs19.statSync(filePath);
42799
+ const stat3 = fs20.statSync(filePath);
42308
42800
  const mtimeMs = stat3.mtimeMs;
42309
42801
  const prev = readHistory.get(filePath);
42310
42802
  if (prev && prev.offset === offset && prev.limit === limit && prev.mtimeMs === mtimeMs) {
@@ -42318,19 +42810,19 @@ function checkReadLoop(filePath, offset, limit) {
42318
42810
  return null;
42319
42811
  }
42320
42812
  function readFileContent(filePath) {
42321
- const fd = fs19.openSync(filePath, "r");
42813
+ const fd = fs20.openSync(filePath, "r");
42322
42814
  const bom = Buffer.alloc(2);
42323
- fs19.readSync(fd, bom, 0, 2, 0);
42324
- fs19.closeSync(fd);
42815
+ fs20.readSync(fd, bom, 0, 2, 0);
42816
+ fs20.closeSync(fd);
42325
42817
  let encoding = "utf8";
42326
42818
  if (bom[0] === 255 && bom[1] === 254) {
42327
42819
  encoding = "utf16le";
42328
42820
  }
42329
- const stat3 = fs19.statSync(filePath);
42821
+ const stat3 = fs20.statSync(filePath);
42330
42822
  if (stat3.size > MAX_FILE_SIZE) {
42331
42823
  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
42824
  }
42333
- const raw = fs19.readFileSync(filePath, encoding);
42825
+ const raw = fs20.readFileSync(filePath, encoding);
42334
42826
  const content = raw.toString().replaceAll("\r\n", "\n");
42335
42827
  return { content, encoding };
42336
42828
  }
@@ -42485,11 +42977,11 @@ Usage:
42485
42977
  } catch (e) {
42486
42978
  return { content: e.message, isError: true };
42487
42979
  }
42488
- if (!fs19.existsSync(filePath)) {
42980
+ if (!fs20.existsSync(filePath)) {
42489
42981
  return { content: `\u6587\u4EF6\u4E0D\u5B58\u5728: ${displayFilePath(filePath, ctx)}`, isError: true };
42490
42982
  }
42491
- const stat3 = fs19.statSync(filePath);
42492
- const baseName = path17.basename(filePath).toUpperCase();
42983
+ const stat3 = fs20.statSync(filePath);
42984
+ const baseName = path18.basename(filePath).toUpperCase();
42493
42985
  if (BLOCKED_BASENAMES.has(baseName)) {
42494
42986
  return { content: `\u8BBE\u5907\u6587\u4EF6\u4E0D\u652F\u6301\u8BFB\u53D6: ${displayFilePath(filePath, ctx)}`, isError: true };
42495
42987
  }
@@ -42497,11 +42989,11 @@ Usage:
42497
42989
  return { content: `\u8BBE\u5907\u6587\u4EF6\u4F1A\u963B\u585E\u6216\u4EA7\u751F\u65E0\u9650\u8F93\u51FA: ${displayFilePath(filePath, ctx)}`, isError: true };
42498
42990
  }
42499
42991
  if (stat3.isDirectory()) {
42500
- const entries = fs19.readdirSync(filePath);
42992
+ const entries = fs20.readdirSync(filePath);
42501
42993
  const items = entries.map((e) => {
42502
- const full = path17.join(filePath, e);
42994
+ const full = path18.join(filePath, e);
42503
42995
  try {
42504
- const s = fs19.statSync(full);
42996
+ const s = fs20.statSync(full);
42505
42997
  return s.isDirectory() ? `${e}/` : e;
42506
42998
  } catch {
42507
42999
  return e;
@@ -42510,7 +43002,7 @@ Usage:
42510
43002
  return { content: `\u76EE\u5F55 (${entries.length} \u9879):
42511
43003
  ${items.join("\n")}` };
42512
43004
  }
42513
- const ext = path17.extname(filePath).toLowerCase();
43005
+ const ext = path18.extname(filePath).toLowerCase();
42514
43006
  if (BINARY_EXTENSIONS.has(ext)) {
42515
43007
  const hint = DOC_SKILL_HINTS[ext];
42516
43008
  return {
@@ -42573,9 +43065,9 @@ ${result}` : result };
42573
43065
  });
42574
43066
 
42575
43067
  // src/memory/topics-history/writes.ts
42576
- import { basename as basename15, relative as relative9, isAbsolute as isAbsolute6, sep as sep7 } from "node:path";
43068
+ import { basename as basename15, relative as relative10, isAbsolute as isAbsolute6, sep as sep7 } from "node:path";
42577
43069
  function stampTopicWrite(file2, workspace2, text2, previous, topicsDir, recordedAt) {
42578
- const rel = topicsDir ? relative9(topicsDir, file2) : "";
43070
+ const rel = topicsDir ? relative10(topicsDir, file2) : "";
42579
43071
  const isTopic = topicsDir ? !!rel && !isAbsolute6(rel) && rel !== ".." && !rel.startsWith(".." + sep7) : workspace2 && isAutoMemPath(file2, workspace2);
42580
43072
  if (!isTopic || !/\.md$/i.test(file2) || basename15(file2).toUpperCase() === "MEMORY.MD") return text2;
42581
43073
  const date = /(?<!\d)(\d{4}-\d{2}-\d{2})(?!\d)/.exec(basename15(file2))?.[1];
@@ -42591,22 +43083,22 @@ var init_writes = __esm({
42591
43083
  });
42592
43084
 
42593
43085
  // src/tools/write.ts
42594
- import * as fs20 from "node:fs";
42595
- import * as path18 from "node:path";
43086
+ import * as fs21 from "node:fs";
43087
+ import * as path19 from "node:path";
42596
43088
  function isBlockedPath(filePath, memoryToolRoot) {
42597
43089
  return !memoryToolRoot && /\/root\//i.test(filePath) || BLOCKED_PATTERNS.some((p) => p.test(filePath));
42598
43090
  }
42599
43091
  function atomicWrite(filePath, content) {
42600
43092
  const tmpPath = filePath + ".tmp." + Date.now() + ".write";
42601
- fs20.writeFileSync(tmpPath, content, "utf-8");
43093
+ fs21.writeFileSync(tmpPath, content, "utf-8");
42602
43094
  try {
42603
- fs20.renameSync(tmpPath, filePath);
43095
+ fs21.renameSync(tmpPath, filePath);
42604
43096
  } catch (e) {
42605
43097
  try {
42606
- fs20.unlinkSync(tmpPath);
43098
+ fs21.unlinkSync(tmpPath);
42607
43099
  } catch {
42608
43100
  }
42609
- fs20.writeFileSync(filePath, content, "utf-8");
43101
+ fs21.writeFileSync(filePath, content, "utf-8");
42610
43102
  }
42611
43103
  }
42612
43104
  function simpleDiff(oldContent, newContent) {
@@ -42700,15 +43192,15 @@ Usage:
42700
43192
  }
42701
43193
  const rawContent = args2.content;
42702
43194
  let content = rawContent.replaceAll("\r\n", "\n");
42703
- if (fs20.existsSync(filePath) && fs20.statSync(filePath).isDirectory()) {
43195
+ if (fs21.existsSync(filePath) && fs21.statSync(filePath).isDirectory()) {
42704
43196
  return { content: `\u8DEF\u5F84\u662F\u76EE\u5F55\u4E0D\u662F\u6587\u4EF6: ${displayFilePath(filePath, ctx)}`, isError: true };
42705
43197
  }
42706
43198
  let oldContent = null;
42707
43199
  let isCreate = true;
42708
- if (fs20.existsSync(filePath)) {
43200
+ if (fs21.existsSync(filePath)) {
42709
43201
  isCreate = false;
42710
43202
  try {
42711
- oldContent = fs20.readFileSync(filePath, "utf-8").replaceAll("\r\n", "\n");
43203
+ oldContent = fs21.readFileSync(filePath, "utf-8").replaceAll("\r\n", "\n");
42712
43204
  } catch {
42713
43205
  isCreate = true;
42714
43206
  }
@@ -42724,10 +43216,10 @@ Usage:
42724
43216
  isError: true
42725
43217
  };
42726
43218
  }
42727
- const currentStat = fs20.statSync(filePath);
43219
+ const currentStat = fs21.statSync(filePath);
42728
43220
  const lastWriteTime = Math.floor(currentStat.mtimeMs);
42729
43221
  if (lastWriteTime > readState.timestamp) {
42730
- const currentContent = fs20.readFileSync(filePath, "utf-8").replaceAll("\r\n", "\n");
43222
+ const currentContent = fs21.readFileSync(filePath, "utf-8").replaceAll("\r\n", "\n");
42731
43223
  if (currentContent !== oldContent) {
42732
43224
  return {
42733
43225
  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 +43228,9 @@ Usage:
42736
43228
  }
42737
43229
  }
42738
43230
  }
42739
- const dir = path18.dirname(filePath);
43231
+ const dir = path19.dirname(filePath);
42740
43232
  try {
42741
- fs20.mkdirSync(dir, { recursive: true });
43233
+ fs21.mkdirSync(dir, { recursive: true });
42742
43234
  } catch (e) {
42743
43235
  return { content: `\u65E0\u6CD5\u521B\u5EFA\u76EE\u5F55: ${dir} \u2014 ${e.message}`, isError: true };
42744
43236
  }
@@ -42749,11 +43241,11 @@ Usage:
42749
43241
  } catch (e) {
42750
43242
  return { content: `\u5199\u5165\u5931\u8D25: ${e.message}`, isError: true };
42751
43243
  }
42752
- readFileState.set(filePath, { timestamp: fs20.statSync(filePath).mtimeMs });
43244
+ readFileState.set(filePath, { timestamp: fs21.statSync(filePath).mtimeMs });
42753
43245
  const action = isCreate ? "\u521B\u5EFA" : "\u66F4\u65B0";
42754
43246
  const lines = content.split("\n").length;
42755
43247
  const chars = content.length;
42756
- const stat3 = fs20.statSync(filePath);
43248
+ const stat3 = fs21.statSync(filePath);
42757
43249
  let diff = "";
42758
43250
  if (!isCreate && oldContent !== null) {
42759
43251
  diff = `
@@ -42772,8 +43264,8 @@ ${simpleDiff(oldContent, content)}`;
42772
43264
  });
42773
43265
 
42774
43266
  // src/tools/edit.ts
42775
- import * as fs21 from "node:fs";
42776
- import * as path19 from "node:path";
43267
+ import * as fs22 from "node:fs";
43268
+ import * as path20 from "node:path";
42777
43269
  function normalizeQuotes(str) {
42778
43270
  return str.replaceAll(LEFT_SINGLE_CURLY, "'").replaceAll(RIGHT_SINGLE_CURLY, "'").replaceAll(LEFT_DOUBLE_CURLY, '"').replaceAll(RIGHT_DOUBLE_CURLY, '"');
42779
43271
  }
@@ -42927,7 +43419,7 @@ Usage:
42927
43419
  }
42928
43420
  let fileContent = null;
42929
43421
  try {
42930
- const stat3 = fs21.statSync(filePath);
43422
+ const stat3 = fs22.statSync(filePath);
42931
43423
  if (stat3.isDirectory()) {
42932
43424
  return { content: `\u8DEF\u5F84\u662F\u76EE\u5F55\u4E0D\u662F\u6587\u4EF6: ${displayFilePath(filePath, ctx)}`, isError: true };
42933
43425
  }
@@ -42937,23 +43429,23 @@ Usage:
42937
43429
  } catch (e) {
42938
43430
  if (e.code === "ENOENT") {
42939
43431
  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");
43432
+ const dir = path20.dirname(filePath);
43433
+ fs22.mkdirSync(dir, { recursive: true });
43434
+ fs22.writeFileSync(filePath, stampTopicWrite(filePath, ctx.workspace, newString, null, ctx.projectTask?.topicsDir ?? ctx.memoryToolRoot, ctx.topicSourceTime), "utf-8");
42943
43435
  noteTopicWrite(filePath, ctx);
42944
- readFileState.set(filePath, { timestamp: fs21.statSync(filePath).mtimeMs });
43436
+ readFileState.set(filePath, { timestamp: fs22.statSync(filePath).mtimeMs });
42945
43437
  return { content: `\u521B\u5EFA\u6587\u4EF6: ${displayFilePath(filePath, ctx)} (${newString.split("\n").length} \u884C)` };
42946
43438
  }
42947
43439
  return { content: `\u6587\u4EF6\u4E0D\u5B58\u5728: ${displayFilePath(filePath, ctx)}`, isError: true };
42948
43440
  }
42949
43441
  throw e;
42950
43442
  }
42951
- const rawContent = fs21.readFileSync(filePath, "utf-8");
43443
+ const rawContent = fs22.readFileSync(filePath, "utf-8");
42952
43444
  fileContent = rawContent.replaceAll("\r\n", "\n");
42953
43445
  if (oldString === "" && fileContent.trim() === "") {
42954
- fs21.writeFileSync(filePath, stampTopicWrite(filePath, ctx.workspace, newString, fileContent, ctx.projectTask?.topicsDir ?? ctx.memoryToolRoot, ctx.topicSourceTime), "utf-8");
43446
+ fs22.writeFileSync(filePath, stampTopicWrite(filePath, ctx.workspace, newString, fileContent, ctx.projectTask?.topicsDir ?? ctx.memoryToolRoot, ctx.topicSourceTime), "utf-8");
42955
43447
  noteTopicWrite(filePath, ctx);
42956
- readFileState.set(filePath, { timestamp: fs21.statSync(filePath).mtimeMs });
43448
+ readFileState.set(filePath, { timestamp: fs22.statSync(filePath).mtimeMs });
42957
43449
  return { content: `\u5199\u5165\u7A7A\u6587\u4EF6: ${displayFilePath(filePath, ctx)} (${newString.split("\n").length} \u884C)` };
42958
43450
  }
42959
43451
  const readState = readFileState.get(filePath);
@@ -42963,11 +43455,11 @@ Usage:
42963
43455
  isError: true
42964
43456
  };
42965
43457
  }
42966
- const currentStat = fs21.statSync(filePath);
43458
+ const currentStat = fs22.statSync(filePath);
42967
43459
  const lastWriteTime = Math.floor(currentStat.mtimeMs);
42968
43460
  if (lastWriteTime > readState.timestamp) {
42969
43461
  if (fileContent !== rawContent.replaceAll("\r\n", "\n")) {
42970
- if (fileContent !== fs21.readFileSync(filePath, "utf-8").replaceAll("\r\n", "\n")) {
43462
+ if (fileContent !== fs22.readFileSync(filePath, "utf-8").replaceAll("\r\n", "\n")) {
42971
43463
  return {
42972
43464
  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
43465
  isError: true
@@ -43000,9 +43492,9 @@ ${preview}
43000
43492
  const diffView = generateEditDiff(fileContent, actualOldString, actualNewString);
43001
43493
  const newContent = applyEditToFile(fileContent, actualOldString, actualNewString, replaceAll);
43002
43494
  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");
43495
+ fs22.writeFileSync(filePath, stampTopicWrite(filePath, ctx.workspace, newContent, fileContent, ctx.projectTask?.topicsDir ?? ctx.memoryToolRoot, ctx.topicSourceTime), "utf-8");
43004
43496
  noteTopicWrite(filePath, ctx);
43005
- readFileState.set(filePath, { timestamp: fs21.statSync(filePath).mtimeMs });
43497
+ readFileState.set(filePath, { timestamp: fs22.statSync(filePath).mtimeMs });
43006
43498
  const strategy = actualOldString === oldString ? "\u7CBE\u786E\u5339\u914D" : "\u5F15\u53F7\u89C4\u8303\u5316\u5339\u914D";
43007
43499
  const count = replaceAll ? matchCount : 1;
43008
43500
  const diff = `${oldString.length}\u2192${newString.length}\u5B57\u7B26`;
@@ -43019,8 +43511,8 @@ ${diffView}`
43019
43511
  });
43020
43512
 
43021
43513
  // src/tools/glob.ts
43022
- import * as fs22 from "node:fs";
43023
- import * as path20 from "node:path";
43514
+ import * as fs23 from "node:fs";
43515
+ import * as path21 from "node:path";
43024
43516
  function globMatch(pattern, filename) {
43025
43517
  const regexStr = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "{{GLOBSTAR}}").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]").replace(/\{\{GLOBSTAR\}\}/g, ".*");
43026
43518
  try {
@@ -43032,7 +43524,7 @@ function globMatch(pattern, filename) {
43032
43524
  function findFiles(dir, pattern, limit, baseDir) {
43033
43525
  const results = [];
43034
43526
  let truncated = false;
43035
- function walk(currentDir) {
43527
+ function walk2(currentDir) {
43036
43528
  if (truncated) return;
43037
43529
  if (results.length >= limit * 2) {
43038
43530
  truncated = true;
@@ -43040,18 +43532,18 @@ function findFiles(dir, pattern, limit, baseDir) {
43040
43532
  }
43041
43533
  let entries;
43042
43534
  try {
43043
- entries = fs22.readdirSync(currentDir, { withFileTypes: true });
43535
+ entries = fs23.readdirSync(currentDir, { withFileTypes: true });
43044
43536
  } catch {
43045
43537
  return;
43046
43538
  }
43047
43539
  for (const entry of entries) {
43048
43540
  if (truncated) return;
43049
- const fullPath = path20.join(currentDir, entry.name);
43541
+ const fullPath = path21.join(currentDir, entry.name);
43050
43542
  if (entry.isDirectory()) {
43051
43543
  if (VCS_DIRS.has(entry.name)) continue;
43052
- walk(fullPath);
43544
+ walk2(fullPath);
43053
43545
  } else if (entry.isFile()) {
43054
- const relativePath = path20.relative(baseDir, fullPath).replace(/\\/g, "/");
43546
+ const relativePath = path21.relative(baseDir, fullPath).replace(/\\/g, "/");
43055
43547
  const patternsToTry = [pattern];
43056
43548
  if (pattern.startsWith("**/")) {
43057
43549
  patternsToTry.push(pattern.slice(3));
@@ -43061,7 +43553,7 @@ function findFiles(dir, pattern, limit, baseDir) {
43061
43553
  );
43062
43554
  if (matched) {
43063
43555
  try {
43064
- const stat3 = fs22.statSync(fullPath);
43556
+ const stat3 = fs23.statSync(fullPath);
43065
43557
  results.push({ path: fullPath, mtimeMs: stat3.mtimeMs });
43066
43558
  } catch {
43067
43559
  }
@@ -43069,7 +43561,7 @@ function findFiles(dir, pattern, limit, baseDir) {
43069
43561
  }
43070
43562
  }
43071
43563
  }
43072
- walk(dir);
43564
+ walk2(dir);
43073
43565
  results.sort((a, b) => b.mtimeMs - a.mtimeMs);
43074
43566
  const finalTruncated = truncated || results.length > limit;
43075
43567
  return {
@@ -43078,7 +43570,7 @@ function findFiles(dir, pattern, limit, baseDir) {
43078
43570
  };
43079
43571
  }
43080
43572
  function toRelativePath(absolutePath, cwd) {
43081
- if (absolutePath.startsWith(cwd + path20.sep)) {
43573
+ if (absolutePath.startsWith(cwd + path21.sep)) {
43082
43574
  return absolutePath.slice(cwd.length + 1);
43083
43575
  }
43084
43576
  return absolutePath;
@@ -43111,10 +43603,10 @@ var init_glob = __esm({
43111
43603
  const searchPath = args2.path ? resolveFilePath(args2.path, ctx) : resolveFilePath(".", ctx);
43112
43604
  const pattern = args2.pattern;
43113
43605
  const limit = args2.limit || DEFAULT_LIMIT;
43114
- if (!fs22.existsSync(searchPath)) {
43606
+ if (!fs23.existsSync(searchPath)) {
43115
43607
  return { content: `\u76EE\u5F55\u4E0D\u5B58\u5728: ${displayFilePath(searchPath, ctx)}`, isError: true };
43116
43608
  }
43117
- if (!fs22.statSync(searchPath).isDirectory()) {
43609
+ if (!fs23.statSync(searchPath).isDirectory()) {
43118
43610
  return { content: `\u8DEF\u5F84\u4E0D\u662F\u76EE\u5F55: ${displayFilePath(searchPath, ctx)}`, isError: true };
43119
43611
  }
43120
43612
  const start = Date.now();
@@ -43138,7 +43630,7 @@ ${filenames.join("\n")}${truncatedNote}`
43138
43630
 
43139
43631
  // src/tools/grep.ts
43140
43632
  import { execFile as execFile3 } from "node:child_process";
43141
- import * as path21 from "node:path";
43633
+ import * as path22 from "node:path";
43142
43634
  function ripGrep(args2, searchPath, signal) {
43143
43635
  return new Promise((resolve26) => {
43144
43636
  const fullArgs = [...args2, searchPath];
@@ -43176,7 +43668,7 @@ function applyHeadLimit(items, limit, offset = 0) {
43176
43668
  };
43177
43669
  }
43178
43670
  function toRelativePath2(absolutePath, cwd) {
43179
- if (absolutePath.startsWith(cwd + path21.sep)) {
43671
+ if (absolutePath.startsWith(cwd + path22.sep)) {
43180
43672
  return absolutePath.slice(cwd.length + 1);
43181
43673
  }
43182
43674
  if (absolutePath.startsWith(cwd)) {
@@ -43287,7 +43779,7 @@ var init_grep = __esm({
43287
43779
  if (result.lines.length === 0) {
43288
43780
  return { content: "No files found" };
43289
43781
  }
43290
- const cwd = ctx.memoryToolRoot ? path21.resolve(ctx.memoryToolRoot) : ctx.workspace;
43782
+ const cwd = ctx.memoryToolRoot ? path22.resolve(ctx.memoryToolRoot) : ctx.workspace;
43291
43783
  const lines = result.lines.map((line) => toRelativePath2(line, cwd));
43292
43784
  if (outputMode === "content") {
43293
43785
  const { items: limited2, appliedLimit: appliedLimit2 } = applyHeadLimit(lines, headLimit, offset);
@@ -43355,7 +43847,7 @@ __export(topic_extraction_exports, {
43355
43847
  startTopicExtraction: () => startTopicExtraction
43356
43848
  });
43357
43849
  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";
43850
+ import { basename as basename16, join as join64, resolve as resolve24 } from "node:path";
43359
43851
  function startTopicExtraction(config, workspace2, stateDir2, isBusy) {
43360
43852
  const toolConfig = { stateDir: stateDir2, workspace: workspace2 };
43361
43853
  liveConfig.init(toolConfig);
@@ -43481,12 +43973,12 @@ function startTopicExtraction(config, workspace2, stateDir2, isBusy) {
43481
43973
  const recover = async () => {
43482
43974
  if (!enabled()) return;
43483
43975
  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)));
43976
+ const dir = join64(stateDir2, "agents", "main", "sessions");
43977
+ const [platform, index] = await Promise.all(["platform-map.json", "session-index.json"].map((file3) => readFile3(join64(dir, file3), "utf8").then(JSON.parse)));
43486
43978
  const sessionId = platform["scope:main"], file2 = index[sessionId]?.file;
43487
43979
  if (typeof sessionId === "string" && typeof file2 === "string") {
43488
43980
  const localName = basename16(file2.replace(/\\/g, "/"));
43489
- notify({ sessionId, transcriptPath: join62(dir, localName) });
43981
+ notify({ sessionId, transcriptPath: join64(dir, localName) });
43490
43982
  }
43491
43983
  } catch (error) {
43492
43984
  if (error?.code !== "ENOENT") console.warn(`[bg-worker] topics recovery: ${error?.message ?? error}`);
@@ -43546,7 +44038,7 @@ var init_topic_extraction = __esm({
43546
44038
  });
43547
44039
 
43548
44040
  // src/bg/bg-worker.ts
43549
- import { existsSync as existsSync32 } from "node:fs";
44041
+ import { existsSync as existsSync34 } from "node:fs";
43550
44042
  import { resolve as resolve25 } from "node:path";
43551
44043
 
43552
44044
  // src/bg/host.ts
@@ -43559,8 +44051,8 @@ init_pipeline();
43559
44051
  init_job_runner();
43560
44052
  init_projection_driver();
43561
44053
  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";
44054
+ import { dirname as dirname27, join as join53 } from "node:path";
44055
+ import { existsSync as existsSync26 } from "node:fs";
43564
44056
  import { fileURLToPath as fileURLToPath14 } from "node:url";
43565
44057
 
43566
44058
  // src/mem7/worker-projection.ts
@@ -43643,9 +44135,9 @@ var diagnosticLimits = /* @__PURE__ */ new Map();
43643
44135
  var operationSequence = 0;
43644
44136
  var fingerprint = (line) => createHash34("sha256").update(line).digest("hex").slice(0, 16);
43645
44137
  var storageCode = (error) => String(error?.code ?? error?.message?.match(/INTAKE_[A-Z_]+/)?.[0] ?? "UNKNOWN");
43646
- function fileBytes(path22) {
44138
+ function fileBytes(path23) {
43647
44139
  try {
43648
- return statSync4(path22).size;
44140
+ return statSync4(path23).size;
43649
44141
  } catch (error) {
43650
44142
  if (error?.code !== "ENOENT") throw error;
43651
44143
  return 0;
@@ -43729,11 +44221,11 @@ function warnIntake(stateDir2, message) {
43729
44221
  }
43730
44222
  warnings.set(key5, { at: now2, suppressed: 0 });
43731
44223
  }
43732
- function lockOwnerState(path22) {
44224
+ function lockOwnerState(path23) {
43733
44225
  let pid;
43734
44226
  try {
43735
- if (fileBytes(path22) > 32) return "alive";
43736
- pid = Number(readFileSync32(path22, "utf8").trim());
44227
+ if (fileBytes(path23) > 32) return "alive";
44228
+ pid = Number(readFileSync32(path23, "utf8").trim());
43737
44229
  } catch (error) {
43738
44230
  if (error?.code === "ENOENT") return "missing";
43739
44231
  throw error;
@@ -43747,15 +44239,15 @@ function lockOwnerState(path22) {
43747
44239
  }
43748
44240
  }
43749
44241
  function withSpoolWriteLock(stateDir2, operation) {
43750
- const path22 = writeLockPath(stateDir2);
43751
- mkdirSync17(dirname21(path22), { recursive: true });
44242
+ const path23 = writeLockPath(stateDir2);
44243
+ mkdirSync17(dirname21(path23), { recursive: true });
43752
44244
  let fd;
43753
44245
  try {
43754
- fd = openSync10(path22, "wx");
44246
+ fd = openSync10(path23, "wx");
43755
44247
  } catch (error) {
43756
44248
  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";
44249
+ 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");
44250
+ const reaperPath = path23 + ".reap";
43759
44251
  let reaper;
43760
44252
  try {
43761
44253
  reaper = openSync10(reaperPath, "wx");
@@ -43764,9 +44256,9 @@ function withSpoolWriteLock(stateDir2, operation) {
43764
44256
  throw Error("INTAKE_WRITER_BUSY: \u5199\u9501\u6062\u590D\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
43765
44257
  }
43766
44258
  try {
43767
- if (lockOwnerState(path22) === "dead") unlinkSync5(path22);
44259
+ if (lockOwnerState(path23) === "dead") unlinkSync5(path23);
43768
44260
  try {
43769
- fd = openSync10(path22, "wx");
44261
+ fd = openSync10(path23, "wx");
43770
44262
  } catch (error2) {
43771
44263
  if (error2?.code !== "EEXIST") throw error2;
43772
44264
  throw Error("INTAKE_WRITER_BUSY: \u5199\u5165\u8005\u6B63\u5728\u64CD\u4F5C\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
@@ -43781,7 +44273,7 @@ function withSpoolWriteLock(stateDir2, operation) {
43781
44273
  return operation();
43782
44274
  } finally {
43783
44275
  closeSync10(fd);
43784
- unlinkSync5(path22);
44276
+ unlinkSync5(path23);
43785
44277
  }
43786
44278
  }
43787
44279
  function* spoolLines(fd, offset, maxEntries) {
@@ -43812,10 +44304,10 @@ function* spoolLines(fd, offset, maxEntries) {
43812
44304
  position += bytes2;
43813
44305
  }
43814
44306
  }
43815
- function readCursor(stateDir2, path22, identity, size2) {
44307
+ function readCursor(stateDir2, path23, identity, size2) {
43816
44308
  try {
43817
- if (fileBytes(path22) > 4096) throw Error("INTAKE_CURSOR_INVALID_SIZE");
43818
- const cursor = JSON.parse(readFileSync32(path22, "utf8"));
44309
+ if (fileBytes(path23) > 4096) throw Error("INTAKE_CURSOR_INVALID_SIZE");
44310
+ const cursor = JSON.parse(readFileSync32(path23, "utf8"));
43819
44311
  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
44312
  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
44313
  } catch (error) {
@@ -43854,21 +44346,21 @@ function drainIntakeSpool(stateDir2, store, maxEntries = 50) {
43854
44346
  } : {},
43855
44347
  elapsedMs: Math.round(performance.now() - started)
43856
44348
  });
43857
- const path22 = spoolPath(stateDir2);
44349
+ const path23 = spoolPath(stateDir2);
43858
44350
  const processing = processingPath(stateDir2);
43859
44351
  const cursorPath = processing + ".cursor";
43860
44352
  try {
43861
44353
  withSpoolWriteLock(stateDir2, () => {
43862
44354
  if (!existsSync19(processing)) {
43863
- if (!existsSync19(path22) || statSync4(path22).size === 0) return;
44355
+ if (!existsSync19(path23) || statSync4(path23).size === 0) return;
43864
44356
  try {
43865
44357
  unlinkSync5(cursorPath);
43866
44358
  } catch (error) {
43867
44359
  if (error?.code !== "ENOENT") throw error;
43868
44360
  }
43869
- renameSync10(path22, processing);
44361
+ renameSync10(path23, processing);
43870
44362
  }
43871
- appendFileSync3(path22, "", "utf8");
44363
+ appendFileSync3(path23, "", "utf8");
43872
44364
  });
43873
44365
  if (!existsSync19(processing)) return 0;
43874
44366
  } catch (error) {
@@ -44121,6 +44613,8 @@ function createMemoryProviderRecovery(now2 = Date.now) {
44121
44613
  // src/bg/host.ts
44122
44614
  init_scope();
44123
44615
  init_import_backups();
44616
+ init_paths();
44617
+ init_embedding();
44124
44618
 
44125
44619
  // src/bg/sqlite-maintenance.ts
44126
44620
  import { fork } from "node:child_process";
@@ -44305,8 +44799,8 @@ function openPhysicalMaintenanceDatabase(file2, stateDir2) {
44305
44799
  }
44306
44800
 
44307
44801
  // src/mem7/sqlite-maintenance-worker.ts
44308
- function intakePendingForDatabase(path22) {
44309
- const spool = join48(dirname26(dirname26(path22)), "spool");
44802
+ function intakePendingForDatabase(path23) {
44803
+ const spool = join48(dirname26(dirname26(path23)), "spool");
44310
44804
  return ["intake.jsonl", "intake.processing.jsonl"].some((name) => {
44311
44805
  try {
44312
44806
  return statSync5(join48(spool, name)).size > 0;
@@ -44316,22 +44810,22 @@ function intakePendingForDatabase(path22) {
44316
44810
  }
44317
44811
  });
44318
44812
  }
44319
- var bytes = (path22) => {
44813
+ var bytes = (path23) => {
44320
44814
  try {
44321
- return statSync5(path22).size;
44815
+ return statSync5(path23).size;
44322
44816
  } catch (e) {
44323
44817
  if (e.code !== "ENOENT") throw e;
44324
44818
  return 0;
44325
44819
  }
44326
44820
  };
44327
- async function runSqlitePhysicalMaintenance(path22, options = {}) {
44821
+ async function runSqlitePhysicalMaintenance(path23, options = {}) {
44328
44822
  const minimum = options.minFreeBytes ?? 32 * 1024 * 1024, ratio = options.minFreeRatio ?? 0.05;
44329
44823
  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);
44824
+ const before = bytes(path23) + bytes(path23 + "-wal"), started = performance.now();
44825
+ const allowed = () => options.shouldRun?.() !== false && !intakePendingForDatabase(path23);
44826
+ const db2 = openPhysicalMaintenanceDatabase(path23, options.stateDir);
44333
44827
  let mode = "bootstrap";
44334
- const report = (state) => ({ state, mode, reclaimedBytes: Math.max(0, before - bytes(path22) - bytes(path22 + "-wal")) });
44828
+ const report = (state) => ({ state, mode, reclaimedBytes: Math.max(0, before - bytes(path23) - bytes(path23 + "-wal")) });
44335
44829
  try {
44336
44830
  db2.exec("PRAGMA busy_timeout=0");
44337
44831
  mode = Number(db2.prepare("PRAGMA auto_vacuum").get().auto_vacuum) === 2 ? "incremental" : "bootstrap";
@@ -44341,10 +44835,10 @@ async function runSqlitePhysicalMaintenance(path22, options = {}) {
44341
44835
  const pageSize = Number(db2.prepare("PRAGMA page_size").get().page_size);
44342
44836
  const pages = Number(db2.prepare("PRAGMA page_count").get().page_count);
44343
44837
  const free = Number(db2.prepare("PRAGMA freelist_count").get().freelist_count);
44344
- const oversized = bytes(path22) > pages * pageSize + 1024 * 1024;
44838
+ const oversized = bytes(path23) > pages * pageSize + 1024 * 1024;
44345
44839
  if (!oversized && (free * pageSize < minimum || free / Math.max(1, pages) < ratio)) return report("idle");
44346
44840
  if (mode === "bootstrap" || oversized) {
44347
- const disk = statfsSync2(dirname26(path22));
44841
+ const disk = statfsSync2(dirname26(path23));
44348
44842
  if (disk.bavail * disk.bsize < (pages - free) * pageSize * 2 + 64 * 1024 * 1024) return report("deferred");
44349
44843
  if (!allowed()) return report("deferred");
44350
44844
  options.onPhase?.("vacuum");
@@ -44363,7 +44857,7 @@ async function runSqlitePhysicalMaintenance(path22, options = {}) {
44363
44857
  }
44364
44858
  const finalCheckpoint = db2.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get();
44365
44859
  const finalPages = Number(db2.prepare("PRAGMA page_count").get().page_count);
44366
- if (finalCheckpoint.busy || bytes(path22) > finalPages * pageSize + 1024 * 1024) return report("deferred");
44860
+ if (finalCheckpoint.busy || bytes(path23) > finalPages * pageSize + 1024 * 1024) return report("deferred");
44367
44861
  return report("complete");
44368
44862
  } catch (error) {
44369
44863
  if (/database is locked|SQLITE_BUSY|SQLITE_LOCKED/i.test(String(error))) return report("deferred");
@@ -44374,9 +44868,9 @@ async function runSqlitePhysicalMaintenance(path22, options = {}) {
44374
44868
  }
44375
44869
  if (process.argv.includes("--sqlite-checkpoint")) {
44376
44870
  const flag2 = process.argv.indexOf("--sqlite-checkpoint");
44377
- const path22 = process.argv[flag2 + 1], stateDir2 = process.argv[flag2 + 2];
44871
+ const path23 = process.argv[flag2 + 1], stateDir2 = process.argv[flag2 + 2];
44378
44872
  registerRuntimeWriter(stateDir2, "sqlite-checkpoint");
44379
- const db2 = openPhysicalMaintenanceDatabase(path22, stateDir2);
44873
+ const db2 = openPhysicalMaintenanceDatabase(path23, stateDir2);
44380
44874
  try {
44381
44875
  db2.exec("PRAGMA busy_timeout=15000");
44382
44876
  console.log("wal checkpoint " + JSON.stringify(db2.prepare("PRAGMA wal_checkpoint(TRUNCATE)").get()));
@@ -44388,7 +44882,7 @@ if (process.argv.includes("--sqlite-checkpoint")) {
44388
44882
  }
44389
44883
  }
44390
44884
  if (process.argv.includes("--sqlite-maintenance")) {
44391
- const flag2 = process.argv.indexOf("--sqlite-maintenance"), path22 = resolve20(process.argv[flag2 + 1] ?? "");
44885
+ const flag2 = process.argv.indexOf("--sqlite-maintenance"), path23 = resolve20(process.argv[flag2 + 1] ?? "");
44392
44886
  if (!process.argv[flag2 + 1]) throw new Error("SQLITE_MAINTENANCE_PATH_REQUIRED");
44393
44887
  const config = process.argv[flag2 + 2] ? JSON.parse(process.argv[flag2 + 2]) : {};
44394
44888
  if (!config.stateDir) throw new Error("SQLITE_MAINTENANCE_STATE_DIR_REQUIRED");
@@ -44408,9 +44902,9 @@ if (process.argv.includes("--sqlite-maintenance")) {
44408
44902
  }
44409
44903
  if (cancel) process.kill(process.pid, 'SIGTERM')
44410
44904
  }, 100)
44411
- `, { eval: true, workerData: { path: path22, ownerPid: process.connected ? process.ppid : null } });
44905
+ `, { eval: true, workerData: { path: path23, ownerPid: process.connected ? process.ppid : null } });
44412
44906
  try {
44413
- console.log(JSON.stringify(await runSqlitePhysicalMaintenance(path22, {
44907
+ console.log(JSON.stringify(await runSqlitePhysicalMaintenance(path23, {
44414
44908
  ...config,
44415
44909
  onPhase: (phase) => {
44416
44910
  if (process.connected) process.send?.({ type: "sqliteMaintenancePhase", phase });
@@ -44452,9 +44946,9 @@ if (process.argv.includes("--validate-topics-import-live")) {
44452
44946
  }
44453
44947
 
44454
44948
  // src/bg/sqlite-maintenance.ts
44455
- var size = (path22) => {
44949
+ var size = (path23) => {
44456
44950
  try {
44457
- return statSync6(path22).size;
44951
+ return statSync6(path23).size;
44458
44952
  } catch (error) {
44459
44953
  if (error.code !== "ENOENT") throw error;
44460
44954
  return 0;
@@ -44469,7 +44963,7 @@ function live(pid) {
44469
44963
  }
44470
44964
  }
44471
44965
  function createSqliteMaintenance(stateDir2, options = {}) {
44472
- const path22 = join49(stateDir2, "mem7", "index", "mem7.db"), marker = join49(stateDir2, "mem7", "index", ".sqlite-maintenance.json");
44966
+ const path23 = join49(stateDir2, "mem7", "index", "mem7.db"), marker = join49(stateDir2, "mem7", "index", ".sqlite-maintenance.json");
44473
44967
  let child, completion, timer;
44474
44968
  let nextCheck = Date.now() + (options.firstRunDelayMs ?? 18e4), stopped = false;
44475
44969
  const idle = options.idleMs ?? 6e4;
@@ -44491,12 +44985,12 @@ function createSqliteMaintenance(stateDir2, options = {}) {
44491
44985
  const poll = () => {
44492
44986
  try {
44493
44987
  if (child) {
44494
- if (stopped || intakePendingForDatabase(path22) || options.shouldRun?.() === false) void interrupt();
44988
+ if (stopped || intakePendingForDatabase(path23) || options.shouldRun?.() === false) void interrupt();
44495
44989
  return;
44496
44990
  }
44497
44991
  if (stopped || Date.now() < nextCheck || options.shouldRun?.() === false) return;
44498
44992
  nextCheck = Date.now() + (options.checkIntervalMs ?? 6e4);
44499
- if (!existsSync23(path22) || intakePendingForDatabase(path22)) return;
44993
+ if (!existsSync23(path23) || intakePendingForDatabase(path23)) return;
44500
44994
  if (Date.now() - lastRequest < idle) return;
44501
44995
  if (existsSync23(marker)) {
44502
44996
  let previous;
@@ -44507,14 +45001,14 @@ function createSqliteMaintenance(stateDir2, options = {}) {
44507
45001
  if (Number.isSafeInteger(previous?.pid) && previous.pid > 0 && live(previous.pid) && Number.isSafeInteger(previous.startedAt) && Date.now() - previous.startedAt < 24e4) return;
44508
45002
  unlinkSync7(marker);
44509
45003
  }
44510
- const db2 = new DatabaseSync20(path22, { readOnly: true });
45004
+ const db2 = new DatabaseSync20(path23, { readOnly: true });
44511
45005
  let eligible = false;
44512
45006
  try {
44513
45007
  db2.exec("PRAGMA query_only=ON");
44514
45008
  const pageSize = Number(db2.prepare("PRAGMA page_size").get().page_size);
44515
45009
  const pages = Number(db2.prepare("PRAGMA page_count").get().page_count);
44516
45010
  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;
45011
+ 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
45012
  } finally {
44519
45013
  db2.close();
44520
45014
  }
@@ -44527,7 +45021,7 @@ function createSqliteMaintenance(stateDir2, options = {}) {
44527
45021
  windowsHide: true,
44528
45022
  execArgv: entry.endsWith(".ts") ? ["--import", "tsx"] : []
44529
45023
  };
44530
- child = fork(entry, ["--sqlite-maintenance", path22, JSON.stringify({ stateDir: stateDir2, minFreeBytes: options.minFreeBytes })], launchOptions);
45024
+ child = fork(entry, ["--sqlite-maintenance", path23, JSON.stringify({ stateDir: stateDir2, minFreeBytes: options.minFreeBytes })], launchOptions);
44531
45025
  console.log("[bg-worker] SQLite physical reclaim started");
44532
45026
  const current2 = child;
44533
45027
  let output = "", errors2 = "";
@@ -44612,6 +45106,7 @@ function startMem7Worker(config, fallback, options = {}) {
44612
45106
  let lastPipelineMs = 0;
44613
45107
  let lastCheckpointMs = 0;
44614
45108
  let lastBackupCleanupMs = 0;
45109
+ let lastTopicChunksMs = Date.now() - 36e5 + 5 * 6e4;
44615
45110
  const scanSchedule = createOpportunityScanSchedule(now2());
44616
45111
  const completedScanScopes = /* @__PURE__ */ new Set();
44617
45112
  const scan = async (store, busy = false) => {
@@ -44654,10 +45149,10 @@ function startMem7Worker(config, fallback, options = {}) {
44654
45149
  }
44655
45150
  if (!options.isBusy?.() && Date.now() - lastCheckpointMs >= 6e5) {
44656
45151
  lastCheckpointMs = Date.now();
44657
- const dbPath = join52(mem7Root(stateDir2), "index", "mem7.db");
45152
+ const dbPath = join53(mem7Root(stateDir2), "index", "mem7.db");
44658
45153
  const built = fileURLToPath14(new URL("./sqlite-maintenance-worker.mjs", import.meta.url));
44659
45154
  const source = fileURLToPath14(new URL("../mem7/sqlite-maintenance-worker.ts", import.meta.url));
44660
- const entry = existsSync25(built) ? built : source;
45155
+ const entry = existsSync26(built) ? built : source;
44661
45156
  execFile2(process.execPath, [...entry.endsWith(".ts") ? ["--import", "tsx"] : [], entry, "--sqlite-checkpoint", dbPath, stateDir2], { timeout: 18e4, windowsHide: true }, (error, stdout) => {
44662
45157
  if (error) console.warn(`[bg-worker] wal checkpoint \u8F85\u52A9\u8FDB\u7A0B\u5931\u8D25: ${error.message}`);
44663
45158
  else console.log(`[bg-worker] ${(stdout || "").trim()}`);
@@ -44671,12 +45166,12 @@ function startMem7Worker(config, fallback, options = {}) {
44671
45166
  const recoveredTurns = store.hostTurns.recoverInterrupted();
44672
45167
  if (recoveredTurns) console.log(`[bg-worker] abandoned host turns reconciled=${recoveredTurns}`);
44673
45168
  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) });
45169
+ 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
45170
  if (retention.results || retention.payloads) console.log(`[bg-worker] job retention results=${retention.results} inputs=${retention.payloads} archived=${retention.archivedInputs} logicalBytes=${retention.bytesReclaimed}`);
44676
45171
  } catch (error) {
44677
45172
  console.warn(`[bg-worker] job retention deferred: ${error?.message ?? error}`);
44678
45173
  }
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);
45174
+ 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
45175
  if (Date.now() - lastBackupCleanupMs >= 36e5 && backupCleanupAllowed()) {
44681
45176
  lastBackupCleanupMs = Date.now();
44682
45177
  try {
@@ -44686,6 +45181,28 @@ function startMem7Worker(config, fallback, options = {}) {
44686
45181
  console.warn(`[bg-worker] backup retention deferred: ${error?.message ?? error}`);
44687
45182
  }
44688
45183
  }
45184
+ if (Date.now() - lastTopicChunksMs >= 36e5 && backupCleanupAllowed()) {
45185
+ lastTopicChunksMs = Date.now();
45186
+ const workspace2 = String(config.get("workspace") ?? "");
45187
+ const topicsDir = workspace2 ? getAutoMemPath(workspace2) : "";
45188
+ const embedding = resolveWorkerEmbedding(config);
45189
+ if (topicsDir && embedding) void (async () => {
45190
+ try {
45191
+ const { importTopicChunks: importTopicChunks2 } = await Promise.resolve().then(() => (init_topics_chunks(), topics_chunks_exports));
45192
+ const report = await importTopicChunks2({
45193
+ stateDir: stateDir2,
45194
+ topicsDir,
45195
+ userId: mem7UserId((key5) => config.get(key5)),
45196
+ embed: (texts) => embedBatch(embedding, texts, { read: true }),
45197
+ concurrency: 2
45198
+ });
45199
+ if (report.failed) console.warn(`[bg-worker] topics chunks failed=${report.failed} errors=${report.errors.slice(0, 2).join(" | ")}`);
45200
+ else if (report.chunks || report.deleted) console.log(`[bg-worker] topics chunks files=${report.files} chunks=${report.chunks} deleted=${report.deleted}`);
45201
+ } catch (error) {
45202
+ console.warn(`[bg-worker] topics chunks deferred: ${error?.message ?? error}`);
45203
+ }
45204
+ })();
45205
+ }
44689
45206
  const cleanupMs = Math.round(performance.now() - started);
44690
45207
  if (cleanupMs >= 1e3) console.log(`[bg-worker] cleanup ${cleanupMs}ms`);
44691
45208
  const agentName = mem7AgentName((key5) => config.get(key5));
@@ -44693,7 +45210,7 @@ function startMem7Worker(config, fallback, options = {}) {
44693
45210
  let relationshipGraph;
44694
45211
  if (config.get("mem7.relationshipCognition") !== false) {
44695
45212
  if (options.relationshipGraphPath) {
44696
- if (existsSync25(options.relationshipGraphPath)) {
45213
+ if (existsSync26(options.relationshipGraphPath)) {
44697
45214
  try {
44698
45215
  relationshipGraph = workerGraph(options.relationshipGraphPath, store).graph;
44699
45216
  relationshipGraph.ensureFresh();
@@ -44781,7 +45298,7 @@ function startMem7Worker(config, fallback, options = {}) {
44781
45298
  if (!store || !stateDir2 || config.get("mem7.enabled") !== true) return;
44782
45299
  try {
44783
45300
  if (physicalMaintenance?.running()) {
44784
- if (!intakePendingForDatabase(join52(mem7Root(stateDir2), "index", "mem7.db"))) return;
45301
+ if (!intakePendingForDatabase(join53(mem7Root(stateDir2), "index", "mem7.db"))) return;
44785
45302
  await physicalMaintenance.interrupt();
44786
45303
  }
44787
45304
  const applied = drainIntakeSpool(stateDir2, store, 50);
@@ -44789,10 +45306,10 @@ function startMem7Worker(config, fallback, options = {}) {
44789
45306
  await physicalMaintenance?.interrupt();
44790
45307
  void pipeline.tick();
44791
45308
  }
44792
- if (!activeStore && !options.isBusy?.() && !intakePendingForDatabase(join52(mem7Root(stateDir2), "index", "mem7.db"))) {
45309
+ if (!activeStore && !options.isBusy?.() && !intakePendingForDatabase(join53(mem7Root(stateDir2), "index", "mem7.db"))) {
44793
45310
  const retired = store.retireGraphPlanAuditsBatch();
44794
45311
  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")) });
45312
+ await store.pruneTerminalJobData({ shouldRun: () => !stopping && !options.isBusy?.() && !activeStore && !intakePendingForDatabase(join53(mem7Root(stateDir2), "index", "mem7.db")) });
44796
45313
  }
44797
45314
  } catch (error) {
44798
45315
  console.warn(`[bg-worker] intake service failed: ${error?.message ?? error}`);
@@ -45188,7 +45705,7 @@ var relationshipGraphPath = graphFlag >= 0 ? resolve25(args[graphFlag + 1]) : vo
45188
45705
  var mainFlag = args.indexOf("--main-model");
45189
45706
  var mainModelRef = mainFlag >= 0 ? args[mainFlag + 1] : void 0;
45190
45707
  var workspaceFlag = args.indexOf("--workspace");
45191
- if (!configPath || !existsSync32(configPath)) {
45708
+ if (!configPath || !existsSync34(configPath)) {
45192
45709
  console.error("[bg-worker] usage: node dist/bg-worker.mjs --engine-config <path>");
45193
45710
  process.exit(1);
45194
45711
  }