engine7 7.1.144 → 7.1.146

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.
@@ -627,9 +627,9 @@ var init_key_service_store = __esm({
627
627
  throw error;
628
628
  }
629
629
  }
630
- provision(identity, key2) {
630
+ provision(identity, key4) {
631
631
  const text2 = identityText(identity);
632
- if (!(key2 instanceof Uint8Array) || key2.byteLength !== 32) throw new Error("KEY_SERVICE_INVALID_KEY");
632
+ if (!(key4 instanceof Uint8Array) || key4.byteLength !== 32) throw new Error("KEY_SERVICE_INVALID_KEY");
633
633
  this.transaction(() => {
634
634
  if (this.db.prepare("SELECT key_id FROM seat_keys WHERE key_id=?").get(identity.keyId))
635
635
  throw new Error("KEY_SERVICE_KEY_EXISTS");
@@ -638,7 +638,7 @@ var init_key_service_store = __esm({
638
638
  const fd = openSync2(path35, constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL, 384);
639
639
  try {
640
640
  let written = 0;
641
- while (written < key2.byteLength) written += writeSync(fd, key2, written, key2.byteLength - written);
641
+ while (written < key4.byteLength) written += writeSync(fd, key4, written, key4.byteLength - written);
642
642
  fsyncSync2(fd);
643
643
  } catch (error) {
644
644
  closeSync2(fd);
@@ -690,12 +690,12 @@ var init_key_service_store = __esm({
690
690
  if (typeof seat.secret_file !== "string" || !/^[a-f0-9-]{36}\.key$/.test(seat.secret_file))
691
691
  throw new Error("KEY_SERVICE_INVALID_KEY_FILE");
692
692
  assertPrivateStat(lstatSync2(this.secrets), true);
693
- const key2 = readPrivateFile(join2(this.secrets, seat.secret_file), 32);
694
- if (key2.length !== 32) {
695
- key2.fill(0);
693
+ const key4 = readPrivateFile(join2(this.secrets, seat.secret_file), 32);
694
+ if (key4.length !== 32) {
695
+ key4.fill(0);
696
696
  throw new Error("KEY_SERVICE_INVALID_KEY_FILE");
697
697
  }
698
- return { key: key2, deletionWatermark: current2 };
698
+ return { key: key4, deletionWatermark: current2 };
699
699
  });
700
700
  }
701
701
  advanceWatermark(keyId, value) {
@@ -837,7 +837,7 @@ function validateTravelChannelConfiguration(channels) {
837
837
  if (name === "emotion" || value?.enabled !== true) continue;
838
838
  if (!["feishu", "discord", "wechat"].includes(name)) throw new Error("TRAVEL_CHANNEL_NOT_CONTROLLED");
839
839
  if (value.mode !== "remote-only") throw new Error("TRAVEL_REMOTE_ONLY_REQUIRED");
840
- 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));
840
+ 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));
841
841
  if (hasPlatformSecret(value)) throw new Error("TRAVEL_PLATFORM_SECRET_PRESENT");
842
842
  let url;
843
843
  try {
@@ -1583,15 +1583,15 @@ var init_sqlite_replication = __esm({
1583
1583
  requireForeignKeys(this.db);
1584
1584
  if (captureGuardHash(this.db) !== this.guardHash) throw new Error("REPLICATION_GUARD_MISMATCH");
1585
1585
  if (sqliteReplicationSchemaHash(this.db) !== this.schemaHash) throw new Error("REPLICATION_SCHEMA_MISMATCH");
1586
- const before = sequences(this.db, this.excludedTables), sessions = [];
1586
+ const before = sequences(this.db, this.excludedTables), sessions2 = [];
1587
1587
  try {
1588
- if (this.sessionTables) for (const table of this.sessionTables) sessions.push(this.db.createSession({ table }));
1589
- else sessions.push(this.db.createSession());
1588
+ if (this.sessionTables) for (const table of this.sessionTables) sessions2.push(this.db.createSession({ table }));
1589
+ else sessions2.push(this.db.createSession());
1590
1590
  } catch (error) {
1591
- for (const session of sessions) session.close();
1591
+ for (const session of sessions2) session.close();
1592
1592
  throw error;
1593
1593
  }
1594
- this.active = { sessions, sequences: before, closed: false };
1594
+ this.active = { sessions: sessions2, sequences: before, closed: false };
1595
1595
  return this.active;
1596
1596
  }
1597
1597
  appendCapture(capture) {
@@ -2054,10 +2054,10 @@ var init_live = __esm({
2054
2054
  /** 安全取子段('services.voice-chat.start' → current.services.voice-chat.start) */
2055
2055
  get(dotPath) {
2056
2056
  if (!this.current) return void 0;
2057
- return dotPath.split(".").reduce((acc, key2) => {
2057
+ return dotPath.split(".").reduce((acc, key4) => {
2058
2058
  if (acc == null) return void 0;
2059
- if (key2 === "__proto__" || key2 === "constructor" || key2 === "prototype") return void 0;
2060
- return acc[key2];
2059
+ if (key4 === "__proto__" || key4 === "constructor" || key4 === "prototype") return void 0;
2060
+ return acc[key4];
2061
2061
  }, this.current);
2062
2062
  }
2063
2063
  /** reload 时原地更新(Object.assign 保持引用不变)
@@ -2223,9 +2223,9 @@ function toWall(i = /* @__PURE__ */ new Date()) {
2223
2223
  return `${p.y}-${p2(p.mo)}-${p2(p.d)} ${p2(p.hh)}:${p2(p.mm)}:${p2(p.ss)}`;
2224
2224
  }
2225
2225
  function warnOnce(callSite, shape, sample) {
2226
- const key2 = `${callSite}:${shape}`;
2227
- if (warned.has(key2)) return;
2228
- warned.add(key2);
2226
+ const key4 = `${callSite}:${shape}`;
2227
+ if (warned.has(key4)) return;
2228
+ warned.add(key4);
2229
2229
  console.warn(`[clock] ${callSite} \u5951\u7EA6\u8FDD\u89C4(${shape})\uFF0C\u6837\u672C: ${String(sample).slice(0, 80)}`);
2230
2230
  }
2231
2231
  function zoneOffsetMs(d) {
@@ -2373,11 +2373,11 @@ var init_filters = __esm({
2373
2373
  import { createHash as createHash5 } from "node:crypto";
2374
2374
  function scopeId(scope) {
2375
2375
  if ([scope.ownerId, scope.appId, scope.projectId].some((value) => typeof value !== "string" || !value.trim())) throw new Error("Invalid memory scope");
2376
- const key2 = JSON.stringify([scope.ownerId, scope.appId, scope.projectId]);
2377
- const cached2 = scopeIdMemo.get(key2);
2376
+ const key4 = JSON.stringify([scope.ownerId, scope.appId, scope.projectId]);
2377
+ const cached2 = scopeIdMemo.get(key4);
2378
2378
  if (cached2) return cached2;
2379
2379
  const id3 = "scope_" + createHash5("sha256").update(JSON.stringify([scope.ownerId, scope.appId, scope.projectId])).digest("hex");
2380
- scopeIdMemo.set(key2, id3);
2380
+ scopeIdMemo.set(key4, id3);
2381
2381
  return id3;
2382
2382
  }
2383
2383
  var scopeIdMemo;
@@ -2390,10 +2390,14 @@ var init_scope = __esm({
2390
2390
 
2391
2391
  // src/mem7/core/state/temporal.ts
2392
2392
  function instant(value) {
2393
- if (!/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/.test(value)) throw new Error("TIME_REQUIRED: explicit UTC offset required");
2394
- if (!isCalendarDate(value.substring(0, 10))) throw new Error("INVALID_TIME");
2395
- const time = Date.parse(value);
2396
- if (!Number.isFinite(time)) throw new Error("INVALID_TIME");
2393
+ let text2 = value;
2394
+ if (typeof text2 !== "string" || !INSTANT.test(text2)) {
2395
+ text2 = typeof value === "string" ? value.trim().replace(/^(\d{4}-\d{2}-\d{2}) /, "$1T").replace(/([+-]\d{2})(\d{2})$/, "$1:$2") : value;
2396
+ if (typeof text2 !== "string" || !INSTANT.test(text2)) throw new Error(`TIME_REQUIRED: explicit UTC offset required \u2014 \u6536\u5230 ${received(value)}\uFF1B${INSTANT_FORMAT}`);
2397
+ }
2398
+ 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)}`);
2399
+ const time = Date.parse(text2);
2400
+ if (!Number.isFinite(time)) throw new Error(`INVALID_TIME \u2014 \u6536\u5230 ${received(value)}\uFF1B${INSTANT_FORMAT}`);
2397
2401
  return new Date(time).toISOString();
2398
2402
  }
2399
2403
  function isCalendarDate(value) {
@@ -2406,7 +2410,7 @@ function validateTimezone(timezone) {
2406
2410
  try {
2407
2411
  new Intl.DateTimeFormat("en", { timeZone: timezone });
2408
2412
  } catch {
2409
- throw new Error("INVALID_TIMEZONE");
2413
+ throw new Error(`INVALID_TIMEZONE: timezone \u7528 IANA \u65F6\u533A\u540D\uFF0C\u5982 Asia/Shanghai\uFF08\u6536\u5230 ${String(timezone).slice(0, 60)}\uFF09`);
2410
2414
  }
2411
2415
  }
2412
2416
  function localInstant(date, time, timezone) {
@@ -2438,10 +2442,13 @@ function localInstant(date, time, timezone) {
2438
2442
  return new Date([...matches][0]).toISOString();
2439
2443
  }
2440
2444
  function normalizeValidity(value) {
2445
+ for (const field of ["validFrom", "validTo"]) {
2446
+ 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}`);
2447
+ }
2441
2448
  const validFrom = value.validFrom === null ? null : instant(value.validFrom);
2442
2449
  const validTo = value.validTo === null ? null : instant(value.validTo);
2443
- if (validFrom !== null && validTo !== null && validFrom >= validTo) throw new Error("INVALID_INTERVAL: expected [from,to)");
2444
- if (!["exact", "observed", "unknown"].includes(value.precision)) throw new Error("INVALID_PRECISION");
2450
+ 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");
2451
+ 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");
2445
2452
  if (value.timezone) validateTimezone(value.timezone);
2446
2453
  return { ...value, validFrom, validTo };
2447
2454
  }
@@ -2451,16 +2458,20 @@ function overlaps(a, b) {
2451
2458
  function canonicalJson(value) {
2452
2459
  const normalize6 = (input) => {
2453
2460
  if (Array.isArray(input)) return input.map(normalize6);
2454
- 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)]));
2461
+ 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)]));
2455
2462
  return input;
2456
2463
  };
2457
2464
  const json = JSON.stringify(normalize6(value));
2458
2465
  if (json === void 0) throw new Error("INVALID_JSON_VALUE");
2459
2466
  return json;
2460
2467
  }
2468
+ var INSTANT, INSTANT_FORMAT, received;
2461
2469
  var init_temporal = __esm({
2462
2470
  "src/mem7/core/state/temporal.ts"() {
2463
2471
  "use strict";
2472
+ INSTANT = /^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/;
2473
+ 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';
2474
+ received = (value) => (JSON.stringify(value) ?? String(value)).slice(0, 80);
2464
2475
  }
2465
2476
  });
2466
2477
 
@@ -2485,8 +2496,8 @@ function contextTimeKey(db2, scopeId2, validAt) {
2485
2496
  }
2486
2497
  return `valid-window:${from}:${to}`;
2487
2498
  }
2488
- function assertContextTime(key2, now2 = Date.now()) {
2489
- const match = key2.match(/^valid-window:(-?\d+):(-?\d+)$/);
2499
+ function assertContextTime(key4, now2 = Date.now()) {
2500
+ const match = key4.match(/^valid-window:(-?\d+):(-?\d+)$/);
2490
2501
  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");
2491
2502
  if (now2 < Number(match[1]) || now2 >= Number(match[2])) throw new Error("CONTEXT_TIME_EXPIRED");
2492
2503
  }
@@ -2591,9 +2602,9 @@ function append(db2, scope, kind, id3, payload) {
2591
2602
  return Number(result.lastInsertRowid);
2592
2603
  }
2593
2604
  function recordArtifactBasis(db2, scope, kind, id3, version, dependencies) {
2594
- const key2 = basisKey(kind, id3, version);
2595
- if (!db2.prepare("SELECT 1 FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=?").get(scopeId(scope), key2)) {
2596
- append(db2, scope, "artifact.basis", key2, { dependencies });
2605
+ const key4 = basisKey(kind, id3, version);
2606
+ if (!db2.prepare("SELECT 1 FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=?").get(scopeId(scope), key4)) {
2607
+ append(db2, scope, "artifact.basis", key4, { dependencies });
2597
2608
  }
2598
2609
  }
2599
2610
  var ARTIFACT_HISTORY_SCHEMA, hash3, basisKey, stateKey, generationKinds, normalizedRefs, ArtifactHistory;
@@ -2743,8 +2754,8 @@ END;
2743
2754
  if (cutoff) return historicalRow(this.db, scope, "artifact.basis", basisKey(kind, id3, version), cutoff)?.dependencies ?? null;
2744
2755
  return this.dependencies.version(scope, kind, id3) === version ? this.dependencies.refs(scope, kind, id3) : null;
2745
2756
  }
2746
- scopeContextRetained(scope, key2) {
2747
- 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);
2757
+ scopeContextRetained(scope, key4) {
2758
+ 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);
2748
2759
  if (!basis) return false;
2749
2760
  const atGeneration = historicalRow(this.db, scope, "scope", "state", { historyId: basis.history_id, time: null, complete: true });
2750
2761
  if (!atGeneration) return false;
@@ -2762,15 +2773,15 @@ END;
2762
2773
  WHERE scope_id=? AND source_id=? AND interpretation_status<>'deleted'`).get(scopeKey, sourceId));
2763
2774
  const walk = (kind2, id4, version2) => {
2764
2775
  checkMemoryReadBudget(visited.size);
2765
- const key2 = basisKey(kind2, id4, version2);
2766
- if (memo.has(key2)) return memo.get(key2);
2767
- if (visited.has(key2)) return false;
2768
- visited.add(key2);
2776
+ const key4 = basisKey(kind2, id4, version2);
2777
+ if (memo.has(key4)) return memo.get(key4);
2778
+ if (visited.has(key4)) return false;
2779
+ visited.add(key4);
2769
2780
  try {
2770
- 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);
2781
+ 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);
2771
2782
  const refs = basis && JSON.parse(basis.payload_json).dependencies;
2772
2783
  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;
2773
- if (refs.some((ref) => ref.parentKind === "scope" && !ref.parentId.startsWith("valid-window:")) && !this.scopeContextRetained(scope, key2)) return false;
2784
+ if (refs.some((ref) => ref.parentKind === "scope" && !ref.parentId.startsWith("valid-window:")) && !this.scopeContextRetained(scope, key4)) return false;
2774
2785
  const retained = refs.every((ref) => {
2775
2786
  checkMemoryReadBudget(visited.size);
2776
2787
  if (ref.parentKind === "source") return sourceRetained(ref.parentId);
@@ -2790,10 +2801,10 @@ END;
2790
2801
  }
2791
2802
  return true;
2792
2803
  });
2793
- memo.set(key2, retained);
2804
+ memo.set(key4, retained);
2794
2805
  return retained;
2795
2806
  } finally {
2796
- visited.delete(key2);
2807
+ visited.delete(key4);
2797
2808
  }
2798
2809
  };
2799
2810
  return walk(kind, id3, version);
@@ -2819,8 +2830,8 @@ END;
2819
2830
  };
2820
2831
  const walk = (parentKind, parentId, parentVersion, ancestors) => {
2821
2832
  checkMemoryReadBudget(ancestors.size);
2822
- const key2 = basisKey(parentKind, parentId, parentVersion);
2823
- if (ancestors.has(key2)) return false;
2833
+ const key4 = basisKey(parentKind, parentId, parentVersion);
2834
+ if (ancestors.has(key4)) return false;
2824
2835
  const state = this.state(scope, parentKind, parentId, cutoff);
2825
2836
  if (state?.state !== "current" || state.version !== parentVersion) return false;
2826
2837
  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;
@@ -2835,9 +2846,9 @@ END;
2835
2846
  }
2836
2847
  }
2837
2848
  if (refs.some((ref) => ref.parentKind === "scope" && !ref.parentId.startsWith("valid-window:"))) {
2838
- if (!this.scopeContextRetained(scope, key2)) return false;
2849
+ if (!this.scopeContextRetained(scope, key4)) return false;
2839
2850
  }
2840
- const next = new Set(ancestors).add(key2);
2851
+ const next = new Set(ancestors).add(key4);
2841
2852
  for (const ref of refs) {
2842
2853
  checkMemoryReadBudget(next.size);
2843
2854
  if (ref.parentKind === "source") {
@@ -2984,9 +2995,9 @@ function invalidateChildren(db2, scope, pending, reason) {
2984
2995
  let referencedPlan;
2985
2996
  while (pending.length) {
2986
2997
  const child = pending.shift();
2987
- const key2 = JSON.stringify([child.child_kind, child.child_id]);
2988
- if (visited.has(key2) && (visited.get(key2) || !child.deleted)) continue;
2989
- visited.set(key2, Boolean(child.deleted));
2998
+ const key4 = JSON.stringify([child.child_kind, child.child_id]);
2999
+ if (visited.has(key4) && (visited.get(key4) || !child.deleted)) continue;
3000
+ visited.set(key4, Boolean(child.deleted));
2990
3001
  if (child.child_kind === "graph_plan") {
2991
3002
  referencedPlan ??= db2.prepare(`SELECT 1 WHERE EXISTS (SELECT 1 FROM memory_dependencies
2992
3003
  WHERE scope_id=? AND parent_kind='artifact' AND parent_id=?)
@@ -3067,8 +3078,8 @@ var init_dependencies = __esm({
3067
3078
  this.snapshotStamp = void 0;
3068
3079
  }
3069
3080
  }
3070
- observeTimeBoundary(key2) {
3071
- const match = key2.match(/^valid-window:(-?\d+):(-?\d+)$/);
3081
+ observeTimeBoundary(key4) {
3082
+ const match = key4.match(/^valid-window:(-?\d+):(-?\d+)$/);
3072
3083
  if (!match) return;
3073
3084
  const now2 = Date.now();
3074
3085
  for (const boundary of [Number(match[1]), Number(match[2])]) {
@@ -3150,9 +3161,9 @@ var init_dependencies = __esm({
3150
3161
  }
3151
3162
  artifactTimeCurrent(scope, kind, id3, visited = /* @__PURE__ */ new Set(), memo) {
3152
3163
  checkMemoryReadBudget(visited.size);
3153
- const key2 = JSON.stringify([kind, id3]);
3154
- if (visited.has(key2)) return false;
3155
- visited.add(key2);
3164
+ const key4 = JSON.stringify([kind, id3]);
3165
+ if (visited.has(key4)) return false;
3166
+ visited.add(key4);
3156
3167
  try {
3157
3168
  const refs = this.refs(scope, kind, id3);
3158
3169
  for (const ref of refs.filter((ref2) => ref2.parentKind !== "artifact")) {
@@ -3187,7 +3198,7 @@ var init_dependencies = __esm({
3187
3198
  }
3188
3199
  return true;
3189
3200
  } finally {
3190
- visited.delete(key2);
3201
+ visited.delete(key4);
3191
3202
  }
3192
3203
  }
3193
3204
  version(scope, kind, id3) {
@@ -3386,6 +3397,28 @@ var init_timing = __esm({
3386
3397
  }
3387
3398
  });
3388
3399
 
3400
+ // src/mem7/core/lance-cache.ts
3401
+ function memoryLanceSession(lance) {
3402
+ if (typeof lance.Session !== "function") return void 0;
3403
+ let session = sessions.get(lance);
3404
+ if (!session) {
3405
+ session = new lance.Session(BigInt(LANCE_INDEX_CACHE_BYTES), BigInt(LANCE_METADATA_CACHE_BYTES));
3406
+ sessions.set(lance, session);
3407
+ }
3408
+ return session;
3409
+ }
3410
+ var LANCE_INDEX_CACHE_BYTES, LANCE_METADATA_CACHE_BYTES, key, globals, sessions;
3411
+ var init_lance_cache = __esm({
3412
+ "src/mem7/core/lance-cache.ts"() {
3413
+ "use strict";
3414
+ LANCE_INDEX_CACHE_BYTES = 256 * 1024 * 1024;
3415
+ LANCE_METADATA_CACHE_BYTES = 64 * 1024 * 1024;
3416
+ key = Symbol.for("engine7.mem7.lanceCacheSessions");
3417
+ globals = globalThis;
3418
+ sessions = globals[key] ??= /* @__PURE__ */ new WeakMap();
3419
+ }
3420
+ });
3421
+
3389
3422
  // src/mem7/core/vector-store.ts
3390
3423
  import { mkdirSync as mkdirSync5, existsSync as existsSync3 } from "node:fs";
3391
3424
  import { DatabaseSync as DatabaseSync5 } from "node:sqlite";
@@ -3535,6 +3568,7 @@ var init_vector_store = __esm({
3535
3568
  init_read_guard();
3536
3569
  init_timing();
3537
3570
  init_runtime_authority();
3571
+ init_lance_cache();
3538
3572
  isIntelMac = process.platform === "darwin" && process.arch === "x64";
3539
3573
  lancePromise = null;
3540
3574
  mem7VectorWarning = null;
@@ -3621,7 +3655,7 @@ var init_vector_store = __esm({
3621
3655
  /** Reuse expensive dependency walks, but bind each verdict to SQL, time and the actual indexed body. */
3622
3656
  cachedRowVisible(ledger, kind, row, dependencies) {
3623
3657
  if (!dependencies) return vectorRowVisible(ledger, kind, row);
3624
- const key2 = kind + ":" + String(row.id);
3658
+ const key4 = kind + ":" + String(row.id);
3625
3659
  let signature2;
3626
3660
  try {
3627
3661
  signature2 = JSON.stringify([
@@ -3645,11 +3679,11 @@ var init_vector_store = __esm({
3645
3679
  this.visibleCacheVersion = version;
3646
3680
  this.visibleCache.clear();
3647
3681
  }
3648
- const cached2 = this.visibleCache.get(key2);
3682
+ const cached2 = this.visibleCache.get(key4);
3649
3683
  if (cached2?.signature === signature2) return cached2.verdict;
3650
3684
  const verdict = vectorRowVisible(ledger, kind, row, dependencies);
3651
3685
  if (dependencies.cacheRevision() !== version) return false;
3652
- this.visibleCache.set(key2, { signature: signature2, verdict });
3686
+ this.visibleCache.set(key4, { signature: signature2, verdict });
3653
3687
  return verdict;
3654
3688
  }
3655
3689
  visibleCache = /* @__PURE__ */ new Map();
@@ -3670,7 +3704,8 @@ var init_vector_store = __esm({
3670
3704
  assertRuntimeAuthority(this.stateDir, "WRITE");
3671
3705
  mkdirSync5(this.dir, { recursive: true });
3672
3706
  }
3673
- this.db = await lance.connect(this.dir);
3707
+ const session = memoryLanceSession(lance);
3708
+ this.db = await lance.connect(this.dir, session ? { session } : void 0);
3674
3709
  }
3675
3710
  return this.db;
3676
3711
  }
@@ -4147,11 +4182,11 @@ var init_vector_store = __esm({
4147
4182
  const rrf = /* @__PURE__ */ new Map();
4148
4183
  const add = (list) => {
4149
4184
  list.forEach((h, i) => {
4150
- const key2 = h.text.replace(/\s+/g, "");
4185
+ const key4 = h.text.replace(/\s+/g, "");
4151
4186
  const contrib = 1 / (RRF_K + i + 1);
4152
- const cur = rrf.get(key2);
4187
+ const cur = rrf.get(key4);
4153
4188
  if (cur) cur.score += contrib;
4154
- else rrf.set(key2, { hit: h, score: contrib });
4189
+ else rrf.set(key4, { hit: h, score: contrib });
4155
4190
  });
4156
4191
  };
4157
4192
  add(dense);
@@ -4379,8 +4414,8 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
4379
4414
  * 事件重放失败一次即回死信+skip,不重烧 5 轮预算)。先 UPDATE 后记账:中间崩溃只会
4380
4415
  * 多治一次(幂等无害),反过来会出现"记了账但没治"的永久死锁。 */
4381
4416
  reenqueueGapPrefix(sinkId, head, now2 = Date.now()) {
4382
- const key2 = `${sinkId}:${head.scopeId}:${head.eventSeq}`;
4383
- if (this.healedGaps.has(key2)) return;
4417
+ const key4 = `${sinkId}:${head.scopeId}:${head.eventSeq}`;
4418
+ if (this.healedGaps.has(key4)) return;
4384
4419
  const ledgerPath = this.gapHealLedgerPath;
4385
4420
  let ledger = {};
4386
4421
  if (ledgerPath) {
@@ -4388,8 +4423,8 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
4388
4423
  ledger = JSON.parse(readFileSync4(ledgerPath, "utf8"))?.heals ?? {};
4389
4424
  } catch {
4390
4425
  }
4391
- if (Number.isFinite(ledger[key2])) {
4392
- this.healedGaps.add(key2);
4426
+ if (Number.isFinite(ledger[key4])) {
4427
+ this.healedGaps.add(key4);
4393
4428
  return;
4394
4429
  }
4395
4430
  }
@@ -4403,11 +4438,11 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
4403
4438
  const count = Number(result?.changes ?? 0);
4404
4439
  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`);
4405
4440
  });
4406
- this.healedGaps.add(key2);
4441
+ this.healedGaps.add(key4);
4407
4442
  if (!ledgerPath) return;
4408
4443
  const cutoff = now2 - _ChangeFeed.GAP_HEAL_RETENTION_MS, retained = {};
4409
4444
  for (const [entry, at] of Object.entries(ledger)) if (Number.isFinite(at) && at >= cutoff) retained[entry] = at;
4410
- retained[key2] = now2;
4445
+ retained[key4] = now2;
4411
4446
  const temp = `${ledgerPath}.${randomUUID6()}.tmp`;
4412
4447
  try {
4413
4448
  writeFileSync4(temp, JSON.stringify({ version: 1, heals: retained }));
@@ -4532,7 +4567,7 @@ function validatePredicateValue(predicate, value) {
4532
4567
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("INVALID_FACT_VALUE");
4533
4568
  const object3 = value;
4534
4569
  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"];
4535
- if (Object.keys(object3).some((key2) => !allowed.includes(key2))) throw new Error("INVALID_FACT_VALUE: unknown field");
4570
+ if (Object.keys(object3).some((key4) => !allowed.includes(key4))) throw new Error("INVALID_FACT_VALUE: unknown field");
4536
4571
  if (predicate === "activity.schedule") {
4537
4572
  const schedule = object3;
4538
4573
  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");
@@ -4754,8 +4789,8 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
4754
4789
  ).all(scopeId(scope), `%${word.replace(/[!%_]/g, (character) => "!" + character)}%`, limit2);
4755
4790
  return rows.map((row) => this.source(row));
4756
4791
  }
4757
- snapshotRead(key2, load) {
4758
- return this.snapshotReads ? this.snapshotReads.read(JSON.stringify(key2), load) : load();
4792
+ snapshotRead(key4, load) {
4793
+ return this.snapshotReads ? this.snapshotReads.read(JSON.stringify(key4), load) : load();
4759
4794
  }
4760
4795
  receive(input, options = {}) {
4761
4796
  const id3 = scopeId(input.scope);
@@ -4936,8 +4971,8 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
4936
4971
  const result = { applied: 0, needsReview: 0, failed: 0, received: 0 };
4937
4972
  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));
4938
4973
  for (const row of rows) {
4939
- const key2 = row.state === "needs_review" ? "needsReview" : row.state;
4940
- if (Object.hasOwn(result, key2)) result[key2] += Number(row.count);
4974
+ const key4 = row.state === "needs_review" ? "needsReview" : row.state;
4975
+ if (Object.hasOwn(result, key4)) result[key4] += Number(row.count);
4941
4976
  }
4942
4977
  return result;
4943
4978
  }
@@ -5361,13 +5396,13 @@ function purgeRecoveryEvidence(db2, graph) {
5361
5396
  db2.prepare("UPDATE e7_recovery_items SET result=? WHERE item_id=?").run(JSON.stringify(item), saved.item_id);
5362
5397
  }
5363
5398
  }
5364
- var text, key, RecoveryDeletionGraph;
5399
+ var text, key2, RecoveryDeletionGraph;
5365
5400
  var init_recovery_deletion = __esm({
5366
5401
  "src/continuity/recovery-deletion.ts"() {
5367
5402
  "use strict";
5368
5403
  init_recovery_deletion_sources();
5369
- text = (row, key2) => row[key2]?.[0] === "text" ? row[key2][1] : void 0;
5370
- key = (scope, kind, id3) => JSON.stringify([scope, kind, id3]);
5404
+ text = (row, key4) => row[key4]?.[0] === "text" ? row[key4][1] : void 0;
5405
+ key2 = (scope, kind, id3) => JSON.stringify([scope, kind, id3]);
5371
5406
  RecoveryDeletionGraph = class {
5372
5407
  edges = /* @__PURE__ */ new Map();
5373
5408
  roots = /* @__PURE__ */ new Set();
@@ -5380,10 +5415,10 @@ var init_recovery_deletion = __esm({
5380
5415
  constructor(deletions) {
5381
5416
  if (deletions.length > 1e5) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
5382
5417
  for (const d of deletions) {
5383
- this.roots.add(key(d.scopeId, "source", d.sourceId));
5418
+ this.roots.add(key2(d.scopeId, "source", d.sourceId));
5384
5419
  if (d.version !== void 0) {
5385
5420
  if (!Number.isSafeInteger(d.version) || d.version < 1) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
5386
- const sourceKey = key(d.scopeId, "source", d.sourceId), prior = this.deletionVersions.get(sourceKey);
5421
+ const sourceKey = key2(d.scopeId, "source", d.sourceId), prior = this.deletionVersions.get(sourceKey);
5387
5422
  if (prior !== void 0 && prior !== d.version) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
5388
5423
  this.deletionVersions.set(sourceKey, d.version);
5389
5424
  }
@@ -5398,7 +5433,7 @@ var init_recovery_deletion = __esm({
5398
5433
  links(table, row) {
5399
5434
  const scope = text(row, "scope_id");
5400
5435
  if (!scope) return { owners: [], parents: [] };
5401
- const node = (kind2, id3) => id3 ? [key(scope, kind2, id3)] : [];
5436
+ const node = (kind2, id3) => id3 ? [key2(scope, kind2, id3)] : [];
5402
5437
  const source = text(row, "source_id"), fact = text(row, "assertion_id");
5403
5438
  const artifact = text(row, "artifact_id") ?? text(row, "child_id") ?? text(row, "entry_id");
5404
5439
  const owners = fact ? node("fact", fact) : artifact ? node("artifact", artifact) : source ? node("source", source) : node("entity", text(row, "entity_id"));
@@ -5422,19 +5457,19 @@ var init_recovery_deletion = __esm({
5422
5457
  if (!ref || typeof ref !== "object") continue;
5423
5458
  const refScope = typeof ref.scopeId === "string" ? ref.scopeId : typeof ref.scope_id === "string" ? ref.scope_id : scope;
5424
5459
  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"]]) {
5425
- if (typeof ref[field2] === "string") parents.push(key(refScope, kind2, ref[field2]));
5460
+ if (typeof ref[field2] === "string") parents.push(key2(refScope, kind2, ref[field2]));
5426
5461
  }
5427
- if (typeof ref.parentId === "string" && ["source", "fact", "entity", "artifact"].includes(ref.parentKind)) parents.push(key(refScope, ref.parentKind, ref.parentId));
5462
+ if (typeof ref.parentId === "string" && ["source", "fact", "entity", "artifact"].includes(ref.parentKind)) parents.push(key2(refScope, ref.parentKind, ref.parentId));
5428
5463
  pending.push(...Object.values(ref).filter((value) => value && typeof value === "object"));
5429
5464
  }
5430
5465
  }
5431
5466
  if (table === "memory_knowledge_history") {
5432
5467
  const kind2 = text(row, "target_kind"), target = text(row, "target_id");
5433
- if (kind2 === "source" && target) parents.push(key(scope, "source", target));
5468
+ if (kind2 === "source" && target) parents.push(key2(scope, "source", target));
5434
5469
  if (kind2?.startsWith("artifact.") && target) {
5435
5470
  try {
5436
5471
  const parts = JSON.parse(target);
5437
- if (Array.isArray(parts) && typeof parts[1] === "string") parents.push(key(scope, "artifact", parts[1]));
5472
+ if (Array.isArray(parts) && typeof parts[1] === "string") parents.push(key2(scope, "artifact", parts[1]));
5438
5473
  } catch {
5439
5474
  }
5440
5475
  }
@@ -5442,7 +5477,7 @@ var init_recovery_deletion = __esm({
5442
5477
  if (table === "memory_sources" && source) {
5443
5478
  const origin = text(row, "origin_key");
5444
5479
  if (origin) {
5445
- const originNode = key(scope, "origin", origin), sourceNode = key(scope, "source", source);
5480
+ const originNode = key2(scope, "origin", origin), sourceNode = key2(scope, "source", source);
5446
5481
  this.edge(sourceNode, originNode);
5447
5482
  this.edge(originNode, sourceNode);
5448
5483
  const version = row.source_version?.[0] === "integer" ? Number(row.source_version[1]) : void 0;
@@ -5452,15 +5487,15 @@ var init_recovery_deletion = __esm({
5452
5487
  if (deletion.version === void 0) continue;
5453
5488
  if (!Number.isSafeInteger(deletion.version) || deletion.version < 1) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
5454
5489
  if (++this.deletionChecks > 1e6) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
5455
- if (recoveryOriginalSourceId(scope, origin, deletion.version) === deletion.sourceId) this.edge(key(scope, "source", deletion.sourceId), originNode);
5490
+ if (recoveryOriginalSourceId(scope, origin, deletion.version) === deletion.sourceId) this.edge(key2(scope, "source", deletion.sourceId), originNode);
5456
5491
  }
5457
5492
  this.familyProofs.add(originNode);
5458
5493
  }
5459
- if (text(row, "interpretation_status") === "deleted") this.roots.add(key(scope, "source", source));
5494
+ if (text(row, "interpretation_status") === "deleted") this.roots.add(key2(scope, "source", source));
5460
5495
  }
5461
5496
  if (table === "memory_tombstones") {
5462
5497
  const target = text(row, "target_id"), kind2 = text(row, "target_kind");
5463
- if (target && kind2) this.roots.add(key(scope, kind2, target));
5498
+ if (target && kind2) this.roots.add(key2(scope, kind2, target));
5464
5499
  }
5465
5500
  return { owners, parents };
5466
5501
  }
@@ -5868,9 +5903,9 @@ ALTER TABLE memory_host_turns ADD COLUMN owner_id TEXT;
5868
5903
  }
5869
5904
  }
5870
5905
  recordCompleted(id3, sourceId, sourceVersion, now2) {
5871
- const key2 = JSON.stringify(["host.turn.completed", id3, sourceId]);
5906
+ const key4 = JSON.stringify(["host.turn.completed", id3, sourceId]);
5872
5907
  this.db.prepare(`INSERT OR IGNORE INTO ome_jobs(kind,payload,status,next_run_at,created_at,job_key,scope_id,completed_at)
5873
- VALUES ('host.turn.completed',?,'done',?,?,?,?,?)`).run(JSON.stringify({ scopeId: id3, sourceId, sourceVersion }), now2, now2, key2, id3, now2);
5908
+ VALUES ('host.turn.completed',?,'done',?,?,?,?,?)`).run(JSON.stringify({ scopeId: id3, sourceId, sourceVersion }), now2, now2, key4, id3, now2);
5874
5909
  }
5875
5910
  };
5876
5911
  }
@@ -6498,7 +6533,7 @@ function recoverLegacySession(db2, store, mapping, files, apply = false) {
6498
6533
  return report;
6499
6534
  }
6500
6535
  function recoverLegacyProjections(db2, store, input, apply = false) {
6501
- const key2 = scopeId(input.scope);
6536
+ const key4 = scopeId(input.scope);
6502
6537
  const root = realpathSync3(input.root);
6503
6538
  const report = { files: 0, entries: 0, recoverable: 0, alreadyMapped: 0, unavailable: 0, reasons: {}, applied: false };
6504
6539
  const gap = (reason) => {
@@ -6543,7 +6578,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6543
6578
  const block = match[0];
6544
6579
  const field = (name) => match[2].match(new RegExp(`^\\*\\*${name}\\*\\*: ([^\\n]*)$`, "m"))?.[1]?.trim();
6545
6580
  const parent = field("parent_id");
6546
- const mapping = db2.prepare("SELECT * FROM memory_legacy_cell_maps WHERE cell_id=? AND scope_id=?").get(parent ?? "", key2);
6581
+ const mapping = db2.prepare("SELECT * FROM memory_legacy_cell_maps WHERE cell_id=? AND scope_id=?").get(parent ?? "", key4);
6547
6582
  if (!mapping || field("parent_type") !== "memcell" || field("owner_id") !== input.scope.ownerId || field("session_id") !== mapping.session_id) {
6548
6583
  gap("projection_parent_provenance_missing");
6549
6584
  continue;
@@ -6560,7 +6595,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6560
6595
  gap("projection_body_missing");
6561
6596
  continue;
6562
6597
  }
6563
- const previous = db2.prepare("SELECT * FROM memory_legacy_projection_maps WHERE scope_id=? AND kind=? AND entry_id=?").get(key2, kind, match[1]);
6598
+ const previous = db2.prepare("SELECT * FROM memory_legacy_projection_maps WHERE scope_id=? AND kind=? AND entry_id=?").get(key4, kind, match[1]);
6564
6599
  const target = join9(store.mem7RootPath(), path35);
6565
6600
  if (previous) {
6566
6601
  if (previous.source_file_hash !== fileHash || previous.parent_id !== parent || previous.source_relative_path !== path35 || !store.projectionMatches(input.scope, kind, match[1], target, block)) {
@@ -6612,7 +6647,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6612
6647
  role: "supports"
6613
6648
  })));
6614
6649
  const digest7 = hash4(candidate.block.trim());
6615
- db2.prepare("INSERT INTO memory_projection_entries VALUES (?,?,?,?,?,?)").run(key2, candidate.kind, candidate.id, candidate.relativePath, 1, digest7);
6650
+ db2.prepare("INSERT INTO memory_projection_entries VALUES (?,?,?,?,?,?)").run(key4, candidate.kind, candidate.id, candidate.relativePath, 1, digest7);
6616
6651
  store.artifacts.publish(input.scope, {
6617
6652
  kind: candidate.kind,
6618
6653
  id: candidate.id,
@@ -6624,7 +6659,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6624
6659
  summary: candidate.summary,
6625
6660
  title: candidate.title
6626
6661
  });
6627
- db2.prepare("INSERT INTO memory_legacy_projection_maps VALUES (?,?,?,?,?,?,?)").run(key2, candidate.kind, candidate.id, candidate.fileHash, candidate.relativePath, candidate.parent, 1);
6662
+ db2.prepare("INSERT INTO memory_legacy_projection_maps VALUES (?,?,?,?,?,?,?)").run(key4, candidate.kind, candidate.id, candidate.fileHash, candidate.relativePath, candidate.parent, 1);
6628
6663
  }
6629
6664
  });
6630
6665
  report.applied = true;
@@ -6756,10 +6791,10 @@ var init_recall_sources = __esm({
6756
6791
  }
6757
6792
  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}`);
6758
6793
  for (let index = 0; index < queue.length; index++) {
6759
- const key2 = queue[index];
6760
- if (this.removed.has(key2)) continue;
6761
- this.removed.add(key2);
6762
- queue.push(...dependents.get(key2) ?? []);
6794
+ const key4 = queue[index];
6795
+ if (this.removed.has(key4)) continue;
6796
+ this.removed.add(key4);
6797
+ queue.push(...dependents.get(key4) ?? []);
6763
6798
  }
6764
6799
  }
6765
6800
  sources = /* @__PURE__ */ new Map();
@@ -6934,9 +6969,9 @@ CREATE TABLE memory_person_mentions (
6934
6969
  ])];
6935
6970
  if (ids.length > 8192 || this.snapshot.relationships.size > 8192) return result;
6936
6971
  const sourceIds = JSON.stringify(ids.sort());
6937
- const relationshipRefs = JSON.stringify([...this.snapshot.relationships.keys()].sort().map((key2) => {
6938
- const split = key2.lastIndexOf(":");
6939
- return [key2.slice(0, split), Number(key2.slice(split + 1))];
6972
+ const relationshipRefs = JSON.stringify([...this.snapshot.relationships.keys()].sort().map((key4) => {
6973
+ const split = key4.lastIndexOf(":");
6974
+ return [key4.slice(0, split), Number(key4.slice(split + 1))];
6940
6975
  }));
6941
6976
  this.snapshotBasis = this.readProvenanceBasis(this.snapshot, sourceIds, relationshipRefs);
6942
6977
  }
@@ -6984,19 +7019,19 @@ CREATE TABLE memory_person_mentions (
6984
7019
  const sourceChecks = new Map(sources.map((row) => [row.id, JSON.stringify(row)]));
6985
7020
  const relationshipRows = /* @__PURE__ */ new Map();
6986
7021
  for (const row of relationships) {
6987
- const key2 = `${row.id}:${row.version}`;
6988
- const rows = relationshipRows.get(key2) ?? [];
7022
+ const key4 = `${row.id}:${row.version}`;
7023
+ const rows = relationshipRows.get(key4) ?? [];
6989
7024
  rows.push(row);
6990
- relationshipRows.set(key2, rows);
7025
+ relationshipRows.set(key4, rows);
6991
7026
  }
6992
- const relationshipChecks = new Map([...relationshipRows].map(([key2, rows]) => [key2, createHash15("sha256").update(JSON.stringify(rows)).digest("hex")]));
7027
+ const relationshipChecks = new Map([...relationshipRows].map(([key4, rows]) => [key4, createHash15("sha256").update(JSON.stringify(rows)).digest("hex")]));
6993
7028
  checkMemoryReadBudget();
6994
7029
  return { sourceIds, relationshipRefs, digest: digest7, sources: sourceChecks, relationships: relationshipChecks };
6995
7030
  }
6996
7031
  provenanceSnapshot(scope, cutoff) {
6997
7032
  const stamp = this.provenanceStamp();
6998
- const key2 = JSON.stringify([scopeId(scope), cutoff ?? null]);
6999
- if (stamp !== this.snapshotStamp && this.snapshot?.key === key2 && !cutoff && this.snapshotBasis && this.readSnapshotDepth && this.snapshot.sources.size <= 8192) {
7033
+ const key4 = JSON.stringify([scopeId(scope), cutoff ?? null]);
7034
+ if (stamp !== this.snapshotStamp && this.snapshot?.key === key4 && !cutoff && this.snapshotBasis && this.readSnapshotDepth && this.snapshot.sources.size <= 8192) {
7000
7035
  const previous = this.snapshotBasis;
7001
7036
  const next = this.readProvenanceBasis(this.snapshot, previous.sourceIds, previous.relationshipRefs);
7002
7037
  if (next.digest !== previous.digest) {
@@ -7008,17 +7043,17 @@ CREATE TABLE memory_person_mentions (
7008
7043
  this.snapshot.metadata.delete(id3);
7009
7044
  this.snapshot.currentSources.delete(id3);
7010
7045
  }
7011
- for (const [key3, check] of previous.relationships) {
7012
- if (next.relationships.get(key3) !== check) this.snapshot.relationships.delete(key3);
7046
+ for (const [key5, check] of previous.relationships) {
7047
+ if (next.relationships.get(key5) !== check) this.snapshot.relationships.delete(key5);
7013
7048
  }
7014
7049
  }
7015
7050
  this.snapshotBasis = next;
7016
7051
  this.snapshotStamp = stamp;
7017
7052
  }
7018
- if (stamp !== this.snapshotStamp || this.snapshot?.key !== key2 || this.snapshot.sources.size > 8192 || this.snapshot.currentSources.size > 8192 || this.snapshot.relationships.size > 8192) {
7053
+ if (stamp !== this.snapshotStamp || this.snapshot?.key !== key4 || this.snapshot.sources.size > 8192 || this.snapshot.currentSources.size > 8192 || this.snapshot.relationships.size > 8192) {
7019
7054
  this.snapshotStamp = stamp;
7020
7055
  this.snapshotBasis = void 0;
7021
- 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() };
7056
+ 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() };
7022
7057
  }
7023
7058
  return this.snapshot;
7024
7059
  }
@@ -7149,21 +7184,21 @@ CREATE TABLE memory_person_mentions (
7149
7184
  provenanceReferenceRetained(scope, ref, visited, cutoff, snapshot) {
7150
7185
  checkMemoryReadBudget(visited.size);
7151
7186
  if (ref.scopeId !== scopeId(scope) || visited.has(ref.sourceId) || ref.relationshipId && visited.has(`${ref.relationshipId}:${ref.semanticVersion}`)) return false;
7152
- const key2 = `reference:${JSON.stringify([ref.sourceId, ref.sourceVersion, ref.relationshipId, ref.semanticVersion])}`;
7153
- if (snapshot.memo.has(key2)) return snapshot.memo.get(key2);
7187
+ const key4 = `reference:${JSON.stringify([ref.sourceId, ref.sourceVersion, ref.relationshipId, ref.semanticVersion])}`;
7188
+ if (snapshot.memo.has(key4)) return snapshot.memo.get(key4);
7154
7189
  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);
7155
- snapshot.memo.set(key2, retained);
7190
+ snapshot.memo.set(key4, retained);
7156
7191
  return retained;
7157
7192
  }
7158
7193
  /** Authored thoughts remain historical memories when a cited source is corrected; deletion still wins. */
7159
7194
  provenanceRetained(scope, sourceId, visited, cutoff, snapshot) {
7160
7195
  checkMemoryReadBudget(visited.size);
7161
7196
  if (visited.has(sourceId)) return false;
7162
- const key2 = `source:${sourceId}`;
7197
+ const key4 = `source:${sourceId}`;
7163
7198
  const { memo } = snapshot;
7164
- if (memo.has(key2)) return memo.get(key2);
7199
+ if (memo.has(key4)) return memo.get(key4);
7165
7200
  if (!this.provenanceSource(scope, sourceId, cutoff, snapshot) || this.tombstoneRead.get(scopeId(scope), sourceId)) {
7166
- memo.set(key2, false);
7201
+ memo.set(key4, false);
7167
7202
  return false;
7168
7203
  }
7169
7204
  if (!snapshot.metadata.has(sourceId)) snapshot.metadata.set(sourceId, this.metadata(scope, sourceId));
@@ -7172,7 +7207,7 @@ CREATE TABLE memory_person_mentions (
7172
7207
  try {
7173
7208
  const check = (ref) => this.provenanceReferenceRetained(scope, ref, visited, cutoff, snapshot);
7174
7209
  const retained = !metadata2 || metadata2.contextRefs.every(check) && metadata2.basisRefs.every(check);
7175
- memo.set(key2, retained);
7210
+ memo.set(key4, retained);
7176
7211
  return retained;
7177
7212
  } finally {
7178
7213
  visited.delete(sourceId);
@@ -7206,10 +7241,10 @@ CREATE TABLE memory_person_mentions (
7206
7241
  sourceGroundsCurrent(scope, sourceId, visited, cutoff, snapshot) {
7207
7242
  checkMemoryReadBudget(visited.size);
7208
7243
  if (visited.has(sourceId)) return false;
7209
- const key2 = `source:${sourceId}`;
7210
- if (snapshot.grounds.has(key2)) return snapshot.grounds.get(key2);
7244
+ const key4 = `source:${sourceId}`;
7245
+ if (snapshot.grounds.has(key4)) return snapshot.grounds.get(key4);
7211
7246
  if (!this.sourceCurrent(scope, sourceId, cutoff, snapshot) || !this.provenanceRetained(scope, sourceId, /* @__PURE__ */ new Set(), cutoff, snapshot)) {
7212
- snapshot.grounds.set(key2, false);
7247
+ snapshot.grounds.set(key4, false);
7213
7248
  return false;
7214
7249
  }
7215
7250
  if (!snapshot.metadata.has(sourceId)) snapshot.metadata.set(sourceId, this.metadata(scope, sourceId));
@@ -7217,7 +7252,7 @@ CREATE TABLE memory_person_mentions (
7217
7252
  visited.add(sourceId);
7218
7253
  try {
7219
7254
  const current2 = !metadata2 || metadata2.basisRefs.every((ref) => this.currentReference(scope, ref, visited, cutoff, snapshot));
7220
- snapshot.grounds.set(key2, current2);
7255
+ snapshot.grounds.set(key4, current2);
7221
7256
  return current2;
7222
7257
  } finally {
7223
7258
  visited.delete(sourceId);
@@ -7227,46 +7262,46 @@ CREATE TABLE memory_person_mentions (
7227
7262
  checkMemoryReadBudget(visited.size);
7228
7263
  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;
7229
7264
  if (!ref.relationshipId) return true;
7230
- const key2 = `${ref.relationshipId}:${ref.semanticVersion}`;
7231
- if (visited.has(key2)) return false;
7232
- const memoKey = `relationship:${key2}:${ref.purpose === "historical" ? "historical" : "current"}`;
7265
+ const key4 = `${ref.relationshipId}:${ref.semanticVersion}`;
7266
+ if (visited.has(key4)) return false;
7267
+ const memoKey = `relationship:${key4}:${ref.purpose === "historical" ? "historical" : "current"}`;
7233
7268
  if (snapshot.grounds.has(memoKey)) return snapshot.grounds.get(memoKey);
7234
- if (!snapshot.relationships.has(key2)) {
7269
+ if (!snapshot.relationships.has(key4)) {
7235
7270
  this.snapshotBasis = void 0;
7236
- snapshot.relationships.set(key2, this.relationshipReferenceMaterial(scope, ref, cutoff));
7271
+ snapshot.relationships.set(key4, this.relationshipReferenceMaterial(scope, ref, cutoff));
7237
7272
  }
7238
- const material = snapshot.relationships.get(key2);
7273
+ const material = snapshot.relationships.get(key4);
7239
7274
  if (!material || ["deleted", "retracted"].includes(material.state) || ref.purpose !== "historical" && !material.current) return false;
7240
- visited.add(key2);
7275
+ visited.add(key4);
7241
7276
  try {
7242
7277
  const current2 = material.evidenceSourceIds.every((id3) => this.sourceGroundsCurrent(scope, id3, visited, cutoff, snapshot)) && material.basisRefs.every((basis) => this.currentReference(scope, basis, visited, cutoff, snapshot));
7243
7278
  snapshot.grounds.set(memoKey, current2);
7244
7279
  return current2;
7245
7280
  } finally {
7246
- visited.delete(key2);
7281
+ visited.delete(key4);
7247
7282
  }
7248
7283
  }
7249
7284
  relationshipReferenceRetained(scope, ref, visited, cutoff, snapshot = this.provenanceSnapshot(scope, cutoff)) {
7250
7285
  checkMemoryReadBudget(visited.size);
7251
7286
  if (!ref.relationshipId) return true;
7252
- const key2 = `${ref.relationshipId}:${ref.semanticVersion}`;
7253
- if (visited.has(key2)) return false;
7254
- const memoKey = `relationship:${key2}`;
7287
+ const key4 = `${ref.relationshipId}:${ref.semanticVersion}`;
7288
+ if (visited.has(key4)) return false;
7289
+ const memoKey = `relationship:${key4}`;
7255
7290
  const { memo } = snapshot;
7256
7291
  if (memo.has(memoKey)) return memo.get(memoKey);
7257
- if (!snapshot.relationships.has(key2)) {
7292
+ if (!snapshot.relationships.has(key4)) {
7258
7293
  this.snapshotBasis = void 0;
7259
- snapshot.relationships.set(key2, this.relationshipReferenceMaterial(scope, ref, cutoff));
7294
+ snapshot.relationships.set(key4, this.relationshipReferenceMaterial(scope, ref, cutoff));
7260
7295
  }
7261
- const material = snapshot.relationships.get(key2);
7296
+ const material = snapshot.relationships.get(key4);
7262
7297
  if (!material) return false;
7263
- visited.add(key2);
7298
+ visited.add(key4);
7264
7299
  try {
7265
7300
  const retained = material.evidenceSourceIds.every((id3) => this.provenanceRetained(scope, id3, visited, cutoff, snapshot)) && material.basisRefs.every((basis) => this.provenanceReferenceRetained(scope, basis, visited, cutoff, snapshot));
7266
7301
  memo.set(memoKey, retained);
7267
7302
  return retained;
7268
7303
  } finally {
7269
- visited.delete(key2);
7304
+ visited.delete(key4);
7270
7305
  }
7271
7306
  }
7272
7307
  relationshipReferenceMaterial(scope, ref, cutoff) {
@@ -7713,16 +7748,16 @@ CREATE TABLE memory_relationship_receipts (
7713
7748
  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);
7714
7749
  if (!row) return null;
7715
7750
  if (historicalVersion) Object.assign(row, historicalVersion);
7716
- const key2 = `${relationshipId}:${row.semantic_version}`;
7717
- if (visited.has(key2)) return null;
7718
- const next = new Set(visited).add(key2);
7751
+ const key4 = `${relationshipId}:${row.semantic_version}`;
7752
+ if (visited.has(key4)) return null;
7753
+ const next = new Set(visited).add(key4);
7719
7754
  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 }));
7720
7755
  const basisRefs = JSON.parse(row.basis_refs);
7721
7756
  const refs = [...evidence.map((ref) => ({ sourceId: ref.sourceId })), ...basisRefs];
7722
7757
  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;
7723
7758
  const value = JSON.parse(row.value_json);
7724
7759
  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;
7725
- 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));
7760
+ 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));
7726
7761
  return {
7727
7762
  relationshipId,
7728
7763
  semanticVersion: row.semantic_version,
@@ -8047,15 +8082,15 @@ var init_cutoff = __esm({
8047
8082
  // src/continuity/runtime-replication.ts
8048
8083
  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";
8049
8084
  import { basename as basename2, dirname as dirname5, join as join11, resolve as resolve5 } from "node:path";
8050
- function checkKey(component, key2) {
8051
- if (component === "topics-vectors" && typeof key2 === "string" && /^[a-f0-9]{64}$/.test(key2)) return;
8052
- 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;
8053
- if (["calendar", "proactive", "session-events"].includes(component) && key2 === void 0) return;
8085
+ function checkKey(component, key4) {
8086
+ if (component === "topics-vectors" && typeof key4 === "string" && /^[a-f0-9]{64}$/.test(key4)) return;
8087
+ 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;
8088
+ if (["calendar", "proactive", "session-events"].includes(component) && key4 === void 0) return;
8054
8089
  throw new Error("REPLICATION_REGISTRATION_INVALID");
8055
8090
  }
8056
- function location2(stateDir, component, key2) {
8057
- checkKey(component, key2);
8058
- return join11(stateDir, ".continuity", component + (key2 === void 0 ? "" : "-" + key2) + "-replication.json");
8091
+ function location2(stateDir, component, key4) {
8092
+ checkKey(component, key4);
8093
+ return join11(stateDir, ".continuity", component + (key4 === void 0 ? "" : "-" + key4) + "-replication.json");
8059
8094
  }
8060
8095
  function normalize3(input) {
8061
8096
  if (!input || !/^[a-f0-9]{64}$/.test(input.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
@@ -8066,8 +8101,8 @@ function directory(path35) {
8066
8101
  if (!info.isDirectory() || info.isSymbolicLink() || realpathSync4(path35) !== resolve5(path35) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
8067
8102
  throw new Error("REPLICATION_REGISTRATION_INVALID");
8068
8103
  }
8069
- function readRuntimeReplicationRegistration(stateDir, component, key2) {
8070
- const file2 = location2(stateDir, component, key2);
8104
+ function readRuntimeReplicationRegistration(stateDir, component, key4) {
8105
+ const file2 = location2(stateDir, component, key4);
8071
8106
  try {
8072
8107
  lstatSync6(dirname5(file2));
8073
8108
  } catch (error) {
@@ -8130,8 +8165,8 @@ function checkRuntimeReplicationDatabase(db2, registration, component, version,
8130
8165
  }
8131
8166
  return requested ?? registration?.binding;
8132
8167
  }
8133
- function enrollRuntimeReplication(db2, stateDir, component, binding, key2) {
8134
- const file2 = location2(stateDir, component, key2), old = readRuntimeReplicationRegistration(stateDir, component, key2);
8168
+ function enrollRuntimeReplication(db2, stateDir, component, binding, key4) {
8169
+ const file2 = location2(stateDir, component, key4), old = readRuntimeReplicationRegistration(stateDir, component, key4);
8135
8170
  const version = readSchemaVersion(db2);
8136
8171
  if (version?.component !== component) throw new Error("REPLICATION_SCHEMA_MISMATCH");
8137
8172
  checkRuntimeReplicationDatabase(db2, old, component, version.version, binding);
@@ -8144,7 +8179,7 @@ function enrollRuntimeReplication(db2, stateDir, component, binding, key2) {
8144
8179
  writeFileSync5(file2, JSON.stringify(input), { mode: 384, flag: "wx", flush: true });
8145
8180
  } catch (error) {
8146
8181
  if (error.code !== "EEXIST") throw error;
8147
- if (JSON.stringify(readRuntimeReplicationRegistration(stateDir, component, key2)) !== JSON.stringify(input)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
8182
+ if (JSON.stringify(readRuntimeReplicationRegistration(stateDir, component, key4)) !== JSON.stringify(input)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
8148
8183
  }
8149
8184
  if (process.platform !== "win32") {
8150
8185
  const fd = openSync6(dirname5(file2), "r");
@@ -8578,10 +8613,10 @@ CREATE TABLE memory_relationship_cognition_results (
8578
8613
  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)] : []);
8579
8614
  const groups = /* @__PURE__ */ new Map();
8580
8615
  for (const row of rows) {
8581
- const key2 = canonicalJson([row.scope_id, row.perspective_entity_id, row.group_key, row.generation]);
8582
- const group = groups.get(key2) || { scopeId: row.scope_id, perspectiveEntityId: row.perspective_entity_id, groupKey: row.group_key, sourceIds: [], generation: row.generation };
8616
+ const key4 = canonicalJson([row.scope_id, row.perspective_entity_id, row.group_key, row.generation]);
8617
+ const group = groups.get(key4) || { scopeId: row.scope_id, perspectiveEntityId: row.perspective_entity_id, groupKey: row.group_key, sourceIds: [], generation: row.generation };
8583
8618
  if (group.sourceIds.length < 20) group.sourceIds.push(row.source_id);
8584
- groups.set(key2, group);
8619
+ groups.set(key4, group);
8585
8620
  }
8586
8621
  return [...groups.values()];
8587
8622
  }
@@ -8771,9 +8806,9 @@ var init_entities = __esm({
8771
8806
  aliasEvidence(scope, entityId, cutoff) {
8772
8807
  const seen = /* @__PURE__ */ new Set();
8773
8808
  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) => {
8774
- const key2 = normalizeAlias(alias.alias);
8775
- 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;
8776
- seen.add(key2);
8809
+ const key4 = normalizeAlias(alias.alias);
8810
+ 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;
8811
+ seen.add(key4);
8777
8812
  return true;
8778
8813
  }).map((alias) => ({ alias: alias.alias, sourceId: alias.sourceId, sourceVersion: this.sources.get(scope, alias.sourceId, cutoff).sourceVersion }));
8779
8814
  }
@@ -8972,12 +9007,12 @@ function checkNotice(db2, sources, social, scope, id3, options) {
8972
9007
  return Boolean(source && (version === void 0 || source.sourceVersion === version) && social.readable(memoryScope, sourceId) && social.groundsCurrent(memoryScope, sourceId));
8973
9008
  };
8974
9009
  const relationshipCurrent = (relationshipId, version) => {
8975
- const key2 = `${relationshipId}:${version}`;
9010
+ const key4 = `${relationshipId}:${version}`;
8976
9011
  const row = db2.prepare(`SELECT r.*,v.state FROM memory_relationship_versions r JOIN fact_versions v
8977
9012
  ON v.scope_id=r.scope_id AND v.assertion_id=r.assertion_id AND v.system_to_revision IS NULL
8978
9013
  WHERE r.scope_id=? AND r.relationship_id=? AND r.semantic_version=?`).get(scope, relationshipId, version);
8979
9014
  if (!row || ["deleted", "retracted"].includes(row.state)) return false;
8980
- const derivation = db2.prepare("SELECT state FROM memory_derivations WHERE scope_id=? AND child_kind='relationship' AND child_id=?").get(scope, key2);
9015
+ const derivation = db2.prepare("SELECT state FROM memory_derivations WHERE scope_id=? AND child_kind='relationship' AND child_id=?").get(scope, key4);
8981
9016
  if (derivation && derivation.state !== "current") return false;
8982
9017
  const evidence = db2.prepare("SELECT source_id FROM fact_evidence WHERE scope_id=? AND assertion_id=?").all(scope, row.assertion_id);
8983
9018
  return evidence.length > 0 && evidence.every((ref) => sourceCurrent(ref.source_id)) && JSON.parse(row.basis_refs).every((ref) => social.referenceCurrent(memoryScope, ref));
@@ -9052,8 +9087,11 @@ CREATE TABLE memory_relationship_notice_versions (
9052
9087
  }
9053
9088
  get(scope, id3) {
9054
9089
  const row = this.db.prepare("SELECT * FROM memory_relationship_notices WHERE scope_id=? AND notice_id=?").get(scopeId(scope), id3);
9055
- return row ? {
9056
- id: id3,
9090
+ return row ? this.decode(scope, row) : null;
9091
+ }
9092
+ decode(scope, row) {
9093
+ return {
9094
+ id: row.notice_id,
9057
9095
  scope,
9058
9096
  kind: row.kind,
9059
9097
  targetId: row.target_id,
@@ -9063,10 +9101,25 @@ CREATE TABLE memory_relationship_notice_versions (
9063
9101
  state: row.state,
9064
9102
  attempts: row.attempts,
9065
9103
  reason: row.reason
9066
- } : null;
9104
+ };
9067
9105
  }
9068
- list(scope) {
9069
- 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));
9106
+ list(scope, includeTerminal = true) {
9107
+ return this.db.prepare(`SELECT * FROM memory_relationship_notices WHERE scope_id=?
9108
+ ${includeTerminal ? "" : "AND state NOT IN ('delivered','blocked')"} ORDER BY updated_at,notice_id`).all(scopeId(scope)).map((row) => this.decode(scope, row));
9109
+ }
9110
+ /** Quiet identity work is not notification work. Evidence-backed resolved identities can still be withdrawn. */
9111
+ clarificationCandidates(scope) {
9112
+ const rows = this.db.prepare(`SELECT m.mention_id,m.question,m.mention_kind,m.candidates,m.span_start,m.span_end,s.text
9113
+ FROM memory_person_mentions m JOIN memory_sources s ON s.scope_id=m.scope_id AND s.source_id=m.source_id
9114
+ WHERE m.scope_id=? AND m.question IS NOT NULL AND trim(m.question)<>''
9115
+ AND (m.state='unresolved' OR m.clarification_source_id IS NOT NULL OR m.basis_refs<>'[]')
9116
+ AND (m.mention_kind NOT IN ('description','reference') OR json_array_length(m.candidates)>=2)
9117
+ ORDER BY m.source_id,m.span_start`).all(scopeId(scope));
9118
+ return rows.filter((row) => hasIdentityQuestion(
9119
+ row.question,
9120
+ row.text.slice(row.span_start, row.span_end),
9121
+ { mentionKind: row.mention_kind, candidateEntityIds: JSON.parse(row.candidates) }
9122
+ )).map((row) => row.mention_id);
9070
9123
  }
9071
9124
  finish(scope, id3, state, reason = "", redact = false) {
9072
9125
  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);
@@ -9077,6 +9130,12 @@ CREATE TABLE memory_relationship_notice_versions (
9077
9130
  check(scope, id3, options = {}) {
9078
9131
  return checkRelationshipNotice(this.db, scopeId(scope), id3, options);
9079
9132
  }
9133
+ /** The caller holds one transaction; proofs are discarded before any later batch or write. */
9134
+ checkMany(scope, ids, options = {}) {
9135
+ if (!ids.length) return [];
9136
+ const check = createRelationshipNoticeChecker(this.db);
9137
+ return ids.map((id3) => check(scopeId(scope), id3, options));
9138
+ }
9080
9139
  queue(scope, id3) {
9081
9140
  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);
9082
9141
  }
@@ -9088,6 +9147,7 @@ CREATE TABLE memory_relationship_notice_versions (
9088
9147
  importantRecords(scope) {
9089
9148
  return this.db.prepare(`SELECT v.relationship_id,v.semantic_version FROM memory_relationship_notice_versions v
9090
9149
  JOIN memory_relationship_cognition_results r ON r.scope_id=v.scope_id AND r.job_id=v.job_id
9150
+ 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
9091
9151
  WHERE v.scope_id=? AND r.important=1`).all(scopeId(scope)).map((row) => ({ relationshipId: row.relationship_id, semanticVersion: row.semantic_version }));
9092
9152
  }
9093
9153
  recordRoute(scope, sourceId, input) {
@@ -9155,9 +9215,9 @@ function installRelationshipHistory(db2) {
9155
9215
  FROM memory_scopes s WHERE EXISTS (SELECT 1 FROM memory_relationship_heads h WHERE h.scope_id=s.scope_id)
9156
9216
  OR EXISTS (SELECT 1 FROM memory_person_sources p WHERE p.scope_id=s.scope_id)
9157
9217
  OR EXISTS (SELECT 1 FROM memory_person_mentions m WHERE m.scope_id=s.scope_id)`);
9158
- for (const { table, kind, key: key2, columns: columns2 } of tables) {
9218
+ for (const { table, kind, key: key4, columns: columns2 } of tables) {
9159
9219
  const payload = (prefix2) => `json_object(${columns2.map((column) => `'${column}',${prefix2}${column}`).join(",")})`;
9160
- const target = (prefix2) => key2.startsWith("json_array") ? `json_array(${key2.slice(11, -1).split(",").map((column) => `${prefix2}${column}`).join(",")})` : `${prefix2}${key2}`;
9220
+ const target = (prefix2) => key4.startsWith("json_array") ? `json_array(${key4.slice(11, -1).split(",").map((column) => `${prefix2}${column}`).join(",")})` : `${prefix2}${key4}`;
9161
9221
  db2.exec(`INSERT INTO memory_knowledge_history(scope_id,target_kind,target_id,entity_revision,fact_revision,context_revision,recorded_at,payload_json)
9162
9222
  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.")}
9163
9223
  FROM ${table} t JOIN memory_scopes s ON s.scope_id=t.scope_id`);
@@ -9586,16 +9646,16 @@ var init_snapshot_reads = __esm({
9586
9646
  this.changes = -1;
9587
9647
  }
9588
9648
  }
9589
- read(key2, load) {
9649
+ read(key4, load) {
9590
9650
  if (!this.values || !this.db.isTransaction) return load();
9591
9651
  const changes = this.changesRead.get().n;
9592
9652
  if (changes !== this.changes) {
9593
9653
  this.values.clear();
9594
9654
  this.changes = changes;
9595
9655
  }
9596
- if (this.values.has(key2)) return this.values.get(key2);
9656
+ if (this.values.has(key4)) return this.values.get(key4);
9597
9657
  const value = load();
9598
- if (this.values.size < 8192) this.values.set(key2, value);
9658
+ if (this.values.size < 8192) this.values.set(key4, value);
9599
9659
  return value;
9600
9660
  }
9601
9661
  };
@@ -9721,7 +9781,7 @@ function classifyFactVersions(versions, predicate, time) {
9721
9781
  needsReview: disputed || hypotheses.some((fact) => fact.validFrom === null)
9722
9782
  };
9723
9783
  }
9724
- var hash6, makeSlotId, FactStore;
9784
+ var hash6, makeSlotId, CLOSE_VALIDITY, occurrences, CHANGE_KINDS, CLAIM_KINDS, normalizeChange, FactStore;
9725
9785
  var init_facts = __esm({
9726
9786
  "src/mem7/core/state/facts.ts"() {
9727
9787
  "use strict";
@@ -9733,6 +9793,15 @@ var init_facts = __esm({
9733
9793
  init_basis_check();
9734
9794
  hash6 = (value) => createHash18("sha256").update(canonicalJson(value)).digest("hex");
9735
9795
  makeSlotId = (subjectId, predicate, context) => `slot_${hash6([subjectId, predicate, context]).slice(0, 32)}`;
9796
+ CLOSE_VALIDITY = '{"validFrom":null,"validTo":"\u7ED3\u675F\u65F6\u523B","precision":"exact"}';
9797
+ occurrences = (text2, quote2) => {
9798
+ let count = 0;
9799
+ for (let at = text2.indexOf(quote2); quote2 && at >= 0; at = text2.indexOf(quote2, at + 1)) count++;
9800
+ return count;
9801
+ };
9802
+ CHANGE_KINDS = ["assert", "reinforce", "state_change", "correction", "exception", "dispute", "retract", "close"];
9803
+ CLAIM_KINDS = ["user_statement", "tool_observation", "reported_statement", "inference", "agent_statement"];
9804
+ normalizeChange = (proposal) => !["close", "retract"].includes(proposal.changeKind) || !proposal.validity || proposal.validity.validFrom !== void 0 ? proposal : { ...proposal, validity: { ...proposal.validity, validFrom: null } };
9736
9805
  FactStore = class {
9737
9806
  constructor(db2, entities, transaction, readTransaction = transaction) {
9738
9807
  this.db = db2;
@@ -9899,6 +9968,8 @@ var init_facts = __esm({
9899
9968
  applyChange(scope, proposal, expectedSlotRevision, requestKey, batch) {
9900
9969
  if (!requestKey || !Number.isSafeInteger(expectedSlotRevision) || expectedSlotRevision < 0) throw new Error("INVALID_FACT_REQUEST");
9901
9970
  const id3 = scopeId(scope);
9971
+ const located = this.locateEvidence(id3, normalizeChange(proposal));
9972
+ proposal = located.proposal;
9902
9973
  const requestHash = hash6([proposal, expectedSlotRevision]);
9903
9974
  const prior = this.db.prepare("SELECT request_hash,result_json FROM fact_changes WHERE scope_id=? AND request_key=?").get(id3, requestKey);
9904
9975
  if (prior) {
@@ -9907,21 +9978,22 @@ var init_facts = __esm({
9907
9978
  }
9908
9979
  this.validate(scope, proposal);
9909
9980
  const slot = this.slot(scope, proposal.subjectId, proposal.predicate, proposal.contextKey);
9910
- if (slot.revision !== expectedSlotRevision) throw new Error(`STALE_VERSION: expected slot ${expectedSlotRevision}, current ${slot.revision}`);
9981
+ 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` : ""));
9911
9982
  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);
9912
9983
  const before = this.current(id3, slot.slotId);
9913
9984
  const targetIds = [...new Set(proposal.targetAssertionIds ?? [])];
9914
9985
  const targets = targetIds.map((targetId) => {
9915
9986
  const target = before.find((fact) => fact.assertionId === targetId);
9916
- if (!target || ["retracted", "deleted"].includes(target.state)) throw new Error("FACT_TARGET_MISMATCH");
9987
+ 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`);
9917
9988
  return target;
9918
9989
  });
9919
- if (["reinforce", "state_change", "correction", "retract", "close"].includes(proposal.changeKind) && targets.length === 0) throw new Error("FACT_TARGET_REQUIRED");
9990
+ 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`);
9920
9991
  if (proposal.changeKind === "reinforce" && targets.length !== 1) throw new Error("REINFORCE_REQUIRES_ONE_TARGET");
9921
9992
  if (["assert", "exception"].includes(proposal.changeKind) && targets.length) throw new Error("UNEXPECTED_FACT_TARGET");
9922
9993
  const validity = proposal.validity ? normalizeValidity(proposal.validity) : void 0;
9923
- if (proposal.changeKind === "state_change" && (validity?.validFrom == null || validity.precision !== "exact")) throw new Error("CHANGE_TIME_REQUIRED");
9924
- if (proposal.changeKind === "close" && (validity?.validTo == null || validity.validFrom !== null || validity.precision === "unknown")) throw new Error("CHANGE_TIME_REQUIRED");
9994
+ const received2 = JSON.stringify({ validFrom: proposal.validity?.validFrom, validTo: proposal.validity?.validTo, precision: proposal.validity?.precision });
9995
+ 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"`);
9996
+ 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}`);
9925
9997
  if (proposal.changeKind === "reinforce" && (canonicalJson(proposal.value) !== canonicalJson(targets[0].value) || proposal.claimKind !== targets[0].claimKind)) throw new Error("REINFORCE_VALUE_MISMATCH");
9926
9998
  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");
9927
9999
  const timestamp = batch?.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
@@ -9937,8 +10009,8 @@ var init_facts = __esm({
9937
10009
  let state = proposal.changeKind === "correction" || proposal.changeKind === "retract" ? "retracted" : "disputed";
9938
10010
  if (proposal.changeKind === "state_change" || proposal.changeKind === "close") {
9939
10011
  const end = proposal.changeKind === "close" ? validity.validTo : validity.validFrom;
9940
- if (target.validFrom !== null && target.validFrom >= end) throw new Error("CHANGE_BEFORE_TARGET_START: use correction");
9941
- if (target.validTo !== null && target.validTo <= end) throw new Error("CHANGE_AFTER_TARGET_END");
10012
+ 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`);
10013
+ 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`);
9942
10014
  state = target.state;
9943
10015
  nextValidity = { ...target, validTo: end };
9944
10016
  }
@@ -9954,7 +10026,7 @@ var init_facts = __esm({
9954
10026
  }
9955
10027
  if (!["retract", "close"].includes(proposal.changeKind)) {
9956
10028
  let state = proposal.claimKind === "inference" ? "candidate" : proposal.changeKind === "dispute" ? "disputed" : "supported";
9957
- if (state === "supported" && !proposal.evidence.some((evidence) => evidence.relation === "supports")) throw new Error("SUPPORTING_EVIDENCE_REQUIRED");
10029
+ 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");
9958
10030
  const current2 = this.current(id3, slot.slotId);
9959
10031
  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");
9960
10032
  if (state === "supported" && validity.validFrom === null && !(proposal.predicate === "relation.open" && proposal.value.observedAsCurrentAt)) state = "candidate";
@@ -9986,7 +10058,8 @@ var init_facts = __esm({
9986
10058
  slotId: slot.slotId,
9987
10059
  slotRevision: slot.revision + Number(changed),
9988
10060
  assertionIds: changedIds,
9989
- outcome: !changed ? "no_change" : after.some((fact) => ["candidate", "disputed"].includes(fact.state) && (!isRelationship(proposal.predicate) || changedIds.includes(fact.assertionId))) ? "needs_review" : "applied"
10061
+ outcome: !changed ? "no_change" : after.some((fact) => ["candidate", "disputed"].includes(fact.state) && (!isRelationship(proposal.predicate) || changedIds.includes(fact.assertionId))) ? "needs_review" : "applied",
10062
+ ...located.aligned.length ? { evidenceAligned: located.aligned } : {}
9990
10063
  };
9991
10064
  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);
9992
10065
  if (changed) {
@@ -10025,21 +10098,31 @@ var init_facts = __esm({
10025
10098
  });
10026
10099
  }
10027
10100
  validate(scope, proposal) {
10028
- if (!Object.hasOwn(predicates, proposal.predicate)) throw new Error("UNKNOWN_PREDICATE");
10029
- 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");
10030
- if (proposal.claimKind === "inference" && (proposal.changeKind !== "assert" || proposal.targetAssertionIds?.length)) throw new Error("INFERENCE_CANNOT_REVISE_SUPPORTED_FACT");
10101
+ 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`);
10102
+ const invalid = [
10103
+ !CHANGE_KINDS.includes(proposal.changeKind) && "changeKind",
10104
+ !CLAIM_KINDS.includes(proposal.claimKind) && "claimKind",
10105
+ !proposal.contextKey && "contextKey",
10106
+ !proposal.reason && "reason",
10107
+ (!Array.isArray(proposal.evidence) || !proposal.evidence.length) && "evidence"
10108
+ ].filter(Boolean);
10109
+ 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`);
10110
+ 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");
10031
10111
  const subject = this.entities.get(scope, proposal.subjectId);
10032
- if (!subject || !matchesEntityKind(subject.kind, predicates[proposal.predicate].subjectKind)) throw new Error("ENTITY_SCOPE_MISMATCH");
10112
+ const subjectKind = predicates[proposal.predicate].subjectKind;
10113
+ 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}`);
10033
10114
  if (proposal.predicate === "relation.family" && !familyRoles.includes(proposal.contextKey)) throw new Error("INVALID_FAMILY_ROLE");
10034
10115
  if (proposal.predicate === "relation.colleague" && (proposal.contextKey !== normalizeOrganization(proposal.contextKey) || proposal.contextKey.length > 200)) throw new Error("INVALID_ORGANIZATION_CONTEXT");
10035
10116
  if (proposal.changeKind === "close") {
10036
- if (!isRelationship(proposal.predicate) || proposal.value !== void 0) throw new Error("INVALID_RELATION_CLOSE");
10037
- if (!proposal.validity) throw new Error("FACT_VALIDITY_REQUIRED");
10117
+ 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`);
10118
+ 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");
10119
+ if (!proposal.validity) throw new Error(`FACT_VALIDITY_REQUIRED: proposal.validity \u5FC5\u586B \u2014 close \u7528 ${CLOSE_VALIDITY}`);
10038
10120
  normalizeValidity(proposal.validity);
10039
10121
  }
10040
10122
  if (!["retract", "close"].includes(proposal.changeKind)) {
10123
+ 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`);
10041
10124
  validatePredicateValue(proposal.predicate, proposal.value);
10042
- if (!proposal.validity) throw new Error("FACT_VALIDITY_REQUIRED");
10125
+ 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"}');
10043
10126
  normalizeValidity(proposal.validity);
10044
10127
  const objectKind = predicates[proposal.predicate].objectKind;
10045
10128
  if (objectKind && !matchesEntityKind(this.entities.get(scope, proposal.value.entityId)?.kind, objectKind)) throw new Error("OBJECT_SCOPE_MISMATCH");
@@ -10054,7 +10137,7 @@ var init_facts = __esm({
10054
10137
  const targets = (proposal.targetAssertionIds ?? []).map((assertionId) => this.db.prepare(`SELECT a.claim_kind,a.value_json,s.subject_id
10055
10138
  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));
10056
10139
  const perspective = value?.relationshipId ? this.entities.get(scope, value.perspectiveEntityId) : subject;
10057
- 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");
10140
+ 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");
10058
10141
  }
10059
10142
  if (proposal.predicate === "activity.schedule" && proposal.changeKind !== "retract") {
10060
10143
  const schedule = proposal.value;
@@ -10062,26 +10145,53 @@ var init_facts = __esm({
10062
10145
  if (proposal.contextKey !== "baseline" && !exception) throw new Error("INVALID_SCHEDULE_CONTEXT");
10063
10146
  if ((exception || proposal.changeKind === "exception") && (!exception || schedule.frequency !== "once")) throw new Error("OCCURRENCE_EXCEPTION_REQUIRED");
10064
10147
  }
10065
- for (const evidence of proposal.evidence) {
10148
+ for (const [index, evidence] of proposal.evidence.entries()) {
10149
+ const path35 = `evidence[${index}]`;
10150
+ if (!evidence || typeof evidence !== "object") throw new Error(`INVALID_EVIDENCE_SPAN: ${path35} \u2014 \u6BCF\u6761\u8BC1\u636E\u987B\u662F\u5BF9\u8C61 {sourceId, quote, relation}`);
10066
10151
  const source = this.db.prepare(`SELECT text,role,origin_class,interpretation_status FROM memory_sources s WHERE scope_id=? AND source_id=?
10067
10152
  AND NOT EXISTS (SELECT 1 FROM memory_sources newer WHERE newer.scope_id=s.scope_id
10068
- AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)`).get(scopeId(scope), evidence.sourceId);
10069
- 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");
10153
+ AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)`).get(scopeId(scope), evidence.sourceId ?? null);
10154
+ 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`);
10155
+ 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`);
10156
+ 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) {
10157
+ const count = occurrences(source.text, evidence.quote);
10158
+ 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`);
10159
+ }
10160
+ 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`);
10070
10161
  const relationValue = proposal.value;
10071
10162
  if (proposal.predicate === "relation.open" && relationValue?.attribution === "reported" && (proposal.claimKind !== "reported_statement" || !hasReportedAttribution(source.text, relationValue, this.entities.sourceMentions(scope, evidence.sourceId)))) {
10072
- throw new Error("EVIDENCE_REPORTED_ATTRIBUTION_UNGROUNDED");
10163
+ 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");
10073
10164
  }
10165
+ 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`);
10074
10166
  if (proposal.claimKind !== "inference") {
10075
- if (proposal.claimKind === "user_statement" && (source.role !== "user" || !["host_user", "client_reported_user"].includes(source.origin_class))) throw new Error("EVIDENCE_ROLE_MISMATCH");
10076
- if (proposal.claimKind === "tool_observation" && (source.role !== "tool" || source.origin_class !== "tool_observation")) throw new Error("EVIDENCE_ROLE_MISMATCH");
10167
+ if (proposal.claimKind === "user_statement" && (source.role !== "user" || !["host_user", "client_reported_user"].includes(source.origin_class))) throw roleMismatch();
10168
+ if (proposal.claimKind === "tool_observation" && (source.role !== "tool" || source.origin_class !== "tool_observation")) throw roleMismatch();
10077
10169
  if (proposal.claimKind === "reported_statement" && (source.role !== "user" || !["third_party_report", "legacy_import"].includes(source.origin_class))) {
10078
10170
  const value = proposal.value;
10079
10171
  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));
10080
- if (!attributed) throw new Error("EVIDENCE_ROLE_MISMATCH");
10172
+ if (!attributed) throw roleMismatch();
10081
10173
  }
10082
- 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");
10083
- }
10084
- }
10174
+ 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();
10175
+ }
10176
+ }
10177
+ }
10178
+ /** 1124:UTF-16 下标不是人能数准的——引文在原文中只出现一次时,start/end 可省略或写错,由引擎对齐;没有或重复的留给 validate() 说明。 */
10179
+ locateEvidence(scope, proposal) {
10180
+ const aligned = [];
10181
+ if (!Array.isArray(proposal.evidence)) return { proposal, aligned };
10182
+ const evidence = proposal.evidence.map((ref, index) => {
10183
+ const text2 = this.db.prepare("SELECT text FROM memory_sources WHERE scope_id=? AND source_id=?").get(scope, ref?.sourceId ?? null)?.text;
10184
+ if (typeof text2 !== "string" || typeof ref?.quote !== "string" || !ref.quote || occurrences(text2, ref.quote) !== 1) return ref;
10185
+ const start = text2.indexOf(ref.quote);
10186
+ if (Number.isSafeInteger(ref.start) && ref.start === start && ref.end === start + ref.quote.length) return ref;
10187
+ aligned.push({
10188
+ index,
10189
+ given: [Number.isSafeInteger(ref.start) ? ref.start : null, Number.isSafeInteger(ref.end) ? ref.end : null],
10190
+ located: [start, start + ref.quote.length]
10191
+ });
10192
+ return { ...ref, start, end: start + ref.quote.length };
10193
+ });
10194
+ return { proposal: { ...proposal, evidence }, aligned };
10085
10195
  }
10086
10196
  current(scope, slotId) {
10087
10197
  return this.versions(scope, slotId);
@@ -10224,7 +10334,7 @@ function summary(input) {
10224
10334
  try {
10225
10335
  const p = JSON.parse(input);
10226
10336
  if (!p || typeof p !== "object" || Array.isArray(p)) return input;
10227
- const small = Object.fromEntries(Object.entries(p).filter(([key2, value]) => routing.has(key2) || Buffer.byteLength(JSON.stringify(value)) <= 1024));
10337
+ const small = Object.fromEntries(Object.entries(p).filter(([key4, value]) => routing.has(key4) || Buffer.byteLength(JSON.stringify(value)) <= 1024));
10228
10338
  if (!Object.hasOwn(small, "basis") && p.basis?.scope) small.basis = { scope: p.basis.scope };
10229
10339
  return JSON.stringify(small);
10230
10340
  } catch {
@@ -11783,10 +11893,10 @@ ${e.outcome}
11783
11893
  ];
11784
11894
  if (revalidationKinds.length === 0) return 0;
11785
11895
  for (const scope of this.sources.scopes()) {
11786
- const received = this.sources.interpretationProgress(scope).received;
11896
+ const received2 = this.sources.interpretationProgress(scope).received;
11787
11897
  for (const artifact of this.dependencies.dirty(scope)) {
11788
11898
  if (!revalidationKinds.includes(artifact.kind)) continue;
11789
- if (received > 0 && !(artifact.updatedAt !== null && Date.now() - artifact.updatedAt >= STALE_ARTIFACT_FORCE_MS)) continue;
11899
+ if (received2 > 0 && !(artifact.updatedAt !== null && Date.now() - artifact.updatedAt >= STALE_ARTIFACT_FORCE_MS)) continue;
11790
11900
  const previous = this.db.prepare("SELECT kind,payload FROM ome_jobs WHERE id=?").all(artifactGenerationJobId(this.db, scope, artifact.kind, artifact.id, artifact.version));
11791
11901
  for (const row of previous) {
11792
11902
  const payload = JSON.parse(row.payload);
@@ -12730,10 +12840,6 @@ var init_process_card = __esm({
12730
12840
  });
12731
12841
  return this.creation;
12732
12842
  }
12733
- /** Mode decisions can start native progress without awaiting any channel I/O. */
12734
- start() {
12735
- if (!this.ended && !this.started && (this.nativeCapable() || this.legacyCapable() || this.progressCapable())) this.beginInBackground();
12736
- }
12737
12843
  progressCapable() {
12738
12844
  return !!this.adapter.sendProgress && !!this.adapter.updateProgress && !!this.adapter.removeProgress;
12739
12845
  }
@@ -12874,8 +12980,7 @@ var init_process_card = __esm({
12874
12980
  }
12875
12981
  /** stream_event content_block_delta(thinking_delta):实时喂思考内容 */
12876
12982
  onThinkingDelta(chunk) {
12877
- if (!chunk || this.ended || this.disposed) return;
12878
- this.ensureStarted();
12983
+ if (!chunk || this.ended || this.disposed || !this.started) return;
12879
12984
  const lt = this.state.liveThink ??= { start: Date.now(), text: "" };
12880
12985
  lt.text += chunk;
12881
12986
  if (lt.text.length > 800) lt.text = lt.text.slice(-600);
@@ -12893,8 +12998,7 @@ var init_process_card = __esm({
12893
12998
  }
12894
12999
  /** assistant thinking 完整块(无增量流时的兜底;增量路径下与 Thought 行去重) */
12895
13000
  onThinking(text2) {
12896
- if (this.ended || this.disposed) return;
12897
- this.ensureStarted();
13001
+ if (this.ended || this.disposed || !this.started) return;
12898
13002
  if (this.state.liveThink) return;
12899
13003
  const last = this.state.rows[this.state.rows.length - 1];
12900
13004
  if (last?.kind === "think") return;
@@ -12906,10 +13010,10 @@ var init_process_card = __esm({
12906
13010
  const rid = this.nextRid("p");
12907
13011
  const preview = stripCardUnsafe(toolArgsSummary(toolName, input) || oneLine(JSON.stringify(input).slice(0, 200)));
12908
13012
  return new Promise((resolve13) => {
12909
- let settled = false;
13013
+ let settled2 = false;
12910
13014
  const settle = (v, message) => {
12911
- if (settled) return;
12912
- settled = true;
13015
+ if (settled2) return;
13016
+ settled2 = true;
12913
13017
  clearTimeout(timer);
12914
13018
  pendingPerms.delete(rid);
12915
13019
  this.currentPermRid = null;
@@ -12937,10 +13041,10 @@ var init_process_card = __esm({
12937
13041
  const rid = this.nextRid("q");
12938
13042
  const safeQ = questions.map((q) => ({ ...q, question: stripCardUnsafe(q.question), header: stripCardUnsafe(q.header), options: q.options.map((o) => ({ ...o, label: stripCardUnsafe(o.label) })) }));
12939
13043
  return new Promise((resolve13) => {
12940
- let settled = false;
13044
+ let settled2 = false;
12941
13045
  const settle = (answers, message) => {
12942
- if (settled) return;
12943
- settled = true;
13046
+ if (settled2) return;
13047
+ settled2 = true;
12944
13048
  clearTimeout(timer);
12945
13049
  pendingAsks.delete(rid);
12946
13050
  this.currentAskRid = null;
@@ -13031,7 +13135,7 @@ var init_process_card = __esm({
13031
13135
  return;
13032
13136
  }
13033
13137
  if (this.patchTimer) return;
13034
- const min = this.channelV === "cardkit" || this.channelV === "progress" ? CARDKIT_UPDATE_INTERVAL_MS : PATCH_MIN_INTERVAL_MS;
13138
+ const min = this.channelV === "cardkit" || this.channelV === "progress" ? this.adapter.progressThrottleMs ?? CARDKIT_UPDATE_INTERVAL_MS : PATCH_MIN_INTERVAL_MS;
13035
13139
  const wait2 = Math.max(0, min - (Date.now() - this.lastPatchAt));
13036
13140
  this.patchTimer = setTimeout(() => {
13037
13141
  this.patchTimer = null;
@@ -13046,10 +13150,6 @@ var init_process_card = __esm({
13046
13150
  await this.creation?.catch(() => {
13047
13151
  });
13048
13152
  if (this.disposed || this.ended && !final) return;
13049
- 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)) {
13050
- await this.removeCard().catch((error) => console.warn("[process-card] \u7A7A\u56DE\u5408\u6E05\u7406\u5931\u8D25:", error instanceof Error ? error.message : String(error)));
13051
- return;
13052
- }
13053
13153
  const pushed = await this.doPatch(final);
13054
13154
  if (final && !pushed && !this.disposed && this.options.sendSummary && !this.summarySent) {
13055
13155
  this.summarySent = true;
@@ -13073,8 +13173,8 @@ var init_process_card = __esm({
13073
13173
  }
13074
13174
  async doPatch(final = false) {
13075
13175
  if (this.degraded || !this.messageId && this.channelV !== "cardkit") return false;
13076
- const key2 = this.pushKey();
13077
- if (key2 === this.lastPushKey) return true;
13176
+ const key4 = this.pushKey();
13177
+ if (key4 === this.lastPushKey) return true;
13078
13178
  this.lastPatchAt = Date.now();
13079
13179
  const card = this.channelV === "progress" ? null : this.channelV === "patch-v1" ? buildProcessCard(this.state) : buildProcessCardV2(this.state) ?? (this.options.allowLegacyCard !== false ? buildProcessCard(this.state) : null);
13080
13180
  if (this.channelV !== "preview" && this.channelV !== "progress" && !card) return false;
@@ -13090,7 +13190,7 @@ var init_process_card = __esm({
13090
13190
  await this.adapter.patchCard(this.messageId, card);
13091
13191
  } else return false;
13092
13192
  this.patchFailures = 0;
13093
- this.lastPushKey = key2;
13193
+ this.lastPushKey = key4;
13094
13194
  return true;
13095
13195
  } catch (err) {
13096
13196
  if (this.channelV === "cardkit" && isPermissionDenied(err)) {
@@ -13100,7 +13200,7 @@ var init_process_card = __esm({
13100
13200
  await this.removeCard();
13101
13201
  if (this.disposed) return false;
13102
13202
  await this.createLegacyCard();
13103
- this.lastPushKey = key2;
13203
+ this.lastPushKey = key4;
13104
13204
  this.patchFailures = 0;
13105
13205
  if (!this.ended) this.startHeartbeat();
13106
13206
  return true;
@@ -13235,23 +13335,23 @@ var init_session_map = __esm({
13235
13335
  this.map = {};
13236
13336
  }
13237
13337
  }
13238
- get(key2) {
13239
- return this.map[key2];
13338
+ get(key4) {
13339
+ return this.map[key4];
13240
13340
  }
13241
- set(key2, sessionId, workDir) {
13242
- this.map[key2] = { sessionId, workDir, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
13341
+ set(key4, sessionId, workDir) {
13342
+ this.map[key4] = { sessionId, workDir, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
13243
13343
  this.save();
13244
13344
  }
13245
13345
  /** 清掉 binding 的会话绑定(/cc-new)。返回是否真的清了。 */
13246
- clear(key2) {
13247
- if (!(key2 in this.map)) return false;
13248
- delete this.map[key2];
13346
+ clear(key4) {
13347
+ if (!(key4 in this.map)) return false;
13348
+ delete this.map[key4];
13249
13349
  this.save();
13250
13350
  return true;
13251
13351
  }
13252
13352
  /** /cc-switch 直写目标会话 */
13253
- switchTo(key2, sessionId, workDir) {
13254
- this.set(key2, sessionId, workDir);
13353
+ switchTo(key4, sessionId, workDir) {
13354
+ this.set(key4, sessionId, workDir);
13255
13355
  }
13256
13356
  save() {
13257
13357
  try {
@@ -13504,9 +13604,9 @@ function sharedNodeModules() {
13504
13604
  function pkgDir(name) {
13505
13605
  return path5.join(sharedNodeModules(), ...name.split("/"));
13506
13606
  }
13507
- function readConfig(key2) {
13607
+ function readConfig(key4) {
13508
13608
  try {
13509
- return liveConfig.get(key2);
13609
+ return liveConfig.get(key4);
13510
13610
  } catch {
13511
13611
  }
13512
13612
  }
@@ -13521,9 +13621,9 @@ function downloadsEnabled() {
13521
13621
  function currentPlatformKey() {
13522
13622
  return `${process.platform}-${process.arch}`;
13523
13623
  }
13524
- function featureSpec(key2) {
13525
- const spec = OPTIONAL_FEATURES[key2];
13526
- if (!spec) throw new Error(`[dep-downloader] optional-deps.json \u91CC\u6CA1\u6709\u952E\uFF1A${key2}`);
13624
+ function featureSpec(key4) {
13625
+ const spec = OPTIONAL_FEATURES[key4];
13626
+ if (!spec) throw new Error(`[dep-downloader] optional-deps.json \u91CC\u6CA1\u6709\u952E\uFF1A${key4}`);
13527
13627
  return spec;
13528
13628
  }
13529
13629
  function markerPath(spec) {
@@ -13536,8 +13636,8 @@ function isPkgInstalled(spec) {
13536
13636
  return false;
13537
13637
  }
13538
13638
  }
13539
- function isOptionalFeatureInstalled(key2) {
13540
- const spec = featureSpec(key2);
13639
+ function isOptionalFeatureInstalled(key4) {
13640
+ const spec = featureSpec(key4);
13541
13641
  if (!isPkgInstalled(spec.main)) return false;
13542
13642
  const plat = spec.platform?.[currentPlatformKey()];
13543
13643
  if (plat && !isPkgInstalled(plat)) return false;
@@ -13641,9 +13741,9 @@ function notInstalledError(spec) {
13641
13741
  err.code = "ERR_MODULE_NOT_FOUND";
13642
13742
  return err;
13643
13743
  }
13644
- async function ensureOptionalFeature(key2, onProgress) {
13645
- const spec = featureSpec(key2);
13646
- if (isOptionalFeatureInstalled(key2)) return pkgDir(spec.main.name);
13744
+ async function ensureOptionalFeature(key4, onProgress) {
13745
+ const spec = featureSpec(key4);
13746
+ if (isOptionalFeatureInstalled(key4)) return pkgDir(spec.main.name);
13647
13747
  if (!downloadsEnabled()) throw notInstalledError(spec);
13648
13748
  const plat = spec.platform?.[currentPlatformKey()];
13649
13749
  const pkgs = [spec.main, ...plat ? [plat] : [], ...spec.extra ?? []];
@@ -13654,17 +13754,17 @@ function requireFromShared(name) {
13654
13754
  const req = createRequire3(path5.join(sharedNodeModules(), ".e7-resolve.js"));
13655
13755
  return req(name);
13656
13756
  }
13657
- async function loadOptionalModule(key2, onProgress) {
13658
- const spec = featureSpec(key2);
13757
+ async function loadOptionalModule(key4, onProgress) {
13758
+ const spec = featureSpec(key4);
13659
13759
  const notFound = (err) => err?.code === "ERR_MODULE_NOT_FOUND" || err?.code === "MODULE_NOT_FOUND";
13660
13760
  try {
13661
13761
  return nodeRequire(spec.main.name);
13662
13762
  } catch (err) {
13663
13763
  if (!notFound(err)) throw err;
13664
13764
  }
13665
- if (!isOptionalFeatureInstalled(key2)) {
13765
+ if (!isOptionalFeatureInstalled(key4)) {
13666
13766
  if (!downloadsEnabled()) throw notInstalledError(spec);
13667
- await ensureOptionalFeature(key2, onProgress);
13767
+ await ensureOptionalFeature(key4, onProgress);
13668
13768
  }
13669
13769
  const dir = pkgDir(spec.main.name);
13670
13770
  try {
@@ -13694,11 +13794,11 @@ var init_dep_downloader = __esm({
13694
13794
  OPTIONAL_FEATURES = (() => {
13695
13795
  const raw = optional_deps_default;
13696
13796
  const out = {};
13697
- for (const [key2, v] of Object.entries(raw)) {
13698
- if (key2 === "//") continue;
13797
+ for (const [key4, v] of Object.entries(raw)) {
13798
+ if (key4 === "//") continue;
13699
13799
  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-")));
13700
- 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`);
13701
- out[key2] = { key: key2, label: v.label ?? key2, main: v.main, platform: v.platform, extra: v.extra };
13800
+ 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`);
13801
+ out[key4] = { key: key4, label: v.label ?? key4, main: v.main, platform: v.platform, extra: v.extra };
13702
13802
  }
13703
13803
  return out;
13704
13804
  })();
@@ -14360,7 +14460,7 @@ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
14360
14460
  const file2 = join15(dir, `${stamp}-${tail}-${i + 1}${ext}`);
14361
14461
  mkdirSync9(dir, { recursive: true });
14362
14462
  writeFileSync8(file2, bytes2);
14363
- 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`;
14463
+ 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`;
14364
14464
  lines.push(`${i + 1}. ${label}\uFF0C${how}\uFF1A${file2}`);
14365
14465
  } catch (err) {
14366
14466
  lines.push(`${i + 1}. ${label} \u843D\u76D8\u5931\u8D25\uFF1A${err?.message || String(err)}`);
@@ -14390,10 +14490,10 @@ ${note}` : note)).catch((err) => session.enqueue(`${inbound.content}
14390
14490
  return this.sessions.get(`${channel}:${chatId}`);
14391
14491
  }
14392
14492
  /** 按 bindingKey(channel:chatId)找 session——卡片停止钮回调用(1119) */
14393
- forChatKey(key2) {
14394
- const idx = key2.indexOf(":");
14493
+ forChatKey(key4) {
14494
+ const idx = key4.indexOf(":");
14395
14495
  if (idx <= 0) return void 0;
14396
- return this.sessions.get(key2);
14496
+ return this.sessions.get(key4);
14397
14497
  }
14398
14498
  /** 全部绑定的工作目录(去重;cc-progress 工具省参推断用) */
14399
14499
  get bindingWorkDirs() {
@@ -14402,8 +14502,8 @@ ${note}` : note)).catch((err) => session.enqueue(`${inbound.content}
14402
14502
  get bindings() {
14403
14503
  return [...this.sessions.values()].map((s) => ({ key: s.key, workDir: s.workDir, sessionId: s.currentSessionId, busy: s.busy }));
14404
14504
  }
14405
- ask(key2, workDir, prompt, source, expectedSessionId, signal) {
14406
- const session = this.sessions.get(key2);
14505
+ ask(key4, workDir, prompt, source, expectedSessionId, signal) {
14506
+ const session = this.sessions.get(key4);
14407
14507
  if (!session) return Promise.reject(requestError("CC binding not found", 404));
14408
14508
  if (session.workDir !== workDir) return Promise.reject(requestError("CC binding workDir changed"));
14409
14509
  return session.ask(prompt, source, expectedSessionId, signal);
@@ -14429,7 +14529,7 @@ function registerCcHub(hub2, stateDir, port) {
14429
14529
  const dir = registryDir2();
14430
14530
  fs6.mkdirSync(dir, { recursive: true, mode: 448 });
14431
14531
  const file2 = path6.join(dir, `${process.pid}.json`);
14432
- const endpoint = { pid: process.pid, stateDir, port, bindings: hub2.bindings.map(({ key: key2, workDir }) => ({ key: key2, workDir })) };
14532
+ const endpoint = { pid: process.pid, stateDir, port, bindings: hub2.bindings.map(({ key: key4, workDir }) => ({ key: key4, workDir })) };
14433
14533
  const tmp = `${file2}.tmp`;
14434
14534
  fs6.writeFileSync(tmp, JSON.stringify(endpoint), { mode: 384 });
14435
14535
  fs6.renameSync(tmp, file2);
@@ -14669,11 +14769,11 @@ __export(dispatches_exports, {
14669
14769
  finishCalendarDispatch: () => finishCalendarDispatch,
14670
14770
  recoverCalendarDispatches: () => recoverCalendarDispatches
14671
14771
  });
14672
- function beginCalendarDispatch(db2, key2, binding, context) {
14772
+ function beginCalendarDispatch(db2, key4, binding, context) {
14673
14773
  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");
14674
14774
  return Boolean(db2.prepare(`INSERT OR IGNORE INTO calendar_dispatches
14675
14775
  (dispatch_key,event_id,binding_version,occurrence_id,state,started_at,scope_id,context_json) VALUES (?,?,?,?,'started',?,?,?)`).run(
14676
- key2,
14776
+ key4,
14677
14777
  binding.eventId,
14678
14778
  binding.version,
14679
14779
  binding.occurrenceId,
@@ -14682,8 +14782,8 @@ function beginCalendarDispatch(db2, key2, binding, context) {
14682
14782
  context ? JSON.stringify(context) : null
14683
14783
  ).changes);
14684
14784
  }
14685
- function finishCalendarDispatch(db2, key2, state) {
14686
- db2.prepare("UPDATE calendar_dispatches SET state=?,finished_at=?,version=version+1 WHERE dispatch_key=? AND state='started'").run(state, Date.now(), key2);
14785
+ function finishCalendarDispatch(db2, key4, state) {
14786
+ db2.prepare("UPDATE calendar_dispatches SET state=?,finished_at=?,version=version+1 WHERE dispatch_key=? AND state='started'").run(state, Date.now(), key4);
14687
14787
  }
14688
14788
  function recoverCalendarDispatches(db2) {
14689
14789
  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);
@@ -15159,7 +15259,7 @@ var init_intent_state = __esm({
15159
15259
  // src/memory/proactive/mutation-service.ts
15160
15260
  function canonical3(value) {
15161
15261
  if (Array.isArray(value)) return value.map(canonical3);
15162
- if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key2, item]) => [key2, canonical3(item)]));
15262
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key4, item]) => [key4, canonical3(item)]));
15163
15263
  return value;
15164
15264
  }
15165
15265
  var graphBasis;
@@ -15356,18 +15456,18 @@ function createGraphMemoryValidator(memory) {
15356
15456
  }
15357
15457
  const scope = memory?.sources.scope(scopeKey);
15358
15458
  if (!memory || !scope) throw new Error("GRAPH_MEMORY_READ_GUARD_REQUIRED");
15359
- const unseen = [...new Map(refs.map((ref) => [JSON.stringify([scopeKey, ref]), ref])).entries()].filter(([key2]) => !checkedRefs.has(key2));
15459
+ const unseen = [...new Map(refs.map((ref) => [JSON.stringify([scopeKey, ref]), ref])).entries()].filter(([key4]) => !checkedRefs.has(key4));
15360
15460
  memory.dependencies.assertReferences(scope, unseen.map(([, ref]) => ref));
15361
- for (const [key2] of unseen) checkedRefs.add(key2);
15461
+ for (const [key4] of unseen) checkedRefs.add(key4);
15362
15462
  const sourceIds = [.../* @__PURE__ */ new Set([
15363
15463
  ...refs.filter((ref) => ref.parentKind === "source").map((ref) => ref.parentId),
15364
15464
  ...typeof node.data.socialSourceId === "string" ? [node.data.socialSourceId] : []
15365
15465
  ])];
15366
15466
  for (const id3 of sourceIds) {
15367
- const key2 = JSON.stringify([scopeKey, id3]);
15368
- if (checkedSources.has(key2)) continue;
15467
+ const key4 = JSON.stringify([scopeKey, id3]);
15468
+ if (checkedSources.has(key4)) continue;
15369
15469
  if (!memory.socialSources.readable(scope, id3) || !memory.socialSources.groundsCurrent(scope, id3)) throw new Error("STALE_GRAPH_SOCIAL_SOURCE");
15370
- checkedSources.add(key2);
15470
+ checkedSources.add(key4);
15371
15471
  }
15372
15472
  const relation = node.data.relationshipRef;
15373
15473
  const relationshipKey = relation && JSON.stringify([scopeKey, relation]);
@@ -15400,7 +15500,7 @@ function digest5(value) {
15400
15500
  }
15401
15501
  function generationBasis(intent) {
15402
15502
  const data = { ...intent.data };
15403
- for (const key2 of ["status", "stateVersion", "reasonCode", "deferredReason", "waitingFor", "nextEligibleAt", "completedOccurrenceId"]) delete data[key2];
15503
+ for (const key4 of ["status", "stateVersion", "reasonCode", "deferredReason", "waitingFor", "nextEligibleAt", "completedOccurrenceId"]) delete data[key4];
15404
15504
  return graphBasis({ ...intent, data });
15405
15505
  }
15406
15506
  var IntentRunStore;
@@ -15604,9 +15704,9 @@ CREATE TABLE memory_projection_heads (
15604
15704
  }
15605
15705
  inspect(event2) {
15606
15706
  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");
15607
- const received = this.db.prepare("SELECT payload_hash FROM memory_projection_inbox WHERE event_id=?").get(event2.eventId);
15608
- if (received) {
15609
- if (received.payload_hash !== eventHash(event2)) throw new Error("PROJECTION_EVENT_ID_CONFLICT");
15707
+ const received2 = this.db.prepare("SELECT payload_hash FROM memory_projection_inbox WHERE event_id=?").get(event2.eventId);
15708
+ if (received2) {
15709
+ if (received2.payload_hash !== eventHash(event2)) throw new Error("PROJECTION_EVENT_ID_CONFLICT");
15610
15710
  return "duplicate";
15611
15711
  }
15612
15712
  if (event2.eventSeq !== this.position(event2.scopeId) + 1) throw new Error("PROJECTION_SEQUENCE_GAP");
@@ -15636,9 +15736,9 @@ CREATE TABLE memory_projection_heads (
15636
15736
  * 详见 docs/research/2026-10-20-mem7-poison-delivery-followup.md。 */
15637
15737
  skip(event2) {
15638
15738
  if (event2.schemaVersion !== 1 || !event2.eventId || !event2.scopeId || !Number.isSafeInteger(event2.eventSeq) || event2.eventSeq < 1) throw new Error("INVALID_PROJECTION_EVENT");
15639
- const received = this.db.prepare("SELECT payload_hash FROM memory_projection_inbox WHERE event_id=?").get(event2.eventId);
15640
- if (received) {
15641
- if (received.payload_hash !== eventHash(event2)) throw new Error("PROJECTION_EVENT_ID_CONFLICT");
15739
+ const received2 = this.db.prepare("SELECT payload_hash FROM memory_projection_inbox WHERE event_id=?").get(event2.eventId);
15740
+ if (received2) {
15741
+ if (received2.payload_hash !== eventHash(event2)) throw new Error("PROJECTION_EVENT_ID_CONFLICT");
15642
15742
  return;
15643
15743
  }
15644
15744
  if (event2.eventSeq !== this.position(event2.scopeId) + 1) throw new Error("PROJECTION_SEQUENCE_GAP");
@@ -15834,20 +15934,20 @@ CREATE INDEX idx_action_dispatch_state ON action_dispatches(state,started_at);
15834
15934
  constructor(db2) {
15835
15935
  this.db = db2;
15836
15936
  }
15837
- begin(key2, scopeId2, versions) {
15937
+ begin(key4, scopeId2, versions) {
15838
15938
  const result = this.db.prepare(`INSERT OR IGNORE INTO action_dispatches
15839
- (dispatch_key,scope_id,action_versions,state,started_at) VALUES (?,?,?,'started',?)`).run(key2, scopeId2, JSON.stringify(versions), Date.now());
15939
+ (dispatch_key,scope_id,action_versions,state,started_at) VALUES (?,?,?,'started',?)`).run(key4, scopeId2, JSON.stringify(versions), Date.now());
15840
15940
  if (!result.changes) return false;
15841
15941
  for (const id3 of Object.keys(versions)) this.db.prepare(`UPDATE actions SET dispatch_key=?,dispatch_state='started'
15842
- WHERE id=? AND scope_id=?`).run(key2, id3, scopeId2);
15942
+ WHERE id=? AND scope_id=?`).run(key4, id3, scopeId2);
15843
15943
  return true;
15844
15944
  }
15845
- finish(key2, state, receipt) {
15846
- const row = this.db.prepare("SELECT * FROM action_dispatches WHERE dispatch_key=?").get(key2);
15945
+ finish(key4, state, receipt) {
15946
+ const row = this.db.prepare("SELECT * FROM action_dispatches WHERE dispatch_key=?").get(key4);
15847
15947
  if (!row || row.state !== "started") return;
15848
- this.db.prepare("UPDATE action_dispatches SET state=?,finished_at=?,receipt=? WHERE dispatch_key=? AND state='started'").run(state, Date.now(), receipt ?? null, key2);
15948
+ this.db.prepare("UPDATE action_dispatches SET state=?,finished_at=?,receipt=? WHERE dispatch_key=? AND state='started'").run(state, Date.now(), receipt ?? null, key4);
15849
15949
  for (const id3 of Object.keys(JSON.parse(row.action_versions))) this.db.prepare(`UPDATE actions SET dispatch_state=?
15850
- WHERE id=? AND dispatch_key=?`).run(state, id3, key2);
15950
+ WHERE id=? AND dispatch_key=?`).run(state, id3, key4);
15851
15951
  }
15852
15952
  /** Called once by the owning plugin at startup, never by another connection's constructor. */
15853
15953
  recoverInterrupted() {
@@ -15874,15 +15974,15 @@ var init_host_deliveries = __esm({
15874
15974
  this.db = db2;
15875
15975
  }
15876
15976
  enqueue(actionId, version, blocks, context) {
15877
- const key2 = JSON.stringify(["proactive", actionId, version]);
15878
- 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());
15879
- return key2;
15977
+ const key4 = JSON.stringify(["proactive", actionId, version]);
15978
+ 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());
15979
+ return key4;
15880
15980
  }
15881
15981
  pending() {
15882
15982
  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) }));
15883
15983
  }
15884
- finish(key2, state, reason) {
15885
- 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);
15984
+ finish(key4, state, reason) {
15985
+ 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);
15886
15986
  }
15887
15987
  list(scope, options = {}) {
15888
15988
  const where = scope ? ["a.scope_id=? AND json_extract(h.context_json,'$.scopeId')=?"] : [];
@@ -16152,7 +16252,8 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16152
16252
  this.replication = enrollRuntimeReplication(this.db, stateDir, "proactive", binding);
16153
16253
  this.capture = installSQLiteWriteCapture(this.db, this.replication);
16154
16254
  }
16155
- this.transaction(() => this.personNodes.rebuild(this.loadNodes()));
16255
+ if (!this.db.prepare("SELECT 1 FROM graph_person_nodes LIMIT 1").get())
16256
+ this.transaction(() => this.personNodes.rebuild(this.loadNodes()));
16156
16257
  } catch (error) {
16157
16258
  try {
16158
16259
  this.capture?.close();
@@ -16251,6 +16352,12 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16251
16352
  graphRevision() {
16252
16353
  return Number(this.db.prepare("SELECT revision FROM graph_state WHERE id=1").get().revision);
16253
16354
  }
16355
+ graphCounts() {
16356
+ return {
16357
+ nodes: Number(this.db.prepare("SELECT COUNT(*) n FROM nodes").get().n),
16358
+ edges: Number(this.db.prepare("SELECT COUNT(*) n FROM edges").get().n)
16359
+ };
16360
+ }
16254
16361
  // B7.1(astra review):SQL 级联失效(invalidateGraphChildren/invalidateMemoryEvent)改动的
16255
16362
  // 节点不在调用方 delta 里——事务内收集,提交后由 GraphStore 逐 id 单行刷回缓存。
16256
16363
  cascadeTouched = [];
@@ -16343,6 +16450,9 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16343
16450
  const edges = new Map(keys.flatMap((id3) => this.loadIncidentEdges(id3)).map((edge) => [edgeKey(edge.source, edge.target, edge.edgeType), edge]));
16344
16451
  return { nodes, edges: [...edges.values()], revision: this.graphRevision() };
16345
16452
  };
16453
+ return this.readGraphTransaction(read2);
16454
+ }
16455
+ readGraphTransaction(read2) {
16346
16456
  if (this.inTransaction) return read2();
16347
16457
  this.db.exec("BEGIN");
16348
16458
  try {
@@ -16354,9 +16464,18 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16354
16464
  throw error;
16355
16465
  }
16356
16466
  }
16357
- loadNodes() {
16358
- const rows = this.db.prepare("SELECT * FROM nodes").all();
16359
- return rows.map((r) => ({
16467
+ loadNodes(type, scope) {
16468
+ const clauses = [], values = [];
16469
+ if (type) {
16470
+ clauses.push("type=?");
16471
+ values.push(type);
16472
+ }
16473
+ if (scope !== void 0) {
16474
+ clauses.push("COALESCE(NULLIF(json_extract(data,'$.scopeId'),''),'legacy')=?");
16475
+ values.push(scope);
16476
+ }
16477
+ const rows = this.db.prepare("SELECT * FROM nodes" + (clauses.length ? " WHERE " + clauses.join(" AND ") : "")).iterate(...values);
16478
+ return Array.from(rows, (r) => ({
16360
16479
  id: r.id,
16361
16480
  type: r.type,
16362
16481
  data: JSON.parse(r.data),
@@ -16395,8 +16514,8 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16395
16514
  }));
16396
16515
  }
16397
16516
  loadEdges() {
16398
- const rows = this.db.prepare("SELECT * FROM edges").all();
16399
- return rows.map((r) => ({
16517
+ const rows = this.db.prepare("SELECT * FROM edges").iterate();
16518
+ return Array.from(rows, (r) => ({
16400
16519
  source: r.source,
16401
16520
  target: r.target,
16402
16521
  edgeType: r.edge_type,
@@ -16404,6 +16523,20 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16404
16523
  createdAt: r.created_at
16405
16524
  }));
16406
16525
  }
16526
+ /** One indexed read for a model snapshot, instead of one node/adjacency query per node. */
16527
+ loadEdgesAmong(ids) {
16528
+ if (!ids.size) return [];
16529
+ const keys = JSON.stringify([...ids]);
16530
+ const rows = this.db.prepare(`SELECT * FROM edges WHERE source IN (SELECT value FROM json_each(?))
16531
+ AND target IN (SELECT value FROM json_each(?))`).iterate(keys, keys);
16532
+ return Array.from(rows, (row) => ({
16533
+ source: row.source,
16534
+ target: row.target,
16535
+ edgeType: row.edge_type,
16536
+ weight: row.weight,
16537
+ createdAt: row.created_at
16538
+ }));
16539
+ }
16407
16540
  // === 图:写(GraphStore 镜像调用) ===
16408
16541
  insertNode(node) {
16409
16542
  this.transaction(() => {
@@ -16437,7 +16570,7 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16437
16570
  this.transaction(() => {
16438
16571
  const previous = knownPrevious ?? this.loadNodeById(node.id);
16439
16572
  if (!previous) throw new Error(`nodes row '${node.id}' missing on update (memory/DB divergence)`);
16440
- 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);
16573
+ 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);
16441
16574
  if (changed && previous.type === "intent") {
16442
16575
  patchIntentState(previous.data, node.data);
16443
16576
  if (stateVersion(node.data) !== stateVersion(previous.data) + 1) throw new Error("STALE_INTENT_VERSION");
@@ -16448,9 +16581,9 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16448
16581
  this.validateOutcomeEvidence(node.data, node.data.completionEvidence);
16449
16582
  }
16450
16583
  }
16451
- 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;
16452
- if (keys && keys.every((key2) => node.data[key2] !== void 0 && (node.data[key2] === null || typeof node.data[key2] !== "object"))) {
16453
- const patch = keys.flatMap((key2) => [`$.${JSON.stringify(key2)}`, JSON.stringify(node.data[key2])]);
16584
+ 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;
16585
+ if (keys && keys.every((key4) => node.data[key4] !== void 0 && (node.data[key4] === null || typeof node.data[key4] !== "object"))) {
16586
+ const patch = keys.flatMap((key4) => [`$.${JSON.stringify(key4)}`, JSON.stringify(node.data[key4])]);
16454
16587
  const data = keys.length ? `json_set(data,${keys.map(() => "?,json(?)").join(",")})` : "data";
16455
16588
  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);
16456
16589
  } 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);
@@ -16976,10 +17109,10 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16976
17109
  /** Close a held host turn after evidence-based review; never make the old outbox pending again. */
16977
17110
  reconcileHostDelivery(input, scope) {
16978
17111
  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");
16979
- const versions = (provided, key2, version) => {
17112
+ const versions = (provided, key4, version) => {
16980
17113
  if (provided !== void 0 && (!provided || typeof provided !== "object" || Array.isArray(provided))) throw new Error("INVALID_DELIVERY_RECONCILIATION");
16981
- if (provided && Object.hasOwn(provided, key2) && provided[key2] !== version) throw new Error("INVALID_DELIVERY_RECONCILIATION");
16982
- const entries = Object.entries({ ...provided, [key2]: version }).sort(([a], [b]) => a.localeCompare(b));
17114
+ if (provided && Object.hasOwn(provided, key4) && provided[key4] !== version) throw new Error("INVALID_DELIVERY_RECONCILIATION");
17115
+ const entries = Object.entries({ ...provided, [key4]: version }).sort(([a], [b]) => a.localeCompare(b));
16983
17116
  if (entries.some(([id3, value]) => !id3 || !Number.isSafeInteger(value) || value < 1)) throw new Error("INVALID_DELIVERY_RECONCILIATION");
16984
17117
  return Object.fromEntries(entries);
16985
17118
  };
@@ -19103,15 +19236,15 @@ function validManagement(input) {
19103
19236
  if (input.action === "retire" && !(typeof input.jobId === "string" && identifier.test(input.jobId))) return false;
19104
19237
  if (!Object.hasOwn(managementFields, String(input.action))) return false;
19105
19238
  const fields = managementFields[String(input.action)];
19106
- if (!fields || Object.keys(input).some((key2) => !["version", "action", ...fields].includes(key2)) || fields.some((key2) => !Object.hasOwn(input, key2))) return false;
19107
- 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;
19108
- for (const key2 of ["transferId", "targetNodeId"]) if (Object.hasOwn(input, key2) && (typeof input[key2] !== "string" || !identifier.test(input[key2]))) return false;
19239
+ if (!fields || Object.keys(input).some((key4) => !["version", "action", ...fields].includes(key4)) || fields.some((key4) => !Object.hasOwn(input, key4))) return false;
19240
+ 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;
19241
+ for (const key4 of ["transferId", "targetNodeId"]) if (Object.hasOwn(input, key4) && (typeof input[key4] !== "string" || !identifier.test(input[key4]))) return false;
19109
19242
  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;
19110
19243
  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;
19111
19244
  if (Object.hasOwn(input, "permit") && !record(input.permit)) return false;
19112
19245
  if (Object.hasOwn(input, "operation") && !["WRITE", "SEND", "TOOL", "INPUT", "PUBLISH", "CONTROL"].includes(String(input.operation))) return false;
19113
- 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;
19114
- if (Object.hasOwn(input, "boundary") && (!record(input.boundary) || Object.keys(input.boundary).some((key2) => !["checkpointDigest", "safeBoundary", "effectsSettled"].includes(key2)))) return false;
19246
+ 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;
19247
+ if (Object.hasOwn(input, "boundary") && (!record(input.boundary) || Object.keys(input.boundary).some((key4) => !["checkpointDigest", "safeBoundary", "effectsSettled"].includes(key4)))) return false;
19115
19248
  return true;
19116
19249
  }
19117
19250
  function createTravelAuthorityServer(options) {
@@ -19221,7 +19354,7 @@ function createTravelAuthorityServer(options) {
19221
19354
  return;
19222
19355
  }
19223
19356
  const input = envelope?.travel, keys = input?.action === "register" ? ["version", "action", "bootId"] : input?.action === "heartbeat" ? ["version", "action", "bootId", "sequence", "permit", "deletionWatermark"] : ["version", "action"];
19224
- 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));
19357
+ 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));
19225
19358
  if (!envelope || typeof envelope !== "object" || Array.isArray(envelope) || Object.keys(envelope).length !== 1 || !input || typeof input !== "object" || Array.isArray(input) || input.version !== 1 || !validAction) {
19226
19359
  reply(400, { error: "TRAVEL_CONTROL_INVALID_REQUEST" });
19227
19360
  return;
@@ -19235,7 +19368,7 @@ function createTravelAuthorityServer(options) {
19235
19368
  }
19236
19369
  let result;
19237
19370
  if (managing) {
19238
- if (input.permit && ["tenantId", "companionId", "seatId", "nodeId"].some((key2) => input.permit[key2] !== principal[key2])) throw new Error("TRAVEL_AUTH_DENIED");
19371
+ if (input.permit && ["tenantId", "companionId", "seatId", "nodeId"].some((key4) => input.permit[key4] !== principal[key4])) throw new Error("TRAVEL_AUTH_DENIED");
19239
19372
  switch (input.action) {
19240
19373
  case "bindInitialCheckpoint":
19241
19374
  if (!bootstrapGrants.get(peerFingerprint)?.has(principal.credentialHash)) throw new Error("TRAVEL_AUTH_DENIED");
@@ -19396,12 +19529,12 @@ async function fetchTravelKey(options) {
19396
19529
  const wanted = options.identity;
19397
19530
  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))
19398
19531
  throw new Error("KEY_SERVICE_INVALID_RESPONSE");
19399
- const key2 = Buffer.from(value.key, "base64");
19400
- if (key2.length !== 32 || key2.toString("base64") !== value.key) {
19401
- key2.fill(0);
19532
+ const key4 = Buffer.from(value.key, "base64");
19533
+ if (key4.length !== 32 || key4.toString("base64") !== value.key) {
19534
+ key4.fill(0);
19402
19535
  throw new Error("KEY_SERVICE_INVALID_RESPONSE");
19403
19536
  }
19404
- return { key: key2, deletionWatermark: value.deletionWatermark };
19537
+ return { key: key4, deletionWatermark: value.deletionWatermark };
19405
19538
  }
19406
19539
 
19407
19540
  // src/continuity/gateway-store.ts
@@ -19419,6 +19552,13 @@ import { DatabaseSync as DatabaseSync9 } from "node:sqlite";
19419
19552
  init_store();
19420
19553
  init_mem7_replication();
19421
19554
 
19555
+ // src/travel/chunk-store.ts
19556
+ import { gunzipSync as gunzipSync2, gzip as gzip2 } from "node:zlib";
19557
+ import { promisify as promisify2 } from "node:util";
19558
+ var CHUNK_BYTES = 4 * 1024 * 1024;
19559
+ var DATABASE_CHUNK_BYTES = 64 * 1024;
19560
+ var compress2 = promisify2(gzip2);
19561
+
19422
19562
  // src/mem7/intake.ts
19423
19563
  init_system_filter();
19424
19564
  init_host_turns();
@@ -20074,7 +20214,7 @@ function createTravelGatewayServer(options) {
20074
20214
  reply(200, store.applyRecoveryDeletedInputs(principal, input.bindings, input.floor));
20075
20215
  return;
20076
20216
  }
20077
- 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");
20217
+ 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");
20078
20218
  if (action === "preparation") {
20079
20219
  if (Object.keys(input).length) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
20080
20220
  reply(200, store.preparationEvidence(principal));
@@ -20126,7 +20266,7 @@ function createTravelGatewayServer(options) {
20126
20266
  const values = action === "produce" ? [input.input] : input.inputs;
20127
20267
  if (!Array.isArray(values) || !values.length || values.length > 100) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
20128
20268
  const decoded = values.map((value) => {
20129
- if (!value || typeof value !== "object" || Object.keys(value).some((key2) => !["eventId", "kind", "ordinal", "version", "bodyBase64"].includes(key2))) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
20269
+ if (!value || typeof value !== "object" || Object.keys(value).some((key4) => !["eventId", "kind", "ordinal", "version", "bodyBase64"].includes(key4))) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
20130
20270
  return { ...value, body: decodeBody(value.bodyBase64) };
20131
20271
  });
20132
20272
  if (input.finalOutput !== void 0 && typeof input.finalOutput !== "boolean") throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
@@ -20402,7 +20542,7 @@ var AgentRegistryImpl = class {
20402
20542
  var agentRegistry = new AgentRegistryImpl();
20403
20543
 
20404
20544
  // src/channels/discord.ts
20405
- import { Client, GatewayIntentBits, Partials, ApplicationCommandOptionType } from "discord.js";
20545
+ import { Client, GatewayIntentBits, MessageFlags, Partials, ApplicationCommandOptionType } from "discord.js";
20406
20546
  import { ProxyAgent as UndiciProxyAgent } from "undici";
20407
20547
  import { HttpsProxyAgent } from "https-proxy-agent";
20408
20548
 
@@ -20637,16 +20777,16 @@ async function guardedExternalEffect(run) {
20637
20777
  Promise.resolve().then(() => (init_dispatches(), dispatches_exports))
20638
20778
  ]);
20639
20779
  const db2 = openDb2(workspace);
20640
- const key3 = "calendar_" + createHash25("sha256").update(JSON.stringify([context.scopeId, context.calendarBinding, effectId])).digest("hex");
20780
+ const key5 = "calendar_" + createHash25("sha256").update(JSON.stringify([context.scopeId, context.calendarBinding, effectId])).digest("hex");
20641
20781
  try {
20642
20782
  assertMemoryExecution(stateDir, workspace, context);
20643
- if (!beginCalendarDispatch2(db2, key3, context.calendarBinding, context)) throw new MemoryExecutionBlockedError("DISPATCH_ALREADY_STARTED");
20783
+ if (!beginCalendarDispatch2(db2, key5, context.calendarBinding, context)) throw new MemoryExecutionBlockedError("DISPATCH_ALREADY_STARTED");
20644
20784
  try {
20645
- const result = await effects.run({ ...host, activeDispatchKey: key3 }, run);
20646
- finishCalendarDispatch2(db2, key3, "delivered");
20785
+ const result = await effects.run({ ...host, activeDispatchKey: key5 }, run);
20786
+ finishCalendarDispatch2(db2, key5, "delivered");
20647
20787
  return result;
20648
20788
  } catch (error) {
20649
- finishCalendarDispatch2(db2, key3, "delivery_unknown");
20789
+ finishCalendarDispatch2(db2, key5, "delivery_unknown");
20650
20790
  throw error;
20651
20791
  }
20652
20792
  } finally {
@@ -20658,22 +20798,22 @@ async function guardedExternalEffect(run) {
20658
20798
  return run();
20659
20799
  }
20660
20800
  const persist = new Persistence2(join18(workspace, ".proactive", "proactive.db"));
20661
- const key2 = "dispatch_" + createHash25("sha256").update(JSON.stringify([
20801
+ const key4 = "dispatch_" + createHash25("sha256").update(JSON.stringify([
20662
20802
  context.scopeId,
20663
20803
  Object.entries(versions).sort(([a], [b]) => a.localeCompare(b)),
20664
20804
  effectId
20665
20805
  ])).digest("hex");
20666
20806
  try {
20667
20807
  assertMemoryExecution(stateDir, workspace, context);
20668
- if (!persist.transaction(() => persist.dispatches.begin(key2, context.scopeId, versions))) {
20808
+ if (!persist.transaction(() => persist.dispatches.begin(key4, context.scopeId, versions))) {
20669
20809
  throw new MemoryExecutionBlockedError("DISPATCH_ALREADY_STARTED");
20670
20810
  }
20671
20811
  try {
20672
- const result = await effects.run({ ...host, activeDispatchKey: key2 }, run);
20673
- persist.transaction(() => persist.dispatches.finish(key2, "delivered", "adapter_acknowledged"));
20812
+ const result = await effects.run({ ...host, activeDispatchKey: key4 }, run);
20813
+ persist.transaction(() => persist.dispatches.finish(key4, "delivered", "adapter_acknowledged"));
20674
20814
  return result;
20675
20815
  } catch (error) {
20676
- persist.transaction(() => persist.dispatches.finish(key2, "delivery_unknown"));
20816
+ persist.transaction(() => persist.dispatches.finish(key4, "delivery_unknown"));
20677
20817
  throw error;
20678
20818
  }
20679
20819
  } finally {
@@ -20759,6 +20899,85 @@ function totalFromContentRange(header) {
20759
20899
  return Number.isFinite(n) && n >= 0 ? n : null;
20760
20900
  }
20761
20901
 
20902
+ // src/channels/discord-progress.ts
20903
+ init_folded_panel();
20904
+ init_process_card_model();
20905
+ init_process_card_render();
20906
+ import { ContainerBuilder, SeparatorBuilder, TextDisplayBuilder } from "@discordjs/builders";
20907
+ import { SeparatorSpacingSize } from "discord-api-types/v10";
20908
+ var SHOWN_STEPS_MAX = 8;
20909
+ var RESULT_LINE_MAX = 100;
20910
+ var SETTLED_TTL_MS = 30 * 60 * 1e3;
20911
+ function buildDiscordProgressContainer(state, accent) {
20912
+ const container = new ContainerBuilder().setAccentColor(accent);
20913
+ const context = state.presentation;
20914
+ const status = context?.statusLabels?.[state.status] ?? STATUS_META[state.status].suffix;
20915
+ container.addTextDisplayComponents(new TextDisplayBuilder().setContent(`**${context?.title ?? state.repoName}** \xB7 ${status}`));
20916
+ container.addSeparatorComponents(new SeparatorBuilder().setSpacing(SeparatorSpacingSize.Small).setDivider(true));
20917
+ const tools = state.rows.filter((row) => row.kind === "tool");
20918
+ const shown = tools.slice(-SHOWN_STEPS_MAX);
20919
+ const hidden = (state.earlierSteps || 0) + tools.length - shown.length;
20920
+ if (hidden > 0) container.addTextDisplayComponents(new TextDisplayBuilder().setContent(`\u22EF \u524D\u9762\u8FD8\u6709 ${hidden} \u6B65`));
20921
+ for (const row of shown) {
20922
+ let content = toolRowTitle(row.name, row.args, row.state);
20923
+ if (row.state !== "run" && row.resultVisible !== false) {
20924
+ content += `
20925
+ \u23BF ${row.state === "err" ? "\u2717 " : ""}${clipCardText(oneLine(row.out.split("\n")[0] || "(\u65E0\u8F93\u51FA)"), RESULT_LINE_MAX)}`;
20926
+ }
20927
+ container.addTextDisplayComponents(new TextDisplayBuilder().setContent(content));
20928
+ }
20929
+ const thought = state.rows.findLast((row) => row.kind === "think");
20930
+ if (thought?.kind === "think") container.addTextDisplayComponents(new TextDisplayBuilder().setContent(thoughtLine(thought.preview)));
20931
+ return container;
20932
+ }
20933
+ var DiscordProgressCards = class {
20934
+ constructor(transport, accent) {
20935
+ this.transport = transport;
20936
+ this.accent = accent;
20937
+ }
20938
+ entries = /* @__PURE__ */ new Map();
20939
+ queues = /* @__PURE__ */ new Map();
20940
+ async sendProgress(target, state) {
20941
+ const container = buildDiscordProgressContainer(state, this.accent);
20942
+ const id3 = await this.transport.send(target, container);
20943
+ this.entries.set(id3, { channelId: target, sent: key3(container) });
20944
+ if (settled(state.status)) this.expire(id3);
20945
+ return id3;
20946
+ }
20947
+ /** 内容与上次发出的一致就不编辑(过程控制器的 5 秒活性桶会空推一轮);同一条消息的编辑按入队顺序串行 */
20948
+ updateProgress(id3, state) {
20949
+ const run = async () => {
20950
+ const entry = this.entries.get(id3);
20951
+ if (!entry) return;
20952
+ const container = buildDiscordProgressContainer(state, this.accent);
20953
+ const next = key3(container);
20954
+ if (next === entry.sent) return;
20955
+ await this.transport.edit(entry.channelId, id3, container);
20956
+ entry.sent = next;
20957
+ if (settled(state.status)) this.expire(id3);
20958
+ };
20959
+ const queued = (this.queues.get(id3) ?? Promise.resolve()).then(run, run);
20960
+ this.queues.set(id3, queued);
20961
+ const forget = () => {
20962
+ if (this.queues.get(id3) === queued) this.queues.delete(id3);
20963
+ };
20964
+ void queued.then(forget, forget);
20965
+ return queued;
20966
+ }
20967
+ async removeProgress(id3) {
20968
+ const entry = this.entries.get(id3);
20969
+ this.entries.delete(id3);
20970
+ if (entry) await this.transport.remove(entry.channelId, id3);
20971
+ }
20972
+ expire(id3) {
20973
+ setTimeout(() => {
20974
+ this.entries.delete(id3);
20975
+ }, SETTLED_TTL_MS).unref?.();
20976
+ }
20977
+ };
20978
+ var key3 = (container) => JSON.stringify(container.toJSON());
20979
+ var settled = (status) => status !== "run" && status !== "wait";
20980
+
20762
20981
  // src/channels/discord.ts
20763
20982
  var DISCORD_MSG_LIMIT = 2e3;
20764
20983
  var DiscordAdapter = class _DiscordAdapter {
@@ -20767,6 +20986,10 @@ var DiscordAdapter = class _DiscordAdapter {
20767
20986
  client;
20768
20987
  config;
20769
20988
  ownsClient;
20989
+ /** 1124:折叠过程卡只在折叠模式下出(没折叠维持逐步显示);编辑型消息的推送节奏 */
20990
+ progressRequiresCollapsed = true;
20991
+ progressThrottleMs = 2500;
20992
+ progressCards;
20770
20993
  messageHandler = null;
20771
20994
  commandHandler = null;
20772
20995
  registeredCommands = [];
@@ -20811,6 +21034,25 @@ var DiscordAdapter = class _DiscordAdapter {
20811
21034
  this.client = new Client(clientOptions);
20812
21035
  this.ownsClient = true;
20813
21036
  }
21037
+ this.progressCards = new DiscordProgressCards({
21038
+ send: async (channelId, container) => {
21039
+ const channel = await this.textChannel(channelId);
21040
+ assertExternalEffectCurrent();
21041
+ const sent = await channel.send({ flags: MessageFlags.IsComponentsV2, components: [container], allowedMentions: { parse: [] } });
21042
+ return sent.id;
21043
+ },
21044
+ edit: async (channelId, messageId, container) => {
21045
+ const channel = await this.textChannel(channelId);
21046
+ const message = channel.messages?.cache?.get(messageId) ?? await channel.messages.fetch(messageId);
21047
+ assertExternalEffectCurrent();
21048
+ await message.edit({ components: [container], allowedMentions: { parse: [] } });
21049
+ },
21050
+ // 删除与 deletePreview 同口径:不过 assertExternalEffectCurrent(删是减法)
21051
+ remove: async (channelId, messageId) => {
21052
+ const channel = await this.textChannel(channelId);
21053
+ await channel.messages.delete(messageId);
21054
+ }
21055
+ }, this.previewColor);
20814
21056
  }
20815
21057
  /** 暴露 discord.js Client(供 VisualTransport 等模块使用) */
20816
21058
  getClient() {
@@ -21182,6 +21424,23 @@ var DiscordAdapter = class _DiscordAdapter {
21182
21424
  } catch {
21183
21425
  }
21184
21426
  }
21427
+ // === 折叠过程卡(1124):Discord 卡片消息,每步带一行结果;没有按钮 ===
21428
+ async textChannel(channelId) {
21429
+ const channel = this.client.channels.cache.get(channelId) ?? await this.client.channels.fetch(channelId);
21430
+ if (!channel?.isTextBased() || !("send" in channel)) {
21431
+ throw new Error(`discord: \u8FC7\u7A0B\u5361: channel ${channelId} not found or not text-based`);
21432
+ }
21433
+ return channel;
21434
+ }
21435
+ async sendProgress(target, state) {
21436
+ return this.progressCards.sendProgress(target, state);
21437
+ }
21438
+ async updateProgress(id3, state) {
21439
+ await this.progressCards.updateProgress(id3, state);
21440
+ }
21441
+ async removeProgress(id3) {
21442
+ await this.progressCards.removeProgress(id3);
21443
+ }
21185
21444
  // === Streaming preview — 对齐 cc-connect Discord 的 SendPreviewStart/UpdateMessage/DeletePreviewMessage ===
21186
21445
  // 对齐 cc-connect platform/discord/progress.go:preview 消息用 Embed(彩色标题栏 + 内容)
21187
21446
  /** Embed 颜色常量 — 对齐 cc-connect discordProgressStateMeta */
@@ -21644,8 +21903,8 @@ var FeishuAdapter = class _FeishuAdapter {
21644
21903
  let durationMs = Math.round(fileBuffer.length / 3);
21645
21904
  try {
21646
21905
  const { execFile: execFile2 } = await import("node:child_process");
21647
- const { promisify: promisify3 } = await import("node:util");
21648
- const execFileAsync2 = promisify3(execFile2);
21906
+ const { promisify: promisify4 } = await import("node:util");
21907
+ const execFileAsync2 = promisify4(execFile2);
21649
21908
  const probe = await execFileAsync2("ffprobe", ["-v", "quiet", "-show_format", "-print_format", "json", attachment.path], { timeout: 1e4 });
21650
21909
  const fmt = JSON.parse(probe.stdout);
21651
21910
  if (fmt?.format?.duration) durationMs = Math.round(parseFloat(fmt.format.duration) * 1e3);
@@ -21740,8 +21999,8 @@ var FeishuAdapter = class _FeishuAdapter {
21740
21999
  return fileKey;
21741
22000
  }
21742
22001
  /** 消息资源 URL(三个下载方法 + Range 预探共用) */
21743
- _resourceUrl(messageId, key2, kind) {
21744
- return `https://open.feishu.cn/open-apis/im/v1/messages/${messageId}/resources/${key2}?type=${kind}`;
22002
+ _resourceUrl(messageId, key4, kind) {
22003
+ return `https://open.feishu.cn/open-apis/im/v1/messages/${messageId}/resources/${key4}?type=${kind}`;
21745
22004
  }
21746
22005
  /** 通过飞书API下载消息中的图片 */
21747
22006
  async _downloadImage(messageId, imageKey, tokenOverride, init) {
@@ -21810,7 +22069,7 @@ var FeishuAdapter = class _FeishuAdapter {
21810
22069
  let totalBytes = 0;
21811
22070
  let token;
21812
22071
  const nameCache = /* @__PURE__ */ new Map();
21813
- const fetchOne = async (msgId, key2, kind, nameHint, idx, notes) => {
22072
+ const fetchOne = async (msgId, key4, kind, nameHint, idx, notes) => {
21814
22073
  if (Date.now() - started > HISTORY_DOWNLOAD_BUDGET_MS) {
21815
22074
  notes.push(budgetNote(1));
21816
22075
  return null;
@@ -21818,7 +22077,7 @@ var FeishuAdapter = class _FeishuAdapter {
21818
22077
  try {
21819
22078
  token ??= await this._getTenantToken();
21820
22079
  try {
21821
- const probe = await fetch(this._resourceUrl(msgId, key2, kind === "image" ? "image" : "file"), {
22080
+ const probe = await fetch(this._resourceUrl(msgId, key4, kind === "image" ? "image" : "file"), {
21822
22081
  headers: { Authorization: `Bearer ${token}`, Range: "bytes=0-0" },
21823
22082
  signal: AbortSignal.timeout(5e3)
21824
22083
  });
@@ -21832,7 +22091,7 @@ var FeishuAdapter = class _FeishuAdapter {
21832
22091
  } catch {
21833
22092
  }
21834
22093
  const dlInit = { signal: AbortSignal.timeout(HISTORY_ATTACH_TIMEOUT_MS) };
21835
- 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);
22094
+ 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);
21836
22095
  if (buf.length > HISTORY_ATTACH_MAX_BYTES) {
21837
22096
  notes.push(skipNote(nameHint, buf.length));
21838
22097
  return null;
@@ -21882,9 +22141,9 @@ var FeishuAdapter = class _FeishuAdapter {
21882
22141
  if (r?.tag === "text") segs.push(String(r.text ?? ""));
21883
22142
  else if (r?.tag === "img") {
21884
22143
  segs.push("[\u56FE\u7247]");
21885
- const key2 = String(r?.image_key ?? "");
21886
- if (key2) {
21887
- const att = await fetchOne(msgId, key2, "image", `post-${msgId}-${imgIdx}.jpg`, imgIdx, notes);
22144
+ const key4 = String(r?.image_key ?? "");
22145
+ if (key4) {
22146
+ const att = await fetchOne(msgId, key4, "image", `post-${msgId}-${imgIdx}.jpg`, imgIdx, notes);
21888
22147
  if (att) attachments.push(att);
21889
22148
  imgIdx++;
21890
22149
  }
@@ -21893,18 +22152,18 @@ var FeishuAdapter = class _FeishuAdapter {
21893
22152
  content = segs.join("").trim() || "[\u56FE\u6587]";
21894
22153
  } else if (type === "image") {
21895
22154
  content = "[\u56FE\u7247]";
21896
- const key2 = String(body?.image_key ?? "");
21897
- if (key2) {
21898
- const att = await fetchOne(msgId, key2, "image", `img-${msgId}.jpg`, 0, notes);
22155
+ const key4 = String(body?.image_key ?? "");
22156
+ if (key4) {
22157
+ const att = await fetchOne(msgId, key4, "image", `img-${msgId}.jpg`, 0, notes);
21899
22158
  if (att) attachments.push(att);
21900
22159
  }
21901
22160
  } else if (type === "file" || type === "audio" || type === "media") {
21902
22161
  const name0 = String(body?.file_name ?? body?.file_key ?? "file");
21903
22162
  const label = type === "audio" ? "\u8BED\u97F3" : type === "media" ? "\u89C6\u9891" : "\u6587\u4EF6";
21904
22163
  content = `[${label}] ${name0}`;
21905
- const key2 = String(body?.file_key ?? "");
21906
- if (key2) {
21907
- const att = await fetchOne(msgId, key2, type === "media" ? "video" : "file", name0, 0, notes);
22164
+ const key4 = String(body?.file_key ?? "");
22165
+ if (key4) {
22166
+ const att = await fetchOne(msgId, key4, type === "media" ? "video" : "file", name0, 0, notes);
21908
22167
  if (att) attachments.push(att);
21909
22168
  }
21910
22169
  } else if (type === "sticker") {
@@ -22368,8 +22627,8 @@ var FeishuAdapter = class _FeishuAdapter {
22368
22627
  const earlyImageKeys = imageKeys.filter(Boolean);
22369
22628
  if (message.message_type === "image" && !earlyImageKeys.length) {
22370
22629
  try {
22371
- const key2 = JSON.parse(message.content || "{}").image_key;
22372
- if (key2) earlyImageKeys.push(key2);
22630
+ const key4 = JSON.parse(message.content || "{}").image_key;
22631
+ if (key4) earlyImageKeys.push(key4);
22373
22632
  } catch {
22374
22633
  }
22375
22634
  }
@@ -22385,12 +22644,12 @@ var FeishuAdapter = class _FeishuAdapter {
22385
22644
  messageId,
22386
22645
  recvAt: Date.now(),
22387
22646
  metadata: { chatId, chatType, ...parentId ? { parentId } : {} },
22388
- attachments: earlyImageKeys.map((key2) => ({
22647
+ attachments: earlyImageKeys.map((key4) => ({
22389
22648
  url: "",
22390
22649
  filename: "image.png",
22391
22650
  contentType: "image/png",
22392
22651
  size: 0,
22393
- loadBytes: (signal) => this._downloadImage(messageId, key2, void 0, { signal })
22652
+ loadBytes: (signal) => this._downloadImage(messageId, key4, void 0, { signal })
22394
22653
  })),
22395
22654
  prepareContext: async (signal) => {
22396
22655
  signal?.throwIfAborted();
@@ -22476,7 +22735,8 @@ var FeishuAdapter = class _FeishuAdapter {
22476
22735
  }
22477
22736
  }
22478
22737
  if (!cleanContent.trim() && !imageAttachments?.length && !fileAttachment && !videoAttachment && !attachNotes.length) return;
22479
- const senderName = await this._resolveSenderName(senderOpenId);
22738
+ const senderName = this.config?.nameMap?.[senderOpenId] || this._senderNameCache.get(senderOpenId)?.name || senderOpenId.slice(0, 8);
22739
+ void this._resolveSenderName(senderOpenId);
22480
22740
  const inbound = {
22481
22741
  // 1012 翀哥实测:引用原文和新正文挤一行会混——引用独占一行,正文(含附件留痕)另起一行。
22482
22742
  content: [
@@ -22584,8 +22844,8 @@ var FeishuAdapter = class _FeishuAdapter {
22584
22844
  } else if (block.tag === "at") {
22585
22845
  lines.push(block.user_name ? `@${block.user_name}` : "@user");
22586
22846
  } else if (block.tag === "img") {
22587
- const key2 = block.image_key;
22588
- if (key2) imageKeys.push(key2);
22847
+ const key4 = block.image_key;
22848
+ if (key4) imageKeys.push(key4);
22589
22849
  }
22590
22850
  }
22591
22851
  lines.push("\n");
@@ -22720,6 +22980,11 @@ function hasWechatPriorContact(stateDir, accountId, userId) {
22720
22980
  }
22721
22981
  }
22722
22982
 
22983
+ // src/auth/client.ts
22984
+ var DEFAULT_AUTH_BROKER = "https://auth.engine7.ai/auth/";
22985
+ var LEGACY_AUTH_BROKERS = ["https://www.twinsun.top/auth/"];
22986
+ var OFFICIAL_AUTH_BROKERS = /* @__PURE__ */ new Set([DEFAULT_AUTH_BROKER, ...LEGACY_AUTH_BROKERS]);
22987
+
22723
22988
  // src/config/features.ts
22724
22989
  init_live();
22725
22990
 
@@ -22788,13 +23053,13 @@ function pkcs7Unpad(data) {
22788
23053
  if (pad < 1 || pad > 16 || pad > data.length) return data;
22789
23054
  return data.subarray(0, data.length - pad);
22790
23055
  }
22791
- function aesEncrypt(plaintext, key2) {
22792
- const c = crypto2.createCipheriv("aes-128-ecb", key2, null);
23056
+ function aesEncrypt(plaintext, key4) {
23057
+ const c = crypto2.createCipheriv("aes-128-ecb", key4, null);
22793
23058
  c.setAutoPadding(false);
22794
23059
  return Buffer.concat([c.update(pkcs7Pad(plaintext)), c.final()]);
22795
23060
  }
22796
- function aesDecrypt(ciphertext, key2) {
22797
- const d = crypto2.createDecipheriv("aes-128-ecb", key2, null);
23061
+ function aesDecrypt(ciphertext, key4) {
23062
+ const d = crypto2.createDecipheriv("aes-128-ecb", key4, null);
22798
23063
  d.setAutoPadding(false);
22799
23064
  return pkcs7Unpad(Buffer.concat([d.update(ciphertext), d.final()]));
22800
23065
  }
@@ -23053,8 +23318,8 @@ var ContextTokenStore = class {
23053
23318
  this.save();
23054
23319
  }
23055
23320
  delete(a, p) {
23056
- const key2 = p !== void 0 ? this.k(a, p) : a;
23057
- this.cache.delete(key2);
23321
+ const key4 = p !== void 0 ? this.k(a, p) : a;
23322
+ this.cache.delete(key4);
23058
23323
  this.save();
23059
23324
  }
23060
23325
  };
@@ -23615,12 +23880,12 @@ import { WebSocketServer, WebSocket } from "ws";
23615
23880
  init_live();
23616
23881
  init_well_formed();
23617
23882
  import { execFile } from "node:child_process";
23618
- import { promisify as promisify2 } from "node:util";
23883
+ import { promisify as promisify3 } from "node:util";
23619
23884
  init_voice_chat_tts_daemon();
23620
23885
  import * as path14 from "node:path";
23621
23886
  import * as os6 from "node:os";
23622
23887
  import net2 from "net";
23623
- var execFileAsync = promisify2(execFile);
23888
+ var execFileAsync = promisify3(execFile);
23624
23889
  var VOICE_DIR = path14.join(os6.tmpdir(), "engine-voice");
23625
23890
  async function ttsCosyvoiceWorker(text2, cfg, onChunk) {
23626
23891
  if (!isDaemonReady()) {
@@ -24586,10 +24851,10 @@ var PreviewEditThrottle = class {
24586
24851
  }
24587
24852
  st = /* @__PURE__ */ new Map();
24588
24853
  /** 提交一次编辑;返回的 promise 在"该内容(或其后覆盖它的更新内容)真实落盘"后 settle,失败 reject */
24589
- submit(key2, req, run) {
24590
- const s = this.st.get(key2) ?? { lastEditAt: -Infinity, timer: null, pending: null, pendingRun: null, waiters: [] };
24854
+ submit(key4, req, run) {
24855
+ const s = this.st.get(key4) ?? { lastEditAt: -Infinity, timer: null, pending: null, pendingRun: null, waiters: [] };
24591
24856
  const guardedRun = AsyncLocalStorage6.bind(run);
24592
- this.st.set(key2, s);
24857
+ this.st.set(key4, s);
24593
24858
  return new Promise((resolve13, reject) => {
24594
24859
  const waiter = { resolve: resolve13, reject };
24595
24860
  if (s.timer) {
@@ -24599,7 +24864,7 @@ var PreviewEditThrottle = class {
24599
24864
  return;
24600
24865
  }
24601
24866
  if (this.now() - s.lastEditAt >= this.minIntervalMs) {
24602
- this.fire(key2, req, [waiter], guardedRun);
24867
+ this.fire(key4, req, [waiter], guardedRun);
24603
24868
  return;
24604
24869
  }
24605
24870
  s.pending = req;
@@ -24613,12 +24878,12 @@ var PreviewEditThrottle = class {
24613
24878
  s.pending = null;
24614
24879
  s.pendingRun = null;
24615
24880
  s.waiters = [];
24616
- if (p && latestRun) this.fire(key2, p, w, latestRun);
24881
+ if (p && latestRun) this.fire(key4, p, w, latestRun);
24617
24882
  }, this.minIntervalMs - (this.now() - s.lastEditAt));
24618
24883
  });
24619
24884
  }
24620
- fire(key2, req, waiters, run) {
24621
- const s = this.st.get(key2);
24885
+ fire(key4, req, waiters, run) {
24886
+ const s = this.st.get(key4);
24622
24887
  if (s) s.lastEditAt = this.now();
24623
24888
  Promise.resolve().then(() => run(req)).then(
24624
24889
  () => {
@@ -24853,16 +25118,16 @@ var AlbumBuffer = class {
24853
25118
  }
24854
25119
  groups = /* @__PURE__ */ new Map();
24855
25120
  add(item) {
24856
- const key2 = item.mediaGroupId;
24857
- const g = this.groups.get(key2) ?? { items: [], lastAt: 0 };
25121
+ const key4 = item.mediaGroupId;
25122
+ const g = this.groups.get(key4) ?? { items: [], lastAt: 0 };
24858
25123
  g.items.push(item);
24859
25124
  g.lastAt = this.now();
24860
- this.groups.set(key2, g);
25125
+ this.groups.set(key4, g);
24861
25126
  }
24862
25127
  tick() {
24863
- for (const [key2, g] of this.groups) {
25128
+ for (const [key4, g] of this.groups) {
24864
25129
  if (this.now() - g.lastAt < this.timeoutMs) continue;
24865
- this.groups.delete(key2);
25130
+ this.groups.delete(key4);
24866
25131
  g.items.sort((a, b) => Number(a.inbound.messageId) - Number(b.inbound.messageId));
24867
25132
  this.flush(g.items);
24868
25133
  }
@@ -25302,9 +25567,9 @@ var TelegramAdapter = class {
25302
25567
  */
25303
25568
  async editPreview(handle, content, agentName, isFinal) {
25304
25569
  const chatId = Number(handle.channelId);
25305
- const key2 = `${handle.channelId}:${handle.messageId}`;
25570
+ const key4 = `${handle.channelId}:${handle.messageId}`;
25306
25571
  try {
25307
- await this.editThrottle.submit(key2, { content, agentName, isFinal: !!isFinal }, async (r) => {
25572
+ await this.editThrottle.submit(key4, { content, agentName, isFinal: !!isFinal }, async (r) => {
25308
25573
  await this.enqueueSend(chatId, async () => {
25309
25574
  if (r.isFinal) {
25310
25575
  const chunks = splitTextChunks(r.content, 4e3);
@@ -25422,11 +25687,11 @@ function inboundGate(inp) {
25422
25687
  if (!inp.hasUserContent) {
25423
25688
  return { pass: false, gate: 4, reason: "\u65E0 user \u53EF\u89C1\u5185\u5BB9\uFF08receipt/protocol \u7A7A\u6D88\u606F\uFF09" };
25424
25689
  }
25425
- const key2 = `${inp.jid}:${inp.messageId}`;
25426
- if (inp.seenKeys.has(key2)) {
25427
- return { pass: false, gate: 5, reason: `\u91CD\u590D\u6D88\u606F: ${key2}` };
25690
+ const key4 = `${inp.jid}:${inp.messageId}`;
25691
+ if (inp.seenKeys.has(key4)) {
25692
+ return { pass: false, gate: 5, reason: `\u91CD\u590D\u6D88\u606F: ${key4}` };
25428
25693
  }
25429
- inp.seenKeys.add(key2);
25694
+ inp.seenKeys.add(key4);
25430
25695
  return { pass: true };
25431
25696
  }
25432
25697
  var WRAPPERS = [
@@ -26619,7 +26884,7 @@ ${archiveNotice(resultArchive)}`, resultArchive };
26619
26884
 
26620
26885
  // src/models/provider-errors.ts
26621
26886
  function isQuotaExhaustedError(message) {
26622
- 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);
26887
+ 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);
26623
26888
  }
26624
26889
 
26625
26890
  // src/core/query.ts
@@ -26761,8 +27026,8 @@ function withTravelEventContext(context, run) {
26761
27026
  }
26762
27027
  function travelEventPermit(context) {
26763
27028
  const permit = context.permit(), original = context.originalPermit;
26764
- for (const key2 of ["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"]) {
26765
- if (permit[key2] !== original[key2]) throw new Error("TRAVEL_GATEWAY_STALE_CONTEXT");
27029
+ for (const key4 of ["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"]) {
27030
+ if (permit[key4] !== original[key4]) throw new Error("TRAVEL_GATEWAY_STALE_CONTEXT");
26766
27031
  }
26767
27032
  if (context.complete) throw new Error("TRAVEL_GATEWAY_EVENT_COMPLETED");
26768
27033
  return permit;
@@ -26907,7 +27172,10 @@ function isCpuModeHook(command) {
26907
27172
  return (tokens[0] === process.execPath || /^(?:node|python[\d.]*|py)(?:\.exe)?$/i.test(executable)) && /^emotion(?:_state_machine\.(?:mjs|py)|-hook-gate\.js)$/i.test(script);
26908
27173
  }
26909
27174
  function cpuModeHookOutput(command, input, workspace) {
26910
- if (!isCpuModeHook(command) || !["emotion", "work"].includes(input.cpu_router_mode)) return null;
27175
+ return isCpuModeHook(command) ? cpuModeOutput(input, workspace) : null;
27176
+ }
27177
+ function cpuModeOutput(input, workspace) {
27178
+ if (!["emotion", "work"].includes(input.cpu_router_mode)) return null;
26911
27179
  const text2 = typeof input.prompt === "string" ? input.prompt : "";
26912
27180
  const internal = ["heartbeat", "cron", "system", "inner-voice", "mem7"];
26913
27181
  const marks = ["\u3010", "[\u5B9A\u65F6", "\u5F53\u524D\u65F6\u95F4\uFF1A", "[inner-voice]", "<calendar-notification>", "<nudge-notification>", "<task-notification>", "<system-reminder>"];
@@ -27158,10 +27426,10 @@ async function executeOneHook(hook, hookEvent, hookName, hookInput, toolUseID, s
27158
27426
  hook
27159
27427
  };
27160
27428
  }
27161
- const cpuModeOutput = hookEvent === "UserPromptSubmit" ? cpuModeHookOutput(hook.command, hookInput, ctx.workspace) : null;
27162
- if (cpuModeOutput) {
27163
- const processed = processHookJSONOutput({ json: cpuModeOutput, command: hook.command, hookEvent, durationMs: Date.now() - startMs });
27164
- console.log(`[cpu-router] mode-hook=${hookTimingLabel(hook, 0)} mode=${cpuModeOutput._mode ?? "skip"}`);
27429
+ const cpuModeOutput2 = hookEvent === "UserPromptSubmit" ? cpuModeHookOutput(hook.command, hookInput, ctx.workspace) : null;
27430
+ if (cpuModeOutput2) {
27431
+ const processed = processHookJSONOutput({ json: cpuModeOutput2, command: hook.command, hookEvent, durationMs: Date.now() - startMs });
27432
+ console.log(`[cpu-router] mode-hook=${hookTimingLabel(hook, 0)} mode=${cpuModeOutput2._mode ?? "skip"}`);
27165
27433
  return { ...processed, outcome: "success", hook };
27166
27434
  }
27167
27435
  const jsonInput = JSON.stringify(hookInput);
@@ -27290,10 +27558,10 @@ function matchesPromptHookCondition(hook, input) {
27290
27558
  if (hook.when === void 0) return true;
27291
27559
  const when = hook.when;
27292
27560
  if (!when || typeof when !== "object" || Array.isArray(when) || input.hook_event_name !== "UserPromptSubmit") return false;
27293
- if (Object.keys(when).some((key2) => !["channel", "channelType", "source", "excludeSenderIds"].includes(key2))) return false;
27561
+ if (Object.keys(when).some((key4) => !["channel", "channelType", "source", "excludeSenderIds"].includes(key4))) return false;
27294
27562
  if (!input.prompt.trim()) return false;
27295
- for (const [key2, actual] of [["channel", input.channel], ["channelType", input.channel_type], ["source", input.source]]) {
27296
- if (when[key2] !== void 0 && (typeof when[key2] !== "string" || when[key2] !== actual)) return false;
27563
+ for (const [key4, actual] of [["channel", input.channel], ["channelType", input.channel_type], ["source", input.source]]) {
27564
+ if (when[key4] !== void 0 && (typeof when[key4] !== "string" || when[key4] !== actual)) return false;
27297
27565
  }
27298
27566
  if (when.excludeSenderIds !== void 0) {
27299
27567
  if (!Array.isArray(when.excludeSenderIds) || when.excludeSenderIds.some((id3) => typeof id3 !== "string")) return false;
@@ -27431,6 +27699,7 @@ async function executeStopHooks(ctx, signal, lastAssistantMessage) {
27431
27699
  cwd: ctx.cwd,
27432
27700
  stop_hook_active: false,
27433
27701
  last_assistant_message: lastAssistantMessage,
27702
+ turn_evidence: ctx.stopTurnEvidence,
27434
27703
  channel: ctx.channel,
27435
27704
  // 让 callback hook 能判断来源
27436
27705
  channelTarget: ctx.channelTarget,
@@ -27673,13 +27942,17 @@ init_read_guard();
27673
27942
  var OnDemandRecall = class {
27674
27943
  used = /* @__PURE__ */ new Set();
27675
27944
  cache = /* @__PURE__ */ new Map();
27945
+ /** Actual tool mutations invalidate this turn's snapshot without polling SQLite. */
27946
+ invalidate() {
27947
+ this.cache.clear();
27948
+ }
27676
27949
  // 1024 翀哥裁决:6 秒墙全撤。它界的是返回大小不是时延来源(检索耗时在 embedding/bm25/rerank),
27677
27950
  // 底层各有各的界(SQL overlay 死线 12s、embedding HTTP 30s、rerank 1500ms 竞速),1+1 配额防循环。
27678
27951
  // 这层墙当天制造了两次 timeout 假阴性 + 额度连坐,没拦住任何真问题。
27679
27952
  constructor(keywordAlreadySearched = false) {
27680
27953
  if (keywordAlreadySearched) this.used.add("keyword");
27681
27954
  }
27682
- async search(binding, args, captureGuard, run, signal) {
27955
+ async search(binding, args, run, signal) {
27683
27956
  const status = (value, reason) => JSON.stringify({ historySearch: { status: value, reason } });
27684
27957
  if (signal?.aborted) return status("aborted", "\u672C\u8F6E\u5DF2\u53D6\u6D88\u3002");
27685
27958
  if (args.mode === "agentic") return status("unavailable", "\u60C5\u611F\u8F6E\u8BF7\u7528 keyword \u6216 hybrid \u6709\u754C\u8865\u67E5\u3002");
@@ -27691,17 +27964,12 @@ var OnDemandRecall = class {
27691
27964
  };
27692
27965
  for (const passthrough of ["known_at", "known_at_revision", "valid_at", "entity_ref", "after_receipt", "session_id"])
27693
27966
  if (args[passthrough] !== void 0) bounded[passthrough] = args[passthrough];
27694
- const key2 = JSON.stringify([binding, Object.entries(bounded).sort(([a], [b]) => a.localeCompare(b))]);
27695
- const cached2 = this.cache.get(key2);
27967
+ const key4 = JSON.stringify([binding, Object.entries(bounded).sort(([a], [b]) => a.localeCompare(b))]);
27968
+ const cached2 = this.cache.get(key4);
27696
27969
  if (cached2) {
27697
- const result2 = await cached2.result;
27970
+ const result2 = await cached2;
27698
27971
  if (signal?.aborted) return status("aborted", "\u672C\u8F6E\u5DF2\u53D6\u6D88\u3002");
27699
- try {
27700
- cached2.assertCurrent();
27701
- return result2;
27702
- } catch {
27703
- 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");
27704
- }
27972
+ return result2;
27705
27973
  }
27706
27974
  const kind = bounded.view === "current" || bounded.mode === "keyword" ? "keyword" : "semantic";
27707
27975
  if (kind === "keyword" && this.used.has("keyword") && !this.used.has("semantic")) {
@@ -27710,7 +27978,6 @@ var OnDemandRecall = class {
27710
27978
  if (this.used.has(kind)) {
27711
27979
  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");
27712
27980
  }
27713
- const assertCurrent = captureGuard();
27714
27981
  this.used.add(kind);
27715
27982
  if (kind === "semantic") this.used.add("keyword");
27716
27983
  const controller = new AbortController();
@@ -27740,7 +28007,7 @@ ${error.stack.split("\n").slice(0, 6).join("\n")}` : ""
27740
28007
  controller.abort();
27741
28008
  }
27742
28009
  })();
27743
- this.cache.set(key2, { result, assertCurrent });
28010
+ this.cache.set(key4, result);
27744
28011
  return result;
27745
28012
  }
27746
28013
  };
@@ -27801,13 +28068,13 @@ async function materializeImageMessages(messages, store, signal, maxBase64Bytes
27801
28068
  continue;
27802
28069
  }
27803
28070
  if (!store) throw new Error("Image asset store is required to materialize image refs");
27804
- const key2 = JSON.stringify([block.image.sha256, block.image.bytes, block.image.mediaType]);
27805
- if (!cache.has(key2)) cache.set(key2, store.materialize(block.image).catch((error) => {
28071
+ const key4 = JSON.stringify([block.image.sha256, block.image.bytes, block.image.mediaType]);
28072
+ if (!cache.has(key4)) cache.set(key4, store.materialize(block.image).catch((error) => {
27806
28073
  if (strict) throw error;
27807
28074
  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)}`);
27808
28075
  return null;
27809
28076
  }));
27810
- content.push(await cache.get(key2) ?? { type: "text", text: "[\u56FE\u7247\u6587\u4EF6\u5DF2\u4E0D\u5728\u672C\u673A\uFF0C\u5185\u5BB9\u4E0D\u53EF\u89C1]" });
28077
+ content.push(await cache.get(key4) ?? { type: "text", text: "[\u56FE\u7247\u6587\u4EF6\u5DF2\u4E0D\u5728\u672C\u673A\uFF0C\u5185\u5BB9\u4E0D\u53EF\u89C1]" });
27811
28078
  signal?.throwIfAborted();
27812
28079
  }
27813
28080
  output.push({ ...message, content });
@@ -27867,8 +28134,8 @@ var MAX_PENDING_BYTES = 512 * 1024;
27867
28134
  var SteerMailbox = class {
27868
28135
  constructor(stateDir, sessionId) {
27869
28136
  this.sessionId = sessionId;
27870
- const key2 = createHash31("sha256").update(sessionId).digest("hex");
27871
- this.path = path23.join(stateDir, "steer", `${key2}.json`);
28137
+ const key4 = createHash31("sha256").update(sessionId).digest("hex");
28138
+ this.path = path23.join(stateDir, "steer", `${key4}.json`);
27872
28139
  }
27873
28140
  path;
27874
28141
  list() {
@@ -28209,9 +28476,9 @@ function smartCompressToolResult(content, essentialFields, sizeLimit) {
28209
28476
  if (typeof item === "object" && item !== null && !Array.isArray(item)) {
28210
28477
  const extracted = {};
28211
28478
  if (fieldSet) {
28212
- for (const key2 of essentialFields) {
28213
- if (key2 in item) {
28214
- extracted[key2] = item[key2];
28479
+ for (const key4 of essentialFields) {
28480
+ if (key4 in item) {
28481
+ extracted[key4] = item[key4];
28215
28482
  }
28216
28483
  }
28217
28484
  } else {
@@ -29583,7 +29850,7 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
29583
29850
  outputHandle.close().catch(() => {
29584
29851
  });
29585
29852
  let aborted = false;
29586
- let settled = false;
29853
+ let settled2 = false;
29587
29854
  const cleanup = () => {
29588
29855
  clearTimeout(timer);
29589
29856
  signal?.removeEventListener("abort", onAbort);
@@ -29592,8 +29859,8 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
29592
29859
  child.removeListener("error", onError);
29593
29860
  };
29594
29861
  const done = async (code, error) => {
29595
- if (settled) return;
29596
- settled = true;
29862
+ if (settled2) return;
29863
+ settled2 = true;
29597
29864
  cleanup();
29598
29865
  let output = "";
29599
29866
  let truncated = false;
@@ -29627,12 +29894,12 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
29627
29894
  void done(1, error.message);
29628
29895
  };
29629
29896
  const onAbort = () => {
29630
- if (settled || signal?.reason === "interrupt") return;
29897
+ if (settled2 || signal?.reason === "interrupt") return;
29631
29898
  aborted = true;
29632
29899
  killChild(child);
29633
29900
  };
29634
29901
  const onYield = () => {
29635
- if (settled) return;
29902
+ if (settled2) return;
29636
29903
  if (child.exitCode !== null || child.signalCode !== null) {
29637
29904
  void done(child.exitCode);
29638
29905
  return;
@@ -29649,12 +29916,12 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
29649
29916
  channelTarget: ctx.channelTarget ?? "",
29650
29917
  queryAbortSignal: ctx.queryAbortSignal ?? signal
29651
29918
  });
29652
- settled = true;
29919
+ settled2 = true;
29653
29920
  cleanup();
29654
29921
  resolve13({ 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.` });
29655
29922
  };
29656
29923
  const timer = setTimeout(() => {
29657
- if (!settled) {
29924
+ if (!settled2) {
29658
29925
  aborted = true;
29659
29926
  killChild(child);
29660
29927
  }
@@ -29697,17 +29964,17 @@ function createNotificationStateReader() {
29697
29964
  const databases = /* @__PURE__ */ new Map();
29698
29965
  const checkers = /* @__PURE__ */ new Map();
29699
29966
  const open3 = (path35) => {
29700
- const key2 = resolve8(path35);
29701
- let db2 = databases.get(key2);
29967
+ const key4 = resolve8(path35);
29968
+ let db2 = databases.get(key4);
29702
29969
  if (!db2) {
29703
- db2 = new DatabaseSync11(key2, { readOnly: true });
29970
+ db2 = new DatabaseSync11(key4, { readOnly: true });
29704
29971
  try {
29705
29972
  db2.exec("BEGIN");
29706
29973
  } catch (error) {
29707
29974
  db2.close();
29708
29975
  throw error;
29709
29976
  }
29710
- databases.set(key2, db2);
29977
+ databases.set(key4, db2);
29711
29978
  }
29712
29979
  return db2;
29713
29980
  };
@@ -30568,6 +30835,7 @@ var QueryEngine = class _QueryEngine {
30568
30835
  const mailbox = this.steerMailbox;
30569
30836
  this.attachmentScopeId = perTurnOptions?.attachmentScopeId;
30570
30837
  const queryId = this.steerQueryId;
30838
+ const hasPendingUserInput = () => this.pendingSteers.some((input) => !input.attachment);
30571
30839
  this.steerHistoryIds = new Set(messages.flatMap((m) => "steerInput" in m && m.steerInput ? [m.steerInput.id] : "attachment" in m ? [m.uuid] : []));
30572
30840
  try {
30573
30841
  for (const input of mailbox?.pending(this.steerRoute ?? void 0) ?? []) {
@@ -30601,6 +30869,13 @@ var QueryEngine = class _QueryEngine {
30601
30869
  const activeSystemStable = perTurnSystemStable || this.resolveOpt(this.options.systemStable) || this.resolveOpt(this.options.systemPrompt);
30602
30870
  for (const m of messages) if ("role" in m && hasMedia(m) && !m.imageInput) m.imageInput = { id: randomUUID17(), observed: hasImage(m) };
30603
30871
  let currentMessages = [...messages];
30872
+ const stopUserMessages = [];
30873
+ const stopToolResults = [];
30874
+ const collectStopEvidence = !this.options.skipStopHook && !perTurnEmotion;
30875
+ const currentUser = collectStopEvidence ? messages.findLast((m) => "role" in m && m.role === "user") : void 0;
30876
+ if (currentUser && "role" in currentUser) {
30877
+ stopUserMessages.push(currentUser.memoryOriginalText ?? (typeof currentUser.content === "string" ? currentUser.content : currentUser.content.filter((b) => b.type === "text").map((b) => b.text).join("\n")));
30878
+ }
30604
30879
  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\.$/;
30605
30880
  const historicalGateTools = new Set(currentMessages.flatMap((m) => {
30606
30881
  if (!("role" in m) || m.role !== "tool" || typeof m.content !== "string") return [];
@@ -30679,6 +30954,7 @@ var QueryEngine = class _QueryEngine {
30679
30954
  };
30680
30955
  let turnCount = 0;
30681
30956
  let recallContinuation = false;
30957
+ const stopReplies = [];
30682
30958
  let toolCalls = [];
30683
30959
  let streamRetries = 0;
30684
30960
  let maxTokensOverride = null;
@@ -30735,6 +31011,7 @@ var QueryEngine = class _QueryEngine {
30735
31011
  }
30736
31012
  const steerMsg = buildSteerMessage(input);
30737
31013
  currentMessages.push(steerMsg);
31014
+ if (collectStopEvidence) stopUserMessages.push(input.originalText ?? input.text);
30738
31015
  this.steerHistoryIds.add(input.id);
30739
31016
  steerConsumedThisTurn = true;
30740
31017
  yield {
@@ -31024,7 +31301,7 @@ ${hint}` : [...current2.content, { type: "text", text: hint }] };
31024
31301
  const fullSystemDynamic = deferredHint && perTurnSystemDynamic ? `${deferredHint}
31025
31302
 
31026
31303
  ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31027
- if (!this.options.agentLabel || this.options.agentLabel === "main") {
31304
+ if (process.env.ENGINE_DUMP_REQUEST === "1" && (!this.options.agentLabel || this.options.agentLabel === "main")) {
31028
31305
  try {
31029
31306
  const ws = process.env.ENGINE7_WORKSPACE;
31030
31307
  if (ws) {
@@ -31246,20 +31523,22 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31246
31523
  if (toolCalls.length === 0) {
31247
31524
  const carryReply = () => {
31248
31525
  if (!this.pendingSteers.some((input) => input.attachment)) return null;
31526
+ const replyId = randomUUID17();
31249
31527
  const reply = msg.assistant(textContent);
31250
31528
  if (turnThinking) reply.reasoning_content = turnThinking;
31251
31529
  if (turnThinkingSig) reply.thinking_signature = turnThinkingSig;
31252
31530
  if (turnResponsesReasoning) reply.responses_reasoning = turnResponsesReasoning;
31253
31531
  currentMessages.push(reply);
31254
- finalText = textContent;
31532
+ finalText = "";
31533
+ if (collectStopEvidence) stopReplies.push(textContent);
31255
31534
  recallContinuation = true;
31256
31535
  turnThinking = turnThinkingSig = turnResponsesReasoning = "";
31257
- return { type: "history", messages: [reply] };
31536
+ return [{ type: "history", messages: [reply], replyId }, { type: "reply", content: textContent, replyId }];
31258
31537
  };
31259
31538
  if (responseStopReason === "max_tokens" || responseStopReason === "length") {
31260
31539
  if (this.pendingSteers.length > 0) {
31261
31540
  const carried = carryReply();
31262
- if (carried) yield carried;
31541
+ if (carried) yield* carried;
31263
31542
  continue;
31264
31543
  }
31265
31544
  finalText = textContent;
@@ -31269,7 +31548,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31269
31548
  if (this.options.skipStopHook || perTurnEmotion) {
31270
31549
  if (this.pendingSteers.length > 0) {
31271
31550
  const carried = carryReply();
31272
- if (carried) yield carried;
31551
+ if (carried) yield* carried;
31273
31552
  continue;
31274
31553
  }
31275
31554
  finalText = textContent;
@@ -31286,9 +31565,14 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31286
31565
  // 'group' | 'dm',Stop hook 用来判断是否跳过 group
31287
31566
  cwd: context?.workspace || "",
31288
31567
  source: typeof context?.source === "string" ? context.source : "",
31289
- executionContext: context?.executionContext
31568
+ executionContext: context?.executionContext,
31569
+ stopTurnEvidence: { userMessages: stopUserMessages, toolResults: stopToolResults }
31290
31570
  };
31291
- const stopResult = await executeStopHooks(stopCtx, ac.signal, textContent);
31571
+ const stopResult = await executeStopHooks(
31572
+ stopCtx,
31573
+ ac.signal,
31574
+ stopReplies.length ? [...stopReplies, textContent].join("\n\n") : textContent
31575
+ );
31292
31576
  if (stopResult.preventContinuation) {
31293
31577
  console.log(`[hook] Stop blocked: ${stopResult.stopReason || "no reason"}`);
31294
31578
  if (stopResult.additionalContexts?.length) {
@@ -31303,7 +31587,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31303
31587
  }
31304
31588
  if (this.pendingSteers.length > 0) {
31305
31589
  const carried = carryReply();
31306
- if (carried) yield carried;
31590
+ if (carried) yield* carried;
31307
31591
  continue;
31308
31592
  }
31309
31593
  finalText = textContent;
@@ -31383,6 +31667,12 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31383
31667
  turnResponsesReasoning = "";
31384
31668
  currentMessages.push(gateAssistant);
31385
31669
  currentMessages.push(...blockResults);
31670
+ if (collectStopEvidence) for (let i = 0; i < toolCalls.length; i++) stopToolResults.push({
31671
+ tool: toolCalls[i].function.name,
31672
+ toolCallId: toolCalls[i].id,
31673
+ summary: String(blockResults[i].content),
31674
+ isError: true
31675
+ });
31386
31676
  for (const g of gatedCalls) {
31387
31677
  yield { type: "tool_result", tool: g.call.function?.name, tool_call_id: g.call.id, summary: g.text.slice(0, 200), isError: true };
31388
31678
  }
@@ -31403,7 +31693,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31403
31693
  try {
31404
31694
  this.phase = "tools";
31405
31695
  this.toolYield = new AbortController();
31406
- if (this.pendingSteers.length) this.toolYield.abort("steer");
31696
+ if (hasPendingUserInput()) this.toolYield.abort("steer");
31407
31697
  toolCtx.yieldSignal = this.toolYield.signal;
31408
31698
  toolRes = await executeTools(toolCalls, ac.signal, { ...toolCtx, toolResultHistory: currentMessages });
31409
31699
  } finally {
@@ -31412,6 +31702,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31412
31702
  if (vcDelivery) await vcDelivery;
31413
31703
  }
31414
31704
  const { messages: toolResults, summaries } = toolRes;
31705
+ if (collectStopEvidence) stopToolResults.push(...summaries);
31415
31706
  for (const s of summaries) {
31416
31707
  try {
31417
31708
  const postResult = await executePostToolUseHooks(s.tool, {}, s.summary, hookCtx, ac.signal);
@@ -31513,7 +31804,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31513
31804
  this.toolYield = null;
31514
31805
  this.phase = "idle";
31515
31806
  this.loopAlive = false;
31516
- if (this.pendingSteers.length > 0 && completionReason !== "aborted") {
31807
+ if (hasPendingUserInput() && completionReason !== "aborted") {
31517
31808
  console.warn(`${this.logPrefix} [steer] ${this.pendingSteers.length} pending input(s) retained for same-route recovery (completionReason=${completionReason ?? "completed"})`);
31518
31809
  }
31519
31810
  this.pendingSteers.length = 0;
@@ -31638,7 +31929,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31638
31929
  }
31639
31930
  }
31640
31931
  this.pendingSteers.push(receipt.input);
31641
- this.toolYield?.abort("steer");
31932
+ if (!receipt.input.attachment) this.toolYield?.abort("steer");
31642
31933
  if (opts.mode === "queue") {
31643
31934
  console.log(`${this.logPrefix} Steer queued (${this.pendingSteers.length} pending \u2014 next turn, no interrupt)`);
31644
31935
  return true;
@@ -31758,8 +32049,8 @@ function defaultWriteMemoryNote(workspace) {
31758
32049
  }
31759
32050
  function makeSubmitToMain(engineDeps) {
31760
32051
  return (text2) => {
31761
- const sessions = engineDeps.deps?.sessions;
31762
- const mainSessionId = sessions?.getSessionId?.("scope:main");
32052
+ const sessions2 = engineDeps.deps?.sessions;
32053
+ const mainSessionId = sessions2?.getSessionId?.("scope:main");
31763
32054
  if (!mainSessionId) {
31764
32055
  console.warn("[whatsapp/patrol] \u65E0\u4E3B session\uFF08scope:main \u672A\u5EFA\u7ACB\uFF09\uFF0C\u26A0\uFE0F \u5347\u7EA7\u6295\u9012\u4E22\u5F03");
31765
32056
  return;
@@ -31792,10 +32083,10 @@ function makeReadOnlyAgentRunner(engineDeps) {
31792
32083
  });
31793
32084
  const sessionId = base.sessions.getOrCreateSessionId(PATROL_SESSION_KEY);
31794
32085
  return new Promise((resolve13, reject) => {
31795
- let settled = false;
32086
+ let settled2 = false;
31796
32087
  const timeout = setTimeout(() => {
31797
- if (settled) return;
31798
- settled = true;
32088
+ if (settled2) return;
32089
+ settled2 = true;
31799
32090
  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`));
31800
32091
  }, PATROL_TIMEOUT_MS);
31801
32092
  const ok = engineDeps.dispatcher.submitMessage({
@@ -31809,21 +32100,21 @@ function makeReadOnlyAgentRunner(engineDeps) {
31809
32100
  deps: { ...base, engine: patrolEngine },
31810
32101
  callbacks: {
31811
32102
  onResult: (content) => {
31812
- if (settled) return;
31813
- settled = true;
32103
+ if (settled2) return;
32104
+ settled2 = true;
31814
32105
  clearTimeout(timeout);
31815
32106
  resolve13(content);
31816
32107
  },
31817
32108
  onError: (err) => {
31818
- if (settled) return;
31819
- settled = true;
32109
+ if (settled2) return;
32110
+ settled2 = true;
31820
32111
  clearTimeout(timeout);
31821
32112
  reject(new Error(err));
31822
32113
  }
31823
32114
  }
31824
32115
  });
31825
- if (ok === false && !settled) {
31826
- settled = true;
32116
+ if (ok === false && !settled2) {
32117
+ settled2 = true;
31827
32118
  clearTimeout(timeout);
31828
32119
  reject(new Error("dispatcher \u62D2\u7EDD wa-patrol \u63D0\u4EA4\uFF08guard \u5FD9\uFF09\u2014\u2014\u4E0B\u8F6E\u91CD\u5DE1"));
31829
32120
  }
@@ -33012,10 +33303,10 @@ var DingStreamClient = class extends EventEmitter {
33012
33303
  return;
33013
33304
  }
33014
33305
  this.ws = ws;
33015
- let settled = false;
33306
+ let settled2 = false;
33016
33307
  const settle = (err) => {
33017
- if (settled) return;
33018
- settled = true;
33308
+ if (settled2) return;
33309
+ settled2 = true;
33019
33310
  this.clearHeartbeat();
33020
33311
  if (err) reject(err);
33021
33312
  else resolve13();
@@ -33036,8 +33327,8 @@ var DingStreamClient = class extends EventEmitter {
33036
33327
  });
33037
33328
  ws.on("error", (err) => {
33038
33329
  this.emit("error", err instanceof Error ? err : new Error(String(err)));
33039
- if (!settled) {
33040
- settled = true;
33330
+ if (!settled2) {
33331
+ settled2 = true;
33041
33332
  this.clearHeartbeat();
33042
33333
  reject(err);
33043
33334
  return;
@@ -33712,18 +34003,18 @@ var DingTalkAdapter = class _DingTalkAdapter {
33712
34003
  /** per-card 流式串行链(无间隔闸)——throttle 保证 ≥300ms 节奏,但 HTTP 慢时相邻两次
33713
34004
  * fire 仍可能并发(后发先到→旧内容覆盖新内容);openclaw 的 in-flight 保护同语义 */
33714
34005
  cardStreamQueues = /* @__PURE__ */ new Map();
33715
- streamCardSerial(key2, outTrackId, content, isFinalize) {
33716
- const prev = this.cardStreamQueues.get(key2) ?? Promise.resolve();
34006
+ streamCardSerial(key4, outTrackId, content, isFinalize) {
34007
+ const prev = this.cardStreamQueues.get(key4) ?? Promise.resolve();
33717
34008
  const next = prev.then(
33718
34009
  () => this.streamCard(outTrackId, content, isFinalize),
33719
34010
  () => this.streamCard(outTrackId, content, isFinalize)
33720
34011
  );
33721
- this.cardStreamQueues.set(key2, next.then(() => {
34012
+ this.cardStreamQueues.set(key4, next.then(() => {
33722
34013
  }, () => {
33723
34014
  }));
33724
34015
  if (this.cardStreamQueues.size > 200) {
33725
34016
  const drop = this.cardStreamQueues.keys().next().value;
33726
- if (drop !== void 0 && drop !== key2) this.cardStreamQueues.delete(drop);
34017
+ if (drop !== void 0 && drop !== key4) this.cardStreamQueues.delete(drop);
33727
34018
  }
33728
34019
  return next;
33729
34020
  }
@@ -33732,10 +34023,10 @@ var DingTalkAdapter = class _DingTalkAdapter {
33732
34023
  * API,双重节流会把打字机压成"两秒一跳"(openclaw 实测:300ms 直打才流畅)。保序由
33733
34024
  * throttle(last-write-wins)+ per-card 串行链保证。 */
33734
34025
  async editPreview(handle, content, agentName, isFinal) {
33735
- const key2 = `${handle.channelId}:${handle.messageId}`;
34026
+ const key4 = `${handle.channelId}:${handle.messageId}`;
33736
34027
  try {
33737
- await this.editThrottle.submit(key2, { content, agentName, isFinal: !!isFinal }, async (r) => {
33738
- await this.streamCardSerial(key2, handle.messageId, r.content, r.isFinal);
34028
+ await this.editThrottle.submit(key4, { content, agentName, isFinal: !!isFinal }, async (r) => {
34029
+ await this.streamCardSerial(key4, handle.messageId, r.content, r.isFinal);
33739
34030
  if (r.isFinal) {
33740
34031
  await this.putCardData(handle.messageId, "3");
33741
34032
  await this.notifyGroupFinalized(handle.channelId, handle.messageId).catch(() => {
@@ -34038,10 +34329,10 @@ var WecomStreamClient = class extends EventEmitter2 {
34038
34329
  return;
34039
34330
  }
34040
34331
  this.ws = ws;
34041
- let settled = false;
34332
+ let settled2 = false;
34042
34333
  const settle = (err) => {
34043
- if (settled) return;
34044
- settled = true;
34334
+ if (settled2) return;
34335
+ settled2 = true;
34045
34336
  this.clearHeartbeat();
34046
34337
  const wasSubscribed = this.everSubscribed;
34047
34338
  this.subscribed = false;
@@ -34067,7 +34358,7 @@ var WecomStreamClient = class extends EventEmitter2 {
34067
34358
  ws.on("error", (err) => {
34068
34359
  const e = err instanceof Error ? err : new Error(String(err));
34069
34360
  this.emit("error", e);
34070
- if (!settled) {
34361
+ if (!settled2) {
34071
34362
  settle(e);
34072
34363
  return;
34073
34364
  }
@@ -34358,9 +34649,9 @@ function wecomTextFormat(text2, format2 = "markdown") {
34358
34649
  }
34359
34650
  function decryptWecomMedia(buf, aeskey) {
34360
34651
  const padded = aeskey + "=".repeat((4 - aeskey.length % 4) % 4);
34361
- const key2 = Buffer.from(padded, "base64");
34362
- if (key2.length !== 32) throw new Error(`wecom media aeskey \u89E3\u7801\u540E\u5E94\u4E3A 32 \u5B57\u8282\uFF0C\u5B9E\u5F97 ${key2.length}`);
34363
- const d = createDecipheriv3("aes-256-cbc", key2, key2.subarray(0, 16));
34652
+ const key4 = Buffer.from(padded, "base64");
34653
+ if (key4.length !== 32) throw new Error(`wecom media aeskey \u89E3\u7801\u540E\u5E94\u4E3A 32 \u5B57\u8282\uFF0C\u5B9E\u5F97 ${key4.length}`);
34654
+ const d = createDecipheriv3("aes-256-cbc", key4, key4.subarray(0, 16));
34364
34655
  d.setAutoPadding(false);
34365
34656
  const raw = Buffer.concat([d.update(buf), d.final()]);
34366
34657
  const pad = raw[raw.length - 1];
@@ -34659,22 +34950,22 @@ var WecomAdapter = class {
34659
34950
  this.emitInbound(parsed.inbound);
34660
34951
  return;
34661
34952
  }
34662
- const key2 = `${parsed.chatId}:${parsed.senderId}`;
34663
- const cur = this.pending.get(key2);
34953
+ const key4 = `${parsed.chatId}:${parsed.senderId}`;
34954
+ const cur = this.pending.get(key4);
34664
34955
  if (cur) {
34665
34956
  cur.parsed.inbound.content = `${cur.parsed.inbound.content}
34666
34957
  ${parsed.inbound.content}`;
34667
34958
  cur.version++;
34668
34959
  } else {
34669
- this.pending.set(key2, { parsed, version: 1 });
34960
+ this.pending.set(key4, { parsed, version: 1 });
34670
34961
  }
34671
- const entry = this.pending.get(key2);
34962
+ const entry = this.pending.get(key4);
34672
34963
  const v = entry.version;
34673
34964
  void this.sleepImpl(windowMs).then(() => {
34674
- const live = this.pending.get(key2);
34965
+ const live = this.pending.get(key4);
34675
34966
  if (!live) return;
34676
34967
  if (live.version !== v) return;
34677
- this.pending.delete(key2);
34968
+ this.pending.delete(key4);
34678
34969
  this.emitInbound(live.parsed.inbound);
34679
34970
  });
34680
34971
  }
@@ -34688,10 +34979,10 @@ ${parsed.inbound.content}`;
34688
34979
  }
34689
34980
  /** 立即投递并清空某会话挂起的合并片段(媒体直投前的顺序保护,review) */
34690
34981
  flushPending(chatId, senderId) {
34691
- const key2 = `${chatId}:${senderId}`;
34692
- const live = this.pending.get(key2);
34982
+ const key4 = `${chatId}:${senderId}`;
34983
+ const live = this.pending.get(key4);
34693
34984
  if (!live) return;
34694
- this.pending.delete(key2);
34985
+ this.pending.delete(key4);
34695
34986
  this.emitInbound(live.parsed.inbound);
34696
34987
  }
34697
34988
  // === 出站(spec §五) ===
@@ -35200,8 +35491,8 @@ function createFeishuGatewayDispatcher(options) {
35200
35491
  const timestamp = Number(message.create_time);
35201
35492
  if (!Number.isSafeInteger(timestamp) || timestamp < 0) throw new Error("TRAVEL_FEISHU_INVALID_EVENT");
35202
35493
  const content = JSON.parse(String(message.content)), descriptors = [];
35203
- const add = (key2, type, filename, contentType) => {
35204
- if (typeof key2 === "string" && key2) descriptors.push({ key: key2, type, filename, contentType });
35494
+ const add = (key4, type, filename, contentType) => {
35495
+ if (typeof key4 === "string" && key4) descriptors.push({ key: key4, type, filename, contentType });
35205
35496
  };
35206
35497
  if (message.message_type === "image") add(content.image_key, "image", "image.jpg", "image/jpeg");
35207
35498
  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");
@@ -35339,9 +35630,9 @@ function createFeishuGatewayPlatform(options) {
35339
35630
  return { messageId: result.data.message_id };
35340
35631
  });
35341
35632
  },
35342
- downloadResource: async (messageId, key2, type) => {
35633
+ downloadResource: async (messageId, key4, type) => {
35343
35634
  if (closed) throw new Error("TRAVEL_FEISHU_CLOSED");
35344
- const response = await client.im.messageResource.get({ path: { message_id: messageId, file_key: key2 }, params: { type } });
35635
+ const response = await client.im.messageResource.get({ path: { message_id: messageId, file_key: key4 }, params: { type } });
35345
35636
  const stream = response.getReadableStream(), chunks = [];
35346
35637
  let bytes2 = 0;
35347
35638
  try {
@@ -35376,7 +35667,7 @@ function createRemoteTravelChannel(block, stateDir, channel = "feishu") {
35376
35667
  if (!stateDir || !runtimeAuthorityFor(stateDir)) throw new Error("TRAVEL_GATEWAY_RUNTIME_REQUIRED");
35377
35668
  validateTravelChannels(stateDir, { [channel]: block });
35378
35669
  const tls2 = block.gatewayTls;
35379
- if (!tls2 || ["caFile", "certFile", "keyFile"].some((key2) => typeof tls2[key2] !== "string" || !tls2[key2])) throw new Error("TRAVEL_GATEWAY_REMOTE_CONFIG_REQUIRED");
35670
+ if (!tls2 || ["caFile", "certFile", "keyFile"].some((key4) => typeof tls2[key4] !== "string" || !tls2[key4])) throw new Error("TRAVEL_GATEWAY_REMOTE_CONFIG_REQUIRED");
35380
35671
  const client = new TravelGatewayClient({ url: block.gatewayUrl, ca: readPrivateFile(tls2.caFile, 1024 * 1024), cert: readPrivateFile(tls2.certFile, 1024 * 1024), key: readPrivateFile(tls2.keyFile, 16384) });
35381
35672
  return new RemoteTravelChannel({ client, channel, permit: () => runtimeAuthorityFor(stateDir).assert("INPUT"), pollIntervalMs: block.gatewayPollIntervalMs });
35382
35673
  }
@@ -35582,9 +35873,9 @@ function archive(manager, name, mime, bytes2, role, caption, identity) {
35582
35873
  const adapter = manager.getAdapter("chan7");
35583
35874
  if (!adapter?.files || bytes2.length > 16 * 1024 * 1024) return;
35584
35875
  const safeName = path33.basename(name).replace(/[<>:"/\\|?*\x00-\x1f]/g, "_").slice(0, 255) || "attachment";
35585
- const key2 = createHash35("sha256").update(JSON.stringify(identity)).update(bytes2).digest("hex");
35876
+ const key4 = createHash35("sha256").update(JSON.stringify(identity)).update(bytes2).digest("hex");
35586
35877
  try {
35587
- adapter.files.import(safeName, mime, bytes2, role, caption.slice(0, 4e3), key2);
35878
+ adapter.files.import(safeName, mime, bytes2, role, caption.slice(0, 4e3), key4);
35588
35879
  } catch (e) {
35589
35880
  console.warn("[library] delivered copy not archived: " + e.message);
35590
35881
  }
@@ -35818,7 +36109,7 @@ var ChannelManager = class {
35818
36109
  const changes = [];
35819
36110
  for (const name of MANAGED_CHANNEL_NAMES) {
35820
36111
  const block = config[name];
35821
- const key2 = JSON.stringify(block ?? null);
36112
+ const key4 = JSON.stringify(block ?? null);
35822
36113
  const cur = this.managed.get(name);
35823
36114
  const enabled = block?.enabled === true;
35824
36115
  if (!enabled && !cur) continue;
@@ -35827,7 +36118,7 @@ var ChannelManager = class {
35827
36118
  changes.push(`${name}: removed`);
35828
36119
  continue;
35829
36120
  }
35830
- if (cur && cur.key === key2) continue;
36121
+ if (cur && cur.key === key4) continue;
35831
36122
  if (cur) {
35832
36123
  if (runningQueries.includes(name)) {
35833
36124
  console.log(`[channels] ${name} rebuild deferred (query in flight)`);
@@ -35839,7 +36130,7 @@ var ChannelManager = class {
35839
36130
  const adapter = this.buildManagedAdapter(name, block);
35840
36131
  if (!adapter) continue;
35841
36132
  this.adapters.push(adapter);
35842
- this.managed.set(name, { adapter, key: key2 });
36133
+ this.managed.set(name, { adapter, key: key4 });
35843
36134
  this.wireAdapter(adapter);
35844
36135
  if (adapter.registerCommands && this.registeredCommands.size > 0) {
35845
36136
  void adapter.registerCommands([...this.registeredCommands.values()]).catch((e) => console.error(`[channels] ${name} registerCommands failed: ${e.message}`));
@@ -36082,7 +36373,7 @@ function tls(config) {
36082
36373
  return { ca: readPrivateFile(path34(config?.caFile), 1024 * 1024), cert: readPrivateFile(path34(config?.certFile), 1024 * 1024), key: readPrivateFile(path34(config?.keyFile), 16384) };
36083
36374
  }
36084
36375
  async function startTravelGateway(config) {
36085
- if (!config?.identity || !config.keyService?.identity || ["tenantId", "companionId", "seatId"].some((key2) => config.identity[key2] !== config.keyService.identity[key2])) throw new Error("TRAVEL_GATEWAY_IDENTITY");
36376
+ if (!config?.identity || !config.keyService?.identity || ["tenantId", "companionId", "seatId"].some((key4) => config.identity[key4] !== config.keyService.identity[key4])) throw new Error("TRAVEL_GATEWAY_IDENTITY");
36086
36377
  if (!Number.isSafeInteger(config.port) || config.port < 0 || config.port > 65535 || typeof config.host !== "string" || !config.host) throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
36087
36378
  for (const [name, value] of Object.entries(config.channels ?? {})) if (value?.enabled && !["feishu", "discord", "wechat"].includes(name)) throw new Error("TRAVEL_CHANNEL_NOT_CONTROLLED");
36088
36379
  const feishuIngress = config.ingressEnabled !== false && config.feishu?.ingressEnabled !== false && config.channels?.feishu?.enabled !== false;
@@ -36135,7 +36426,7 @@ async function startTravelGateway(config) {
36135
36426
  if (!config.allowedPeers || !Object.keys(config.allowedPeers).length) throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
36136
36427
  for (const credential of Object.values(config.allowedPeers)) {
36137
36428
  const principal = authority.authenticate(String(credential));
36138
- if (["tenantId", "companionId", "seatId"].some((key2) => principal[key2] !== config.identity[key2]) || authority.status(principal).deletionWatermark !== material.deletionWatermark) throw new Error("TRAVEL_GATEWAY_IDENTITY");
36429
+ if (["tenantId", "companionId", "seatId"].some((key4) => principal[key4] !== config.identity[key4]) || authority.status(principal).deletionWatermark !== material.deletionWatermark) throw new Error("TRAVEL_GATEWAY_IDENTITY");
36139
36430
  }
36140
36431
  store = new TravelGatewayStore({ directory: path34(config.gatewayDir), identity: config.identity, objects, authority });
36141
36432
  await store.migrateStoredInputs();
@@ -36185,9 +36476,9 @@ async function startTravelGateway(config) {
36185
36476
  assertIngress: assertKey,
36186
36477
  authorizeStop: (sender) => Array.isArray(config.feishu.stopAllowedUserIds) && config.feishu.stopAllowedUserIds.includes(sender.sender_id?.open_id),
36187
36478
  onReceivedTyping: (chatId, openId, messageId) => platform.startChatTyping(chatId, openId, messageId),
36188
- downloadResource: async (messageId, key2, type) => {
36479
+ downloadResource: async (messageId, key4, type) => {
36189
36480
  assertKey();
36190
- return platform.downloadResource(messageId, key2, type);
36481
+ return platform.downloadResource(messageId, key4, type);
36191
36482
  }
36192
36483
  });
36193
36484
  if (config.channels && config.ingressEnabled !== false) {
@@ -36316,20 +36607,20 @@ async function startPairingControl(config) {
36316
36607
  authority.close();
36317
36608
  }
36318
36609
  const keys = new KeyServiceStore(join32(directory2, "keys"));
36319
- const key2 = read2("data.key");
36610
+ const key4 = read2("data.key");
36320
36611
  try {
36321
- if (createHash37("sha256").update(key2).digest("hex") !== config.keySha256) throw new Error("TRAVEL_PAIRING_KEY");
36612
+ if (createHash37("sha256").update(key4).digest("hex") !== config.keySha256) throw new Error("TRAVEL_PAIRING_KEY");
36322
36613
  try {
36323
36614
  keys.assertIdentity(binding.keyIdentity);
36324
36615
  } catch {
36325
- keys.provision(binding.keyIdentity, key2);
36616
+ keys.provision(binding.keyIdentity, key4);
36326
36617
  }
36327
36618
  for (const name of ["local", "cloud", "manager"]) {
36328
36619
  const certificate = new X509Certificate(read2(name + ".pem"));
36329
36620
  keys.authorizeCertificate(certificate.fingerprint256.replaceAll(":", ""), binding.keyIdentity, Date.parse(certificate.validTo));
36330
36621
  }
36331
36622
  } finally {
36332
- key2.fill(0);
36623
+ key4.fill(0);
36333
36624
  }
36334
36625
  const keyServer = createKeyServiceServer({ ...tls2, store: keys });
36335
36626
  await new Promise((done, reject) => {