engine7 7.1.143 → 7.1.145

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
  }
@@ -2499,15 +2510,15 @@ var init_context_time = __esm({
2499
2510
  });
2500
2511
 
2501
2512
  // src/mem7/core/state/knowledge-history.ts
2502
- function knowledgeCutoff(db2, scope, request3) {
2503
- if (request3.knownAt === void 0 && request3.knownAtRevision === void 0) return void 0;
2504
- if (request3.knownAt !== void 0 && request3.knownAtRevision !== void 0) throw new Error("AMBIGUOUS_KNOWLEDGE_TIME");
2513
+ function knowledgeCutoff(db2, scope, request4) {
2514
+ if (request4.knownAt === void 0 && request4.knownAtRevision === void 0) return void 0;
2515
+ if (request4.knownAt !== void 0 && request4.knownAtRevision !== void 0) throw new Error("AMBIGUOUS_KNOWLEDGE_TIME");
2505
2516
  const id3 = scopeId(scope);
2506
- const time = request3.knownAt === void 0 ? null : instant(request3.knownAt);
2507
- const checkpoint = request3.knownAtRevision === void 0 ? void 0 : db2.prepare("SELECT history_id FROM memory_knowledge_checkpoints WHERE scope_id=? AND fact_revision=?").get(id3, request3.knownAtRevision);
2517
+ const time = request4.knownAt === void 0 ? null : instant(request4.knownAt);
2518
+ const checkpoint = request4.knownAtRevision === void 0 ? void 0 : db2.prepare("SELECT history_id FROM memory_knowledge_checkpoints WHERE scope_id=? AND fact_revision=?").get(id3, request4.knownAtRevision);
2508
2519
  const historyId = time ? Number(db2.prepare("SELECT COALESCE(MAX(history_id),0) history_id FROM memory_knowledge_history WHERE scope_id=? AND recorded_at<=?").get(id3, time).history_id) : Number(checkpoint?.history_id ?? 0);
2509
2520
  const baseline = db2.prepare("SELECT history_id FROM memory_knowledge_history WHERE scope_id=? AND target_kind='coverage' ORDER BY history_id LIMIT 1").get(id3);
2510
- return { historyId, time, complete: (!baseline || historyId >= baseline.history_id) && (request3.knownAtRevision === void 0 || request3.knownAtRevision === 0 || Boolean(checkpoint)) };
2521
+ return { historyId, time, complete: (!baseline || historyId >= baseline.history_id) && (request4.knownAtRevision === void 0 || request4.knownAtRevision === 0 || Boolean(checkpoint)) };
2511
2522
  }
2512
2523
  function journalEntityCutoff(db2, scope, revision) {
2513
2524
  const row = db2.prepare("SELECT history_id FROM memory_entity_checkpoints WHERE scope_id=? AND entity_revision<=? ORDER BY entity_revision DESC LIMIT 1").get(scopeId(scope), revision);
@@ -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) {
@@ -7683,13 +7718,13 @@ CREATE TABLE memory_relationship_receipts (
7683
7718
  JOIN memory_relationship_versions r ON r.scope_id=h.scope_id AND r.relationship_id=h.relationship_id AND r.semantic_version=h.semantic_version
7684
7719
  JOIN fact_assertions a ON a.scope_id=r.scope_id AND a.assertion_id=r.assertion_id
7685
7720
  WHERE h.scope_id=? AND h.perspective_entity_id=? AND h.subject_id=? AND h.object_id=?`);
7686
- for (const request3 of requests) {
7687
- const endpoints = [[request3.subjectId, request3.objectId]];
7688
- if (request3.direction === "symmetric") endpoints.push([request3.objectId, request3.subjectId]);
7721
+ for (const request4 of requests) {
7722
+ const endpoints = [[request4.subjectId, request4.objectId]];
7723
+ if (request4.direction === "symmetric") endpoints.push([request4.objectId, request4.subjectId]);
7689
7724
  for (const [subject, object3] of endpoints) {
7690
- for (const row of query.all(scopeId(scope), request3.perspectiveEntityId, subject, object3)) {
7725
+ for (const row of query.all(scopeId(scope), request4.perspectiveEntityId, subject, object3)) {
7691
7726
  const value = JSON.parse(row.value_json);
7692
- if (value.contentKind === request3.contentKind && value.temporalScope === request3.temporalScope) ids.add(row.relationship_id);
7727
+ if (value.contentKind === request4.contentKind && value.temporalScope === request4.temporalScope) ids.add(row.relationship_id);
7693
7728
  }
7694
7729
  }
7695
7730
  }
@@ -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 {
@@ -10620,8 +10730,8 @@ CREATE TABLE IF NOT EXISTS cluster_members (
10620
10730
  socialInterpretations;
10621
10731
  relationshipCognition;
10622
10732
  relationshipNotices;
10623
- knowledgeCutoff(scope, request3) {
10624
- return knowledgeCutoff(this.db, scope, request3);
10733
+ knowledgeCutoff(scope, request4) {
10734
+ return knowledgeCutoff(this.db, scope, request4);
10625
10735
  }
10626
10736
  knowledgeSnapshot(scope, cutoff) {
10627
10737
  return historicalRows(this.db, scope, "scope", cutoff)[0] ?? { entityRevision: 0, factRevision: 0, contextRevision: 0, sourceSeq: 0, interpretedSeq: 0 };
@@ -10854,6 +10964,35 @@ CREATE TABLE IF NOT EXISTS cluster_members (
10854
10964
  };
10855
10965
  }, scope, version);
10856
10966
  }
10967
+ /** 1123 跨轮去重(md):entry id 由正文决定、所在文件由日期决定——日期判定跨轮漂移时新块落到
10968
+ * 另一个日期文件,appendMd 的原位替换只扫目标文件,旧块留成孤儿(妹妹 1122 重洗 44 处双份)。
10969
+ * 单遍扫 episodes:id 在本轮写入表里、但所在文件 ≠ 本轮目标日期的块删掉,entry_count 同步。
10970
+ * 不在本轮写入表里的条目不碰(别的来源/原生记忆)。 */
10971
+ purgeEpisodeEntries(ownerId, targetDateById) {
10972
+ if (!targetDateById.size) return 0;
10973
+ const dir = join12(this.root, "users", ownerId, "episodes");
10974
+ if (!existsSync5(dir)) return 0;
10975
+ let removed = 0;
10976
+ for (const name of readdirSync(dir)) {
10977
+ const fileDate = /^episode-(\d{4}-\d{2}-\d{2})\.md$/.exec(name)?.[1];
10978
+ if (!fileDate) continue;
10979
+ const file2 = join12(dir, name);
10980
+ let text2 = readFileSync8(file2, "utf8"), hit = false;
10981
+ for (const m of text2.matchAll(/<!-- entry:(\S+) -->/g)) {
10982
+ const target = targetDateById.get(m[1]);
10983
+ if (target === void 0 || target === fileDate) continue;
10984
+ text2 = text2.replace(new RegExp(`\\n*<!-- entry:${m[1]} -->[\\s\\S]*?<!-- /entry:${m[1]} -->`), "");
10985
+ removed++;
10986
+ hit = true;
10987
+ }
10988
+ if (!hit) continue;
10989
+ text2 = text2.replace(/entry_count: \d+/, `entry_count: ${(text2.match(/<!-- entry:/g) ?? []).length}`);
10990
+ const tmp = `${file2}.${process.pid}.tmp`;
10991
+ writeFileSync6(tmp, text2);
10992
+ renameSync3(tmp, file2);
10993
+ }
10994
+ return removed;
10995
+ }
10857
10996
  appendAtomicFacts(ownerId, dateStr, entries, scope, version) {
10858
10997
  const flat2 = [];
10859
10998
  for (const e of entries) {
@@ -11754,10 +11893,10 @@ ${e.outcome}
11754
11893
  ];
11755
11894
  if (revalidationKinds.length === 0) return 0;
11756
11895
  for (const scope of this.sources.scopes()) {
11757
- const received = this.sources.interpretationProgress(scope).received;
11896
+ const received2 = this.sources.interpretationProgress(scope).received;
11758
11897
  for (const artifact of this.dependencies.dirty(scope)) {
11759
11898
  if (!revalidationKinds.includes(artifact.kind)) continue;
11760
- 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;
11761
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));
11762
11901
  for (const row of previous) {
11763
11902
  const payload = JSON.parse(row.payload);
@@ -12701,10 +12840,6 @@ var init_process_card = __esm({
12701
12840
  });
12702
12841
  return this.creation;
12703
12842
  }
12704
- /** Mode decisions can start native progress without awaiting any channel I/O. */
12705
- start() {
12706
- if (!this.ended && !this.started && (this.nativeCapable() || this.legacyCapable() || this.progressCapable())) this.beginInBackground();
12707
- }
12708
12843
  progressCapable() {
12709
12844
  return !!this.adapter.sendProgress && !!this.adapter.updateProgress && !!this.adapter.removeProgress;
12710
12845
  }
@@ -12845,8 +12980,7 @@ var init_process_card = __esm({
12845
12980
  }
12846
12981
  /** stream_event content_block_delta(thinking_delta):实时喂思考内容 */
12847
12982
  onThinkingDelta(chunk) {
12848
- if (!chunk || this.ended || this.disposed) return;
12849
- this.ensureStarted();
12983
+ if (!chunk || this.ended || this.disposed || !this.started) return;
12850
12984
  const lt = this.state.liveThink ??= { start: Date.now(), text: "" };
12851
12985
  lt.text += chunk;
12852
12986
  if (lt.text.length > 800) lt.text = lt.text.slice(-600);
@@ -12864,8 +12998,7 @@ var init_process_card = __esm({
12864
12998
  }
12865
12999
  /** assistant thinking 完整块(无增量流时的兜底;增量路径下与 Thought 行去重) */
12866
13000
  onThinking(text2) {
12867
- if (this.ended || this.disposed) return;
12868
- this.ensureStarted();
13001
+ if (this.ended || this.disposed || !this.started) return;
12869
13002
  if (this.state.liveThink) return;
12870
13003
  const last = this.state.rows[this.state.rows.length - 1];
12871
13004
  if (last?.kind === "think") return;
@@ -12877,10 +13010,10 @@ var init_process_card = __esm({
12877
13010
  const rid = this.nextRid("p");
12878
13011
  const preview = stripCardUnsafe(toolArgsSummary(toolName, input) || oneLine(JSON.stringify(input).slice(0, 200)));
12879
13012
  return new Promise((resolve13) => {
12880
- let settled = false;
13013
+ let settled2 = false;
12881
13014
  const settle = (v, message) => {
12882
- if (settled) return;
12883
- settled = true;
13015
+ if (settled2) return;
13016
+ settled2 = true;
12884
13017
  clearTimeout(timer);
12885
13018
  pendingPerms.delete(rid);
12886
13019
  this.currentPermRid = null;
@@ -12908,10 +13041,10 @@ var init_process_card = __esm({
12908
13041
  const rid = this.nextRid("q");
12909
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) })) }));
12910
13043
  return new Promise((resolve13) => {
12911
- let settled = false;
13044
+ let settled2 = false;
12912
13045
  const settle = (answers, message) => {
12913
- if (settled) return;
12914
- settled = true;
13046
+ if (settled2) return;
13047
+ settled2 = true;
12915
13048
  clearTimeout(timer);
12916
13049
  pendingAsks.delete(rid);
12917
13050
  this.currentAskRid = null;
@@ -13002,7 +13135,7 @@ var init_process_card = __esm({
13002
13135
  return;
13003
13136
  }
13004
13137
  if (this.patchTimer) return;
13005
- 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;
13006
13139
  const wait2 = Math.max(0, min - (Date.now() - this.lastPatchAt));
13007
13140
  this.patchTimer = setTimeout(() => {
13008
13141
  this.patchTimer = null;
@@ -13017,10 +13150,6 @@ var init_process_card = __esm({
13017
13150
  await this.creation?.catch(() => {
13018
13151
  });
13019
13152
  if (this.disposed || this.ended && !final) return;
13020
- 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)) {
13021
- await this.removeCard().catch((error) => console.warn("[process-card] \u7A7A\u56DE\u5408\u6E05\u7406\u5931\u8D25:", error instanceof Error ? error.message : String(error)));
13022
- return;
13023
- }
13024
13153
  const pushed = await this.doPatch(final);
13025
13154
  if (final && !pushed && !this.disposed && this.options.sendSummary && !this.summarySent) {
13026
13155
  this.summarySent = true;
@@ -13044,8 +13173,8 @@ var init_process_card = __esm({
13044
13173
  }
13045
13174
  async doPatch(final = false) {
13046
13175
  if (this.degraded || !this.messageId && this.channelV !== "cardkit") return false;
13047
- const key2 = this.pushKey();
13048
- if (key2 === this.lastPushKey) return true;
13176
+ const key4 = this.pushKey();
13177
+ if (key4 === this.lastPushKey) return true;
13049
13178
  this.lastPatchAt = Date.now();
13050
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);
13051
13180
  if (this.channelV !== "preview" && this.channelV !== "progress" && !card) return false;
@@ -13061,7 +13190,7 @@ var init_process_card = __esm({
13061
13190
  await this.adapter.patchCard(this.messageId, card);
13062
13191
  } else return false;
13063
13192
  this.patchFailures = 0;
13064
- this.lastPushKey = key2;
13193
+ this.lastPushKey = key4;
13065
13194
  return true;
13066
13195
  } catch (err) {
13067
13196
  if (this.channelV === "cardkit" && isPermissionDenied(err)) {
@@ -13071,7 +13200,7 @@ var init_process_card = __esm({
13071
13200
  await this.removeCard();
13072
13201
  if (this.disposed) return false;
13073
13202
  await this.createLegacyCard();
13074
- this.lastPushKey = key2;
13203
+ this.lastPushKey = key4;
13075
13204
  this.patchFailures = 0;
13076
13205
  if (!this.ended) this.startHeartbeat();
13077
13206
  return true;
@@ -13206,23 +13335,23 @@ var init_session_map = __esm({
13206
13335
  this.map = {};
13207
13336
  }
13208
13337
  }
13209
- get(key2) {
13210
- return this.map[key2];
13338
+ get(key4) {
13339
+ return this.map[key4];
13211
13340
  }
13212
- set(key2, sessionId, workDir) {
13213
- 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() };
13214
13343
  this.save();
13215
13344
  }
13216
13345
  /** 清掉 binding 的会话绑定(/cc-new)。返回是否真的清了。 */
13217
- clear(key2) {
13218
- if (!(key2 in this.map)) return false;
13219
- delete this.map[key2];
13346
+ clear(key4) {
13347
+ if (!(key4 in this.map)) return false;
13348
+ delete this.map[key4];
13220
13349
  this.save();
13221
13350
  return true;
13222
13351
  }
13223
13352
  /** /cc-switch 直写目标会话 */
13224
- switchTo(key2, sessionId, workDir) {
13225
- this.set(key2, sessionId, workDir);
13353
+ switchTo(key4, sessionId, workDir) {
13354
+ this.set(key4, sessionId, workDir);
13226
13355
  }
13227
13356
  save() {
13228
13357
  try {
@@ -13238,6 +13367,52 @@ var init_session_map = __esm({
13238
13367
  }
13239
13368
  });
13240
13369
 
13370
+ // src/cc-driver/long-http.ts
13371
+ import { request as request3 } from "node:http";
13372
+ function longPostJson(url, body, headers = {}, signal) {
13373
+ const data = Buffer.from(JSON.stringify(body));
13374
+ return new Promise((resolve13, reject) => {
13375
+ const req = request3(url, { method: "POST", headers: { ...headers, "Content-Length": String(data.byteLength) } }, (res) => {
13376
+ const chunks = [];
13377
+ res.on("data", (chunk) => chunks.push(chunk));
13378
+ res.on("error", reject);
13379
+ res.on("end", () => {
13380
+ cleanup();
13381
+ const text2 = Buffer.concat(chunks).toString("utf8");
13382
+ try {
13383
+ resolve13({ status: res.statusCode ?? 0, json: JSON.parse(text2) });
13384
+ } catch {
13385
+ reject(new Error(`\u5BF9\u7AEF\u8FD4\u56DE\u4E86\u975E JSON\uFF08HTTP ${res.statusCode}\uFF09\uFF1A${text2.slice(0, 200)}`));
13386
+ }
13387
+ });
13388
+ });
13389
+ req.on("error", (err) => {
13390
+ cleanup();
13391
+ reject(err);
13392
+ });
13393
+ const onAbort = () => {
13394
+ req.destroy();
13395
+ reject(signal.reason instanceof Error ? signal.reason : new Error("\u8BF7\u6C42\u5DF2\u53D6\u6D88"));
13396
+ };
13397
+ const cleanup = () => {
13398
+ signal?.removeEventListener("abort", onAbort);
13399
+ };
13400
+ if (signal) {
13401
+ if (signal.aborted) {
13402
+ onAbort();
13403
+ return;
13404
+ }
13405
+ signal.addEventListener("abort", onAbort, { once: true });
13406
+ }
13407
+ req.end(data);
13408
+ });
13409
+ }
13410
+ var init_long_http = __esm({
13411
+ "src/cc-driver/long-http.ts"() {
13412
+ "use strict";
13413
+ }
13414
+ });
13415
+
13241
13416
  // src/cc-driver/desktop.ts
13242
13417
  import fs4 from "node:fs";
13243
13418
  import os2 from "node:os";
@@ -13289,14 +13464,13 @@ async function findDesktopTargets(workDir, sessionId) {
13289
13464
  return targets;
13290
13465
  }
13291
13466
  async function askDesktop(target, prompt, source, signal) {
13292
- const response = await fetch(`http://127.0.0.1:${target.port}/ask`, {
13293
- method: "POST",
13294
- headers: { authorization: `Bearer ${target.token}`, "content-type": "application/json" },
13295
- signal,
13296
- body: JSON.stringify({ prompt, source, sessionId: target.sessionId, instance: target.instance, workDir: target.workDir })
13297
- });
13298
- const result = await response.json();
13299
- if (!response.ok) throw failure(result.error || `Desktop CC HTTP ${response.status}`, response.status);
13467
+ const { status, json: result } = await longPostJson(
13468
+ `http://127.0.0.1:${target.port}/ask`,
13469
+ { prompt, source, sessionId: target.sessionId, instance: target.instance, workDir: target.workDir },
13470
+ { authorization: `Bearer ${target.token}` },
13471
+ signal
13472
+ );
13473
+ if (status !== 200) throw failure(result?.error || `Desktop CC HTTP ${status}`, status);
13300
13474
  if (result.sessionId !== target.sessionId || typeof result.text !== "string" || typeof result.isError !== "boolean") {
13301
13475
  throw failure("Desktop CC returned an invalid result");
13302
13476
  }
@@ -13306,6 +13480,7 @@ var registryDir, canonical2, failure, alive;
13306
13480
  var init_desktop = __esm({
13307
13481
  "src/cc-driver/desktop.ts"() {
13308
13482
  "use strict";
13483
+ init_long_http();
13309
13484
  registryDir = () => process.env.CC_DESKTOP_REGISTRY_DIR || path4.join(os2.homedir(), ".engine7", "cc-driver", "desktops");
13310
13485
  canonical2 = (dir) => {
13311
13486
  try {
@@ -13429,9 +13604,9 @@ function sharedNodeModules() {
13429
13604
  function pkgDir(name) {
13430
13605
  return path5.join(sharedNodeModules(), ...name.split("/"));
13431
13606
  }
13432
- function readConfig(key2) {
13607
+ function readConfig(key4) {
13433
13608
  try {
13434
- return liveConfig.get(key2);
13609
+ return liveConfig.get(key4);
13435
13610
  } catch {
13436
13611
  }
13437
13612
  }
@@ -13446,9 +13621,9 @@ function downloadsEnabled() {
13446
13621
  function currentPlatformKey() {
13447
13622
  return `${process.platform}-${process.arch}`;
13448
13623
  }
13449
- function featureSpec(key2) {
13450
- const spec = OPTIONAL_FEATURES[key2];
13451
- 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}`);
13452
13627
  return spec;
13453
13628
  }
13454
13629
  function markerPath(spec) {
@@ -13461,8 +13636,8 @@ function isPkgInstalled(spec) {
13461
13636
  return false;
13462
13637
  }
13463
13638
  }
13464
- function isOptionalFeatureInstalled(key2) {
13465
- const spec = featureSpec(key2);
13639
+ function isOptionalFeatureInstalled(key4) {
13640
+ const spec = featureSpec(key4);
13466
13641
  if (!isPkgInstalled(spec.main)) return false;
13467
13642
  const plat = spec.platform?.[currentPlatformKey()];
13468
13643
  if (plat && !isPkgInstalled(plat)) return false;
@@ -13566,9 +13741,9 @@ function notInstalledError(spec) {
13566
13741
  err.code = "ERR_MODULE_NOT_FOUND";
13567
13742
  return err;
13568
13743
  }
13569
- async function ensureOptionalFeature(key2, onProgress) {
13570
- const spec = featureSpec(key2);
13571
- 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);
13572
13747
  if (!downloadsEnabled()) throw notInstalledError(spec);
13573
13748
  const plat = spec.platform?.[currentPlatformKey()];
13574
13749
  const pkgs = [spec.main, ...plat ? [plat] : [], ...spec.extra ?? []];
@@ -13579,17 +13754,17 @@ function requireFromShared(name) {
13579
13754
  const req = createRequire3(path5.join(sharedNodeModules(), ".e7-resolve.js"));
13580
13755
  return req(name);
13581
13756
  }
13582
- async function loadOptionalModule(key2, onProgress) {
13583
- const spec = featureSpec(key2);
13757
+ async function loadOptionalModule(key4, onProgress) {
13758
+ const spec = featureSpec(key4);
13584
13759
  const notFound = (err) => err?.code === "ERR_MODULE_NOT_FOUND" || err?.code === "MODULE_NOT_FOUND";
13585
13760
  try {
13586
13761
  return nodeRequire(spec.main.name);
13587
13762
  } catch (err) {
13588
13763
  if (!notFound(err)) throw err;
13589
13764
  }
13590
- if (!isOptionalFeatureInstalled(key2)) {
13765
+ if (!isOptionalFeatureInstalled(key4)) {
13591
13766
  if (!downloadsEnabled()) throw notInstalledError(spec);
13592
- await ensureOptionalFeature(key2, onProgress);
13767
+ await ensureOptionalFeature(key4, onProgress);
13593
13768
  }
13594
13769
  const dir = pkgDir(spec.main.name);
13595
13770
  try {
@@ -13619,11 +13794,11 @@ var init_dep_downloader = __esm({
13619
13794
  OPTIONAL_FEATURES = (() => {
13620
13795
  const raw = optional_deps_default;
13621
13796
  const out = {};
13622
- for (const [key2, v] of Object.entries(raw)) {
13623
- if (key2 === "//") continue;
13797
+ for (const [key4, v] of Object.entries(raw)) {
13798
+ if (key4 === "//") continue;
13624
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-")));
13625
- 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`);
13626
- 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 };
13627
13802
  }
13628
13803
  return out;
13629
13804
  })();
@@ -13633,6 +13808,8 @@ var init_dep_downloader = __esm({
13633
13808
  });
13634
13809
 
13635
13810
  // src/cc-driver/driver.ts
13811
+ import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync8 } from "node:fs";
13812
+ import { extname, join as join15 } from "node:path";
13636
13813
  function requestError(message, status = 409) {
13637
13814
  return Object.assign(new Error(message), { status });
13638
13815
  }
@@ -14242,14 +14419,16 @@ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
14242
14419
  return task;
14243
14420
  }
14244
14421
  };
14245
- CcDriverHub = class {
14422
+ CcDriverHub = class _CcDriverHub {
14246
14423
  map;
14247
14424
  sessions = /* @__PURE__ */ new Map();
14248
14425
  cfg;
14249
14426
  cm;
14427
+ stateDir;
14250
14428
  constructor(cfg, cm, stateDir, predecessor) {
14251
14429
  this.cfg = cfg;
14252
14430
  this.cm = cm;
14431
+ this.stateDir = stateDir;
14253
14432
  this.map = new CcSessionMapStore(stateDir);
14254
14433
  for (const b of cfg.bindings) {
14255
14434
  this.sessions.set(bindingKey(b), new CcDriverSession(b, cm, this.map, predecessor));
@@ -14259,15 +14438,49 @@ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
14259
14438
  matches(inbound) {
14260
14439
  return findBinding(inbound, this.cfg) !== null;
14261
14440
  }
14262
- /** 路由一条命中消息(调用方已 matches 过)。附件消息 MVP 不支持,提示。 */
14441
+ /** 落盘附件的体积上限:这条通道只收图/文档,不让大视频把 stateDir 撑爆 */
14442
+ static MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024;
14443
+ /**
14444
+ * 入站附件落盘(1123 翀哥:「我给你发图片你现在收不到」):CC 会话靠工具读文件——
14445
+ * 图片用 Read 工具直接看,文档走对应 skill。只做落盘+正文附路径,不改 CC 的输入协议。
14446
+ * 落在 <stateDir>/media/inbound(与 my-eyes 等同目录惯例);单个附件失败不影响其它附件和正文。
14447
+ */
14448
+ async saveAttachments(inbound) {
14449
+ const lines = [];
14450
+ const dir = join15(this.stateDir, "media", "inbound");
14451
+ for (const [i, a] of (inbound.attachments ?? []).entries()) {
14452
+ const label = a.filename || `\u9644\u4EF6${i + 1}`;
14453
+ try {
14454
+ if (!a.loadBytes) throw new Error("\u9002\u914D\u5668\u672A\u63D0\u4F9B\u4E0B\u8F7D\u80FD\u529B");
14455
+ if (a.size > _CcDriverHub.MAX_ATTACHMENT_BYTES) throw new Error(`\u6587\u4EF6\u8FC7\u5927\uFF08${a.size} \u5B57\u8282\uFF09\uFF0C\u672A\u843D\u76D8`);
14456
+ const bytes2 = await a.loadBytes();
14457
+ const ext = extname(a.filename || "").toLowerCase().replace(/[^.a-z0-9]/g, "") || (a.contentType.startsWith("image/") ? "." + a.contentType.slice(6).replace("jpeg", "jpg") : "");
14458
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:T]/g, "").slice(0, 14);
14459
+ const tail = (inbound.messageId || "msg").replace(/\W/g, "").slice(-8);
14460
+ const file2 = join15(dir, `${stamp}-${tail}-${i + 1}${ext}`);
14461
+ mkdirSync9(dir, { recursive: true });
14462
+ writeFileSync8(file2, bytes2);
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`;
14464
+ lines.push(`${i + 1}. ${label}\uFF0C${how}\uFF1A${file2}`);
14465
+ } catch (err) {
14466
+ lines.push(`${i + 1}. ${label} \u843D\u76D8\u5931\u8D25\uFF1A${err?.message || String(err)}`);
14467
+ }
14468
+ }
14469
+ return `\uFF08\u6536\u5230 ${lines.length} \u4E2A\u9644\u4EF6\uFF0C\u5DF2\u4FDD\u5B58\u5230\u672C\u673A\uFF1A
14470
+ ${lines.join("\n")}\uFF09`;
14471
+ }
14472
+ /** 路由一条命中消息(调用方已 matches 过)。附件先落盘,路径随正文一起进会话(1123)。 */
14263
14473
  route(inbound) {
14264
14474
  const binding = findBinding(inbound, this.cfg);
14265
14475
  if (!binding) return;
14266
14476
  const session = this.sessions.get(bindingKey(binding));
14267
14477
  if (!session) return;
14268
14478
  if (inbound.attachments?.length) {
14269
- void session.enqueue(`${inbound.content}
14270
- \uFF08\u6536\u5230 ${inbound.attachments.length} \u4E2A\u9644\u4EF6\u2014\u2014CC \u7EC8\u7AEF\u6682\u4E0D\u652F\u6301\u9644\u4EF6\uFF0C\u53EA\u5904\u7406\u4E86\u6587\u5B57\u90E8\u5206\uFF09`);
14479
+ void this.saveAttachments(inbound).then((note) => session.enqueue(inbound.content.trim() ? `${inbound.content}
14480
+
14481
+ ${note}` : note)).catch((err) => session.enqueue(`${inbound.content}
14482
+
14483
+ \uFF08\u9644\u4EF6\u5904\u7406\u5931\u8D25\uFF1A${err?.message || String(err)}\uFF09`));
14271
14484
  return;
14272
14485
  }
14273
14486
  session.enqueue(inbound.content);
@@ -14277,10 +14490,10 @@ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
14277
14490
  return this.sessions.get(`${channel}:${chatId}`);
14278
14491
  }
14279
14492
  /** 按 bindingKey(channel:chatId)找 session——卡片停止钮回调用(1119) */
14280
- forChatKey(key2) {
14281
- const idx = key2.indexOf(":");
14493
+ forChatKey(key4) {
14494
+ const idx = key4.indexOf(":");
14282
14495
  if (idx <= 0) return void 0;
14283
- return this.sessions.get(key2);
14496
+ return this.sessions.get(key4);
14284
14497
  }
14285
14498
  /** 全部绑定的工作目录(去重;cc-progress 工具省参推断用) */
14286
14499
  get bindingWorkDirs() {
@@ -14289,8 +14502,8 @@ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
14289
14502
  get bindings() {
14290
14503
  return [...this.sessions.values()].map((s) => ({ key: s.key, workDir: s.workDir, sessionId: s.currentSessionId, busy: s.busy }));
14291
14504
  }
14292
- ask(key2, workDir, prompt, source, expectedSessionId, signal) {
14293
- const session = this.sessions.get(key2);
14505
+ ask(key4, workDir, prompt, source, expectedSessionId, signal) {
14506
+ const session = this.sessions.get(key4);
14294
14507
  if (!session) return Promise.reject(requestError("CC binding not found", 404));
14295
14508
  if (session.workDir !== workDir) return Promise.reject(requestError("CC binding workDir changed"));
14296
14509
  return session.ask(prompt, source, expectedSessionId, signal);
@@ -14316,7 +14529,7 @@ function registerCcHub(hub2, stateDir, port) {
14316
14529
  const dir = registryDir2();
14317
14530
  fs6.mkdirSync(dir, { recursive: true, mode: 448 });
14318
14531
  const file2 = path6.join(dir, `${process.pid}.json`);
14319
- 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 })) };
14320
14533
  const tmp = `${file2}.tmp`;
14321
14534
  fs6.writeFileSync(tmp, JSON.stringify(endpoint), { mode: 384 });
14322
14535
  fs6.renameSync(tmp, file2);
@@ -14330,6 +14543,7 @@ function registerCcHub(hub2, stateDir, port) {
14330
14543
  var init_handoff = __esm({
14331
14544
  "src/cc-driver/handoff.ts"() {
14332
14545
  "use strict";
14546
+ init_long_http();
14333
14547
  init_router();
14334
14548
  }
14335
14549
  });
@@ -14555,11 +14769,11 @@ __export(dispatches_exports, {
14555
14769
  finishCalendarDispatch: () => finishCalendarDispatch,
14556
14770
  recoverCalendarDispatches: () => recoverCalendarDispatches
14557
14771
  });
14558
- function beginCalendarDispatch(db2, key2, binding, context) {
14772
+ function beginCalendarDispatch(db2, key4, binding, context) {
14559
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");
14560
14774
  return Boolean(db2.prepare(`INSERT OR IGNORE INTO calendar_dispatches
14561
14775
  (dispatch_key,event_id,binding_version,occurrence_id,state,started_at,scope_id,context_json) VALUES (?,?,?,?,'started',?,?,?)`).run(
14562
- key2,
14776
+ key4,
14563
14777
  binding.eventId,
14564
14778
  binding.version,
14565
14779
  binding.occurrenceId,
@@ -14568,8 +14782,8 @@ function beginCalendarDispatch(db2, key2, binding, context) {
14568
14782
  context ? JSON.stringify(context) : null
14569
14783
  ).changes);
14570
14784
  }
14571
- function finishCalendarDispatch(db2, key2, state) {
14572
- 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);
14573
14787
  }
14574
14788
  function recoverCalendarDispatches(db2) {
14575
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);
@@ -15045,7 +15259,7 @@ var init_intent_state = __esm({
15045
15259
  // src/memory/proactive/mutation-service.ts
15046
15260
  function canonical3(value) {
15047
15261
  if (Array.isArray(value)) return value.map(canonical3);
15048
- 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)]));
15049
15263
  return value;
15050
15264
  }
15051
15265
  var graphBasis;
@@ -15242,18 +15456,18 @@ function createGraphMemoryValidator(memory) {
15242
15456
  }
15243
15457
  const scope = memory?.sources.scope(scopeKey);
15244
15458
  if (!memory || !scope) throw new Error("GRAPH_MEMORY_READ_GUARD_REQUIRED");
15245
- 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));
15246
15460
  memory.dependencies.assertReferences(scope, unseen.map(([, ref]) => ref));
15247
- for (const [key2] of unseen) checkedRefs.add(key2);
15461
+ for (const [key4] of unseen) checkedRefs.add(key4);
15248
15462
  const sourceIds = [.../* @__PURE__ */ new Set([
15249
15463
  ...refs.filter((ref) => ref.parentKind === "source").map((ref) => ref.parentId),
15250
15464
  ...typeof node.data.socialSourceId === "string" ? [node.data.socialSourceId] : []
15251
15465
  ])];
15252
15466
  for (const id3 of sourceIds) {
15253
- const key2 = JSON.stringify([scopeKey, id3]);
15254
- if (checkedSources.has(key2)) continue;
15467
+ const key4 = JSON.stringify([scopeKey, id3]);
15468
+ if (checkedSources.has(key4)) continue;
15255
15469
  if (!memory.socialSources.readable(scope, id3) || !memory.socialSources.groundsCurrent(scope, id3)) throw new Error("STALE_GRAPH_SOCIAL_SOURCE");
15256
- checkedSources.add(key2);
15470
+ checkedSources.add(key4);
15257
15471
  }
15258
15472
  const relation = node.data.relationshipRef;
15259
15473
  const relationshipKey = relation && JSON.stringify([scopeKey, relation]);
@@ -15286,7 +15500,7 @@ function digest5(value) {
15286
15500
  }
15287
15501
  function generationBasis(intent) {
15288
15502
  const data = { ...intent.data };
15289
- 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];
15290
15504
  return graphBasis({ ...intent, data });
15291
15505
  }
15292
15506
  var IntentRunStore;
@@ -15490,9 +15704,9 @@ CREATE TABLE memory_projection_heads (
15490
15704
  }
15491
15705
  inspect(event2) {
15492
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");
15493
- const received = this.db.prepare("SELECT payload_hash FROM memory_projection_inbox WHERE event_id=?").get(event2.eventId);
15494
- if (received) {
15495
- 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");
15496
15710
  return "duplicate";
15497
15711
  }
15498
15712
  if (event2.eventSeq !== this.position(event2.scopeId) + 1) throw new Error("PROJECTION_SEQUENCE_GAP");
@@ -15522,9 +15736,9 @@ CREATE TABLE memory_projection_heads (
15522
15736
  * 详见 docs/research/2026-10-20-mem7-poison-delivery-followup.md。 */
15523
15737
  skip(event2) {
15524
15738
  if (event2.schemaVersion !== 1 || !event2.eventId || !event2.scopeId || !Number.isSafeInteger(event2.eventSeq) || event2.eventSeq < 1) throw new Error("INVALID_PROJECTION_EVENT");
15525
- const received = this.db.prepare("SELECT payload_hash FROM memory_projection_inbox WHERE event_id=?").get(event2.eventId);
15526
- if (received) {
15527
- 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");
15528
15742
  return;
15529
15743
  }
15530
15744
  if (event2.eventSeq !== this.position(event2.scopeId) + 1) throw new Error("PROJECTION_SEQUENCE_GAP");
@@ -15720,20 +15934,20 @@ CREATE INDEX idx_action_dispatch_state ON action_dispatches(state,started_at);
15720
15934
  constructor(db2) {
15721
15935
  this.db = db2;
15722
15936
  }
15723
- begin(key2, scopeId2, versions) {
15937
+ begin(key4, scopeId2, versions) {
15724
15938
  const result = this.db.prepare(`INSERT OR IGNORE INTO action_dispatches
15725
- (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());
15726
15940
  if (!result.changes) return false;
15727
15941
  for (const id3 of Object.keys(versions)) this.db.prepare(`UPDATE actions SET dispatch_key=?,dispatch_state='started'
15728
- WHERE id=? AND scope_id=?`).run(key2, id3, scopeId2);
15942
+ WHERE id=? AND scope_id=?`).run(key4, id3, scopeId2);
15729
15943
  return true;
15730
15944
  }
15731
- finish(key2, state, receipt) {
15732
- 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);
15733
15947
  if (!row || row.state !== "started") return;
15734
- 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);
15735
15949
  for (const id3 of Object.keys(JSON.parse(row.action_versions))) this.db.prepare(`UPDATE actions SET dispatch_state=?
15736
- WHERE id=? AND dispatch_key=?`).run(state, id3, key2);
15950
+ WHERE id=? AND dispatch_key=?`).run(state, id3, key4);
15737
15951
  }
15738
15952
  /** Called once by the owning plugin at startup, never by another connection's constructor. */
15739
15953
  recoverInterrupted() {
@@ -15760,15 +15974,15 @@ var init_host_deliveries = __esm({
15760
15974
  this.db = db2;
15761
15975
  }
15762
15976
  enqueue(actionId, version, blocks, context) {
15763
- const key2 = JSON.stringify(["proactive", actionId, version]);
15764
- 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());
15765
- 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;
15766
15980
  }
15767
15981
  pending() {
15768
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) }));
15769
15983
  }
15770
- finish(key2, state, reason) {
15771
- 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);
15772
15986
  }
