engine7 7.1.147 → 7.1.149

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.
@@ -236,14 +236,14 @@ var init_live = __esm({
236
236
  }
237
237
  /** 把改动写回 config 文件对应段(找不到文件路径则只内存生效)。返回是否真的落盘。 */
238
238
  async persistToFile(dotPath, val, atomic = false) {
239
- const fs8 = await import("node:fs");
239
+ const fs9 = await import("node:fs");
240
240
  const cfgPath = this.current?._configFilePath;
241
- if (!cfgPath || !fs8.existsSync(cfgPath)) {
241
+ if (!cfgPath || !fs9.existsSync(cfgPath)) {
242
242
  console.warn(`[liveConfig] set: no config file path, in-memory only (${dotPath})`);
243
243
  return false;
244
244
  }
245
245
  try {
246
- const raw = JSON.parse(fs8.readFileSync(cfgPath, "utf-8"));
246
+ const raw = JSON.parse(fs9.readFileSync(cfgPath, "utf-8"));
247
247
  const keys = dotPath.split(".");
248
248
  let o = raw;
249
249
  for (let i = 0; i < keys.length - 1; i++) {
@@ -253,7 +253,7 @@ var init_live = __esm({
253
253
  o[keys[keys.length - 1]] = val;
254
254
  if (atomic) {
255
255
  writeConfigAtomic(cfgPath, raw);
256
- } else fs8.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
256
+ } else fs9.writeFileSync(cfgPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
257
257
  const lastKey = keys[keys.length - 1].toLowerCase();
258
258
  const looksSecret = /(^|[-_.])(key|token|secret|passwd|password|passphrase|authorization|auth|cred)([-_.]|$)/.test(lastKey);
259
259
  const shown = val !== null && typeof val === "object" ? "{\u2026}" : looksSecret ? "{\u2026}" : JSON.stringify(val);
@@ -279,14 +279,14 @@ var init_live = __esm({
279
279
  import { randomUUID, verify } from "node:crypto";
280
280
  import { constants, closeSync, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync } from "node:fs";
281
281
  import { basename, dirname, join, resolve } from "node:path";
282
- function assertPrivateDirectory(path7) {
283
- const stat2 = lstatSync(path7);
282
+ function assertPrivateDirectory(path8) {
283
+ const stat2 = lstatSync(path8);
284
284
  if (!stat2.isDirectory() || stat2.isSymbolicLink() || process.platform !== "win32" && (stat2.uid !== process.getuid() || stat2.mode & 63)) throw new Error("TRAVEL_PRIVATE_CONTROL_REQUIRED");
285
285
  }
286
- function readPrivateFile(path7, maximum) {
287
- const before = lstatSync(path7);
286
+ function readPrivateFile(path8, maximum) {
287
+ const before = lstatSync(path8);
288
288
  if (!before.isFile() || before.isSymbolicLink() || process.platform !== "win32" && (before.uid !== process.getuid() || before.mode & 63)) throw new Error("TRAVEL_PRIVATE_CONTROL_REQUIRED");
289
- const fd = openSync(path7, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
289
+ const fd = openSync(path8, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
290
290
  try {
291
291
  if (fstatSync(fd).size > maximum) throw new Error("TRAVEL_INVALID_CONTROL");
292
292
  return readFileSync(fd);
@@ -294,12 +294,12 @@ function readPrivateFile(path7, maximum) {
294
294
  closeSync(fd);
295
295
  }
296
296
  }
297
- function writeControl(path7, value) {
298
- const temporary = path7 + "." + randomUUID() + ".tmp";
297
+ function writeControl(path8, value) {
298
+ const temporary = path8 + "." + randomUUID() + ".tmp";
299
299
  writeFileSync(temporary, JSON.stringify(value), { mode: 384, flag: "wx", flush: true });
300
- renameSync(temporary, path7);
300
+ renameSync(temporary, path8);
301
301
  if (process.platform !== "win32") {
302
- const fd = openSync(dirname(path7), "r");
302
+ const fd = openSync(dirname(path8), "r");
303
303
  try {
304
304
  fsyncSync(fd);
305
305
  } finally {
@@ -1179,9 +1179,9 @@ function assertPrivateStat(stat2, directory2) {
1179
1179
  if ((directory2 ? !stat2.isDirectory() : !stat2.isFile()) || process.platform !== "win32" && ((stat2.mode & 63) !== 0 || stat2.uid !== process.getuid?.()))
1180
1180
  throw new Error("KEY_SERVICE_PRIVATE_PATH_REQUIRED");
1181
1181
  }
1182
- function readPrivateFile2(path7, maximumBytes = 65536) {
1183
- assertPrivateStat(lstatSync3(path7), false);
1184
- const fd = openSync3(path7, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
1182
+ function readPrivateFile2(path8, maximumBytes = 65536) {
1183
+ assertPrivateStat(lstatSync3(path8), false);
1184
+ const fd = openSync3(path8, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
1185
1185
  try {
1186
1186
  const stat2 = fstatSync2(fd);
1187
1187
  assertPrivateStat(stat2, false);
@@ -1211,23 +1211,23 @@ import {
1211
1211
  mkdirSync as mkdirSync4
1212
1212
  } from "node:fs";
1213
1213
  import { join as join3, dirname as dirname2, resolve as resolve2 } from "node:path";
1214
- function assertPrivateDirectory2(path7) {
1215
- const info = lstatSync4(path7);
1216
- if (!info.isDirectory() || info.isSymbolicLink() || realpathSync2(path7) !== resolve2(path7) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
1214
+ function assertPrivateDirectory2(path8) {
1215
+ const info = lstatSync4(path8);
1216
+ if (!info.isDirectory() || info.isSymbolicLink() || realpathSync2(path8) !== resolve2(path8) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
1217
1217
  throw new Error("PUBLICATION_PRIVATE_DIRECTORY_REQUIRED");
1218
1218
  }
1219
- function syncDir(path7) {
1219
+ function syncDir(path8) {
1220
1220
  if (process.platform === "win32") return;
1221
- const fd = openSync4(path7, constants4.O_RDONLY);
1221
+ const fd = openSync4(path8, constants4.O_RDONLY);
1222
1222
  try {
1223
1223
  fsyncSync3(fd);
1224
1224
  } finally {
1225
1225
  closeSync4(fd);
1226
1226
  }
1227
1227
  }
1228
- function preparePrivateDirectory(path7) {
1228
+ function preparePrivateDirectory(path8) {
1229
1229
  const missing = [];
1230
- let parent = resolve2(path7);
1230
+ let parent = resolve2(path8);
1231
1231
  for (; ; ) {
1232
1232
  try {
1233
1233
  lstatSync4(parent);
@@ -1248,7 +1248,7 @@ function preparePrivateDirectory(path7) {
1248
1248
  assertPrivateDirectory2(directory2);
1249
1249
  syncDir(dirname2(directory2));
1250
1250
  }
1251
- assertPrivateDirectory2(path7);
1251
+ assertPrivateDirectory2(path8);
1252
1252
  }
1253
1253
  var PUBLICATION_CHUNK_BYTES, MAGIC, INLINE_BYTES, noFollow;
1254
1254
  var init_publication_objects = __esm({
@@ -2987,7 +2987,7 @@ function textColumnOf(kind) {
2987
2987
  return "fact";
2988
2988
  }
2989
2989
  }
2990
- var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, RRF_K, warnedFts, warnedVecIdx, bootAt, schemasCache, Mem7VectorStore;
2990
+ var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
2991
2991
  var init_vector_store = __esm({
2992
2992
  "src/mem7/core/vector-store.ts"() {
2993
2993
  "use strict";
@@ -3021,6 +3021,7 @@ var init_vector_store = __esm({
3021
3021
  RRF_K = 60;
3022
3022
  warnedFts = /* @__PURE__ */ new Set();
3023
3023
  warnedVecIdx = /* @__PURE__ */ new Set();
3024
+ incompatibleIndexSegments = (error) => error instanceof Error && error.message.includes("Index type URL should be present and identical across all segments");
3024
3025
  bootAt = Date.now();
3025
3026
  schemasCache = null;
3026
3027
  Mem7VectorStore = class {
@@ -3190,18 +3191,18 @@ var init_vector_store = __esm({
3190
3191
  * 快照版本——18:46 实测:香港相关 episode 在库、探针 BM25 可召回,线上 hybrid 却
3191
3192
  * 0 命中,时序与连续 3 次 conflict 吻合)。
3192
3193
  */
3193
- async ensureFtsIndexes(kind, tbl) {
3194
+ async ensureFtsIndexes(kind, tbl, indices) {
3194
3195
  const lance = await loadLance();
3195
3196
  if (!lance) return;
3196
- let existing = null;
3197
+ let existing;
3198
+ try {
3199
+ existing = new Set((indices ?? await tbl.listIndices()).filter((index) => index.indexType === "FTS").flatMap((index) => index.columns));
3200
+ } catch (err) {
3201
+ console.warn(`[mem7] FTS index check failed for ${kind}: ${err instanceof Error ? err.message : err}`);
3202
+ return;
3203
+ }
3197
3204
  for (const col of BM25_FIELDS[kind]) {
3198
3205
  try {
3199
- if (existing === null) {
3200
- existing = /* @__PURE__ */ new Set();
3201
- for (const idx of await tbl.listIndices()) {
3202
- if (idx.indexType === "FTS") for (const c of idx.columns) existing.add(c);
3203
- }
3204
- }
3205
3206
  if (existing.has(col)) continue;
3206
3207
  assertRuntimeAuthority(this.stateDir, "WRITE");
3207
3208
  await tbl.createIndex(col, {
@@ -3220,6 +3221,34 @@ var init_vector_store = __esm({
3220
3221
  }
3221
3222
  }
3222
3223
  }
3224
+ /** Called by the idle writer. Intel's all-in-one optimize can append an unreadable ANN delta
3225
+ * to a returned table, even with no new rows. Keep the existing ANN and let queries scan its tail. */
3226
+ async maintainIndexes(kind, canStart) {
3227
+ if (this.options.readOnly) throw new Error("MEM7_VECTOR_READ_ONLY");
3228
+ const tbl = await this.table(kind);
3229
+ if (!canStart()) return;
3230
+ let indices;
3231
+ try {
3232
+ indices = await tbl.listIndices();
3233
+ } catch (error) {
3234
+ if (isIntelMac || !incompatibleIndexSegments(error)) throw error;
3235
+ const statsError = await tbl.indexStats("vector_idx").then(() => void 0, (failure) => failure);
3236
+ if (!incompatibleIndexSegments(statsError)) throw error;
3237
+ const lance = await loadLance();
3238
+ if (!lance || typeof lance.Index?.hnswSq !== "function") throw error;
3239
+ if (!canStart()) return;
3240
+ assertRuntimeAuthority(this.stateDir, "WRITE");
3241
+ await tbl.createIndex("vector", { config: lance.Index.hnswSq({ distanceType: "cosine" }), replace: true });
3242
+ if (this.tables.get(kind) === tbl) this.vectorIndexesReady.add(kind);
3243
+ await this.ensureFtsIndexes(kind, tbl, await tbl.listIndices());
3244
+ console.log(`[mem7] ANN \u7D22\u5F15\u517C\u5BB9\u4FEE\u590D\u5B8C\u6210\uFF08${kind}.vector\uFF09`);
3245
+ return "repaired";
3246
+ }
3247
+ if (isIntelMac && indices.some((index) => index.columns.includes("vector"))) return "preserved";
3248
+ if (!canStart()) return;
3249
+ assertRuntimeAuthority(this.stateDir, "WRITE");
3250
+ return tbl.optimize();
3251
+ }
3223
3252
  /**
3224
3253
  * ANN 向量索引(1004 妹妹 review 版):
3225
3254
  * - ★ **HNSW_SQ + distanceType:'cosine'**——距离必须配 cosine,不传默认 L2 与查询不兼容会
@@ -3968,6 +3997,45 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
3968
3997
  }
3969
3998
  });
3970
3999
 
4000
+ // src/mem7/core/state/watermarks.ts
4001
+ function readRetractionSeq(db, scope) {
4002
+ return Number(db.prepare(`SELECT COALESCE(MAX(event_seq),0) seq FROM memory_state_outbox WHERE scope_id=? AND ${RETRACTED}`).get(scope)?.seq ?? 0);
4003
+ }
4004
+ function readRetractionsSince(db, scope, sinceSeq) {
4005
+ return db.prepare(`SELECT event_seq, payload_json FROM memory_state_outbox WHERE scope_id=? AND ${RETRACTED} AND event_seq>? ORDER BY event_seq`).all(scope, sinceSeq).map((row) => {
4006
+ const payload = JSON.parse(row.payload_json);
4007
+ const aggregate = !payload.targetKind || payload.targetKind === "source" ? [payload.aggregateId] : [];
4008
+ return { eventSeq: Number(row.event_seq), sourceIds: [.../* @__PURE__ */ new Set([...payload.sourceIds ?? [], ...aggregate])].filter((id) => Boolean(id)) };
4009
+ });
4010
+ }
4011
+ function readSourceSeq(db, scope, sourceId) {
4012
+ const row = db.prepare("SELECT source_seq FROM memory_sources WHERE scope_id=? AND source_id=?").get(scope, sourceId);
4013
+ return row && Number.isSafeInteger(row.source_seq) ? Number(row.source_seq) : null;
4014
+ }
4015
+ function deletionHits(db, scope, events, sourceWatermark, sourceSeqs) {
4016
+ return events.some((event) => event.sourceIds.some((id) => {
4017
+ const key4 = JSON.stringify([scope, id]);
4018
+ if (!sourceSeqs.has(key4)) sourceSeqs.set(key4, readSourceSeq(db, scope, id));
4019
+ const seq = sourceSeqs.get(key4);
4020
+ return seq === null || seq <= sourceWatermark;
4021
+ }));
4022
+ }
4023
+ function deletedWithinView(db, scope, sinceSeq, sourceWatermark, cache) {
4024
+ if (!cache.latest.has(scope)) cache.latest.set(scope, readRetractionSeq(db, scope));
4025
+ if (cache.latest.get(scope) <= sinceSeq) return false;
4026
+ const key4 = JSON.stringify([scope, sinceSeq]);
4027
+ if (!cache.events.has(key4)) cache.events.set(key4, readRetractionsSince(db, scope, sinceSeq));
4028
+ return deletionHits(db, scope, cache.events.get(key4), sourceWatermark, cache.sourceSeqs);
4029
+ }
4030
+ var emptyRetractionCache, RETRACTED;
4031
+ var init_watermarks = __esm({
4032
+ "src/mem7/core/state/watermarks.ts"() {
4033
+ "use strict";
4034
+ emptyRetractionCache = () => ({ latest: /* @__PURE__ */ new Map(), events: /* @__PURE__ */ new Map(), sourceSeqs: /* @__PURE__ */ new Map() });
4035
+ RETRACTED = `kind IN ('evidence.retracted','memory.deleted')`;
4036
+ }
4037
+ });
4038
+
3971
4039
  // src/mem7/core/state/predicates.ts
3972
4040
  function hasReportedAttribution(text2, value, mentions) {
3973
4041
  const ref = value.attributionQuote;
@@ -4082,6 +4150,7 @@ var init_source_store = __esm({
4082
4150
  init_dependencies();
4083
4151
  init_knowledge_history();
4084
4152
  init_read_budget();
4153
+ init_watermarks();
4085
4154
  init_interpretation_impact();
4086
4155
  init_conversation_text();
4087
4156
  SOURCE_SCHEMA = `
@@ -4412,6 +4481,20 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
4412
4481
  const row = this.db.prepare("SELECT fact_revision,source_seq,interpreted_seq FROM memory_scopes WHERE scope_id=?").get(scopeId(scope));
4413
4482
  return { factRevision: Number(row?.fact_revision ?? 0), sourceSeq: Number(row?.source_seq ?? 0), interpretedSeq: Number(row?.interpreted_seq ?? 0) };
4414
4483
  }
4484
+ /** Latest deletion or retraction event of the scope; 0 when none ever happened. */
4485
+ retractionSeq(scope) {
4486
+ return readRetractionSeq(this.db, scopeId(scope));
4487
+ }
4488
+ /** Sequence of a source whatever its status. get() hides deleted sources; this does not. */
4489
+ sourceSeqOf(scope, sourceId) {
4490
+ return readSourceSeq(this.db, scopeId(scope), sourceId);
4491
+ }
4492
+ /** A deletion after `sinceSeq` removed a source the node could have seen. One indexed lookup per scope
4493
+ * for the latest deletion, then one event query per (scope, watermark) per cache. */
4494
+ deletedWithinView(scope, sinceSeq, sourceWatermark, cache) {
4495
+ checkMemoryReadBudget();
4496
+ return deletedWithinView(this.db, scopeId(scope), sinceSeq, sourceWatermark, cache);
4497
+ }
4415
4498
  contextRevision(scope) {
4416
4499
  return Number(this.db.prepare("SELECT context_revision FROM memory_scopes WHERE scope_id=?").get(scopeId(scope))?.context_revision ?? 0);
4417
4500
  }
@@ -4944,8 +5027,8 @@ var init_recovery_deletion = __esm({
4944
5027
  const { owners, parents } = this.links(table, row);
4945
5028
  for (const parent of parents) for (const owner of owners) this.edge(parent, owner);
4946
5029
  if (table === "memory_artifact_publications") {
4947
- const medium = text(row, "medium"), path7 = text(row, "path"), physicalId = text(row, "physical_id"), kind = text(row, "kind");
4948
- const identity = medium === "markdown" && path7 ? "file:mem7/" + path7 : medium === "vector" && physicalId && kind ? "vector:" + kind + "/rows/" + createHash8("sha256").update(physicalId).digest("hex") + ".arrow" : void 0;
5030
+ const medium = text(row, "medium"), path8 = text(row, "path"), physicalId = text(row, "physical_id"), kind = text(row, "kind");
5031
+ const identity = medium === "markdown" && path8 ? "file:mem7/" + path8 : medium === "vector" && physicalId && kind ? "vector:" + kind + "/rows/" + createHash8("sha256").update(physicalId).digest("hex") + ".arrow" : void 0;
4949
5032
  if (identity) {
4950
5033
  const rows = this.artifactPaths.get(identity) ?? [];
4951
5034
  rows.push(row);
@@ -4953,8 +5036,8 @@ var init_recovery_deletion = __esm({
4953
5036
  }
4954
5037
  }
4955
5038
  }
4956
- blocksArtifactPath(kind, path7) {
4957
- const rows = this.artifactPaths.get(kind + ":" + path7);
5039
+ blocksArtifactPath(kind, path8) {
5040
+ const rows = this.artifactPaths.get(kind + ":" + path8);
4958
5041
  return rows?.some((row) => this.blocks("memory_artifact_publications", row));
4959
5042
  }
4960
5043
  blocks(table, row) {
@@ -5631,16 +5714,15 @@ function stripInjectedContext(text2) {
5631
5714
  function escapeRegExp(s) {
5632
5715
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5633
5716
  }
5634
- var SKILL_GATE_HINT_PREFIX, SYSTEM_REMINDER_BLOCK, INJECT_SECTION_HEADS, KNOWN_INJECTED_TEXT, INJECTED_LINE_PREFIXES, XML_BLOCK;
5717
+ var SYSTEM_REMINDER_BLOCK, INJECT_SECTION_HEADS, KNOWN_INJECTED_TEXT, INJECTED_LINE_PREFIXES, XML_BLOCK;
5635
5718
  var init_strip_injected = __esm({
5636
5719
  "src/messages/strip-injected.ts"() {
5637
5720
  "use strict";
5638
- SKILL_GATE_HINT_PREFIX = "\u8FD9\u6761\u6D88\u606F\u662F\u5F00\u53D1\u4EFB\u52A1";
5639
5721
  SYSTEM_REMINDER_BLOCK = /<system-reminder>[\s\S]*?<\/system-reminder>/g;
5640
5722
  INJECT_SECTION_HEADS = /^(本轮对话|当前情绪状态|当前模式)/;
5641
5723
  KNOWN_INJECTED_TEXT = [
5642
- SKILL_GATE_HINT_PREFIX,
5643
- // skill-gate hint 默认/自定义前缀(1007 现行)
5724
+ "\u8FD9\u6761\u6D88\u606F\u662F\u5F00\u53D1\u4EFB\u52A1",
5725
+ // 旧版 skill-gate 提示前缀,兼容未打标签的历史
5644
5726
  "\u5F00\u53D1\u4EFB\u52A1\u8DEF\u6807\uFF0C\u6309\u573A\u666F\u5BF9\u53F7\u5165\u5EA7",
5645
5727
  // skill-gate hint(0912 老文案,历史 JSONL 兼容)
5646
5728
  "\u3010\u5B9A\u65F6\u5FC3\u8DF3\u3011\u8BF7 read HEARTBEAT.md"
@@ -5974,7 +6056,7 @@ function recoverLegacyProjections(db, store, input, apply = false) {
5974
6056
  };
5975
6057
  const candidates = [];
5976
6058
  const duplicateIds = /* @__PURE__ */ new Set();
5977
- const inside2 = (path7) => path7 && !isAbsolute(path7) && path7 !== ".." && !path7.startsWith(`..${sep}`);
6059
+ const inside2 = (path8) => path8 && !isAbsolute(path8) && path8 !== ".." && !path8.startsWith(`..${sep}`);
5978
6060
  for (const relativePath of input.files) {
5979
6061
  const logical = resolve3(root, relativePath);
5980
6062
  let canonical3;
@@ -5988,10 +6070,10 @@ function recoverLegacyProjections(db, store, input, apply = false) {
5988
6070
  gap("projection_path_unverified");
5989
6071
  continue;
5990
6072
  }
5991
- const path7 = relative(root, canonical3).replace(/\\/g, "/");
6073
+ const path8 = relative(root, canonical3).replace(/\\/g, "/");
5992
6074
  const user = `users/${input.scope.ownerId}/`;
5993
6075
  const agent = store.ownerProjectionPath("agents", input.scope.ownerId, input.scope).replace(/\\/g, "/") + "/";
5994
- const kind = path7.startsWith(`${user}episodes/`) && /\/episode-\d{4}-\d{2}-\d{2}\.md$/.test(path7) ? "episode" : path7.startsWith(`${user}.atomic_facts/`) && /\/atomic_fact-\d{4}-\d{2}-\d{2}\.md$/.test(path7) ? "atomic_fact" : path7.startsWith(`${user}.foresights/`) && /\/foresight-\d{4}-\d{2}-\d{2}\.md$/.test(path7) ? "foresight" : path7.startsWith(`${agent}.cases/`) && /\/agent_case-\d{4}-\d{2}-\d{2}\.md$/.test(path7) ? "agent_case" : void 0;
6076
+ const kind = path8.startsWith(`${user}episodes/`) && /\/episode-\d{4}-\d{2}-\d{2}\.md$/.test(path8) ? "episode" : path8.startsWith(`${user}.atomic_facts/`) && /\/atomic_fact-\d{4}-\d{2}-\d{2}\.md$/.test(path8) ? "atomic_fact" : path8.startsWith(`${user}.foresights/`) && /\/foresight-\d{4}-\d{2}-\d{2}\.md$/.test(path8) ? "foresight" : path8.startsWith(`${agent}.cases/`) && /\/agent_case-\d{4}-\d{2}-\d{2}\.md$/.test(path8) ? "agent_case" : void 0;
5995
6077
  if (!kind) {
5996
6078
  gap("projection_kind_or_owner_unverified");
5997
6079
  continue;
@@ -6028,9 +6110,9 @@ function recoverLegacyProjections(db, store, input, apply = false) {
6028
6110
  continue;
6029
6111
  }
6030
6112
  const previous = db.prepare("SELECT * FROM memory_legacy_projection_maps WHERE scope_id=? AND kind=? AND entry_id=?").get(key4, kind, match[1]);
6031
- const target = join6(store.mem7RootPath(), path7);
6113
+ const target = join6(store.mem7RootPath(), path8);
6032
6114
  if (previous) {
6033
- if (previous.source_file_hash !== fileHash || previous.parent_id !== parent || previous.source_relative_path !== path7 || !store.projectionMatches(input.scope, kind, match[1], target, block)) {
6115
+ if (previous.source_file_hash !== fileHash || previous.parent_id !== parent || previous.source_relative_path !== path8 || !store.projectionMatches(input.scope, kind, match[1], target, block)) {
6034
6116
  gap("projection_mapping_conflict");
6035
6117
  continue;
6036
6118
  }
@@ -6046,7 +6128,7 @@ function recoverLegacyProjections(db, store, input, apply = false) {
6046
6128
  candidates.push({
6047
6129
  file: canonical3,
6048
6130
  fileHash,
6049
- relativePath: path7,
6131
+ relativePath: path8,
6050
6132
  id: match[1],
6051
6133
  kind,
6052
6134
  parent,
@@ -7468,11 +7550,11 @@ function checkSeal(value) {
7468
7550
  const { digest: actual, ...body } = value ?? {};
7469
7551
  if (actual !== digest3(canonical(body))) throw new Error("MANIFEST_DIGEST_MISMATCH");
7470
7552
  }
7471
- function safeRelative(path7) {
7472
- return typeof path7 === "string" && !!path7 && !isAbsolute2(path7) && !/[:\\\x00-\x1f]/.test(path7) && path7.split("/").every((p) => p && p !== "." && p !== "..");
7553
+ function safeRelative(path8) {
7554
+ return typeof path8 === "string" && !!path8 && !isAbsolute2(path8) && !/[:\\\x00-\x1f]/.test(path8) && path8.split("/").every((p) => p && p !== "." && p !== "..");
7473
7555
  }
7474
- function unlinked(path7) {
7475
- let cursor = resolve4(path7);
7556
+ function unlinked(path8) {
7557
+ let cursor = resolve4(path8);
7476
7558
  for (; ; ) {
7477
7559
  try {
7478
7560
  if (lstatSync6(cursor).isSymbolicLink()) throw new Error("SYMLINK_PATH");
@@ -7480,12 +7562,12 @@ function unlinked(path7) {
7480
7562
  if (e.code !== "ENOENT") throw e;
7481
7563
  }
7482
7564
  const parent = dirname5(cursor);
7483
- if (parent === cursor) return resolve4(path7);
7565
+ if (parent === cursor) return resolve4(path8);
7484
7566
  cursor = parent;
7485
7567
  }
7486
7568
  }
7487
- function readJson(path7) {
7488
- return JSON.parse(readFileSync7(unlinked(path7), "utf8").replace(/^\uFEFF/, ""));
7569
+ function readJson(path8) {
7570
+ return JSON.parse(readFileSync7(unlinked(path8), "utf8").replace(/^\uFEFF/, ""));
7489
7571
  }
7490
7572
  function rawBytes(snapshot, record) {
7491
7573
  if (!/^[a-f0-9]{64}$/.test(record.sha256)) throw new Error("INVALID_OBJECT_REFERENCE");
@@ -7989,9 +8071,9 @@ function normalize3(input) {
7989
8071
  if (!input || !/^[a-f0-9]{64}$/.test(input.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
7990
8072
  return Object.freeze({ binding: normalizeBinding(input.binding), schemaHash: input.schemaHash });
7991
8073
  }
7992
- function directory(path7) {
7993
- const info = lstatSync7(path7);
7994
- if (!info.isDirectory() || info.isSymbolicLink() || realpathSync4(path7) !== resolve5(path7) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
8074
+ function directory(path8) {
8075
+ const info = lstatSync7(path8);
8076
+ if (!info.isDirectory() || info.isSymbolicLink() || realpathSync4(path8) !== resolve5(path8) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
7995
8077
  throw new Error("REPLICATION_REGISTRATION_INVALID");
7996
8078
  }
7997
8079
  function readRuntimeReplicationRegistration(stateDir2, component, key4) {
@@ -8300,10 +8382,10 @@ function installSQLiteWriteCapture(db, source) {
8300
8382
  if (db.isTransaction) throw new Error("REPLICATION_TRANSACTION_ALREADY_OPEN");
8301
8383
  const exec = db.exec, prepare = db.prepare;
8302
8384
  let active, failed = false, closed = false, reading = false;
8303
- let direct;
8385
+ let direct2;
8304
8386
  const check = () => {
8305
8387
  if (closed) throw new Error("REPLICATION_TRANSACTION_CLOSED");
8306
- direct?.assertOpen();
8388
+ direct2?.assertOpen();
8307
8389
  };
8308
8390
  const wrappedExec = function(sql) {
8309
8391
  check();
@@ -8374,10 +8456,10 @@ function installSQLiteWriteCapture(db, source) {
8374
8456
  db.prepare = checkedPrepare;
8375
8457
  const transaction = (operation) => {
8376
8458
  check();
8377
- if (db.isTransaction) return direct.scope(operation);
8459
+ if (db.isTransaction) return direct2.scope(operation);
8378
8460
  db.exec("BEGIN IMMEDIATE");
8379
8461
  try {
8380
- const result = direct.scope(operation);
8462
+ const result = direct2.scope(operation);
8381
8463
  if (result && typeof result.then === "function") throw new Error("REPLICATION_ASYNC_TRANSACTION");
8382
8464
  db.exec("COMMIT");
8383
8465
  return result;
@@ -8386,10 +8468,10 @@ function installSQLiteWriteCapture(db, source) {
8386
8468
  throw error;
8387
8469
  }
8388
8470
  };
8389
- direct = installAutocommitCapture(db, transaction);
8471
+ direct2 = installAutocommitCapture(db, transaction);
8390
8472
  return {
8391
8473
  assertOpen: check,
8392
- scope: (operation) => direct.scope(operation),
8474
+ scope: (operation) => direct2.scope(operation),
8393
8475
  transaction,
8394
8476
  close() {
8395
8477
  if (closed) return;
@@ -8398,7 +8480,7 @@ function installSQLiteWriteCapture(db, source) {
8398
8480
  source.endCapture(active);
8399
8481
  active = void 0;
8400
8482
  }
8401
- direct.close();
8483
+ direct2.close();
8402
8484
  db.prepare = prepare;
8403
8485
  db.exec = exec;
8404
8486
  closed = true;
@@ -8672,10 +8754,10 @@ function topicMatchesYear(dates, year) {
8672
8754
  function topicsHistoryRoot(b) {
8673
8755
  return unlinked(join13(b.stateDir, "topics-history", key3(b)));
8674
8756
  }
8675
- function parseTopicHistoryPath(path7) {
8676
- if (!path7.startsWith("topics-history://") || path7.length > 1e4) throw new Error("INVALID_HISTORY_REFERENCE");
8757
+ function parseTopicHistoryPath(path8) {
8758
+ if (!path8.startsWith("topics-history://") || path8.length > 1e4) throw new Error("INVALID_HISTORY_REFERENCE");
8677
8759
  try {
8678
- return JSON.parse(Buffer.from(path7.slice(17), "base64url").toString("utf8"));
8760
+ return JSON.parse(Buffer.from(path8.slice(17), "base64url").toString("utf8"));
8679
8761
  } catch {
8680
8762
  throw new Error("INVALID_HISTORY_REFERENCE");
8681
8763
  }
@@ -8702,19 +8784,19 @@ async function topicHistoryReadRevision(b, refs) {
8702
8784
  paths.add(join13(resolve7(b.topicsDir), ref.sourcePath));
8703
8785
  paths.add(join13(root, "forgotten", `${digest3(ref.sourcePath)}.json`));
8704
8786
  }
8705
- const stats = await Promise.all([...paths].sort().map(async (path7) => {
8787
+ const stats = await Promise.all([...paths].sort().map(async (path8) => {
8706
8788
  try {
8707
- const stat2 = await fs2.lstat(path7, { bigint: true });
8708
- return [path7, ...[stat2.dev, stat2.ino, stat2.mode, stat2.size, stat2.mtimeNs, stat2.ctimeNs].map(String)];
8789
+ const stat2 = await fs2.lstat(path8, { bigint: true });
8790
+ return [path8, ...[stat2.dev, stat2.ino, stat2.mode, stat2.size, stat2.mtimeNs, stat2.ctimeNs].map(String)];
8709
8791
  } catch (error) {
8710
- if (error.code === "ENOENT") return [path7, null];
8792
+ if (error.code === "ENOENT") return [path8, null];
8711
8793
  throw error;
8712
8794
  }
8713
8795
  }));
8714
8796
  return JSON.stringify([current2, stats]);
8715
8797
  }
8716
- function forgotten(b, path7) {
8717
- return existsSync6(unlinked(join13(topicsHistoryRoot(b), "forgotten", `${digest3(path7)}.json`)));
8798
+ function forgotten(b, path8) {
8799
+ return existsSync6(unlinked(join13(topicsHistoryRoot(b), "forgotten", `${digest3(path8)}.json`)));
8718
8800
  }
8719
8801
  function openIndex(b, version) {
8720
8802
  if (!b.stateDir || !b.topicsDir) return null;
@@ -8754,16 +8836,16 @@ async function walkTopicsNeedsFallback(b) {
8754
8836
  const visit = async (rel) => {
8755
8837
  const entries = await fs2.readdir(unlinked(join13(b.topicsDir, rel)), { withFileTypes: true });
8756
8838
  for (const entry of entries) {
8757
- const path7 = rel ? `${rel}/${entry.name}` : entry.name;
8839
+ const path8 = rel ? `${rel}/${entry.name}` : entry.name;
8758
8840
  if (entry.isSymbolicLink()) continue;
8759
8841
  if (entry.isDirectory()) {
8760
- if (await visit(path7)) return true;
8842
+ if (await visit(path8)) return true;
8761
8843
  continue;
8762
8844
  }
8763
- if (!entry.isFile() || !/\.md$/i.test(path7) || path7.toUpperCase() === "MEMORY.MD" || forgotten(b, path7)) continue;
8764
- const source = sources.get(path7);
8845
+ if (!entry.isFile() || !/\.md$/i.test(path8) || path8.toUpperCase() === "MEMORY.MD" || forgotten(b, path8)) continue;
8846
+ const source = sources.get(path8);
8765
8847
  if (!source) return true;
8766
- const stat2 = await fs2.stat(unlinked(join13(b.topicsDir, path7)));
8848
+ const stat2 = await fs2.stat(unlinked(join13(b.topicsDir, path8)));
8767
8849
  if (stat2.size !== source.bytes || stat2.mtimeMs !== source.mtime_ms) return true;
8768
8850
  }
8769
8851
  return false;
@@ -9460,7 +9542,7 @@ function readRelationshipContext(store, scope, request, clock = () => (/* @__PUR
9460
9542
  for (const entity of (request.graphEntityIds ?? []).flatMap((id) => resolve13(id) || []).filter((entity2) => !selected.has(entity2.entityId)).slice(0, 4)) {
9461
9543
  if (!context.people.some((person) => person.entityId === entity.entityId)) add("people", entity);
9462
9544
  }
9463
- for (const path7 of (request.graphPaths ?? []).slice(0, 40)) add("paths", path7, [path7.source, path7.target]);
9545
+ for (const path8 of (request.graphPaths ?? []).slice(0, 40)) add("paths", path8, [path8.source, path8.target]);
9464
9546
  const linkedIds = store.entities.list(scope, cutoff).filter((entity) => selected.has(resolve13(entity.entityId)?.entityId || entity.entityId)).map((entity) => entity.entityId);
9465
9547
  const views = recall.entitySources(linkedIds, maxRecords);
9466
9548
  const sourceIds = [.../* @__PURE__ */ new Set([
@@ -10950,11 +11032,13 @@ var init_facts = __esm({
10950
11032
  if (subjectIds?.length === 0) return [];
10951
11033
  const placeholders = subjectIds?.map(() => "?").join(",");
10952
11034
  const relations = relationshipPredicates.map((predicate) => `'${predicate}'`).join(",");
11035
+ const key4 = scopeId(scope);
11036
+ const incomingIds = includeIncoming ? subjectIds : void 0;
10953
11037
  return this.readTransaction(() => {
10954
- const slots = this.db.prepare(`SELECT * FROM fact_slots s WHERE scope_id=?${subjectIds ? ` AND (subject_id IN (${placeholders})${includeIncoming ? ` OR (predicate IN (${relations}) AND EXISTS (
10955
- SELECT 1 FROM fact_assertions a WHERE a.scope_id=s.scope_id AND a.slot_id=s.slot_id AND json_extract(a.value_json,'$.entityId') IN (${placeholders})))` : ""})` : ""} ORDER BY slot_id`).all(scopeId(scope), ...subjectIds ?? [], ...includeIncoming ? subjectIds ?? [] : []);
10956
- const assertionsBySlot = this.versionsBySlot(scopeId(scope), knownAtRevision);
10957
- const revisions = knownAtRevision === void 0 ? null : this.slotRevisionsAt(scopeId(scope), knownAtRevision);
11038
+ const slots = this.db.prepare(`SELECT * FROM fact_slots s WHERE scope_id=?${subjectIds ? ` AND (subject_id IN (${placeholders})${incomingIds ? ` OR (predicate IN (${relations}) AND s.slot_id IN (
11039
+ SELECT a.slot_id FROM fact_assertions a WHERE a.scope_id=? AND json_extract(a.value_json,'$.entityId') IN (${placeholders})))` : ""})` : ""} ORDER BY slot_id`).all(key4, ...subjectIds ?? [], ...incomingIds ? [key4, ...incomingIds] : []);
11040
+ const assertionsBySlot = this.versionsBySlot(key4, knownAtRevision);
11041
+ const revisions = knownAtRevision === void 0 ? null : this.slotRevisionsAt(key4, knownAtRevision);
10958
11042
  return slots.map((slot) => ({
10959
11043
  subjectId: slot.subject_id,
10960
11044
  predicate: slot.predicate,
@@ -11199,23 +11283,23 @@ var init_facts = __esm({
11199
11283
  if ((exception || proposal.changeKind === "exception") && (!exception || schedule.frequency !== "once")) throw new Error("OCCURRENCE_EXCEPTION_REQUIRED");
11200
11284
  }
11201
11285
  for (const [index, evidence] of proposal.evidence.entries()) {
11202
- const path7 = `evidence[${index}]`;
11203
- if (!evidence || typeof evidence !== "object") throw new Error(`INVALID_EVIDENCE_SPAN: ${path7} \u2014 \u6BCF\u6761\u8BC1\u636E\u987B\u662F\u5BF9\u8C61 {sourceId, quote, relation}`);
11286
+ const path8 = `evidence[${index}]`;
11287
+ if (!evidence || typeof evidence !== "object") throw new Error(`INVALID_EVIDENCE_SPAN: ${path8} \u2014 \u6BCF\u6761\u8BC1\u636E\u987B\u662F\u5BF9\u8C61 {sourceId, quote, relation}`);
11204
11288
  const source = this.db.prepare(`SELECT text,role,origin_class,interpretation_status FROM memory_sources s WHERE scope_id=? AND source_id=?
11205
11289
  AND NOT EXISTS (SELECT 1 FROM memory_sources newer WHERE newer.scope_id=s.scope_id
11206
11290
  AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)`).get(scopeId(scope), evidence.sourceId ?? null);
11207
- if (!source || source.interpretation_status === "deleted") throw new Error(`INVALID_EVIDENCE_SPAN: ${path7}.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`);
11208
- if (typeof evidence.quote !== "string" || !evidence.quote) throw new Error(`INVALID_EVIDENCE_SPAN: ${path7}.quote \u2014 quote \u5FC5\u586B\uFF0C\u9010\u5B57\u51FA\u81EA\u6765\u6E90\u539F\u6587`);
11291
+ if (!source || source.interpretation_status === "deleted") throw new Error(`INVALID_EVIDENCE_SPAN: ${path8}.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`);
11292
+ if (typeof evidence.quote !== "string" || !evidence.quote) throw new Error(`INVALID_EVIDENCE_SPAN: ${path8}.quote \u2014 quote \u5FC5\u586B\uFF0C\u9010\u5B57\u51FA\u81EA\u6765\u6E90\u539F\u6587`);
11209
11293
  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) {
11210
11294
  const count = occurrences(source.text, evidence.quote);
11211
- throw new Error(count === 0 ? `INVALID_EVIDENCE_SPAN: ${path7}.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: ${path7} \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`);
11295
+ throw new Error(count === 0 ? `INVALID_EVIDENCE_SPAN: ${path8}.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: ${path8} \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`);
11212
11296
  }
11213
- if (!["supports", "refutes"].includes(evidence.relation)) throw new Error(`INVALID_EVIDENCE_SPAN: ${path7}.relation \u2014 \u53EA\u80FD\u662F supports\uFF08\u652F\u6301\uFF09\u6216 refutes\uFF08\u53CD\u9A73\uFF09`);
11297
+ if (!["supports", "refutes"].includes(evidence.relation)) throw new Error(`INVALID_EVIDENCE_SPAN: ${path8}.relation \u2014 \u53EA\u80FD\u662F supports\uFF08\u652F\u6301\uFF09\u6216 refutes\uFF08\u53CD\u9A73\uFF09`);
11214
11298
  const relationValue = proposal.value;
11215
11299
  if (proposal.predicate === "relation.open" && relationValue?.attribution === "reported" && (proposal.claimKind !== "reported_statement" || !hasReportedAttribution(source.text, relationValue, this.entities.sourceMentions(scope, evidence.sourceId)))) {
11216
11300
  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");
11217
11301
  }
11218
- const roleMismatch = () => new Error(`EVIDENCE_ROLE_MISMATCH: ${path7} \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`);
11302
+ const roleMismatch = () => new Error(`EVIDENCE_ROLE_MISMATCH: ${path8} \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`);
11219
11303
  if (proposal.claimKind !== "inference") {
11220
11304
  if (proposal.claimKind === "user_statement" && (source.role !== "user" || !["host_user", "client_reported_user"].includes(source.origin_class))) throw roleMismatch();
11221
11305
  if (proposal.claimKind === "tool_observation" && (source.role !== "tool" || source.origin_class !== "tool_observation")) throw roleMismatch();
@@ -11590,6 +11674,7 @@ var init_store = __esm({
11590
11674
  init_change_feed();
11591
11675
  init_dependencies();
11592
11676
  init_tombstones();
11677
+ init_watermarks();
11593
11678
  init_scope();
11594
11679
  init_knowledge_history();
11595
11680
  init_host_turns();
@@ -11877,32 +11962,32 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11877
11962
  return { built: !hasStats, ms: Date.now() - started };
11878
11963
  }
11879
11964
  async close() {
11880
- const errors = [];
11965
+ const errors2 = [];
11881
11966
  try {
11882
11967
  this.capture?.close();
11883
11968
  } catch (error) {
11884
- errors.push(error);
11969
+ errors2.push(error);
11885
11970
  }
11886
11971
  try {
11887
11972
  this.db.close();
11888
11973
  } catch (error) {
11889
- errors.push(error);
11974
+ errors2.push(error);
11890
11975
  }
11891
11976
  try {
11892
11977
  await this.vectors?.close();
11893
11978
  } catch (error) {
11894
- errors.push(error);
11979
+ errors2.push(error);
11895
11980
  } finally {
11896
11981
  this.vectors = null;
11897
11982
  }
11898
11983
  try {
11899
11984
  this.releaseRuntimeWriter?.();
11900
11985
  } catch (error) {
11901
- errors.push(error);
11986
+ errors2.push(error);
11902
11987
  } finally {
11903
11988
  this.releaseRuntimeWriter = void 0;
11904
11989
  }
11905
- if (errors.length) throw new AggregateError(errors, "MEM7_CLOSE_FAILED");
11990
+ if (errors2.length) throw new AggregateError(errors2, "MEM7_CLOSE_FAILED");
11906
11991
  }
11907
11992
  // ── memcell 账本 ──────────────────────────────────────────
11908
11993
  insertMemcell(cell) {
@@ -12199,13 +12284,13 @@ CREATE TABLE IF NOT EXISTS cluster_members (
12199
12284
  const version = expectedVersion ?? this.dependencies.version(scope, kind, id);
12200
12285
  this.dependencies.assertCurrent(scope, kind, id, version);
12201
12286
  const digest4 = createHash19("sha256").update(content.trim()).digest("hex");
12202
- const path7 = relative3(this.root, file).replace(/\\/g, "/");
12287
+ const path8 = relative3(this.root, file).replace(/\\/g, "/");
12203
12288
  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);
12204
- if (previous?.version === version && (previous.digest !== digest4 || previous.path !== path7)) throw new Error("PROJECTION_PUBLICATION_VERSION_CONFLICT");
12289
+ if (previous?.version === version && (previous.digest !== digest4 || previous.path !== path8)) throw new Error("PROJECTION_PUBLICATION_VERSION_CONFLICT");
12205
12290
  this.db.prepare(`INSERT INTO memory_projection_entries VALUES (?,?,?,?,?,?)
12206
12291
  ON CONFLICT(scope_id,kind,entry_id) DO UPDATE SET path=excluded.path,version=excluded.version,digest=excluded.digest
12207
- WHERE excluded.version>=memory_projection_entries.version`).run(scopeId(scope), kind, id, path7, version, digest4);
12208
- this.artifacts.publish(scope, { ...body, kind, id, version, medium: "markdown", path: path7, markdown: content.trim() });
12292
+ WHERE excluded.version>=memory_projection_entries.version`).run(scopeId(scope), kind, id, path8, version, digest4);
12293
+ this.artifacts.publish(scope, { ...body, kind, id, version, medium: "markdown", path: path8, markdown: content.trim() });
12209
12294
  });
12210
12295
  }
12211
12296
  projectionMatches(scope, kind, id, file, content) {
@@ -12298,13 +12383,13 @@ CREATE TABLE IF NOT EXISTS cluster_members (
12298
12383
  /** Interpretation reads entities, facts and confirmed mentions, independently of later chat intake. */
12299
12384
  interpretationReadStamp(scope, sourceIds, excludedPredicates = []) {
12300
12385
  return this.readTransaction(() => {
12301
- const retractions = this.db.prepare("SELECT COALESCE(MAX(event_seq),0) seq FROM memory_state_outbox WHERE scope_id=? AND kind IN ('evidence.retracted','memory.deleted')").get(scopeId(scope));
12386
+ const retractions = readRetractionSeq(this.db, scopeId(scope));
12302
12387
  const factRevision = excludedPredicates.length ? this.db.prepare(`SELECT slot_id,revision FROM fact_slots
12303
12388
  WHERE scope_id=? AND predicate NOT IN (${excludedPredicates.map(() => "?").join(",")}) ORDER BY slot_id`).all(scopeId(scope), ...excludedPredicates) : this.facts.revision(scope);
12304
12389
  return JSON.stringify([
12305
12390
  this.entities.revision(scope),
12306
12391
  factRevision,
12307
- retractions.seq,
12392
+ retractions,
12308
12393
  sourceIds.map((id) => this.entities.sourceMentions(scope, id))
12309
12394
  ]);
12310
12395
  });
@@ -12321,7 +12406,7 @@ CREATE TABLE IF NOT EXISTS cluster_members (
12321
12406
  }
12322
12407
  /** History retrieval validates each publication; unrelated received/interpreted prose is not its basis. */
12323
12408
  captureHistoricalReadGuard(scope) {
12324
- const stamp = () => this.db.prepare("SELECT COALESCE(MAX(event_seq),0) seq FROM memory_state_outbox WHERE scope_id=? AND kind IN ('evidence.retracted','memory.deleted')").get(scopeId(scope)).seq;
12409
+ const stamp = () => readRetractionSeq(this.db, scopeId(scope));
12325
12410
  const captured = stamp();
12326
12411
  return () => {
12327
12412
  if (stamp() !== captured) throw new MemoryReadSupersededError();
@@ -12402,8 +12487,8 @@ CREATE TABLE IF NOT EXISTS cluster_members (
12402
12487
  };
12403
12488
  }
12404
12489
  unscopedProjectionMatches(ownerId, kind, id, file, content) {
12405
- const path7 = relative3(this.root, file).replace(/\\/g, "/");
12406
- const mappings = this.db.prepare("SELECT scope_id FROM memory_projection_entries WHERE kind=? AND entry_id=? AND path=?").all(kind, id, path7);
12490
+ const path8 = relative3(this.root, file).replace(/\\/g, "/");
12491
+ const mappings = this.db.prepare("SELECT scope_id FROM memory_projection_entries WHERE kind=? AND entry_id=? AND path=?").all(kind, id, path8);
12407
12492
  if (mappings.length) {
12408
12493
  if (mappings.length !== 1) return false;
12409
12494
  const scope = this.sources.scope(mappings[0].scope_id);
@@ -15230,14 +15315,19 @@ function startLanceOptimize(stateDir2, intervalMs = 24 * 36e5, firstRunDelayMs =
15230
15315
  let finished = false;
15231
15316
  try {
15232
15317
  const vs = (store ?? getReadStore(stateDir2)).vectorStore();
15233
- while (nextKind < kinds2.length && !stopped && !options.isBusy?.()) {
15318
+ const canStart = () => !stopped && !options.isBusy?.();
15319
+ while (nextKind < kinds2.length && canStart()) {
15234
15320
  const kind = kinds2[nextKind];
15235
- const tbl = await vs.table(kind);
15236
- if (stopped || options.isBusy?.()) break;
15237
- const stats = await tbl.optimize();
15238
- const merged = stats?.compaction?.filesRemoved ?? stats?.compaction?.fragmentsRemoved;
15239
- const pruned = stats?.prune?.oldVersionsRemoved ?? stats?.prune?.versionsRemoved;
15240
- summary2.push(`${kind}${merged === void 0 ? "" : ` \u5408\u5E76${merged}`}${pruned === void 0 ? "" : ` \u6E05\u7248\u672C${pruned}`}`);
15321
+ const result = await vs.maintainIndexes(kind, canStart);
15322
+ if (result === void 0) break;
15323
+ if (result === "preserved") summary2.push(`${kind} \u4FDD\u7559 ANN`);
15324
+ else if (result === "repaired") summary2.push(`${kind} \u5DF2\u4FEE\u590D ANN`);
15325
+ else {
15326
+ const stats = result;
15327
+ const merged = stats.compaction?.filesRemoved ?? stats.compaction?.fragmentsRemoved;
15328
+ const pruned = stats.prune?.oldVersionsRemoved ?? stats.prune?.versionsRemoved;
15329
+ summary2.push(`${kind}${merged === void 0 ? "" : ` \u5408\u5E76${merged}`}${pruned === void 0 ? "" : ` \u6E05\u7248\u672C${pruned}`}`);
15330
+ }
15241
15331
  nextKind++;
15242
15332
  }
15243
15333
  finished = nextKind === kinds2.length;
@@ -15846,6 +15936,33 @@ var init_events = __esm({
15846
15936
  }
15847
15937
  });
15848
15938
 
15939
+ // src/router/cpu-router-scene.ts
15940
+ var init_cpu_router_scene = __esm({
15941
+ "src/router/cpu-router-scene.ts"() {
15942
+ "use strict";
15943
+ }
15944
+ });
15945
+
15946
+ // src/skills/skill-gate.ts
15947
+ var USER_CHANNELS, SKILL_CHANNELS;
15948
+ var init_skill_gate = __esm({
15949
+ "src/skills/skill-gate.ts"() {
15950
+ "use strict";
15951
+ init_strip_injected();
15952
+ init_writer();
15953
+ init_cpu_router_scene();
15954
+ USER_CHANNELS = /* @__PURE__ */ new Set(["discord", "feishu", "wechat", "telegram", "cli", "console", "voice-chat", "deskBuddy", "ccBridge"]);
15955
+ SKILL_CHANNELS = /* @__PURE__ */ new Set([...USER_CHANNELS, "chan7", "webhook"]);
15956
+ }
15957
+ });
15958
+
15959
+ // src/skills/legacy-session-start.ts
15960
+ var init_legacy_session_start = __esm({
15961
+ "src/skills/legacy-session-start.ts"() {
15962
+ "use strict";
15963
+ }
15964
+ });
15965
+
15849
15966
  // src/travel/chunk-store.ts
15850
15967
  import { gunzipSync as gunzipSync2, gzip as gzip2 } from "node:zlib";
15851
15968
  import { promisify as promisify2 } from "node:util";
@@ -15925,13 +16042,6 @@ var init_cpu_router = __esm({
15925
16042
  }
15926
16043
  });
15927
16044
 
15928
- // src/router/cpu-router-scene.ts
15929
- var init_cpu_router_scene = __esm({
15930
- "src/router/cpu-router-scene.ts"() {
15931
- "use strict";
15932
- }
15933
- });
15934
-
15935
16045
  // src/router/cpu-router-mode-hook.ts
15936
16046
  var init_cpu_router_mode_hook = __esm({
15937
16047
  "src/router/cpu-router-mode-hook.ts"() {
@@ -15944,6 +16054,8 @@ var TOOL_HOOK_EXECUTION_TIMEOUT_MS;
15944
16054
  var init_executor = __esm({
15945
16055
  "src/hooks/executor.ts"() {
15946
16056
  "use strict";
16057
+ init_skill_gate();
16058
+ init_legacy_session_start();
15947
16059
  init_runtime_authority();
15948
16060
  init_config();
15949
16061
  init_events();
@@ -15986,8 +16098,120 @@ var init_provider = __esm({
15986
16098
  }
15987
16099
  });
15988
16100
 
16101
+ // src/services/adaptive-proxy.ts
16102
+ import { HttpsProxyAgent } from "https-proxy-agent";
16103
+ import { Agent, Client, ProxyAgent, errors } from "undici";
16104
+ function proxyAddress(value) {
16105
+ const bareLoopback = /^(?:localhost\.?|127(?:\.\d{1,3}){3}|\[::1\]):\d+$/i;
16106
+ return new URL(bareLoopback.test(value) ? `http://${value}` : value);
16107
+ }
16108
+ function localProxyKey(url) {
16109
+ if (url.protocol !== "http:" && url.protocol !== "https:") return;
16110
+ const host = url.hostname.replace(/\.$/, "");
16111
+ if (host !== "localhost" && host !== "[::1]" && !/^127\./.test(host)) return;
16112
+ return `${host}:${url.port || (url.protocol === "https:" ? 443 : 80)}`;
16113
+ }
16114
+ function proxyUnavailable(key4) {
16115
+ return (unreachableUntil.get(key4) ?? -Infinity) > Date.now();
16116
+ }
16117
+ function markUnavailable(key4) {
16118
+ unreachableUntil.set(key4, Date.now() + RETRY_PROXY_AFTER_MS);
16119
+ }
16120
+ function isTcpDialFailure(error) {
16121
+ if (error instanceof AggregateError) {
16122
+ return error.errors.length > 0 && error.errors.every(isTcpDialFailure);
16123
+ }
16124
+ const err = error;
16125
+ return err?.syscall === "connect" && dialFailureCodes.has(err.code ?? "");
16126
+ }
16127
+ function getProxyDispatcher(value) {
16128
+ const raw = value?.trim();
16129
+ if (!raw) return;
16130
+ const cached = dispatchers.get(raw);
16131
+ if (cached) return cached;
16132
+ const url = proxyAddress(raw);
16133
+ const key4 = localProxyKey(url);
16134
+ const dispatcher = key4 ? new AdaptiveProxyDispatcher(url.href, key4) : new ProxyAgent({ uri: url.href });
16135
+ dispatchers.set(raw, dispatcher);
16136
+ return dispatcher;
16137
+ }
16138
+ var RETRY_PROXY_AFTER_MS, LOCAL_CONNECT_TIMEOUT_MS, unreachableUntil, failedProxyDials, dispatchers, direct, dialFailureCodes, AdaptiveProxyDispatcher;
16139
+ var init_adaptive_proxy = __esm({
16140
+ "src/services/adaptive-proxy.ts"() {
16141
+ "use strict";
16142
+ RETRY_PROXY_AFTER_MS = 5e3;
16143
+ LOCAL_CONNECT_TIMEOUT_MS = 1e3;
16144
+ unreachableUntil = /* @__PURE__ */ new Map();
16145
+ failedProxyDials = /* @__PURE__ */ new WeakSet();
16146
+ dispatchers = /* @__PURE__ */ new Map();
16147
+ direct = new Agent();
16148
+ dialFailureCodes = /* @__PURE__ */ new Set(["ECONNREFUSED", "ETIMEDOUT", "ENETUNREACH", "EHOSTUNREACH", "EADDRNOTAVAIL"]);
16149
+ AdaptiveProxyDispatcher = class extends ProxyAgent {
16150
+ constructor(uri, key4) {
16151
+ super({
16152
+ uri,
16153
+ proxyTls: { timeout: LOCAL_CONNECT_TIMEOUT_MS },
16154
+ clientFactory(origin, opts) {
16155
+ const { connect } = opts;
16156
+ return new Client(origin, {
16157
+ connect(options, callback) {
16158
+ let tcpConnected = false;
16159
+ const socket = connect(options, (...result) => {
16160
+ const [error] = result;
16161
+ if (error && !tcpConnected && (isTcpDialFailure(error) || error.code === "UND_ERR_CONNECT_TIMEOUT")) {
16162
+ markUnavailable(key4);
16163
+ failedProxyDials.add(error);
16164
+ }
16165
+ callback(...result);
16166
+ });
16167
+ socket.once("connect", () => {
16168
+ tcpConnected = true;
16169
+ });
16170
+ return socket;
16171
+ }
16172
+ });
16173
+ }
16174
+ });
16175
+ this.key = key4;
16176
+ }
16177
+ dispatch(options, handler) {
16178
+ if (!this.closed && !this.destroyed && proxyUnavailable(this.key)) {
16179
+ const headers = options.headers;
16180
+ const keys = !headers ? [] : Array.isArray(headers) ? headers.filter((_, index) => index % 2 === 0) : Symbol.iterator in headers ? Array.from(headers, ([name]) => name) : Object.keys(headers);
16181
+ if (keys.some((name) => name.toLowerCase() === "proxy-authorization")) {
16182
+ throw new errors.InvalidArgumentError("Proxy-Authorization should be sent in ProxyAgent constructor");
16183
+ }
16184
+ return direct.dispatch(options, handler);
16185
+ }
16186
+ let connected = false;
16187
+ const extended = handler;
16188
+ const guarded = {
16189
+ onConnect: (abort) => {
16190
+ connected = true;
16191
+ handler.onConnect?.(abort);
16192
+ },
16193
+ onError: (error) => {
16194
+ if (!connected && failedProxyDials.has(error)) {
16195
+ direct.dispatch(options, handler);
16196
+ } else {
16197
+ handler.onError?.(error);
16198
+ }
16199
+ },
16200
+ onHeaders: handler.onHeaders?.bind(handler),
16201
+ onData: handler.onData?.bind(handler),
16202
+ onComplete: handler.onComplete?.bind(handler),
16203
+ onUpgrade: handler.onUpgrade?.bind(handler),
16204
+ onResponseStarted: handler.onResponseStarted?.bind(handler),
16205
+ onBodySent: handler.onBodySent?.bind(handler),
16206
+ onRequestSent: extended.onRequestSent?.bind(handler)
16207
+ };
16208
+ return super.dispatch(options, guarded);
16209
+ }
16210
+ };
16211
+ }
16212
+ });
16213
+
15989
16214
  // src/services/withRetry.ts
15990
- import { ProxyAgent } from "undici";
15991
16215
  function sleep(ms, signal) {
15992
16216
  return new Promise((resolve13, reject) => {
15993
16217
  if (signal?.aborted) {
@@ -16055,15 +16279,6 @@ function shouldRetry(status, errorBody) {
16055
16279
  if (errorBody?.includes('"type":"overloaded_error"')) return true;
16056
16280
  return false;
16057
16281
  }
16058
- function getProxyDispatcher(proxyUrl) {
16059
- if (!proxyUrl) return void 0;
16060
- let agent = proxyAgentCache.get(proxyUrl);
16061
- if (!agent) {
16062
- agent = new ProxyAgent({ uri: proxyUrl });
16063
- proxyAgentCache.set(proxyUrl, agent);
16064
- }
16065
- return agent;
16066
- }
16067
16282
  async function* fetchWithRetry(url, init, providerLabel, proxy, beforeRequest, retryPolicy) {
16068
16283
  const configuredRetries = getMaxRetries();
16069
16284
  const maxRetries = retryPolicy?.maxRetries === void 0 ? configuredRetries : Math.min(configuredRetries, Math.max(0, Math.floor(retryPolicy.maxRetries)));
@@ -16201,10 +16416,11 @@ function readWithTimeout(reader, timeoutMs, signal) {
16201
16416
  if (onAbort) signal?.removeEventListener("abort", onAbort);
16202
16417
  });
16203
16418
  }
16204
- var DEFAULT_MAX_RETRIES, BASE_DELAY_MS, MAX_DELAY_MS, DEFAULT_TIMEOUT_MS, READ_TIMEOUT_MS, FIRST_READ_TIMEOUT_MS, NO_PROGRESS_TIMEOUT_MS, proxyAgentCache;
16419
+ var DEFAULT_MAX_RETRIES, BASE_DELAY_MS, MAX_DELAY_MS, DEFAULT_TIMEOUT_MS, READ_TIMEOUT_MS, FIRST_READ_TIMEOUT_MS, NO_PROGRESS_TIMEOUT_MS;
16205
16420
  var init_withRetry = __esm({
16206
16421
  "src/services/withRetry.ts"() {
16207
16422
  "use strict";
16423
+ init_adaptive_proxy();
16208
16424
  DEFAULT_MAX_RETRIES = 10;
16209
16425
  BASE_DELAY_MS = 500;
16210
16426
  MAX_DELAY_MS = 32e3;
@@ -16212,7 +16428,6 @@ var init_withRetry = __esm({
16212
16428
  READ_TIMEOUT_MS = 6e4;
16213
16429
  FIRST_READ_TIMEOUT_MS = parseInt(process.env.API_TIMEOUT_MS || "", 10) || 6e5;
16214
16430
  NO_PROGRESS_TIMEOUT_MS = parseInt(process.env.STREAM_NO_PROGRESS_TIMEOUT_MS || "", 10) || 3e5;
16215
- proxyAgentCache = /* @__PURE__ */ new Map();
16216
16431
  }
16217
16432
  });
16218
16433
 
@@ -18506,9 +18721,27 @@ function canonical2(value) {
18506
18721
  if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key4, item]) => [key4, canonical2(item)]));
18507
18722
  return value;
18508
18723
  }
18724
+ function indexIncidentEdges(edges) {
18725
+ const incident = /* @__PURE__ */ new Map();
18726
+ const append2 = (id, edge) => {
18727
+ const list = incident.get(id);
18728
+ if (list) list.push(edge);
18729
+ else incident.set(id, [edge]);
18730
+ };
18731
+ for (const edge of edges) {
18732
+ const { source, target } = edge;
18733
+ append2(source, edge);
18734
+ if (source !== target) append2(target, edge);
18735
+ }
18736
+ return incident;
18737
+ }
18509
18738
  function assertGraphBasis(snapshot, basis) {
18510
18739
  const nodes = new Map(snapshot.nodes.map((node) => [node.id, node]));
18511
- if (basis.nodes.some((node) => !matchesBasis(graphBasis(nodes.get(node.id)), node.basis)) || basis.edges.some((edge) => !matchesBasis(incidentBasis(snapshot.edges, edge.id), edge.basis))) {
18740
+ if (basis.nodes.some((node) => !matchesBasis(graphBasis(nodes.get(node.id)), node.basis))) {
18741
+ throw new Error("STALE_GRAPH: model input changed during planning");
18742
+ }
18743
+ const incident = indexIncidentEdges(snapshot.edges);
18744
+ if (basis.edges.some((edge) => !matchesBasis(incidentBasis(incident.get(edge.id)), edge.basis))) {
18512
18745
  throw new Error("STALE_GRAPH: model input changed during planning");
18513
18746
  }
18514
18747
  }
@@ -18529,7 +18762,7 @@ function commitGraphDelta(persist, delta, options) {
18529
18762
  if (!matchesBasis(graphBasis(freshNode(entry.id)), entry.basis)) throw new Error("STALE_GRAPH: model input changed during planning");
18530
18763
  }
18531
18764
  for (const entry of options.basis.edges) {
18532
- if (!matchesBasis(incidentBasis(persist.loadIncidentEdges(entry.id), entry.id), entry.basis)) throw new Error("STALE_GRAPH: model input changed during planning");
18765
+ if (!matchesBasis(incidentBasis(persist.loadIncidentEdges(entry.id)), entry.basis)) throw new Error("STALE_GRAPH: model input changed during planning");
18533
18766
  }
18534
18767
  }
18535
18768
  for (const [id, { before }] of delta.upsertNodes) {
@@ -18616,7 +18849,7 @@ function commitGraphDelta(persist, delta, options) {
18616
18849
  return { revisionAtStart, revisionAtEnd: persist.graphRevision(), applied: [...committed.values()] };
18617
18850
  });
18618
18851
  }
18619
- var graphBasis, same, incidentBasis, compactBasis, matchesBasis;
18852
+ var graphBasis, same, compareEdgeKeys, incidentBasis, compactBasis, matchesBasis;
18620
18853
  var init_mutation_service = __esm({
18621
18854
  "src/memory/proactive/mutation-service.ts"() {
18622
18855
  "use strict";
@@ -18631,7 +18864,8 @@ var init_mutation_service = __esm({
18631
18864
  createdAt: node.createdAt
18632
18865
  } : null));
18633
18866
  same = (a, b) => JSON.stringify(canonical2(a)) === JSON.stringify(canonical2(b));
18634
- incidentBasis = (edges, id) => JSON.stringify(canonical2(edges.filter((edge) => edge.source === id || edge.target === id).sort((a, b) => edgeKey(a.source, a.target, a.edgeType).localeCompare(edgeKey(b.source, b.target, b.edgeType)))));
18867
+ compareEdgeKeys = (a, b) => edgeKey(a.source, a.target, a.edgeType).localeCompare(edgeKey(b.source, b.target, b.edgeType));
18868
+ incidentBasis = (edges = []) => JSON.stringify(canonical2(edges.sort(compareEdgeKeys)));
18635
18869
  compactBasis = (value) => `sha256:${createHash20("sha256").update(value).digest("hex")}`;
18636
18870
  matchesBasis = (current2, expected) => expected.startsWith("sha256:") ? compactBasis(current2) === expected : current2 === expected;
18637
18871
  }
@@ -19156,6 +19390,48 @@ var init_graph_store = __esm({
19156
19390
  if (this.demand && !this.journal) return this.persist.loadEdgesAmong(ids);
19157
19391
  return [...ids].flatMap((id) => this.getEdgesFrom(id)).filter((edge) => ids.has(edge.target));
19158
19392
  }
19393
+ /** Every edge with an end in the set, for node ids as stored. One query while reading on demand;
19394
+ * the adjacency index otherwise. */
19395
+ incidentEdgesFor(ids) {
19396
+ if (!ids.size) return [];
19397
+ if (this.demand && !this.journal) return this.persist.loadIncidentEdgesFor(ids);
19398
+ return [...new Map([...ids].flatMap((id) => [...this.getEdgesFrom(id), ...this.getEdgesTo(id)]).map((edge) => [edgeKey(edge.source, edge.target, edge.edgeType), edge])).values()];
19399
+ }
19400
+ /** Existence by the id as written; a redirect is not followed. */
19401
+ hasExactNode(id) {
19402
+ return this.exactNode(id) !== void 0;
19403
+ }
19404
+ /** The scope's nodes as the database can vouch for their readability. Reading on demand outside a mutation
19405
+ * this is the indexed read. Otherwise, and inside a mutation, the caller gets the scope unfiltered: the
19406
+ * journal's nodes are not filtered by state, so a caller that needs strictly readable nodes applies
19407
+ * graphNodeReadable itself. */
19408
+ readableNodesInScope(scope, allowGuarded) {
19409
+ if (this.demand && !this.journal) return this.persist.loadReadableNodes(scope, allowGuarded);
19410
+ return this.readNodes(void 0, scope);
19411
+ }
19412
+ /** Nodes of these types in the scope with no edge at either end, as this store currently sees them.
19413
+ * Reading on demand, the indexes name the candidates, the open mutation's journal adjusts them for what
19414
+ * it already changed, and the staged graph has the last word; in memory it is one pass over the nodes. */
19415
+ isolatedNodes(types, scope) {
19416
+ const inScope = (node) => !scope || String(node.data.scopeId || "legacy") === scope;
19417
+ const matches = (node) => types.includes(node.type) && inScope(node);
19418
+ const isolated = (id) => this.getNeighbors(id).length === 0 && this.getPredecessors(id).length === 0;
19419
+ if (!this.demand) return this.getAllNodes().filter((node) => matches(node) && isolated(node.id));
19420
+ const candidates = new Set(this.persist.isolatedNodeIds(types, scope || void 0));
19421
+ const delta = this.journal?.delta;
19422
+ if (delta) {
19423
+ for (const id of delta.deleteNodes.keys()) candidates.delete(id);
19424
+ for (const id of delta.upsertNodes.keys()) candidates.add(id);
19425
+ for (const edge of delta.deleteEdges.values()) {
19426
+ candidates.add(edge.source);
19427
+ candidates.add(edge.target);
19428
+ }
19429
+ }
19430
+ return [...candidates].flatMap((id) => {
19431
+ const node = this.exactNode(id);
19432
+ return node && matches(node) && isolated(id) ? [node] : [];
19433
+ });
19434
+ }
19159
19435
  /** 出边后继(store.py:408 successors) */
19160
19436
  getNeighbors(id) {
19161
19437
  id = this.requireNode(id).id;
@@ -19237,6 +19513,7 @@ var init_graph_reads = __esm({
19237
19513
  "src/memory/proactive/graph-reads.ts"() {
19238
19514
  "use strict";
19239
19515
  init_graph_store();
19516
+ init_watermarks();
19240
19517
  }
19241
19518
  });
19242
19519
 
@@ -19575,7 +19852,6 @@ var init_memory_reasoning = __esm({
19575
19852
  "src/memory/proactive/memory-reasoning.ts"() {
19576
19853
  "use strict";
19577
19854
  init_executor2();
19578
- init_models();
19579
19855
  init_change_consumer();
19580
19856
  init_relationship_projection();
19581
19857
  init_context();
@@ -19654,7 +19930,6 @@ var init_opportunity = __esm({
19654
19930
  init_read_guard();
19655
19931
  init_scoped_opportunity();
19656
19932
  init_published_basis();
19657
- init_models();
19658
19933
  init_sweep();
19659
19934
  OPPORTUNITY_SCAN_INTERVAL_MS = 6 * 60 * 6e4;
19660
19935
  FORESIGHT_CACHE_TTL_MS = 30 * 6e4;
@@ -19820,8 +20095,20 @@ var init_delivery_reconciliation = __esm({
19820
20095
  }
19821
20096
  });
19822
20097
 
20098
+ // src/utils/file-transaction.ts
20099
+ import { DatabaseSync as DatabaseSync14 } from "node:sqlite";
20100
+ var init_file_transaction = __esm({
20101
+ "src/utils/file-transaction.ts"() {
20102
+ "use strict";
20103
+ }
20104
+ });
20105
+
19823
20106
  // src/utils/path.ts
19824
20107
  import * as path4 from "node:path";
20108
+ function isWithin(root, target) {
20109
+ const name = path4.relative(root, target);
20110
+ return !path4.isAbsolute(name) && name !== ".." && !name.startsWith(".." + path4.sep);
20111
+ }
19825
20112
  function fixMsysPath(p) {
19826
20113
  let fixed = p.includes("\\") ? p.replace(/\\/g, "/") : p;
19827
20114
  if (process.platform === "win32") {
@@ -19854,6 +20141,98 @@ var init_path = __esm({
19854
20141
  }
19855
20142
  });
19856
20143
 
20144
+ // src/memory/memdir/paths.ts
20145
+ var AUTO_MEM_DIRNAME;
20146
+ var init_paths = __esm({
20147
+ "src/memory/memdir/paths.ts"() {
20148
+ "use strict";
20149
+ AUTO_MEM_DIRNAME = "topics";
20150
+ }
20151
+ });
20152
+
20153
+ // src/tools/file-path.ts
20154
+ import fs5 from "node:fs";
20155
+ import path5 from "node:path";
20156
+ function physicalPath(target) {
20157
+ let ancestor = target;
20158
+ for (; ; ) {
20159
+ try {
20160
+ fs5.lstatSync(ancestor);
20161
+ break;
20162
+ } catch (error) {
20163
+ if (error.code !== "ENOENT") throw error;
20164
+ const parent = path5.dirname(ancestor);
20165
+ if (parent === ancestor) throw error;
20166
+ ancestor = parent;
20167
+ }
20168
+ }
20169
+ return path5.resolve(fs5.realpathSync(ancestor), path5.relative(ancestor, target));
20170
+ }
20171
+ function withoutRepeatedDirectories(relative7) {
20172
+ const parts = relative7.split(path5.sep);
20173
+ while (parts.length > 1 && parts[0].toLowerCase() === AUTO_MEM_DIRNAME) parts.shift();
20174
+ return parts.filter((part, index) => index === parts.length - 1 || index === 0 || part.toLowerCase() !== parts[index - 1].toLowerCase()).join(path5.sep);
20175
+ }
20176
+ function resolveFilePath(requested, context, writing = false) {
20177
+ if (!context.memoryToolRoot) {
20178
+ if (!context.projectTask) return resolvePath(requested, context.workspace);
20179
+ const target = path5.resolve(context.workspace, requested.replaceAll("\\", "/"));
20180
+ const roots = [context.projectTask.topicsDir, ...!writing && context.taskSessionsDir ? [context.taskSessionsDir] : [], context.workspace];
20181
+ const root2 = roots.find((directory2) => isWithin(directory2, target));
20182
+ const physical = physicalPath(target);
20183
+ if (!root2 || !isWithin(physicalPath(root2), physical)) throw new Error("Path is outside this task workspace and project context");
20184
+ if (root2 === context.workspace && context.stateDir && isWithin(physicalPath(path5.join(context.stateDir, "agents")), physical)) {
20185
+ throw new Error("Path is outside this task\u2019s project storage");
20186
+ }
20187
+ if (root2 !== context.workspace && path5.relative(root2, target).split(path5.sep).some((part) => part.startsWith("."))) {
20188
+ throw new Error("Project task storage metadata is internal");
20189
+ }
20190
+ return target;
20191
+ }
20192
+ const root = path5.resolve(context.memoryToolRoot);
20193
+ const resolved = resolvePath(requested, root);
20194
+ if (!isWithin(root, resolved) || !isWithin(physicalPath(root), physicalPath(resolved))) {
20195
+ 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");
20196
+ }
20197
+ const relative7 = path5.relative(root, resolved);
20198
+ if (writing) {
20199
+ if (path5.basename(resolved).toUpperCase() === "MEMORY.MD") {
20200
+ const canonicalIndex = path5.join(root, "MEMORY.md");
20201
+ const indexNames = fs5.existsSync(root) ? fs5.readdirSync(root).filter((name) => name.toUpperCase() === "MEMORY.MD") : [];
20202
+ let sameIndex = false;
20203
+ if (path5.dirname(relative7) === "." && indexNames.length === 1 && fs5.existsSync(resolved) && fs5.existsSync(canonicalIndex)) {
20204
+ const requestedEntry = fs5.lstatSync(resolved);
20205
+ const canonicalEntry = fs5.lstatSync(canonicalIndex);
20206
+ sameIndex = requestedEntry.dev === canonicalEntry.dev && requestedEntry.ino === canonicalEntry.ino;
20207
+ }
20208
+ if (relative7 !== "MEMORY.md" && !sameIndex || relative7 === "MEMORY.md" && indexNames.length > 0 && !fs5.existsSync(canonicalIndex)) {
20209
+ 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");
20210
+ }
20211
+ }
20212
+ if (!fs5.existsSync(resolved)) {
20213
+ const parts = relative7.split(path5.sep);
20214
+ if (parts[0].toLowerCase() === AUTO_MEM_DIRNAME || parts.some((part, index) => index > 0 && index < parts.length - 1 && part.toLowerCase() === parts[index - 1].toLowerCase())) {
20215
+ 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");
20216
+ }
20217
+ if (fs5.existsSync(root)) {
20218
+ const existing = fs5.readdirSync(root, { recursive: true }).filter((entry) => typeof entry === "string" && entry.endsWith(".md") && entry !== relative7 && path5.basename(entry).toUpperCase() !== "MEMORY.MD" && withoutRepeatedDirectories(entry) === relative7);
20219
+ if (existing.length > 0) {
20220
+ 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`);
20221
+ }
20222
+ }
20223
+ }
20224
+ }
20225
+ return resolved;
20226
+ }
20227
+ var init_file_path = __esm({
20228
+ "src/tools/file-path.ts"() {
20229
+ "use strict";
20230
+ init_file_transaction();
20231
+ init_path();
20232
+ init_paths();
20233
+ }
20234
+ });
20235
+
19857
20236
  // src/tools/BashTool/prompt.ts
19858
20237
  function getBackgroundUsageNote() {
19859
20238
  return "You can use the `run_in_background` parameter to run the command in the background. Only use this if you don't need the result immediately and are OK being notified when the command completes later. You do not need to check the output right away - you'll be notified when it finishes. You do not need to use '&' at the end of the command when using this parameter.";
@@ -20070,8 +20449,8 @@ var init_readOnlyValidation = __esm({
20070
20449
 
20071
20450
  // src/tools/BashTool/BashTool.ts
20072
20451
  import { spawn, execSync } from "node:child_process";
20073
- import * as fs5 from "node:fs";
20074
- import * as path5 from "node:path";
20452
+ import * as fs6 from "node:fs";
20453
+ import * as path6 from "node:path";
20075
20454
  function isWslBash(p) {
20076
20455
  const normalized = p.replace(/\//g, "\\").toLowerCase();
20077
20456
  return WSL_PATH_MARKERS.some((m) => normalized.includes(m.toLowerCase()));
@@ -20092,7 +20471,7 @@ function findShell() {
20092
20471
  });
20093
20472
  const candidates = result.trim().split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
20094
20473
  const nonWsl = candidates.find((p) => !isWslBash(p));
20095
- if (nonWsl && fs5.existsSync(nonWsl)) {
20474
+ if (nonWsl && fs6.existsSync(nonWsl)) {
20096
20475
  cachedShell = { shell: nonWsl, args: ["-c"] };
20097
20476
  return cachedShell;
20098
20477
  }
@@ -20102,10 +20481,10 @@ function findShell() {
20102
20481
  "C:\\Program Files\\Git\\bin\\bash.exe",
20103
20482
  "C:\\Program Files (x86)\\Git\\bin\\bash.exe",
20104
20483
  "C:\\Program Files\\Git\\usr\\bin\\bash.exe",
20105
- path5.join(process.env.LOCALAPPDATA || "", "Programs", "Git", "bin", "bash.exe")
20484
+ path6.join(process.env.LOCALAPPDATA || "", "Programs", "Git", "bin", "bash.exe")
20106
20485
  ];
20107
20486
  for (const p of knownPaths) {
20108
- if (p && fs5.existsSync(p)) {
20487
+ if (p && fs6.existsSync(p)) {
20109
20488
  cachedShell = { shell: p, args: ["-c"] };
20110
20489
  return cachedShell;
20111
20490
  }
@@ -20136,7 +20515,7 @@ var init_BashTool = __esm({
20136
20515
  "src/tools/BashTool/BashTool.ts"() {
20137
20516
  "use strict";
20138
20517
  init_registry();
20139
- init_path();
20518
+ init_file_path();
20140
20519
  init_task_manager();
20141
20520
  init_prompt();
20142
20521
  init_bashSecurity();
@@ -20181,7 +20560,7 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
20181
20560
  const runInBackground = args.run_in_background || false;
20182
20561
  let cwd;
20183
20562
  try {
20184
- cwd = args.cwd ? resolvePath(args.cwd, ctx.workspace) : ctx.workspace;
20563
+ cwd = args.cwd ? resolveFilePath(args.cwd, ctx, true) : ctx.workspace;
20185
20564
  } catch (e) {
20186
20565
  return { content: e.message, isError: true };
20187
20566
  }
@@ -20210,12 +20589,12 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
20210
20589
  }
20211
20590
  const MAX_OUTPUT = 100 * 1024;
20212
20591
  const startTime = Date.now();
20213
- fs5.mkdirSync(getTaskOutputDir(), { recursive: true });
20214
- const outputFile = path5.join(getTaskOutputDir(), `exec-${startTime}-${Math.random().toString(36).slice(2)}.output`);
20215
- const outputHandle = await fs5.promises.open(outputFile, "w");
20592
+ fs6.mkdirSync(getTaskOutputDir(), { recursive: true });
20593
+ const outputFile = path6.join(getTaskOutputDir(), `exec-${startTime}-${Math.random().toString(36).slice(2)}.output`);
20594
+ const outputHandle = await fs6.promises.open(outputFile, "w");
20216
20595
  if (signal?.aborted || ctx.yieldSignal?.aborted) {
20217
20596
  await outputHandle.close();
20218
- await fs5.promises.unlink(outputFile);
20597
+ await fs6.promises.unlink(outputFile);
20219
20598
  return { content: "[not executed: new user input or stop received before command start]" };
20220
20599
  }
20221
20600
  return new Promise((resolve13) => {
@@ -20245,18 +20624,18 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
20245
20624
  let output = "";
20246
20625
  let truncated = false;
20247
20626
  try {
20248
- const fd = fs5.openSync(outputFile, "r");
20627
+ const fd = fs6.openSync(outputFile, "r");
20249
20628
  try {
20250
- truncated = fs5.fstatSync(fd).size > MAX_OUTPUT;
20629
+ truncated = fs6.fstatSync(fd).size > MAX_OUTPUT;
20251
20630
  const buffer = Buffer.alloc(MAX_OUTPUT);
20252
- output = buffer.subarray(0, fs5.readSync(fd, buffer, 0, MAX_OUTPUT, 0)).toString("utf8");
20631
+ output = buffer.subarray(0, fs6.readSync(fd, buffer, 0, MAX_OUTPUT, 0)).toString("utf8");
20253
20632
  } finally {
20254
- fs5.closeSync(fd);
20633
+ fs6.closeSync(fd);
20255
20634
  }
20256
20635
  } catch {
20257
20636
  }
20258
20637
  try {
20259
- await fs5.promises.unlink(outputFile);
20638
+ await fs6.promises.unlink(outputFile);
20260
20639
  } catch {
20261
20640
  }
20262
20641
  const parts = [
@@ -20331,8 +20710,8 @@ import { join as join19, resolve as resolve10 } from "node:path";
20331
20710
  function createNotificationStateReader() {
20332
20711
  const databases = /* @__PURE__ */ new Map();
20333
20712
  const checkers = /* @__PURE__ */ new Map();
20334
- const open = (path7) => {
20335
- const key4 = resolve10(path7);
20713
+ const open = (path8) => {
20714
+ const key4 = resolve10(path8);
20336
20715
  let db = databases.get(key4);
20337
20716
  if (!db) {
20338
20717
  db = new DatabaseSync10(key4, { readOnly: true });
@@ -20401,6 +20780,7 @@ function readNotificationState(route, queueStateDir, open, relationshipChecker)
20401
20780
  }
20402
20781
  if (context.actionVersions && Object.keys(context.actionVersions).length) {
20403
20782
  const ledgerDependencies = new MemoryDependencies(memory, (operation) => operation());
20783
+ const retractions = emptyRetractionCache();
20404
20784
  proactive = open(join19(runtime.workspace, ".proactive", "proactive.db"));
20405
20785
  for (const id of Object.keys(context.actionVersions)) {
20406
20786
  const action = proactive.prepare("SELECT scope_id,intent_id FROM actions WHERE id=?").get(id);
@@ -20414,6 +20794,9 @@ function readNotificationState(route, queueStateDir, open, relationshipChecker)
20414
20794
  const row = proactive.prepare("SELECT data FROM nodes WHERE id=?").get(nodeId);
20415
20795
  const data = row && JSON.parse(row.data);
20416
20796
  if (!data || data.scopeId !== context.scopeId || data.evidenceState === "deleted") return { state: "blocked", reason: "memory_deleted", redact: true };
20797
+ if (typeof data.sourceWatermark === "number" && typeof data.retractionWatermark === "number" && deletedWithinView(memory, context.scopeId, data.retractionWatermark, data.sourceWatermark, retractions)) {
20798
+ return { state: "blocked", reason: "memory_deleted", redact: true };
20799
+ }
20417
20800
  for (const evidence of [...data.sourceRefs ?? [], ...data.sourceEvidence ?? []]) {
20418
20801
  if (evidence.sourceId && deletedSource(evidence.sourceId)) return { state: "blocked", reason: "memory_deleted", redact: true };
20419
20802
  if (evidence.sourceId && Number.isSafeInteger(evidence.sourceVersion)) {
@@ -20488,6 +20871,7 @@ var init_notification_state = __esm({
20488
20871
  init_dependencies();
20489
20872
  init_basis_check();
20490
20873
  init_relationship_notice_check();
20874
+ init_watermarks();
20491
20875
  init_scope();
20492
20876
  contextIdentity = (context) => canonicalJson({
20493
20877
  scopeId: context.scopeId,
@@ -20503,8 +20887,8 @@ var init_notification_state = __esm({
20503
20887
  // src/tools/task-manager.ts
20504
20888
  import { randomBytes } from "node:crypto";
20505
20889
  import { spawn as spawn2 } from "node:child_process";
20506
- import * as fs6 from "node:fs";
20507
- import * as path6 from "node:path";
20890
+ import * as fs7 from "node:fs";
20891
+ import * as path7 from "node:path";
20508
20892
  function generateTaskId(type = "local_bash") {
20509
20893
  const prefix = TASK_ID_PREFIXES[type] ?? "x";
20510
20894
  const bytes = randomBytes(8);
@@ -20517,35 +20901,35 @@ function generateTaskId(type = "local_bash") {
20517
20901
  function getTaskOutputDir() {
20518
20902
  if (_taskOutputDir === void 0) {
20519
20903
  const stateDir2 = process.env.ENGINE_STATE_DIR || process.cwd();
20520
- _taskOutputDir = path6.join(stateDir2, "tasks");
20904
+ _taskOutputDir = path7.join(stateDir2, "tasks");
20521
20905
  }
20522
20906
  return _taskOutputDir;
20523
20907
  }
20524
20908
  function getTaskOutputPath(taskId) {
20525
- return path6.join(getTaskOutputDir(), `${taskId}.output`);
20909
+ return path7.join(getTaskOutputDir(), `${taskId}.output`);
20526
20910
  }
20527
20911
  function ensureOutputDir() {
20528
20912
  const dir = getTaskOutputDir();
20529
- if (!fs6.existsSync(dir)) {
20530
- fs6.mkdirSync(dir, { recursive: true });
20913
+ if (!fs7.existsSync(dir)) {
20914
+ fs7.mkdirSync(dir, { recursive: true });
20531
20915
  }
20532
20916
  }
20533
20917
  function initTaskOutput(taskId) {
20534
20918
  ensureOutputDir();
20535
20919
  const outputPath = getTaskOutputPath(taskId);
20536
- fs6.writeFileSync(outputPath, "", "utf-8");
20920
+ fs7.writeFileSync(outputPath, "", "utf-8");
20537
20921
  return outputPath;
20538
20922
  }
20539
20923
  function persistTask(state) {
20540
20924
  try {
20541
20925
  ensureOutputDir();
20542
20926
  const p = taskIndexPath();
20543
- const existing = fs6.existsSync(p) ? JSON.parse(fs6.readFileSync(p, "utf8")) : [];
20927
+ const existing = fs7.existsSync(p) ? JSON.parse(fs7.readFileSync(p, "utf8")) : [];
20544
20928
  const next = existing.filter((t) => t.id !== state.id);
20545
20929
  next.push({ ...state });
20546
20930
  const tmp = `${p}.${process.pid}.tmp`;
20547
- fs6.writeFileSync(tmp, JSON.stringify(next, null, 2));
20548
- fs6.renameSync(tmp, p);
20931
+ fs7.writeFileSync(tmp, JSON.stringify(next, null, 2));
20932
+ fs7.renameSync(tmp, p);
20549
20933
  } catch (err) {
20550
20934
  console.warn(`[task-manager] persist failed: ${err.message}`);
20551
20935
  }
@@ -20554,7 +20938,7 @@ function loadNotificationQueue() {
20554
20938
  if (notificationsLoaded) return;
20555
20939
  notificationsLoaded = true;
20556
20940
  try {
20557
- const value = JSON.parse(fs6.readFileSync(notificationQueuePath(), "utf8"));
20941
+ const value = JSON.parse(fs7.readFileSync(notificationQueuePath(), "utf8"));
20558
20942
  if (Array.isArray(value)) pendingNotifications.push(...value.filter((x) => x && typeof x.notification === "string"));
20559
20943
  } catch {
20560
20944
  }
@@ -20564,8 +20948,8 @@ function persistNotificationQueue(strict = false) {
20564
20948
  ensureOutputDir();
20565
20949
  const p = notificationQueuePath();
20566
20950
  const tmp = `${p}.${process.pid}.tmp`;
20567
- fs6.writeFileSync(tmp, JSON.stringify(pendingNotifications, null, 2), "utf8");
20568
- fs6.renameSync(tmp, p);
20951
+ fs7.writeFileSync(tmp, JSON.stringify(pendingNotifications, null, 2), "utf8");
20952
+ fs7.renameSync(tmp, p);
20569
20953
  } catch (err) {
20570
20954
  if (strict) throw err;
20571
20955
  console.warn(`[task-manager] notification persist failed: ${err.message}`);
@@ -20713,7 +21097,7 @@ function syncPendingNotificationState(runtime) {
20713
21097
  try {
20714
21098
  for (const record of pendingNotifications) {
20715
21099
  const route = record.route;
20716
- if (!route?.executionContext || runtime && (route.executionContext.scopeId !== runtime.scopeId || path6.resolve(route.memoryRuntime?.workspace ?? route.hostDelivery?.workspace ?? "") !== path6.resolve(runtime.workspace) || path6.resolve(route.memoryRuntime?.stateDir ?? process.env.ENGINE_STATE_DIR ?? process.cwd()) !== path6.resolve(runtime.stateDir))) {
21100
+ if (!route?.executionContext || runtime && (route.executionContext.scopeId !== runtime.scopeId || path7.resolve(route.memoryRuntime?.workspace ?? route.hostDelivery?.workspace ?? "") !== path7.resolve(runtime.workspace) || path7.resolve(route.memoryRuntime?.stateDir ?? process.env.ENGINE_STATE_DIR ?? process.cwd()) !== path7.resolve(runtime.stateDir))) {
20717
21101
  next.push(record);
20718
21102
  continue;
20719
21103
  }
@@ -20754,7 +21138,7 @@ function spawnBackgroundTask(opts) {
20754
21138
  const taskId = generateTaskId("local_bash");
20755
21139
  const outputPath = initTaskOutput(taskId);
20756
21140
  const { shell, args: shellArgs } = findShell();
20757
- const outputFd = fs6.openSync(outputPath, "w");
21141
+ const outputFd = fs7.openSync(outputPath, "w");
20758
21142
  const child = spawn2(shell, [...shellArgs, opts.command], {
20759
21143
  cwd: opts.cwd,
20760
21144
  env: opts.env || process.env,
@@ -20765,7 +21149,7 @@ function spawnBackgroundTask(opts) {
20765
21149
  // 1011:GUI 宿主(Electron 装机版)下后台任务别闪黑窗,同 BashTool
20766
21150
  });
20767
21151
  try {
20768
- fs6.closeSync(outputFd);
21152
+ fs7.closeSync(outputFd);
20769
21153
  } catch {
20770
21154
  }
20771
21155
  return trackBackgroundTask(opts, child, outputPath, Date.now(), taskId);
@@ -20807,12 +21191,12 @@ function trackBackgroundTask(opts, child, outputPath, startTime, taskId) {
20807
21191
  let killedForSize = false;
20808
21192
  sizeWatchdog = setInterval(() => {
20809
21193
  if (tasks.get(taskId)?.status !== "running") return;
20810
- fs6.stat(outputPath, (err, st) => {
21194
+ fs7.stat(outputPath, (err, st) => {
20811
21195
  if (err || st.size <= MAX_TASK_OUTPUT_BYTES) return;
20812
21196
  killedForSize = true;
20813
21197
  if (sizeWatchdog) clearInterval(sizeWatchdog);
20814
21198
  try {
20815
- fs6.appendFileSync(outputPath, "\n[output truncated: exceeded 5GB disk cap]\n");
21199
+ fs7.appendFileSync(outputPath, "\n[output truncated: exceeded 5GB disk cap]\n");
20816
21200
  } catch {
20817
21201
  }
20818
21202
  killChild(child);
@@ -20919,10 +21303,10 @@ var init_task_manager = __esm({
20919
21303
  MAX_TASK_OUTPUT_BYTES = 5 * 1024 * 1024 * 1024;
20920
21304
  tasks = /* @__PURE__ */ new Map();
20921
21305
  processes = /* @__PURE__ */ new Map();
20922
- taskIndexPath = () => path6.join(process.env.ENGINE_STATE_DIR || process.cwd(), "tasks", "index.json");
21306
+ taskIndexPath = () => path7.join(process.env.ENGINE_STATE_DIR || process.cwd(), "tasks", "index.json");
20923
21307
  pendingNotifications = [];
20924
21308
  notificationsLoaded = false;
20925
- notificationQueuePath = () => path6.join(process.env.ENGINE_STATE_DIR || process.cwd(), "tasks", "notifications.json");
21309
+ notificationQueuePath = () => path7.join(process.env.ENGINE_STATE_DIR || process.cwd(), "tasks", "notifications.json");
20926
21310
  notificationCallback = null;
20927
21311
  inFlightNotifications = /* @__PURE__ */ new Set();
20928
21312
  DEAD_LETTER_MAX_ATTEMPTS = 10;
@@ -20990,17 +21374,18 @@ var init_execution_guard = __esm({
20990
21374
  init_context_time();
20991
21375
  init_relationship_notice_check();
20992
21376
  init_dependencies();
21377
+ init_watermarks();
20993
21378
  }
20994
21379
  });
20995
21380
 
20996
21381
  // src/memory/proactive/relationship-snapshot.ts
20997
21382
  import { existsSync as existsSync11 } from "node:fs";
20998
- import { DatabaseSync as DatabaseSync14 } from "node:sqlite";
20999
- function readRelationshipGraphSnapshot(path7) {
21000
- if (!path7 || !existsSync11(path7)) return void 0;
21383
+ import { DatabaseSync as DatabaseSync15 } from "node:sqlite";
21384
+ function readRelationshipGraphSnapshot(path8) {
21385
+ if (!path8 || !existsSync11(path8)) return void 0;
21001
21386
  let db;
21002
21387
  try {
21003
- db = new DatabaseSync14(path7, { readOnly: true });
21388
+ db = new DatabaseSync15(path8, { readOnly: true });
21004
21389
  db.exec("BEGIN");
21005
21390
  const version = readSchemaVersion(db);
21006
21391
  if (version?.component !== "proactive" || version.version !== PROACTIVE_SCHEMA_VERSION) return void 0;
@@ -21121,7 +21506,7 @@ var init_memoryTypes = __esm({
21121
21506
  });
21122
21507
 
21123
21508
  // src/memory/memdir/memoryScan.ts
21124
- import fs7 from "node:fs/promises";
21509
+ import fs8 from "node:fs/promises";
21125
21510
  import { StringDecoder } from "node:string_decoder";
21126
21511
  import { basename as basename4, join as join21, sep as sep4 } from "node:path";
21127
21512
  function isArchivedPath(relativePath) {
@@ -21168,7 +21553,7 @@ async function mapFiles(values, concurrency, signal, read) {
21168
21553
  }
21169
21554
  async function readFileHeader(filePath, signal) {
21170
21555
  signal.throwIfAborted();
21171
- const handle = await fs7.open(filePath, "r");
21556
+ const handle = await fs8.open(filePath, "r");
21172
21557
  try {
21173
21558
  const decoder = new StringDecoder("utf8");
21174
21559
  const buffer = Buffer.allocUnsafe(4096);
@@ -21195,11 +21580,11 @@ async function scanMemoryFiles(memoryDir, signal, maxFiles) {
21195
21580
  const limit = maxFiles ?? DEFAULT_MAX_MEMORY_FILES;
21196
21581
  if (signal.aborted || limit <= 0) return [];
21197
21582
  try {
21198
- const entries = await fs7.readdir(memoryDir, { recursive: true });
21583
+ const entries = await fs8.readdir(memoryDir, { recursive: true });
21199
21584
  const files = entries.filter((f) => typeof f === "string" && f.endsWith(".md") && basename4(f) !== "MEMORY.md" && !isArchivedPath(f));
21200
21585
  const candidates = await mapFiles(files, 16, signal, async (filename) => {
21201
21586
  const filePath = join21(memoryDir, filename);
21202
- return { filename, filePath, mtimeMs: (await fs7.stat(filePath)).mtimeMs };
21587
+ return { filename, filePath, mtimeMs: (await fs8.stat(filePath)).mtimeMs };
21203
21588
  });
21204
21589
  const selected = candidates.sort((a, b) => b.mtimeMs - a.mtimeMs).slice(0, limit);
21205
21590
  return await mapFiles(selected, 4, signal, async (file) => {
@@ -21326,7 +21711,7 @@ Return ONLY valid JSON: {"selected_memories": ["filename1.md", "filename2.md"]}`
21326
21711
  });
21327
21712
 
21328
21713
  // src/memory/topics-history/reader.ts
21329
- import { relative as relative4 } from "node:path";
21714
+ import { relative as relative5 } from "node:path";
21330
21715
  async function configuredFallback() {
21331
21716
  const raw = liveConfig.get("topics.recall") ?? {};
21332
21717
  let ref = String(raw.model ?? "");
@@ -21365,7 +21750,7 @@ async function readTopicsHistory(b, query, options = {}) {
21365
21750
  /* @__PURE__ */ new Set(),
21366
21751
  fallback.disableThinking
21367
21752
  );
21368
- selected = files.map((file) => relative4(b.topicsDir, file.path).replace(/\\/g, "/"));
21753
+ selected = files.map((file) => relative5(b.topicsDir, file.path).replace(/\\/g, "/"));
21369
21754
  }
21370
21755
  }
21371
21756
  } catch {
@@ -21402,7 +21787,7 @@ var init_reader = __esm({
21402
21787
  });
21403
21788
 
21404
21789
  // src/memory/topics-history/import-backups.ts
21405
- import { DatabaseSync as DatabaseSync15, backup as backupSqlite } from "node:sqlite";
21790
+ import { DatabaseSync as DatabaseSync16, backup as backupSqlite } from "node:sqlite";
21406
21791
  var TOPICS_BACKUP_RETENTION_MS;
21407
21792
  var init_import_backups = __esm({
21408
21793
  "src/memory/topics-history/import-backups.ts"() {
@@ -21413,7 +21798,7 @@ var init_import_backups = __esm({
21413
21798
  });
21414
21799
 
21415
21800
  // src/memory/topics-history/import-mem7.ts
21416
- import { DatabaseSync as DatabaseSync16 } from "node:sqlite";
21801
+ import { DatabaseSync as DatabaseSync17 } from "node:sqlite";
21417
21802
  import { existsSync as existsSync12, readFileSync as readFileSync16, renameSync as renameSync7, statSync as statSync3, writeFileSync as writeFileSync9 } from "node:fs";
21418
21803
  import { join as join22 } from "node:path";
21419
21804
  function topicsImported(binding) {
@@ -22518,10 +22903,10 @@ var MAX_ITEM_CHARS = 80;
22518
22903
  var dirPath = (root) => join25(root, "status-doc");
22519
22904
  var docPath = (root, sid) => join25(dirPath(root), `${sid}.json`);
22520
22905
  function readStatusDoc(root, sid) {
22521
- const path7 = docPath(root, sid);
22522
- if (!existsSync13(path7)) return null;
22906
+ const path8 = docPath(root, sid);
22907
+ if (!existsSync13(path8)) return null;
22523
22908
  try {
22524
- const parsed = JSON.parse(readFileSync19(path7, "utf-8"));
22909
+ const parsed = JSON.parse(readFileSync19(path8, "utf-8"));
22525
22910
  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;
22526
22911
  return parsed;
22527
22912
  } catch {
@@ -22593,9 +22978,9 @@ var spoolPath = (stateDir2) => join31(mem7Root(stateDir2), "spool", "intake.json
22593
22978
  var failedPath = (stateDir2) => join31(mem7Root(stateDir2), "spool", "intake.failed.jsonl");
22594
22979
  var processingPath = (stateDir2) => join31(mem7Root(stateDir2), "spool", "intake.processing.jsonl");
22595
22980
  var INTAKE_MAX_BYTES = 64 * 1024 ** 2;
22596
- function fileBytes(path7) {
22981
+ function fileBytes(path8) {
22597
22982
  try {
22598
- return statSync4(path7).size;
22983
+ return statSync4(path8).size;
22599
22984
  } catch (error) {
22600
22985
  if (error?.code !== "ENOENT") throw error;
22601
22986
  return 0;
@@ -22912,9 +23297,9 @@ init_context();
22912
23297
 
22913
23298
  // src/mem7/core/projection-read.ts
22914
23299
  import { readFileSync as readFileSync26, realpathSync as realpathSync5, statSync as statSync5 } from "node:fs";
22915
- import { isAbsolute as isAbsolute4, join as join33, relative as relative5, resolve as resolve12, sep as sep5 } from "node:path";
23300
+ import { isAbsolute as isAbsolute4, join as join33, relative as relative6, resolve as resolve12, sep as sep5 } from "node:path";
22916
23301
  var inside = (root, target) => {
22917
- const rel = relative5(root, target);
23302
+ const rel = relative6(root, target);
22918
23303
  return Boolean(rel) && !isAbsolute4(rel) && rel !== ".." && !rel.startsWith(`..${sep5}`);
22919
23304
  };
22920
23305
  function readMemoryProjection(store, scope, input, allowDirs) {
@@ -22924,7 +23309,7 @@ function readMemoryProjection(store, scope, input, allowDirs) {
22924
23309
  root = realpathSync5(store.mem7RootPath());
22925
23310
  const logical = isAbsolute4(input.path) ? resolve12(input.path) : resolve12(root, input.path);
22926
23311
  candidate = realpathSync5(logical);
22927
- if (relative5(logical, candidate)) throw new Error("redirected");
23312
+ if (relative6(logical, candidate)) throw new Error("redirected");
22928
23313
  } catch {
22929
23314
  throw new Error("MEMORY_PATH_SCOPE_MISMATCH");
22930
23315
  }
@@ -22941,10 +23326,10 @@ function readMemoryProjection(store, scope, input, allowDirs) {
22941
23326
  const own = (track) => {
22942
23327
  const logical = resolve12(root, store.ownerProjectionPath(track, scope.ownerId, scope));
22943
23328
  const canonical3 = realpathSync5(logical);
22944
- if (relative5(logical, canonical3)) throw new Error("MEMORY_PROJECTION_REDIRECTED");
23329
+ if (relative6(logical, canonical3)) throw new Error("MEMORY_PROJECTION_REDIRECTED");
22945
23330
  return canonical3;
22946
23331
  };
22947
- const userPath = relative5(root, candidate).replace(/\\/g, "/");
23332
+ const userPath = relative6(root, candidate).replace(/\\/g, "/");
22948
23333
  const dailyKind = userPath.startsWith(`users/${scope.ownerId}/episodes/`) && /\/episode-\d{4}-\d{2}-\d{2}\.md$/.test(userPath) ? "episode" : userPath.startsWith(`users/${scope.ownerId}/.foresights/`) && /\/foresight-\d{4}-\d{2}-\d{2}\.md$/.test(userPath) ? "foresight" : userPath.startsWith(`users/${scope.ownerId}/.atomic_facts/`) && /\/atomic_fact-\d{4}-\d{2}-\d{2}\.md$/.test(userPath) ? "atomic_fact" : void 0;
22949
23334
  if (dailyKind) {
22950
23335
  for (const match of text2.matchAll(/<!-- entry:([^\s<>]+) -->([\s\S]*?)<!-- \/entry:\1 -->/g)) {