engine7 7.1.144 → 7.1.145

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.
@@ -632,7 +632,7 @@ function validateTravelChannelConfiguration(channels) {
632
632
  if (name === "emotion" || value?.enabled !== true) continue;
633
633
  if (!["feishu", "discord", "wechat"].includes(name)) throw new Error("TRAVEL_CHANNEL_NOT_CONTROLLED");
634
634
  if (value.mode !== "remote-only") throw new Error("TRAVEL_REMOTE_ONLY_REQUIRED");
635
- const hasPlatformSecret = (block) => block && typeof block === "object" && Object.entries(block).some(([key2, v]) => ["appSecret", "token", "accessToken", "tenantAccessToken", "app_secret", "botToken", "bot_token"].includes(key2) && typeof v === "string" && !!v.trim() || v && typeof v === "object" && hasPlatformSecret(v));
635
+ const hasPlatformSecret = (block) => block && typeof block === "object" && Object.entries(block).some(([key4, v]) => ["appSecret", "token", "accessToken", "tenantAccessToken", "app_secret", "botToken", "bot_token"].includes(key4) && typeof v === "string" && !!v.trim() || v && typeof v === "object" && hasPlatformSecret(v));
636
636
  if (hasPlatformSecret(value)) throw new Error("TRAVEL_PLATFORM_SECRET_PRESENT");
637
637
  let url;
638
638
  try {
@@ -1378,15 +1378,15 @@ var init_sqlite_replication = __esm({
1378
1378
  requireForeignKeys(this.db);
1379
1379
  if (captureGuardHash(this.db) !== this.guardHash) throw new Error("REPLICATION_GUARD_MISMATCH");
1380
1380
  if (sqliteReplicationSchemaHash(this.db) !== this.schemaHash) throw new Error("REPLICATION_SCHEMA_MISMATCH");
1381
- const before = sequences(this.db, this.excludedTables), sessions = [];
1381
+ const before = sequences(this.db, this.excludedTables), sessions2 = [];
1382
1382
  try {
1383
- if (this.sessionTables) for (const table of this.sessionTables) sessions.push(this.db.createSession({ table }));
1384
- else sessions.push(this.db.createSession());
1383
+ if (this.sessionTables) for (const table of this.sessionTables) sessions2.push(this.db.createSession({ table }));
1384
+ else sessions2.push(this.db.createSession());
1385
1385
  } catch (error) {
1386
- for (const session of sessions) session.close();
1386
+ for (const session of sessions2) session.close();
1387
1387
  throw error;
1388
1388
  }
1389
- this.active = { sessions, sequences: before, closed: false };
1389
+ this.active = { sessions: sessions2, sequences: before, closed: false };
1390
1390
  return this.active;
1391
1391
  }
1392
1392
  appendCapture(capture) {
@@ -1849,10 +1849,10 @@ var init_live = __esm({
1849
1849
  /** 安全取子段('services.voice-chat.start' → current.services.voice-chat.start) */
1850
1850
  get(dotPath) {
1851
1851
  if (!this.current) return void 0;
1852
- return dotPath.split(".").reduce((acc, key2) => {
1852
+ return dotPath.split(".").reduce((acc, key4) => {
1853
1853
  if (acc == null) return void 0;
1854
- if (key2 === "__proto__" || key2 === "constructor" || key2 === "prototype") return void 0;
1855
- return acc[key2];
1854
+ if (key4 === "__proto__" || key4 === "constructor" || key4 === "prototype") return void 0;
1855
+ return acc[key4];
1856
1856
  }, this.current);
1857
1857
  }
1858
1858
  /** reload 时原地更新(Object.assign 保持引用不变)
@@ -2018,9 +2018,9 @@ function toWall(i = /* @__PURE__ */ new Date()) {
2018
2018
  return `${p.y}-${p2(p.mo)}-${p2(p.d)} ${p2(p.hh)}:${p2(p.mm)}:${p2(p.ss)}`;
2019
2019
  }
2020
2020
  function warnOnce(callSite, shape, sample) {
2021
- const key2 = `${callSite}:${shape}`;
2022
- if (warned.has(key2)) return;
2023
- warned.add(key2);
2021
+ const key4 = `${callSite}:${shape}`;
2022
+ if (warned.has(key4)) return;
2023
+ warned.add(key4);
2024
2024
  console.warn(`[clock] ${callSite} \u5951\u7EA6\u8FDD\u89C4(${shape})\uFF0C\u6837\u672C: ${String(sample).slice(0, 80)}`);
2025
2025
  }
2026
2026
  function zoneOffsetMs(d) {
@@ -2168,11 +2168,11 @@ var init_filters = __esm({
2168
2168
  import { createHash as createHash5 } from "node:crypto";
2169
2169
  function scopeId(scope) {
2170
2170
  if ([scope.ownerId, scope.appId, scope.projectId].some((value) => typeof value !== "string" || !value.trim())) throw new Error("Invalid memory scope");
2171
- const key2 = JSON.stringify([scope.ownerId, scope.appId, scope.projectId]);
2172
- const cached2 = scopeIdMemo.get(key2);
2171
+ const key4 = JSON.stringify([scope.ownerId, scope.appId, scope.projectId]);
2172
+ const cached2 = scopeIdMemo.get(key4);
2173
2173
  if (cached2) return cached2;
2174
2174
  const id3 = "scope_" + createHash5("sha256").update(JSON.stringify([scope.ownerId, scope.appId, scope.projectId])).digest("hex");
2175
- scopeIdMemo.set(key2, id3);
2175
+ scopeIdMemo.set(key4, id3);
2176
2176
  return id3;
2177
2177
  }
2178
2178
  var scopeIdMemo;
@@ -2185,10 +2185,14 @@ var init_scope = __esm({
2185
2185
 
2186
2186
  // src/mem7/core/state/temporal.ts
2187
2187
  function instant(value) {
2188
- if (!/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/.test(value)) throw new Error("TIME_REQUIRED: explicit UTC offset required");
2189
- if (!isCalendarDate(value.substring(0, 10))) throw new Error("INVALID_TIME");
2190
- const time = Date.parse(value);
2191
- if (!Number.isFinite(time)) throw new Error("INVALID_TIME");
2188
+ let text2 = value;
2189
+ if (typeof text2 !== "string" || !INSTANT.test(text2)) {
2190
+ text2 = typeof value === "string" ? value.trim().replace(/^(\d{4}-\d{2}-\d{2}) /, "$1T").replace(/([+-]\d{2})(\d{2})$/, "$1:$2") : value;
2191
+ if (typeof text2 !== "string" || !INSTANT.test(text2)) throw new Error(`TIME_REQUIRED: explicit UTC offset required \u2014 \u6536\u5230 ${received(value)}\uFF1B${INSTANT_FORMAT}`);
2192
+ }
2193
+ if (!isCalendarDate(text2.substring(0, 10))) throw new Error(`INVALID_TIME: \u4E0D\u662F\u6709\u6548\u7684\u65E5\u5386\u65E5\u671F \u2014 \u6536\u5230 ${received(value)}`);
2194
+ const time = Date.parse(text2);
2195
+ if (!Number.isFinite(time)) throw new Error(`INVALID_TIME \u2014 \u6536\u5230 ${received(value)}\uFF1B${INSTANT_FORMAT}`);
2192
2196
  return new Date(time).toISOString();
2193
2197
  }
2194
2198
  function isCalendarDate(value) {
@@ -2201,7 +2205,7 @@ function validateTimezone(timezone) {
2201
2205
  try {
2202
2206
  new Intl.DateTimeFormat("en", { timeZone: timezone });
2203
2207
  } catch {
2204
- throw new Error("INVALID_TIMEZONE");
2208
+ throw new Error(`INVALID_TIMEZONE: timezone \u7528 IANA \u65F6\u533A\u540D\uFF0C\u5982 Asia/Shanghai\uFF08\u6536\u5230 ${String(timezone).slice(0, 60)}\uFF09`);
2205
2209
  }
2206
2210
  }
2207
2211
  function localInstant(date, time, timezone) {
@@ -2233,10 +2237,13 @@ function localInstant(date, time, timezone) {
2233
2237
  return new Date([...matches][0]).toISOString();
2234
2238
  }
2235
2239
  function normalizeValidity(value) {
2240
+ for (const field of ["validFrom", "validTo"]) {
2241
+ if (value[field] === void 0) throw new Error(`TIME_REQUIRED: validity.${field} \u7F3A\u5931 \u2014 validFrom\u3001validTo\u3001precision \u4E09\u4E2A\u952E\u90FD\u8981\u5199\uFF1BvalidFrom\u3001validTo \u6CA1\u6709\u5C31\u5199 null\uFF0Cprecision \u53EA\u80FD\u662F exact/observed/unknown\uFF1B${INSTANT_FORMAT}`);
2242
+ }
2236
2243
  const validFrom = value.validFrom === null ? null : instant(value.validFrom);
2237
2244
  const validTo = value.validTo === null ? null : instant(value.validTo);
2238
- if (validFrom !== null && validTo !== null && validFrom >= validTo) throw new Error("INVALID_INTERVAL: expected [from,to)");
2239
- if (!["exact", "observed", "unknown"].includes(value.precision)) throw new Error("INVALID_PRECISION");
2245
+ if (validFrom !== null && validTo !== null && validFrom >= validTo) throw new Error("INVALID_INTERVAL: \u9700\u8981 [validFrom, validTo) \u4E14 validFrom \u65E9\u4E8E validTo\uFF1B\u6CA1\u6709\u8D77\u70B9\u586B null\uFF0C\u53EA\u7ED3\u675F\u5173\u7CFB\u7528 changeKind=close");
2246
+ if (!["exact", "observed", "unknown"].includes(value.precision)) throw new Error("INVALID_PRECISION: precision \u53EA\u80FD\u662F exact\uFF08\u786E\u5207\u65F6\u523B\uFF09\u3001observed\uFF08\u89C2\u5BDF\u5230\u7684\u5927\u81F4\u65F6\u95F4\uFF09\u3001unknown\uFF08\u65F6\u95F4\u4E0D\u660E\uFF09");
2240
2247
  if (value.timezone) validateTimezone(value.timezone);
2241
2248
  return { ...value, validFrom, validTo };
2242
2249
  }
@@ -2246,16 +2253,20 @@ function overlaps(a, b) {
2246
2253
  function canonicalJson(value) {
2247
2254
  const normalize6 = (input) => {
2248
2255
  if (Array.isArray(input)) return input.map(normalize6);
2249
- if (input && typeof input === "object") return Object.fromEntries(Object.entries(input).filter(([, entry]) => entry !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key2, entry]) => [key2, normalize6(entry)]));
2256
+ if (input && typeof input === "object") return Object.fromEntries(Object.entries(input).filter(([, entry]) => entry !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key4, entry]) => [key4, normalize6(entry)]));
2250
2257
  return input;
2251
2258
  };
2252
2259
  const json = JSON.stringify(normalize6(value));
2253
2260
  if (json === void 0) throw new Error("INVALID_JSON_VALUE");
2254
2261
  return json;
2255
2262
  }
2263
+ var INSTANT, INSTANT_FORMAT, received;
2256
2264
  var init_temporal = __esm({
2257
2265
  "src/mem7/core/state/temporal.ts"() {
2258
2266
  "use strict";
2267
+ INSTANT = /^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/;
2268
+ INSTANT_FORMAT = '\u65F6\u95F4\u7528\u5E26\u65F6\u533A\u504F\u79FB\u7684\u5B8C\u6574\u65F6\u523B\uFF0C\u5982 "2026-11-24T09:10:41+08:00"\uFF08\u65E5\u671F\u4E0E\u65F6\u95F4\u4E4B\u95F4\u7528 T \u6216\u7A7A\u683C\uFF0C\u7ED3\u5C3E\u662F Z \u6216 \xB1HH:MM\uFF09';
2269
+ received = (value) => (JSON.stringify(value) ?? String(value)).slice(0, 80);
2259
2270
  }
2260
2271
  });
2261
2272
 
@@ -2280,8 +2291,8 @@ function contextTimeKey(db2, scopeId2, validAt) {
2280
2291
  }
2281
2292
  return `valid-window:${from}:${to}`;
2282
2293
  }
2283
- function assertContextTime(key2, now2 = Date.now()) {
2284
- const match = key2.match(/^valid-window:(-?\d+):(-?\d+)$/);
2294
+ function assertContextTime(key4, now2 = Date.now()) {
2295
+ const match = key4.match(/^valid-window:(-?\d+):(-?\d+)$/);
2285
2296
  if (!match || !Number.isSafeInteger(Number(match[1])) || !Number.isSafeInteger(Number(match[2])) || Number(match[1]) >= Number(match[2])) throw new Error("INVALID_CONTEXT_TIME_DEPENDENCY");
2286
2297
  if (now2 < Number(match[1]) || now2 >= Number(match[2])) throw new Error("CONTEXT_TIME_EXPIRED");
2287
2298
  }
@@ -2386,9 +2397,9 @@ function append(db2, scope, kind, id3, payload) {
2386
2397
  return Number(result.lastInsertRowid);
2387
2398
  }
2388
2399
  function recordArtifactBasis(db2, scope, kind, id3, version, dependencies) {
2389
- const key2 = basisKey(kind, id3, version);
2390
- if (!db2.prepare("SELECT 1 FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=?").get(scopeId(scope), key2)) {
2391
- append(db2, scope, "artifact.basis", key2, { dependencies });
2400
+ const key4 = basisKey(kind, id3, version);
2401
+ if (!db2.prepare("SELECT 1 FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=?").get(scopeId(scope), key4)) {
2402
+ append(db2, scope, "artifact.basis", key4, { dependencies });
2392
2403
  }
2393
2404
  }
2394
2405
  var ARTIFACT_HISTORY_SCHEMA, hash3, basisKey, stateKey, generationKinds, normalizedRefs, ArtifactHistory;
@@ -2538,8 +2549,8 @@ END;
2538
2549
  if (cutoff) return historicalRow(this.db, scope, "artifact.basis", basisKey(kind, id3, version), cutoff)?.dependencies ?? null;
2539
2550
  return this.dependencies.version(scope, kind, id3) === version ? this.dependencies.refs(scope, kind, id3) : null;
2540
2551
  }
2541
- scopeContextRetained(scope, key2) {
2542
- const basis = this.db.prepare("SELECT history_id FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=? ORDER BY history_id LIMIT 1").get(scopeId(scope), key2);
2552
+ scopeContextRetained(scope, key4) {
2553
+ const basis = this.db.prepare("SELECT history_id FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=? ORDER BY history_id LIMIT 1").get(scopeId(scope), key4);
2543
2554
  if (!basis) return false;
2544
2555
  const atGeneration = historicalRow(this.db, scope, "scope", "state", { historyId: basis.history_id, time: null, complete: true });
2545
2556
  if (!atGeneration) return false;
@@ -2557,15 +2568,15 @@ END;
2557
2568
  WHERE scope_id=? AND source_id=? AND interpretation_status<>'deleted'`).get(scopeKey, sourceId));
2558
2569
  const walk = (kind2, id4, version2) => {
2559
2570
  checkMemoryReadBudget(visited.size);
2560
- const key2 = basisKey(kind2, id4, version2);
2561
- if (memo.has(key2)) return memo.get(key2);
2562
- if (visited.has(key2)) return false;
2563
- visited.add(key2);
2571
+ const key4 = basisKey(kind2, id4, version2);
2572
+ if (memo.has(key4)) return memo.get(key4);
2573
+ if (visited.has(key4)) return false;
2574
+ visited.add(key4);
2564
2575
  try {
2565
- const basis = this.db.prepare("SELECT history_id,payload_json FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=? ORDER BY history_id LIMIT 1").get(scopeKey, key2);
2576
+ const basis = this.db.prepare("SELECT history_id,payload_json FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=? ORDER BY history_id LIMIT 1").get(scopeKey, key4);
2566
2577
  const refs = basis && JSON.parse(basis.payload_json).dependencies;
2567
2578
  if (!refs || this.db.prepare("SELECT 1 FROM memory_tombstones WHERE scope_id=? AND target_kind=? AND target_id=?").get(scopeKey, kind2, id4)) return false;
2568
- if (refs.some((ref) => ref.parentKind === "scope" && !ref.parentId.startsWith("valid-window:")) && !this.scopeContextRetained(scope, key2)) return false;
2579
+ if (refs.some((ref) => ref.parentKind === "scope" && !ref.parentId.startsWith("valid-window:")) && !this.scopeContextRetained(scope, key4)) return false;
2569
2580
  const retained = refs.every((ref) => {
2570
2581
  checkMemoryReadBudget(visited.size);
2571
2582
  if (ref.parentKind === "source") return sourceRetained(ref.parentId);
@@ -2585,10 +2596,10 @@ END;
2585
2596
  }
2586
2597
  return true;
2587
2598
  });
2588
- memo.set(key2, retained);
2599
+ memo.set(key4, retained);
2589
2600
  return retained;
2590
2601
  } finally {
2591
- visited.delete(key2);
2602
+ visited.delete(key4);
2592
2603
  }
2593
2604
  };
2594
2605
  return walk(kind, id3, version);
@@ -2614,8 +2625,8 @@ END;
2614
2625
  };
2615
2626
  const walk = (parentKind, parentId, parentVersion, ancestors) => {
2616
2627
  checkMemoryReadBudget(ancestors.size);
2617
- const key2 = basisKey(parentKind, parentId, parentVersion);
2618
- if (ancestors.has(key2)) return false;
2628
+ const key4 = basisKey(parentKind, parentId, parentVersion);
2629
+ if (ancestors.has(key4)) return false;
2619
2630
  const state = this.state(scope, parentKind, parentId, cutoff);
2620
2631
  if (state?.state !== "current" || state.version !== parentVersion) return false;
2621
2632
  if (this.db.prepare("SELECT 1 FROM memory_tombstones WHERE scope_id=? AND target_kind=? AND target_id=?").get(scopeId(scope), parentKind, parentId)) return false;
@@ -2630,9 +2641,9 @@ END;
2630
2641
  }
2631
2642
  }
2632
2643
  if (refs.some((ref) => ref.parentKind === "scope" && !ref.parentId.startsWith("valid-window:"))) {
2633
- if (!this.scopeContextRetained(scope, key2)) return false;
2644
+ if (!this.scopeContextRetained(scope, key4)) return false;
2634
2645
  }
2635
- const next = new Set(ancestors).add(key2);
2646
+ const next = new Set(ancestors).add(key4);
2636
2647
  for (const ref of refs) {
2637
2648
  checkMemoryReadBudget(next.size);
2638
2649
  if (ref.parentKind === "source") {
@@ -2779,9 +2790,9 @@ function invalidateChildren(db2, scope, pending, reason) {
2779
2790
  let referencedPlan;
2780
2791
  while (pending.length) {
2781
2792
  const child = pending.shift();
2782
- const key2 = JSON.stringify([child.child_kind, child.child_id]);
2783
- if (visited.has(key2) && (visited.get(key2) || !child.deleted)) continue;
2784
- visited.set(key2, Boolean(child.deleted));
2793
+ const key4 = JSON.stringify([child.child_kind, child.child_id]);
2794
+ if (visited.has(key4) && (visited.get(key4) || !child.deleted)) continue;
2795
+ visited.set(key4, Boolean(child.deleted));
2785
2796
  if (child.child_kind === "graph_plan") {
2786
2797
  referencedPlan ??= db2.prepare(`SELECT 1 WHERE EXISTS (SELECT 1 FROM memory_dependencies
2787
2798
  WHERE scope_id=? AND parent_kind='artifact' AND parent_id=?)
@@ -2862,8 +2873,8 @@ var init_dependencies = __esm({
2862
2873
  this.snapshotStamp = void 0;
2863
2874
  }
2864
2875
  }
2865
- observeTimeBoundary(key2) {
2866
- const match = key2.match(/^valid-window:(-?\d+):(-?\d+)$/);
2876
+ observeTimeBoundary(key4) {
2877
+ const match = key4.match(/^valid-window:(-?\d+):(-?\d+)$/);
2867
2878
  if (!match) return;
2868
2879
  const now2 = Date.now();
2869
2880
  for (const boundary of [Number(match[1]), Number(match[2])]) {
@@ -2945,9 +2956,9 @@ var init_dependencies = __esm({
2945
2956
  }
2946
2957
  artifactTimeCurrent(scope, kind, id3, visited = /* @__PURE__ */ new Set(), memo) {
2947
2958
  checkMemoryReadBudget(visited.size);
2948
- const key2 = JSON.stringify([kind, id3]);
2949
- if (visited.has(key2)) return false;
2950
- visited.add(key2);
2959
+ const key4 = JSON.stringify([kind, id3]);
2960
+ if (visited.has(key4)) return false;
2961
+ visited.add(key4);
2951
2962
  try {
2952
2963
  const refs = this.refs(scope, kind, id3);
2953
2964
  for (const ref of refs.filter((ref2) => ref2.parentKind !== "artifact")) {
@@ -2982,7 +2993,7 @@ var init_dependencies = __esm({
2982
2993
  }
2983
2994
  return true;
2984
2995
  } finally {
2985
- visited.delete(key2);
2996
+ visited.delete(key4);
2986
2997
  }
2987
2998
  }
2988
2999
  version(scope, kind, id3) {
@@ -3181,6 +3192,28 @@ var init_timing = __esm({
3181
3192
  }
3182
3193
  });
3183
3194
 
3195
+ // src/mem7/core/lance-cache.ts
3196
+ function memoryLanceSession(lance) {
3197
+ if (typeof lance.Session !== "function") return void 0;
3198
+ let session = sessions.get(lance);
3199
+ if (!session) {
3200
+ session = new lance.Session(BigInt(LANCE_INDEX_CACHE_BYTES), BigInt(LANCE_METADATA_CACHE_BYTES));
3201
+ sessions.set(lance, session);
3202
+ }
3203
+ return session;
3204
+ }
3205
+ var LANCE_INDEX_CACHE_BYTES, LANCE_METADATA_CACHE_BYTES, key, globals, sessions;
3206
+ var init_lance_cache = __esm({
3207
+ "src/mem7/core/lance-cache.ts"() {
3208
+ "use strict";
3209
+ LANCE_INDEX_CACHE_BYTES = 256 * 1024 * 1024;
3210
+ LANCE_METADATA_CACHE_BYTES = 64 * 1024 * 1024;
3211
+ key = Symbol.for("engine7.mem7.lanceCacheSessions");
3212
+ globals = globalThis;
3213
+ sessions = globals[key] ??= /* @__PURE__ */ new WeakMap();
3214
+ }
3215
+ });
3216
+
3184
3217
  // src/mem7/core/vector-store.ts
3185
3218
  import { mkdirSync as mkdirSync5, existsSync as existsSync3 } from "node:fs";
3186
3219
  import { DatabaseSync as DatabaseSync5 } from "node:sqlite";
@@ -3330,6 +3363,7 @@ var init_vector_store = __esm({
3330
3363
  init_read_guard();
3331
3364
  init_timing();
3332
3365
  init_runtime_authority();
3366
+ init_lance_cache();
3333
3367
  isIntelMac = process.platform === "darwin" && process.arch === "x64";
3334
3368
  lancePromise = null;
3335
3369
  mem7VectorWarning = null;
@@ -3416,7 +3450,7 @@ var init_vector_store = __esm({
3416
3450
  /** Reuse expensive dependency walks, but bind each verdict to SQL, time and the actual indexed body. */
3417
3451
  cachedRowVisible(ledger, kind, row, dependencies) {
3418
3452
  if (!dependencies) return vectorRowVisible(ledger, kind, row);
3419
- const key2 = kind + ":" + String(row.id);
3453
+ const key4 = kind + ":" + String(row.id);
3420
3454
  let signature2;
3421
3455
  try {
3422
3456
  signature2 = JSON.stringify([
@@ -3440,11 +3474,11 @@ var init_vector_store = __esm({
3440
3474
  this.visibleCacheVersion = version;
3441
3475
  this.visibleCache.clear();
3442
3476
  }
3443
- const cached2 = this.visibleCache.get(key2);
3477
+ const cached2 = this.visibleCache.get(key4);
3444
3478
  if (cached2?.signature === signature2) return cached2.verdict;
3445
3479
  const verdict = vectorRowVisible(ledger, kind, row, dependencies);
3446
3480
  if (dependencies.cacheRevision() !== version) return false;
3447
- this.visibleCache.set(key2, { signature: signature2, verdict });
3481
+ this.visibleCache.set(key4, { signature: signature2, verdict });
3448
3482
  return verdict;
3449
3483
  }
3450
3484
  visibleCache = /* @__PURE__ */ new Map();
@@ -3465,7 +3499,8 @@ var init_vector_store = __esm({
3465
3499
  assertRuntimeAuthority(this.stateDir, "WRITE");
3466
3500
  mkdirSync5(this.dir, { recursive: true });
3467
3501
  }
3468
- this.db = await lance.connect(this.dir);
3502
+ const session = memoryLanceSession(lance);
3503
+ this.db = await lance.connect(this.dir, session ? { session } : void 0);
3469
3504
  }
3470
3505
  return this.db;
3471
3506
  }
@@ -3942,11 +3977,11 @@ var init_vector_store = __esm({
3942
3977
  const rrf = /* @__PURE__ */ new Map();
3943
3978
  const add = (list) => {
3944
3979
  list.forEach((h, i) => {
3945
- const key2 = h.text.replace(/\s+/g, "");
3980
+ const key4 = h.text.replace(/\s+/g, "");
3946
3981
  const contrib = 1 / (RRF_K + i + 1);
3947
- const cur = rrf.get(key2);
3982
+ const cur = rrf.get(key4);
3948
3983
  if (cur) cur.score += contrib;
3949
- else rrf.set(key2, { hit: h, score: contrib });
3984
+ else rrf.set(key4, { hit: h, score: contrib });
3950
3985
  });
3951
3986
  };
3952
3987
  add(dense);
@@ -4174,8 +4209,8 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
4174
4209
  * 事件重放失败一次即回死信+skip,不重烧 5 轮预算)。先 UPDATE 后记账:中间崩溃只会
4175
4210
  * 多治一次(幂等无害),反过来会出现"记了账但没治"的永久死锁。 */
4176
4211
  reenqueueGapPrefix(sinkId, head, now2 = Date.now()) {
4177
- const key2 = `${sinkId}:${head.scopeId}:${head.eventSeq}`;
4178
- if (this.healedGaps.has(key2)) return;
4212
+ const key4 = `${sinkId}:${head.scopeId}:${head.eventSeq}`;
4213
+ if (this.healedGaps.has(key4)) return;
4179
4214
  const ledgerPath = this.gapHealLedgerPath;
4180
4215
  let ledger = {};
4181
4216
  if (ledgerPath) {
@@ -4183,8 +4218,8 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
4183
4218
  ledger = JSON.parse(readFileSync4(ledgerPath, "utf8"))?.heals ?? {};
4184
4219
  } catch {
4185
4220
  }
4186
- if (Number.isFinite(ledger[key2])) {
4187
- this.healedGaps.add(key2);
4221
+ if (Number.isFinite(ledger[key4])) {
4222
+ this.healedGaps.add(key4);
4188
4223
  return;
4189
4224
  }
4190
4225
  }
@@ -4198,11 +4233,11 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
4198
4233
  const count = Number(result?.changes ?? 0);
4199
4234
  if (count > 0) console.warn(`[mem7] \u5E8F\u5217\u7F3A\u53E3\u81EA\u6108\uFF1Ahead seq=${head.eventSeq} \u524D ${count} \u6761\u5DF2 ack \u6295\u9012\u884C\u91CD\u7F6E\u5F85\u6295\uFF08\u65B0\u56FE\u5982\u5B9E\u91CD\u653E / \u65E7\u56FE\u5E42\u7B49 duplicate-ack\uFF1B\u6B7B\u4FE1\u884C\u4FDD\u7559 attempts\uFF09`);
4200
4235
  });
4201
- this.healedGaps.add(key2);
4236
+ this.healedGaps.add(key4);
4202
4237
  if (!ledgerPath) return;
4203
4238
  const cutoff = now2 - _ChangeFeed.GAP_HEAL_RETENTION_MS, retained = {};
4204
4239
  for (const [entry, at] of Object.entries(ledger)) if (Number.isFinite(at) && at >= cutoff) retained[entry] = at;
4205
- retained[key2] = now2;
4240
+ retained[key4] = now2;
4206
4241
  const temp = `${ledgerPath}.${randomUUID5()}.tmp`;
4207
4242
  try {
4208
4243
  writeFileSync4(temp, JSON.stringify({ version: 1, heals: retained }));
@@ -4327,7 +4362,7 @@ function validatePredicateValue(predicate, value) {
4327
4362
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("INVALID_FACT_VALUE");
4328
4363
  const object3 = value;
4329
4364
  const allowed = predicate === "activity.schedule" ? ["frequency", "weekday", "date", "localTime", "timezone", "durationMinutes"] : predicate === "person.residence" ? ["place"] : predicate === "relation.open" ? ["entityId", "label", "direction", "perspectiveEntityId", "relationshipId", "semanticVersion", "body", "contentKind", "temporalScope", "certainty", "observedAsCurrentAt", "attribution", "attributionQuote", "realm", "sensitivity"] : ["entityId"];
4330
- if (Object.keys(object3).some((key2) => !allowed.includes(key2))) throw new Error("INVALID_FACT_VALUE: unknown field");
4365
+ if (Object.keys(object3).some((key4) => !allowed.includes(key4))) throw new Error("INVALID_FACT_VALUE: unknown field");
4331
4366
  if (predicate === "activity.schedule") {
4332
4367
  const schedule = object3;
4333
4368
  if (!["weekly", "once"].includes(schedule.frequency) || !/^([01]\d|2[0-3]):[0-5]\d$/.test(schedule.localTime) || !Number.isInteger(schedule.durationMinutes) || schedule.durationMinutes <= 0 || schedule.durationMinutes > 1440) throw new Error("INVALID_SCHEDULE");
@@ -4549,8 +4584,8 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
4549
4584
  ).all(scopeId(scope), `%${word.replace(/[!%_]/g, (character) => "!" + character)}%`, limit2);
4550
4585
  return rows.map((row) => this.source(row));
4551
4586
  }
4552
- snapshotRead(key2, load) {
4553
- return this.snapshotReads ? this.snapshotReads.read(JSON.stringify(key2), load) : load();
4587
+ snapshotRead(key4, load) {
4588
+ return this.snapshotReads ? this.snapshotReads.read(JSON.stringify(key4), load) : load();
4554
4589
  }
4555
4590
  receive(input, options = {}) {
4556
4591
  const id3 = scopeId(input.scope);
@@ -4731,8 +4766,8 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
4731
4766
  const result = { applied: 0, needsReview: 0, failed: 0, received: 0 };
4732
4767
  const rows = cutoff ? historicalRows(this.db, scope, "source", cutoff).map((row) => ({ state: row.state, count: 1 })) : this.db.prepare("SELECT interpretation_status state,COUNT(*) count FROM memory_sources WHERE scope_id=? GROUP BY interpretation_status").all(scopeId(scope));
4733
4768
  for (const row of rows) {
4734
- const key2 = row.state === "needs_review" ? "needsReview" : row.state;
4735
- if (Object.hasOwn(result, key2)) result[key2] += Number(row.count);
4769
+ const key4 = row.state === "needs_review" ? "needsReview" : row.state;
4770
+ if (Object.hasOwn(result, key4)) result[key4] += Number(row.count);
4736
4771
  }
4737
4772
  return result;
4738
4773
  }
@@ -5156,13 +5191,13 @@ function purgeRecoveryEvidence(db2, graph) {
5156
5191
  db2.prepare("UPDATE e7_recovery_items SET result=? WHERE item_id=?").run(JSON.stringify(item), saved.item_id);
5157
5192
  }
5158
5193
  }
5159
- var text, key, RecoveryDeletionGraph;
5194
+ var text, key2, RecoveryDeletionGraph;
5160
5195
  var init_recovery_deletion = __esm({
5161
5196
  "src/continuity/recovery-deletion.ts"() {
5162
5197
  "use strict";
5163
5198
  init_recovery_deletion_sources();
5164
- text = (row, key2) => row[key2]?.[0] === "text" ? row[key2][1] : void 0;
5165
- key = (scope, kind, id3) => JSON.stringify([scope, kind, id3]);
5199
+ text = (row, key4) => row[key4]?.[0] === "text" ? row[key4][1] : void 0;
5200
+ key2 = (scope, kind, id3) => JSON.stringify([scope, kind, id3]);
5166
5201
  RecoveryDeletionGraph = class {
5167
5202
  edges = /* @__PURE__ */ new Map();
5168
5203
  roots = /* @__PURE__ */ new Set();
@@ -5175,10 +5210,10 @@ var init_recovery_deletion = __esm({
5175
5210
  constructor(deletions) {
5176
5211
  if (deletions.length > 1e5) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
5177
5212
  for (const d of deletions) {
5178
- this.roots.add(key(d.scopeId, "source", d.sourceId));
5213
+ this.roots.add(key2(d.scopeId, "source", d.sourceId));
5179
5214
  if (d.version !== void 0) {
5180
5215
  if (!Number.isSafeInteger(d.version) || d.version < 1) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
5181
- const sourceKey = key(d.scopeId, "source", d.sourceId), prior = this.deletionVersions.get(sourceKey);
5216
+ const sourceKey = key2(d.scopeId, "source", d.sourceId), prior = this.deletionVersions.get(sourceKey);
5182
5217
  if (prior !== void 0 && prior !== d.version) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
5183
5218
  this.deletionVersions.set(sourceKey, d.version);
5184
5219
  }
@@ -5193,7 +5228,7 @@ var init_recovery_deletion = __esm({
5193
5228
  links(table, row) {
5194
5229
  const scope = text(row, "scope_id");
5195
5230
  if (!scope) return { owners: [], parents: [] };
5196
- const node = (kind2, id3) => id3 ? [key(scope, kind2, id3)] : [];
5231
+ const node = (kind2, id3) => id3 ? [key2(scope, kind2, id3)] : [];
5197
5232
  const source = text(row, "source_id"), fact = text(row, "assertion_id");
5198
5233
  const artifact = text(row, "artifact_id") ?? text(row, "child_id") ?? text(row, "entry_id");
5199
5234
  const owners = fact ? node("fact", fact) : artifact ? node("artifact", artifact) : source ? node("source", source) : node("entity", text(row, "entity_id"));
@@ -5217,19 +5252,19 @@ var init_recovery_deletion = __esm({
5217
5252
  if (!ref || typeof ref !== "object") continue;
5218
5253
  const refScope = typeof ref.scopeId === "string" ? ref.scopeId : typeof ref.scope_id === "string" ? ref.scope_id : scope;
5219
5254
  for (const [field2, kind2] of [["sourceId", "source"], ["source_id", "source"], ["assertionId", "fact"], ["assertion_id", "fact"], ["artifactId", "artifact"], ["artifact_id", "artifact"], ["entryId", "artifact"], ["entry_id", "artifact"]]) {
5220
- if (typeof ref[field2] === "string") parents.push(key(refScope, kind2, ref[field2]));
5255
+ if (typeof ref[field2] === "string") parents.push(key2(refScope, kind2, ref[field2]));
5221
5256
  }
5222
- if (typeof ref.parentId === "string" && ["source", "fact", "entity", "artifact"].includes(ref.parentKind)) parents.push(key(refScope, ref.parentKind, ref.parentId));
5257
+ if (typeof ref.parentId === "string" && ["source", "fact", "entity", "artifact"].includes(ref.parentKind)) parents.push(key2(refScope, ref.parentKind, ref.parentId));
5223
5258
  pending.push(...Object.values(ref).filter((value) => value && typeof value === "object"));
5224
5259
  }
5225
5260
  }
5226
5261
  if (table === "memory_knowledge_history") {
5227
5262
  const kind2 = text(row, "target_kind"), target = text(row, "target_id");
5228
- if (kind2 === "source" && target) parents.push(key(scope, "source", target));
5263
+ if (kind2 === "source" && target) parents.push(key2(scope, "source", target));
5229
5264
  if (kind2?.startsWith("artifact.") && target) {
5230
5265
  try {
5231
5266
  const parts = JSON.parse(target);
5232
- if (Array.isArray(parts) && typeof parts[1] === "string") parents.push(key(scope, "artifact", parts[1]));
5267
+ if (Array.isArray(parts) && typeof parts[1] === "string") parents.push(key2(scope, "artifact", parts[1]));
5233
5268
  } catch {
5234
5269
  }
5235
5270
  }
@@ -5237,7 +5272,7 @@ var init_recovery_deletion = __esm({
5237
5272
  if (table === "memory_sources" && source) {
5238
5273
  const origin = text(row, "origin_key");
5239
5274
  if (origin) {
5240
- const originNode = key(scope, "origin", origin), sourceNode = key(scope, "source", source);
5275
+ const originNode = key2(scope, "origin", origin), sourceNode = key2(scope, "source", source);
5241
5276
  this.edge(sourceNode, originNode);
5242
5277
  this.edge(originNode, sourceNode);
5243
5278
  const version = row.source_version?.[0] === "integer" ? Number(row.source_version[1]) : void 0;
@@ -5247,15 +5282,15 @@ var init_recovery_deletion = __esm({
5247
5282
  if (deletion.version === void 0) continue;
5248
5283
  if (!Number.isSafeInteger(deletion.version) || deletion.version < 1) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
5249
5284
  if (++this.deletionChecks > 1e6) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
5250
- if (recoveryOriginalSourceId(scope, origin, deletion.version) === deletion.sourceId) this.edge(key(scope, "source", deletion.sourceId), originNode);
5285
+ if (recoveryOriginalSourceId(scope, origin, deletion.version) === deletion.sourceId) this.edge(key2(scope, "source", deletion.sourceId), originNode);
5251
5286
  }
5252
5287
  this.familyProofs.add(originNode);
5253
5288
  }
5254
- if (text(row, "interpretation_status") === "deleted") this.roots.add(key(scope, "source", source));
5289
+ if (text(row, "interpretation_status") === "deleted") this.roots.add(key2(scope, "source", source));
5255
5290
  }
5256
5291
  if (table === "memory_tombstones") {
5257
5292
  const target = text(row, "target_id"), kind2 = text(row, "target_kind");
5258
- if (target && kind2) this.roots.add(key(scope, kind2, target));
5293
+ if (target && kind2) this.roots.add(key2(scope, kind2, target));
5259
5294
  }
5260
5295
  return { owners, parents };
5261
5296
  }
@@ -5663,9 +5698,9 @@ ALTER TABLE memory_host_turns ADD COLUMN owner_id TEXT;
5663
5698
  }
5664
5699
  }
5665
5700
  recordCompleted(id3, sourceId, sourceVersion, now2) {
5666
- const key2 = JSON.stringify(["host.turn.completed", id3, sourceId]);
5701
+ const key4 = JSON.stringify(["host.turn.completed", id3, sourceId]);
5667
5702
  this.db.prepare(`INSERT OR IGNORE INTO ome_jobs(kind,payload,status,next_run_at,created_at,job_key,scope_id,completed_at)
5668
- VALUES ('host.turn.completed',?,'done',?,?,?,?,?)`).run(JSON.stringify({ scopeId: id3, sourceId, sourceVersion }), now2, now2, key2, id3, now2);
5703
+ VALUES ('host.turn.completed',?,'done',?,?,?,?,?)`).run(JSON.stringify({ scopeId: id3, sourceId, sourceVersion }), now2, now2, key4, id3, now2);
5669
5704
  }
5670
5705
  };
5671
5706
  }
@@ -6293,7 +6328,7 @@ function recoverLegacySession(db2, store, mapping, files, apply = false) {
6293
6328
  return report;
6294
6329
  }
6295
6330
  function recoverLegacyProjections(db2, store, input, apply = false) {
6296
- const key2 = scopeId(input.scope);
6331
+ const key4 = scopeId(input.scope);
6297
6332
  const root = realpathSync3(input.root);
6298
6333
  const report = { files: 0, entries: 0, recoverable: 0, alreadyMapped: 0, unavailable: 0, reasons: {}, applied: false };
6299
6334
  const gap = (reason) => {
@@ -6338,7 +6373,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6338
6373
  const block = match[0];
6339
6374
  const field = (name) => match[2].match(new RegExp(`^\\*\\*${name}\\*\\*: ([^\\n]*)$`, "m"))?.[1]?.trim();
6340
6375
  const parent = field("parent_id");
6341
- const mapping = db2.prepare("SELECT * FROM memory_legacy_cell_maps WHERE cell_id=? AND scope_id=?").get(parent ?? "", key2);
6376
+ const mapping = db2.prepare("SELECT * FROM memory_legacy_cell_maps WHERE cell_id=? AND scope_id=?").get(parent ?? "", key4);
6342
6377
  if (!mapping || field("parent_type") !== "memcell" || field("owner_id") !== input.scope.ownerId || field("session_id") !== mapping.session_id) {
6343
6378
  gap("projection_parent_provenance_missing");
6344
6379
  continue;
@@ -6355,7 +6390,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6355
6390
  gap("projection_body_missing");
6356
6391
  continue;
6357
6392
  }
6358
- const previous = db2.prepare("SELECT * FROM memory_legacy_projection_maps WHERE scope_id=? AND kind=? AND entry_id=?").get(key2, kind, match[1]);
6393
+ const previous = db2.prepare("SELECT * FROM memory_legacy_projection_maps WHERE scope_id=? AND kind=? AND entry_id=?").get(key4, kind, match[1]);
6359
6394
  const target = join8(store.mem7RootPath(), path35);
6360
6395
  if (previous) {
6361
6396
  if (previous.source_file_hash !== fileHash || previous.parent_id !== parent || previous.source_relative_path !== path35 || !store.projectionMatches(input.scope, kind, match[1], target, block)) {
@@ -6407,7 +6442,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6407
6442
  role: "supports"
6408
6443
  })));
6409
6444
  const digest7 = hash4(candidate.block.trim());
6410
- db2.prepare("INSERT INTO memory_projection_entries VALUES (?,?,?,?,?,?)").run(key2, candidate.kind, candidate.id, candidate.relativePath, 1, digest7);
6445
+ db2.prepare("INSERT INTO memory_projection_entries VALUES (?,?,?,?,?,?)").run(key4, candidate.kind, candidate.id, candidate.relativePath, 1, digest7);
6411
6446
  store.artifacts.publish(input.scope, {
6412
6447
  kind: candidate.kind,
6413
6448
  id: candidate.id,
@@ -6419,7 +6454,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6419
6454
  summary: candidate.summary,
6420
6455
  title: candidate.title
6421
6456
  });
6422
- db2.prepare("INSERT INTO memory_legacy_projection_maps VALUES (?,?,?,?,?,?,?)").run(key2, candidate.kind, candidate.id, candidate.fileHash, candidate.relativePath, candidate.parent, 1);
6457
+ db2.prepare("INSERT INTO memory_legacy_projection_maps VALUES (?,?,?,?,?,?,?)").run(key4, candidate.kind, candidate.id, candidate.fileHash, candidate.relativePath, candidate.parent, 1);
6423
6458
  }
6424
6459
  });
6425
6460
  report.applied = true;
@@ -6551,10 +6586,10 @@ var init_recall_sources = __esm({
6551
6586
  }
6552
6587
  const queue = db2.prepare("SELECT target_id FROM memory_tombstones WHERE scope_id=? AND target_kind='source'").all(id3).map((row) => `s:${row.target_id}`);
6553
6588
  for (let index = 0; index < queue.length; index++) {
6554
- const key2 = queue[index];
6555
- if (this.removed.has(key2)) continue;
6556
- this.removed.add(key2);
6557
- queue.push(...dependents.get(key2) ?? []);
6589
+ const key4 = queue[index];
6590
+ if (this.removed.has(key4)) continue;
6591
+ this.removed.add(key4);
6592
+ queue.push(...dependents.get(key4) ?? []);
6558
6593
  }
6559
6594
  }
6560
6595
  sources = /* @__PURE__ */ new Map();
@@ -6729,9 +6764,9 @@ CREATE TABLE memory_person_mentions (
6729
6764
  ])];
6730
6765
  if (ids.length > 8192 || this.snapshot.relationships.size > 8192) return result;
6731
6766
  const sourceIds = JSON.stringify(ids.sort());
6732
- const relationshipRefs = JSON.stringify([...this.snapshot.relationships.keys()].sort().map((key2) => {
6733
- const split = key2.lastIndexOf(":");
6734
- return [key2.slice(0, split), Number(key2.slice(split + 1))];
6767
+ const relationshipRefs = JSON.stringify([...this.snapshot.relationships.keys()].sort().map((key4) => {
6768
+ const split = key4.lastIndexOf(":");
6769
+ return [key4.slice(0, split), Number(key4.slice(split + 1))];
6735
6770
  }));
6736
6771
  this.snapshotBasis = this.readProvenanceBasis(this.snapshot, sourceIds, relationshipRefs);
6737
6772
  }
@@ -6779,19 +6814,19 @@ CREATE TABLE memory_person_mentions (
6779
6814
  const sourceChecks = new Map(sources.map((row) => [row.id, JSON.stringify(row)]));
6780
6815
  const relationshipRows = /* @__PURE__ */ new Map();
6781
6816
  for (const row of relationships) {
6782
- const key2 = `${row.id}:${row.version}`;
6783
- const rows = relationshipRows.get(key2) ?? [];
6817
+ const key4 = `${row.id}:${row.version}`;
6818
+ const rows = relationshipRows.get(key4) ?? [];
6784
6819
  rows.push(row);
6785
- relationshipRows.set(key2, rows);
6820
+ relationshipRows.set(key4, rows);
6786
6821
  }
6787
- const relationshipChecks = new Map([...relationshipRows].map(([key2, rows]) => [key2, createHash15("sha256").update(JSON.stringify(rows)).digest("hex")]));
6822
+ const relationshipChecks = new Map([...relationshipRows].map(([key4, rows]) => [key4, createHash15("sha256").update(JSON.stringify(rows)).digest("hex")]));
6788
6823
  checkMemoryReadBudget();
6789
6824
  return { sourceIds, relationshipRefs, digest: digest7, sources: sourceChecks, relationships: relationshipChecks };
6790
6825
  }
6791
6826
  provenanceSnapshot(scope, cutoff) {
6792
6827
  const stamp = this.provenanceStamp();
6793
- const key2 = JSON.stringify([scopeId(scope), cutoff ?? null]);
6794
- if (stamp !== this.snapshotStamp && this.snapshot?.key === key2 && !cutoff && this.snapshotBasis && this.readSnapshotDepth && this.snapshot.sources.size <= 8192) {
6828
+ const key4 = JSON.stringify([scopeId(scope), cutoff ?? null]);
6829
+ if (stamp !== this.snapshotStamp && this.snapshot?.key === key4 && !cutoff && this.snapshotBasis && this.readSnapshotDepth && this.snapshot.sources.size <= 8192) {
6795
6830
  const previous = this.snapshotBasis;
6796
6831
  const next = this.readProvenanceBasis(this.snapshot, previous.sourceIds, previous.relationshipRefs);
6797
6832
  if (next.digest !== previous.digest) {
@@ -6803,17 +6838,17 @@ CREATE TABLE memory_person_mentions (
6803
6838
  this.snapshot.metadata.delete(id3);
6804
6839
  this.snapshot.currentSources.delete(id3);
6805
6840
  }
6806
- for (const [key3, check] of previous.relationships) {
6807
- if (next.relationships.get(key3) !== check) this.snapshot.relationships.delete(key3);
6841
+ for (const [key5, check] of previous.relationships) {
6842
+ if (next.relationships.get(key5) !== check) this.snapshot.relationships.delete(key5);
6808
6843
  }
6809
6844
  }
6810
6845
  this.snapshotBasis = next;
6811
6846
  this.snapshotStamp = stamp;
6812
6847
  }
6813
- if (stamp !== this.snapshotStamp || this.snapshot?.key !== key2 || this.snapshot.sources.size > 8192 || this.snapshot.currentSources.size > 8192 || this.snapshot.relationships.size > 8192) {
6848
+ if (stamp !== this.snapshotStamp || this.snapshot?.key !== key4 || this.snapshot.sources.size > 8192 || this.snapshot.currentSources.size > 8192 || this.snapshot.relationships.size > 8192) {
6814
6849
  this.snapshotStamp = stamp;
6815
6850
  this.snapshotBasis = void 0;
6816
- this.snapshot = { key: key2, memo: /* @__PURE__ */ new Map(), grounds: /* @__PURE__ */ new Map(), currentSources: /* @__PURE__ */ new Map(), sources: /* @__PURE__ */ new Map(), metadata: /* @__PURE__ */ new Map(), relationships: /* @__PURE__ */ new Map() };
6851
+ this.snapshot = { key: key4, memo: /* @__PURE__ */ new Map(), grounds: /* @__PURE__ */ new Map(), currentSources: /* @__PURE__ */ new Map(), sources: /* @__PURE__ */ new Map(), metadata: /* @__PURE__ */ new Map(), relationships: /* @__PURE__ */ new Map() };
6817
6852
  }
6818
6853
  return this.snapshot;
6819
6854
  }
@@ -6944,21 +6979,21 @@ CREATE TABLE memory_person_mentions (
6944
6979
  provenanceReferenceRetained(scope, ref, visited, cutoff, snapshot) {
6945
6980
  checkMemoryReadBudget(visited.size);
6946
6981
  if (ref.scopeId !== scopeId(scope) || visited.has(ref.sourceId) || ref.relationshipId && visited.has(`${ref.relationshipId}:${ref.semanticVersion}`)) return false;
6947
- const key2 = `reference:${JSON.stringify([ref.sourceId, ref.sourceVersion, ref.relationshipId, ref.semanticVersion])}`;
6948
- if (snapshot.memo.has(key2)) return snapshot.memo.get(key2);
6982
+ const key4 = `reference:${JSON.stringify([ref.sourceId, ref.sourceVersion, ref.relationshipId, ref.semanticVersion])}`;
6983
+ if (snapshot.memo.has(key4)) return snapshot.memo.get(key4);
6949
6984
  const retained = this.provenanceSource(scope, ref.sourceId, cutoff, snapshot)?.sourceVersion === ref.sourceVersion && this.provenanceRetained(scope, ref.sourceId, visited, cutoff, snapshot) && this.relationshipReferenceRetained(scope, ref, visited, cutoff, snapshot);
6950
- snapshot.memo.set(key2, retained);
6985
+ snapshot.memo.set(key4, retained);
6951
6986
  return retained;
6952
6987
  }
6953
6988
  /** Authored thoughts remain historical memories when a cited source is corrected; deletion still wins. */
6954
6989
  provenanceRetained(scope, sourceId, visited, cutoff, snapshot) {
6955
6990
  checkMemoryReadBudget(visited.size);
6956
6991
  if (visited.has(sourceId)) return false;
6957
- const key2 = `source:${sourceId}`;
6992
+ const key4 = `source:${sourceId}`;
6958
6993
  const { memo } = snapshot;
6959
- if (memo.has(key2)) return memo.get(key2);
6994
+ if (memo.has(key4)) return memo.get(key4);
6960
6995
  if (!this.provenanceSource(scope, sourceId, cutoff, snapshot) || this.tombstoneRead.get(scopeId(scope), sourceId)) {
6961
- memo.set(key2, false);
6996
+ memo.set(key4, false);
6962
6997
  return false;
6963
6998
  }
6964
6999
  if (!snapshot.metadata.has(sourceId)) snapshot.metadata.set(sourceId, this.metadata(scope, sourceId));
@@ -6967,7 +7002,7 @@ CREATE TABLE memory_person_mentions (
6967
7002
  try {
6968
7003
  const check = (ref) => this.provenanceReferenceRetained(scope, ref, visited, cutoff, snapshot);
6969
7004
  const retained = !metadata2 || metadata2.contextRefs.every(check) && metadata2.basisRefs.every(check);
6970
- memo.set(key2, retained);
7005
+ memo.set(key4, retained);
6971
7006
  return retained;
6972
7007
  } finally {
6973
7008
  visited.delete(sourceId);
@@ -7001,10 +7036,10 @@ CREATE TABLE memory_person_mentions (
7001
7036
  sourceGroundsCurrent(scope, sourceId, visited, cutoff, snapshot) {
7002
7037
  checkMemoryReadBudget(visited.size);
7003
7038
  if (visited.has(sourceId)) return false;
7004
- const key2 = `source:${sourceId}`;
7005
- if (snapshot.grounds.has(key2)) return snapshot.grounds.get(key2);
7039
+ const key4 = `source:${sourceId}`;
7040
+ if (snapshot.grounds.has(key4)) return snapshot.grounds.get(key4);
7006
7041
  if (!this.sourceCurrent(scope, sourceId, cutoff, snapshot) || !this.provenanceRetained(scope, sourceId, /* @__PURE__ */ new Set(), cutoff, snapshot)) {
7007
- snapshot.grounds.set(key2, false);
7042
+ snapshot.grounds.set(key4, false);
7008
7043
  return false;
7009
7044
  }
7010
7045
  if (!snapshot.metadata.has(sourceId)) snapshot.metadata.set(sourceId, this.metadata(scope, sourceId));
@@ -7012,7 +7047,7 @@ CREATE TABLE memory_person_mentions (
7012
7047
  visited.add(sourceId);
7013
7048
  try {
7014
7049
  const current2 = !metadata2 || metadata2.basisRefs.every((ref) => this.currentReference(scope, ref, visited, cutoff, snapshot));
7015
- snapshot.grounds.set(key2, current2);
7050
+ snapshot.grounds.set(key4, current2);
7016
7051
  return current2;
7017
7052
  } finally {
7018
7053
  visited.delete(sourceId);
@@ -7022,46 +7057,46 @@ CREATE TABLE memory_person_mentions (
7022
7057
  checkMemoryReadBudget(visited.size);
7023
7058
  if (ref.scopeId !== scopeId(scope) || this.provenanceSource(scope, ref.sourceId, cutoff, snapshot)?.sourceVersion !== ref.sourceVersion || !this.sourceGroundsCurrent(scope, ref.sourceId, visited, cutoff, snapshot)) return false;
7024
7059
  if (!ref.relationshipId) return true;
7025
- const key2 = `${ref.relationshipId}:${ref.semanticVersion}`;
7026
- if (visited.has(key2)) return false;
7027
- const memoKey = `relationship:${key2}:${ref.purpose === "historical" ? "historical" : "current"}`;
7060
+ const key4 = `${ref.relationshipId}:${ref.semanticVersion}`;
7061
+ if (visited.has(key4)) return false;
7062
+ const memoKey = `relationship:${key4}:${ref.purpose === "historical" ? "historical" : "current"}`;
7028
7063
  if (snapshot.grounds.has(memoKey)) return snapshot.grounds.get(memoKey);
7029
- if (!snapshot.relationships.has(key2)) {
7064
+ if (!snapshot.relationships.has(key4)) {
7030
7065
  this.snapshotBasis = void 0;
7031
- snapshot.relationships.set(key2, this.relationshipReferenceMaterial(scope, ref, cutoff));
7066
+ snapshot.relationships.set(key4, this.relationshipReferenceMaterial(scope, ref, cutoff));
7032
7067
  }
7033
- const material = snapshot.relationships.get(key2);
7068
+ const material = snapshot.relationships.get(key4);
7034
7069
  if (!material || ["deleted", "retracted"].includes(material.state) || ref.purpose !== "historical" && !material.current) return false;
7035
- visited.add(key2);
7070
+ visited.add(key4);
7036
7071
  try {
7037
7072
  const current2 = material.evidenceSourceIds.every((id3) => this.sourceGroundsCurrent(scope, id3, visited, cutoff, snapshot)) && material.basisRefs.every((basis) => this.currentReference(scope, basis, visited, cutoff, snapshot));
7038
7073
  snapshot.grounds.set(memoKey, current2);
7039
7074
  return current2;
7040
7075
  } finally {
7041
- visited.delete(key2);
7076
+ visited.delete(key4);
7042
7077
  }
7043
7078
  }
7044
7079
  relationshipReferenceRetained(scope, ref, visited, cutoff, snapshot = this.provenanceSnapshot(scope, cutoff)) {
7045
7080
  checkMemoryReadBudget(visited.size);
7046
7081
  if (!ref.relationshipId) return true;
7047
- const key2 = `${ref.relationshipId}:${ref.semanticVersion}`;
7048
- if (visited.has(key2)) return false;
7049
- const memoKey = `relationship:${key2}`;
7082
+ const key4 = `${ref.relationshipId}:${ref.semanticVersion}`;
7083
+ if (visited.has(key4)) return false;
7084
+ const memoKey = `relationship:${key4}`;
7050
7085
  const { memo } = snapshot;
7051
7086
  if (memo.has(memoKey)) return memo.get(memoKey);
7052
- if (!snapshot.relationships.has(key2)) {
7087
+ if (!snapshot.relationships.has(key4)) {
7053
7088
  this.snapshotBasis = void 0;
7054
- snapshot.relationships.set(key2, this.relationshipReferenceMaterial(scope, ref, cutoff));
7089
+ snapshot.relationships.set(key4, this.relationshipReferenceMaterial(scope, ref, cutoff));
7055
7090
  }
7056
- const material = snapshot.relationships.get(key2);
7091
+ const material = snapshot.relationships.get(key4);
7057
7092
  if (!material) return false;
7058
- visited.add(key2);
7093
+ visited.add(key4);
7059
7094
  try {
7060
7095
  const retained = material.evidenceSourceIds.every((id3) => this.provenanceRetained(scope, id3, visited, cutoff, snapshot)) && material.basisRefs.every((basis) => this.provenanceReferenceRetained(scope, basis, visited, cutoff, snapshot));
7061
7096
  memo.set(memoKey, retained);
7062
7097
  return retained;
7063
7098
  } finally {
7064
- visited.delete(key2);
7099
+ visited.delete(key4);
7065
7100
  }
7066
7101
  }
7067
7102
  relationshipReferenceMaterial(scope, ref, cutoff) {
@@ -7508,16 +7543,16 @@ CREATE TABLE memory_relationship_receipts (
7508
7543
  WHERE h.scope_id=? AND h.relationship_id=? AND r.semantic_version=COALESCE(?,h.semantic_version)`).get(...cutoff ? [revision, revision] : [], scopeId(scope), relationshipId, version ?? null);
7509
7544
  if (!row) return null;
7510
7545
  if (historicalVersion) Object.assign(row, historicalVersion);
7511
- const key2 = `${relationshipId}:${row.semantic_version}`;
7512
- if (visited.has(key2)) return null;
7513
- const next = new Set(visited).add(key2);
7546
+ const key4 = `${relationshipId}:${row.semantic_version}`;
7547
+ if (visited.has(key4)) return null;
7548
+ const next = new Set(visited).add(key4);
7514
7549
  const evidence = this.db.prepare("SELECT source_id sourceId,span_start start,span_end end,quote,relation FROM fact_evidence WHERE scope_id=? AND assertion_id=? AND added_revision<=?").all(scopeId(scope), row.assertion_id, revision ?? Number.MAX_SAFE_INTEGER).map((ref) => ({ ...ref }));
7515
7550
  const basisRefs = JSON.parse(row.basis_refs);
7516
7551
  const refs = [...evidence.map((ref) => ({ sourceId: ref.sourceId })), ...basisRefs];
7517
7552
  if (recall ? recall.deletedRelationship(relationshipId, row.semantic_version) : evidence.some((ref) => !this.socialSources.retained(scope, ref.sourceId, /* @__PURE__ */ new Set(), cutoff)) || basisRefs.some((ref) => !this.socialSources.referenceRetained(scope, ref, /* @__PURE__ */ new Set(), cutoff))) return null;
7518
7553
  const value = JSON.parse(row.value_json);
7519
7554
  const current2 = (historicalHead ?? this.db.prepare("SELECT semantic_version FROM memory_relationship_heads WHERE scope_id=? AND relationship_id=?").get(scopeId(scope), relationshipId)).semantic_version === row.semantic_version;
7520
- const valid = recall ? evidence.length > 0 && evidence.every((ref) => recall.current(ref.sourceId)) && basisRefs.every((ref) => recall.referenceCurrent(ref)) && (cutoff || [void 0, null, "current"].includes(this.db.prepare("SELECT state FROM memory_derivations WHERE scope_id=? AND child_kind='relationship' AND child_id=?").get(scopeId(scope), key2)?.state)) : refs.every((ref) => this.sources.isCurrent(scope, ref.sourceId, cutoff) && this.socialSources.groundsCurrent(scope, ref.sourceId, /* @__PURE__ */ new Set(), cutoff)) && (cutoff || [void 0, null, "current"].includes(this.dependencies?.state(scope, "relationship", `${relationshipId}:${row.semantic_version}`))) && basisRefs.every((ref) => this.socialSources.referenceCurrent(scope, ref, next, cutoff));
7555
+ const valid = recall ? evidence.length > 0 && evidence.every((ref) => recall.current(ref.sourceId)) && basisRefs.every((ref) => recall.referenceCurrent(ref)) && (cutoff || [void 0, null, "current"].includes(this.db.prepare("SELECT state FROM memory_derivations WHERE scope_id=? AND child_kind='relationship' AND child_id=?").get(scopeId(scope), key4)?.state)) : refs.every((ref) => this.sources.isCurrent(scope, ref.sourceId, cutoff) && this.socialSources.groundsCurrent(scope, ref.sourceId, /* @__PURE__ */ new Set(), cutoff)) && (cutoff || [void 0, null, "current"].includes(this.dependencies?.state(scope, "relationship", `${relationshipId}:${row.semantic_version}`))) && basisRefs.every((ref) => this.socialSources.referenceCurrent(scope, ref, next, cutoff));
7521
7556
  return {
7522
7557
  relationshipId,
7523
7558
  semanticVersion: row.semantic_version,
@@ -7842,15 +7877,15 @@ var init_cutoff = __esm({
7842
7877
  // src/continuity/runtime-replication.ts
7843
7878
  import { constants as constants5, lstatSync as lstatSync6, realpathSync as realpathSync4, mkdirSync as mkdirSync6, openSync as openSync6, closeSync as closeSync6, fstatSync as fstatSync4, readFileSync as readFileSync7, writeFileSync as writeFileSync5, fsyncSync as fsyncSync5 } from "node:fs";
7844
7879
  import { basename as basename2, dirname as dirname5, join as join10, resolve as resolve5 } from "node:path";
7845
- function checkKey(component, key2) {
7846
- if (component === "topics-vectors" && typeof key2 === "string" && /^[a-f0-9]{64}$/.test(key2)) return;
7847
- if (component === "legacy-memory" && typeof key2 === "string" && /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(key2) && !/[. ]$/.test(key2) && !/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(key2)) return;
7848
- if (["calendar", "proactive", "session-events"].includes(component) && key2 === void 0) return;
7880
+ function checkKey(component, key4) {
7881
+ if (component === "topics-vectors" && typeof key4 === "string" && /^[a-f0-9]{64}$/.test(key4)) return;
7882
+ if (component === "legacy-memory" && typeof key4 === "string" && /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(key4) && !/[. ]$/.test(key4) && !/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(key4)) return;
7883
+ if (["calendar", "proactive", "session-events"].includes(component) && key4 === void 0) return;
7849
7884
  throw new Error("REPLICATION_REGISTRATION_INVALID");
7850
7885
  }
7851
- function location2(stateDir, component, key2) {
7852
- checkKey(component, key2);
7853
- return join10(stateDir, ".continuity", component + (key2 === void 0 ? "" : "-" + key2) + "-replication.json");
7886
+ function location2(stateDir, component, key4) {
7887
+ checkKey(component, key4);
7888
+ return join10(stateDir, ".continuity", component + (key4 === void 0 ? "" : "-" + key4) + "-replication.json");
7854
7889
  }
7855
7890
  function normalize3(input) {
7856
7891
  if (!input || !/^[a-f0-9]{64}$/.test(input.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
@@ -7861,8 +7896,8 @@ function directory(path35) {
7861
7896
  if (!info.isDirectory() || info.isSymbolicLink() || realpathSync4(path35) !== resolve5(path35) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
7862
7897
  throw new Error("REPLICATION_REGISTRATION_INVALID");
7863
7898
  }
7864
- function readRuntimeReplicationRegistration(stateDir, component, key2) {
7865
- const file2 = location2(stateDir, component, key2);
7899
+ function readRuntimeReplicationRegistration(stateDir, component, key4) {
7900
+ const file2 = location2(stateDir, component, key4);
7866
7901
  try {
7867
7902
  lstatSync6(dirname5(file2));
7868
7903
  } catch (error) {
@@ -7925,8 +7960,8 @@ function checkRuntimeReplicationDatabase(db2, registration, component, version,
7925
7960
  }
7926
7961
  return requested ?? registration?.binding;
7927
7962
  }
7928
- function enrollRuntimeReplication(db2, stateDir, component, binding, key2) {
7929
- const file2 = location2(stateDir, component, key2), old = readRuntimeReplicationRegistration(stateDir, component, key2);
7963
+ function enrollRuntimeReplication(db2, stateDir, component, binding, key4) {
7964
+ const file2 = location2(stateDir, component, key4), old = readRuntimeReplicationRegistration(stateDir, component, key4);
7930
7965
  const version = readSchemaVersion(db2);
7931
7966
  if (version?.component !== component) throw new Error("REPLICATION_SCHEMA_MISMATCH");
7932
7967
  checkRuntimeReplicationDatabase(db2, old, component, version.version, binding);
@@ -7939,7 +7974,7 @@ function enrollRuntimeReplication(db2, stateDir, component, binding, key2) {
7939
7974
  writeFileSync5(file2, JSON.stringify(input), { mode: 384, flag: "wx", flush: true });
7940
7975
  } catch (error) {
7941
7976
  if (error.code !== "EEXIST") throw error;
7942
- if (JSON.stringify(readRuntimeReplicationRegistration(stateDir, component, key2)) !== JSON.stringify(input)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
7977
+ if (JSON.stringify(readRuntimeReplicationRegistration(stateDir, component, key4)) !== JSON.stringify(input)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
7943
7978
  }
7944
7979
  if (process.platform !== "win32") {
7945
7980
  const fd = openSync6(dirname5(file2), "r");
@@ -8373,10 +8408,10 @@ CREATE TABLE memory_relationship_cognition_results (
8373
8408
  const rows = this.db.prepare(`SELECT * FROM memory_relationship_coverage WHERE state='deferred'${scope ? " AND scope_id=?" : ""} ORDER BY scope_id,group_key,source_id`).all(...scope ? [scopeId(scope)] : []);
8374
8409
  const groups = /* @__PURE__ */ new Map();
8375
8410
  for (const row of rows) {
8376
- const key2 = canonicalJson([row.scope_id, row.perspective_entity_id, row.group_key, row.generation]);
8377
- const group = groups.get(key2) || { scopeId: row.scope_id, perspectiveEntityId: row.perspective_entity_id, groupKey: row.group_key, sourceIds: [], generation: row.generation };
8411
+ const key4 = canonicalJson([row.scope_id, row.perspective_entity_id, row.group_key, row.generation]);
8412
+ const group = groups.get(key4) || { scopeId: row.scope_id, perspectiveEntityId: row.perspective_entity_id, groupKey: row.group_key, sourceIds: [], generation: row.generation };
8378
8413
  if (group.sourceIds.length < 20) group.sourceIds.push(row.source_id);
8379
- groups.set(key2, group);
8414
+ groups.set(key4, group);
8380
8415
  }
8381
8416
  return [...groups.values()];
8382
8417
  }
@@ -8566,9 +8601,9 @@ var init_entities = __esm({
8566
8601
  aliasEvidence(scope, entityId, cutoff) {
8567
8602
  const seen = /* @__PURE__ */ new Set();
8568
8603
  return (cutoff ? historicalRows(this.db, scope, "alias", cutoff) : this.db.prepare("SELECT entity_id entityId,source_id sourceId,alias FROM entity_aliases WHERE scope_id=? AND entity_id=?").all(scopeId(scope), entityId)).filter((alias) => {
8569
- const key2 = normalizeAlias(alias.alias);
8570
- if (seen.has(key2) || alias.entityId !== entityId || !this.sources.isCurrent(scope, alias.sourceId, cutoff) || !this.aliasIsName(scope, entityId, alias.sourceId, alias.alias, cutoff) || this.aliasReadable && !this.aliasReadable(scope, entityId, alias.sourceId, alias.alias, cutoff)) return false;
8571
- seen.add(key2);
8604
+ const key4 = normalizeAlias(alias.alias);
8605
+ if (seen.has(key4) || alias.entityId !== entityId || !this.sources.isCurrent(scope, alias.sourceId, cutoff) || !this.aliasIsName(scope, entityId, alias.sourceId, alias.alias, cutoff) || this.aliasReadable && !this.aliasReadable(scope, entityId, alias.sourceId, alias.alias, cutoff)) return false;
8606
+ seen.add(key4);
8572
8607
  return true;
8573
8608
  }).map((alias) => ({ alias: alias.alias, sourceId: alias.sourceId, sourceVersion: this.sources.get(scope, alias.sourceId, cutoff).sourceVersion }));
8574
8609
  }
@@ -8767,12 +8802,12 @@ function checkNotice(db2, sources, social, scope, id3, options) {
8767
8802
  return Boolean(source && (version === void 0 || source.sourceVersion === version) && social.readable(memoryScope, sourceId) && social.groundsCurrent(memoryScope, sourceId));
8768
8803
  };
8769
8804
  const relationshipCurrent = (relationshipId, version) => {
8770
- const key2 = `${relationshipId}:${version}`;
8805
+ const key4 = `${relationshipId}:${version}`;
8771
8806
  const row = db2.prepare(`SELECT r.*,v.state FROM memory_relationship_versions r JOIN fact_versions v
8772
8807
  ON v.scope_id=r.scope_id AND v.assertion_id=r.assertion_id AND v.system_to_revision IS NULL
8773
8808
  WHERE r.scope_id=? AND r.relationship_id=? AND r.semantic_version=?`).get(scope, relationshipId, version);
8774
8809
  if (!row || ["deleted", "retracted"].includes(row.state)) return false;
8775
- const derivation = db2.prepare("SELECT state FROM memory_derivations WHERE scope_id=? AND child_kind='relationship' AND child_id=?").get(scope, key2);
8810
+ const derivation = db2.prepare("SELECT state FROM memory_derivations WHERE scope_id=? AND child_kind='relationship' AND child_id=?").get(scope, key4);
8776
8811
  if (derivation && derivation.state !== "current") return false;
8777
8812
  const evidence = db2.prepare("SELECT source_id FROM fact_evidence WHERE scope_id=? AND assertion_id=?").all(scope, row.assertion_id);
8778
8813
  return evidence.length > 0 && evidence.every((ref) => sourceCurrent(ref.source_id)) && JSON.parse(row.basis_refs).every((ref) => social.referenceCurrent(memoryScope, ref));
@@ -8847,8 +8882,11 @@ CREATE TABLE memory_relationship_notice_versions (
8847
8882
  }
8848
8883
  get(scope, id3) {
8849
8884
  const row = this.db.prepare("SELECT * FROM memory_relationship_notices WHERE scope_id=? AND notice_id=?").get(scopeId(scope), id3);
8850
- return row ? {
8851
- id: id3,
8885
+ return row ? this.decode(scope, row) : null;
8886
+ }
8887
+ decode(scope, row) {
8888
+ return {
8889
+ id: row.notice_id,
8852
8890
  scope,
8853
8891
  kind: row.kind,
8854
8892
  targetId: row.target_id,
@@ -8858,10 +8896,25 @@ CREATE TABLE memory_relationship_notice_versions (
8858
8896
  state: row.state,
8859
8897
  attempts: row.attempts,
8860
8898
  reason: row.reason
8861
- } : null;
8899
+ };
8862
8900
  }
8863
- list(scope) {
8864
- return this.db.prepare("SELECT notice_id FROM memory_relationship_notices WHERE scope_id=? ORDER BY updated_at,notice_id").all(scopeId(scope)).map((row) => this.get(scope, row.notice_id));
8901
+ list(scope, includeTerminal = true) {
8902
+ return this.db.prepare(`SELECT * FROM memory_relationship_notices WHERE scope_id=?
8903
+ ${includeTerminal ? "" : "AND state NOT IN ('delivered','blocked')"} ORDER BY updated_at,notice_id`).all(scopeId(scope)).map((row) => this.decode(scope, row));
8904
+ }
8905
+ /** Quiet identity work is not notification work. Evidence-backed resolved identities can still be withdrawn. */
8906
+ clarificationCandidates(scope) {
8907
+ const rows = this.db.prepare(`SELECT m.mention_id,m.question,m.mention_kind,m.candidates,m.span_start,m.span_end,s.text
8908
+ FROM memory_person_mentions m JOIN memory_sources s ON s.scope_id=m.scope_id AND s.source_id=m.source_id
8909
+ WHERE m.scope_id=? AND m.question IS NOT NULL AND trim(m.question)<>''
8910
+ AND (m.state='unresolved' OR m.clarification_source_id IS NOT NULL OR m.basis_refs<>'[]')
8911
+ AND (m.mention_kind NOT IN ('description','reference') OR json_array_length(m.candidates)>=2)
8912
+ ORDER BY m.source_id,m.span_start`).all(scopeId(scope));
8913
+ return rows.filter((row) => hasIdentityQuestion(
8914
+ row.question,
8915
+ row.text.slice(row.span_start, row.span_end),
8916
+ { mentionKind: row.mention_kind, candidateEntityIds: JSON.parse(row.candidates) }
8917
+ )).map((row) => row.mention_id);
8865
8918
  }
8866
8919
  finish(scope, id3, state, reason = "", redact = false) {
8867
8920
  this.db.prepare(`UPDATE memory_relationship_notices SET state=?,reason=?,updated_at=?,message=CASE WHEN ? THEN '[memory unavailable]' ELSE message END WHERE scope_id=? AND notice_id=?`).run(state, reason, (/* @__PURE__ */ new Date()).toISOString(), Number(redact), scopeId(scope), id3);
@@ -8872,6 +8925,12 @@ CREATE TABLE memory_relationship_notice_versions (
8872
8925
  check(scope, id3, options = {}) {
8873
8926
  return checkRelationshipNotice(this.db, scopeId(scope), id3, options);
8874
8927
  }
8928
+ /** The caller holds one transaction; proofs are discarded before any later batch or write. */
8929
+ checkMany(scope, ids, options = {}) {
8930
+ if (!ids.length) return [];
8931
+ const check = createRelationshipNoticeChecker(this.db);
8932
+ return ids.map((id3) => check(scopeId(scope), id3, options));
8933
+ }
8875
8934
  queue(scope, id3) {
8876
8935
  return Boolean(this.db.prepare("UPDATE memory_relationship_notices SET state='queued',reason='accepted_by_durable_queue',updated_at=? WHERE scope_id=? AND notice_id=? AND state IN ('pending','failed')").run((/* @__PURE__ */ new Date()).toISOString(), scopeId(scope), id3).changes);
8877
8936
  }
@@ -8883,6 +8942,7 @@ CREATE TABLE memory_relationship_notice_versions (
8883
8942
  importantRecords(scope) {
8884
8943
  return this.db.prepare(`SELECT v.relationship_id,v.semantic_version FROM memory_relationship_notice_versions v
8885
8944
  JOIN memory_relationship_cognition_results r ON r.scope_id=v.scope_id AND r.job_id=v.job_id
8945
+ JOIN memory_relationship_heads h ON h.scope_id=v.scope_id AND h.relationship_id=v.relationship_id AND h.semantic_version=v.semantic_version
8886
8946
  WHERE v.scope_id=? AND r.important=1`).all(scopeId(scope)).map((row) => ({ relationshipId: row.relationship_id, semanticVersion: row.semantic_version }));
8887
8947
  }
8888
8948
  recordRoute(scope, sourceId, input) {
@@ -8950,9 +9010,9 @@ function installRelationshipHistory(db2) {
8950
9010
  FROM memory_scopes s WHERE EXISTS (SELECT 1 FROM memory_relationship_heads h WHERE h.scope_id=s.scope_id)
8951
9011
  OR EXISTS (SELECT 1 FROM memory_person_sources p WHERE p.scope_id=s.scope_id)
8952
9012
  OR EXISTS (SELECT 1 FROM memory_person_mentions m WHERE m.scope_id=s.scope_id)`);
8953
- for (const { table, kind, key: key2, columns: columns2 } of tables) {
9013
+ for (const { table, kind, key: key4, columns: columns2 } of tables) {
8954
9014
  const payload = (prefix2) => `json_object(${columns2.map((column) => `'${column}',${prefix2}${column}`).join(",")})`;
8955
- const target = (prefix2) => key2.startsWith("json_array") ? `json_array(${key2.slice(11, -1).split(",").map((column) => `${prefix2}${column}`).join(",")})` : `${prefix2}${key2}`;
9015
+ const target = (prefix2) => key4.startsWith("json_array") ? `json_array(${key4.slice(11, -1).split(",").map((column) => `${prefix2}${column}`).join(",")})` : `${prefix2}${key4}`;
8956
9016
  db2.exec(`INSERT INTO memory_knowledge_history(scope_id,target_kind,target_id,entity_revision,fact_revision,context_revision,recorded_at,payload_json)
8957
9017
  SELECT t.scope_id,'${kind}',${target("t.")},s.entity_revision,s.fact_revision,s.context_revision,strftime('%Y-%m-%dT%H:%M:%fZ','now'),${payload("t.")}
8958
9018
  FROM ${table} t JOIN memory_scopes s ON s.scope_id=t.scope_id`);
@@ -9381,16 +9441,16 @@ var init_snapshot_reads = __esm({
9381
9441
  this.changes = -1;
9382
9442
  }
9383
9443
  }
9384
- read(key2, load) {
9444
+ read(key4, load) {
9385
9445
  if (!this.values || !this.db.isTransaction) return load();
9386
9446
  const changes = this.changesRead.get().n;
9387
9447
  if (changes !== this.changes) {
9388
9448
  this.values.clear();
9389
9449
  this.changes = changes;
9390
9450
  }
9391
- if (this.values.has(key2)) return this.values.get(key2);
9451
+ if (this.values.has(key4)) return this.values.get(key4);
9392
9452
  const value = load();
9393
- if (this.values.size < 8192) this.values.set(key2, value);
9453
+ if (this.values.size < 8192) this.values.set(key4, value);
9394
9454
  return value;
9395
9455
  }
9396
9456
  };
@@ -9516,7 +9576,7 @@ function classifyFactVersions(versions, predicate, time) {
9516
9576
  needsReview: disputed || hypotheses.some((fact) => fact.validFrom === null)
9517
9577
  };
9518
9578
  }
9519
- var hash6, makeSlotId, FactStore;
9579
+ var hash6, makeSlotId, CLOSE_VALIDITY, occurrences, CHANGE_KINDS, CLAIM_KINDS, normalizeChange, FactStore;
9520
9580
  var init_facts = __esm({
9521
9581
  "src/mem7/core/state/facts.ts"() {
9522
9582
  "use strict";
@@ -9528,6 +9588,15 @@ var init_facts = __esm({
9528
9588
  init_basis_check();
9529
9589
  hash6 = (value) => createHash18("sha256").update(canonicalJson(value)).digest("hex");
9530
9590
  makeSlotId = (subjectId, predicate, context) => `slot_${hash6([subjectId, predicate, context]).slice(0, 32)}`;
9591
+ CLOSE_VALIDITY = '{"validFrom":null,"validTo":"\u7ED3\u675F\u65F6\u523B","precision":"exact"}';
9592
+ occurrences = (text2, quote2) => {
9593
+ let count = 0;
9594
+ for (let at = text2.indexOf(quote2); quote2 && at >= 0; at = text2.indexOf(quote2, at + 1)) count++;
9595
+ return count;
9596
+ };
9597
+ CHANGE_KINDS = ["assert", "reinforce", "state_change", "correction", "exception", "dispute", "retract", "close"];
9598
+ CLAIM_KINDS = ["user_statement", "tool_observation", "reported_statement", "inference", "agent_statement"];
9599
+ normalizeChange = (proposal) => !["close", "retract"].includes(proposal.changeKind) || !proposal.validity || proposal.validity.validFrom !== void 0 ? proposal : { ...proposal, validity: { ...proposal.validity, validFrom: null } };
9531
9600
  FactStore = class {
9532
9601
  constructor(db2, entities, transaction, readTransaction = transaction) {
9533
9602
  this.db = db2;
@@ -9694,6 +9763,8 @@ var init_facts = __esm({
9694
9763
  applyChange(scope, proposal, expectedSlotRevision, requestKey, batch) {
9695
9764
  if (!requestKey || !Number.isSafeInteger(expectedSlotRevision) || expectedSlotRevision < 0) throw new Error("INVALID_FACT_REQUEST");
9696
9765
  const id3 = scopeId(scope);
9766
+ const located = this.locateEvidence(id3, normalizeChange(proposal));
9767
+ proposal = located.proposal;
9697
9768
  const requestHash = hash6([proposal, expectedSlotRevision]);
9698
9769
  const prior = this.db.prepare("SELECT request_hash,result_json FROM fact_changes WHERE scope_id=? AND request_key=?").get(id3, requestKey);
9699
9770
  if (prior) {
@@ -9702,21 +9773,22 @@ var init_facts = __esm({
9702
9773
  }
9703
9774
  this.validate(scope, proposal);
9704
9775
  const slot = this.slot(scope, proposal.subjectId, proposal.predicate, proposal.contextKey);
9705
- if (slot.revision !== expectedSlotRevision) throw new Error(`STALE_VERSION: expected slot ${expectedSlotRevision}, current ${slot.revision}`);
9776
+ if (slot.revision !== expectedSlotRevision) throw new Error(`STALE_VERSION: expected slot ${expectedSlotRevision}, current ${slot.revision} \u2014 ` + (slot.revision > expectedSlotRevision ? "\u8BE5\u69FD\u5728\u4F60\u8BFB\u53D6\u4E4B\u540E\u6709\u65B0\u7684\u4FEE\u6539" : "\u8FD9\u4E2A\u69FD\u7684\u5199\u5165\u6B21\u6570\u5C11\u4E8E\u4F60\u586B\u7684\u7248\u672C\uFF0C\u591A\u534A\u662F proposal \u6307\u5230\u4E86\u522B\u7684\u69FD") + "\uFF1Bexpected_slot_revision \u586B\u91CD\u65B0\u8BFB\u53D6\u5230\u7684 basis.slotRevision" + (slot.revision < expectedSlotRevision ? `\u3002\u672C\u6B21\u843D\u5230 subjectId=${proposal.subjectId} predicate=${proposal.predicate} contextKey=${proposal.contextKey}\uFF08\u4E09\u8005\u987B\u4E0E\u65AD\u8A00\u4E00\u81F4\uFF1Brelation.open \u505A state_change/correction \u65F6 value \u5E26\u4E0A\u539F\u8BB0\u5F55\u7684 relationshipId\uFF09` : ""));
9706
9777
  this.db.prepare("INSERT OR IGNORE INTO fact_slots(scope_id,slot_id,subject_id,predicate,context_key,cardinality) VALUES (?,?,?,?,?,?)").run(id3, slot.slotId, proposal.subjectId, proposal.predicate, proposal.contextKey, predicates[proposal.predicate].cardinality);
9707
9778
  const before = this.current(id3, slot.slotId);
9708
9779
  const targetIds = [...new Set(proposal.targetAssertionIds ?? [])];
9709
9780
  const targets = targetIds.map((targetId) => {
9710
9781
  const target = before.find((fact) => fact.assertionId === targetId);
9711
- if (!target || ["retracted", "deleted"].includes(target.state)) throw new Error("FACT_TARGET_MISMATCH");
9782
+ if (!target || ["retracted", "deleted"].includes(target.state)) throw new Error(`FACT_TARGET_MISMATCH: ${targetId} \u4E0D\u5728\u8FD9\u4E2A\u69FD\uFF08subject+predicate+contextKey\uFF09\u7684\u5F53\u524D\u65AD\u8A00\u91CC\uFF0C\u6216\u5DF2\u64A4\u56DE/\u5220\u9664\uFF1B\u91CD\u65B0\u8BFB\u53D6\u5E76\u590D\u5236\u4ECD\u6709\u6548\u7684 assertionId`);
9712
9783
  return target;
9713
9784
  });
9714
- if (["reinforce", "state_change", "correction", "retract", "close"].includes(proposal.changeKind) && targets.length === 0) throw new Error("FACT_TARGET_REQUIRED");
9785
+ if (["reinforce", "state_change", "correction", "retract", "close"].includes(proposal.changeKind) && targets.length === 0) throw new Error(`FACT_TARGET_REQUIRED: changeKind=${proposal.changeKind} \u5FC5\u987B\u5E26 targetAssertionIds\uFF08\u88AB\u4FEE\u8BA2\u7684 assertionId\uFF0C\u4ECE\u8BFB\u53D6\u7ED3\u679C\u91CC\u6284\uFF09`);
9715
9786
  if (proposal.changeKind === "reinforce" && targets.length !== 1) throw new Error("REINFORCE_REQUIRES_ONE_TARGET");
9716
9787
  if (["assert", "exception"].includes(proposal.changeKind) && targets.length) throw new Error("UNEXPECTED_FACT_TARGET");
9717
9788
  const validity = proposal.validity ? normalizeValidity(proposal.validity) : void 0;
9718
- if (proposal.changeKind === "state_change" && (validity?.validFrom == null || validity.precision !== "exact")) throw new Error("CHANGE_TIME_REQUIRED");
9719
- if (proposal.changeKind === "close" && (validity?.validTo == null || validity.validFrom !== null || validity.precision === "unknown")) throw new Error("CHANGE_TIME_REQUIRED");
9789
+ const received2 = JSON.stringify({ validFrom: proposal.validity?.validFrom, validTo: proposal.validity?.validTo, precision: proposal.validity?.precision });
9790
+ if (proposal.changeKind === "state_change" && (validity?.validFrom == null || validity.precision !== "exact")) throw new Error(`CHANGE_TIME_REQUIRED: changeKind=state_change \u9700\u8981 validity.validFrom=\u53D8\u5316\u65F6\u523B \u4E14 precision="exact"\uFF08\u65E7\u503C\u5230\u8FD9\u4E00\u523B\u4E3A\u6B62\uFF0C\u65B0 value \u4ECE\u8FD9\u4E00\u523B\u751F\u6548\uFF09\uFF1B\u6536\u5230 ${received2}\u3002\u53EA\u662F\u7ED3\u675F\u5173\u7CFB\uFF1AchangeKind \u6539 "close"`);
9791
+ if (proposal.changeKind === "close" && (validity?.validTo == null || validity.validFrom !== null || validity.precision === "unknown")) throw new Error(`CHANGE_TIME_REQUIRED: changeKind=close \u9700\u8981 validity=${CLOSE_VALIDITY}\uFF08validFrom \u586B null\uFF1Bprecision \u4E5F\u53EF\u7528 observed\uFF09\uFF1B\u6536\u5230 ${received2}`);
9720
9792
  if (proposal.changeKind === "reinforce" && (canonicalJson(proposal.value) !== canonicalJson(targets[0].value) || proposal.claimKind !== targets[0].claimKind)) throw new Error("REINFORCE_VALUE_MISMATCH");
9721
9793
  if (proposal.changeKind === "reinforce" && (validity.validFrom !== targets[0].validFrom || validity.validTo !== targets[0].validTo || proposal.evidence.some((evidence) => evidence.relation !== "supports"))) throw new Error("REINFORCE_INTERVAL_OR_EVIDENCE_MISMATCH");
9722
9794
  const timestamp = batch?.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
@@ -9732,8 +9804,8 @@ var init_facts = __esm({
9732
9804
  let state = proposal.changeKind === "correction" || proposal.changeKind === "retract" ? "retracted" : "disputed";
9733
9805
  if (proposal.changeKind === "state_change" || proposal.changeKind === "close") {
9734
9806
  const end = proposal.changeKind === "close" ? validity.validTo : validity.validFrom;
9735
- if (target.validFrom !== null && target.validFrom >= end) throw new Error("CHANGE_BEFORE_TARGET_START: use correction");
9736
- if (target.validTo !== null && target.validTo <= end) throw new Error("CHANGE_AFTER_TARGET_END");
9807
+ if (target.validFrom !== null && target.validFrom >= end) throw new Error(`CHANGE_BEFORE_TARGET_START: \u7ED3\u675F\u65F6\u523B ${end} \u4E0D\u665A\u4E8E\u8BE5\u65AD\u8A00\u7684\u5F00\u59CB\u65F6\u95F4 ${target.validFrom}\uFF1B\u4ECE\u4E00\u5F00\u59CB\u5C31\u4E0D\u6210\u7ACB\u7528 changeKind=correction`);
9808
+ if (target.validTo !== null && target.validTo <= end) throw new Error(`CHANGE_AFTER_TARGET_END: \u8BE5\u65AD\u8A00\u5DF2\u4E8E ${target.validTo} \u7ED3\u675F\uFF0C\u65E0\u9700\u518D\u5173\u95ED\uFF08\u6536\u5230 ${end}\uFF09`);
9737
9809
  state = target.state;
9738
9810
  nextValidity = { ...target, validTo: end };
9739
9811
  }
@@ -9749,7 +9821,7 @@ var init_facts = __esm({
9749
9821
  }
9750
9822
  if (!["retract", "close"].includes(proposal.changeKind)) {
9751
9823
  let state = proposal.claimKind === "inference" ? "candidate" : proposal.changeKind === "dispute" ? "disputed" : "supported";
9752
- if (state === "supported" && !proposal.evidence.some((evidence) => evidence.relation === "supports")) throw new Error("SUPPORTING_EVIDENCE_REQUIRED");
9824
+ if (state === "supported" && !proposal.evidence.some((evidence) => evidence.relation === "supports")) throw new Error("SUPPORTING_EVIDENCE_REQUIRED: \u65B0\u767B\u8BB0\u7684\u65AD\u8A00\u81F3\u5C11\u8981\u4E00\u6761 relation=supports \u7684\u539F\u8BDD\u8BC1\u636E");
9753
9825
  const current2 = this.current(id3, slot.slotId);
9754
9826
  if (predicates[proposal.predicate].cardinality === "single" && state === "supported" && current2.some((fact) => ["supported", "disputed"].includes(fact.state) && overlaps(fact, validity))) throw new Error("FACT_INTERVAL_CONFLICT: explicit correction/change/dispute required");
9755
9827
  if (state === "supported" && validity.validFrom === null && !(proposal.predicate === "relation.open" && proposal.value.observedAsCurrentAt)) state = "candidate";
@@ -9781,7 +9853,8 @@ var init_facts = __esm({
9781
9853
  slotId: slot.slotId,
9782
9854
  slotRevision: slot.revision + Number(changed),
9783
9855
  assertionIds: changedIds,
9784
- outcome: !changed ? "no_change" : after.some((fact) => ["candidate", "disputed"].includes(fact.state) && (!isRelationship(proposal.predicate) || changedIds.includes(fact.assertionId))) ? "needs_review" : "applied"
9856
+ outcome: !changed ? "no_change" : after.some((fact) => ["candidate", "disputed"].includes(fact.state) && (!isRelationship(proposal.predicate) || changedIds.includes(fact.assertionId))) ? "needs_review" : "applied",
9857
+ ...located.aligned.length ? { evidenceAligned: located.aligned } : {}
9785
9858
  };
9786
9859
  this.db.prepare("INSERT INTO fact_changes(scope_id,request_key,request_hash,fact_revision,result_json,proposal_json,before_json,after_json,recorded_at) VALUES (?,?,?,?,?,?,?,?,?)").run(id3, requestKey, requestHash, committedRevision, canonicalJson(result), canonicalJson(proposal), canonicalJson(before), canonicalJson(after), timestamp);
9787
9860
  if (changed) {
@@ -9820,21 +9893,31 @@ var init_facts = __esm({
9820
9893
  });
9821
9894
  }
9822
9895
  validate(scope, proposal) {
9823
- if (!Object.hasOwn(predicates, proposal.predicate)) throw new Error("UNKNOWN_PREDICATE");
9824
- if (!["assert", "reinforce", "state_change", "correction", "exception", "dispute", "retract", "close"].includes(proposal.changeKind) || !["user_statement", "tool_observation", "reported_statement", "inference", "agent_statement"].includes(proposal.claimKind) || !proposal.contextKey || !proposal.reason || !proposal.evidence.length) throw new Error("INVALID_FACT_PROPOSAL");
9825
- if (proposal.claimKind === "inference" && (proposal.changeKind !== "assert" || proposal.targetAssertionIds?.length)) throw new Error("INFERENCE_CANNOT_REVISE_SUPPORTED_FACT");
9896
+ if (!Object.hasOwn(predicates, proposal.predicate)) throw new Error(`UNKNOWN_PREDICATE: predicate \u53EA\u80FD\u662F ${Object.keys(predicates).join("/")}\uFF08\u6536\u5230 ${String(proposal.predicate)}\uFF09`);
9897
+ const invalid = [
9898
+ !CHANGE_KINDS.includes(proposal.changeKind) && "changeKind",
9899
+ !CLAIM_KINDS.includes(proposal.claimKind) && "claimKind",
9900
+ !proposal.contextKey && "contextKey",
9901
+ !proposal.reason && "reason",
9902
+ (!Array.isArray(proposal.evidence) || !proposal.evidence.length) && "evidence"
9903
+ ].filter(Boolean);
9904
+ if (invalid.length) throw new Error(`INVALID_FACT_PROPOSAL: ${invalid.join("\u3001")} \u7F3A\u5931\u6216\u65E0\u6548 \u2014 changeKind \u53D6 ${CHANGE_KINDS.join("/")}\uFF0CclaimKind \u53D6 ${CLAIM_KINDS.join("/")}\uFF1BcontextKey\u3001reason \u5FC5\u586B\uFF0Cevidence \u81F3\u5C11\u4E00\u6761\u539F\u8BDD\u5F15\u6587`);
9905
+ if (proposal.claimKind === "inference" && (proposal.changeKind !== "assert" || proposal.targetAssertionIds?.length)) throw new Error("INFERENCE_CANNOT_REVISE_SUPPORTED_FACT: inference \u53EA\u80FD\u767B\u8BB0\u65B0\u65AD\u8A00\uFF08changeKind=assert\uFF09\uFF0C\u4E0D\u80FD\u4FEE\u8BA2\u5DF2\u6709\u65AD\u8A00");
9826
9906
  const subject = this.entities.get(scope, proposal.subjectId);
9827
- if (!subject || !matchesEntityKind(subject.kind, predicates[proposal.predicate].subjectKind)) throw new Error("ENTITY_SCOPE_MISMATCH");
9907
+ const subjectKind = predicates[proposal.predicate].subjectKind;
9908
+ if (!subject || !matchesEntityKind(subject.kind, subjectKind)) throw new Error(`ENTITY_SCOPE_MISMATCH: predicate=${proposal.predicate} \u7684\u4E3B\u4F53\u987B\u662F ${typeof subjectKind === "string" ? subjectKind : subjectKind.join("/")}\uFF1B\u6536\u5230 ${proposal.subjectId}`);
9828
9909
  if (proposal.predicate === "relation.family" && !familyRoles.includes(proposal.contextKey)) throw new Error("INVALID_FAMILY_ROLE");
9829
9910
  if (proposal.predicate === "relation.colleague" && (proposal.contextKey !== normalizeOrganization(proposal.contextKey) || proposal.contextKey.length > 200)) throw new Error("INVALID_ORGANIZATION_CONTEXT");
9830
9911
  if (proposal.changeKind === "close") {
9831
- if (!isRelationship(proposal.predicate) || proposal.value !== void 0) throw new Error("INVALID_RELATION_CLOSE");
9832
- if (!proposal.validity) throw new Error("FACT_VALIDITY_REQUIRED");
9912
+ if (!isRelationship(proposal.predicate)) throw new Error(`INVALID_RELATION_CLOSE: close \u53EA\u80FD\u7ED3\u675F\u5173\u7CFB\uFF08relation.family/colleague/open\uFF09\uFF0Cpredicate=${proposal.predicate} \u4E0D\u80FD close\uFF1B\u5176\u5B83\u4E8B\u5B9E\u7528 state_change\uFF08\u5E26\u65B0 value\uFF09\u6216 retract`);
9913
+ if (proposal.value !== void 0) throw new Error("INVALID_RELATION_CLOSE: close \u4E0D\u5E26 value \u2014 \u53BB\u6389 proposal.value\uFF08\u5B83\u53EA\u5199\u7ED3\u675F\u65F6\u523B\uFF0C\u4E0D\u767B\u8BB0\u65B0\u5185\u5BB9\uFF09");
9914
+ if (!proposal.validity) throw new Error(`FACT_VALIDITY_REQUIRED: proposal.validity \u5FC5\u586B \u2014 close \u7528 ${CLOSE_VALIDITY}`);
9833
9915
  normalizeValidity(proposal.validity);
9834
9916
  }
9835
9917
  if (!["retract", "close"].includes(proposal.changeKind)) {
9918
+ if (proposal.value === void 0 || proposal.value === null) throw new Error(isRelationship(proposal.predicate) ? `INVALID_FACT_VALUE: changeKind=${proposal.changeKind} \u5FC5\u987B\u5E26\u65B0 value\uFF08\u65E7\u503C\u5230 validity.validFrom \u4E3A\u6B62\u3001\u65B0 value \u4ECE\u8FD9\u4E00\u523B\u751F\u6548\uFF09\uFF1B\u53EA\u662F\u7ED3\u675F\u5173\u7CFB\uFF1AchangeKind \u6539 "close"\uFF0C\u53BB\u6389 value\uFF0Cvalidity \u7528 ${CLOSE_VALIDITY}` : `INVALID_FACT_VALUE: changeKind=${proposal.changeKind} \u5FC5\u987B\u5E26 value`);
9836
9919
  validatePredicateValue(proposal.predicate, proposal.value);
9837
- if (!proposal.validity) throw new Error("FACT_VALIDITY_REQUIRED");
9920
+ if (!proposal.validity) throw new Error('FACT_VALIDITY_REQUIRED: proposal.validity \u5FC5\u586B \u2014 {"validFrom":\u5F00\u59CB\u65F6\u523B\u6216null,"validTo":\u7ED3\u675F\u65F6\u523B\u6216null,"precision":"exact|observed|unknown"}');
9838
9921
  normalizeValidity(proposal.validity);
9839
9922
  const objectKind = predicates[proposal.predicate].objectKind;
9840
9923
  if (objectKind && !matchesEntityKind(this.entities.get(scope, proposal.value.entityId)?.kind, objectKind)) throw new Error("OBJECT_SCOPE_MISMATCH");
@@ -9849,7 +9932,7 @@ var init_facts = __esm({
9849
9932
  const targets = (proposal.targetAssertionIds ?? []).map((assertionId) => this.db.prepare(`SELECT a.claim_kind,a.value_json,s.subject_id
9850
9933
  FROM fact_assertions a JOIN fact_slots s ON s.scope_id=a.scope_id AND s.slot_id=a.slot_id WHERE a.scope_id=? AND a.assertion_id=?`).get(scopeId(scope), assertionId));
9851
9934
  const perspective = value?.relationshipId ? this.entities.get(scope, value.perspectiveEntityId) : subject;
9852
- if (proposal.predicate !== "relation.open" || perspective?.kind !== "agent" || !["close", "retract"].includes(proposal.changeKind) && value?.perspectiveEntityId !== perspective.entityId || targets.some((target) => !target || target.claim_kind !== "agent_statement" || target.subject_id !== subject.entityId || JSON.parse(target.value_json).perspectiveEntityId !== perspective.entityId)) throw new Error("INVALID_AGENT_PERSPECTIVE");
9935
+ if (proposal.predicate !== "relation.open" || perspective?.kind !== "agent" || !["close", "retract"].includes(proposal.changeKind) && value?.perspectiveEntityId !== perspective.entityId || targets.some((target) => target && (target.claim_kind !== "agent_statement" || target.subject_id !== subject.entityId || JSON.parse(target.value_json).perspectiveEntityId !== perspective.entityId))) throw new Error("INVALID_AGENT_PERSPECTIVE: agent_statement \u53EA\u80FD\u7528\u4E8E relation.open\u2014\u2014\u8BC1\u636E\u5FC5\u987B\u662F\u8FD9\u4E2A agent \u81EA\u5DF1\u8BF4\u7684\u8BDD\uFF0C\u76EE\u6807\u65AD\u8A00\u4E5F\u5FC5\u987B\u662F\u540C\u4E00 agent \u767B\u8BB0\u7684 agent_statement");
9853
9936
  }
9854
9937
  if (proposal.predicate === "activity.schedule" && proposal.changeKind !== "retract") {
9855
9938
  const schedule = proposal.value;
@@ -9857,26 +9940,53 @@ var init_facts = __esm({
9857
9940
  if (proposal.contextKey !== "baseline" && !exception) throw new Error("INVALID_SCHEDULE_CONTEXT");
9858
9941
  if ((exception || proposal.changeKind === "exception") && (!exception || schedule.frequency !== "once")) throw new Error("OCCURRENCE_EXCEPTION_REQUIRED");
9859
9942
  }
9860
- for (const evidence of proposal.evidence) {
9943
+ for (const [index, evidence] of proposal.evidence.entries()) {
9944
+ const path35 = `evidence[${index}]`;
9945
+ if (!evidence || typeof evidence !== "object") throw new Error(`INVALID_EVIDENCE_SPAN: ${path35} \u2014 \u6BCF\u6761\u8BC1\u636E\u987B\u662F\u5BF9\u8C61 {sourceId, quote, relation}`);
9861
9946
  const source = this.db.prepare(`SELECT text,role,origin_class,interpretation_status FROM memory_sources s WHERE scope_id=? AND source_id=?
9862
9947
  AND NOT EXISTS (SELECT 1 FROM memory_sources newer WHERE newer.scope_id=s.scope_id
9863
- AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)`).get(scopeId(scope), evidence.sourceId);
9864
- if (!source || source.interpretation_status === "deleted" || !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 || !["supports", "refutes"].includes(evidence.relation)) throw new Error("INVALID_EVIDENCE_SPAN");
9948
+ AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)`).get(scopeId(scope), evidence.sourceId ?? null);
9949
+ if (!source || source.interpretation_status === "deleted") throw new Error(`INVALID_EVIDENCE_SPAN: ${path35}.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`);
9950
+ if (typeof evidence.quote !== "string" || !evidence.quote) throw new Error(`INVALID_EVIDENCE_SPAN: ${path35}.quote \u2014 quote \u5FC5\u586B\uFF0C\u9010\u5B57\u51FA\u81EA\u6765\u6E90\u539F\u6587`);
9951
+ 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) {
9952
+ const count = occurrences(source.text, evidence.quote);
9953
+ throw new Error(count === 0 ? `INVALID_EVIDENCE_SPAN: ${path35}.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: ${path35} \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`);
9954
+ }
9955
+ if (!["supports", "refutes"].includes(evidence.relation)) throw new Error(`INVALID_EVIDENCE_SPAN: ${path35}.relation \u2014 \u53EA\u80FD\u662F supports\uFF08\u652F\u6301\uFF09\u6216 refutes\uFF08\u53CD\u9A73\uFF09`);
9865
9956
  const relationValue = proposal.value;
9866
9957
  if (proposal.predicate === "relation.open" && relationValue?.attribution === "reported" && (proposal.claimKind !== "reported_statement" || !hasReportedAttribution(source.text, relationValue, this.entities.sourceMentions(scope, evidence.sourceId)))) {
9867
- throw new Error("EVIDENCE_REPORTED_ATTRIBUTION_UNGROUNDED");
9958
+ 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");
9868
9959
  }
9960
+ const roleMismatch = () => new Error(`EVIDENCE_ROLE_MISMATCH: ${path35} \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`);
9869
9961
  if (proposal.claimKind !== "inference") {
9870
- if (proposal.claimKind === "user_statement" && (source.role !== "user" || !["host_user", "client_reported_user"].includes(source.origin_class))) throw new Error("EVIDENCE_ROLE_MISMATCH");
9871
- if (proposal.claimKind === "tool_observation" && (source.role !== "tool" || source.origin_class !== "tool_observation")) throw new Error("EVIDENCE_ROLE_MISMATCH");
9962
+ if (proposal.claimKind === "user_statement" && (source.role !== "user" || !["host_user", "client_reported_user"].includes(source.origin_class))) throw roleMismatch();
9963
+ if (proposal.claimKind === "tool_observation" && (source.role !== "tool" || source.origin_class !== "tool_observation")) throw roleMismatch();
9872
9964
  if (proposal.claimKind === "reported_statement" && (source.role !== "user" || !["third_party_report", "legacy_import"].includes(source.origin_class))) {
9873
9965
  const value = proposal.value;
9874
9966
  const attributed = proposal.predicate === "relation.open" && value?.attribution === "reported" && ["user", "assistant"].includes(source.role) && ["host_user", "client_reported_user", "assistant"].includes(source.origin_class) && hasReportedAttribution(source.text, value, this.entities.sourceMentions(scope, evidence.sourceId));
9875
- if (!attributed) throw new Error("EVIDENCE_ROLE_MISMATCH");
9967
+ if (!attributed) throw roleMismatch();
9876
9968
  }
9877
- if (proposal.claimKind === "agent_statement" && (source.role !== "assistant" || source.origin_class !== "assistant" || this.entities.speaker(scope, evidence.sourceId)?.entityId !== (proposal.value?.perspectiveEntityId ?? subject.entityId))) throw new Error("EVIDENCE_ROLE_MISMATCH");
9878
- }
9879
- }
9969
+ if (proposal.claimKind === "agent_statement" && (source.role !== "assistant" || source.origin_class !== "assistant" || this.entities.speaker(scope, evidence.sourceId)?.entityId !== (proposal.value?.perspectiveEntityId ?? subject.entityId))) throw roleMismatch();
9970
+ }
9971
+ }
9972
+ }
9973
+ /** 1124:UTF-16 下标不是人能数准的——引文在原文中只出现一次时,start/end 可省略或写错,由引擎对齐;没有或重复的留给 validate() 说明。 */
9974
+ locateEvidence(scope, proposal) {
9975
+ const aligned = [];
9976
+ if (!Array.isArray(proposal.evidence)) return { proposal, aligned };
9977
+ const evidence = proposal.evidence.map((ref, index) => {
9978
+ const text2 = this.db.prepare("SELECT text FROM memory_sources WHERE scope_id=? AND source_id=?").get(scope, ref?.sourceId ?? null)?.text;
9979
+ if (typeof text2 !== "string" || typeof ref?.quote !== "string" || !ref.quote || occurrences(text2, ref.quote) !== 1) return ref;
9980
+ const start = text2.indexOf(ref.quote);
9981
+ if (Number.isSafeInteger(ref.start) && ref.start === start && ref.end === start + ref.quote.length) return ref;
9982
+ aligned.push({
9983
+ index,
9984
+ given: [Number.isSafeInteger(ref.start) ? ref.start : null, Number.isSafeInteger(ref.end) ? ref.end : null],
9985
+ located: [start, start + ref.quote.length]
9986
+ });
9987
+ return { ...ref, start, end: start + ref.quote.length };
9988
+ });
9989
+ return { proposal: { ...proposal, evidence }, aligned };
9880
9990
  }
9881
9991
  current(scope, slotId) {
9882
9992
  return this.versions(scope, slotId);
@@ -10019,7 +10129,7 @@ function summary(input) {
10019
10129
  try {
10020
10130
  const p = JSON.parse(input);
10021
10131
  if (!p || typeof p !== "object" || Array.isArray(p)) return input;
10022
- const small = Object.fromEntries(Object.entries(p).filter(([key2, value]) => routing.has(key2) || Buffer.byteLength(JSON.stringify(value)) <= 1024));
10132
+ const small = Object.fromEntries(Object.entries(p).filter(([key4, value]) => routing.has(key4) || Buffer.byteLength(JSON.stringify(value)) <= 1024));
10023
10133
  if (!Object.hasOwn(small, "basis") && p.basis?.scope) small.basis = { scope: p.basis.scope };
10024
10134
  return JSON.stringify(small);
10025
10135
  } catch {
@@ -11578,10 +11688,10 @@ ${e.outcome}
11578
11688
  ];
11579
11689
  if (revalidationKinds.length === 0) return 0;
11580
11690
  for (const scope of this.sources.scopes()) {
11581
- const received = this.sources.interpretationProgress(scope).received;
11691
+ const received2 = this.sources.interpretationProgress(scope).received;
11582
11692
  for (const artifact of this.dependencies.dirty(scope)) {
11583
11693
  if (!revalidationKinds.includes(artifact.kind)) continue;
11584
- if (received > 0 && !(artifact.updatedAt !== null && Date.now() - artifact.updatedAt >= STALE_ARTIFACT_FORCE_MS)) continue;
11694
+ if (received2 > 0 && !(artifact.updatedAt !== null && Date.now() - artifact.updatedAt >= STALE_ARTIFACT_FORCE_MS)) continue;
11585
11695
  const previous = this.db.prepare("SELECT kind,payload FROM ome_jobs WHERE id=?").all(artifactGenerationJobId(this.db, scope, artifact.kind, artifact.id, artifact.version));
11586
11696
  for (const row of previous) {
11587
11697
  const payload = JSON.parse(row.payload);
@@ -12525,10 +12635,6 @@ var init_process_card = __esm({
12525
12635
  });
12526
12636
  return this.creation;
12527
12637
  }
12528
- /** Mode decisions can start native progress without awaiting any channel I/O. */
12529
- start() {
12530
- if (!this.ended && !this.started && (this.nativeCapable() || this.legacyCapable() || this.progressCapable())) this.beginInBackground();
12531
- }
12532
12638
  progressCapable() {
12533
12639
  return !!this.adapter.sendProgress && !!this.adapter.updateProgress && !!this.adapter.removeProgress;
12534
12640
  }
@@ -12669,8 +12775,7 @@ var init_process_card = __esm({
12669
12775
  }
12670
12776
  /** stream_event content_block_delta(thinking_delta):实时喂思考内容 */
12671
12777
  onThinkingDelta(chunk) {
12672
- if (!chunk || this.ended || this.disposed) return;
12673
- this.ensureStarted();
12778
+ if (!chunk || this.ended || this.disposed || !this.started) return;
12674
12779
  const lt = this.state.liveThink ??= { start: Date.now(), text: "" };
12675
12780
  lt.text += chunk;
12676
12781
  if (lt.text.length > 800) lt.text = lt.text.slice(-600);
@@ -12688,8 +12793,7 @@ var init_process_card = __esm({
12688
12793
  }
12689
12794
  /** assistant thinking 完整块(无增量流时的兜底;增量路径下与 Thought 行去重) */
12690
12795
  onThinking(text2) {
12691
- if (this.ended || this.disposed) return;
12692
- this.ensureStarted();
12796
+ if (this.ended || this.disposed || !this.started) return;
12693
12797
  if (this.state.liveThink) return;
12694
12798
  const last = this.state.rows[this.state.rows.length - 1];
12695
12799
  if (last?.kind === "think") return;
@@ -12701,10 +12805,10 @@ var init_process_card = __esm({
12701
12805
  const rid = this.nextRid("p");
12702
12806
  const preview = stripCardUnsafe(toolArgsSummary(toolName, input) || oneLine(JSON.stringify(input).slice(0, 200)));
12703
12807
  return new Promise((resolve12) => {
12704
- let settled = false;
12808
+ let settled2 = false;
12705
12809
  const settle = (v, message) => {
12706
- if (settled) return;
12707
- settled = true;
12810
+ if (settled2) return;
12811
+ settled2 = true;
12708
12812
  clearTimeout(timer);
12709
12813
  pendingPerms.delete(rid);
12710
12814
  this.currentPermRid = null;
@@ -12732,10 +12836,10 @@ var init_process_card = __esm({
12732
12836
  const rid = this.nextRid("q");
12733
12837
  const safeQ = questions.map((q) => ({ ...q, question: stripCardUnsafe(q.question), header: stripCardUnsafe(q.header), options: q.options.map((o) => ({ ...o, label: stripCardUnsafe(o.label) })) }));
12734
12838
  return new Promise((resolve12) => {
12735
- let settled = false;
12839
+ let settled2 = false;
12736
12840
  const settle = (answers, message) => {
12737
- if (settled) return;
12738
- settled = true;
12841
+ if (settled2) return;
12842
+ settled2 = true;
12739
12843
  clearTimeout(timer);
12740
12844
  pendingAsks.delete(rid);
12741
12845
  this.currentAskRid = null;
@@ -12826,7 +12930,7 @@ var init_process_card = __esm({
12826
12930
  return;
12827
12931
  }
12828
12932
  if (this.patchTimer) return;
12829
- const min = this.channelV === "cardkit" || this.channelV === "progress" ? CARDKIT_UPDATE_INTERVAL_MS : PATCH_MIN_INTERVAL_MS;
12933
+ const min = this.channelV === "cardkit" || this.channelV === "progress" ? this.adapter.progressThrottleMs ?? CARDKIT_UPDATE_INTERVAL_MS : PATCH_MIN_INTERVAL_MS;
12830
12934
  const wait2 = Math.max(0, min - (Date.now() - this.lastPatchAt));
12831
12935
  this.patchTimer = setTimeout(() => {
12832
12936
  this.patchTimer = null;
@@ -12841,10 +12945,6 @@ var init_process_card = __esm({
12841
12945
  await this.creation?.catch(() => {
12842
12946
  });
12843
12947
  if (this.disposed || this.ended && !final) return;
12844
- if (final && this.options.discardEmptyOnDone && this.state.status === "done" && !this.state.earlierSteps && !this.state.rows.some((row) => row.kind !== "think") && (!this.messageId || this.adapter.deletePreview || this.adapter.removeProgress)) {
12845
- await this.removeCard().catch((error) => console.warn("[process-card] \u7A7A\u56DE\u5408\u6E05\u7406\u5931\u8D25:", error instanceof Error ? error.message : String(error)));
12846
- return;
12847
- }
12848
12948
  const pushed = await this.doPatch(final);
12849
12949
  if (final && !pushed && !this.disposed && this.options.sendSummary && !this.summarySent) {
12850
12950
  this.summarySent = true;
@@ -12868,8 +12968,8 @@ var init_process_card = __esm({
12868
12968
  }
12869
12969
  async doPatch(final = false) {
12870
12970
  if (this.degraded || !this.messageId && this.channelV !== "cardkit") return false;
12871
- const key2 = this.pushKey();
12872
- if (key2 === this.lastPushKey) return true;
12971
+ const key4 = this.pushKey();
12972
+ if (key4 === this.lastPushKey) return true;
12873
12973
  this.lastPatchAt = Date.now();
12874
12974
  const card = this.channelV === "progress" ? null : this.channelV === "patch-v1" ? buildProcessCard(this.state) : buildProcessCardV2(this.state) ?? (this.options.allowLegacyCard !== false ? buildProcessCard(this.state) : null);
12875
12975
  if (this.channelV !== "preview" && this.channelV !== "progress" && !card) return false;
@@ -12885,7 +12985,7 @@ var init_process_card = __esm({
12885
12985
  await this.adapter.patchCard(this.messageId, card);
12886
12986
  } else return false;
12887
12987
  this.patchFailures = 0;
12888
- this.lastPushKey = key2;
12988
+ this.lastPushKey = key4;
12889
12989
  return true;
12890
12990
  } catch (err) {
12891
12991
  if (this.channelV === "cardkit" && isPermissionDenied(err)) {
@@ -12895,7 +12995,7 @@ var init_process_card = __esm({
12895
12995
  await this.removeCard();
12896
12996
  if (this.disposed) return false;
12897
12997
  await this.createLegacyCard();
12898
- this.lastPushKey = key2;
12998
+ this.lastPushKey = key4;
12899
12999
  this.patchFailures = 0;
12900
13000
  if (!this.ended) this.startHeartbeat();
12901
13001
  return true;
@@ -13030,23 +13130,23 @@ var init_session_map = __esm({
13030
13130
  this.map = {};
13031
13131
  }
13032
13132
  }
13033
- get(key2) {
13034
- return this.map[key2];
13133
+ get(key4) {
13134
+ return this.map[key4];
13035
13135
  }
13036
- set(key2, sessionId, workDir) {
13037
- this.map[key2] = { sessionId, workDir, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
13136
+ set(key4, sessionId, workDir) {
13137
+ this.map[key4] = { sessionId, workDir, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
13038
13138
  this.save();
13039
13139
  }
13040
13140
  /** 清掉 binding 的会话绑定(/cc-new)。返回是否真的清了。 */
13041
- clear(key2) {
13042
- if (!(key2 in this.map)) return false;
13043
- delete this.map[key2];
13141
+ clear(key4) {
13142
+ if (!(key4 in this.map)) return false;
13143
+ delete this.map[key4];
13044
13144
  this.save();
13045
13145
  return true;
13046
13146
  }
13047
13147
  /** /cc-switch 直写目标会话 */
13048
- switchTo(key2, sessionId, workDir) {
13049
- this.set(key2, sessionId, workDir);
13148
+ switchTo(key4, sessionId, workDir) {
13149
+ this.set(key4, sessionId, workDir);
13050
13150
  }
13051
13151
  save() {
13052
13152
  try {
@@ -13299,9 +13399,9 @@ function sharedNodeModules() {
13299
13399
  function pkgDir(name) {
13300
13400
  return path5.join(sharedNodeModules(), ...name.split("/"));
13301
13401
  }
13302
- function readConfig(key2) {
13402
+ function readConfig(key4) {
13303
13403
  try {
13304
- return liveConfig.get(key2);
13404
+ return liveConfig.get(key4);
13305
13405
  } catch {
13306
13406
  }
13307
13407
  }
@@ -13316,9 +13416,9 @@ function downloadsEnabled() {
13316
13416
  function currentPlatformKey() {
13317
13417
  return `${process.platform}-${process.arch}`;
13318
13418
  }
13319
- function featureSpec(key2) {
13320
- const spec = OPTIONAL_FEATURES[key2];
13321
- if (!spec) throw new Error(`[dep-downloader] optional-deps.json \u91CC\u6CA1\u6709\u952E\uFF1A${key2}`);
13419
+ function featureSpec(key4) {
13420
+ const spec = OPTIONAL_FEATURES[key4];
13421
+ if (!spec) throw new Error(`[dep-downloader] optional-deps.json \u91CC\u6CA1\u6709\u952E\uFF1A${key4}`);
13322
13422
  return spec;
13323
13423
  }
13324
13424
  function markerPath(spec) {
@@ -13331,8 +13431,8 @@ function isPkgInstalled(spec) {
13331
13431
  return false;
13332
13432
  }
13333
13433
  }
13334
- function isOptionalFeatureInstalled(key2) {
13335
- const spec = featureSpec(key2);
13434
+ function isOptionalFeatureInstalled(key4) {
13435
+ const spec = featureSpec(key4);
13336
13436
  if (!isPkgInstalled(spec.main)) return false;
13337
13437
  const plat = spec.platform?.[currentPlatformKey()];
13338
13438
  if (plat && !isPkgInstalled(plat)) return false;
@@ -13436,9 +13536,9 @@ function notInstalledError(spec) {
13436
13536
  err.code = "ERR_MODULE_NOT_FOUND";
13437
13537
  return err;
13438
13538
  }
13439
- async function ensureOptionalFeature(key2, onProgress) {
13440
- const spec = featureSpec(key2);
13441
- if (isOptionalFeatureInstalled(key2)) return pkgDir(spec.main.name);
13539
+ async function ensureOptionalFeature(key4, onProgress) {
13540
+ const spec = featureSpec(key4);
13541
+ if (isOptionalFeatureInstalled(key4)) return pkgDir(spec.main.name);
13442
13542
  if (!downloadsEnabled()) throw notInstalledError(spec);
13443
13543
  const plat = spec.platform?.[currentPlatformKey()];
13444
13544
  const pkgs = [spec.main, ...plat ? [plat] : [], ...spec.extra ?? []];
@@ -13449,17 +13549,17 @@ function requireFromShared(name) {
13449
13549
  const req = createRequire3(path5.join(sharedNodeModules(), ".e7-resolve.js"));
13450
13550
  return req(name);
13451
13551
  }
13452
- async function loadOptionalModule(key2, onProgress) {
13453
- const spec = featureSpec(key2);
13552
+ async function loadOptionalModule(key4, onProgress) {
13553
+ const spec = featureSpec(key4);
13454
13554
  const notFound = (err) => err?.code === "ERR_MODULE_NOT_FOUND" || err?.code === "MODULE_NOT_FOUND";
13455
13555
  try {
13456
13556
  return nodeRequire(spec.main.name);
13457
13557
  } catch (err) {
13458
13558
  if (!notFound(err)) throw err;
13459
13559
  }
13460
- if (!isOptionalFeatureInstalled(key2)) {
13560
+ if (!isOptionalFeatureInstalled(key4)) {
13461
13561
  if (!downloadsEnabled()) throw notInstalledError(spec);
13462
- await ensureOptionalFeature(key2, onProgress);
13562
+ await ensureOptionalFeature(key4, onProgress);
13463
13563
  }
13464
13564
  const dir = pkgDir(spec.main.name);
13465
13565
  try {
@@ -13489,11 +13589,11 @@ var init_dep_downloader = __esm({
13489
13589
  OPTIONAL_FEATURES = (() => {
13490
13590
  const raw = optional_deps_default;
13491
13591
  const out = {};
13492
- for (const [key2, v] of Object.entries(raw)) {
13493
- if (key2 === "//") continue;
13592
+ for (const [key4, v] of Object.entries(raw)) {
13593
+ if (key4 === "//") continue;
13494
13594
  const bad = !v?.main?.name || !v?.main?.version || !v?.main?.integrity?.startsWith("sha512-") || v.platform !== void 0 && Object.values(v.platform).some((p) => !p?.name || !p?.version || !p?.integrity?.startsWith("sha512-")) || v.extra !== void 0 && (!Array.isArray(v.extra) || v.extra.some((p) => !p?.name || !p?.version || !p?.integrity?.startsWith("sha512-")));
13495
- if (bad) throw new Error(`[dep-downloader] optional-deps.json \u6761\u76EE ${key2} \u7F3A name/version/integrity\uFF08integrity \u53D6 npm view <name>@<version> dist.integrity\uFF09`);
13496
- out[key2] = { key: key2, label: v.label ?? key2, main: v.main, platform: v.platform, extra: v.extra };
13595
+ if (bad) throw new Error(`[dep-downloader] optional-deps.json \u6761\u76EE ${key4} \u7F3A name/version/integrity\uFF08integrity \u53D6 npm view <name>@<version> dist.integrity\uFF09`);
13596
+ out[key4] = { key: key4, label: v.label ?? key4, main: v.main, platform: v.platform, extra: v.extra };
13497
13597
  }
13498
13598
  return out;
13499
13599
  })();
@@ -14155,7 +14255,7 @@ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
14155
14255
  const file2 = join14(dir, `${stamp}-${tail}-${i + 1}${ext}`);
14156
14256
  mkdirSync9(dir, { recursive: true });
14157
14257
  writeFileSync8(file2, bytes2);
14158
- const how = a.contentType.startsWith("image/") ? "\u56FE\u7247\u2014\u2014\u7528 Read \u5DE5\u5177\u6253\u5F00\u8FD9\u4E2A\u8DEF\u5F84\u5373\u53EF\u770B\u5230" : `\u6587\u4EF6\uFF08${a.contentType || "\u672A\u77E5\u7C7B\u578B"}\uFF09`;
14258
+ const how = a.contentType.startsWith("image/") ? "\u56FE\u7247\u2014\u2014\u8FD9\u662F\u4E00\u6761\u5FC5\u987B\u56DE\u5E94\u7684\u6D88\u606F\uFF1A\u5148\u7528 Read \u5DE5\u5177\u6253\u5F00\u8FD9\u4E2A\u8DEF\u5F84\u67E5\u770B\u5185\u5BB9\uFF0C\u518D\u544A\u8BC9\u6211\u4F60\u770B\u5230\u4E86\u4EC0\u4E48" : `\u6587\u4EF6\uFF08${a.contentType || "\u672A\u77E5\u7C7B\u578B"}\uFF09\u2014\u2014\u7528\u5BF9\u5E94\u5DE5\u5177\u6253\u5F00\u8FD9\u4E2A\u8DEF\u5F84\u67E5\u770B\u5185\u5BB9\u540E\u56DE\u5E94`;
14159
14259
  lines.push(`${i + 1}. ${label}\uFF0C${how}\uFF1A${file2}`);
14160
14260
  } catch (err) {
14161
14261
  lines.push(`${i + 1}. ${label} \u843D\u76D8\u5931\u8D25\uFF1A${err?.message || String(err)}`);
@@ -14185,10 +14285,10 @@ ${note}` : note)).catch((err) => session.enqueue(`${inbound.content}
14185
14285
  return this.sessions.get(`${channel}:${chatId}`);
14186
14286
  }
14187
14287
  /** 按 bindingKey(channel:chatId)找 session——卡片停止钮回调用(1119) */
14188
- forChatKey(key2) {
14189
- const idx = key2.indexOf(":");
14288
+ forChatKey(key4) {
14289
+ const idx = key4.indexOf(":");
14190
14290
  if (idx <= 0) return void 0;
14191
- return this.sessions.get(key2);
14291
+ return this.sessions.get(key4);
14192
14292
  }
14193
14293
  /** 全部绑定的工作目录(去重;cc-progress 工具省参推断用) */
14194
14294
  get bindingWorkDirs() {
@@ -14197,8 +14297,8 @@ ${note}` : note)).catch((err) => session.enqueue(`${inbound.content}
14197
14297
  get bindings() {
14198
14298
  return [...this.sessions.values()].map((s) => ({ key: s.key, workDir: s.workDir, sessionId: s.currentSessionId, busy: s.busy }));
14199
14299
  }
14200
- ask(key2, workDir, prompt, source, expectedSessionId, signal) {
14201
- const session = this.sessions.get(key2);
14300
+ ask(key4, workDir, prompt, source, expectedSessionId, signal) {
14301
+ const session = this.sessions.get(key4);
14202
14302
  if (!session) return Promise.reject(requestError("CC binding not found", 404));
14203
14303
  if (session.workDir !== workDir) return Promise.reject(requestError("CC binding workDir changed"));
14204
14304
  return session.ask(prompt, source, expectedSessionId, signal);
@@ -14224,7 +14324,7 @@ function registerCcHub(hub2, stateDir, port) {
14224
14324
  const dir = registryDir2();
14225
14325
  fs6.mkdirSync(dir, { recursive: true, mode: 448 });
14226
14326
  const file2 = path6.join(dir, `${process.pid}.json`);
14227
- const endpoint = { pid: process.pid, stateDir, port, bindings: hub2.bindings.map(({ key: key2, workDir }) => ({ key: key2, workDir })) };
14327
+ const endpoint = { pid: process.pid, stateDir, port, bindings: hub2.bindings.map(({ key: key4, workDir }) => ({ key: key4, workDir })) };
14228
14328
  const tmp = `${file2}.tmp`;
14229
14329
  fs6.writeFileSync(tmp, JSON.stringify(endpoint), { mode: 384 });
14230
14330
  fs6.renameSync(tmp, file2);
@@ -14464,11 +14564,11 @@ __export(dispatches_exports, {
14464
14564
  finishCalendarDispatch: () => finishCalendarDispatch,
14465
14565
  recoverCalendarDispatches: () => recoverCalendarDispatches
14466
14566
  });
14467
- function beginCalendarDispatch(db2, key2, binding, context) {
14567
+ function beginCalendarDispatch(db2, key4, binding, context) {
14468
14568
  if (context && (!context.scopeId || context.calendarBinding?.eventId !== binding.eventId || context.calendarBinding.version !== binding.version || context.calendarBinding.occurrenceId !== binding.occurrenceId || !Array.isArray(context.basisRefs) || context.basisRefs.some((ref) => ref.scopeId !== context.scopeId))) throw new Error("CALENDAR_DISPATCH_CONTEXT_INVALID");
14469
14569
  return Boolean(db2.prepare(`INSERT OR IGNORE INTO calendar_dispatches
14470
14570
  (dispatch_key,event_id,binding_version,occurrence_id,state,started_at,scope_id,context_json) VALUES (?,?,?,?,'started',?,?,?)`).run(
14471
- key2,
14571
+ key4,
14472
14572
  binding.eventId,
14473
14573
  binding.version,
14474
14574
  binding.occurrenceId,
@@ -14477,8 +14577,8 @@ function beginCalendarDispatch(db2, key2, binding, context) {
14477
14577
  context ? JSON.stringify(context) : null
14478
14578
  ).changes);
14479
14579
  }
14480
- function finishCalendarDispatch(db2, key2, state) {
14481
- db2.prepare("UPDATE calendar_dispatches SET state=?,finished_at=?,version=version+1 WHERE dispatch_key=? AND state='started'").run(state, Date.now(), key2);
14580
+ function finishCalendarDispatch(db2, key4, state) {
14581
+ db2.prepare("UPDATE calendar_dispatches SET state=?,finished_at=?,version=version+1 WHERE dispatch_key=? AND state='started'").run(state, Date.now(), key4);
14482
14582
  }
14483
14583
  function recoverCalendarDispatches(db2) {
14484
14584
  return Number(db2.prepare("UPDATE calendar_dispatches SET state='delivery_unknown',finished_at=?,receipt='process_interrupted_before_receipt',version=version+1 WHERE state='started'").run(Date.now()).changes);
@@ -14954,7 +15054,7 @@ var init_intent_state = __esm({
14954
15054
  // src/memory/proactive/mutation-service.ts
14955
15055
  function canonical3(value) {
14956
15056
  if (Array.isArray(value)) return value.map(canonical3);
14957
- if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key2, item]) => [key2, canonical3(item)]));
15057
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key4, item]) => [key4, canonical3(item)]));
14958
15058
  return value;
14959
15059
  }
14960
15060
  var graphBasis;
@@ -15151,18 +15251,18 @@ function createGraphMemoryValidator(memory) {
15151
15251
  }
15152
15252
  const scope = memory?.sources.scope(scopeKey);
15153
15253
  if (!memory || !scope) throw new Error("GRAPH_MEMORY_READ_GUARD_REQUIRED");
15154
- const unseen = [...new Map(refs.map((ref) => [JSON.stringify([scopeKey, ref]), ref])).entries()].filter(([key2]) => !checkedRefs.has(key2));
15254
+ const unseen = [...new Map(refs.map((ref) => [JSON.stringify([scopeKey, ref]), ref])).entries()].filter(([key4]) => !checkedRefs.has(key4));
15155
15255
  memory.dependencies.assertReferences(scope, unseen.map(([, ref]) => ref));
15156
- for (const [key2] of unseen) checkedRefs.add(key2);
15256
+ for (const [key4] of unseen) checkedRefs.add(key4);
15157
15257
  const sourceIds = [.../* @__PURE__ */ new Set([
15158
15258
  ...refs.filter((ref) => ref.parentKind === "source").map((ref) => ref.parentId),
15159
15259
  ...typeof node.data.socialSourceId === "string" ? [node.data.socialSourceId] : []
15160
15260
  ])];
15161
15261
  for (const id3 of sourceIds) {
15162
- const key2 = JSON.stringify([scopeKey, id3]);
15163
- if (checkedSources.has(key2)) continue;
15262
+ const key4 = JSON.stringify([scopeKey, id3]);
15263
+ if (checkedSources.has(key4)) continue;
15164
15264
  if (!memory.socialSources.readable(scope, id3) || !memory.socialSources.groundsCurrent(scope, id3)) throw new Error("STALE_GRAPH_SOCIAL_SOURCE");
15165
- checkedSources.add(key2);
15265
+ checkedSources.add(key4);
15166
15266
  }
15167
15267
  const relation = node.data.relationshipRef;
15168
15268
  const relationshipKey = relation && JSON.stringify([scopeKey, relation]);
@@ -15195,7 +15295,7 @@ function digest5(value) {
15195
15295
  }
15196
15296
  function generationBasis(intent) {
15197
15297
  const data = { ...intent.data };
15198
- for (const key2 of ["status", "stateVersion", "reasonCode", "deferredReason", "waitingFor", "nextEligibleAt", "completedOccurrenceId"]) delete data[key2];
15298
+ for (const key4 of ["status", "stateVersion", "reasonCode", "deferredReason", "waitingFor", "nextEligibleAt", "completedOccurrenceId"]) delete data[key4];
15199
15299
  return graphBasis({ ...intent, data });
15200
15300
  }
15201
15301
  var IntentRunStore;
@@ -15399,9 +15499,9 @@ CREATE TABLE memory_projection_heads (
15399
15499
  }
15400
15500
  inspect(event2) {
15401
15501
  if (event2.schemaVersion !== 1 || !event2.eventId || !event2.scopeId || !event2.aggregateId || !Number.isSafeInteger(event2.eventSeq) || event2.eventSeq < 1 || !Number.isSafeInteger(event2.aggregateVersion) || event2.aggregateVersion < 1) throw new Error("INVALID_PROJECTION_EVENT");
15402
- const received = this.db.prepare("SELECT payload_hash FROM memory_projection_inbox WHERE event_id=?").get(event2.eventId);
15403
- if (received) {
15404
- if (received.payload_hash !== eventHash(event2)) throw new Error("PROJECTION_EVENT_ID_CONFLICT");
15502
+ const received2 = this.db.prepare("SELECT payload_hash FROM memory_projection_inbox WHERE event_id=?").get(event2.eventId);
15503
+ if (received2) {
15504
+ if (received2.payload_hash !== eventHash(event2)) throw new Error("PROJECTION_EVENT_ID_CONFLICT");
15405
15505
  return "duplicate";
15406
15506
  }
15407
15507
  if (event2.eventSeq !== this.position(event2.scopeId) + 1) throw new Error("PROJECTION_SEQUENCE_GAP");
@@ -15431,9 +15531,9 @@ CREATE TABLE memory_projection_heads (
15431
15531
  * 详见 docs/research/2026-10-20-mem7-poison-delivery-followup.md。 */
15432
15532
  skip(event2) {
15433
15533
  if (event2.schemaVersion !== 1 || !event2.eventId || !event2.scopeId || !Number.isSafeInteger(event2.eventSeq) || event2.eventSeq < 1) throw new Error("INVALID_PROJECTION_EVENT");
15434
- const received = this.db.prepare("SELECT payload_hash FROM memory_projection_inbox WHERE event_id=?").get(event2.eventId);
15435
- if (received) {
15436
- if (received.payload_hash !== eventHash(event2)) throw new Error("PROJECTION_EVENT_ID_CONFLICT");
15534
+ const received2 = this.db.prepare("SELECT payload_hash FROM memory_projection_inbox WHERE event_id=?").get(event2.eventId);
15535
+ if (received2) {
15536
+ if (received2.payload_hash !== eventHash(event2)) throw new Error("PROJECTION_EVENT_ID_CONFLICT");
15437
15537
  return;
15438
15538
  }
15439
15539
  if (event2.eventSeq !== this.position(event2.scopeId) + 1) throw new Error("PROJECTION_SEQUENCE_GAP");
@@ -15629,20 +15729,20 @@ CREATE INDEX idx_action_dispatch_state ON action_dispatches(state,started_at);
15629
15729
  constructor(db2) {
15630
15730
  this.db = db2;
15631
15731
  }
15632
- begin(key2, scopeId2, versions) {
15732
+ begin(key4, scopeId2, versions) {
15633
15733
  const result = this.db.prepare(`INSERT OR IGNORE INTO action_dispatches
15634
- (dispatch_key,scope_id,action_versions,state,started_at) VALUES (?,?,?,'started',?)`).run(key2, scopeId2, JSON.stringify(versions), Date.now());
15734
+ (dispatch_key,scope_id,action_versions,state,started_at) VALUES (?,?,?,'started',?)`).run(key4, scopeId2, JSON.stringify(versions), Date.now());
15635
15735
  if (!result.changes) return false;
15636
15736
  for (const id3 of Object.keys(versions)) this.db.prepare(`UPDATE actions SET dispatch_key=?,dispatch_state='started'
15637
- WHERE id=? AND scope_id=?`).run(key2, id3, scopeId2);
15737
+ WHERE id=? AND scope_id=?`).run(key4, id3, scopeId2);
15638
15738
  return true;
15639
15739
  }
15640
- finish(key2, state, receipt) {
15641
- const row = this.db.prepare("SELECT * FROM action_dispatches WHERE dispatch_key=?").get(key2);
15740
+ finish(key4, state, receipt) {
15741
+ const row = this.db.prepare("SELECT * FROM action_dispatches WHERE dispatch_key=?").get(key4);
15642
15742
  if (!row || row.state !== "started") return;
15643
- this.db.prepare("UPDATE action_dispatches SET state=?,finished_at=?,receipt=? WHERE dispatch_key=? AND state='started'").run(state, Date.now(), receipt ?? null, key2);
15743
+ this.db.prepare("UPDATE action_dispatches SET state=?,finished_at=?,receipt=? WHERE dispatch_key=? AND state='started'").run(state, Date.now(), receipt ?? null, key4);
15644
15744
  for (const id3 of Object.keys(JSON.parse(row.action_versions))) this.db.prepare(`UPDATE actions SET dispatch_state=?
15645
- WHERE id=? AND dispatch_key=?`).run(state, id3, key2);
15745
+ WHERE id=? AND dispatch_key=?`).run(state, id3, key4);
15646
15746
  }
15647
15747
  /** Called once by the owning plugin at startup, never by another connection's constructor. */
15648
15748
  recoverInterrupted() {
@@ -15669,15 +15769,15 @@ var init_host_deliveries = __esm({
15669
15769
  this.db = db2;
15670
15770
  }
15671
15771
  enqueue(actionId, version, blocks, context) {
15672
- const key2 = JSON.stringify(["proactive", actionId, version]);
15673
- this.db.prepare("INSERT OR IGNORE INTO proactive_host_deliveries(delivery_key,action_id,action_version,blocks_json,context_json,created_at) VALUES (?,?,?,?,?,?)").run(key2, actionId, version, JSON.stringify(blocks), JSON.stringify(context), (/* @__PURE__ */ new Date()).toISOString());
15674
- return key2;
15772
+ const key4 = JSON.stringify(["proactive", actionId, version]);
15773
+ this.db.prepare("INSERT OR IGNORE INTO proactive_host_deliveries(delivery_key,action_id,action_version,blocks_json,context_json,created_at) VALUES (?,?,?,?,?,?)").run(key4, actionId, version, JSON.stringify(blocks), JSON.stringify(context), (/* @__PURE__ */ new Date()).toISOString());
15774
+ return key4;
15675
15775
  }
15676
15776
  pending() {
15677
15777
  return this.db.prepare("SELECT * FROM proactive_host_deliveries WHERE state='pending' ORDER BY created_at").all().map((row) => ({ key: row.delivery_key, blocks: JSON.parse(row.blocks_json), context: JSON.parse(row.context_json) }));
15678
15778
  }
15679
- finish(key2, state, reason) {
15680
- this.db.prepare("UPDATE proactive_host_deliveries SET state=?,reason=?,finished_at=?,version=version+1 WHERE delivery_key=? AND state='pending'").run(state, reason, (/* @__PURE__ */ new Date()).toISOString(), key2);
15779
+ finish(key4, state, reason) {
15780
+ this.db.prepare("UPDATE proactive_host_deliveries SET state=?,reason=?,finished_at=?,version=version+1 WHERE delivery_key=? AND state='pending'").run(state, reason, (/* @__PURE__ */ new Date()).toISOString(), key4);
15681
15781
  }
15682
15782
  list(scope, options = {}) {
15683
15783
  const where = scope ? ["a.scope_id=? AND json_extract(h.context_json,'$.scopeId')=?"] : [];
@@ -15947,7 +16047,8 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
15947
16047
  this.replication = enrollRuntimeReplication(this.db, stateDir, "proactive", binding);
15948
16048
  this.capture = installSQLiteWriteCapture(this.db, this.replication);
15949
16049
  }
15950
- this.transaction(() => this.personNodes.rebuild(this.loadNodes()));
16050
+ if (!this.db.prepare("SELECT 1 FROM graph_person_nodes LIMIT 1").get())
16051
+ this.transaction(() => this.personNodes.rebuild(this.loadNodes()));
15951
16052
  } catch (error) {
15952
16053
  try {
15953
16054
  this.capture?.close();
@@ -16046,6 +16147,12 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16046
16147
  graphRevision() {
16047
16148
  return Number(this.db.prepare("SELECT revision FROM graph_state WHERE id=1").get().revision);
16048
16149
  }
16150
+ graphCounts() {
16151
+ return {
16152
+ nodes: Number(this.db.prepare("SELECT COUNT(*) n FROM nodes").get().n),
16153
+ edges: Number(this.db.prepare("SELECT COUNT(*) n FROM edges").get().n)
16154
+ };
16155
+ }
16049
16156
  // B7.1(astra review):SQL 级联失效(invalidateGraphChildren/invalidateMemoryEvent)改动的
16050
16157
  // 节点不在调用方 delta 里——事务内收集,提交后由 GraphStore 逐 id 单行刷回缓存。
16051
16158
  cascadeTouched = [];
@@ -16138,6 +16245,9 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16138
16245
  const edges = new Map(keys.flatMap((id3) => this.loadIncidentEdges(id3)).map((edge) => [edgeKey(edge.source, edge.target, edge.edgeType), edge]));
16139
16246
  return { nodes, edges: [...edges.values()], revision: this.graphRevision() };
16140
16247
  };
16248
+ return this.readGraphTransaction(read2);
16249
+ }
16250
+ readGraphTransaction(read2) {
16141
16251
  if (this.inTransaction) return read2();
16142
16252
  this.db.exec("BEGIN");
16143
16253
  try {
@@ -16149,9 +16259,18 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16149
16259
  throw error;
16150
16260
  }
16151
16261
  }
16152
- loadNodes() {
16153
- const rows = this.db.prepare("SELECT * FROM nodes").all();
16154
- return rows.map((r) => ({
16262
+ loadNodes(type, scope) {
16263
+ const clauses = [], values = [];
16264
+ if (type) {
16265
+ clauses.push("type=?");
16266
+ values.push(type);
16267
+ }
16268
+ if (scope !== void 0) {
16269
+ clauses.push("COALESCE(NULLIF(json_extract(data,'$.scopeId'),''),'legacy')=?");
16270
+ values.push(scope);
16271
+ }
16272
+ const rows = this.db.prepare("SELECT * FROM nodes" + (clauses.length ? " WHERE " + clauses.join(" AND ") : "")).iterate(...values);
16273
+ return Array.from(rows, (r) => ({
16155
16274
  id: r.id,
16156
16275
  type: r.type,
16157
16276
  data: JSON.parse(r.data),
@@ -16190,8 +16309,8 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16190
16309
  }));
16191
16310
  }
16192
16311
  loadEdges() {
16193
- const rows = this.db.prepare("SELECT * FROM edges").all();
16194
- return rows.map((r) => ({
16312
+ const rows = this.db.prepare("SELECT * FROM edges").iterate();
16313
+ return Array.from(rows, (r) => ({
16195
16314
  source: r.source,
16196
16315
  target: r.target,
16197
16316
  edgeType: r.edge_type,
@@ -16199,6 +16318,20 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16199
16318
  createdAt: r.created_at
16200
16319
  }));
16201
16320
  }
16321
+ /** One indexed read for a model snapshot, instead of one node/adjacency query per node. */
16322
+ loadEdgesAmong(ids) {
16323
+ if (!ids.size) return [];
16324
+ const keys = JSON.stringify([...ids]);
16325
+ const rows = this.db.prepare(`SELECT * FROM edges WHERE source IN (SELECT value FROM json_each(?))
16326
+ AND target IN (SELECT value FROM json_each(?))`).iterate(keys, keys);
16327
+ return Array.from(rows, (row) => ({
16328
+ source: row.source,
16329
+ target: row.target,
16330
+ edgeType: row.edge_type,
16331
+ weight: row.weight,
16332
+ createdAt: row.created_at
16333
+ }));
16334
+ }
16202
16335
  // === 图:写(GraphStore 镜像调用) ===
16203
16336
  insertNode(node) {
16204
16337
  this.transaction(() => {
@@ -16232,7 +16365,7 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16232
16365
  this.transaction(() => {
16233
16366
  const previous = knownPrevious ?? this.loadNodeById(node.id);
16234
16367
  if (!previous) throw new Error(`nodes row '${node.id}' missing on update (memory/DB divergence)`);
16235
- const changed = this.applyingMemoryInvalidation && knownPrevious ? previous.reasoning !== node.reasoning || previous.groundedIn !== node.groundedIn || [.../* @__PURE__ */ new Set([...Object.keys(previous.data), ...Object.keys(node.data)])].some((key2) => previous.data[key2] !== node.data[key2]) : graphBasis(previous) !== graphBasis(node);
16368
+ const changed = this.applyingMemoryInvalidation && knownPrevious ? previous.reasoning !== node.reasoning || previous.groundedIn !== node.groundedIn || [.../* @__PURE__ */ new Set([...Object.keys(previous.data), ...Object.keys(node.data)])].some((key4) => previous.data[key4] !== node.data[key4]) : graphBasis(previous) !== graphBasis(node);
16236
16369
  if (changed && previous.type === "intent") {
16237
16370
  patchIntentState(previous.data, node.data);
16238
16371
  if (stateVersion(node.data) !== stateVersion(previous.data) + 1) throw new Error("STALE_INTENT_VERSION");
@@ -16243,9 +16376,9 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16243
16376
  this.validateOutcomeEvidence(node.data, node.data.completionEvidence);
16244
16377
  }
16245
16378
  }
16246
- const keys = this.applyingMemoryInvalidation && knownPrevious && node.data.evidenceState !== "deleted" ? [.../* @__PURE__ */ new Set([...Object.keys(previous.data), ...Object.keys(node.data)])].filter((key2) => previous.data[key2] !== node.data[key2]) : void 0;
16247
- if (keys && keys.every((key2) => node.data[key2] !== void 0 && (node.data[key2] === null || typeof node.data[key2] !== "object"))) {
16248
- const patch = keys.flatMap((key2) => [`$.${JSON.stringify(key2)}`, JSON.stringify(node.data[key2])]);
16379
+ const keys = this.applyingMemoryInvalidation && knownPrevious && node.data.evidenceState !== "deleted" ? [.../* @__PURE__ */ new Set([...Object.keys(previous.data), ...Object.keys(node.data)])].filter((key4) => previous.data[key4] !== node.data[key4]) : void 0;
16380
+ if (keys && keys.every((key4) => node.data[key4] !== void 0 && (node.data[key4] === null || typeof node.data[key4] !== "object"))) {
16381
+ const patch = keys.flatMap((key4) => [`$.${JSON.stringify(key4)}`, JSON.stringify(node.data[key4])]);
16249
16382
  const data = keys.length ? `json_set(data,${keys.map(() => "?,json(?)").join(",")})` : "data";
16250
16383
  this.db.prepare(`UPDATE nodes SET data=${data}, reasoning=?, grounded_in=?, last_accessed=?, access_count=? WHERE id=?`).run(...patch, node.reasoning ?? null, JSON.stringify(node.groundedIn), node.lastAccessed, node.accessCount, node.id);
16251
16384
  } else this.db.prepare("UPDATE nodes SET data=?, reasoning=?, grounded_in=?, last_accessed=?, access_count=? WHERE id=?").run(JSON.stringify(node.data), node.reasoning ?? null, JSON.stringify(node.groundedIn), node.lastAccessed, node.accessCount, node.id);
@@ -16771,10 +16904,10 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16771
16904
  /** Close a held host turn after evidence-based review; never make the old outbox pending again. */
16772
16905
  reconcileHostDelivery(input, scope) {
16773
16906
  if (typeof input.requestKey !== "string" || !input.requestKey.trim() || !scope || !input.deliveryKey || !input.actionId || !input.evidence || typeof input.evidence.quote !== "string" || !input.evidence.quote.trim() || !input.evidence.eventId || !["delivered", "cancelled"].includes(input.outcome) || !Number.isSafeInteger(input.expectedActionVersion) || input.expectedActionVersion < 1 || !Number.isSafeInteger(input.expectedDeliveryVersion) || input.expectedDeliveryVersion < 1) throw new Error("INVALID_DELIVERY_RECONCILIATION");
16774
- const versions = (provided, key2, version) => {
16907
+ const versions = (provided, key4, version) => {
16775
16908
  if (provided !== void 0 && (!provided || typeof provided !== "object" || Array.isArray(provided))) throw new Error("INVALID_DELIVERY_RECONCILIATION");
16776
- if (provided && Object.hasOwn(provided, key2) && provided[key2] !== version) throw new Error("INVALID_DELIVERY_RECONCILIATION");
16777
- const entries = Object.entries({ ...provided, [key2]: version }).sort(([a], [b]) => a.localeCompare(b));
16909
+ if (provided && Object.hasOwn(provided, key4) && provided[key4] !== version) throw new Error("INVALID_DELIVERY_RECONCILIATION");
16910
+ const entries = Object.entries({ ...provided, [key4]: version }).sort(([a], [b]) => a.localeCompare(b));
16778
16911
  if (entries.some(([id3, value]) => !id3 || !Number.isSafeInteger(value) || value < 1)) throw new Error("INVALID_DELIVERY_RECONCILIATION");
16779
16912
  return Object.fromEntries(entries);
16780
16913
  };
@@ -18814,15 +18947,15 @@ function validManagement(input) {
18814
18947
  if (input.action === "retire" && !(typeof input.jobId === "string" && identifier.test(input.jobId))) return false;
18815
18948
  if (!Object.hasOwn(managementFields, String(input.action))) return false;
18816
18949
  const fields = managementFields[String(input.action)];
18817
- if (!fields || Object.keys(input).some((key2) => !["version", "action", ...fields].includes(key2)) || fields.some((key2) => !Object.hasOwn(input, key2))) return false;
18818
- for (const key2 of ["ancestor", "descendant", "digest", "parent", "common", "local"]) if (Object.hasOwn(input, key2) && (typeof input[key2] !== "string" || !/^[a-f0-9]{64}$/.test(input[key2]))) return false;
18819
- for (const key2 of ["transferId", "targetNodeId"]) if (Object.hasOwn(input, key2) && (typeof input[key2] !== "string" || !identifier.test(input[key2]))) return false;
18950
+ if (!fields || Object.keys(input).some((key4) => !["version", "action", ...fields].includes(key4)) || fields.some((key4) => !Object.hasOwn(input, key4))) return false;
18951
+ for (const key4 of ["ancestor", "descendant", "digest", "parent", "common", "local"]) if (Object.hasOwn(input, key4) && (typeof input[key4] !== "string" || !/^[a-f0-9]{64}$/.test(input[key4]))) return false;
18952
+ for (const key4 of ["transferId", "targetNodeId"]) if (Object.hasOwn(input, key4) && (typeof input[key4] !== "string" || !identifier.test(input[key4]))) return false;
18820
18953
  if (input.action === "deletionsSince" && (!Number.isSafeInteger(input.after) || Number(input.after) < 0 || !Number.isSafeInteger(input.maximum) || Number(input.maximum) < 1 || Number(input.maximum) > 32)) return false;
18821
18954
  if (input.action === "recordRecoveryBranch" && (!Array.isArray(input.chain) || input.chain.length < 1 || input.chain.length > 4096 || input.chain.some((value) => typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value)) || !Array.isArray(input.proof) || input.proof.length !== input.chain.length)) return false;
18822
18955
  if (Object.hasOwn(input, "permit") && !record(input.permit)) return false;
18823
18956
  if (Object.hasOwn(input, "operation") && !["WRITE", "SEND", "TOOL", "INPUT", "PUBLISH", "CONTROL"].includes(String(input.operation))) return false;
18824
- if (Object.hasOwn(input, "ready") && (!record(input.ready) || Object.keys(input.ready).some((key2) => !["checkpointDigest", "deletionWatermark", "buildManifestId", "volumeVerified", "capabilitiesVerified", "effectsLoaded", "unresolvedCritical"].includes(key2)))) return false;
18825
- if (Object.hasOwn(input, "boundary") && (!record(input.boundary) || Object.keys(input.boundary).some((key2) => !["checkpointDigest", "safeBoundary", "effectsSettled"].includes(key2)))) return false;
18957
+ if (Object.hasOwn(input, "ready") && (!record(input.ready) || Object.keys(input.ready).some((key4) => !["checkpointDigest", "deletionWatermark", "buildManifestId", "volumeVerified", "capabilitiesVerified", "effectsLoaded", "unresolvedCritical"].includes(key4)))) return false;
18958
+ if (Object.hasOwn(input, "boundary") && (!record(input.boundary) || Object.keys(input.boundary).some((key4) => !["checkpointDigest", "safeBoundary", "effectsSettled"].includes(key4)))) return false;
18826
18959
  return true;
18827
18960
  }
18828
18961
  function createTravelAuthorityServer(options) {
@@ -18932,7 +19065,7 @@ function createTravelAuthorityServer(options) {
18932
19065
  return;
18933
19066
  }
18934
19067
  const input = envelope?.travel, keys = input?.action === "register" ? ["version", "action", "bootId"] : input?.action === "heartbeat" ? ["version", "action", "bootId", "sequence", "permit", "deletionWatermark"] : ["version", "action"];
18935
- const validAction = managing ? record(input) && validManagement(input) : ["register", "heartbeat", "status"].includes(input?.action) && Object.keys(input).every((key2) => keys.includes(key2)) && (input.action === "status" || typeof input.bootId === "string" && identifier.test(input.bootId));
19068
+ const validAction = managing ? record(input) && validManagement(input) : ["register", "heartbeat", "status"].includes(input?.action) && Object.keys(input).every((key4) => keys.includes(key4)) && (input.action === "status" || typeof input.bootId === "string" && identifier.test(input.bootId));
18936
19069
  if (!envelope || typeof envelope !== "object" || Array.isArray(envelope) || Object.keys(envelope).length !== 1 || !input || typeof input !== "object" || Array.isArray(input) || input.version !== 1 || !validAction) {
18937
19070
  reply(400, { error: "TRAVEL_CONTROL_INVALID_REQUEST" });
18938
19071
  return;
@@ -18946,7 +19079,7 @@ function createTravelAuthorityServer(options) {
18946
19079
  }
18947
19080
  let result;
18948
19081
  if (managing) {
18949
- if (input.permit && ["tenantId", "companionId", "seatId", "nodeId"].some((key2) => input.permit[key2] !== principal[key2])) throw new Error("TRAVEL_AUTH_DENIED");
19082
+ if (input.permit && ["tenantId", "companionId", "seatId", "nodeId"].some((key4) => input.permit[key4] !== principal[key4])) throw new Error("TRAVEL_AUTH_DENIED");
18950
19083
  switch (input.action) {
18951
19084
  case "bindInitialCheckpoint":
18952
19085
  if (!bootstrapGrants.get(peerFingerprint)?.has(principal.credentialHash)) throw new Error("TRAVEL_AUTH_DENIED");
@@ -19107,12 +19240,12 @@ async function fetchTravelKey(options) {
19107
19240
  const wanted = options.identity;
19108
19241
  if (value?.protocolVersion !== 1 || !value.identity || ["tenantId", "companionId", "seatId", "keyId", "generation"].some((k) => value.identity[k] !== wanted[k]) || !Number.isSafeInteger(value.deletionWatermark) || value.deletionWatermark < options.minimumDeletionWatermark || typeof value.key !== "string" || !/^[A-Za-z0-9+/]{43}=$/.test(value.key))
19109
19242
  throw new Error("KEY_SERVICE_INVALID_RESPONSE");
19110
- const key2 = Buffer.from(value.key, "base64");
19111
- if (key2.length !== 32 || key2.toString("base64") !== value.key) {
19112
- key2.fill(0);
19243
+ const key4 = Buffer.from(value.key, "base64");
19244
+ if (key4.length !== 32 || key4.toString("base64") !== value.key) {
19245
+ key4.fill(0);
19113
19246
  throw new Error("KEY_SERVICE_INVALID_RESPONSE");
19114
19247
  }
19115
- return { key: key2, deletionWatermark: value.deletionWatermark };
19248
+ return { key: key4, deletionWatermark: value.deletionWatermark };
19116
19249
  }
19117
19250
 
19118
19251
  // src/continuity/gateway-store.ts
@@ -19130,6 +19263,13 @@ import { DatabaseSync as DatabaseSync9 } from "node:sqlite";
19130
19263
  init_store();
19131
19264
  init_mem7_replication();
19132
19265
 
19266
+ // src/travel/chunk-store.ts
19267
+ import { gunzipSync as gunzipSync2, gzip as gzip2 } from "node:zlib";
19268
+ import { promisify as promisify2 } from "node:util";
19269
+ var CHUNK_BYTES = 4 * 1024 * 1024;
19270
+ var DATABASE_CHUNK_BYTES = 64 * 1024;
19271
+ var compress2 = promisify2(gzip2);
19272
+
19133
19273
  // src/mem7/intake.ts
19134
19274
  init_system_filter();
19135
19275
  init_host_turns();
@@ -19785,7 +19925,7 @@ function createTravelGatewayServer(options) {
19785
19925
  reply(200, store.applyRecoveryDeletedInputs(principal, input.bindings, input.floor));
19786
19926
  return;
19787
19927
  }
19788
- if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((key2) => !["permit", "options", "eventId", "input", "inputs", "effectId", "dispatchId", "resultBase64", "index", "finalOutput", "channel"].includes(key2))) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
19928
+ if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((key4) => !["permit", "options", "eventId", "input", "inputs", "effectId", "dispatchId", "resultBase64", "index", "finalOutput", "channel"].includes(key4))) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
19789
19929
  if (action === "preparation") {
19790
19930
  if (Object.keys(input).length) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
19791
19931
  reply(200, store.preparationEvidence(principal));
@@ -19837,7 +19977,7 @@ function createTravelGatewayServer(options) {
19837
19977
  const values = action === "produce" ? [input.input] : input.inputs;
19838
19978
  if (!Array.isArray(values) || !values.length || values.length > 100) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
19839
19979
  const decoded = values.map((value) => {
19840
- if (!value || typeof value !== "object" || Object.keys(value).some((key2) => !["eventId", "kind", "ordinal", "version", "bodyBase64"].includes(key2))) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
19980
+ if (!value || typeof value !== "object" || Object.keys(value).some((key4) => !["eventId", "kind", "ordinal", "version", "bodyBase64"].includes(key4))) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
19841
19981
  return { ...value, body: decodeBody(value.bodyBase64) };
19842
19982
  });
19843
19983
  if (input.finalOutput !== void 0 && typeof input.finalOutput !== "boolean") throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
@@ -20113,7 +20253,7 @@ var AgentRegistryImpl = class {
20113
20253
  var agentRegistry = new AgentRegistryImpl();
20114
20254
 
20115
20255
  // src/channels/discord.ts
20116
- import { Client, GatewayIntentBits, Partials, ApplicationCommandOptionType } from "discord.js";
20256
+ import { Client, GatewayIntentBits, MessageFlags, Partials, ApplicationCommandOptionType } from "discord.js";
20117
20257
  import { ProxyAgent as UndiciProxyAgent } from "undici";
20118
20258
  import { HttpsProxyAgent } from "https-proxy-agent";
20119
20259
 
@@ -20348,16 +20488,16 @@ async function guardedExternalEffect(run) {
20348
20488
  Promise.resolve().then(() => (init_dispatches(), dispatches_exports))
20349
20489
  ]);
20350
20490
  const db2 = openDb2(workspace);
20351
- const key3 = "calendar_" + createHash25("sha256").update(JSON.stringify([context.scopeId, context.calendarBinding, effectId])).digest("hex");
20491
+ const key5 = "calendar_" + createHash25("sha256").update(JSON.stringify([context.scopeId, context.calendarBinding, effectId])).digest("hex");
20352
20492
  try {
20353
20493
  assertMemoryExecution(stateDir, workspace, context);
20354
- if (!beginCalendarDispatch2(db2, key3, context.calendarBinding, context)) throw new MemoryExecutionBlockedError("DISPATCH_ALREADY_STARTED");
20494
+ if (!beginCalendarDispatch2(db2, key5, context.calendarBinding, context)) throw new MemoryExecutionBlockedError("DISPATCH_ALREADY_STARTED");
20355
20495
  try {
20356
- const result = await effects.run({ ...host, activeDispatchKey: key3 }, run);
20357
- finishCalendarDispatch2(db2, key3, "delivered");
20496
+ const result = await effects.run({ ...host, activeDispatchKey: key5 }, run);
20497
+ finishCalendarDispatch2(db2, key5, "delivered");
20358
20498
  return result;
20359
20499
  } catch (error) {
20360
- finishCalendarDispatch2(db2, key3, "delivery_unknown");
20500
+ finishCalendarDispatch2(db2, key5, "delivery_unknown");
20361
20501
  throw error;
20362
20502
  }
20363
20503
  } finally {
@@ -20369,22 +20509,22 @@ async function guardedExternalEffect(run) {
20369
20509
  return run();
20370
20510
  }
20371
20511
  const persist = new Persistence2(join17(workspace, ".proactive", "proactive.db"));
20372
- const key2 = "dispatch_" + createHash25("sha256").update(JSON.stringify([
20512
+ const key4 = "dispatch_" + createHash25("sha256").update(JSON.stringify([
20373
20513
  context.scopeId,
20374
20514
  Object.entries(versions).sort(([a], [b]) => a.localeCompare(b)),
20375
20515
  effectId
20376
20516
  ])).digest("hex");
20377
20517
  try {
20378
20518
  assertMemoryExecution(stateDir, workspace, context);
20379
- if (!persist.transaction(() => persist.dispatches.begin(key2, context.scopeId, versions))) {
20519
+ if (!persist.transaction(() => persist.dispatches.begin(key4, context.scopeId, versions))) {
20380
20520
  throw new MemoryExecutionBlockedError("DISPATCH_ALREADY_STARTED");
20381
20521
  }
20382
20522
  try {
20383
- const result = await effects.run({ ...host, activeDispatchKey: key2 }, run);
20384
- persist.transaction(() => persist.dispatches.finish(key2, "delivered", "adapter_acknowledged"));
20523
+ const result = await effects.run({ ...host, activeDispatchKey: key4 }, run);
20524
+ persist.transaction(() => persist.dispatches.finish(key4, "delivered", "adapter_acknowledged"));
20385
20525
  return result;
20386
20526
  } catch (error) {
20387
- persist.transaction(() => persist.dispatches.finish(key2, "delivery_unknown"));
20527
+ persist.transaction(() => persist.dispatches.finish(key4, "delivery_unknown"));
20388
20528
  throw error;
20389
20529
  }
20390
20530
  } finally {
@@ -20470,6 +20610,85 @@ function totalFromContentRange(header) {
20470
20610
  return Number.isFinite(n) && n >= 0 ? n : null;
20471
20611
  }
20472
20612
 
20613
+ // src/channels/discord-progress.ts
20614
+ init_folded_panel();
20615
+ init_process_card_model();
20616
+ init_process_card_render();
20617
+ import { ContainerBuilder, SeparatorBuilder, TextDisplayBuilder } from "@discordjs/builders";
20618
+ import { SeparatorSpacingSize } from "discord-api-types/v10";
20619
+ var SHOWN_STEPS_MAX = 8;
20620
+ var RESULT_LINE_MAX = 100;
20621
+ var SETTLED_TTL_MS = 30 * 60 * 1e3;
20622
+ function buildDiscordProgressContainer(state, accent) {
20623
+ const container = new ContainerBuilder().setAccentColor(accent);
20624
+ const context = state.presentation;
20625
+ const status = context?.statusLabels?.[state.status] ?? STATUS_META[state.status].suffix;
20626
+ container.addTextDisplayComponents(new TextDisplayBuilder().setContent(`**${context?.title ?? state.repoName}** \xB7 ${status}`));
20627
+ container.addSeparatorComponents(new SeparatorBuilder().setSpacing(SeparatorSpacingSize.Small).setDivider(true));
20628
+ const tools = state.rows.filter((row) => row.kind === "tool");
20629
+ const shown = tools.slice(-SHOWN_STEPS_MAX);
20630
+ const hidden = (state.earlierSteps || 0) + tools.length - shown.length;
20631
+ if (hidden > 0) container.addTextDisplayComponents(new TextDisplayBuilder().setContent(`\u22EF \u524D\u9762\u8FD8\u6709 ${hidden} \u6B65`));
20632
+ for (const row of shown) {
20633
+ let content = toolRowTitle(row.name, row.args, row.state);
20634
+ if (row.state !== "run" && row.resultVisible !== false) {
20635
+ content += `
20636
+ \u23BF ${row.state === "err" ? "\u2717 " : ""}${clipCardText(oneLine(row.out.split("\n")[0] || "(\u65E0\u8F93\u51FA)"), RESULT_LINE_MAX)}`;
20637
+ }
20638
+ container.addTextDisplayComponents(new TextDisplayBuilder().setContent(content));
20639
+ }
20640
+ const thought = state.rows.findLast((row) => row.kind === "think");
20641
+ if (thought?.kind === "think") container.addTextDisplayComponents(new TextDisplayBuilder().setContent(thoughtLine(thought.preview)));
20642
+ return container;
20643
+ }
20644
+ var DiscordProgressCards = class {
20645
+ constructor(transport, accent) {
20646
+ this.transport = transport;
20647
+ this.accent = accent;
20648
+ }
20649
+ entries = /* @__PURE__ */ new Map();
20650
+ queues = /* @__PURE__ */ new Map();
20651
+ async sendProgress(target, state) {
20652
+ const container = buildDiscordProgressContainer(state, this.accent);
20653
+ const id3 = await this.transport.send(target, container);
20654
+ this.entries.set(id3, { channelId: target, sent: key3(container) });
20655
+ if (settled(state.status)) this.expire(id3);
20656
+ return id3;
20657
+ }
20658
+ /** 内容与上次发出的一致就不编辑(过程控制器的 5 秒活性桶会空推一轮);同一条消息的编辑按入队顺序串行 */
20659
+ updateProgress(id3, state) {
20660
+ const run = async () => {
20661
+ const entry = this.entries.get(id3);
20662
+ if (!entry) return;
20663
+ const container = buildDiscordProgressContainer(state, this.accent);
20664
+ const next = key3(container);
20665
+ if (next === entry.sent) return;
20666
+ await this.transport.edit(entry.channelId, id3, container);
20667
+ entry.sent = next;
20668
+ if (settled(state.status)) this.expire(id3);
20669
+ };
20670
+ const queued = (this.queues.get(id3) ?? Promise.resolve()).then(run, run);
20671
+ this.queues.set(id3, queued);
20672
+ const forget = () => {
20673
+ if (this.queues.get(id3) === queued) this.queues.delete(id3);
20674
+ };
20675
+ void queued.then(forget, forget);
20676
+ return queued;
20677
+ }
20678
+ async removeProgress(id3) {
20679
+ const entry = this.entries.get(id3);
20680
+ this.entries.delete(id3);
20681
+ if (entry) await this.transport.remove(entry.channelId, id3);
20682
+ }
20683
+ expire(id3) {
20684
+ setTimeout(() => {
20685
+ this.entries.delete(id3);
20686
+ }, SETTLED_TTL_MS).unref?.();
20687
+ }
20688
+ };
20689
+ var key3 = (container) => JSON.stringify(container.toJSON());
20690
+ var settled = (status) => status !== "run" && status !== "wait";
20691
+
20473
20692
  // src/channels/discord.ts
20474
20693
  var DISCORD_MSG_LIMIT = 2e3;
20475
20694
  var DiscordAdapter = class _DiscordAdapter {
@@ -20478,6 +20697,10 @@ var DiscordAdapter = class _DiscordAdapter {
20478
20697
  client;
20479
20698
  config;
20480
20699
  ownsClient;
20700
+ /** 1124:折叠过程卡只在折叠模式下出(没折叠维持逐步显示);编辑型消息的推送节奏 */
20701
+ progressRequiresCollapsed = true;
20702
+ progressThrottleMs = 2500;
20703
+ progressCards;
20481
20704
  messageHandler = null;
20482
20705
  commandHandler = null;
20483
20706
  registeredCommands = [];
@@ -20522,6 +20745,25 @@ var DiscordAdapter = class _DiscordAdapter {
20522
20745
  this.client = new Client(clientOptions);
20523
20746
  this.ownsClient = true;
20524
20747
  }
20748
+ this.progressCards = new DiscordProgressCards({
20749
+ send: async (channelId, container) => {
20750
+ const channel = await this.textChannel(channelId);
20751
+ assertExternalEffectCurrent();
20752
+ const sent = await channel.send({ flags: MessageFlags.IsComponentsV2, components: [container], allowedMentions: { parse: [] } });
20753
+ return sent.id;
20754
+ },
20755
+ edit: async (channelId, messageId, container) => {
20756
+ const channel = await this.textChannel(channelId);
20757
+ const message = channel.messages?.cache?.get(messageId) ?? await channel.messages.fetch(messageId);
20758
+ assertExternalEffectCurrent();
20759
+ await message.edit({ components: [container], allowedMentions: { parse: [] } });
20760
+ },
20761
+ // 删除与 deletePreview 同口径:不过 assertExternalEffectCurrent(删是减法)
20762
+ remove: async (channelId, messageId) => {
20763
+ const channel = await this.textChannel(channelId);
20764
+ await channel.messages.delete(messageId);
20765
+ }
20766
+ }, this.previewColor);
20525
20767
  }
20526
20768
  /** 暴露 discord.js Client(供 VisualTransport 等模块使用) */
20527
20769
  getClient() {
@@ -20893,6 +21135,23 @@ var DiscordAdapter = class _DiscordAdapter {
20893
21135
  } catch {
20894
21136
  }
20895
21137
  }
21138
+ // === 折叠过程卡(1124):Discord 卡片消息,每步带一行结果;没有按钮 ===
21139
+ async textChannel(channelId) {
21140
+ const channel = this.client.channels.cache.get(channelId) ?? await this.client.channels.fetch(channelId);
21141
+ if (!channel?.isTextBased() || !("send" in channel)) {
21142
+ throw new Error(`discord: \u8FC7\u7A0B\u5361: channel ${channelId} not found or not text-based`);
21143
+ }
21144
+ return channel;
21145
+ }
21146
+ async sendProgress(target, state) {
21147
+ return this.progressCards.sendProgress(target, state);
21148
+ }
21149
+ async updateProgress(id3, state) {
21150
+ await this.progressCards.updateProgress(id3, state);
21151
+ }
21152
+ async removeProgress(id3) {
21153
+ await this.progressCards.removeProgress(id3);
21154
+ }
20896
21155
  // === Streaming preview — 对齐 cc-connect Discord 的 SendPreviewStart/UpdateMessage/DeletePreviewMessage ===
20897
21156
  // 对齐 cc-connect platform/discord/progress.go:preview 消息用 Embed(彩色标题栏 + 内容)
20898
21157
  /** Embed 颜色常量 — 对齐 cc-connect discordProgressStateMeta */
@@ -21355,8 +21614,8 @@ var FeishuAdapter = class _FeishuAdapter {
21355
21614
  let durationMs = Math.round(fileBuffer.length / 3);
21356
21615
  try {
21357
21616
  const { execFile: execFile2 } = await import("node:child_process");
21358
- const { promisify: promisify3 } = await import("node:util");
21359
- const execFileAsync2 = promisify3(execFile2);
21617
+ const { promisify: promisify4 } = await import("node:util");
21618
+ const execFileAsync2 = promisify4(execFile2);
21360
21619
  const probe = await execFileAsync2("ffprobe", ["-v", "quiet", "-show_format", "-print_format", "json", attachment.path], { timeout: 1e4 });
21361
21620
  const fmt = JSON.parse(probe.stdout);
21362
21621
  if (fmt?.format?.duration) durationMs = Math.round(parseFloat(fmt.format.duration) * 1e3);
@@ -21451,8 +21710,8 @@ var FeishuAdapter = class _FeishuAdapter {
21451
21710
  return fileKey;
21452
21711
  }
21453
21712
  /** 消息资源 URL(三个下载方法 + Range 预探共用) */
21454
- _resourceUrl(messageId, key2, kind) {
21455
- return `https://open.feishu.cn/open-apis/im/v1/messages/${messageId}/resources/${key2}?type=${kind}`;
21713
+ _resourceUrl(messageId, key4, kind) {
21714
+ return `https://open.feishu.cn/open-apis/im/v1/messages/${messageId}/resources/${key4}?type=${kind}`;
21456
21715
  }
21457
21716
  /** 通过飞书API下载消息中的图片 */
21458
21717
  async _downloadImage(messageId, imageKey, tokenOverride, init) {
@@ -21521,7 +21780,7 @@ var FeishuAdapter = class _FeishuAdapter {
21521
21780
  let totalBytes = 0;
21522
21781
  let token;
21523
21782
  const nameCache = /* @__PURE__ */ new Map();
21524
- const fetchOne = async (msgId, key2, kind, nameHint, idx, notes) => {
21783
+ const fetchOne = async (msgId, key4, kind, nameHint, idx, notes) => {
21525
21784
  if (Date.now() - started > HISTORY_DOWNLOAD_BUDGET_MS) {
21526
21785
  notes.push(budgetNote(1));
21527
21786
  return null;
@@ -21529,7 +21788,7 @@ var FeishuAdapter = class _FeishuAdapter {
21529
21788
  try {
21530
21789
  token ??= await this._getTenantToken();
21531
21790
  try {
21532
- const probe = await fetch(this._resourceUrl(msgId, key2, kind === "image" ? "image" : "file"), {
21791
+ const probe = await fetch(this._resourceUrl(msgId, key4, kind === "image" ? "image" : "file"), {
21533
21792
  headers: { Authorization: `Bearer ${token}`, Range: "bytes=0-0" },
21534
21793
  signal: AbortSignal.timeout(5e3)
21535
21794
  });
@@ -21543,7 +21802,7 @@ var FeishuAdapter = class _FeishuAdapter {
21543
21802
  } catch {
21544
21803
  }
21545
21804
  const dlInit = { signal: AbortSignal.timeout(HISTORY_ATTACH_TIMEOUT_MS) };
21546
- const buf = kind === "image" ? await this._downloadImage(msgId, key2, token, dlInit) : kind === "video" ? await this._downloadVideo(msgId, key2, token, dlInit) : await this._downloadFile(msgId, key2, token, dlInit);
21805
+ const buf = kind === "image" ? await this._downloadImage(msgId, key4, token, dlInit) : kind === "video" ? await this._downloadVideo(msgId, key4, token, dlInit) : await this._downloadFile(msgId, key4, token, dlInit);
21547
21806
  if (buf.length > HISTORY_ATTACH_MAX_BYTES) {
21548
21807
  notes.push(skipNote(nameHint, buf.length));
21549
21808
  return null;
@@ -21593,9 +21852,9 @@ var FeishuAdapter = class _FeishuAdapter {
21593
21852
  if (r?.tag === "text") segs.push(String(r.text ?? ""));
21594
21853
  else if (r?.tag === "img") {
21595
21854
  segs.push("[\u56FE\u7247]");
21596
- const key2 = String(r?.image_key ?? "");
21597
- if (key2) {
21598
- const att = await fetchOne(msgId, key2, "image", `post-${msgId}-${imgIdx}.jpg`, imgIdx, notes);
21855
+ const key4 = String(r?.image_key ?? "");
21856
+ if (key4) {
21857
+ const att = await fetchOne(msgId, key4, "image", `post-${msgId}-${imgIdx}.jpg`, imgIdx, notes);
21599
21858
  if (att) attachments.push(att);
21600
21859
  imgIdx++;
21601
21860
  }
@@ -21604,18 +21863,18 @@ var FeishuAdapter = class _FeishuAdapter {
21604
21863
  content = segs.join("").trim() || "[\u56FE\u6587]";
21605
21864
  } else if (type === "image") {
21606
21865
  content = "[\u56FE\u7247]";
21607
- const key2 = String(body?.image_key ?? "");
21608
- if (key2) {
21609
- const att = await fetchOne(msgId, key2, "image", `img-${msgId}.jpg`, 0, notes);
21866
+ const key4 = String(body?.image_key ?? "");
21867
+ if (key4) {
21868
+ const att = await fetchOne(msgId, key4, "image", `img-${msgId}.jpg`, 0, notes);
21610
21869
  if (att) attachments.push(att);
21611
21870
  }
21612
21871
  } else if (type === "file" || type === "audio" || type === "media") {
21613
21872
  const name0 = String(body?.file_name ?? body?.file_key ?? "file");
21614
21873
  const label = type === "audio" ? "\u8BED\u97F3" : type === "media" ? "\u89C6\u9891" : "\u6587\u4EF6";
21615
21874
  content = `[${label}] ${name0}`;
21616
- const key2 = String(body?.file_key ?? "");
21617
- if (key2) {
21618
- const att = await fetchOne(msgId, key2, type === "media" ? "video" : "file", name0, 0, notes);
21875
+ const key4 = String(body?.file_key ?? "");
21876
+ if (key4) {
21877
+ const att = await fetchOne(msgId, key4, type === "media" ? "video" : "file", name0, 0, notes);
21619
21878
  if (att) attachments.push(att);
21620
21879
  }
21621
21880
  } else if (type === "sticker") {
@@ -22079,8 +22338,8 @@ var FeishuAdapter = class _FeishuAdapter {
22079
22338
  const earlyImageKeys = imageKeys.filter(Boolean);
22080
22339
  if (message.message_type === "image" && !earlyImageKeys.length) {
22081
22340
  try {
22082
- const key2 = JSON.parse(message.content || "{}").image_key;
22083
- if (key2) earlyImageKeys.push(key2);
22341
+ const key4 = JSON.parse(message.content || "{}").image_key;
22342
+ if (key4) earlyImageKeys.push(key4);
22084
22343
  } catch {
22085
22344
  }
22086
22345
  }
@@ -22096,12 +22355,12 @@ var FeishuAdapter = class _FeishuAdapter {
22096
22355
  messageId,
22097
22356
  recvAt: Date.now(),
22098
22357
  metadata: { chatId, chatType, ...parentId ? { parentId } : {} },
22099
- attachments: earlyImageKeys.map((key2) => ({
22358
+ attachments: earlyImageKeys.map((key4) => ({
22100
22359
  url: "",
22101
22360
  filename: "image.png",
22102
22361
  contentType: "image/png",
22103
22362
  size: 0,
22104
- loadBytes: (signal) => this._downloadImage(messageId, key2, void 0, { signal })
22363
+ loadBytes: (signal) => this._downloadImage(messageId, key4, void 0, { signal })
22105
22364
  })),
22106
22365
  prepareContext: async (signal) => {
22107
22366
  signal?.throwIfAborted();
@@ -22187,7 +22446,8 @@ var FeishuAdapter = class _FeishuAdapter {
22187
22446
  }
22188
22447
  }
22189
22448
  if (!cleanContent.trim() && !imageAttachments?.length && !fileAttachment && !videoAttachment && !attachNotes.length) return;
22190
- const senderName = await this._resolveSenderName(senderOpenId);
22449
+ const senderName = this.config?.nameMap?.[senderOpenId] || this._senderNameCache.get(senderOpenId)?.name || senderOpenId.slice(0, 8);
22450
+ void this._resolveSenderName(senderOpenId);
22191
22451
  const inbound = {
22192
22452
  // 1012 翀哥实测:引用原文和新正文挤一行会混——引用独占一行,正文(含附件留痕)另起一行。
22193
22453
  content: [
@@ -22295,8 +22555,8 @@ var FeishuAdapter = class _FeishuAdapter {
22295
22555
  } else if (block.tag === "at") {
22296
22556
  lines.push(block.user_name ? `@${block.user_name}` : "@user");
22297
22557
  } else if (block.tag === "img") {
22298
- const key2 = block.image_key;
22299
- if (key2) imageKeys.push(key2);
22558
+ const key4 = block.image_key;
22559
+ if (key4) imageKeys.push(key4);
22300
22560
  }
22301
22561
  }
22302
22562
  lines.push("\n");
@@ -22431,6 +22691,11 @@ function hasWechatPriorContact(stateDir, accountId, userId) {
22431
22691
  }
22432
22692
  }
22433
22693
 
22694
+ // src/auth/client.ts
22695
+ var DEFAULT_AUTH_BROKER = "https://auth.engine7.ai/auth/";
22696
+ var LEGACY_AUTH_BROKERS = ["https://www.twinsun.top/auth/"];
22697
+ var OFFICIAL_AUTH_BROKERS = /* @__PURE__ */ new Set([DEFAULT_AUTH_BROKER, ...LEGACY_AUTH_BROKERS]);
22698
+
22434
22699
  // src/config/features.ts
22435
22700
  init_live();
22436
22701
 
@@ -22499,13 +22764,13 @@ function pkcs7Unpad(data) {
22499
22764
  if (pad < 1 || pad > 16 || pad > data.length) return data;
22500
22765
  return data.subarray(0, data.length - pad);
22501
22766
  }
22502
- function aesEncrypt(plaintext, key2) {
22503
- const c = crypto2.createCipheriv("aes-128-ecb", key2, null);
22767
+ function aesEncrypt(plaintext, key4) {
22768
+ const c = crypto2.createCipheriv("aes-128-ecb", key4, null);
22504
22769
  c.setAutoPadding(false);
22505
22770
  return Buffer.concat([c.update(pkcs7Pad(plaintext)), c.final()]);
22506
22771
  }
22507
- function aesDecrypt(ciphertext, key2) {
22508
- const d = crypto2.createDecipheriv("aes-128-ecb", key2, null);
22772
+ function aesDecrypt(ciphertext, key4) {
22773
+ const d = crypto2.createDecipheriv("aes-128-ecb", key4, null);
22509
22774
  d.setAutoPadding(false);
22510
22775
  return pkcs7Unpad(Buffer.concat([d.update(ciphertext), d.final()]));
22511
22776
  }
@@ -22764,8 +23029,8 @@ var ContextTokenStore = class {
22764
23029
  this.save();
22765
23030
  }
22766
23031
  delete(a, p) {
22767
- const key2 = p !== void 0 ? this.k(a, p) : a;
22768
- this.cache.delete(key2);
23032
+ const key4 = p !== void 0 ? this.k(a, p) : a;
23033
+ this.cache.delete(key4);
22769
23034
  this.save();
22770
23035
  }
22771
23036
  };
@@ -23326,12 +23591,12 @@ import { WebSocketServer, WebSocket } from "ws";
23326
23591
  init_live();
23327
23592
  init_well_formed();
23328
23593
  import { execFile } from "node:child_process";
23329
- import { promisify as promisify2 } from "node:util";
23594
+ import { promisify as promisify3 } from "node:util";
23330
23595
  init_voice_chat_tts_daemon();
23331
23596
  import * as path14 from "node:path";
23332
23597
  import * as os6 from "node:os";
23333
23598
  import net2 from "net";
23334
- var execFileAsync = promisify2(execFile);
23599
+ var execFileAsync = promisify3(execFile);
23335
23600
  var VOICE_DIR = path14.join(os6.tmpdir(), "engine-voice");
23336
23601
  async function ttsCosyvoiceWorker(text2, cfg, onChunk) {
23337
23602
  if (!isDaemonReady()) {
@@ -24297,10 +24562,10 @@ var PreviewEditThrottle = class {
24297
24562
  }
24298
24563
  st = /* @__PURE__ */ new Map();
24299
24564
  /** 提交一次编辑;返回的 promise 在"该内容(或其后覆盖它的更新内容)真实落盘"后 settle,失败 reject */
24300
- submit(key2, req, run) {
24301
- const s = this.st.get(key2) ?? { lastEditAt: -Infinity, timer: null, pending: null, pendingRun: null, waiters: [] };
24565
+ submit(key4, req, run) {
24566
+ const s = this.st.get(key4) ?? { lastEditAt: -Infinity, timer: null, pending: null, pendingRun: null, waiters: [] };
24302
24567
  const guardedRun = AsyncLocalStorage6.bind(run);
24303
- this.st.set(key2, s);
24568
+ this.st.set(key4, s);
24304
24569
  return new Promise((resolve12, reject) => {
24305
24570
  const waiter = { resolve: resolve12, reject };
24306
24571
  if (s.timer) {
@@ -24310,7 +24575,7 @@ var PreviewEditThrottle = class {
24310
24575
  return;
24311
24576
  }
24312
24577
  if (this.now() - s.lastEditAt >= this.minIntervalMs) {
24313
- this.fire(key2, req, [waiter], guardedRun);
24578
+ this.fire(key4, req, [waiter], guardedRun);
24314
24579
  return;
24315
24580
  }
24316
24581
  s.pending = req;
@@ -24324,12 +24589,12 @@ var PreviewEditThrottle = class {
24324
24589
  s.pending = null;
24325
24590
  s.pendingRun = null;
24326
24591
  s.waiters = [];
24327
- if (p && latestRun) this.fire(key2, p, w, latestRun);
24592
+ if (p && latestRun) this.fire(key4, p, w, latestRun);
24328
24593
  }, this.minIntervalMs - (this.now() - s.lastEditAt));
24329
24594
  });
24330
24595
  }
24331
- fire(key2, req, waiters, run) {
24332
- const s = this.st.get(key2);
24596
+ fire(key4, req, waiters, run) {
24597
+ const s = this.st.get(key4);
24333
24598
  if (s) s.lastEditAt = this.now();
24334
24599
  Promise.resolve().then(() => run(req)).then(
24335
24600
  () => {
@@ -24564,16 +24829,16 @@ var AlbumBuffer = class {
24564
24829
  }
24565
24830
  groups = /* @__PURE__ */ new Map();
24566
24831
  add(item) {
24567
- const key2 = item.mediaGroupId;
24568
- const g = this.groups.get(key2) ?? { items: [], lastAt: 0 };
24832
+ const key4 = item.mediaGroupId;
24833
+ const g = this.groups.get(key4) ?? { items: [], lastAt: 0 };
24569
24834
  g.items.push(item);
24570
24835
  g.lastAt = this.now();
24571
- this.groups.set(key2, g);
24836
+ this.groups.set(key4, g);
24572
24837
  }
24573
24838
  tick() {
24574
- for (const [key2, g] of this.groups) {
24839
+ for (const [key4, g] of this.groups) {
24575
24840
  if (this.now() - g.lastAt < this.timeoutMs) continue;
24576
- this.groups.delete(key2);
24841
+ this.groups.delete(key4);
24577
24842
  g.items.sort((a, b) => Number(a.inbound.messageId) - Number(b.inbound.messageId));
24578
24843
  this.flush(g.items);
24579
24844
  }
@@ -25013,9 +25278,9 @@ var TelegramAdapter = class {
25013
25278
  */
25014
25279
  async editPreview(handle, content, agentName, isFinal) {
25015
25280
  const chatId = Number(handle.channelId);
25016
- const key2 = `${handle.channelId}:${handle.messageId}`;
25281
+ const key4 = `${handle.channelId}:${handle.messageId}`;
25017
25282
  try {
25018
- await this.editThrottle.submit(key2, { content, agentName, isFinal: !!isFinal }, async (r) => {
25283
+ await this.editThrottle.submit(key4, { content, agentName, isFinal: !!isFinal }, async (r) => {
25019
25284
  await this.enqueueSend(chatId, async () => {
25020
25285
  if (r.isFinal) {
25021
25286
  const chunks = splitTextChunks(r.content, 4e3);
@@ -25133,11 +25398,11 @@ function inboundGate(inp) {
25133
25398
  if (!inp.hasUserContent) {
25134
25399
  return { pass: false, gate: 4, reason: "\u65E0 user \u53EF\u89C1\u5185\u5BB9\uFF08receipt/protocol \u7A7A\u6D88\u606F\uFF09" };
25135
25400
  }
25136
- const key2 = `${inp.jid}:${inp.messageId}`;
25137
- if (inp.seenKeys.has(key2)) {
25138
- return { pass: false, gate: 5, reason: `\u91CD\u590D\u6D88\u606F: ${key2}` };
25401
+ const key4 = `${inp.jid}:${inp.messageId}`;
25402
+ if (inp.seenKeys.has(key4)) {
25403
+ return { pass: false, gate: 5, reason: `\u91CD\u590D\u6D88\u606F: ${key4}` };
25139
25404
  }
25140
- inp.seenKeys.add(key2);
25405
+ inp.seenKeys.add(key4);
25141
25406
  return { pass: true };
25142
25407
  }
25143
25408
  var WRAPPERS = [
@@ -26330,7 +26595,7 @@ ${archiveNotice(resultArchive)}`, resultArchive };
26330
26595
 
26331
26596
  // src/models/provider-errors.ts
26332
26597
  function isQuotaExhaustedError(message) {
26333
- return /\b(?:insufficient_quota|billing_hard_limit_reached|credit_balance_too_low)\b|exceeded your current quota|credit balance is too low|insufficient (?:credits|balance)|Token Plan[^\n]{0,60}(?:用量上限|额度(?:已)?用尽)/i.test(message);
26598
+ return /\b(?:insufficient_quota|billing_hard_limit_reached|credit_balance_too_low|free_pool_exhausted|free_quota_exhausted|vip_quota_exhausted|quota_exhausted)\b|subscription quota insufficient|订阅额度不足|exceeded your current quota|credit balance is too low|insufficient (?:credits|balance)|Token Plan[^\n]{0,60}(?:用量上限|额度(?:已)?用尽)/i.test(message);
26334
26599
  }
26335
26600
 
26336
26601
  // src/core/query.ts
@@ -26472,8 +26737,8 @@ function withTravelEventContext(context, run) {
26472
26737
  }
26473
26738
  function travelEventPermit(context) {
26474
26739
  const permit = context.permit(), original = context.originalPermit;
26475
- for (const key2 of ["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"]) {
26476
- if (permit[key2] !== original[key2]) throw new Error("TRAVEL_GATEWAY_STALE_CONTEXT");
26740
+ for (const key4 of ["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"]) {
26741
+ if (permit[key4] !== original[key4]) throw new Error("TRAVEL_GATEWAY_STALE_CONTEXT");
26477
26742
  }
26478
26743
  if (context.complete) throw new Error("TRAVEL_GATEWAY_EVENT_COMPLETED");
26479
26744
  return permit;
@@ -26618,7 +26883,10 @@ function isCpuModeHook(command) {
26618
26883
  return (tokens[0] === process.execPath || /^(?:node|python[\d.]*|py)(?:\.exe)?$/i.test(executable)) && /^emotion(?:_state_machine\.(?:mjs|py)|-hook-gate\.js)$/i.test(script);
26619
26884
  }
26620
26885
  function cpuModeHookOutput(command, input, workspace) {
26621
- if (!isCpuModeHook(command) || !["emotion", "work"].includes(input.cpu_router_mode)) return null;
26886
+ return isCpuModeHook(command) ? cpuModeOutput(input, workspace) : null;
26887
+ }
26888
+ function cpuModeOutput(input, workspace) {
26889
+ if (!["emotion", "work"].includes(input.cpu_router_mode)) return null;
26622
26890
  const text2 = typeof input.prompt === "string" ? input.prompt : "";
26623
26891
  const internal = ["heartbeat", "cron", "system", "inner-voice", "mem7"];
26624
26892
  const marks = ["\u3010", "[\u5B9A\u65F6", "\u5F53\u524D\u65F6\u95F4\uFF1A", "[inner-voice]", "<calendar-notification>", "<nudge-notification>", "<task-notification>", "<system-reminder>"];
@@ -26869,10 +27137,10 @@ async function executeOneHook(hook, hookEvent, hookName, hookInput, toolUseID, s
26869
27137
  hook
26870
27138
  };
26871
27139
  }
26872
- const cpuModeOutput = hookEvent === "UserPromptSubmit" ? cpuModeHookOutput(hook.command, hookInput, ctx.workspace) : null;
26873
- if (cpuModeOutput) {
26874
- const processed = processHookJSONOutput({ json: cpuModeOutput, command: hook.command, hookEvent, durationMs: Date.now() - startMs });
26875
- console.log(`[cpu-router] mode-hook=${hookTimingLabel(hook, 0)} mode=${cpuModeOutput._mode ?? "skip"}`);
27140
+ const cpuModeOutput2 = hookEvent === "UserPromptSubmit" ? cpuModeHookOutput(hook.command, hookInput, ctx.workspace) : null;
27141
+ if (cpuModeOutput2) {
27142
+ const processed = processHookJSONOutput({ json: cpuModeOutput2, command: hook.command, hookEvent, durationMs: Date.now() - startMs });
27143
+ console.log(`[cpu-router] mode-hook=${hookTimingLabel(hook, 0)} mode=${cpuModeOutput2._mode ?? "skip"}`);
26876
27144
  return { ...processed, outcome: "success", hook };
26877
27145
  }
26878
27146
  const jsonInput = JSON.stringify(hookInput);
@@ -27001,10 +27269,10 @@ function matchesPromptHookCondition(hook, input) {
27001
27269
  if (hook.when === void 0) return true;
27002
27270
  const when = hook.when;
27003
27271
  if (!when || typeof when !== "object" || Array.isArray(when) || input.hook_event_name !== "UserPromptSubmit") return false;
27004
- if (Object.keys(when).some((key2) => !["channel", "channelType", "source", "excludeSenderIds"].includes(key2))) return false;
27272
+ if (Object.keys(when).some((key4) => !["channel", "channelType", "source", "excludeSenderIds"].includes(key4))) return false;
27005
27273
  if (!input.prompt.trim()) return false;
27006
- for (const [key2, actual] of [["channel", input.channel], ["channelType", input.channel_type], ["source", input.source]]) {
27007
- if (when[key2] !== void 0 && (typeof when[key2] !== "string" || when[key2] !== actual)) return false;
27274
+ for (const [key4, actual] of [["channel", input.channel], ["channelType", input.channel_type], ["source", input.source]]) {
27275
+ if (when[key4] !== void 0 && (typeof when[key4] !== "string" || when[key4] !== actual)) return false;
27008
27276
  }
27009
27277
  if (when.excludeSenderIds !== void 0) {
27010
27278
  if (!Array.isArray(when.excludeSenderIds) || when.excludeSenderIds.some((id3) => typeof id3 !== "string")) return false;
@@ -27142,6 +27410,7 @@ async function executeStopHooks(ctx, signal, lastAssistantMessage) {
27142
27410
  cwd: ctx.cwd,
27143
27411
  stop_hook_active: false,
27144
27412
  last_assistant_message: lastAssistantMessage,
27413
+ turn_evidence: ctx.stopTurnEvidence,
27145
27414
  channel: ctx.channel,
27146
27415
  // 让 callback hook 能判断来源
27147
27416
  channelTarget: ctx.channelTarget,
@@ -27384,13 +27653,17 @@ init_read_guard();
27384
27653
  var OnDemandRecall = class {
27385
27654
  used = /* @__PURE__ */ new Set();
27386
27655
  cache = /* @__PURE__ */ new Map();
27656
+ /** Actual tool mutations invalidate this turn's snapshot without polling SQLite. */
27657
+ invalidate() {
27658
+ this.cache.clear();
27659
+ }
27387
27660
  // 1024 翀哥裁决:6 秒墙全撤。它界的是返回大小不是时延来源(检索耗时在 embedding/bm25/rerank),
27388
27661
  // 底层各有各的界(SQL overlay 死线 12s、embedding HTTP 30s、rerank 1500ms 竞速),1+1 配额防循环。
27389
27662
  // 这层墙当天制造了两次 timeout 假阴性 + 额度连坐,没拦住任何真问题。
27390
27663
  constructor(keywordAlreadySearched = false) {
27391
27664
  if (keywordAlreadySearched) this.used.add("keyword");
27392
27665
  }
27393
- async search(binding, args, captureGuard, run, signal) {
27666
+ async search(binding, args, run, signal) {
27394
27667
  const status = (value, reason) => JSON.stringify({ historySearch: { status: value, reason } });
27395
27668
  if (signal?.aborted) return status("aborted", "\u672C\u8F6E\u5DF2\u53D6\u6D88\u3002");
27396
27669
  if (args.mode === "agentic") return status("unavailable", "\u60C5\u611F\u8F6E\u8BF7\u7528 keyword \u6216 hybrid \u6709\u754C\u8865\u67E5\u3002");
@@ -27402,17 +27675,12 @@ var OnDemandRecall = class {
27402
27675
  };
27403
27676
  for (const passthrough of ["known_at", "known_at_revision", "valid_at", "entity_ref", "after_receipt", "session_id"])
27404
27677
  if (args[passthrough] !== void 0) bounded[passthrough] = args[passthrough];
27405
- const key2 = JSON.stringify([binding, Object.entries(bounded).sort(([a], [b]) => a.localeCompare(b))]);
27406
- const cached2 = this.cache.get(key2);
27678
+ const key4 = JSON.stringify([binding, Object.entries(bounded).sort(([a], [b]) => a.localeCompare(b))]);
27679
+ const cached2 = this.cache.get(key4);
27407
27680
  if (cached2) {
27408
- const result2 = await cached2.result;
27681
+ const result2 = await cached2;
27409
27682
  if (signal?.aborted) return status("aborted", "\u672C\u8F6E\u5DF2\u53D6\u6D88\u3002");
27410
- try {
27411
- cached2.assertCurrent();
27412
- return result2;
27413
- } catch {
27414
- return status("stale", "\u6765\u6E90\u5DF2\u53D8\u5316\uFF0C\u65E7\u7ED3\u679C\u4E0D\u53EF\u590D\u7528\uFF1B\u8BF7\u4F9D\u636E\u5F53\u524D\u6750\u6599\u6216\u6F84\u6E05\u3002");
27415
- }
27683
+ return result2;
27416
27684
  }
27417
27685
  const kind = bounded.view === "current" || bounded.mode === "keyword" ? "keyword" : "semantic";
27418
27686
  if (kind === "keyword" && this.used.has("keyword") && !this.used.has("semantic")) {
@@ -27421,7 +27689,6 @@ var OnDemandRecall = class {
27421
27689
  if (this.used.has(kind)) {
27422
27690
  return status("budget_exhausted", "\u672C\u8F6E\u5DF2\u7528\u5B8C\u8BE5\u7C7B\u8865\u67E5\uFF1B\u4E0D\u8981\u6362\u8BCD\u53CD\u590D\u67E5\uFF0C\u53EF\u8BE2\u95EE\u7EBF\u7D22\u3002");
27423
27691
  }
27424
- const assertCurrent = captureGuard();
27425
27692
  this.used.add(kind);
27426
27693
  if (kind === "semantic") this.used.add("keyword");
27427
27694
  const controller = new AbortController();
@@ -27451,7 +27718,7 @@ ${error.stack.split("\n").slice(0, 6).join("\n")}` : ""
27451
27718
  controller.abort();
27452
27719
  }
27453
27720
  })();
27454
- this.cache.set(key2, { result, assertCurrent });
27721
+ this.cache.set(key4, result);
27455
27722
  return result;
27456
27723
  }
27457
27724
  };
@@ -27512,13 +27779,13 @@ async function materializeImageMessages(messages, store, signal, maxBase64Bytes
27512
27779
  continue;
27513
27780
  }
27514
27781
  if (!store) throw new Error("Image asset store is required to materialize image refs");
27515
- const key2 = JSON.stringify([block.image.sha256, block.image.bytes, block.image.mediaType]);
27516
- if (!cache.has(key2)) cache.set(key2, store.materialize(block.image).catch((error) => {
27782
+ const key4 = JSON.stringify([block.image.sha256, block.image.bytes, block.image.mediaType]);
27783
+ if (!cache.has(key4)) cache.set(key4, store.materialize(block.image).catch((error) => {
27517
27784
  if (strict) throw error;
27518
27785
  console.warn(`[image-assets] \u5386\u53F2\u56FE\u7247\u4E0D\u53EF\u7528\uFF0C\u964D\u7EA7\u4E3A\u5360\u4F4D\uFF08sha256=${block.image.sha256.slice(0, 12)}\uFF09\uFF1A${error instanceof Error ? error.message : String(error)}`);
27519
27786
  return null;
27520
27787
  }));
27521
- content.push(await cache.get(key2) ?? { type: "text", text: "[\u56FE\u7247\u6587\u4EF6\u5DF2\u4E0D\u5728\u672C\u673A\uFF0C\u5185\u5BB9\u4E0D\u53EF\u89C1]" });
27788
+ content.push(await cache.get(key4) ?? { type: "text", text: "[\u56FE\u7247\u6587\u4EF6\u5DF2\u4E0D\u5728\u672C\u673A\uFF0C\u5185\u5BB9\u4E0D\u53EF\u89C1]" });
27522
27789
  signal?.throwIfAborted();
27523
27790
  }
27524
27791
  output.push({ ...message, content });
@@ -27578,8 +27845,8 @@ var MAX_PENDING_BYTES = 512 * 1024;
27578
27845
  var SteerMailbox = class {
27579
27846
  constructor(stateDir, sessionId) {
27580
27847
  this.sessionId = sessionId;
27581
- const key2 = createHash31("sha256").update(sessionId).digest("hex");
27582
- this.path = path23.join(stateDir, "steer", `${key2}.json`);
27848
+ const key4 = createHash31("sha256").update(sessionId).digest("hex");
27849
+ this.path = path23.join(stateDir, "steer", `${key4}.json`);
27583
27850
  }
27584
27851
  path;
27585
27852
  list() {
@@ -27920,9 +28187,9 @@ function smartCompressToolResult(content, essentialFields, sizeLimit) {
27920
28187
  if (typeof item === "object" && item !== null && !Array.isArray(item)) {
27921
28188
  const extracted = {};
27922
28189
  if (fieldSet) {
27923
- for (const key2 of essentialFields) {
27924
- if (key2 in item) {
27925
- extracted[key2] = item[key2];
28190
+ for (const key4 of essentialFields) {
28191
+ if (key4 in item) {
28192
+ extracted[key4] = item[key4];
27926
28193
  }
27927
28194
  }
27928
28195
  } else {
@@ -29294,7 +29561,7 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
29294
29561
  outputHandle.close().catch(() => {
29295
29562
  });
29296
29563
  let aborted = false;
29297
- let settled = false;
29564
+ let settled2 = false;
29298
29565
  const cleanup = () => {
29299
29566
  clearTimeout(timer);
29300
29567
  signal?.removeEventListener("abort", onAbort);
@@ -29303,8 +29570,8 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
29303
29570
  child.removeListener("error", onError);
29304
29571
  };
29305
29572
  const done = async (code, error) => {
29306
- if (settled) return;
29307
- settled = true;
29573
+ if (settled2) return;
29574
+ settled2 = true;
29308
29575
  cleanup();
29309
29576
  let output = "";
29310
29577
  let truncated = false;
@@ -29338,12 +29605,12 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
29338
29605
  void done(1, error.message);
29339
29606
  };
29340
29607
  const onAbort = () => {
29341
- if (settled || signal?.reason === "interrupt") return;
29608
+ if (settled2 || signal?.reason === "interrupt") return;
29342
29609
  aborted = true;
29343
29610
  killChild(child);
29344
29611
  };
29345
29612
  const onYield = () => {
29346
- if (settled) return;
29613
+ if (settled2) return;
29347
29614
  if (child.exitCode !== null || child.signalCode !== null) {
29348
29615
  void done(child.exitCode);
29349
29616
  return;
@@ -29360,12 +29627,12 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
29360
29627
  channelTarget: ctx.channelTarget ?? "",
29361
29628
  queryAbortSignal: ctx.queryAbortSignal ?? signal
29362
29629
  });
29363
- settled = true;
29630
+ settled2 = true;
29364
29631
  cleanup();
29365
29632
  resolve12({ content: `Waiting yielded for new user input. Command running in background with ID: ${task.id}. Output is being written to: ${task.outputFile}. Use TaskOutput or Read to observe it; do not restart the command.` });
29366
29633
  };
29367
29634
  const timer = setTimeout(() => {
29368
- if (!settled) {
29635
+ if (!settled2) {
29369
29636
  aborted = true;
29370
29637
  killChild(child);
29371
29638
  }
@@ -29408,17 +29675,17 @@ function createNotificationStateReader() {
29408
29675
  const databases = /* @__PURE__ */ new Map();
29409
29676
  const checkers = /* @__PURE__ */ new Map();
29410
29677
  const open3 = (path35) => {
29411
- const key2 = resolve8(path35);
29412
- let db2 = databases.get(key2);
29678
+ const key4 = resolve8(path35);
29679
+ let db2 = databases.get(key4);
29413
29680
  if (!db2) {
29414
- db2 = new DatabaseSync11(key2, { readOnly: true });
29681
+ db2 = new DatabaseSync11(key4, { readOnly: true });
29415
29682
  try {
29416
29683
  db2.exec("BEGIN");
29417
29684
  } catch (error) {
29418
29685
  db2.close();
29419
29686
  throw error;
29420
29687
  }
29421
- databases.set(key2, db2);
29688
+ databases.set(key4, db2);
29422
29689
  }
29423
29690
  return db2;
29424
29691
  };
@@ -30279,6 +30546,7 @@ var QueryEngine = class _QueryEngine {
30279
30546
  const mailbox = this.steerMailbox;
30280
30547
  this.attachmentScopeId = perTurnOptions?.attachmentScopeId;
30281
30548
  const queryId = this.steerQueryId;
30549
+ const hasPendingUserInput = () => this.pendingSteers.some((input) => !input.attachment);
30282
30550
  this.steerHistoryIds = new Set(messages.flatMap((m) => "steerInput" in m && m.steerInput ? [m.steerInput.id] : "attachment" in m ? [m.uuid] : []));
30283
30551
  try {
30284
30552
  for (const input of mailbox?.pending(this.steerRoute ?? void 0) ?? []) {
@@ -30312,6 +30580,13 @@ var QueryEngine = class _QueryEngine {
30312
30580
  const activeSystemStable = perTurnSystemStable || this.resolveOpt(this.options.systemStable) || this.resolveOpt(this.options.systemPrompt);
30313
30581
  for (const m of messages) if ("role" in m && hasMedia(m) && !m.imageInput) m.imageInput = { id: randomUUID16(), observed: hasImage(m) };
30314
30582
  let currentMessages = [...messages];
30583
+ const stopUserMessages = [];
30584
+ const stopToolResults = [];
30585
+ const collectStopEvidence = !this.options.skipStopHook && !perTurnEmotion;
30586
+ const currentUser = collectStopEvidence ? messages.findLast((m) => "role" in m && m.role === "user") : void 0;
30587
+ if (currentUser && "role" in currentUser) {
30588
+ stopUserMessages.push(currentUser.memoryOriginalText ?? (typeof currentUser.content === "string" ? currentUser.content : currentUser.content.filter((b) => b.type === "text").map((b) => b.text).join("\n")));
30589
+ }
30315
30590
  const oldGatePattern = /^Tool "([^"]+)" is permanently unavailable in this channel\. Do NOT retry it or any other tool — answer the user directly in plain speech now\.$/;
30316
30591
  const historicalGateTools = new Set(currentMessages.flatMap((m) => {
30317
30592
  if (!("role" in m) || m.role !== "tool" || typeof m.content !== "string") return [];
@@ -30390,6 +30665,7 @@ var QueryEngine = class _QueryEngine {
30390
30665
  };
30391
30666
  let turnCount = 0;
30392
30667
  let recallContinuation = false;
30668
+ const stopReplies = [];
30393
30669
  let toolCalls = [];
30394
30670
  let streamRetries = 0;
30395
30671
  let maxTokensOverride = null;
@@ -30446,6 +30722,7 @@ var QueryEngine = class _QueryEngine {
30446
30722
  }
30447
30723
  const steerMsg = buildSteerMessage(input);
30448
30724
  currentMessages.push(steerMsg);
30725
+ if (collectStopEvidence) stopUserMessages.push(input.originalText ?? input.text);
30449
30726
  this.steerHistoryIds.add(input.id);
30450
30727
  steerConsumedThisTurn = true;
30451
30728
  yield {
@@ -30735,7 +31012,7 @@ ${hint}` : [...current2.content, { type: "text", text: hint }] };
30735
31012
  const fullSystemDynamic = deferredHint && perTurnSystemDynamic ? `${deferredHint}
30736
31013
 
30737
31014
  ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
30738
- if (!this.options.agentLabel || this.options.agentLabel === "main") {
31015
+ if (process.env.ENGINE_DUMP_REQUEST === "1" && (!this.options.agentLabel || this.options.agentLabel === "main")) {
30739
31016
  try {
30740
31017
  const ws = process.env.ENGINE7_WORKSPACE;
30741
31018
  if (ws) {
@@ -30957,20 +31234,22 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
30957
31234
  if (toolCalls.length === 0) {
30958
31235
  const carryReply = () => {
30959
31236
  if (!this.pendingSteers.some((input) => input.attachment)) return null;
31237
+ const replyId = randomUUID16();
30960
31238
  const reply = msg.assistant(textContent);
30961
31239
  if (turnThinking) reply.reasoning_content = turnThinking;
30962
31240
  if (turnThinkingSig) reply.thinking_signature = turnThinkingSig;
30963
31241
  if (turnResponsesReasoning) reply.responses_reasoning = turnResponsesReasoning;
30964
31242
  currentMessages.push(reply);
30965
- finalText = textContent;
31243
+ finalText = "";
31244
+ if (collectStopEvidence) stopReplies.push(textContent);
30966
31245
  recallContinuation = true;
30967
31246
  turnThinking = turnThinkingSig = turnResponsesReasoning = "";
30968
- return { type: "history", messages: [reply] };
31247
+ return [{ type: "history", messages: [reply], replyId }, { type: "reply", content: textContent, replyId }];
30969
31248
  };
30970
31249
  if (responseStopReason === "max_tokens" || responseStopReason === "length") {
30971
31250
  if (this.pendingSteers.length > 0) {
30972
31251
  const carried = carryReply();
30973
- if (carried) yield carried;
31252
+ if (carried) yield* carried;
30974
31253
  continue;
30975
31254
  }
30976
31255
  finalText = textContent;
@@ -30980,7 +31259,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
30980
31259
  if (this.options.skipStopHook || perTurnEmotion) {
30981
31260
  if (this.pendingSteers.length > 0) {
30982
31261
  const carried = carryReply();
30983
- if (carried) yield carried;
31262
+ if (carried) yield* carried;
30984
31263
  continue;
30985
31264
  }
30986
31265
  finalText = textContent;
@@ -30997,9 +31276,14 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
30997
31276
  // 'group' | 'dm',Stop hook 用来判断是否跳过 group
30998
31277
  cwd: context?.workspace || "",
30999
31278
  source: typeof context?.source === "string" ? context.source : "",
31000
- executionContext: context?.executionContext
31279
+ executionContext: context?.executionContext,
31280
+ stopTurnEvidence: { userMessages: stopUserMessages, toolResults: stopToolResults }
31001
31281
  };
31002
- const stopResult = await executeStopHooks(stopCtx, ac.signal, textContent);
31282
+ const stopResult = await executeStopHooks(
31283
+ stopCtx,
31284
+ ac.signal,
31285
+ stopReplies.length ? [...stopReplies, textContent].join("\n\n") : textContent
31286
+ );
31003
31287
  if (stopResult.preventContinuation) {
31004
31288
  console.log(`[hook] Stop blocked: ${stopResult.stopReason || "no reason"}`);
31005
31289
  if (stopResult.additionalContexts?.length) {
@@ -31014,7 +31298,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31014
31298
  }
31015
31299
  if (this.pendingSteers.length > 0) {
31016
31300
  const carried = carryReply();
31017
- if (carried) yield carried;
31301
+ if (carried) yield* carried;
31018
31302
  continue;
31019
31303
  }
31020
31304
  finalText = textContent;
@@ -31094,6 +31378,12 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31094
31378
  turnResponsesReasoning = "";
31095
31379
  currentMessages.push(gateAssistant);
31096
31380
  currentMessages.push(...blockResults);
31381
+ if (collectStopEvidence) for (let i = 0; i < toolCalls.length; i++) stopToolResults.push({
31382
+ tool: toolCalls[i].function.name,
31383
+ toolCallId: toolCalls[i].id,
31384
+ summary: String(blockResults[i].content),
31385
+ isError: true
31386
+ });
31097
31387
  for (const g of gatedCalls) {
31098
31388
  yield { type: "tool_result", tool: g.call.function?.name, tool_call_id: g.call.id, summary: g.text.slice(0, 200), isError: true };
31099
31389
  }
@@ -31114,7 +31404,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31114
31404
  try {
31115
31405
  this.phase = "tools";
31116
31406
  this.toolYield = new AbortController();
31117
- if (this.pendingSteers.length) this.toolYield.abort("steer");
31407
+ if (hasPendingUserInput()) this.toolYield.abort("steer");
31118
31408
  toolCtx.yieldSignal = this.toolYield.signal;
31119
31409
  toolRes = await executeTools(toolCalls, ac.signal, { ...toolCtx, toolResultHistory: currentMessages });
31120
31410
  } finally {
@@ -31123,6 +31413,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31123
31413
  if (vcDelivery) await vcDelivery;
31124
31414
  }
31125
31415
  const { messages: toolResults, summaries } = toolRes;
31416
+ if (collectStopEvidence) stopToolResults.push(...summaries);
31126
31417
  for (const s of summaries) {
31127
31418
  try {
31128
31419
  const postResult = await executePostToolUseHooks(s.tool, {}, s.summary, hookCtx, ac.signal);
@@ -31224,7 +31515,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31224
31515
  this.toolYield = null;
31225
31516
  this.phase = "idle";
31226
31517
  this.loopAlive = false;
31227
- if (this.pendingSteers.length > 0 && completionReason !== "aborted") {
31518
+ if (hasPendingUserInput() && completionReason !== "aborted") {
31228
31519
  console.warn(`${this.logPrefix} [steer] ${this.pendingSteers.length} pending input(s) retained for same-route recovery (completionReason=${completionReason ?? "completed"})`);
31229
31520
  }
31230
31521
  this.pendingSteers.length = 0;
@@ -31349,7 +31640,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31349
31640
  }
31350
31641
  }
31351
31642
  this.pendingSteers.push(receipt.input);
31352
- this.toolYield?.abort("steer");
31643
+ if (!receipt.input.attachment) this.toolYield?.abort("steer");
31353
31644
  if (opts.mode === "queue") {
31354
31645
  console.log(`${this.logPrefix} Steer queued (${this.pendingSteers.length} pending \u2014 next turn, no interrupt)`);
31355
31646
  return true;
@@ -31469,8 +31760,8 @@ function defaultWriteMemoryNote(workspace) {
31469
31760
  }
31470
31761
  function makeSubmitToMain(engineDeps) {
31471
31762
  return (text2) => {
31472
- const sessions = engineDeps.deps?.sessions;
31473
- const mainSessionId = sessions?.getSessionId?.("scope:main");
31763
+ const sessions2 = engineDeps.deps?.sessions;
31764
+ const mainSessionId = sessions2?.getSessionId?.("scope:main");
31474
31765
  if (!mainSessionId) {
31475
31766
  console.warn("[whatsapp/patrol] \u65E0\u4E3B session\uFF08scope:main \u672A\u5EFA\u7ACB\uFF09\uFF0C\u26A0\uFE0F \u5347\u7EA7\u6295\u9012\u4E22\u5F03");
31476
31767
  return;
@@ -31503,10 +31794,10 @@ function makeReadOnlyAgentRunner(engineDeps) {
31503
31794
  });
31504
31795
  const sessionId = base.sessions.getOrCreateSessionId(PATROL_SESSION_KEY);
31505
31796
  return new Promise((resolve12, reject) => {
31506
- let settled = false;
31797
+ let settled2 = false;
31507
31798
  const timeout = setTimeout(() => {
31508
- if (settled) return;
31509
- settled = true;
31799
+ if (settled2) return;
31800
+ settled2 = true;
31510
31801
  reject(new Error(`wa-patrol \u5DE1\u68C0\u8D85\u65F6\uFF08${PATROL_TIMEOUT_MS / 6e4}min\uFF09\u2014\u2014\u72B6\u6001\u4E0D\u63A8\u8FDB\uFF0C\u4E0B\u8F6E\u91CD\u5DE1`));
31511
31802
  }, PATROL_TIMEOUT_MS);
31512
31803
  const ok = engineDeps.dispatcher.submitMessage({
@@ -31520,21 +31811,21 @@ function makeReadOnlyAgentRunner(engineDeps) {
31520
31811
  deps: { ...base, engine: patrolEngine },
31521
31812
  callbacks: {
31522
31813
  onResult: (content) => {
31523
- if (settled) return;
31524
- settled = true;
31814
+ if (settled2) return;
31815
+ settled2 = true;
31525
31816
  clearTimeout(timeout);
31526
31817
  resolve12(content);
31527
31818
  },
31528
31819
  onError: (err) => {
31529
- if (settled) return;
31530
- settled = true;
31820
+ if (settled2) return;
31821
+ settled2 = true;
31531
31822
  clearTimeout(timeout);
31532
31823
  reject(new Error(err));
31533
31824
  }
31534
31825
  }
31535
31826
  });
31536
- if (ok === false && !settled) {
31537
- settled = true;
31827
+ if (ok === false && !settled2) {
31828
+ settled2 = true;
31538
31829
  clearTimeout(timeout);
31539
31830
  reject(new Error("dispatcher \u62D2\u7EDD wa-patrol \u63D0\u4EA4\uFF08guard \u5FD9\uFF09\u2014\u2014\u4E0B\u8F6E\u91CD\u5DE1"));
31540
31831
  }
@@ -32723,10 +33014,10 @@ var DingStreamClient = class extends EventEmitter {
32723
33014
  return;
32724
33015
  }
32725
33016
  this.ws = ws;
32726
- let settled = false;
33017
+ let settled2 = false;
32727
33018
  const settle = (err) => {
32728
- if (settled) return;
32729
- settled = true;
33019
+ if (settled2) return;
33020
+ settled2 = true;
32730
33021
  this.clearHeartbeat();
32731
33022
  if (err) reject(err);
32732
33023
  else resolve12();
@@ -32747,8 +33038,8 @@ var DingStreamClient = class extends EventEmitter {
32747
33038
  });
32748
33039
  ws.on("error", (err) => {
32749
33040
  this.emit("error", err instanceof Error ? err : new Error(String(err)));
32750
- if (!settled) {
32751
- settled = true;
33041
+ if (!settled2) {
33042
+ settled2 = true;
32752
33043
  this.clearHeartbeat();
32753
33044
  reject(err);
32754
33045
  return;
@@ -33423,18 +33714,18 @@ var DingTalkAdapter = class _DingTalkAdapter {
33423
33714
  /** per-card 流式串行链(无间隔闸)——throttle 保证 ≥300ms 节奏,但 HTTP 慢时相邻两次
33424
33715
  * fire 仍可能并发(后发先到→旧内容覆盖新内容);openclaw 的 in-flight 保护同语义 */
33425
33716
  cardStreamQueues = /* @__PURE__ */ new Map();
33426
- streamCardSerial(key2, outTrackId, content, isFinalize) {
33427
- const prev = this.cardStreamQueues.get(key2) ?? Promise.resolve();
33717
+ streamCardSerial(key4, outTrackId, content, isFinalize) {
33718
+ const prev = this.cardStreamQueues.get(key4) ?? Promise.resolve();
33428
33719
  const next = prev.then(
33429
33720
  () => this.streamCard(outTrackId, content, isFinalize),
33430
33721
  () => this.streamCard(outTrackId, content, isFinalize)
33431
33722
  );
33432
- this.cardStreamQueues.set(key2, next.then(() => {
33723
+ this.cardStreamQueues.set(key4, next.then(() => {
33433
33724
  }, () => {
33434
33725
  }));
33435
33726
  if (this.cardStreamQueues.size > 200) {
33436
33727
  const drop = this.cardStreamQueues.keys().next().value;
33437
- if (drop !== void 0 && drop !== key2) this.cardStreamQueues.delete(drop);
33728
+ if (drop !== void 0 && drop !== key4) this.cardStreamQueues.delete(drop);
33438
33729
  }
33439
33730
  return next;
33440
33731
  }
@@ -33443,10 +33734,10 @@ var DingTalkAdapter = class _DingTalkAdapter {
33443
33734
  * API,双重节流会把打字机压成"两秒一跳"(openclaw 实测:300ms 直打才流畅)。保序由
33444
33735
  * throttle(last-write-wins)+ per-card 串行链保证。 */
33445
33736
  async editPreview(handle, content, agentName, isFinal) {
33446
- const key2 = `${handle.channelId}:${handle.messageId}`;
33737
+ const key4 = `${handle.channelId}:${handle.messageId}`;
33447
33738
  try {
33448
- await this.editThrottle.submit(key2, { content, agentName, isFinal: !!isFinal }, async (r) => {
33449
- await this.streamCardSerial(key2, handle.messageId, r.content, r.isFinal);
33739
+ await this.editThrottle.submit(key4, { content, agentName, isFinal: !!isFinal }, async (r) => {
33740
+ await this.streamCardSerial(key4, handle.messageId, r.content, r.isFinal);
33450
33741
  if (r.isFinal) {
33451
33742
  await this.putCardData(handle.messageId, "3");
33452
33743
  await this.notifyGroupFinalized(handle.channelId, handle.messageId).catch(() => {
@@ -33749,10 +34040,10 @@ var WecomStreamClient = class extends EventEmitter2 {
33749
34040
  return;
33750
34041
  }
33751
34042
  this.ws = ws;
33752
- let settled = false;
34043
+ let settled2 = false;
33753
34044
  const settle = (err) => {
33754
- if (settled) return;
33755
- settled = true;
34045
+ if (settled2) return;
34046
+ settled2 = true;
33756
34047
  this.clearHeartbeat();
33757
34048
  const wasSubscribed = this.everSubscribed;
33758
34049
  this.subscribed = false;
@@ -33778,7 +34069,7 @@ var WecomStreamClient = class extends EventEmitter2 {
33778
34069
  ws.on("error", (err) => {
33779
34070
  const e = err instanceof Error ? err : new Error(String(err));
33780
34071
  this.emit("error", e);
33781
- if (!settled) {
34072
+ if (!settled2) {
33782
34073
  settle(e);
33783
34074
  return;
33784
34075
  }
@@ -34069,9 +34360,9 @@ function wecomTextFormat(text2, format2 = "markdown") {
34069
34360
  }
34070
34361
  function decryptWecomMedia(buf, aeskey) {
34071
34362
  const padded = aeskey + "=".repeat((4 - aeskey.length % 4) % 4);
34072
- const key2 = Buffer.from(padded, "base64");
34073
- if (key2.length !== 32) throw new Error(`wecom media aeskey \u89E3\u7801\u540E\u5E94\u4E3A 32 \u5B57\u8282\uFF0C\u5B9E\u5F97 ${key2.length}`);
34074
- const d = createDecipheriv3("aes-256-cbc", key2, key2.subarray(0, 16));
34363
+ const key4 = Buffer.from(padded, "base64");
34364
+ if (key4.length !== 32) throw new Error(`wecom media aeskey \u89E3\u7801\u540E\u5E94\u4E3A 32 \u5B57\u8282\uFF0C\u5B9E\u5F97 ${key4.length}`);
34365
+ const d = createDecipheriv3("aes-256-cbc", key4, key4.subarray(0, 16));
34075
34366
  d.setAutoPadding(false);
34076
34367
  const raw = Buffer.concat([d.update(buf), d.final()]);
34077
34368
  const pad = raw[raw.length - 1];
@@ -34370,22 +34661,22 @@ var WecomAdapter = class {
34370
34661
  this.emitInbound(parsed.inbound);
34371
34662
  return;
34372
34663
  }
34373
- const key2 = `${parsed.chatId}:${parsed.senderId}`;
34374
- const cur = this.pending.get(key2);
34664
+ const key4 = `${parsed.chatId}:${parsed.senderId}`;
34665
+ const cur = this.pending.get(key4);
34375
34666
  if (cur) {
34376
34667
  cur.parsed.inbound.content = `${cur.parsed.inbound.content}
34377
34668
  ${parsed.inbound.content}`;
34378
34669
  cur.version++;
34379
34670
  } else {
34380
- this.pending.set(key2, { parsed, version: 1 });
34671
+ this.pending.set(key4, { parsed, version: 1 });
34381
34672
  }
34382
- const entry = this.pending.get(key2);
34673
+ const entry = this.pending.get(key4);
34383
34674
  const v = entry.version;
34384
34675
  void this.sleepImpl(windowMs).then(() => {
34385
- const live = this.pending.get(key2);
34676
+ const live = this.pending.get(key4);
34386
34677
  if (!live) return;
34387
34678
  if (live.version !== v) return;
34388
- this.pending.delete(key2);
34679
+ this.pending.delete(key4);
34389
34680
  this.emitInbound(live.parsed.inbound);
34390
34681
  });
34391
34682
  }
@@ -34399,10 +34690,10 @@ ${parsed.inbound.content}`;
34399
34690
  }
34400
34691
  /** 立即投递并清空某会话挂起的合并片段(媒体直投前的顺序保护,review) */
34401
34692
  flushPending(chatId, senderId) {
34402
- const key2 = `${chatId}:${senderId}`;
34403
- const live = this.pending.get(key2);
34693
+ const key4 = `${chatId}:${senderId}`;
34694
+ const live = this.pending.get(key4);
34404
34695
  if (!live) return;
34405
- this.pending.delete(key2);
34696
+ this.pending.delete(key4);
34406
34697
  this.emitInbound(live.parsed.inbound);
34407
34698
  }
34408
34699
  // === 出站(spec §五) ===
@@ -34911,8 +35202,8 @@ function createFeishuGatewayDispatcher(options) {
34911
35202
  const timestamp = Number(message.create_time);
34912
35203
  if (!Number.isSafeInteger(timestamp) || timestamp < 0) throw new Error("TRAVEL_FEISHU_INVALID_EVENT");
34913
35204
  const content = JSON.parse(String(message.content)), descriptors = [];
34914
- const add = (key2, type, filename, contentType) => {
34915
- if (typeof key2 === "string" && key2) descriptors.push({ key: key2, type, filename, contentType });
35205
+ const add = (key4, type, filename, contentType) => {
35206
+ if (typeof key4 === "string" && key4) descriptors.push({ key: key4, type, filename, contentType });
34916
35207
  };
34917
35208
  if (message.message_type === "image") add(content.image_key, "image", "image.jpg", "image/jpeg");
34918
35209
  if (["file", "audio", "media"].includes(message.message_type)) add(content.file_key, "file", basename6(String(content.file_name ?? (message.message_type === "audio" ? "audio.opus" : message.message_type === "media" ? "video.mp4" : "file"))), message.message_type === "audio" ? "audio/opus" : message.message_type === "media" ? "video/mp4" : "application/octet-stream");
@@ -35050,9 +35341,9 @@ function createFeishuGatewayPlatform(options) {
35050
35341
  return { messageId: result.data.message_id };
35051
35342
  });
35052
35343
  },
35053
- downloadResource: async (messageId, key2, type) => {
35344
+ downloadResource: async (messageId, key4, type) => {
35054
35345
  if (closed) throw new Error("TRAVEL_FEISHU_CLOSED");
35055
- const response = await client.im.messageResource.get({ path: { message_id: messageId, file_key: key2 }, params: { type } });
35346
+ const response = await client.im.messageResource.get({ path: { message_id: messageId, file_key: key4 }, params: { type } });
35056
35347
  const stream = response.getReadableStream(), chunks = [];
35057
35348
  let bytes2 = 0;
35058
35349
  try {
@@ -35087,7 +35378,7 @@ function createRemoteTravelChannel(block, stateDir, channel = "feishu") {
35087
35378
  if (!stateDir || !runtimeAuthorityFor(stateDir)) throw new Error("TRAVEL_GATEWAY_RUNTIME_REQUIRED");
35088
35379
  validateTravelChannels(stateDir, { [channel]: block });
35089
35380
  const tls2 = block.gatewayTls;
35090
- if (!tls2 || ["caFile", "certFile", "keyFile"].some((key2) => typeof tls2[key2] !== "string" || !tls2[key2])) throw new Error("TRAVEL_GATEWAY_REMOTE_CONFIG_REQUIRED");
35381
+ if (!tls2 || ["caFile", "certFile", "keyFile"].some((key4) => typeof tls2[key4] !== "string" || !tls2[key4])) throw new Error("TRAVEL_GATEWAY_REMOTE_CONFIG_REQUIRED");
35091
35382
  const client = new TravelGatewayClient({ url: block.gatewayUrl, ca: readPrivateFile(tls2.caFile, 1024 * 1024), cert: readPrivateFile(tls2.certFile, 1024 * 1024), key: readPrivateFile(tls2.keyFile, 16384) });
35092
35383
  return new RemoteTravelChannel({ client, channel, permit: () => runtimeAuthorityFor(stateDir).assert("INPUT"), pollIntervalMs: block.gatewayPollIntervalMs });
35093
35384
  }
@@ -35293,9 +35584,9 @@ function archive(manager, name, mime, bytes2, role, caption, identity) {
35293
35584
  const adapter = manager.getAdapter("chan7");
35294
35585
  if (!adapter?.files || bytes2.length > 16 * 1024 * 1024) return;
35295
35586
  const safeName = path33.basename(name).replace(/[<>:"/\\|?*\x00-\x1f]/g, "_").slice(0, 255) || "attachment";
35296
- const key2 = createHash35("sha256").update(JSON.stringify(identity)).update(bytes2).digest("hex");
35587
+ const key4 = createHash35("sha256").update(JSON.stringify(identity)).update(bytes2).digest("hex");
35297
35588
  try {
35298
- adapter.files.import(safeName, mime, bytes2, role, caption.slice(0, 4e3), key2);
35589
+ adapter.files.import(safeName, mime, bytes2, role, caption.slice(0, 4e3), key4);
35299
35590
  } catch (e) {
35300
35591
  console.warn("[library] delivered copy not archived: " + e.message);
35301
35592
  }
@@ -35529,7 +35820,7 @@ var ChannelManager = class {
35529
35820
  const changes = [];
35530
35821
  for (const name of MANAGED_CHANNEL_NAMES) {
35531
35822
  const block = config[name];
35532
- const key2 = JSON.stringify(block ?? null);
35823
+ const key4 = JSON.stringify(block ?? null);
35533
35824
  const cur = this.managed.get(name);
35534
35825
  const enabled = block?.enabled === true;
35535
35826
  if (!enabled && !cur) continue;
@@ -35538,7 +35829,7 @@ var ChannelManager = class {
35538
35829
  changes.push(`${name}: removed`);
35539
35830
  continue;
35540
35831
  }
35541
- if (cur && cur.key === key2) continue;
35832
+ if (cur && cur.key === key4) continue;
35542
35833
  if (cur) {
35543
35834
  if (runningQueries.includes(name)) {
35544
35835
  console.log(`[channels] ${name} rebuild deferred (query in flight)`);
@@ -35550,7 +35841,7 @@ var ChannelManager = class {
35550
35841
  const adapter = this.buildManagedAdapter(name, block);
35551
35842
  if (!adapter) continue;
35552
35843
  this.adapters.push(adapter);
35553
- this.managed.set(name, { adapter, key: key2 });
35844
+ this.managed.set(name, { adapter, key: key4 });
35554
35845
  this.wireAdapter(adapter);
35555
35846
  if (adapter.registerCommands && this.registeredCommands.size > 0) {
35556
35847
  void adapter.registerCommands([...this.registeredCommands.values()]).catch((e) => console.error(`[channels] ${name} registerCommands failed: ${e.message}`));
@@ -35793,7 +36084,7 @@ function tls(config) {
35793
36084
  return { ca: readPrivateFile(path34(config?.caFile), 1024 * 1024), cert: readPrivateFile(path34(config?.certFile), 1024 * 1024), key: readPrivateFile(path34(config?.keyFile), 16384) };
35794
36085
  }
35795
36086
  async function startTravelGateway(config) {
35796
- if (!config?.identity || !config.keyService?.identity || ["tenantId", "companionId", "seatId"].some((key2) => config.identity[key2] !== config.keyService.identity[key2])) throw new Error("TRAVEL_GATEWAY_IDENTITY");
36087
+ if (!config?.identity || !config.keyService?.identity || ["tenantId", "companionId", "seatId"].some((key4) => config.identity[key4] !== config.keyService.identity[key4])) throw new Error("TRAVEL_GATEWAY_IDENTITY");
35797
36088
  if (!Number.isSafeInteger(config.port) || config.port < 0 || config.port > 65535 || typeof config.host !== "string" || !config.host) throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
35798
36089
  for (const [name, value] of Object.entries(config.channels ?? {})) if (value?.enabled && !["feishu", "discord", "wechat"].includes(name)) throw new Error("TRAVEL_CHANNEL_NOT_CONTROLLED");
35799
36090
  const feishuIngress = config.ingressEnabled !== false && config.feishu?.ingressEnabled !== false && config.channels?.feishu?.enabled !== false;
@@ -35846,7 +36137,7 @@ async function startTravelGateway(config) {
35846
36137
  if (!config.allowedPeers || !Object.keys(config.allowedPeers).length) throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
35847
36138
  for (const credential of Object.values(config.allowedPeers)) {
35848
36139
  const principal = authority.authenticate(String(credential));
35849
- if (["tenantId", "companionId", "seatId"].some((key2) => principal[key2] !== config.identity[key2]) || authority.status(principal).deletionWatermark !== material.deletionWatermark) throw new Error("TRAVEL_GATEWAY_IDENTITY");
36140
+ if (["tenantId", "companionId", "seatId"].some((key4) => principal[key4] !== config.identity[key4]) || authority.status(principal).deletionWatermark !== material.deletionWatermark) throw new Error("TRAVEL_GATEWAY_IDENTITY");
35850
36141
  }
35851
36142
  store = new TravelGatewayStore({ directory: path34(config.gatewayDir), identity: config.identity, objects, authority });
35852
36143
  await store.migrateStoredInputs();
@@ -35896,9 +36187,9 @@ async function startTravelGateway(config) {
35896
36187
  assertIngress: assertKey,
35897
36188
  authorizeStop: (sender) => Array.isArray(config.feishu.stopAllowedUserIds) && config.feishu.stopAllowedUserIds.includes(sender.sender_id?.open_id),
35898
36189
  onReceivedTyping: (chatId, openId, messageId) => platform.startChatTyping(chatId, openId, messageId),
35899
- downloadResource: async (messageId, key2, type) => {
36190
+ downloadResource: async (messageId, key4, type) => {
35900
36191
  assertKey();
35901
- return platform.downloadResource(messageId, key2, type);
36192
+ return platform.downloadResource(messageId, key4, type);
35902
36193
  }
35903
36194
  });
35904
36195
  if (config.channels && config.ingressEnabled !== false) {