15773
15987
  list(scope, options = {}) {
15774
15988
  const where = scope ? ["a.scope_id=? AND json_extract(h.context_json,'$.scopeId')=?"] : [];
@@ -15812,7 +16026,7 @@ __export(persistence_exports, {
15812
16026
  normalizeToUtcIso: () => normalizeToUtcIso
15813
16027
  });
15814
16028
  import { DatabaseSync as DatabaseSync12 } from "node:sqlite";
15815
- import { mkdirSync as mkdirSync10 } from "node:fs";
16029
+ import { mkdirSync as mkdirSync11 } from "node:fs";
15816
16030
  import { basename as basename3, dirname as dirname7, resolve as resolve6 } from "node:path";
15817
16031
  function rowToAction(r) {
15818
16032
  return {
@@ -15950,7 +16164,7 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
15950
16164
  checkRuntimeReplicationFile(dbPath, registration, Boolean(options.replication));
15951
16165
  this.releaseRuntimeWriter = registration || options.replication ? registerRuntimeWriter(stateDir, "proactive") : void 0;
15952
16166
  try {
15953
- mkdirSync10(dirname7(dbPath), { recursive: true });
16167
+ mkdirSync11(dirname7(dbPath), { recursive: true });
15954
16168
  this.db = new DatabaseSync12(dbPath);
15955
16169
  } catch (error) {
15956
16170
  this.releaseRuntimeWriter?.();
@@ -16038,7 +16252,8 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16038
16252
  this.replication = enrollRuntimeReplication(this.db, stateDir, "proactive", binding);
16039
16253
  this.capture = installSQLiteWriteCapture(this.db, this.replication);
16040
16254
  }
16041
- 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()));
16042
16257
  } catch (error) {
16043
16258
  try {
16044
16259
  this.capture?.close();
@@ -16137,6 +16352,12 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16137
16352
  graphRevision() {
16138
16353
  return Number(this.db.prepare("SELECT revision FROM graph_state WHERE id=1").get().revision);
16139
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
+ }
16140
16361
  // B7.1(astra review):SQL 级联失效(invalidateGraphChildren/invalidateMemoryEvent)改动的
16141
16362
  // 节点不在调用方 delta 里——事务内收集,提交后由 GraphStore 逐 id 单行刷回缓存。
16142
16363
  cascadeTouched = [];
@@ -16229,6 +16450,9 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16229
16450
  const edges = new Map(keys.flatMap((id3) => this.loadIncidentEdges(id3)).map((edge) => [edgeKey(edge.source, edge.target, edge.edgeType), edge]));
16230
16451
  return { nodes, edges: [...edges.values()], revision: this.graphRevision() };
16231
16452
  };
16453
+ return this.readGraphTransaction(read2);
16454
+ }
16455
+ readGraphTransaction(read2) {
16232
16456
  if (this.inTransaction) return read2();
16233
16457
  this.db.exec("BEGIN");
16234
16458
  try {
@@ -16240,9 +16464,18 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16240
16464
  throw error;
16241
16465
  }
16242
16466
  }
16243
- loadNodes() {
16244
- const rows = this.db.prepare("SELECT * FROM nodes").all();
16245
- 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) => ({
16246
16479
  id: r.id,
16247
16480
  type: r.type,
16248
16481
  data: JSON.parse(r.data),
@@ -16281,8 +16514,8 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16281
16514
  }));
16282
16515
  }
16283
16516
  loadEdges() {
16284
- const rows = this.db.prepare("SELECT * FROM edges").all();
16285
- return rows.map((r) => ({
16517
+ const rows = this.db.prepare("SELECT * FROM edges").iterate();
16518
+ return Array.from(rows, (r) => ({
16286
16519
  source: r.source,
16287
16520
  target: r.target,
16288
16521
  edgeType: r.edge_type,
@@ -16290,6 +16523,20 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16290
16523
  createdAt: r.created_at
16291
16524
  }));
16292
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
+ }
16293
16540
  // === 图:写(GraphStore 镜像调用) ===
16294
16541
  insertNode(node) {
16295
16542
  this.transaction(() => {
@@ -16323,7 +16570,7 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16323
16570
  this.transaction(() => {
16324
16571
  const previous = knownPrevious ?? this.loadNodeById(node.id);
16325
16572
  if (!previous) throw new Error(`nodes row '${node.id}' missing on update (memory/DB divergence)`);
16326
- 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);
16327
16574
  if (changed && previous.type === "intent") {
16328
16575
  patchIntentState(previous.data, node.data);
16329
16576
  if (stateVersion(node.data) !== stateVersion(previous.data) + 1) throw new Error("STALE_INTENT_VERSION");
@@ -16334,9 +16581,9 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16334
16581
  this.validateOutcomeEvidence(node.data, node.data.completionEvidence);
16335
16582
  }
16336
16583
  }
16337
- 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;
16338
- if (keys && keys.every((key2) => node.data[key2] !== void 0 && (node.data[key2] === null || typeof node.data[key2] !== "object"))) {
16339
- 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])]);
16340
16587
  const data = keys.length ? `json_set(data,${keys.map(() => "?,json(?)").join(",")})` : "data";
16341
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);
16342
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);
@@ -16862,10 +17109,10 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16862
17109
  /** Close a held host turn after evidence-based review; never make the old outbox pending again. */
16863
17110
  reconcileHostDelivery(input, scope) {
16864
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");
16865
- const versions = (provided, key2, version) => {
17112
+ const versions = (provided, key4, version) => {
16866
17113
  if (provided !== void 0 && (!provided || typeof provided !== "object" || Array.isArray(provided))) throw new Error("INVALID_DELIVERY_RECONCILIATION");
16867
- if (provided && Object.hasOwn(provided, key2) && provided[key2] !== version) throw new Error("INVALID_DELIVERY_RECONCILIATION");
16868
- 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));
16869
17116
  if (entries.some(([id3, value]) => !id3 || !Number.isSafeInteger(value) || value < 1)) throw new Error("INVALID_DELIVERY_RECONCILIATION");
16870
17117
  return Object.fromEntries(entries);
16871
17118
  };
@@ -17503,17 +17750,17 @@ __export(paths_exports, {
17503
17750
  isAutoMemPath: () => isAutoMemPath,
17504
17751
  setMemoryDirOverride: () => setMemoryDirOverride
17505
17752
  });
17506
- import { join as join27, normalize as normalize5, sep as sep4, isAbsolute as isAbsolute4, resolve as resolve10 } from "node:path";
17753
+ import { join as join28, normalize as normalize5, sep as sep4, isAbsolute as isAbsolute4, resolve as resolve10 } from "node:path";
17507
17754
  function setMemoryDirOverride(dir) {
17508
17755
  _overrideMemoryDir = dir;
17509
17756
  }
17510
17757
  function getAutoMemPath(workspace) {
17511
- const dir = _overrideMemoryDir ? isAbsolute4(_overrideMemoryDir) ? _overrideMemoryDir : resolve10(workspace, _overrideMemoryDir) : join27(workspace, AUTO_MEM_DIRNAME);
17758
+ const dir = _overrideMemoryDir ? isAbsolute4(_overrideMemoryDir) ? _overrideMemoryDir : resolve10(workspace, _overrideMemoryDir) : join28(workspace, AUTO_MEM_DIRNAME);
17512
17759
  const normalized = normalize5(dir);
17513
17760
  return (normalized + sep4).normalize("NFC");
17514
17761
  }
17515
17762
  function getAutoMemEntrypoint(workspace) {
17516
- return join27(getAutoMemPath(workspace), ENTRYPOINT_NAME);
17763
+ return join28(getAutoMemPath(workspace), ENTRYPOINT_NAME);
17517
17764
  }
17518
17765
  function isAutoMemPath(absolutePath, workspace) {
17519
17766
  const normalizedPath = normalize5(absolutePath);
@@ -17704,7 +17951,7 @@ __export(memdir_exports, {
17704
17951
  truncateEntrypointContent: () => truncateEntrypointContent
17705
17952
  });
17706
17953
  import { readFileSync as readFileSync15 } from "node:fs";
17707
- import { join as join28 } from "node:path";
17954
+ import { join as join29 } from "node:path";
17708
17955
  function truncateEntrypointContent(raw) {
17709
17956
  const trimmed = raw.trim();
17710
17957
  const contentLines = trimmed.split("\n");
@@ -17797,7 +18044,7 @@ function buildMemoryLines(displayName, memoryDir, extraGuidelines, skipIndex = f
17797
18044
  }
17798
18045
  function buildMemoryPrompt(params) {
17799
18046
  const { displayName, memoryDir, extraGuidelines } = params;
17800
- const entrypoint = join28(memoryDir, ENTRYPOINT_NAME);
18047
+ const entrypoint = join29(memoryDir, ENTRYPOINT_NAME);
17801
18048
  let entrypointContent = "";
17802
18049
  try {
17803
18050
  entrypointContent = readFileSync15(entrypoint, { encoding: "utf-8" });
@@ -18196,8 +18443,8 @@ var init_gateway_media = __esm({
18196
18443
  });
18197
18444
 
18198
18445
  // src/continuity/pairing-control.ts
18199
- import { writeFileSync as writeFileSync14, existsSync as existsSync15, rmSync as rmSync3 } from "node:fs";
18200
- import { join as join31, resolve as resolve12 } from "node:path";
18446
+ import { writeFileSync as writeFileSync15, existsSync as existsSync15, rmSync as rmSync3 } from "node:fs";
18447
+ import { join as join32, resolve as resolve12 } from "node:path";
18201
18448
  import { fileURLToPath as fileURLToPath5 } from "node:url";
18202
18449
  import { createServer as createServer4 } from "node:https";
18203
18450
  import { timingSafeEqual, X509Certificate, createHash as createHash37 } from "node:crypto";
@@ -18456,22 +18703,22 @@ var TravelAuthority = class {
18456
18703
  if (operation !== "CONTROL" && row.frozen) throw new Error("TRAVEL_HANDOFF_FROZEN");
18457
18704
  if (operation !== "CONTROL" && permit.deletionWatermark !== Number(row.floor)) throw new Error("TRAVEL_DELETION_BARRIER");
18458
18705
  }
18459
- heartbeat(principal, request3) {
18706
+ heartbeat(principal, request4) {
18460
18707
  return this.transaction(() => {
18461
18708
  const node = this.principal(principal), text2 = identityText2(principal), seat = this.seat(principal);
18462
- natural(request3.sequence);
18463
- if (request3.bootId !== node.boot) throw new Error("TRAVEL_BOOT_MISMATCH");
18464
- if (request3.sequence <= Number(node.sequence)) throw new Error("TRAVEL_HEARTBEAT_REPLAY");
18709
+ natural(request4.sequence);
18710
+ if (request4.bootId !== node.boot) throw new Error("TRAVEL_BOOT_MISMATCH");
18711
+ if (request4.sequence <= Number(node.sequence)) throw new Error("TRAVEL_HEARTBEAT_REPLAY");
18465
18712
  let permit;
18466
- if (request3.permit) {
18467
- this.assertPermit(request3.permit, "CONTROL");
18468
- if (request3.permit.nodeId !== principal.nodeId || !same(identityText2(request3.permit), text2)) throw new Error("TRAVEL_AUTH_DENIED");
18469
- const floor = request3.deletionWatermark ?? request3.permit.deletionWatermark;
18713
+ if (request4.permit) {
18714
+ this.assertPermit(request4.permit, "CONTROL");
18715
+ if (request4.permit.nodeId !== principal.nodeId || !same(identityText2(request4.permit), text2)) throw new Error("TRAVEL_AUTH_DENIED");
18716
+ const floor = request4.deletionWatermark ?? request4.permit.deletionWatermark;
18470
18717
  if (floor !== Number(seat.floor)) throw new Error("TRAVEL_DELETION_BARRIER");
18471
18718
  this.deadlines.set(text2, this.monotonicNow() + this.leaseMs);
18472
18719
  permit = this.issue(principal, seat);
18473
18720
  }
18474
- this.db.prepare("UPDATE nodes SET sequence=? WHERE identity=? AND node_id=?").run(request3.sequence, text2, principal.nodeId);
18721
+ this.db.prepare("UPDATE nodes SET sequence=? WHERE identity=? AND node_id=?").run(request4.sequence, text2, principal.nodeId);
18475
18722
  this.healthy.set(text2 + principal.nodeId, this.monotonicNow() + this.leaseMs);
18476
18723
  return {
18477
18724
  authorityBootId: this.authorityBootId,
@@ -18770,10 +19017,10 @@ function createKeyServiceServer(options) {
18770
19017
  }
18771
19018
  chunks.push(chunk);
18772
19019
  }
18773
- let request3;
19020
+ let request4;
18774
19021
  try {
18775
- request3 = JSON.parse(Buffer.concat(chunks).toString());
18776
- validateKeyIdentity(request3?.identity);
19022
+ request4 = JSON.parse(Buffer.concat(chunks).toString());
19023
+ validateKeyIdentity(request4?.identity);
18777
19024
  } catch {
18778
19025
  reply(400, "KEY_SERVICE_INVALID_REQUEST");
18779
19026
  return;
@@ -18781,13 +19028,13 @@ function createKeyServiceServer(options) {
18781
19028
  let result;
18782
19029
  try {
18783
19030
  const cert = socket.getPeerCertificate();
18784
- result = store.readKey((cert.fingerprint256 ?? "").replaceAll(":", ""), request3.identity, request3.minimumDeletionWatermark);
19031
+ result = store.readKey((cert.fingerprint256 ?? "").replaceAll(":", ""), request4.identity, request4.minimumDeletionWatermark);
18785
19032
  } catch {
18786
19033
  reply(403, "KEY_SERVICE_DENIED");
18787
19034
  return;
18788
19035
  }
18789
19036
  try {
18790
- res.end(JSON.stringify({ protocolVersion: 1, identity: request3.identity, deletionWatermark: result.deletionWatermark, key: result.key.toString("base64") }));
19037
+ res.end(JSON.stringify({ protocolVersion: 1, identity: request4.identity, deletionWatermark: result.deletionWatermark, key: result.key.toString("base64") }));
18791
19038
  } finally {
18792
19039
  result.key.fill(0);
18793
19040
  }
@@ -18989,15 +19236,15 @@ function validManagement(input) {
18989
19236
  if (input.action === "retire" && !(typeof input.jobId === "string" && identifier.test(input.jobId))) return false;
18990
19237
  if (!Object.hasOwn(managementFields, String(input.action))) return false;
18991
19238
  const fields = managementFields[String(input.action)];
18992
- if (!fields || Object.keys(input).some((key2) => !["version", "action", ...fields].includes(key2)) || fields.some((key2) => !Object.hasOwn(input, key2))) return false;
18993
- 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;
18994
- 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;
18995
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;
18996
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;
18997
19244
  if (Object.hasOwn(input, "permit") && !record(input.permit)) return false;
18998
19245
  if (Object.hasOwn(input, "operation") && !["WRITE", "SEND", "TOOL", "INPUT", "PUBLISH", "CONTROL"].includes(String(input.operation))) return false;
18999
- 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;
19000
- 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;
19001
19248
  return true;
19002
19249
  }
19003
19250
  function createTravelAuthorityServer(options) {
@@ -19107,7 +19354,7 @@ function createTravelAuthorityServer(options) {
19107
19354
  return;
19108
19355
  }
19109
19356
  const input = envelope?.travel, keys = input?.action === "register" ? ["version", "action", "bootId"] : input?.action === "heartbeat" ? ["version", "action", "bootId", "sequence", "permit", "deletionWatermark"] : ["version", "action"];
19110
- 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));
19111
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) {
19112
19359
  reply(400, { error: "TRAVEL_CONTROL_INVALID_REQUEST" });
19113
19360
  return;
@@ -19121,7 +19368,7 @@ function createTravelAuthorityServer(options) {
19121
19368
  }
19122
19369
  let result;
19123
19370
  if (managing) {
19124
- 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");
19125
19372
  switch (input.action) {
19126
19373
  case "bindInitialCheckpoint":
19127
19374
  if (!bootstrapGrants.get(peerFingerprint)?.has(principal.credentialHash)) throw new Error("TRAVEL_AUTH_DENIED");
@@ -19282,12 +19529,12 @@ async function fetchTravelKey(options) {
19282
19529
  const wanted = options.identity;
19283
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))
19284
19531
  throw new Error("KEY_SERVICE_INVALID_RESPONSE");
19285
- const key2 = Buffer.from(value.key, "base64");
19286
- if (key2.length !== 32 || key2.toString("base64") !== value.key) {
19287
- 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);
19288
19535
  throw new Error("KEY_SERVICE_INVALID_RESPONSE");
19289
19536
  }
19290
- return { key: key2, deletionWatermark: value.deletionWatermark };
19537
+ return { key: key4, deletionWatermark: value.deletionWatermark };
19291
19538
  }
19292
19539
 
19293
19540
  // src/continuity/gateway-store.ts
@@ -19305,6 +19552,13 @@ import { DatabaseSync as DatabaseSync9 } from "node:sqlite";
19305
19552
  init_store();
19306
19553
  init_mem7_replication();
19307
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
+
19308
19562
  // src/mem7/intake.ts
19309
19563
  init_system_filter();
19310
19564
  init_host_turns();
@@ -19960,7 +20214,7 @@ function createTravelGatewayServer(options) {
19960
20214
  reply(200, store.applyRecoveryDeletedInputs(principal, input.bindings, input.floor));
19961
20215
  return;
19962
20216
  }
19963
- 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");
19964
20218
  if (action === "preparation") {
19965
20219
  if (Object.keys(input).length) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
19966
20220
  reply(200, store.preparationEvidence(principal));
@@ -20012,7 +20266,7 @@ function createTravelGatewayServer(options) {
20012
20266
  const values = action === "produce" ? [input.input] : input.inputs;
20013
20267
  if (!Array.isArray(values) || !values.length || values.length > 100) throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
20014
20268
  const decoded = values.map((value) => {
20015
- 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");
20016
20270
  return { ...value, body: decodeBody(value.bodyBase64) };
20017
20271
  });
20018
20272
  if (input.finalOutput !== void 0 && typeof input.finalOutput !== "boolean") throw new Error("TRAVEL_GATEWAY_INVALID_REQUEST");
@@ -20288,14 +20542,14 @@ var AgentRegistryImpl = class {
20288
20542
  var agentRegistry = new AgentRegistryImpl();
20289
20543
 
20290
20544
  // src/channels/discord.ts
20291
- import { Client, GatewayIntentBits, Partials, ApplicationCommandOptionType } from "discord.js";
20545
+ import { Client, GatewayIntentBits, MessageFlags, Partials, ApplicationCommandOptionType } from "discord.js";
20292
20546
  import { ProxyAgent as UndiciProxyAgent } from "undici";
20293
20547
  import { HttpsProxyAgent } from "https-proxy-agent";
20294
20548
 
20295
20549
  // src/memory/external-effect.ts
20296
20550
  import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
20297
20551
  import { createHash as createHash25 } from "node:crypto";
20298
- import { join as join17 } from "node:path";
20552
+ import { join as join18 } from "node:path";
20299
20553
 
20300
20554
  // src/memory/execution-guard.ts
20301
20555
  init_db();
@@ -20305,7 +20559,7 @@ init_migrations();
20305
20559
  init_context_time();
20306
20560
  init_relationship_notice_check();
20307
20561
  init_dependencies();
20308
- import { join as join16 } from "node:path";
20562
+ import { join as join17 } from "node:path";
20309
20563
  var MemoryExecutionBlockedError = class extends Error {
20310
20564
  constructor(reason) {
20311
20565
  super(`MEMORY_EXECUTION_BLOCKED: ${reason}`);
@@ -20318,7 +20572,7 @@ function checkMemoryExecution(stateDir, workspace, context, activeDispatchKey) {
20318
20572
  let calendar;
20319
20573
  try {
20320
20574
  if (!stateDir || !context.scopeId || !Array.isArray(context.basisRefs)) return { ok: false, reason: "EXECUTION_CONTEXT_INVALID" };
20321
- memory = new DatabaseSync11(join16(stateDir, "mem7", "index", "mem7.db"), { readOnly: true });
20575
+ memory = new DatabaseSync11(join17(stateDir, "mem7", "index", "mem7.db"), { readOnly: true });
20322
20576
  memory.exec("PRAGMA query_only=ON; BEGIN");
20323
20577
  const schema = readSchemaVersion(memory);
20324
20578
  if (schema?.component !== "mem7" || schema.version !== MEM7_SCHEMA_VERSION) return { ok: false, reason: "MEMORY_SCHEMA_UNSUPPORTED" };
@@ -20333,7 +20587,7 @@ function checkMemoryExecution(stateDir, workspace, context, activeDispatchKey) {
20333
20587
  if (!result.ok) return result;
20334
20588
  }
20335
20589
  if (context.calendarBinding) {
20336
- calendar = new DatabaseSync11(join16(workspace, ".calendar", "calendar.db"), { readOnly: true });
20590
+ calendar = new DatabaseSync11(join17(workspace, ".calendar", "calendar.db"), { readOnly: true });
20337
20591
  calendar.exec("PRAGMA query_only=ON; BEGIN");
20338
20592
  const binding = calendar.prepare(`SELECT b.*,e.status event_status,e.memory_version current_event_version FROM calendar_memory_bindings b
20339
20593
  JOIN events e ON e.id=b.event_id WHERE b.event_id=?`).get(context.calendarBinding.eventId);
@@ -20351,7 +20605,7 @@ function checkMemoryExecution(stateDir, workspace, context, activeDispatchKey) {
20351
20605
  if (!bound.ok) return bound;
20352
20606
  }
20353
20607
  if (context.actionVersions && Object.keys(context.actionVersions).length) {
20354
- proactive = new DatabaseSync11(join16(workspace, ".proactive", "proactive.db"), { readOnly: true });
20608
+ proactive = new DatabaseSync11(join17(workspace, ".proactive", "proactive.db"), { readOnly: true });
20355
20609
  proactive.exec("PRAGMA query_only=ON; BEGIN");
20356
20610
  for (const [id3, version] of Object.entries(context.actionVersions)) {
20357
20611
  const action = proactive.prepare("SELECT * FROM actions WHERE id=?").get(id3);
@@ -20523,16 +20777,16 @@ async function guardedExternalEffect(run) {
20523
20777
  Promise.resolve().then(() => (init_dispatches(), dispatches_exports))
20524
20778
  ]);
20525
20779
  const db2 = openDb2(workspace);
20526
- 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");
20527
20781
  try {
20528
20782
  assertMemoryExecution(stateDir, workspace, context);
20529
- 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");
20530
20784
  try {
20531
- const result = await effects.run({ ...host, activeDispatchKey: key3 }, run);
20532
- finishCalendarDispatch2(db2, key3, "delivered");
20785
+ const result = await effects.run({ ...host, activeDispatchKey: key5 }, run);
20786
+ finishCalendarDispatch2(db2, key5, "delivered");
20533
20787
  return result;
20534
20788
  } catch (error) {
20535
- finishCalendarDispatch2(db2, key3, "delivery_unknown");
20789
+ finishCalendarDispatch2(db2, key5, "delivery_unknown");
20536
20790
  throw error;
20537
20791
  }
20538
20792
  } finally {
@@ -20543,23 +20797,23 @@ async function guardedExternalEffect(run) {
20543
20797
  assertMemoryExecution(stateDir, workspace, context);
20544
20798
  return run();
20545
20799
  }
20546
- const persist = new Persistence2(join17(workspace, ".proactive", "proactive.db"));
20547
- const key2 = "dispatch_" + createHash25("sha256").update(JSON.stringify([
20800
+ const persist = new Persistence2(join18(workspace, ".proactive", "proactive.db"));
20801
+ const key4 = "dispatch_" + createHash25("sha256").update(JSON.stringify([
20548
20802
  context.scopeId,
20549
20803
  Object.entries(versions).sort(([a], [b]) => a.localeCompare(b)),
20550
20804
  effectId
20551
20805
  ])).digest("hex");
20552
20806
  try {
20553
20807
  assertMemoryExecution(stateDir, workspace, context);
20554
- if (!persist.transaction(() => persist.dispatches.begin(key2, context.scopeId, versions))) {
20808
+ if (!persist.transaction(() => persist.dispatches.begin(key4, context.scopeId, versions))) {
20555
20809
  throw new MemoryExecutionBlockedError("DISPATCH_ALREADY_STARTED");
20556
20810
  }
20557
20811
  try {
20558
- const result = await effects.run({ ...host, activeDispatchKey: key2 }, run);
20559
- 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"));
20560
20814
  return result;
20561
20815
  } catch (error) {
20562
- persist.transaction(() => persist.dispatches.finish(key2, "delivery_unknown"));
20816
+ persist.transaction(() => persist.dispatches.finish(key4, "delivery_unknown"));
20563
20817
  throw error;
20564
20818
  }
20565
20819
  } finally {
@@ -20645,6 +20899,85 @@ function totalFromContentRange(header) {
20645
20899
  return Number.isFinite(n) && n >= 0 ? n : null;
20646
20900
  }
20647
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
+
20648
20981
  // src/channels/discord.ts
20649
20982
  var DISCORD_MSG_LIMIT = 2e3;
20650
20983
  var DiscordAdapter = class _DiscordAdapter {
@@ -20653,6 +20986,10 @@ var DiscordAdapter = class _DiscordAdapter {
20653
20986
  client;
20654
20987
  config;
20655
20988
  ownsClient;
20989
+ /** 1124:折叠过程卡只在折叠模式下出(没折叠维持逐步显示);编辑型消息的推送节奏 */
20990
+ progressRequiresCollapsed = true;
20991
+ progressThrottleMs = 2500;
20992
+ progressCards;
20656
20993
  messageHandler = null;
20657
20994
  commandHandler = null;
20658
20995
  registeredCommands = [];
@@ -20697,6 +21034,25 @@ var DiscordAdapter = class _DiscordAdapter {
20697
21034
  this.client = new Client(clientOptions);
20698
21035
  this.ownsClient = true;
20699
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);
20700
21056
  }
20701
21057
  /** 暴露 discord.js Client(供 VisualTransport 等模块使用) */
20702
21058
  getClient() {
@@ -21068,6 +21424,23 @@ var DiscordAdapter = class _DiscordAdapter {
21068
21424
  } catch {
21069
21425
  }
21070
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
+ }
21071
21444
  // === Streaming preview — 对齐 cc-connect Discord 的 SendPreviewStart/UpdateMessage/DeletePreviewMessage ===
21072
21445
  // 对齐 cc-connect platform/discord/progress.go:preview 消息用 Embed(彩色标题栏 + 内容)
21073
21446
  /** Embed 颜色常量 — 对齐 cc-connect discordProgressStateMeta */
@@ -21530,8 +21903,8 @@ var FeishuAdapter = class _FeishuAdapter {
21530
21903
  let durationMs = Math.round(fileBuffer.length / 3);
21531
21904
  try {
21532
21905
  const { execFile: execFile2 } = await import("node:child_process");
21533
- const { promisify: promisify3 } = await import("node:util");
21534
- const execFileAsync2 = promisify3(execFile2);
21906
+ const { promisify: promisify4 } = await import("node:util");
21907
+ const execFileAsync2 = promisify4(execFile2);
21535
21908
  const probe = await execFileAsync2("ffprobe", ["-v", "quiet", "-show_format", "-print_format", "json", attachment.path], { timeout: 1e4 });
21536
21909
  const fmt = JSON.parse(probe.stdout);
21537
21910
  if (fmt?.format?.duration) durationMs = Math.round(parseFloat(fmt.format.duration) * 1e3);
@@ -21626,8 +21999,8 @@ var FeishuAdapter = class _FeishuAdapter {
21626
21999
  return fileKey;
21627
22000
  }
21628
22001
  /** 消息资源 URL(三个下载方法 + Range 预探共用) */
21629
- _resourceUrl(messageId, key2, kind) {
21630
- 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}`;
21631
22004
  }
21632
22005
  /** 通过飞书API下载消息中的图片 */
21633
22006
  async _downloadImage(messageId, imageKey, tokenOverride, init) {
@@ -21696,7 +22069,7 @@ var FeishuAdapter = class _FeishuAdapter {
21696
22069
  let totalBytes = 0;
21697
22070
  let token;
21698
22071
  const nameCache = /* @__PURE__ */ new Map();
21699
- const fetchOne = async (msgId, key2, kind, nameHint, idx, notes) => {
22072
+ const fetchOne = async (msgId, key4, kind, nameHint, idx, notes) => {
21700
22073
  if (Date.now() - started > HISTORY_DOWNLOAD_BUDGET_MS) {
21701
22074
  notes.push(budgetNote(1));
21702
22075
  return null;
@@ -21704,7 +22077,7 @@ var FeishuAdapter = class _FeishuAdapter {
21704
22077
  try {
21705
22078
  token ??= await this._getTenantToken();
21706
22079
  try {
21707
- 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"), {
21708
22081
  headers: { Authorization: `Bearer ${token}`, Range: "bytes=0-0" },
21709
22082
  signal: AbortSignal.timeout(5e3)
21710
22083
  });
@@ -21718,7 +22091,7 @@ var FeishuAdapter = class _FeishuAdapter {
21718
22091
  } catch {
21719
22092
  }
21720
22093
  const dlInit = { signal: AbortSignal.timeout(HISTORY_ATTACH_TIMEOUT_MS) };
21721
- 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);
21722
22095
  if (buf.length > HISTORY_ATTACH_MAX_BYTES) {
21723
22096
  notes.push(skipNote(nameHint, buf.length));
21724
22097
  return null;
@@ -21768,9 +22141,9 @@ var FeishuAdapter = class _FeishuAdapter {
21768
22141
  if (r?.tag === "text") segs.push(String(r.text ?? ""));
21769
22142
  else if (r?.tag === "img") {
21770
22143
  segs.push("[\u56FE\u7247]");
21771
- const key2 = String(r?.image_key ?? "");
21772
- if (key2) {
21773
- 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);
21774
22147
  if (att) attachments.push(att);
21775
22148
  imgIdx++;
21776
22149
  }
@@ -21779,18 +22152,18 @@ var FeishuAdapter = class _FeishuAdapter {
21779
22152
  content = segs.join("").trim() || "[\u56FE\u6587]";
21780
22153
  } else if (type === "image") {
21781
22154
  content = "[\u56FE\u7247]";
21782
- const key2 = String(body?.image_key ?? "");
21783
- if (key2) {
21784
- 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);
21785
22158
  if (att) attachments.push(att);
21786
22159
  }
21787
22160
  } else if (type === "file" || type === "audio" || type === "media") {
21788
22161
  const name0 = String(body?.file_name ?? body?.file_key ?? "file");
21789
22162
  const label = type === "audio" ? "\u8BED\u97F3" : type === "media" ? "\u89C6\u9891" : "\u6587\u4EF6";
21790
22163
  content = `[${label}] ${name0}`;
21791
- const key2 = String(body?.file_key ?? "");
21792
- if (key2) {
21793
- 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);
21794
22167
  if (att) attachments.push(att);
21795
22168
  }
21796
22169
  } else if (type === "sticker") {
@@ -22254,8 +22627,8 @@ var FeishuAdapter = class _FeishuAdapter {
22254
22627
  const earlyImageKeys = imageKeys.filter(Boolean);
22255
22628
  if (message.message_type === "image" && !earlyImageKeys.length) {
22256
22629
  try {
22257
- const key2 = JSON.parse(message.content || "{}").image_key;
22258
- if (key2) earlyImageKeys.push(key2);
22630
+ const key4 = JSON.parse(message.content || "{}").image_key;
22631
+ if (key4) earlyImageKeys.push(key4);
22259
22632
  } catch {
22260
22633
  }
22261
22634
  }
@@ -22271,12 +22644,12 @@ var FeishuAdapter = class _FeishuAdapter {
22271
22644
  messageId,
22272
22645
  recvAt: Date.now(),
22273
22646
  metadata: { chatId, chatType, ...parentId ? { parentId } : {} },
22274
- attachments: earlyImageKeys.map((key2) => ({
22647
+ attachments: earlyImageKeys.map((key4) => ({
22275
22648
  url: "",
22276
22649
  filename: "image.png",
22277
22650
  contentType: "image/png",
22278
22651
  size: 0,
22279
- loadBytes: (signal) => this._downloadImage(messageId, key2, void 0, { signal })
22652
+ loadBytes: (signal) => this._downloadImage(messageId, key4, void 0, { signal })
22280
22653
  })),
22281
22654
  prepareContext: async (signal) => {
22282
22655
  signal?.throwIfAborted();
@@ -22362,7 +22735,8 @@ var FeishuAdapter = class _FeishuAdapter {
22362
22735
  }
22363
22736
  }
22364
22737
  if (!cleanContent.trim() && !imageAttachments?.length && !fileAttachment && !videoAttachment && !attachNotes.length) return;
22365
- 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);
22366
22740
  const inbound = {
22367
22741
  // 1012 翀哥实测:引用原文和新正文挤一行会混——引用独占一行,正文(含附件留痕)另起一行。
22368
22742
  content: [
@@ -22470,8 +22844,8 @@ var FeishuAdapter = class _FeishuAdapter {
22470
22844
  } else if (block.tag === "at") {
22471
22845
  lines.push(block.user_name ? `@${block.user_name}` : "@user");
22472
22846
  } else if (block.tag === "img") {
22473
- const key2 = block.image_key;
22474
- if (key2) imageKeys.push(key2);
22847
+ const key4 = block.image_key;
22848
+ if (key4) imageKeys.push(key4);
22475
22849
  }
22476
22850
  }
22477
22851
  lines.push("\n");
@@ -22606,6 +22980,11 @@ function hasWechatPriorContact(stateDir, accountId, userId) {
22606
22980
  }
22607
22981
  }
22608
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
+
22609
22988
  // src/config/features.ts
22610
22989
  init_live();
22611
22990
 
@@ -22674,13 +23053,13 @@ function pkcs7Unpad(data) {
22674
23053
  if (pad < 1 || pad > 16 || pad > data.length) return data;
22675
23054
  return data.subarray(0, data.length - pad);
22676
23055
  }
22677
- function aesEncrypt(plaintext, key2) {
22678
- const c = crypto2.createCipheriv("aes-128-ecb", key2, null);
23056
+ function aesEncrypt(plaintext, key4) {
23057
+ const c = crypto2.createCipheriv("aes-128-ecb", key4, null);
22679
23058
  c.setAutoPadding(false);
22680
23059
  return Buffer.concat([c.update(pkcs7Pad(plaintext)), c.final()]);
22681
23060
  }
22682
- function aesDecrypt(ciphertext, key2) {
22683
- const d = crypto2.createDecipheriv("aes-128-ecb", key2, null);
23061
+ function aesDecrypt(ciphertext, key4) {
23062
+ const d = crypto2.createDecipheriv("aes-128-ecb", key4, null);
22684
23063
  d.setAutoPadding(false);
22685
23064
  return pkcs7Unpad(Buffer.concat([d.update(ciphertext), d.final()]));
22686
23065
  }
@@ -22939,8 +23318,8 @@ var ContextTokenStore = class {
22939
23318
  this.save();
22940
23319
  }
22941
23320
  delete(a, p) {
22942
- const key2 = p !== void 0 ? this.k(a, p) : a;
22943
- this.cache.delete(key2);
23321
+ const key4 = p !== void 0 ? this.k(a, p) : a;
23322
+ this.cache.delete(key4);
22944
23323
  this.save();
22945
23324
  }
22946
23325
  };
@@ -23501,12 +23880,12 @@ import { WebSocketServer, WebSocket } from "ws";
23501
23880
  init_live();
23502
23881
  init_well_formed();
23503
23882
  import { execFile } from "node:child_process";
23504
- import { promisify as promisify2 } from "node:util";
23883
+ import { promisify as promisify3 } from "node:util";
23505
23884
  init_voice_chat_tts_daemon();
23506
23885
  import * as path14 from "node:path";
23507
23886
  import * as os6 from "node:os";
23508
23887
  import net2 from "net";
23509
- var execFileAsync = promisify2(execFile);
23888
+ var execFileAsync = promisify3(execFile);
23510
23889
  var VOICE_DIR = path14.join(os6.tmpdir(), "engine-voice");
23511
23890
  async function ttsCosyvoiceWorker(text2, cfg, onChunk) {
23512
23891
  if (!isDaemonReady()) {
@@ -24472,10 +24851,10 @@ var PreviewEditThrottle = class {
24472
24851
  }
24473
24852
  st = /* @__PURE__ */ new Map();
24474
24853
  /** 提交一次编辑;返回的 promise 在"该内容(或其后覆盖它的更新内容)真实落盘"后 settle,失败 reject */
24475
- submit(key2, req, run) {
24476
- 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: [] };
24477
24856
  const guardedRun = AsyncLocalStorage6.bind(run);
24478
- this.st.set(key2, s);
24857
+ this.st.set(key4, s);
24479
24858
  return new Promise((resolve13, reject) => {
24480
24859
  const waiter = { resolve: resolve13, reject };
24481
24860
  if (s.timer) {
@@ -24485,7 +24864,7 @@ var PreviewEditThrottle = class {
24485
24864
  return;
24486
24865
  }
24487
24866
  if (this.now() - s.lastEditAt >= this.minIntervalMs) {
24488
- this.fire(key2, req, [waiter], guardedRun);
24867
+ this.fire(key4, req, [waiter], guardedRun);
24489
24868
  return;
24490
24869
  }
24491
24870
  s.pending = req;
@@ -24499,12 +24878,12 @@ var PreviewEditThrottle = class {
24499
24878
  s.pending = null;
24500
24879
  s.pendingRun = null;
24501
24880
  s.waiters = [];
24502
- if (p && latestRun) this.fire(key2, p, w, latestRun);
24881
+ if (p && latestRun) this.fire(key4, p, w, latestRun);
24503
24882
  }, this.minIntervalMs - (this.now() - s.lastEditAt));
24504
24883
  });
24505
24884
  }
24506
- fire(key2, req, waiters, run) {
24507
- const s = this.st.get(key2);
24885
+ fire(key4, req, waiters, run) {
24886
+ const s = this.st.get(key4);
24508
24887
  if (s) s.lastEditAt = this.now();
24509
24888
  Promise.resolve().then(() => run(req)).then(
24510
24889
  () => {
@@ -24739,16 +25118,16 @@ var AlbumBuffer = class {
24739
25118
  }
24740
25119
  groups = /* @__PURE__ */ new Map();
24741
25120
  add(item) {
24742
- const key2 = item.mediaGroupId;
24743
- const g = this.groups.get(key2) ?? { items: [], lastAt: 0 };
25121
+ const key4 = item.mediaGroupId;
25122
+ const g = this.groups.get(key4) ?? { items: [], lastAt: 0 };
24744
25123
  g.items.push(item);
24745
25124
  g.lastAt = this.now();
24746
- this.groups.set(key2, g);
25125
+ this.groups.set(key4, g);
24747
25126
  }
24748
25127
  tick() {
24749
- for (const [key2, g] of this.groups) {
25128
+ for (const [key4, g] of this.groups) {
24750
25129
  if (this.now() - g.lastAt < this.timeoutMs) continue;
24751
- this.groups.delete(key2);
25130
+ this.groups.delete(key4);
24752
25131
  g.items.sort((a, b) => Number(a.inbound.messageId) - Number(b.inbound.messageId));
24753
25132
  this.flush(g.items);
24754
25133
  }
@@ -25188,9 +25567,9 @@ var TelegramAdapter = class {
25188
25567
  */
25189
25568
  async editPreview(handle, content, agentName, isFinal) {
25190
25569
  const chatId = Number(handle.channelId);
25191
- const key2 = `${handle.channelId}:${handle.messageId}`;
25570
+ const key4 = `${handle.channelId}:${handle.messageId}`;
25192
25571
  try {
25193
- await this.editThrottle.submit(key2, { content, agentName, isFinal: !!isFinal }, async (r) => {
25572
+ await this.editThrottle.submit(key4, { content, agentName, isFinal: !!isFinal }, async (r) => {
25194
25573
  await this.enqueueSend(chatId, async () => {
25195
25574
  if (r.isFinal) {
25196
25575
  const chunks = splitTextChunks(r.content, 4e3);
@@ -25308,11 +25687,11 @@ function inboundGate(inp) {
25308
25687
  if (!inp.hasUserContent) {
25309
25688
  return { pass: false, gate: 4, reason: "\u65E0 user \u53EF\u89C1\u5185\u5BB9\uFF08receipt/protocol \u7A7A\u6D88\u606F\uFF09" };
25310
25689
  }
25311
- const key2 = `${inp.jid}:${inp.messageId}`;
25312
- if (inp.seenKeys.has(key2)) {
25313
- 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}` };
25314
25693
  }
25315
- inp.seenKeys.add(key2);
25694
+ inp.seenKeys.add(key4);
25316
25695
  return { pass: true };
25317
25696
  }
25318
25697
  var WRAPPERS = [
@@ -25665,14 +26044,14 @@ import { HttpsProxyAgent as HttpsProxyAgent2 } from "https-proxy-agent";
25665
26044
 
25666
26045
  // src/version.ts
25667
26046
  import { readFileSync as readFileSync12 } from "node:fs";
25668
- import { dirname as dirname10, join as join21 } from "node:path";
26047
+ import { dirname as dirname10, join as join22 } from "node:path";
25669
26048
  import { fileURLToPath as fileURLToPath2 } from "node:url";
25670
26049
  var _loaded = null;
25671
26050
  var _pkgDirOverride = null;
25672
26051
  function candidates() {
25673
- if (_pkgDirOverride !== null) return [join21(_pkgDirOverride, "package.json")];
26052
+ if (_pkgDirOverride !== null) return [join22(_pkgDirOverride, "package.json")];
25674
26053
  const here = dirname10(fileURLToPath2(import.meta.url));
25675
- return [join21(here, "..", "package.json"), join21(here, "..", "..", "package.json")];
26054
+ return [join22(here, "..", "package.json"), join22(here, "..", "..", "package.json")];
25676
26055
  }
25677
26056
  function readFromDisk() {
25678
26057
  for (const p of candidates()) {
@@ -26321,8 +26700,11 @@ function fitProtectedTail(suffix, budget) {
26321
26700
  function hasImage(m) {
26322
26701
  return "role" in m && Array.isArray(m.content) && m.content.some((b) => b.type === "image_ref" || b.type === "image");
26323
26702
  }
26703
+ function hasMedia(m) {
26704
+ return hasImage(m) || "role" in m && Array.isArray(m.content) && m.content.some((b) => b.type === "video");
26705
+ }
26324
26706
  function unobservedImageIndex(messages) {
26325
- return messages.findIndex((m) => hasImage(m) && !("role" in m && m.imageInput?.observed === true));
26707
+ return messages.findIndex((m) => hasMedia(m) && !("role" in m && m.imageInput?.observed === true));
26326
26708
  }
26327
26709
  function splitProtectedImages(messages, budget) {
26328
26710
  const index = unobservedImageIndex(messages);
@@ -26502,7 +26884,7 @@ ${archiveNotice(resultArchive)}`, resultArchive };
26502
26884
 
26503
26885
  // src/models/provider-errors.ts
26504
26886
  function isQuotaExhaustedError(message) {
26505
- 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);
26506
26888
  }
26507
26889
 
26508
26890
  // src/core/query.ts
@@ -26644,8 +27026,8 @@ function withTravelEventContext(context, run) {
26644
27026
  }
26645
27027
  function travelEventPermit(context) {
26646
27028
  const permit = context.permit(), original = context.originalPermit;
26647
- for (const key2 of ["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"]) {
26648
- 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");
26649
27031
  }
26650
27032
  if (context.complete) throw new Error("TRAVEL_GATEWAY_EVENT_COMPLETED");
26651
27033
  return permit;
@@ -26790,7 +27172,10 @@ function isCpuModeHook(command) {
26790
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);
26791
27173
  }
26792
27174
  function cpuModeHookOutput(command, input, workspace) {
26793
- 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;
26794
27179
  const text2 = typeof input.prompt === "string" ? input.prompt : "";
26795
27180
  const internal = ["heartbeat", "cron", "system", "inner-voice", "mem7"];
26796
27181
  const marks = ["\u3010", "[\u5B9A\u65F6", "\u5F53\u524D\u65F6\u95F4\uFF1A", "[inner-voice]", "<calendar-notification>", "<nudge-notification>", "<task-notification>", "<system-reminder>"];
@@ -27041,10 +27426,10 @@ async function executeOneHook(hook, hookEvent, hookName, hookInput, toolUseID, s
27041
27426
  hook
27042
27427
  };
27043
27428
  }
27044
- const cpuModeOutput = hookEvent === "UserPromptSubmit" ? cpuModeHookOutput(hook.command, hookInput, ctx.workspace) : null;
27045
- if (cpuModeOutput) {
27046
- const processed = processHookJSONOutput({ json: cpuModeOutput, command: hook.command, hookEvent, durationMs: Date.now() - startMs });
27047
- 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"}`);
27048
27433
  return { ...processed, outcome: "success", hook };
27049
27434
  }
27050
27435
  const jsonInput = JSON.stringify(hookInput);
@@ -27173,10 +27558,10 @@ function matchesPromptHookCondition(hook, input) {
27173
27558
  if (hook.when === void 0) return true;
27174
27559
  const when = hook.when;
27175
27560
  if (!when || typeof when !== "object" || Array.isArray(when) || input.hook_event_name !== "UserPromptSubmit") return false;
27176
- 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;
27177
27562
  if (!input.prompt.trim()) return false;
27178
- for (const [key2, actual] of [["channel", input.channel], ["channelType", input.channel_type], ["source", input.source]]) {
27179
- 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;
27180
27565
  }
27181
27566
  if (when.excludeSenderIds !== void 0) {
27182
27567
  if (!Array.isArray(when.excludeSenderIds) || when.excludeSenderIds.some((id3) => typeof id3 !== "string")) return false;
@@ -27314,6 +27699,7 @@ async function executeStopHooks(ctx, signal, lastAssistantMessage) {
27314
27699
  cwd: ctx.cwd,
27315
27700
  stop_hook_active: false,
27316
27701
  last_assistant_message: lastAssistantMessage,
27702
+ turn_evidence: ctx.stopTurnEvidence,
27317
27703
  channel: ctx.channel,
27318
27704
  // 让 callback hook 能判断来源
27319
27705
  channelTarget: ctx.channelTarget,
@@ -27556,13 +27942,17 @@ init_read_guard();
27556
27942
  var OnDemandRecall = class {
27557
27943
  used = /* @__PURE__ */ new Set();
27558
27944
  cache = /* @__PURE__ */ new Map();
27945
+ /** Actual tool mutations invalidate this turn's snapshot without polling SQLite. */
27946
+ invalidate() {
27947
+ this.cache.clear();
27948
+ }
27559
27949
  // 1024 翀哥裁决:6 秒墙全撤。它界的是返回大小不是时延来源(检索耗时在 embedding/bm25/rerank),
27560
27950
  // 底层各有各的界(SQL overlay 死线 12s、embedding HTTP 30s、rerank 1500ms 竞速),1+1 配额防循环。
27561
27951
  // 这层墙当天制造了两次 timeout 假阴性 + 额度连坐,没拦住任何真问题。
27562
27952
  constructor(keywordAlreadySearched = false) {
27563
27953
  if (keywordAlreadySearched) this.used.add("keyword");
27564
27954
  }
27565
- async search(binding, args, captureGuard, run, signal) {
27955
+ async search(binding, args, run, signal) {
27566
27956
  const status = (value, reason) => JSON.stringify({ historySearch: { status: value, reason } });
27567
27957
  if (signal?.aborted) return status("aborted", "\u672C\u8F6E\u5DF2\u53D6\u6D88\u3002");
27568
27958
  if (args.mode === "agentic") return status("unavailable", "\u60C5\u611F\u8F6E\u8BF7\u7528 keyword \u6216 hybrid \u6709\u754C\u8865\u67E5\u3002");
@@ -27574,17 +27964,12 @@ var OnDemandRecall = class {
27574
27964
  };
27575
27965
  for (const passthrough of ["known_at", "known_at_revision", "valid_at", "entity_ref", "after_receipt", "session_id"])
27576
27966
  if (args[passthrough] !== void 0) bounded[passthrough] = args[passthrough];
27577
- const key2 = JSON.stringify([binding, Object.entries(bounded).sort(([a], [b]) => a.localeCompare(b))]);
27578
- 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);
27579
27969
  if (cached2) {
27580
- const result2 = await cached2.result;
27970
+ const result2 = await cached2;
27581
27971
  if (signal?.aborted) return status("aborted", "\u672C\u8F6E\u5DF2\u53D6\u6D88\u3002");
27582
- try {
27583
- cached2.assertCurrent();
27584
- return result2;
27585
- } catch {
27586
- 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");
27587
- }
27972
+ return result2;
27588
27973
  }
27589
27974
  const kind = bounded.view === "current" || bounded.mode === "keyword" ? "keyword" : "semantic";
27590
27975
  if (kind === "keyword" && this.used.has("keyword") && !this.used.has("semantic")) {
@@ -27593,7 +27978,6 @@ var OnDemandRecall = class {
27593
27978
  if (this.used.has(kind)) {
27594
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");
27595
27980
  }
27596
- const assertCurrent = captureGuard();
27597
27981
  this.used.add(kind);
27598
27982
  if (kind === "semantic") this.used.add("keyword");
27599
27983
  const controller = new AbortController();
@@ -27623,7 +28007,7 @@ ${error.stack.split("\n").slice(0, 6).join("\n")}` : ""
27623
28007
  controller.abort();
27624
28008
  }
27625
28009
  })();
27626
- this.cache.set(key2, { result, assertCurrent });
28010
+ this.cache.set(key4, result);
27627
28011
  return result;
27628
28012
  }
27629
28013
  };
@@ -27684,13 +28068,13 @@ async function materializeImageMessages(messages, store, signal, maxBase64Bytes
27684
28068
  continue;
27685
28069
  }
27686
28070
  if (!store) throw new Error("Image asset store is required to materialize image refs");
27687
- const key2 = JSON.stringify([block.image.sha256, block.image.bytes, block.image.mediaType]);
27688
- 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) => {
27689
28073
  if (strict) throw error;
27690
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)}`);
27691
28075
  return null;
27692
28076
  }));
27693
- 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]" });
27694
28078
  signal?.throwIfAborted();
27695
28079
  }
27696
28080
  output.push({ ...message, content });
@@ -27750,8 +28134,8 @@ var MAX_PENDING_BYTES = 512 * 1024;
27750
28134
  var SteerMailbox = class {
27751
28135
  constructor(stateDir, sessionId) {
27752
28136
  this.sessionId = sessionId;
27753
- const key2 = createHash31("sha256").update(sessionId).digest("hex");
27754
- 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`);
27755
28139
  }
27756
28140
  path;
27757
28141
  list() {
@@ -28092,9 +28476,9 @@ function smartCompressToolResult(content, essentialFields, sizeLimit) {
28092
28476
  if (typeof item === "object" && item !== null && !Array.isArray(item)) {
28093
28477
  const extracted = {};
28094
28478
  if (fieldSet) {
28095
- for (const key2 of essentialFields) {
28096
- if (key2 in item) {
28097
- extracted[key2] = item[key2];
28479
+ for (const key4 of essentialFields) {
28480
+ if (key4 in item) {
28481
+ extracted[key4] = item[key4];
28098
28482
  }
28099
28483
  }
28100
28484
  } else {
@@ -29466,7 +29850,7 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
29466
29850
  outputHandle.close().catch(() => {
29467
29851
  });
29468
29852
  let aborted = false;
29469
- let settled = false;
29853
+ let settled2 = false;
29470
29854
  const cleanup = () => {
29471
29855
  clearTimeout(timer);
29472
29856
  signal?.removeEventListener("abort", onAbort);
@@ -29475,8 +29859,8 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
29475
29859
  child.removeListener("error", onError);
29476
29860
  };
29477
29861
  const done = async (code, error) => {
29478
- if (settled) return;
29479
- settled = true;
29862
+ if (settled2) return;
29863
+ settled2 = true;
29480
29864
  cleanup();
29481
29865
  let output = "";
29482
29866
  let truncated = false;
@@ -29510,12 +29894,12 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
29510
29894
  void done(1, error.message);
29511
29895
  };
29512
29896
  const onAbort = () => {
29513
- if (settled || signal?.reason === "interrupt") return;
29897
+ if (settled2 || signal?.reason === "interrupt") return;
29514
29898
  aborted = true;
29515
29899
  killChild(child);
29516
29900
  };
29517
29901
  const onYield = () => {
29518
- if (settled) return;
29902
+ if (settled2) return;
29519
29903
  if (child.exitCode !== null || child.signalCode !== null) {
29520
29904
  void done(child.exitCode);
29521
29905
  return;
@@ -29532,12 +29916,12 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
29532
29916
  channelTarget: ctx.channelTarget ?? "",
29533
29917
  queryAbortSignal: ctx.queryAbortSignal ?? signal
29534
29918
  });
29535
- settled = true;
29919
+ settled2 = true;
29536
29920
  cleanup();
29537
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.` });
29538
29922
  };
29539
29923
  const timer = setTimeout(() => {
29540
- if (!settled) {
29924
+ if (!settled2) {
29541
29925
  aborted = true;
29542
29926
  killChild(child);
29543
29927
  }
@@ -29567,7 +29951,7 @@ init_dependencies();
29567
29951
  init_basis_check();
29568
29952
  init_relationship_notice_check();
29569
29953
  init_scope();
29570
- import { join as join25, resolve as resolve8 } from "node:path";
29954
+ import { join as join26, resolve as resolve8 } from "node:path";
29571
29955
  var contextIdentity = (context) => canonicalJson({
29572
29956
  scopeId: context.scopeId,
29573
29957
  basisRefs: context.basisRefs,
@@ -29580,17 +29964,17 @@ function createNotificationStateReader() {
29580
29964
  const databases = /* @__PURE__ */ new Map();
29581
29965
  const checkers = /* @__PURE__ */ new Map();
29582
29966
  const open3 = (path35) => {
29583
- const key2 = resolve8(path35);
29584
- let db2 = databases.get(key2);
29967
+ const key4 = resolve8(path35);
29968
+ let db2 = databases.get(key4);
29585
29969
  if (!db2) {
29586
- db2 = new DatabaseSync11(key2, { readOnly: true });
29970
+ db2 = new DatabaseSync11(key4, { readOnly: true });
29587
29971
  try {
29588
29972
  db2.exec("BEGIN");
29589
29973
  } catch (error) {
29590
29974
  db2.close();
29591
29975
  throw error;
29592
29976
  }
29593
- databases.set(key2, db2);
29977
+ databases.set(key4, db2);
29594
29978
  }
29595
29979
  return db2;
29596
29980
  };
@@ -29622,7 +30006,7 @@ function readNotificationState(route, queueStateDir, open3, relationshipChecker)
29622
30006
  let proactive;
29623
30007
  let calendar;
29624
30008
  try {
29625
- memory = open3(join25(runtime.stateDir, "mem7", "index", "mem7.db"));
30009
+ memory = open3(join26(runtime.stateDir, "mem7", "index", "mem7.db"));
29626
30010
  const scope = memory.prepare("SELECT * FROM memory_scopes WHERE scope_id=?").get(context.scopeId);
29627
30011
  if (!scope) {
29628
30012
  return { state: "blocked", reason: "MEMORY_NOTIFICATION_SCOPE_MISSING", redact: true };
@@ -29649,7 +30033,7 @@ function readNotificationState(route, queueStateDir, open3, relationshipChecker)
29649
30033
  }
29650
30034
  if (context.actionVersions && Object.keys(context.actionVersions).length) {
29651
30035
  const ledgerDependencies = new MemoryDependencies(memory, (operation) => operation());
29652
- proactive = open3(join25(runtime.workspace, ".proactive", "proactive.db"));
30036
+ proactive = open3(join26(runtime.workspace, ".proactive", "proactive.db"));
29653
30037
  for (const id3 of Object.keys(context.actionVersions)) {
29654
30038
  const action = proactive.prepare("SELECT scope_id,intent_id FROM actions WHERE id=?").get(id3);
29655
30039
  if (!action || action.scope_id !== context.scopeId) return { state: "blocked", reason: "MEMORY_NOTIFICATION_ACTION_MISMATCH", redact: true };
@@ -29703,7 +30087,7 @@ function readNotificationState(route, queueStateDir, open3, relationshipChecker)
29703
30087
  }
29704
30088
  if (route.hostDelivery) {
29705
30089
  if (!proactive) {
29706
- proactive = open3(join25(runtime.workspace, ".proactive", "proactive.db"));
30090
+ proactive = open3(join26(runtime.workspace, ".proactive", "proactive.db"));
29707
30091
  }
29708
30092
  const receipt = proactive.prepare("SELECT * FROM proactive_host_deliveries WHERE delivery_key=?").get(route.hostDelivery.key);
29709
30093
  if (!receipt || contextIdentity(JSON.parse(receipt.context_json)) !== contextIdentity(context)) {
@@ -29714,7 +30098,7 @@ function readNotificationState(route, queueStateDir, open3, relationshipChecker)
29714
30098
  if (["blocked", "delivery_unknown"].includes(receipt.state)) return { state: receipt.state, reason: receipt.reason ?? receipt.state };
29715
30099
  }
29716
30100
  if (context.calendarBinding) {
29717
- calendar = open3(join25(runtime.workspace, ".calendar", "calendar.db"));
30101
+ calendar = open3(join26(runtime.workspace, ".calendar", "calendar.db"));
29718
30102
  const binding = context.calendarBinding;
29719
30103
  const rows = calendar.prepare("SELECT state,closure FROM calendar_dispatches WHERE scope_id=? AND event_id=? AND occurrence_id=?").all(context.scopeId, binding.eventId, binding.occurrenceId);
29720
30104
  if (rows.some((row) => ["started", "delivery_unknown"].includes(row.state) && !row.closure)) {
@@ -30451,6 +30835,7 @@ var QueryEngine = class _QueryEngine {
30451
30835
  const mailbox = this.steerMailbox;
30452
30836
  this.attachmentScopeId = perTurnOptions?.attachmentScopeId;
30453
30837
  const queryId = this.steerQueryId;
30838
+ const hasPendingUserInput = () => this.pendingSteers.some((input) => !input.attachment);
30454
30839
  this.steerHistoryIds = new Set(messages.flatMap((m) => "steerInput" in m && m.steerInput ? [m.steerInput.id] : "attachment" in m ? [m.uuid] : []));
30455
30840
  try {
30456
30841
  for (const input of mailbox?.pending(this.steerRoute ?? void 0) ?? []) {
@@ -30482,8 +30867,15 @@ var QueryEngine = class _QueryEngine {
30482
30867
  this.compactConfig.systemOverheadTokens = overhead ?? this.compactConfig.systemOverheadTokens;
30483
30868
  }
30484
30869
  const activeSystemStable = perTurnSystemStable || this.resolveOpt(this.options.systemStable) || this.resolveOpt(this.options.systemPrompt);
30485
- for (const m of messages) if ("role" in m && hasImage(m) && !m.imageInput) m.imageInput = { id: randomUUID17(), observed: true };
30870
+ for (const m of messages) if ("role" in m && hasMedia(m) && !m.imageInput) m.imageInput = { id: randomUUID17(), observed: hasImage(m) };
30486
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
+ }
30487
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\.$/;
30488
30880
  const historicalGateTools = new Set(currentMessages.flatMap((m) => {
30489
30881
  if (!("role" in m) || m.role !== "tool" || typeof m.content !== "string") return [];
@@ -30562,6 +30954,7 @@ var QueryEngine = class _QueryEngine {
30562
30954
  };
30563
30955
  let turnCount = 0;
30564
30956
  let recallContinuation = false;
30957
+ const stopReplies = [];
30565
30958
  let toolCalls = [];
30566
30959
  let streamRetries = 0;
30567
30960
  let maxTokensOverride = null;
@@ -30618,6 +31011,7 @@ var QueryEngine = class _QueryEngine {
30618
31011
  }
30619
31012
  const steerMsg = buildSteerMessage(input);
30620
31013
  currentMessages.push(steerMsg);
31014
+ if (collectStopEvidence) stopUserMessages.push(input.originalText ?? input.text);
30621
31015
  this.steerHistoryIds.add(input.id);
30622
31016
  steerConsumedThisTurn = true;
30623
31017
  yield {
@@ -30873,9 +31267,13 @@ var QueryEngine = class _QueryEngine {
30873
31267
  try {
30874
31268
  wholeQueryAbort.signal.throwIfAborted();
30875
31269
  const view = normalizeMessagesForAPI(currentMessages).map((m) => {
30876
- if (!Array.isArray(m.content) || !m.imageInput?.observed || queryInputs?.includes("image") || !queryModelRef) return m;
30877
- const blocks = m.content.filter((b) => b.type !== "image" && b.type !== "image_ref");
30878
- return { ...m, content: blocks.length ? blocks : "[previous image omitted]" };
31270
+ if (!Array.isArray(m.content) || !m.imageInput?.observed || !queryModelRef) return m;
31271
+ const blocks = m.content.filter((b) => {
31272
+ if (b.type === "image" || b.type === "image_ref") return !!queryInputs?.includes("image");
31273
+ if (b.type === "video") return !!queryInputs?.includes("video");
31274
+ return true;
31275
+ });
31276
+ return { ...m, content: blocks.length ? blocks : "[previous media omitted]" };
30879
31277
  });
30880
31278
  const apiMessages = await materializeImageMessages(view, this.options.imageAssets, wholeQueryAbort.signal);
30881
31279
  wholeQueryAbort.signal.throwIfAborted();
@@ -30903,7 +31301,7 @@ ${hint}` : [...current2.content, { type: "text", text: hint }] };
30903
31301
  const fullSystemDynamic = deferredHint && perTurnSystemDynamic ? `${deferredHint}
30904
31302
 
30905
31303
  ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
30906
- if (!this.options.agentLabel || this.options.agentLabel === "main") {
31304
+ if (process.env.ENGINE_DUMP_REQUEST === "1" && (!this.options.agentLabel || this.options.agentLabel === "main")) {
30907
31305
  try {
30908
31306
  const ws = process.env.ENGINE7_WORKSPACE;
30909
31307
  if (ws) {
@@ -31036,7 +31434,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31036
31434
  }
31037
31435
  });
31038
31436
  if (!requestComplete || (toolCalls.length ? !validToolCalls : !textContent.trim()) || ["length", "max_tokens", "MAX_TOKENS", "incomplete", "content_filter"].includes(responseStopReason ?? "")) return;
31039
- const inputs = currentMessages.filter((m) => "role" in m && hasImage(m) && !m.imageInput?.observed);
31437
+ const inputs = currentMessages.filter((m) => "role" in m && hasMedia(m) && !m.imageInput?.observed);
31040
31438
  if (!inputs.length) return;
31041
31439
  return {
31042
31440
  type: "image_observed",
@@ -31125,20 +31523,22 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31125
31523
  if (toolCalls.length === 0) {
31126
31524
  const carryReply = () => {
31127
31525
  if (!this.pendingSteers.some((input) => input.attachment)) return null;
31526
+ const replyId = randomUUID17();
31128
31527
  const reply = msg.assistant(textContent);
31129
31528
  if (turnThinking) reply.reasoning_content = turnThinking;
31130
31529
  if (turnThinkingSig) reply.thinking_signature = turnThinkingSig;
31131
31530
  if (turnResponsesReasoning) reply.responses_reasoning = turnResponsesReasoning;
31132
31531
  currentMessages.push(reply);
31133
- finalText = textContent;
31532
+ finalText = "";
31533
+ if (collectStopEvidence) stopReplies.push(textContent);
31134
31534
  recallContinuation = true;
31135
31535
  turnThinking = turnThinkingSig = turnResponsesReasoning = "";
31136
- return { type: "history", messages: [reply] };
31536
+ return [{ type: "history", messages: [reply], replyId }, { type: "reply", content: textContent, replyId }];
31137
31537
  };
31138
31538
  if (responseStopReason === "max_tokens" || responseStopReason === "length") {
31139
31539
  if (this.pendingSteers.length > 0) {
31140
31540
  const carried = carryReply();
31141
- if (carried) yield carried;
31541
+ if (carried) yield* carried;
31142
31542
  continue;
31143
31543
  }
31144
31544
  finalText = textContent;
@@ -31148,7 +31548,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31148
31548
  if (this.options.skipStopHook || perTurnEmotion) {
31149
31549
  if (this.pendingSteers.length > 0) {
31150
31550
  const carried = carryReply();
31151
- if (carried) yield carried;
31551
+ if (carried) yield* carried;
31152
31552
  continue;
31153
31553
  }
31154
31554
  finalText = textContent;
@@ -31165,9 +31565,14 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31165
31565
  // 'group' | 'dm',Stop hook 用来判断是否跳过 group
31166
31566
  cwd: context?.workspace || "",
31167
31567
  source: typeof context?.source === "string" ? context.source : "",
31168
- executionContext: context?.executionContext
31568
+ executionContext: context?.executionContext,
31569
+ stopTurnEvidence: { userMessages: stopUserMessages, toolResults: stopToolResults }
31169
31570
  };
31170
- 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
+ );
31171
31576
  if (stopResult.preventContinuation) {
31172
31577
  console.log(`[hook] Stop blocked: ${stopResult.stopReason || "no reason"}`);
31173
31578
  if (stopResult.additionalContexts?.length) {
@@ -31182,7 +31587,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31182
31587
  }
31183
31588
  if (this.pendingSteers.length > 0) {
31184
31589
  const carried = carryReply();
31185
- if (carried) yield carried;
31590
+ if (carried) yield* carried;
31186
31591
  continue;
31187
31592
  }
31188
31593
  finalText = textContent;
@@ -31262,6 +31667,12 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31262
31667
  turnResponsesReasoning = "";
31263
31668
  currentMessages.push(gateAssistant);
31264
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
+ });
31265
31676
  for (const g of gatedCalls) {
31266
31677
  yield { type: "tool_result", tool: g.call.function?.name, tool_call_id: g.call.id, summary: g.text.slice(0, 200), isError: true };
31267
31678
  }
@@ -31282,7 +31693,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31282
31693
  try {
31283
31694
  this.phase = "tools";
31284
31695
  this.toolYield = new AbortController();
31285
- if (this.pendingSteers.length) this.toolYield.abort("steer");
31696
+ if (hasPendingUserInput()) this.toolYield.abort("steer");
31286
31697
  toolCtx.yieldSignal = this.toolYield.signal;
31287
31698
  toolRes = await executeTools(toolCalls, ac.signal, { ...toolCtx, toolResultHistory: currentMessages });
31288
31699
  } finally {
@@ -31291,6 +31702,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31291
31702
  if (vcDelivery) await vcDelivery;
31292
31703
  }
31293
31704
  const { messages: toolResults, summaries } = toolRes;
31705
+ if (collectStopEvidence) stopToolResults.push(...summaries);
31294
31706
  for (const s of summaries) {
31295
31707
  try {
31296
31708
  const postResult = await executePostToolUseHooks(s.tool, {}, s.summary, hookCtx, ac.signal);
@@ -31392,7 +31804,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31392
31804
  this.toolYield = null;
31393
31805
  this.phase = "idle";
31394
31806
  this.loopAlive = false;
31395
- if (this.pendingSteers.length > 0 && completionReason !== "aborted") {
31807
+ if (hasPendingUserInput() && completionReason !== "aborted") {
31396
31808
  console.warn(`${this.logPrefix} [steer] ${this.pendingSteers.length} pending input(s) retained for same-route recovery (completionReason=${completionReason ?? "completed"})`);
31397
31809
  }
31398
31810
  this.pendingSteers.length = 0;
@@ -31517,7 +31929,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
31517
31929
  }
31518
31930
  }
31519
31931
  this.pendingSteers.push(receipt.input);
31520
- this.toolYield?.abort("steer");
31932
+ if (!receipt.input.attachment) this.toolYield?.abort("steer");
31521
31933
  if (opts.mode === "queue") {
31522
31934
  console.log(`${this.logPrefix} Steer queued (${this.pendingSteers.length} pending \u2014 next turn, no interrupt)`);
31523
31935
  return true;
@@ -31637,8 +32049,8 @@ function defaultWriteMemoryNote(workspace) {
31637
32049
  }
31638
32050
  function makeSubmitToMain(engineDeps) {
31639
32051
  return (text2) => {
31640
- const sessions = engineDeps.deps?.sessions;
31641
- const mainSessionId = sessions?.getSessionId?.("scope:main");
32052
+ const sessions2 = engineDeps.deps?.sessions;
32053
+ const mainSessionId = sessions2?.getSessionId?.("scope:main");
31642
32054
  if (!mainSessionId) {
31643
32055
  console.warn("[whatsapp/patrol] \u65E0\u4E3B session\uFF08scope:main \u672A\u5EFA\u7ACB\uFF09\uFF0C\u26A0\uFE0F \u5347\u7EA7\u6295\u9012\u4E22\u5F03");
31644
32056
  return;
@@ -31671,10 +32083,10 @@ function makeReadOnlyAgentRunner(engineDeps) {
31671
32083
  });
31672
32084
  const sessionId = base.sessions.getOrCreateSessionId(PATROL_SESSION_KEY);
31673
32085
  return new Promise((resolve13, reject) => {
31674
- let settled = false;
32086
+ let settled2 = false;
31675
32087
  const timeout = setTimeout(() => {
31676
- if (settled) return;
31677
- settled = true;
32088
+ if (settled2) return;
32089
+ settled2 = true;
31678
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`));
31679
32091
  }, PATROL_TIMEOUT_MS);
31680
32092
  const ok = engineDeps.dispatcher.submitMessage({
@@ -31688,21 +32100,21 @@ function makeReadOnlyAgentRunner(engineDeps) {
31688
32100
  deps: { ...base, engine: patrolEngine },
31689
32101
  callbacks: {
31690
32102
  onResult: (content) => {
31691
- if (settled) return;
31692
- settled = true;
32103
+ if (settled2) return;
32104
+ settled2 = true;
31693
32105
  clearTimeout(timeout);
31694
32106
  resolve13(content);
31695
32107
  },
31696
32108
  onError: (err) => {
31697
- if (settled) return;
31698
- settled = true;
32109
+ if (settled2) return;
32110
+ settled2 = true;
31699
32111
  clearTimeout(timeout);
31700
32112
  reject(new Error(err));
31701
32113
  }
31702
32114
  }
31703
32115
  });
31704
- if (ok === false && !settled) {
31705
- settled = true;
32116
+ if (ok === false && !settled2) {
32117
+ settled2 = true;
31706
32118
  clearTimeout(timeout);
31707
32119
  reject(new Error("dispatcher \u62D2\u7EDD wa-patrol \u63D0\u4EA4\uFF08guard \u5FD9\uFF09\u2014\u2014\u4E0B\u8F6E\u91CD\u5DE1"));
31708
32120
  }
@@ -32891,10 +33303,10 @@ var DingStreamClient = class extends EventEmitter {
32891
33303
  return;
32892
33304
  }
32893
33305
  this.ws = ws;
32894
- let settled = false;
33306
+ let settled2 = false;
32895
33307
  const settle = (err) => {
32896
- if (settled) return;
32897
- settled = true;
33308
+ if (settled2) return;
33309
+ settled2 = true;
32898
33310
  this.clearHeartbeat();
32899
33311
  if (err) reject(err);
32900
33312
  else resolve13();
@@ -32915,8 +33327,8 @@ var DingStreamClient = class extends EventEmitter {
32915
33327
  });
32916
33328
  ws.on("error", (err) => {
32917
33329
  this.emit("error", err instanceof Error ? err : new Error(String(err)));
32918
- if (!settled) {
32919
- settled = true;
33330
+ if (!settled2) {
33331
+ settled2 = true;
32920
33332
  this.clearHeartbeat();
32921
33333
  reject(err);
32922
33334
  return;
@@ -33591,18 +34003,18 @@ var DingTalkAdapter = class _DingTalkAdapter {
33591
34003
  /** per-card 流式串行链(无间隔闸)——throttle 保证 ≥300ms 节奏,但 HTTP 慢时相邻两次
33592
34004
  * fire 仍可能并发(后发先到→旧内容覆盖新内容);openclaw 的 in-flight 保护同语义 */
33593
34005
  cardStreamQueues = /* @__PURE__ */ new Map();
33594
- streamCardSerial(key2, outTrackId, content, isFinalize) {
33595
- const prev = this.cardStreamQueues.get(key2) ?? Promise.resolve();
34006
+ streamCardSerial(key4, outTrackId, content, isFinalize) {
34007
+ const prev = this.cardStreamQueues.get(key4) ?? Promise.resolve();
33596
34008
  const next = prev.then(
33597
34009
  () => this.streamCard(outTrackId, content, isFinalize),
33598
34010
  () => this.streamCard(outTrackId, content, isFinalize)
33599
34011
  );
33600
- this.cardStreamQueues.set(key2, next.then(() => {
34012
+ this.cardStreamQueues.set(key4, next.then(() => {
33601
34013
  }, () => {
33602
34014
  }));
33603
34015
  if (this.cardStreamQueues.size > 200) {
33604
34016
  const drop = this.cardStreamQueues.keys().next().value;
33605
- if (drop !== void 0 && drop !== key2) this.cardStreamQueues.delete(drop);
34017
+ if (drop !== void 0 && drop !== key4) this.cardStreamQueues.delete(drop);
33606
34018
  }
33607
34019
  return next;
33608
34020
  }
@@ -33611,10 +34023,10 @@ var DingTalkAdapter = class _DingTalkAdapter {
33611
34023
  * API,双重节流会把打字机压成"两秒一跳"(openclaw 实测:300ms 直打才流畅)。保序由
33612
34024
  * throttle(last-write-wins)+ per-card 串行链保证。 */
33613
34025
  async editPreview(handle, content, agentName, isFinal) {
33614
- const key2 = `${handle.channelId}:${handle.messageId}`;
34026
+ const key4 = `${handle.channelId}:${handle.messageId}`;
33615
34027
  try {
33616
- await this.editThrottle.submit(key2, { content, agentName, isFinal: !!isFinal }, async (r) => {
33617
- 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);
33618
34030
  if (r.isFinal) {
33619
34031
  await this.putCardData(handle.messageId, "3");
33620
34032
  await this.notifyGroupFinalized(handle.channelId, handle.messageId).catch(() => {
@@ -33917,10 +34329,10 @@ var WecomStreamClient = class extends EventEmitter2 {
33917
34329
  return;
33918
34330
  }
33919
34331
  this.ws = ws;
33920
- let settled = false;
34332
+ let settled2 = false;
33921
34333
  const settle = (err) => {
33922
- if (settled) return;
33923
- settled = true;
34334
+ if (settled2) return;
34335
+ settled2 = true;
33924
34336
  this.clearHeartbeat();
33925
34337
  const wasSubscribed = this.everSubscribed;
33926
34338
  this.subscribed = false;
@@ -33946,7 +34358,7 @@ var WecomStreamClient = class extends EventEmitter2 {
33946
34358
  ws.on("error", (err) => {
33947
34359
  const e = err instanceof Error ? err : new Error(String(err));
33948
34360
  this.emit("error", e);
33949
- if (!settled) {
34361
+ if (!settled2) {
33950
34362
  settle(e);
33951
34363
  return;
33952
34364
  }
@@ -34237,9 +34649,9 @@ function wecomTextFormat(text2, format2 = "markdown") {
34237
34649
  }
34238
34650
  function decryptWecomMedia(buf, aeskey) {
34239
34651
  const padded = aeskey + "=".repeat((4 - aeskey.length % 4) % 4);
34240
- const key2 = Buffer.from(padded, "base64");
34241
- if (key2.length !== 32) throw new Error(`wecom media aeskey \u89E3\u7801\u540E\u5E94\u4E3A 32 \u5B57\u8282\uFF0C\u5B9E\u5F97 ${key2.length}`);
34242
- 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));
34243
34655
  d.setAutoPadding(false);
34244
34656
  const raw = Buffer.concat([d.update(buf), d.final()]);
34245
34657
  const pad = raw[raw.length - 1];
@@ -34538,22 +34950,22 @@ var WecomAdapter = class {
34538
34950
  this.emitInbound(parsed.inbound);
34539
34951
  return;
34540
34952
  }
34541
- const key2 = `${parsed.chatId}:${parsed.senderId}`;
34542
- const cur = this.pending.get(key2);
34953
+ const key4 = `${parsed.chatId}:${parsed.senderId}`;
34954
+ const cur = this.pending.get(key4);
34543
34955
  if (cur) {
34544
34956
  cur.parsed.inbound.content = `${cur.parsed.inbound.content}
34545
34957
  ${parsed.inbound.content}`;
34546
34958
  cur.version++;
34547
34959
  } else {
34548
- this.pending.set(key2, { parsed, version: 1 });
34960
+ this.pending.set(key4, { parsed, version: 1 });
34549
34961
  }
34550
- const entry = this.pending.get(key2);
34962
+ const entry = this.pending.get(key4);
34551
34963
  const v = entry.version;
34552
34964
  void this.sleepImpl(windowMs).then(() => {
34553
- const live = this.pending.get(key2);
34965
+ const live = this.pending.get(key4);
34554
34966
  if (!live) return;
34555
34967
  if (live.version !== v) return;
34556
- this.pending.delete(key2);
34968
+ this.pending.delete(key4);
34557
34969
  this.emitInbound(live.parsed.inbound);
34558
34970
  });
34559
34971
  }
@@ -34567,10 +34979,10 @@ ${parsed.inbound.content}`;
34567
34979
  }
34568
34980
  /** 立即投递并清空某会话挂起的合并片段(媒体直投前的顺序保护,review) */
34569
34981
  flushPending(chatId, senderId) {
34570
- const key2 = `${chatId}:${senderId}`;
34571
- const live = this.pending.get(key2);
34982
+ const key4 = `${chatId}:${senderId}`;
34983
+ const live = this.pending.get(key4);
34572
34984
  if (!live) return;
34573
- this.pending.delete(key2);
34985
+ this.pending.delete(key4);
34574
34986
  this.emitInbound(live.parsed.inbound);
34575
34987
  }
34576
34988
  // === 出站(spec §五) ===
@@ -34964,8 +35376,8 @@ import { randomUUID as randomUUID21 } from "node:crypto";
34964
35376
 
34965
35377
  // src/continuity/gateway-channel.ts
34966
35378
  init_gateway_media();
34967
- import { mkdtempSync, writeFileSync as writeFileSync13, rmSync as rmSync2, realpathSync as realpathSync5 } from "node:fs";
34968
- import { join as join30 } from "node:path";
35379
+ import { mkdtempSync, writeFileSync as writeFileSync14, rmSync as rmSync2, realpathSync as realpathSync5 } from "node:fs";
35380
+ import { join as join31 } from "node:path";
34969
35381
  import { tmpdir as tmpdir3 } from "node:os";
34970
35382
  function splitChannelGatewayText(text2, channel) {
34971
35383
  if (typeof text2 !== "string" || Buffer.byteLength(text2) > 1024 * 1024) throw new Error("TRAVEL_GATEWAY_REPLY_LIMIT");
@@ -35020,9 +35432,9 @@ async function deliverChannelGatewayEffect(adapter, effect, body, assertCurrent)
35020
35432
  if (!media) await adapter.send(packet.target, packet.text, { replyTo: packet.replyTo });
35021
35433
  else {
35022
35434
  if (!adapter.sendFile) throw new Error("TRAVEL_GATEWAY_MEDIA_UNAVAILABLE");
35023
- const directory2 = realpathSync5(mkdtempSync(join30(tmpdir3(), "e7-gateway-media-"))), file2 = join30(directory2, packet.filename);
35435
+ const directory2 = realpathSync5(mkdtempSync(join31(tmpdir3(), "e7-gateway-media-"))), file2 = join31(directory2, packet.filename);
35024
35436
  try {
35025
- writeFileSync13(file2, media.bytes, { mode: 384 });
35437
+ writeFileSync14(file2, media.bytes, { mode: 384 });
35026
35438
  await adapter.sendFile(packet.target, packet.text, { path: file2, filename: packet.filename, mimeType: packet.mimeType, voiceDurationSec: packet.voiceDurationSec });
35027
35439
  } finally {
35028
35440
  rmSync2(directory2, { recursive: true, force: true });
@@ -35079,8 +35491,8 @@ function createFeishuGatewayDispatcher(options) {
35079
35491
  const timestamp = Number(message.create_time);
35080
35492
  if (!Number.isSafeInteger(timestamp) || timestamp < 0) throw new Error("TRAVEL_FEISHU_INVALID_EVENT");
35081
35493
  const content = JSON.parse(String(message.content)), descriptors = [];
35082
- const add = (key2, type, filename, contentType) => {
35083
- 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 });
35084
35496
  };
35085
35497
  if (message.message_type === "image") add(content.image_key, "image", "image.jpg", "image/jpeg");
35086
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");
@@ -35218,9 +35630,9 @@ function createFeishuGatewayPlatform(options) {
35218
35630
  return { messageId: result.data.message_id };
35219
35631
  });
35220
35632
  },
35221
- downloadResource: async (messageId, key2, type) => {
35633
+ downloadResource: async (messageId, key4, type) => {
35222
35634
  if (closed) throw new Error("TRAVEL_FEISHU_CLOSED");
35223
- 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 } });
35224
35636
  const stream = response.getReadableStream(), chunks = [];
35225
35637
  let bytes2 = 0;
35226
35638
  try {
@@ -35255,7 +35667,7 @@ function createRemoteTravelChannel(block, stateDir, channel = "feishu") {
35255
35667
  if (!stateDir || !runtimeAuthorityFor(stateDir)) throw new Error("TRAVEL_GATEWAY_RUNTIME_REQUIRED");
35256
35668
  validateTravelChannels(stateDir, { [channel]: block });
35257
35669
  const tls2 = block.gatewayTls;
35258
- 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");
35259
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) });
35260
35672
  return new RemoteTravelChannel({ client, channel, permit: () => runtimeAuthorityFor(stateDir).assert("INPUT"), pollIntervalMs: block.gatewayPollIntervalMs });
35261
35673
  }
@@ -35461,9 +35873,9 @@ function archive(manager, name, mime, bytes2, role, caption, identity) {
35461
35873
  const adapter = manager.getAdapter("chan7");
35462
35874
  if (!adapter?.files || bytes2.length > 16 * 1024 * 1024) return;
35463
35875
  const safeName = path33.basename(name).replace(/[<>:"/\\|?*\x00-\x1f]/g, "_").slice(0, 255) || "attachment";
35464
- 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");
35465
35877
  try {
35466
- 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);
35467
35879
  } catch (e) {
35468
35880
  console.warn("[library] delivered copy not archived: " + e.message);
35469
35881
  }
@@ -35697,7 +36109,7 @@ var ChannelManager = class {
35697
36109
  const changes = [];
35698
36110
  for (const name of MANAGED_CHANNEL_NAMES) {
35699
36111
  const block = config[name];
35700
- const key2 = JSON.stringify(block ?? null);
36112
+ const key4 = JSON.stringify(block ?? null);
35701
36113
  const cur = this.managed.get(name);
35702
36114
  const enabled = block?.enabled === true;
35703
36115
  if (!enabled && !cur) continue;
@@ -35706,7 +36118,7 @@ var ChannelManager = class {
35706
36118
  changes.push(`${name}: removed`);
35707
36119
  continue;
35708
36120
  }
35709
- if (cur && cur.key === key2) continue;
36121
+ if (cur && cur.key === key4) continue;
35710
36122
  if (cur) {
35711
36123
  if (runningQueries.includes(name)) {
35712
36124
  console.log(`[channels] ${name} rebuild deferred (query in flight)`);
@@ -35718,7 +36130,7 @@ var ChannelManager = class {
35718
36130
  const adapter = this.buildManagedAdapter(name, block);
35719
36131
  if (!adapter) continue;
35720
36132
  this.adapters.push(adapter);
35721
- this.managed.set(name, { adapter, key: key2 });
36133
+ this.managed.set(name, { adapter, key: key4 });
35722
36134
  this.wireAdapter(adapter);
35723
36135
  if (adapter.registerCommands && this.registeredCommands.size > 0) {
35724
36136
  void adapter.registerCommands([...this.registeredCommands.values()]).catch((e) => console.error(`[channels] ${name} registerCommands failed: ${e.message}`));
@@ -35961,7 +36373,7 @@ function tls(config) {
35961
36373
  return { ca: readPrivateFile(path34(config?.caFile), 1024 * 1024), cert: readPrivateFile(path34(config?.certFile), 1024 * 1024), key: readPrivateFile(path34(config?.keyFile), 16384) };
35962
36374
  }
35963
36375
  async function startTravelGateway(config) {
35964
- 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");
35965
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");
35966
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");
35967
36379
  const feishuIngress = config.ingressEnabled !== false && config.feishu?.ingressEnabled !== false && config.channels?.feishu?.enabled !== false;
@@ -36014,7 +36426,7 @@ async function startTravelGateway(config) {
36014
36426
  if (!config.allowedPeers || !Object.keys(config.allowedPeers).length) throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
36015
36427
  for (const credential of Object.values(config.allowedPeers)) {
36016
36428
  const principal = authority.authenticate(String(credential));
36017
- 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");
36018
36430
  }
36019
36431
  store = new TravelGatewayStore({ directory: path34(config.gatewayDir), identity: config.identity, objects, authority });
36020
36432
  await store.migrateStoredInputs();
@@ -36064,9 +36476,9 @@ async function startTravelGateway(config) {
36064
36476
  assertIngress: assertKey,
36065
36477
  authorizeStop: (sender) => Array.isArray(config.feishu.stopAllowedUserIds) && config.feishu.stopAllowedUserIds.includes(sender.sender_id?.open_id),
36066
36478
  onReceivedTyping: (chatId, openId, messageId) => platform.startChatTyping(chatId, openId, messageId),
36067
- downloadResource: async (messageId, key2, type) => {
36479
+ downloadResource: async (messageId, key4, type) => {
36068
36480
  assertKey();
36069
- return platform.downloadResource(messageId, key2, type);
36481
+ return platform.downloadResource(messageId, key4, type);
36070
36482
  }
36071
36483
  });
36072
36484
  if (config.channels && config.ingressEnabled !== false) {
@@ -36177,9 +36589,9 @@ if (process.argv[1] && /[\\/](gateway-main\.ts|travel-gateway\.mjs)$/.test(proce
36177
36589
 
36178
36590
  // src/continuity/pairing-control.ts
36179
36591
  async function startPairingControl(config) {
36180
- const directory2 = resolve12(config.directory), file2 = join31(directory2, "pairing.json"), read2 = (name) => readPrivateFile(join31(directory2, name), 65536);
36592
+ const directory2 = resolve12(config.directory), file2 = join32(directory2, "pairing.json"), read2 = (name) => readPrivateFile(join32(directory2, name), 65536);
36181
36593
  const tls2 = { ca: read2("ca.pem"), cert: read2("server.pem"), key: read2("server.key") };
36182
- const authority = new TravelAuthority({ directory: join31(directory2, "authority") });
36594
+ const authority = new TravelAuthority({ directory: join32(directory2, "authority") });
36183
36595
  let binding;
36184
36596
  try {
36185
36597
  if (existsSync15(file2)) {
@@ -36189,26 +36601,26 @@ async function startPairingControl(config) {
36189
36601
  } else {
36190
36602
  const tokens = authority.provisionSeat(config.identity, { local: "LOCAL", cloud: "CLOUD" }, { checkpointDigest: "0".repeat(64), buildManifestId: config.buildManifestId });
36191
36603
  binding = { identity: config.identity, buildManifestId: config.buildManifestId, keySha256: config.keySha256, tokens, local: authority.authenticate(tokens.local), cloud: authority.authenticate(tokens.cloud), publicKey: authority.publicKey, keyIdentity: { ...config.identity, keyId: "pair-" + config.identity.seatId, generation: 1 } };
36192
- writeFileSync14(file2, JSON.stringify(binding), { flag: "wx", mode: 384, flush: true });
36604
+ writeFileSync15(file2, JSON.stringify(binding), { flag: "wx", mode: 384, flush: true });
36193
36605
  }
36194
36606
  } finally {
36195
36607
  authority.close();
36196
36608
  }
36197
- const keys = new KeyServiceStore(join31(directory2, "keys"));
36198
- const key2 = read2("data.key");
36609
+ const keys = new KeyServiceStore(join32(directory2, "keys"));
36610
+ const key4 = read2("data.key");
36199
36611
  try {
36200
- 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");
36201
36613
  try {
36202
36614
  keys.assertIdentity(binding.keyIdentity);
36203
36615
  } catch {
36204
- keys.provision(binding.keyIdentity, key2);
36616
+ keys.provision(binding.keyIdentity, key4);
36205
36617
  }
36206
36618
  for (const name of ["local", "cloud", "manager"]) {
36207
36619
  const certificate = new X509Certificate(read2(name + ".pem"));
36208
36620
  keys.authorizeCertificate(certificate.fingerprint256.replaceAll(":", ""), binding.keyIdentity, Date.parse(certificate.validTo));
36209
36621
  }
36210
36622
  } finally {
36211
- key2.fill(0);
36623
+ key4.fill(0);
36212
36624
  }
36213
36625
  const keyServer = createKeyServiceServer({ ...tls2, store: keys });
36214
36626
  await new Promise((done, reject) => {
@@ -36218,13 +36630,13 @@ async function startPairingControl(config) {
36218
36630
  const fp = (name) => new X509Certificate(read2(name + ".pem")).fingerprint256.replaceAll(":", "").toLowerCase();
36219
36631
  const peers = { [fp("local")]: binding.tokens.local, [fp("cloud")]: binding.tokens.cloud };
36220
36632
  const managers = { [fp("manager")]: [binding.tokens.local, binding.tokens.cloud], [fp("local")]: [binding.tokens.local, binding.tokens.cloud], [fp("cloud")]: [binding.tokens.cloud, binding.tokens.local] };
36221
- const tlsFiles = { caFile: join31(directory2, "ca.pem"), certFile: join31(directory2, "server.pem"), keyFile: join31(directory2, "server.key") };
36222
- const managerTls = { ...tlsFiles, certFile: join31(directory2, "manager.pem"), keyFile: join31(directory2, "manager.key") };
36633
+ const tlsFiles = { caFile: join32(directory2, "ca.pem"), certFile: join32(directory2, "server.pem"), keyFile: join32(directory2, "server.key") };
36634
+ const managerTls = { ...tlsFiles, certFile: join32(directory2, "manager.pem"), keyFile: join32(directory2, "manager.key") };
36223
36635
  const gatewayConfig = {
36224
36636
  identity: config.identity,
36225
- authorityDir: join31(directory2, "authority"),
36226
- gatewayDir: join31(directory2, "gateway"),
36227
- objectsDir: join31(directory2, "objects"),
36637
+ authorityDir: join32(directory2, "authority"),
36638
+ gatewayDir: join32(directory2, "gateway"),
36639
+ objectsDir: join32(directory2, "objects"),
36228
36640
  tls: tlsFiles,
36229
36641
  host: "127.0.0.1",
36230
36642
  port: config.ports.gateway,
@@ -36232,12 +36644,12 @@ async function startPairingControl(config) {
36232
36644
  control: { host: "127.0.0.1", port: config.ports.authority, tls: tlsFiles, allowedPeers: peers, managementPeers: managers, recoveryPeers: managers, retirementPeers: { [fp("manager")]: [binding.tokens.local] } },
36233
36645
  allowedPeers: peers,
36234
36646
  recoveryPeers: { [fp("manager")]: binding.tokens.local },
36235
- platformStateDir: join31(directory2, "platform"),
36647
+ platformStateDir: join32(directory2, "platform"),
36236
36648
  channels: config.channels,
36237
36649
  feishu: { ...config.feishu, ingressEnabled: false },
36238
36650
  ingressEnabled: false
36239
36651
  };
36240
- let ingress = existsSync15(join31(directory2, "ingress-enabled.json"));
36652
+ let ingress = existsSync15(join32(directory2, "ingress-enabled.json"));
36241
36653
  let gateway = await startTravelGateway({ ...gatewayConfig, ingressEnabled: ingress, feishu: { ...gatewayConfig.feishu, ingressEnabled: ingress && config.channels?.feishu?.enabled === true } });
36242
36654
  let changing = false, closed = false;
36243
36655
  const pairServer = createServer4({ ...tls2, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
@@ -36266,12 +36678,12 @@ async function startPairingControl(config) {
36266
36678
  if (input.action === "enable_ingress" && !ingress) {
36267
36679
  await gateway.close();
36268
36680
  gateway = await startTravelGateway({ ...gatewayConfig, ingressEnabled: true, feishu: { ...gatewayConfig.feishu, ingressEnabled: config.channels?.feishu?.enabled === true } });
36269
- writeFileSync14(join31(directory2, "ingress-enabled.json"), JSON.stringify({ identity: config.identity }), { mode: 384, flush: true });
36681
+ writeFileSync15(join32(directory2, "ingress-enabled.json"), JSON.stringify({ identity: config.identity }), { mode: 384, flush: true });
36270
36682
  ingress = true;
36271
36683
  }
36272
36684
  if (input.action === "disable_ingress" && ingress) {
36273
36685
  if (gateway.authority.status(binding.local).activeNodeId !== null) throw new Error("TRAVEL_INITIAL_SOURCE_RUNNING");
36274
- rmSync3(join31(directory2, "ingress-enabled.json"), { force: true });
36686
+ rmSync3(join32(directory2, "ingress-enabled.json"), { force: true });
36275
36687
  await gateway.close();
36276
36688
  gateway = await startTravelGateway(gatewayConfig);
36277
36689
  ingress = false;