engine7 7.1.144 → 7.1.146

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -621,9 +621,9 @@ var init_key_service_store = __esm({
621
621
  throw error;
622
622
  }
623
623
  }
624
- provision(identity3, key2) {
624
+ provision(identity3, key3) {
625
625
  const text2 = identityText(identity3);
626
- if (!(key2 instanceof Uint8Array) || key2.byteLength !== 32) throw new Error("KEY_SERVICE_INVALID_KEY");
626
+ if (!(key3 instanceof Uint8Array) || key3.byteLength !== 32) throw new Error("KEY_SERVICE_INVALID_KEY");
627
627
  this.transaction(() => {
628
628
  if (this.db.prepare("SELECT key_id FROM seat_keys WHERE key_id=?").get(identity3.keyId))
629
629
  throw new Error("KEY_SERVICE_KEY_EXISTS");
@@ -632,7 +632,7 @@ var init_key_service_store = __esm({
632
632
  const fd = openSync2(path37, constants2.O_WRONLY | constants2.O_CREAT | constants2.O_EXCL, 384);
633
633
  try {
634
634
  let written = 0;
635
- while (written < key2.byteLength) written += writeSync(fd, key2, written, key2.byteLength - written);
635
+ while (written < key3.byteLength) written += writeSync(fd, key3, written, key3.byteLength - written);
636
636
  fsyncSync2(fd);
637
637
  } catch (error) {
638
638
  closeSync2(fd);
@@ -684,12 +684,12 @@ var init_key_service_store = __esm({
684
684
  if (typeof seat.secret_file !== "string" || !/^[a-f0-9-]{36}\.key$/.test(seat.secret_file))
685
685
  throw new Error("KEY_SERVICE_INVALID_KEY_FILE");
686
686
  assertPrivateStat(lstatSync2(this.secrets), true);
687
- const key2 = readPrivateFile(join2(this.secrets, seat.secret_file), 32);
688
- if (key2.length !== 32) {
689
- key2.fill(0);
687
+ const key3 = readPrivateFile(join2(this.secrets, seat.secret_file), 32);
688
+ if (key3.length !== 32) {
689
+ key3.fill(0);
690
690
  throw new Error("KEY_SERVICE_INVALID_KEY_FILE");
691
691
  }
692
- return { key: key2, deletionWatermark: current2 };
692
+ return { key: key3, deletionWatermark: current2 };
693
693
  });
694
694
  }
695
695
  advanceWatermark(keyId, value2) {
@@ -809,9 +809,9 @@ function readSecretsEntries(stateDir, configName) {
809
809
  function loadSecretsEnv(stateDir, configName, options = {}) {
810
810
  const selected = readSecretsEntries(stateDir, configName);
811
811
  if (!selected) return null;
812
- for (const [key2, value2] of selected.entries) {
813
- const current2 = process.env[key2];
814
- if (options.overwrite || current2 === void 0 || current2 === "") process.env[key2] = value2;
812
+ for (const [key3, value2] of selected.entries) {
813
+ const current2 = process.env[key3];
814
+ if (options.overwrite || current2 === void 0 || current2 === "") process.env[key3] = value2;
815
815
  }
816
816
  return selected.path;
817
817
  }
@@ -866,20 +866,24 @@ var init_capabilities = __esm({
866
866
  });
867
867
 
868
868
  // src/auth/client.ts
869
- var DEFAULT_AUTH_BROKER;
869
+ var DEFAULT_AUTH_BROKER, LEGACY_AUTH_BROKERS, OFFICIAL_AUTH_BROKERS;
870
870
  var init_client = __esm({
871
871
  "src/auth/client.ts"() {
872
872
  "use strict";
873
873
  init_capabilities();
874
874
  init_protocol();
875
- DEFAULT_AUTH_BROKER = "https://www.twinsun.top/auth/";
875
+ DEFAULT_AUTH_BROKER = "https://auth.engine7.ai/auth/";
876
+ LEGACY_AUTH_BROKERS = ["https://www.twinsun.top/auth/"];
877
+ OFFICIAL_AUTH_BROKERS = /* @__PURE__ */ new Set([DEFAULT_AUTH_BROKER, ...LEGACY_AUTH_BROKERS]);
876
878
  }
877
879
  });
878
880
 
879
881
  // src/auth/config.ts
880
882
  function authConfig(raw) {
881
883
  const value2 = raw;
882
- return { brokerUrl: brokerBase(value2?.brokerUrl === void 0 ? DEFAULT_AUTH_BROKER : String(value2.brokerUrl)).toString() };
884
+ const brokerUrl = brokerBase(value2?.brokerUrl === void 0 ? DEFAULT_AUTH_BROKER : String(value2.brokerUrl)).toString();
885
+ const rawProxy = typeof value2?.gmailProxy === "string" ? value2.gmailProxy.trim() : "";
886
+ return rawProxy ? { brokerUrl, gmailProxy: rawProxy } : { brokerUrl };
883
887
  }
884
888
  var init_config = __esm({
885
889
  "src/auth/config.ts"() {
@@ -935,7 +939,7 @@ var init_display = __esm({
935
939
  toolUse: { enabled: true, emoji: "\u{1F527}", displayMode: "summary", bashDisplayMode: "description", displayLimits: { write: 200 } },
936
940
  toolResult: { enabled: true, emoji: "\u{1F4E4}" },
937
941
  reactions: { enabled: true, start: "\u{1F440}", done: "\u2705", error: "\u274C" },
938
- preview: { enabled: true, agentName: "Agent" },
942
+ preview: { agentName: "Agent" },
939
943
  bubbleSplit: { emotion: true, work: false },
940
944
  typing: { enabled: true }
941
945
  };
@@ -1116,10 +1120,10 @@ var init_live = __esm({
1116
1120
  /** 安全取子段('services.voice-chat.start' → current.services.voice-chat.start) */
1117
1121
  get(dotPath) {
1118
1122
  if (!this.current) return void 0;
1119
- return dotPath.split(".").reduce((acc, key2) => {
1123
+ return dotPath.split(".").reduce((acc, key3) => {
1120
1124
  if (acc == null) return void 0;
1121
- if (key2 === "__proto__" || key2 === "constructor" || key2 === "prototype") return void 0;
1122
- return acc[key2];
1125
+ if (key3 === "__proto__" || key3 === "constructor" || key3 === "prototype") return void 0;
1126
+ return acc[key3];
1123
1127
  }, this.current);
1124
1128
  }
1125
1129
  /** reload 时原地更新(Object.assign 保持引用不变)
@@ -1203,9 +1207,9 @@ var init_live = __esm({
1203
1207
  });
1204
1208
 
1205
1209
  // src/config/features.ts
1206
- function getFeature(key2) {
1207
- const v = liveConfig.get(`agents.defaults.features.${key2}`);
1208
- return v === void 0 ? FEATURE_DEFAULTS[key2] : v;
1210
+ function getFeature(key3) {
1211
+ const v = liveConfig.get(`agents.defaults.features.${key3}`);
1212
+ return v === void 0 ? FEATURE_DEFAULTS[key3] : v;
1209
1213
  }
1210
1214
  var FEATURE_DEFAULTS;
1211
1215
  var init_features = __esm({
@@ -1331,9 +1335,9 @@ function toWall(i = /* @__PURE__ */ new Date()) {
1331
1335
  return `${p.y}-${p2(p.mo)}-${p2(p.d)} ${p2(p.hh)}:${p2(p.mm)}:${p2(p.ss)}`;
1332
1336
  }
1333
1337
  function warnOnce(callSite, shape, sample) {
1334
- const key2 = `${callSite}:${shape}`;
1335
- if (warned.has(key2)) return;
1336
- warned.add(key2);
1338
+ const key3 = `${callSite}:${shape}`;
1339
+ if (warned.has(key3)) return;
1340
+ warned.add(key3);
1337
1341
  console.warn(`[clock] ${callSite} \u5951\u7EA6\u8FDD\u89C4(${shape})\uFF0C\u6837\u672C: ${String(sample).slice(0, 80)}`);
1338
1342
  }
1339
1343
  function zoneOffsetMs(d) {
@@ -1699,7 +1703,7 @@ function validateTravelChannelConfiguration(channels) {
1699
1703
  if (name === "emotion" || value2?.enabled !== true) continue;
1700
1704
  if (!["feishu", "discord", "wechat"].includes(name)) throw new Error("TRAVEL_CHANNEL_NOT_CONTROLLED");
1701
1705
  if (value2.mode !== "remote-only") throw new Error("TRAVEL_REMOTE_ONLY_REQUIRED");
1702
- 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));
1706
+ const hasPlatformSecret = (block) => block && typeof block === "object" && Object.entries(block).some(([key3, v]) => ["appSecret", "token", "accessToken", "tenantAccessToken", "app_secret", "botToken", "bot_token"].includes(key3) && typeof v === "string" && !!v.trim() || v && typeof v === "object" && hasPlatformSecret(v));
1703
1707
  if (hasPlatformSecret(value2)) throw new Error("TRAVEL_PLATFORM_SECRET_PRESENT");
1704
1708
  let url;
1705
1709
  try {
@@ -2560,15 +2564,15 @@ var init_sqlite_replication = __esm({
2560
2564
  requireForeignKeys(this.db);
2561
2565
  if (captureGuardHash(this.db) !== this.guardHash) throw new Error("REPLICATION_GUARD_MISMATCH");
2562
2566
  if (sqliteReplicationSchemaHash(this.db) !== this.schemaHash) throw new Error("REPLICATION_SCHEMA_MISMATCH");
2563
- const before = sequences(this.db, this.excludedTables), sessions = [];
2567
+ const before = sequences(this.db, this.excludedTables), sessions2 = [];
2564
2568
  try {
2565
- if (this.sessionTables) for (const table of this.sessionTables) sessions.push(this.db.createSession({ table }));
2566
- else sessions.push(this.db.createSession());
2569
+ if (this.sessionTables) for (const table of this.sessionTables) sessions2.push(this.db.createSession({ table }));
2570
+ else sessions2.push(this.db.createSession());
2567
2571
  } catch (error) {
2568
- for (const session of sessions) session.close();
2572
+ for (const session of sessions2) session.close();
2569
2573
  throw error;
2570
2574
  }
2571
- this.active = { sessions, sequences: before, closed: false };
2575
+ this.active = { sessions: sessions2, sequences: before, closed: false };
2572
2576
  return this.active;
2573
2577
  }
2574
2578
  appendCapture(capture2) {
@@ -2894,31 +2898,31 @@ var init_mem7_replication = __esm({
2894
2898
  // src/continuity/runtime-replication.ts
2895
2899
  import { constants as constants8, lstatSync as lstatSync7, realpathSync as realpathSync4, mkdirSync as mkdirSync7, openSync as openSync8, closeSync as closeSync7, fstatSync as fstatSync4, readFileSync as readFileSync6, writeFileSync as writeFileSync6, fsyncSync as fsyncSync6 } from "node:fs";
2896
2900
  import { basename as basename3, dirname as dirname6, join as join13, resolve as resolve9 } from "node:path";
2897
- function checkKey(component, key2) {
2898
- if (component === "topics-vectors" && typeof key2 === "string" && /^[a-f0-9]{64}$/.test(key2)) return;
2899
- 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;
2900
- if (["calendar", "proactive", "session-events"].includes(component) && key2 === void 0) return;
2901
+ function checkKey(component, key3) {
2902
+ if (component === "topics-vectors" && typeof key3 === "string" && /^[a-f0-9]{64}$/.test(key3)) return;
2903
+ if (component === "legacy-memory" && typeof key3 === "string" && /^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(key3) && !/[. ]$/.test(key3) && !/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(key3)) return;
2904
+ if (["calendar", "proactive", "session-events"].includes(component) && key3 === void 0) return;
2901
2905
  throw new Error("REPLICATION_REGISTRATION_INVALID");
2902
2906
  }
2903
- function location2(stateDir, component, key2) {
2904
- checkKey(component, key2);
2905
- return join13(stateDir, ".continuity", component + (key2 === void 0 ? "" : "-" + key2) + "-replication.json");
2907
+ function location2(stateDir, component, key3) {
2908
+ checkKey(component, key3);
2909
+ return join13(stateDir, ".continuity", component + (key3 === void 0 ? "" : "-" + key3) + "-replication.json");
2906
2910
  }
2907
- function runtimeReplicationFile(stateDir, component, key2) {
2908
- checkKey(component, key2);
2909
- if (component === "legacy-memory") return join13(stateDir, "agents", key2, "memory", "memory.db");
2910
- if (component === "topics-vectors") return join13(stateDir, "topics-history", key2, "vectors.db");
2911
+ function runtimeReplicationFile(stateDir, component, key3) {
2912
+ checkKey(component, key3);
2913
+ if (component === "legacy-memory") return join13(stateDir, "agents", key3, "memory", "memory.db");
2914
+ if (component === "topics-vectors") return join13(stateDir, "topics-history", key3, "vectors.db");
2911
2915
  if (component === "session-events") return join13(stateDir, ".continuity", "session-events.db");
2912
2916
  return join13(stateDir, "." + component, component + ".db");
2913
2917
  }
2914
2918
  function runtimeReplicationLocation(stateDir, component, file2) {
2915
- const key2 = component === "legacy-memory" ? basename3(dirname6(dirname6(file2))) : component === "topics-vectors" ? basename3(dirname6(file2)) : void 0;
2919
+ const key3 = component === "legacy-memory" ? basename3(dirname6(dirname6(file2))) : component === "topics-vectors" ? basename3(dirname6(file2)) : void 0;
2916
2920
  try {
2917
- if (resolve9(file2) !== resolve9(runtimeReplicationFile(stateDir, component, key2))) throw new Error();
2921
+ if (resolve9(file2) !== resolve9(runtimeReplicationFile(stateDir, component, key3))) throw new Error();
2918
2922
  } catch (error) {
2919
2923
  throw new Error("REPLICATION_RUNTIME_PATH_UNSUPPORTED", { cause: error });
2920
2924
  }
2921
- return { component, ...key2 === void 0 ? {} : { key: key2 } };
2925
+ return { component, ...key3 === void 0 ? {} : { key: key3 } };
2922
2926
  }
2923
2927
  function normalize4(input) {
2924
2928
  if (!input || !/^[a-f0-9]{64}$/.test(input.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
@@ -2929,8 +2933,8 @@ function directory(path37) {
2929
2933
  if (!info.isDirectory() || info.isSymbolicLink() || realpathSync4(path37) !== resolve9(path37) || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid()))
2930
2934
  throw new Error("REPLICATION_REGISTRATION_INVALID");
2931
2935
  }
2932
- function readRuntimeReplicationRegistration(stateDir, component, key2) {
2933
- const file2 = location2(stateDir, component, key2);
2936
+ function readRuntimeReplicationRegistration(stateDir, component, key3) {
2937
+ const file2 = location2(stateDir, component, key3);
2934
2938
  try {
2935
2939
  lstatSync7(dirname6(file2));
2936
2940
  } catch (error) {
@@ -2993,8 +2997,8 @@ function checkRuntimeReplicationDatabase(db2, registration, component, version,
2993
2997
  }
2994
2998
  return requested ?? registration?.binding;
2995
2999
  }
2996
- function enrollRuntimeReplication(db2, stateDir, component, binding, key2) {
2997
- const file2 = location2(stateDir, component, key2), old = readRuntimeReplicationRegistration(stateDir, component, key2);
3000
+ function enrollRuntimeReplication(db2, stateDir, component, binding, key3) {
3001
+ const file2 = location2(stateDir, component, key3), old = readRuntimeReplicationRegistration(stateDir, component, key3);
2998
3002
  const version = readSchemaVersion(db2);
2999
3003
  if (version?.component !== component) throw new Error("REPLICATION_SCHEMA_MISMATCH");
3000
3004
  checkRuntimeReplicationDatabase(db2, old, component, version.version, binding);
@@ -3007,7 +3011,7 @@ function enrollRuntimeReplication(db2, stateDir, component, binding, key2) {
3007
3011
  writeFileSync6(file2, JSON.stringify(input), { mode: 384, flag: "wx", flush: true });
3008
3012
  } catch (error) {
3009
3013
  if (error.code !== "EEXIST") throw error;
3010
- if (JSON.stringify(readRuntimeReplicationRegistration(stateDir, component, key2)) !== JSON.stringify(input)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
3014
+ if (JSON.stringify(readRuntimeReplicationRegistration(stateDir, component, key3)) !== JSON.stringify(input)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
3011
3015
  }
3012
3016
  if (process.platform !== "win32") {
3013
3017
  const fd = openSync8(dirname6(file2), "r");
@@ -3088,11 +3092,11 @@ var init_prompt_render = __esm({
3088
3092
  import { createHash as createHash7 } from "node:crypto";
3089
3093
  function scopeId(scope) {
3090
3094
  if ([scope.ownerId, scope.appId, scope.projectId].some((value2) => typeof value2 !== "string" || !value2.trim())) throw new Error("Invalid memory scope");
3091
- const key2 = JSON.stringify([scope.ownerId, scope.appId, scope.projectId]);
3092
- const cached = scopeIdMemo.get(key2);
3095
+ const key3 = JSON.stringify([scope.ownerId, scope.appId, scope.projectId]);
3096
+ const cached = scopeIdMemo.get(key3);
3093
3097
  if (cached) return cached;
3094
3098
  const id2 = "scope_" + createHash7("sha256").update(JSON.stringify([scope.ownerId, scope.appId, scope.projectId])).digest("hex");
3095
- scopeIdMemo.set(key2, id2);
3099
+ scopeIdMemo.set(key3, id2);
3096
3100
  return id2;
3097
3101
  }
3098
3102
  var scopeIdMemo;
@@ -3105,10 +3109,14 @@ var init_scope = __esm({
3105
3109
 
3106
3110
  // src/mem7/core/state/temporal.ts
3107
3111
  function instant(value2) {
3108
- if (!/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/.test(value2)) throw new Error("TIME_REQUIRED: explicit UTC offset required");
3109
- if (!isCalendarDate(value2.substring(0, 10))) throw new Error("INVALID_TIME");
3110
- const time = Date.parse(value2);
3111
- if (!Number.isFinite(time)) throw new Error("INVALID_TIME");
3112
+ let text2 = value2;
3113
+ if (typeof text2 !== "string" || !INSTANT.test(text2)) {
3114
+ text2 = typeof value2 === "string" ? value2.trim().replace(/^(\d{4}-\d{2}-\d{2}) /, "$1T").replace(/([+-]\d{2})(\d{2})$/, "$1:$2") : value2;
3115
+ if (typeof text2 !== "string" || !INSTANT.test(text2)) throw new Error(`TIME_REQUIRED: explicit UTC offset required \u2014 \u6536\u5230 ${received(value2)}\uFF1B${INSTANT_FORMAT}`);
3116
+ }
3117
+ if (!isCalendarDate(text2.substring(0, 10))) throw new Error(`INVALID_TIME: \u4E0D\u662F\u6709\u6548\u7684\u65E5\u5386\u65E5\u671F \u2014 \u6536\u5230 ${received(value2)}`);
3118
+ const time = Date.parse(text2);
3119
+ if (!Number.isFinite(time)) throw new Error(`INVALID_TIME \u2014 \u6536\u5230 ${received(value2)}\uFF1B${INSTANT_FORMAT}`);
3112
3120
  return new Date(time).toISOString();
3113
3121
  }
3114
3122
  function isCalendarDate(value2) {
@@ -3121,7 +3129,7 @@ function validateTimezone(timezone) {
3121
3129
  try {
3122
3130
  new Intl.DateTimeFormat("en", { timeZone: timezone });
3123
3131
  } catch {
3124
- throw new Error("INVALID_TIMEZONE");
3132
+ throw new Error(`INVALID_TIMEZONE: timezone \u7528 IANA \u65F6\u533A\u540D\uFF0C\u5982 Asia/Shanghai\uFF08\u6536\u5230 ${String(timezone).slice(0, 60)}\uFF09`);
3125
3133
  }
3126
3134
  }
3127
3135
  function localInstant(date, time, timezone) {
@@ -3153,10 +3161,13 @@ function localInstant(date, time, timezone) {
3153
3161
  return new Date([...matches][0]).toISOString();
3154
3162
  }
3155
3163
  function normalizeValidity(value2) {
3164
+ for (const field of ["validFrom", "validTo"]) {
3165
+ if (value2[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}`);
3166
+ }
3156
3167
  const validFrom = value2.validFrom === null ? null : instant(value2.validFrom);
3157
3168
  const validTo = value2.validTo === null ? null : instant(value2.validTo);
3158
- if (validFrom !== null && validTo !== null && validFrom >= validTo) throw new Error("INVALID_INTERVAL: expected [from,to)");
3159
- if (!["exact", "observed", "unknown"].includes(value2.precision)) throw new Error("INVALID_PRECISION");
3169
+ 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");
3170
+ if (!["exact", "observed", "unknown"].includes(value2.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");
3160
3171
  if (value2.timezone) validateTimezone(value2.timezone);
3161
3172
  return { ...value2, validFrom, validTo };
3162
3173
  }
@@ -3166,16 +3177,20 @@ function overlaps(a, b) {
3166
3177
  function canonicalJson(value2) {
3167
3178
  const normalize7 = (input) => {
3168
3179
  if (Array.isArray(input)) return input.map(normalize7);
3169
- 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, normalize7(entry)]));
3180
+ if (input && typeof input === "object") return Object.fromEntries(Object.entries(input).filter(([, entry]) => entry !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([key3, entry]) => [key3, normalize7(entry)]));
3170
3181
  return input;
3171
3182
  };
3172
3183
  const json = JSON.stringify(normalize7(value2));
3173
3184
  if (json === void 0) throw new Error("INVALID_JSON_VALUE");
3174
3185
  return json;
3175
3186
  }
3187
+ var INSTANT, INSTANT_FORMAT, received;
3176
3188
  var init_temporal = __esm({
3177
3189
  "src/mem7/core/state/temporal.ts"() {
3178
3190
  "use strict";
3191
+ INSTANT = /^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/;
3192
+ 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';
3193
+ received = (value2) => (JSON.stringify(value2) ?? String(value2)).slice(0, 80);
3179
3194
  }
3180
3195
  });
3181
3196
 
@@ -3200,8 +3215,8 @@ function contextTimeKey(db2, scopeId2, validAt) {
3200
3215
  }
3201
3216
  return `valid-window:${from}:${to}`;
3202
3217
  }
3203
- function assertContextTime(key2, now2 = Date.now()) {
3204
- const match = key2.match(/^valid-window:(-?\d+):(-?\d+)$/);
3218
+ function assertContextTime(key3, now2 = Date.now()) {
3219
+ const match = key3.match(/^valid-window:(-?\d+):(-?\d+)$/);
3205
3220
  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");
3206
3221
  if (now2 < Number(match[1]) || now2 >= Number(match[2])) throw new Error("CONTEXT_TIME_EXPIRED");
3207
3222
  }
@@ -3306,9 +3321,9 @@ function append(db2, scope, kind, id2, payload) {
3306
3321
  return Number(result.lastInsertRowid);
3307
3322
  }
3308
3323
  function recordArtifactBasis(db2, scope, kind, id2, version, dependencies2) {
3309
- const key2 = basisKey(kind, id2, version);
3310
- if (!db2.prepare("SELECT 1 FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=?").get(scopeId(scope), key2)) {
3311
- append(db2, scope, "artifact.basis", key2, { dependencies: dependencies2 });
3324
+ const key3 = basisKey(kind, id2, version);
3325
+ if (!db2.prepare("SELECT 1 FROM memory_knowledge_history WHERE scope_id=? AND target_kind='artifact.basis' AND target_id=?").get(scopeId(scope), key3)) {
3326
+ append(db2, scope, "artifact.basis", key3, { dependencies: dependencies2 });
3312
3327
  }
3313
3328
  }
3314
3329
  var ARTIFACT_HISTORY_SCHEMA, hash2, basisKey, stateKey2, generationKinds, normalizedRefs, ArtifactHistory;
@@ -3458,8 +3473,8 @@ END;
3458
3473
  if (cutoff) return historicalRow(this.db, scope, "artifact.basis", basisKey(kind, id2, version), cutoff)?.dependencies ?? null;
3459
3474
  return this.dependencies.version(scope, kind, id2) === version ? this.dependencies.refs(scope, kind, id2) : null;
3460
3475
  }
3461
- scopeContextRetained(scope, key2) {
3462
- 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);
3476
+ scopeContextRetained(scope, key3) {
3477
+ 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), key3);
3463
3478
  if (!basis) return false;
3464
3479
  const atGeneration = historicalRow(this.db, scope, "scope", "state", { historyId: basis.history_id, time: null, complete: true });
3465
3480
  if (!atGeneration) return false;
@@ -3477,15 +3492,15 @@ END;
3477
3492
  WHERE scope_id=? AND source_id=? AND interpretation_status<>'deleted'`).get(scopeKey, sourceId));
3478
3493
  const walk = (kind2, id3, version2) => {
3479
3494
  checkMemoryReadBudget(visited.size);
3480
- const key2 = basisKey(kind2, id3, version2);
3481
- if (memo.has(key2)) return memo.get(key2);
3482
- if (visited.has(key2)) return false;
3483
- visited.add(key2);
3495
+ const key3 = basisKey(kind2, id3, version2);
3496
+ if (memo.has(key3)) return memo.get(key3);
3497
+ if (visited.has(key3)) return false;
3498
+ visited.add(key3);
3484
3499
  try {
3485
- 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);
3500
+ 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, key3);
3486
3501
  const refs2 = basis && JSON.parse(basis.payload_json).dependencies;
3487
3502
  if (!refs2 || this.db.prepare("SELECT 1 FROM memory_tombstones WHERE scope_id=? AND target_kind=? AND target_id=?").get(scopeKey, kind2, id3)) return false;
3488
- if (refs2.some((ref) => ref.parentKind === "scope" && !ref.parentId.startsWith("valid-window:")) && !this.scopeContextRetained(scope, key2)) return false;
3503
+ if (refs2.some((ref) => ref.parentKind === "scope" && !ref.parentId.startsWith("valid-window:")) && !this.scopeContextRetained(scope, key3)) return false;
3489
3504
  const retained = refs2.every((ref) => {
3490
3505
  checkMemoryReadBudget(visited.size);
3491
3506
  if (ref.parentKind === "source") return sourceRetained(ref.parentId);
@@ -3505,10 +3520,10 @@ END;
3505
3520
  }
3506
3521
  return true;
3507
3522
  });
3508
- memo.set(key2, retained);
3523
+ memo.set(key3, retained);
3509
3524
  return retained;
3510
3525
  } finally {
3511
- visited.delete(key2);
3526
+ visited.delete(key3);
3512
3527
  }
3513
3528
  };
3514
3529
  return walk(kind, id2, version);
@@ -3534,8 +3549,8 @@ END;
3534
3549
  };
3535
3550
  const walk = (parentKind, parentId, parentVersion, ancestors) => {
3536
3551
  checkMemoryReadBudget(ancestors.size);
3537
- const key2 = basisKey(parentKind, parentId, parentVersion);
3538
- if (ancestors.has(key2)) return false;
3552
+ const key3 = basisKey(parentKind, parentId, parentVersion);
3553
+ if (ancestors.has(key3)) return false;
3539
3554
  const state2 = this.state(scope, parentKind, parentId, cutoff);
3540
3555
  if (state2?.state !== "current" || state2.version !== parentVersion) return false;
3541
3556
  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;
@@ -3550,9 +3565,9 @@ END;
3550
3565
  }
3551
3566
  }
3552
3567
  if (refs2.some((ref) => ref.parentKind === "scope" && !ref.parentId.startsWith("valid-window:"))) {
3553
- if (!this.scopeContextRetained(scope, key2)) return false;
3568
+ if (!this.scopeContextRetained(scope, key3)) return false;
3554
3569
  }
3555
- const next = new Set(ancestors).add(key2);
3570
+ const next = new Set(ancestors).add(key3);
3556
3571
  for (const ref of refs2) {
3557
3572
  checkMemoryReadBudget(next.size);
3558
3573
  if (ref.parentKind === "source") {
@@ -3699,9 +3714,9 @@ function invalidateChildren(db2, scope, pending, reason) {
3699
3714
  let referencedPlan;
3700
3715
  while (pending.length) {
3701
3716
  const child = pending.shift();
3702
- const key2 = JSON.stringify([child.child_kind, child.child_id]);
3703
- if (visited.has(key2) && (visited.get(key2) || !child.deleted)) continue;
3704
- visited.set(key2, Boolean(child.deleted));
3717
+ const key3 = JSON.stringify([child.child_kind, child.child_id]);
3718
+ if (visited.has(key3) && (visited.get(key3) || !child.deleted)) continue;
3719
+ visited.set(key3, Boolean(child.deleted));
3705
3720
  if (child.child_kind === "graph_plan") {
3706
3721
  referencedPlan ??= db2.prepare(`SELECT 1 WHERE EXISTS (SELECT 1 FROM memory_dependencies
3707
3722
  WHERE scope_id=? AND parent_kind='artifact' AND parent_id=?)
@@ -3782,8 +3797,8 @@ var init_dependencies = __esm({
3782
3797
  this.snapshotStamp = void 0;
3783
3798
  }
3784
3799
  }
3785
- observeTimeBoundary(key2) {
3786
- const match = key2.match(/^valid-window:(-?\d+):(-?\d+)$/);
3800
+ observeTimeBoundary(key3) {
3801
+ const match = key3.match(/^valid-window:(-?\d+):(-?\d+)$/);
3787
3802
  if (!match) return;
3788
3803
  const now2 = Date.now();
3789
3804
  for (const boundary of [Number(match[1]), Number(match[2])]) {
@@ -3865,9 +3880,9 @@ var init_dependencies = __esm({
3865
3880
  }
3866
3881
  artifactTimeCurrent(scope, kind, id2, visited = /* @__PURE__ */ new Set(), memo) {
3867
3882
  checkMemoryReadBudget(visited.size);
3868
- const key2 = JSON.stringify([kind, id2]);
3869
- if (visited.has(key2)) return false;
3870
- visited.add(key2);
3883
+ const key3 = JSON.stringify([kind, id2]);
3884
+ if (visited.has(key3)) return false;
3885
+ visited.add(key3);
3871
3886
  try {
3872
3887
  const refs2 = this.refs(scope, kind, id2);
3873
3888
  for (const ref of refs2.filter((ref2) => ref2.parentKind !== "artifact")) {
@@ -3902,7 +3917,7 @@ var init_dependencies = __esm({
3902
3917
  }
3903
3918
  return true;
3904
3919
  } finally {
3905
- visited.delete(key2);
3920
+ visited.delete(key3);
3906
3921
  }
3907
3922
  }
3908
3923
  version(scope, kind, id2) {
@@ -4123,8 +4138,8 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
4123
4138
  * 事件重放失败一次即回死信+skip,不重烧 5 轮预算)。先 UPDATE 后记账:中间崩溃只会
4124
4139
  * 多治一次(幂等无害),反过来会出现"记了账但没治"的永久死锁。 */
4125
4140
  reenqueueGapPrefix(sinkId, head, now2 = Date.now()) {
4126
- const key2 = `${sinkId}:${head.scopeId}:${head.eventSeq}`;
4127
- if (this.healedGaps.has(key2)) return;
4141
+ const key3 = `${sinkId}:${head.scopeId}:${head.eventSeq}`;
4142
+ if (this.healedGaps.has(key3)) return;
4128
4143
  const ledgerPath = this.gapHealLedgerPath;
4129
4144
  let ledger = {};
4130
4145
  if (ledgerPath) {
@@ -4132,8 +4147,8 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
4132
4147
  ledger = JSON.parse(readFileSync7(ledgerPath, "utf8"))?.heals ?? {};
4133
4148
  } catch {
4134
4149
  }
4135
- if (Number.isFinite(ledger[key2])) {
4136
- this.healedGaps.add(key2);
4150
+ if (Number.isFinite(ledger[key3])) {
4151
+ this.healedGaps.add(key3);
4137
4152
  return;
4138
4153
  }
4139
4154
  }
@@ -4147,11 +4162,11 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
4147
4162
  const count = Number(result?.changes ?? 0);
4148
4163
  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`);
4149
4164
  });
4150
- this.healedGaps.add(key2);
4165
+ this.healedGaps.add(key3);
4151
4166
  if (!ledgerPath) return;
4152
4167
  const cutoff = now2 - _ChangeFeed.GAP_HEAL_RETENTION_MS, retained = {};
4153
4168
  for (const [entry, at] of Object.entries(ledger)) if (Number.isFinite(at) && at >= cutoff) retained[entry] = at;
4154
- retained[key2] = now2;
4169
+ retained[key3] = now2;
4155
4170
  const temp = `${ledgerPath}.${randomUUID6()}.tmp`;
4156
4171
  try {
4157
4172
  writeFileSync7(temp, JSON.stringify({ version: 1, heals: retained }));
@@ -4276,7 +4291,7 @@ function validatePredicateValue(predicate, value2) {
4276
4291
  if (!value2 || typeof value2 !== "object" || Array.isArray(value2)) throw new Error("INVALID_FACT_VALUE");
4277
4292
  const object4 = value2;
4278
4293
  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"];
4279
- if (Object.keys(object4).some((key2) => !allowed.includes(key2))) throw new Error("INVALID_FACT_VALUE: unknown field");
4294
+ if (Object.keys(object4).some((key3) => !allowed.includes(key3))) throw new Error("INVALID_FACT_VALUE: unknown field");
4280
4295
  if (predicate === "activity.schedule") {
4281
4296
  const schedule = object4;
4282
4297
  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");
@@ -4498,8 +4513,8 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
4498
4513
  ).all(scopeId(scope), `%${word.replace(/[!%_]/g, (character) => "!" + character)}%`, limit);
4499
4514
  return rows.map((row) => this.source(row));
4500
4515
  }
4501
- snapshotRead(key2, load) {
4502
- return this.snapshotReads ? this.snapshotReads.read(JSON.stringify(key2), load) : load();
4516
+ snapshotRead(key3, load) {
4517
+ return this.snapshotReads ? this.snapshotReads.read(JSON.stringify(key3), load) : load();
4503
4518
  }
4504
4519
  receive(input, options = {}) {
4505
4520
  const id2 = scopeId(input.scope);
@@ -4680,8 +4695,8 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
4680
4695
  const result = { applied: 0, needsReview: 0, failed: 0, received: 0 };
4681
4696
  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));
4682
4697
  for (const row of rows) {
4683
- const key2 = row.state === "needs_review" ? "needsReview" : row.state;
4684
- if (Object.hasOwn(result, key2)) result[key2] += Number(row.count);
4698
+ const key3 = row.state === "needs_review" ? "needsReview" : row.state;
4699
+ if (Object.hasOwn(result, key3)) result[key3] += Number(row.count);
4685
4700
  }
4686
4701
  return result;
4687
4702
  }
@@ -5058,9 +5073,9 @@ function resolveRecoveryDeletionSources(databases, deletions) {
5058
5073
  bytes += Buffer.byteLength(JSON.stringify(row));
5059
5074
  if (count > 1e6 || bytes > 64 * 1024 * 1024) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
5060
5075
  if (!row.scope_id || !row.source_id || !row.origin_key || !Number.isSafeInteger(row.source_version) || row.source_version < 1) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
5061
- const key2 = JSON.stringify([row.scope_id, row.source_id]), prior = originals.get(key2);
5076
+ const key3 = JSON.stringify([row.scope_id, row.source_id]), prior = originals.get(key3);
5062
5077
  if (prior && (prior.origin_key !== row.origin_key || prior.source_version !== row.source_version)) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
5063
- originals.set(key2, row);
5078
+ originals.set(key3, row);
5064
5079
  const familyKey = JSON.stringify([row.scope_id, row.origin_key]), family = families.get(familyKey) ?? { sources: /* @__PURE__ */ new Map(), versions: /* @__PURE__ */ new Map() };
5065
5080
  const versionId = family.versions.get(row.source_version);
5066
5081
  if (versionId !== void 0 && versionId !== row.source_id) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
@@ -5076,18 +5091,18 @@ function resolveRecoveryDeletionSources(databases, deletions) {
5076
5091
  const exact3 = originals.get(JSON.stringify([deletion.scopeId, deletion.sourceId]));
5077
5092
  if (exact3 && exact3.source_version !== deletion.version) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
5078
5093
  let familyKey = exact3 ? JSON.stringify([exact3.scope_id, exact3.origin_key]) : void 0;
5079
- if (!familyKey) for (const [key2, family] of families) {
5094
+ if (!familyKey) for (const [key3, family] of families) {
5080
5095
  const original = family.sources.values().next().value;
5081
5096
  if (original.scope_id !== deletion.scopeId) continue;
5082
5097
  if (++checks > 1e6) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
5083
5098
  if (recoveryOriginalSourceId(original.scope_id, original.origin_key, deletion.version) !== deletion.sourceId) continue;
5084
- if (familyKey && familyKey !== key2) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
5085
- familyKey = key2;
5099
+ if (familyKey && familyKey !== key3) throw new Error("RECOVERY_DELETION_SOURCE_MISMATCH");
5100
+ familyKey = key3;
5086
5101
  }
5087
5102
  if (!familyKey) throw new Error("RECOVERY_DELETION_SOURCE_UNRESOLVED");
5088
5103
  for (const original of families.get(familyKey).sources.values()) {
5089
- const key2 = JSON.stringify([original.scope_id, original.source_id]);
5090
- if (!result.has(key2)) result.set(key2, { scopeId: original.scope_id, sourceId: original.source_id, version: original.source_version, deletionId: deletion.id });
5104
+ const key3 = JSON.stringify([original.scope_id, original.source_id]);
5105
+ if (!result.has(key3)) result.set(key3, { scopeId: original.scope_id, sourceId: original.source_id, version: original.source_version, deletionId: deletion.id });
5091
5106
  }
5092
5107
  }
5093
5108
  return [...result.values()].sort((a, b) => a.scopeId.localeCompare(b.scopeId, "en") || a.version - b.version || a.sourceId.localeCompare(b.sourceId, "en"));
@@ -5156,7 +5171,7 @@ var init_recovery_deletion = __esm({
5156
5171
  "src/continuity/recovery-deletion.ts"() {
5157
5172
  "use strict";
5158
5173
  init_recovery_deletion_sources();
5159
- text = (row, key2) => row[key2]?.[0] === "text" ? row[key2][1] : void 0;
5174
+ text = (row, key3) => row[key3]?.[0] === "text" ? row[key3][1] : void 0;
5160
5175
  key = (scope, kind, id2) => JSON.stringify([scope, kind, id2]);
5161
5176
  RecoveryDeletionGraph = class {
5162
5177
  edges = /* @__PURE__ */ new Map();
@@ -5658,9 +5673,9 @@ ALTER TABLE memory_host_turns ADD COLUMN owner_id TEXT;
5658
5673
  }
5659
5674
  }
5660
5675
  recordCompleted(id2, sourceId, sourceVersion, now2) {
5661
- const key2 = JSON.stringify(["host.turn.completed", id2, sourceId]);
5676
+ const key3 = JSON.stringify(["host.turn.completed", id2, sourceId]);
5662
5677
  this.db.prepare(`INSERT OR IGNORE INTO ome_jobs(kind,payload,status,next_run_at,created_at,job_key,scope_id,completed_at)
5663
- VALUES ('host.turn.completed',?,'done',?,?,?,?,?)`).run(JSON.stringify({ scopeId: id2, sourceId, sourceVersion }), now2, now2, key2, id2, now2);
5678
+ VALUES ('host.turn.completed',?,'done',?,?,?,?,?)`).run(JSON.stringify({ scopeId: id2, sourceId, sourceVersion }), now2, now2, key3, id2, now2);
5664
5679
  }
5665
5680
  };
5666
5681
  }
@@ -6288,7 +6303,7 @@ function recoverLegacySession(db2, store, mapping, files, apply = false) {
6288
6303
  return report;
6289
6304
  }
6290
6305
  function recoverLegacyProjections(db2, store, input, apply = false) {
6291
- const key2 = scopeId(input.scope);
6306
+ const key3 = scopeId(input.scope);
6292
6307
  const root = realpathSync6(input.root);
6293
6308
  const report = { files: 0, entries: 0, recoverable: 0, alreadyMapped: 0, unavailable: 0, reasons: {}, applied: false };
6294
6309
  const gap = (reason) => {
@@ -6333,7 +6348,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6333
6348
  const block = match[0];
6334
6349
  const field = (name) => match[2].match(new RegExp(`^\\*\\*${name}\\*\\*: ([^\\n]*)$`, "m"))?.[1]?.trim();
6335
6350
  const parent = field("parent_id");
6336
- const mapping = db2.prepare("SELECT * FROM memory_legacy_cell_maps WHERE cell_id=? AND scope_id=?").get(parent ?? "", key2);
6351
+ const mapping = db2.prepare("SELECT * FROM memory_legacy_cell_maps WHERE cell_id=? AND scope_id=?").get(parent ?? "", key3);
6337
6352
  if (!mapping || field("parent_type") !== "memcell" || field("owner_id") !== input.scope.ownerId || field("session_id") !== mapping.session_id) {
6338
6353
  gap("projection_parent_provenance_missing");
6339
6354
  continue;
@@ -6350,7 +6365,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6350
6365
  gap("projection_body_missing");
6351
6366
  continue;
6352
6367
  }
6353
- const previous = db2.prepare("SELECT * FROM memory_legacy_projection_maps WHERE scope_id=? AND kind=? AND entry_id=?").get(key2, kind, match[1]);
6368
+ const previous = db2.prepare("SELECT * FROM memory_legacy_projection_maps WHERE scope_id=? AND kind=? AND entry_id=?").get(key3, kind, match[1]);
6354
6369
  const target = join14(store.mem7RootPath(), path37);
6355
6370
  if (previous) {
6356
6371
  if (previous.source_file_hash !== fileHash || previous.parent_id !== parent || previous.source_relative_path !== path37 || !store.projectionMatches(input.scope, kind, match[1], target, block)) {
@@ -6402,7 +6417,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6402
6417
  role: "supports"
6403
6418
  })));
6404
6419
  const digest7 = hash3(candidate.block.trim());
6405
- db2.prepare("INSERT INTO memory_projection_entries VALUES (?,?,?,?,?,?)").run(key2, candidate.kind, candidate.id, candidate.relativePath, 1, digest7);
6420
+ db2.prepare("INSERT INTO memory_projection_entries VALUES (?,?,?,?,?,?)").run(key3, candidate.kind, candidate.id, candidate.relativePath, 1, digest7);
6406
6421
  store.artifacts.publish(input.scope, {
6407
6422
  kind: candidate.kind,
6408
6423
  id: candidate.id,
@@ -6414,7 +6429,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6414
6429
  summary: candidate.summary,
6415
6430
  title: candidate.title
6416
6431
  });
6417
- db2.prepare("INSERT INTO memory_legacy_projection_maps VALUES (?,?,?,?,?,?,?)").run(key2, candidate.kind, candidate.id, candidate.fileHash, candidate.relativePath, candidate.parent, 1);
6432
+ db2.prepare("INSERT INTO memory_legacy_projection_maps VALUES (?,?,?,?,?,?,?)").run(key3, candidate.kind, candidate.id, candidate.fileHash, candidate.relativePath, candidate.parent, 1);
6418
6433
  }
6419
6434
  });
6420
6435
  report.applied = true;
@@ -6546,10 +6561,10 @@ var init_recall_sources = __esm({
6546
6561
  }
6547
6562
  const queue = db2.prepare("SELECT target_id FROM memory_tombstones WHERE scope_id=? AND target_kind='source'").all(id2).map((row) => `s:${row.target_id}`);
6548
6563
  for (let index = 0; index < queue.length; index++) {
6549
- const key2 = queue[index];
6550
- if (this.removed.has(key2)) continue;
6551
- this.removed.add(key2);
6552
- queue.push(...dependents.get(key2) ?? []);
6564
+ const key3 = queue[index];
6565
+ if (this.removed.has(key3)) continue;
6566
+ this.removed.add(key3);
6567
+ queue.push(...dependents.get(key3) ?? []);
6553
6568
  }
6554
6569
  }
6555
6570
  sources = /* @__PURE__ */ new Map();
@@ -6724,9 +6739,9 @@ CREATE TABLE memory_person_mentions (
6724
6739
  ])];
6725
6740
  if (ids.length > 8192 || this.snapshot.relationships.size > 8192) return result;
6726
6741
  const sourceIds = JSON.stringify(ids.sort());
6727
- const relationshipRefs = JSON.stringify([...this.snapshot.relationships.keys()].sort().map((key2) => {
6728
- const split = key2.lastIndexOf(":");
6729
- return [key2.slice(0, split), Number(key2.slice(split + 1))];
6742
+ const relationshipRefs = JSON.stringify([...this.snapshot.relationships.keys()].sort().map((key3) => {
6743
+ const split = key3.lastIndexOf(":");
6744
+ return [key3.slice(0, split), Number(key3.slice(split + 1))];
6730
6745
  }));
6731
6746
  this.snapshotBasis = this.readProvenanceBasis(this.snapshot, sourceIds, relationshipRefs);
6732
6747
  }
@@ -6774,19 +6789,19 @@ CREATE TABLE memory_person_mentions (
6774
6789
  const sourceChecks = new Map(sources.map((row) => [row.id, JSON.stringify(row)]));
6775
6790
  const relationshipRows = /* @__PURE__ */ new Map();
6776
6791
  for (const row of relationships) {
6777
- const key2 = `${row.id}:${row.version}`;
6778
- const rows = relationshipRows.get(key2) ?? [];
6792
+ const key3 = `${row.id}:${row.version}`;
6793
+ const rows = relationshipRows.get(key3) ?? [];
6779
6794
  rows.push(row);
6780
- relationshipRows.set(key2, rows);
6795
+ relationshipRows.set(key3, rows);
6781
6796
  }
6782
- const relationshipChecks = new Map([...relationshipRows].map(([key2, rows]) => [key2, createHash16("sha256").update(JSON.stringify(rows)).digest("hex")]));
6797
+ const relationshipChecks = new Map([...relationshipRows].map(([key3, rows]) => [key3, createHash16("sha256").update(JSON.stringify(rows)).digest("hex")]));
6783
6798
  checkMemoryReadBudget();
6784
6799
  return { sourceIds, relationshipRefs, digest: digest7, sources: sourceChecks, relationships: relationshipChecks };
6785
6800
  }
6786
6801
  provenanceSnapshot(scope, cutoff) {
6787
6802
  const stamp2 = this.provenanceStamp();
6788
- const key2 = JSON.stringify([scopeId(scope), cutoff ?? null]);
6789
- if (stamp2 !== this.snapshotStamp && this.snapshot?.key === key2 && !cutoff && this.snapshotBasis && this.readSnapshotDepth && this.snapshot.sources.size <= 8192) {
6803
+ const key3 = JSON.stringify([scopeId(scope), cutoff ?? null]);
6804
+ if (stamp2 !== this.snapshotStamp && this.snapshot?.key === key3 && !cutoff && this.snapshotBasis && this.readSnapshotDepth && this.snapshot.sources.size <= 8192) {
6790
6805
  const previous = this.snapshotBasis;
6791
6806
  const next = this.readProvenanceBasis(this.snapshot, previous.sourceIds, previous.relationshipRefs);
6792
6807
  if (next.digest !== previous.digest) {
@@ -6798,17 +6813,17 @@ CREATE TABLE memory_person_mentions (
6798
6813
  this.snapshot.metadata.delete(id2);
6799
6814
  this.snapshot.currentSources.delete(id2);
6800
6815
  }
6801
- for (const [key3, check] of previous.relationships) {
6802
- if (next.relationships.get(key3) !== check) this.snapshot.relationships.delete(key3);
6816
+ for (const [key4, check] of previous.relationships) {
6817
+ if (next.relationships.get(key4) !== check) this.snapshot.relationships.delete(key4);
6803
6818
  }
6804
6819
  }
6805
6820
  this.snapshotBasis = next;
6806
6821
  this.snapshotStamp = stamp2;
6807
6822
  }
6808
- if (stamp2 !== this.snapshotStamp || this.snapshot?.key !== key2 || this.snapshot.sources.size > 8192 || this.snapshot.currentSources.size > 8192 || this.snapshot.relationships.size > 8192) {
6823
+ if (stamp2 !== this.snapshotStamp || this.snapshot?.key !== key3 || this.snapshot.sources.size > 8192 || this.snapshot.currentSources.size > 8192 || this.snapshot.relationships.size > 8192) {
6809
6824
  this.snapshotStamp = stamp2;
6810
6825
  this.snapshotBasis = void 0;
6811
- 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() };
6826
+ this.snapshot = { key: key3, memo: /* @__PURE__ */ new Map(), grounds: /* @__PURE__ */ new Map(), currentSources: /* @__PURE__ */ new Map(), sources: /* @__PURE__ */ new Map(), metadata: /* @__PURE__ */ new Map(), relationships: /* @__PURE__ */ new Map() };
6812
6827
  }
6813
6828
  return this.snapshot;
6814
6829
  }
@@ -6939,21 +6954,21 @@ CREATE TABLE memory_person_mentions (
6939
6954
  provenanceReferenceRetained(scope, ref, visited, cutoff, snapshot) {
6940
6955
  checkMemoryReadBudget(visited.size);
6941
6956
  if (ref.scopeId !== scopeId(scope) || visited.has(ref.sourceId) || ref.relationshipId && visited.has(`${ref.relationshipId}:${ref.semanticVersion}`)) return false;
6942
- const key2 = `reference:${JSON.stringify([ref.sourceId, ref.sourceVersion, ref.relationshipId, ref.semanticVersion])}`;
6943
- if (snapshot.memo.has(key2)) return snapshot.memo.get(key2);
6957
+ const key3 = `reference:${JSON.stringify([ref.sourceId, ref.sourceVersion, ref.relationshipId, ref.semanticVersion])}`;
6958
+ if (snapshot.memo.has(key3)) return snapshot.memo.get(key3);
6944
6959
  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);
6945
- snapshot.memo.set(key2, retained);
6960
+ snapshot.memo.set(key3, retained);
6946
6961
  return retained;
6947
6962
  }
6948
6963
  /** Authored thoughts remain historical memories when a cited source is corrected; deletion still wins. */
6949
6964
  provenanceRetained(scope, sourceId, visited, cutoff, snapshot) {
6950
6965
  checkMemoryReadBudget(visited.size);
6951
6966
  if (visited.has(sourceId)) return false;
6952
- const key2 = `source:${sourceId}`;
6967
+ const key3 = `source:${sourceId}`;
6953
6968
  const { memo } = snapshot;
6954
- if (memo.has(key2)) return memo.get(key2);
6969
+ if (memo.has(key3)) return memo.get(key3);
6955
6970
  if (!this.provenanceSource(scope, sourceId, cutoff, snapshot) || this.tombstoneRead.get(scopeId(scope), sourceId)) {
6956
- memo.set(key2, false);
6971
+ memo.set(key3, false);
6957
6972
  return false;
6958
6973
  }
6959
6974
  if (!snapshot.metadata.has(sourceId)) snapshot.metadata.set(sourceId, this.metadata(scope, sourceId));
@@ -6962,7 +6977,7 @@ CREATE TABLE memory_person_mentions (
6962
6977
  try {
6963
6978
  const check = (ref) => this.provenanceReferenceRetained(scope, ref, visited, cutoff, snapshot);
6964
6979
  const retained = !metadata4 || metadata4.contextRefs.every(check) && metadata4.basisRefs.every(check);
6965
- memo.set(key2, retained);
6980
+ memo.set(key3, retained);
6966
6981
  return retained;
6967
6982
  } finally {
6968
6983
  visited.delete(sourceId);
@@ -6996,10 +7011,10 @@ CREATE TABLE memory_person_mentions (
6996
7011
  sourceGroundsCurrent(scope, sourceId, visited, cutoff, snapshot) {
6997
7012
  checkMemoryReadBudget(visited.size);
6998
7013
  if (visited.has(sourceId)) return false;
6999
- const key2 = `source:${sourceId}`;
7000
- if (snapshot.grounds.has(key2)) return snapshot.grounds.get(key2);
7014
+ const key3 = `source:${sourceId}`;
7015
+ if (snapshot.grounds.has(key3)) return snapshot.grounds.get(key3);
7001
7016
  if (!this.sourceCurrent(scope, sourceId, cutoff, snapshot) || !this.provenanceRetained(scope, sourceId, /* @__PURE__ */ new Set(), cutoff, snapshot)) {
7002
- snapshot.grounds.set(key2, false);
7017
+ snapshot.grounds.set(key3, false);
7003
7018
  return false;
7004
7019
  }
7005
7020
  if (!snapshot.metadata.has(sourceId)) snapshot.metadata.set(sourceId, this.metadata(scope, sourceId));
@@ -7007,7 +7022,7 @@ CREATE TABLE memory_person_mentions (
7007
7022
  visited.add(sourceId);
7008
7023
  try {
7009
7024
  const current2 = !metadata4 || metadata4.basisRefs.every((ref) => this.currentReference(scope, ref, visited, cutoff, snapshot));
7010
- snapshot.grounds.set(key2, current2);
7025
+ snapshot.grounds.set(key3, current2);
7011
7026
  return current2;
7012
7027
  } finally {
7013
7028
  visited.delete(sourceId);
@@ -7017,46 +7032,46 @@ CREATE TABLE memory_person_mentions (
7017
7032
  checkMemoryReadBudget(visited.size);
7018
7033
  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;
7019
7034
  if (!ref.relationshipId) return true;
7020
- const key2 = `${ref.relationshipId}:${ref.semanticVersion}`;
7021
- if (visited.has(key2)) return false;
7022
- const memoKey = `relationship:${key2}:${ref.purpose === "historical" ? "historical" : "current"}`;
7035
+ const key3 = `${ref.relationshipId}:${ref.semanticVersion}`;
7036
+ if (visited.has(key3)) return false;
7037
+ const memoKey = `relationship:${key3}:${ref.purpose === "historical" ? "historical" : "current"}`;
7023
7038
  if (snapshot.grounds.has(memoKey)) return snapshot.grounds.get(memoKey);
7024
- if (!snapshot.relationships.has(key2)) {
7039
+ if (!snapshot.relationships.has(key3)) {
7025
7040
  this.snapshotBasis = void 0;
7026
- snapshot.relationships.set(key2, this.relationshipReferenceMaterial(scope, ref, cutoff));
7041
+ snapshot.relationships.set(key3, this.relationshipReferenceMaterial(scope, ref, cutoff));
7027
7042
  }
7028
- const material = snapshot.relationships.get(key2);
7043
+ const material = snapshot.relationships.get(key3);
7029
7044
  if (!material || ["deleted", "retracted"].includes(material.state) || ref.purpose !== "historical" && !material.current) return false;
7030
- visited.add(key2);
7045
+ visited.add(key3);
7031
7046
  try {
7032
7047
  const current2 = material.evidenceSourceIds.every((id2) => this.sourceGroundsCurrent(scope, id2, visited, cutoff, snapshot)) && material.basisRefs.every((basis) => this.currentReference(scope, basis, visited, cutoff, snapshot));
7033
7048
  snapshot.grounds.set(memoKey, current2);
7034
7049
  return current2;
7035
7050
  } finally {
7036
- visited.delete(key2);
7051
+ visited.delete(key3);
7037
7052
  }
7038
7053
  }
7039
7054
  relationshipReferenceRetained(scope, ref, visited, cutoff, snapshot = this.provenanceSnapshot(scope, cutoff)) {
7040
7055
  checkMemoryReadBudget(visited.size);
7041
7056
  if (!ref.relationshipId) return true;
7042
- const key2 = `${ref.relationshipId}:${ref.semanticVersion}`;
7043
- if (visited.has(key2)) return false;
7044
- const memoKey = `relationship:${key2}`;
7057
+ const key3 = `${ref.relationshipId}:${ref.semanticVersion}`;
7058
+ if (visited.has(key3)) return false;
7059
+ const memoKey = `relationship:${key3}`;
7045
7060
  const { memo } = snapshot;
7046
7061
  if (memo.has(memoKey)) return memo.get(memoKey);
7047
- if (!snapshot.relationships.has(key2)) {
7062
+ if (!snapshot.relationships.has(key3)) {
7048
7063
  this.snapshotBasis = void 0;
7049
- snapshot.relationships.set(key2, this.relationshipReferenceMaterial(scope, ref, cutoff));
7064
+ snapshot.relationships.set(key3, this.relationshipReferenceMaterial(scope, ref, cutoff));
7050
7065
  }
7051
- const material = snapshot.relationships.get(key2);
7066
+ const material = snapshot.relationships.get(key3);
7052
7067
  if (!material) return false;
7053
- visited.add(key2);
7068
+ visited.add(key3);
7054
7069
  try {
7055
7070
  const retained = material.evidenceSourceIds.every((id2) => this.provenanceRetained(scope, id2, visited, cutoff, snapshot)) && material.basisRefs.every((basis) => this.provenanceReferenceRetained(scope, basis, visited, cutoff, snapshot));
7056
7071
  memo.set(memoKey, retained);
7057
7072
  return retained;
7058
7073
  } finally {
7059
- visited.delete(key2);
7074
+ visited.delete(key3);
7060
7075
  }
7061
7076
  }
7062
7077
  relationshipReferenceMaterial(scope, ref, cutoff) {
@@ -7503,16 +7518,16 @@ CREATE TABLE memory_relationship_receipts (
7503
7518
  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);
7504
7519
  if (!row) return null;
7505
7520
  if (historicalVersion) Object.assign(row, historicalVersion);
7506
- const key2 = `${relationshipId}:${row.semantic_version}`;
7507
- if (visited.has(key2)) return null;
7508
- const next = new Set(visited).add(key2);
7521
+ const key3 = `${relationshipId}:${row.semantic_version}`;
7522
+ if (visited.has(key3)) return null;
7523
+ const next = new Set(visited).add(key3);
7509
7524
  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 }));
7510
7525
  const basisRefs = JSON.parse(row.basis_refs);
7511
7526
  const refs2 = [...evidence.map((ref) => ({ sourceId: ref.sourceId })), ...basisRefs];
7512
7527
  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;
7513
7528
  const value2 = JSON.parse(row.value_json);
7514
7529
  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;
7515
- 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)) : refs2.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));
7530
+ 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), key3)?.state)) : refs2.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));
7516
7531
  return {
7517
7532
  relationshipId,
7518
7533
  semanticVersion: row.semantic_version,
@@ -8371,10 +8386,10 @@ CREATE TABLE memory_relationship_cognition_results (
8371
8386
  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)] : []);
8372
8387
  const groups = /* @__PURE__ */ new Map();
8373
8388
  for (const row of rows) {
8374
- const key2 = canonicalJson([row.scope_id, row.perspective_entity_id, row.group_key, row.generation]);
8375
- const group = groups.get(key2) || { scopeId: row.scope_id, perspectiveEntityId: row.perspective_entity_id, groupKey: row.group_key, sourceIds: [], generation: row.generation };
8389
+ const key3 = canonicalJson([row.scope_id, row.perspective_entity_id, row.group_key, row.generation]);
8390
+ const group = groups.get(key3) || { scopeId: row.scope_id, perspectiveEntityId: row.perspective_entity_id, groupKey: row.group_key, sourceIds: [], generation: row.generation };
8376
8391
  if (group.sourceIds.length < 20) group.sourceIds.push(row.source_id);
8377
- groups.set(key2, group);
8392
+ groups.set(key3, group);
8378
8393
  }
8379
8394
  return [...groups.values()];
8380
8395
  }
@@ -8564,9 +8579,9 @@ var init_entities = __esm({
8564
8579
  aliasEvidence(scope, entityId, cutoff) {
8565
8580
  const seen = /* @__PURE__ */ new Set();
8566
8581
  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) => {
8567
- const key2 = normalizeAlias(alias.alias);
8568
- 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;
8569
- seen.add(key2);
8582
+ const key3 = normalizeAlias(alias.alias);
8583
+ if (seen.has(key3) || 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;
8584
+ seen.add(key3);
8570
8585
  return true;
8571
8586
  }).map((alias) => ({ alias: alias.alias, sourceId: alias.sourceId, sourceVersion: this.sources.get(scope, alias.sourceId, cutoff).sourceVersion }));
8572
8587
  }
@@ -8765,12 +8780,12 @@ function checkNotice(db2, sources, social, scope, id2, options) {
8765
8780
  return Boolean(source && (version === void 0 || source.sourceVersion === version) && social.readable(memoryScope, sourceId) && social.groundsCurrent(memoryScope, sourceId));
8766
8781
  };
8767
8782
  const relationshipCurrent = (relationshipId, version) => {
8768
- const key2 = `${relationshipId}:${version}`;
8783
+ const key3 = `${relationshipId}:${version}`;
8769
8784
  const row = db2.prepare(`SELECT r.*,v.state FROM memory_relationship_versions r JOIN fact_versions v
8770
8785
  ON v.scope_id=r.scope_id AND v.assertion_id=r.assertion_id AND v.system_to_revision IS NULL
8771
8786
  WHERE r.scope_id=? AND r.relationship_id=? AND r.semantic_version=?`).get(scope, relationshipId, version);
8772
8787
  if (!row || ["deleted", "retracted"].includes(row.state)) return false;
8773
- const derivation = db2.prepare("SELECT state FROM memory_derivations WHERE scope_id=? AND child_kind='relationship' AND child_id=?").get(scope, key2);
8788
+ const derivation = db2.prepare("SELECT state FROM memory_derivations WHERE scope_id=? AND child_kind='relationship' AND child_id=?").get(scope, key3);
8774
8789
  if (derivation && derivation.state !== "current") return false;
8775
8790
  const evidence = db2.prepare("SELECT source_id FROM fact_evidence WHERE scope_id=? AND assertion_id=?").all(scope, row.assertion_id);
8776
8791
  return evidence.length > 0 && evidence.every((ref) => sourceCurrent(ref.source_id)) && JSON.parse(row.basis_refs).every((ref) => social.referenceCurrent(memoryScope, ref));
@@ -8845,8 +8860,11 @@ CREATE TABLE memory_relationship_notice_versions (
8845
8860
  }
8846
8861
  get(scope, id2) {
8847
8862
  const row = this.db.prepare("SELECT * FROM memory_relationship_notices WHERE scope_id=? AND notice_id=?").get(scopeId(scope), id2);
8848
- return row ? {
8849
- id: id2,
8863
+ return row ? this.decode(scope, row) : null;
8864
+ }
8865
+ decode(scope, row) {
8866
+ return {
8867
+ id: row.notice_id,
8850
8868
  scope,
8851
8869
  kind: row.kind,
8852
8870
  targetId: row.target_id,
@@ -8856,10 +8874,25 @@ CREATE TABLE memory_relationship_notice_versions (
8856
8874
  state: row.state,
8857
8875
  attempts: row.attempts,
8858
8876
  reason: row.reason
8859
- } : null;
8877
+ };
8860
8878
  }
8861
- list(scope) {
8862
- 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));
8879
+ list(scope, includeTerminal = true) {
8880
+ return this.db.prepare(`SELECT * FROM memory_relationship_notices WHERE scope_id=?
8881
+ ${includeTerminal ? "" : "AND state NOT IN ('delivered','blocked')"} ORDER BY updated_at,notice_id`).all(scopeId(scope)).map((row) => this.decode(scope, row));
8882
+ }
8883
+ /** Quiet identity work is not notification work. Evidence-backed resolved identities can still be withdrawn. */
8884
+ clarificationCandidates(scope) {
8885
+ const rows = this.db.prepare(`SELECT m.mention_id,m.question,m.mention_kind,m.candidates,m.span_start,m.span_end,s.text
8886
+ FROM memory_person_mentions m JOIN memory_sources s ON s.scope_id=m.scope_id AND s.source_id=m.source_id
8887
+ WHERE m.scope_id=? AND m.question IS NOT NULL AND trim(m.question)<>''
8888
+ AND (m.state='unresolved' OR m.clarification_source_id IS NOT NULL OR m.basis_refs<>'[]')
8889
+ AND (m.mention_kind NOT IN ('description','reference') OR json_array_length(m.candidates)>=2)
8890
+ ORDER BY m.source_id,m.span_start`).all(scopeId(scope));
8891
+ return rows.filter((row) => hasIdentityQuestion(
8892
+ row.question,
8893
+ row.text.slice(row.span_start, row.span_end),
8894
+ { mentionKind: row.mention_kind, candidateEntityIds: JSON.parse(row.candidates) }
8895
+ )).map((row) => row.mention_id);
8863
8896
  }
8864
8897
  finish(scope, id2, state2, reason = "", redact = false) {
8865
8898
  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(state2, reason, (/* @__PURE__ */ new Date()).toISOString(), Number(redact), scopeId(scope), id2);
@@ -8870,6 +8903,12 @@ CREATE TABLE memory_relationship_notice_versions (
8870
8903
  check(scope, id2, options = {}) {
8871
8904
  return checkRelationshipNotice(this.db, scopeId(scope), id2, options);
8872
8905
  }
8906
+ /** The caller holds one transaction; proofs are discarded before any later batch or write. */
8907
+ checkMany(scope, ids, options = {}) {
8908
+ if (!ids.length) return [];
8909
+ const check = createRelationshipNoticeChecker(this.db);
8910
+ return ids.map((id2) => check(scopeId(scope), id2, options));
8911
+ }
8873
8912
  queue(scope, id2) {
8874
8913
  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), id2).changes);
8875
8914
  }
@@ -8881,6 +8920,7 @@ CREATE TABLE memory_relationship_notice_versions (
8881
8920
  importantRecords(scope) {
8882
8921
  return this.db.prepare(`SELECT v.relationship_id,v.semantic_version FROM memory_relationship_notice_versions v
8883
8922
  JOIN memory_relationship_cognition_results r ON r.scope_id=v.scope_id AND r.job_id=v.job_id
8923
+ 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
8884
8924
  WHERE v.scope_id=? AND r.important=1`).all(scopeId(scope)).map((row) => ({ relationshipId: row.relationship_id, semanticVersion: row.semantic_version }));
8885
8925
  }
8886
8926
  recordRoute(scope, sourceId, input) {
@@ -8948,9 +8988,9 @@ function installRelationshipHistory(db2) {
8948
8988
  FROM memory_scopes s WHERE EXISTS (SELECT 1 FROM memory_relationship_heads h WHERE h.scope_id=s.scope_id)
8949
8989
  OR EXISTS (SELECT 1 FROM memory_person_sources p WHERE p.scope_id=s.scope_id)
8950
8990
  OR EXISTS (SELECT 1 FROM memory_person_mentions m WHERE m.scope_id=s.scope_id)`);
8951
- for (const { table, kind, key: key2, columns: columns2 } of tables2) {
8991
+ for (const { table, kind, key: key3, columns: columns2 } of tables2) {
8952
8992
  const payload = (prefix2) => `json_object(${columns2.map((column) => `'${column}',${prefix2}${column}`).join(",")})`;
8953
- const target = (prefix2) => key2.startsWith("json_array") ? `json_array(${key2.slice(11, -1).split(",").map((column) => `${prefix2}${column}`).join(",")})` : `${prefix2}${key2}`;
8993
+ const target = (prefix2) => key3.startsWith("json_array") ? `json_array(${key3.slice(11, -1).split(",").map((column) => `${prefix2}${column}`).join(",")})` : `${prefix2}${key3}`;
8954
8994
  db2.exec(`INSERT INTO memory_knowledge_history(scope_id,target_kind,target_id,entity_revision,fact_revision,context_revision,recorded_at,payload_json)
8955
8995
  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.")}
8956
8996
  FROM ${table} t JOIN memory_scopes s ON s.scope_id=t.scope_id`);
@@ -9379,16 +9419,16 @@ var init_snapshot_reads = __esm({
9379
9419
  this.changes = -1;
9380
9420
  }
9381
9421
  }
9382
- read(key2, load) {
9422
+ read(key3, load) {
9383
9423
  if (!this.values || !this.db.isTransaction) return load();
9384
9424
  const changes = this.changesRead.get().n;
9385
9425
  if (changes !== this.changes) {
9386
9426
  this.values.clear();
9387
9427
  this.changes = changes;
9388
9428
  }
9389
- if (this.values.has(key2)) return this.values.get(key2);
9429
+ if (this.values.has(key3)) return this.values.get(key3);
9390
9430
  const value2 = load();
9391
- if (this.values.size < 8192) this.values.set(key2, value2);
9431
+ if (this.values.size < 8192) this.values.set(key3, value2);
9392
9432
  return value2;
9393
9433
  }
9394
9434
  };
@@ -9514,7 +9554,7 @@ function classifyFactVersions(versions, predicate, time) {
9514
9554
  needsReview: disputed || hypotheses.some((fact) => fact.validFrom === null)
9515
9555
  };
9516
9556
  }
9517
- var hash5, makeSlotId, FactStore;
9557
+ var hash5, makeSlotId, CLOSE_VALIDITY, occurrences, CHANGE_KINDS, CLAIM_KINDS, normalizeChange, FactStore;
9518
9558
  var init_facts = __esm({
9519
9559
  "src/mem7/core/state/facts.ts"() {
9520
9560
  "use strict";
@@ -9526,6 +9566,15 @@ var init_facts = __esm({
9526
9566
  init_basis_check();
9527
9567
  hash5 = (value2) => createHash19("sha256").update(canonicalJson(value2)).digest("hex");
9528
9568
  makeSlotId = (subjectId, predicate, context) => `slot_${hash5([subjectId, predicate, context]).slice(0, 32)}`;
9569
+ CLOSE_VALIDITY = '{"validFrom":null,"validTo":"\u7ED3\u675F\u65F6\u523B","precision":"exact"}';
9570
+ occurrences = (text2, quote4) => {
9571
+ let count = 0;
9572
+ for (let at = text2.indexOf(quote4); quote4 && at >= 0; at = text2.indexOf(quote4, at + 1)) count++;
9573
+ return count;
9574
+ };
9575
+ CHANGE_KINDS = ["assert", "reinforce", "state_change", "correction", "exception", "dispute", "retract", "close"];
9576
+ CLAIM_KINDS = ["user_statement", "tool_observation", "reported_statement", "inference", "agent_statement"];
9577
+ normalizeChange = (proposal) => !["close", "retract"].includes(proposal.changeKind) || !proposal.validity || proposal.validity.validFrom !== void 0 ? proposal : { ...proposal, validity: { ...proposal.validity, validFrom: null } };
9529
9578
  FactStore = class {
9530
9579
  constructor(db2, entities, transaction, readTransaction = transaction) {
9531
9580
  this.db = db2;
@@ -9692,6 +9741,8 @@ var init_facts = __esm({
9692
9741
  applyChange(scope, proposal, expectedSlotRevision, requestKey, batch) {
9693
9742
  if (!requestKey || !Number.isSafeInteger(expectedSlotRevision) || expectedSlotRevision < 0) throw new Error("INVALID_FACT_REQUEST");
9694
9743
  const id2 = scopeId(scope);
9744
+ const located = this.locateEvidence(id2, normalizeChange(proposal));
9745
+ proposal = located.proposal;
9695
9746
  const requestHash = hash5([proposal, expectedSlotRevision]);
9696
9747
  const prior = this.db.prepare("SELECT request_hash,result_json FROM fact_changes WHERE scope_id=? AND request_key=?").get(id2, requestKey);
9697
9748
  if (prior) {
@@ -9700,21 +9751,22 @@ var init_facts = __esm({
9700
9751
  }
9701
9752
  this.validate(scope, proposal);
9702
9753
  const slot = this.slot(scope, proposal.subjectId, proposal.predicate, proposal.contextKey);
9703
- if (slot.revision !== expectedSlotRevision) throw new Error(`STALE_VERSION: expected slot ${expectedSlotRevision}, current ${slot.revision}`);
9754
+ 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` : ""));
9704
9755
  this.db.prepare("INSERT OR IGNORE INTO fact_slots(scope_id,slot_id,subject_id,predicate,context_key,cardinality) VALUES (?,?,?,?,?,?)").run(id2, slot.slotId, proposal.subjectId, proposal.predicate, proposal.contextKey, predicates[proposal.predicate].cardinality);
9705
9756
  const before = this.current(id2, slot.slotId);
9706
9757
  const targetIds = [...new Set(proposal.targetAssertionIds ?? [])];
9707
9758
  const targets = targetIds.map((targetId) => {
9708
9759
  const target = before.find((fact) => fact.assertionId === targetId);
9709
- if (!target || ["retracted", "deleted"].includes(target.state)) throw new Error("FACT_TARGET_MISMATCH");
9760
+ 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`);
9710
9761
  return target;
9711
9762
  });
9712
- if (["reinforce", "state_change", "correction", "retract", "close"].includes(proposal.changeKind) && targets.length === 0) throw new Error("FACT_TARGET_REQUIRED");
9763
+ 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`);
9713
9764
  if (proposal.changeKind === "reinforce" && targets.length !== 1) throw new Error("REINFORCE_REQUIRES_ONE_TARGET");
9714
9765
  if (["assert", "exception"].includes(proposal.changeKind) && targets.length) throw new Error("UNEXPECTED_FACT_TARGET");
9715
9766
  const validity = proposal.validity ? normalizeValidity(proposal.validity) : void 0;
9716
- if (proposal.changeKind === "state_change" && (validity?.validFrom == null || validity.precision !== "exact")) throw new Error("CHANGE_TIME_REQUIRED");
9717
- if (proposal.changeKind === "close" && (validity?.validTo == null || validity.validFrom !== null || validity.precision === "unknown")) throw new Error("CHANGE_TIME_REQUIRED");
9767
+ const received2 = JSON.stringify({ validFrom: proposal.validity?.validFrom, validTo: proposal.validity?.validTo, precision: proposal.validity?.precision });
9768
+ 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"`);
9769
+ 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}`);
9718
9770
  if (proposal.changeKind === "reinforce" && (canonicalJson(proposal.value) !== canonicalJson(targets[0].value) || proposal.claimKind !== targets[0].claimKind)) throw new Error("REINFORCE_VALUE_MISMATCH");
9719
9771
  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");
9720
9772
  const timestamp = batch?.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
@@ -9730,8 +9782,8 @@ var init_facts = __esm({
9730
9782
  let state2 = proposal.changeKind === "correction" || proposal.changeKind === "retract" ? "retracted" : "disputed";
9731
9783
  if (proposal.changeKind === "state_change" || proposal.changeKind === "close") {
9732
9784
  const end = proposal.changeKind === "close" ? validity.validTo : validity.validFrom;
9733
- if (target.validFrom !== null && target.validFrom >= end) throw new Error("CHANGE_BEFORE_TARGET_START: use correction");
9734
- if (target.validTo !== null && target.validTo <= end) throw new Error("CHANGE_AFTER_TARGET_END");
9785
+ 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`);
9786
+ 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`);
9735
9787
  state2 = target.state;
9736
9788
  nextValidity = { ...target, validTo: end };
9737
9789
  }
@@ -9747,7 +9799,7 @@ var init_facts = __esm({
9747
9799
  }
9748
9800
  if (!["retract", "close"].includes(proposal.changeKind)) {
9749
9801
  let state2 = proposal.claimKind === "inference" ? "candidate" : proposal.changeKind === "dispute" ? "disputed" : "supported";
9750
- if (state2 === "supported" && !proposal.evidence.some((evidence) => evidence.relation === "supports")) throw new Error("SUPPORTING_EVIDENCE_REQUIRED");
9802
+ if (state2 === "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");
9751
9803
  const current2 = this.current(id2, slot.slotId);
9752
9804
  if (predicates[proposal.predicate].cardinality === "single" && state2 === "supported" && current2.some((fact) => ["supported", "disputed"].includes(fact.state) && overlaps(fact, validity))) throw new Error("FACT_INTERVAL_CONFLICT: explicit correction/change/dispute required");
9753
9805
  if (state2 === "supported" && validity.validFrom === null && !(proposal.predicate === "relation.open" && proposal.value.observedAsCurrentAt)) state2 = "candidate";
@@ -9779,7 +9831,8 @@ var init_facts = __esm({
9779
9831
  slotId: slot.slotId,
9780
9832
  slotRevision: slot.revision + Number(changed),
9781
9833
  assertionIds: changedIds,
9782
- outcome: !changed ? "no_change" : after.some((fact) => ["candidate", "disputed"].includes(fact.state) && (!isRelationship(proposal.predicate) || changedIds.includes(fact.assertionId))) ? "needs_review" : "applied"
9834
+ outcome: !changed ? "no_change" : after.some((fact) => ["candidate", "disputed"].includes(fact.state) && (!isRelationship(proposal.predicate) || changedIds.includes(fact.assertionId))) ? "needs_review" : "applied",
9835
+ ...located.aligned.length ? { evidenceAligned: located.aligned } : {}
9783
9836
  };
9784
9837
  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(id2, requestKey, requestHash, committedRevision, canonicalJson(result), canonicalJson(proposal), canonicalJson(before), canonicalJson(after), timestamp);
9785
9838
  if (changed) {
@@ -9818,21 +9871,31 @@ var init_facts = __esm({
9818
9871
  });
9819
9872
  }
9820
9873
  validate(scope, proposal) {
9821
- if (!Object.hasOwn(predicates, proposal.predicate)) throw new Error("UNKNOWN_PREDICATE");
9822
- 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");
9823
- if (proposal.claimKind === "inference" && (proposal.changeKind !== "assert" || proposal.targetAssertionIds?.length)) throw new Error("INFERENCE_CANNOT_REVISE_SUPPORTED_FACT");
9874
+ 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`);
9875
+ const invalid = [
9876
+ !CHANGE_KINDS.includes(proposal.changeKind) && "changeKind",
9877
+ !CLAIM_KINDS.includes(proposal.claimKind) && "claimKind",
9878
+ !proposal.contextKey && "contextKey",
9879
+ !proposal.reason && "reason",
9880
+ (!Array.isArray(proposal.evidence) || !proposal.evidence.length) && "evidence"
9881
+ ].filter(Boolean);
9882
+ 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`);
9883
+ 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");
9824
9884
  const subject = this.entities.get(scope, proposal.subjectId);
9825
- if (!subject || !matchesEntityKind(subject.kind, predicates[proposal.predicate].subjectKind)) throw new Error("ENTITY_SCOPE_MISMATCH");
9885
+ const subjectKind = predicates[proposal.predicate].subjectKind;
9886
+ 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}`);
9826
9887
  if (proposal.predicate === "relation.family" && !familyRoles.includes(proposal.contextKey)) throw new Error("INVALID_FAMILY_ROLE");
9827
9888
  if (proposal.predicate === "relation.colleague" && (proposal.contextKey !== normalizeOrganization(proposal.contextKey) || proposal.contextKey.length > 200)) throw new Error("INVALID_ORGANIZATION_CONTEXT");
9828
9889
  if (proposal.changeKind === "close") {
9829
- if (!isRelationship(proposal.predicate) || proposal.value !== void 0) throw new Error("INVALID_RELATION_CLOSE");
9830
- if (!proposal.validity) throw new Error("FACT_VALIDITY_REQUIRED");
9890
+ 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`);
9891
+ 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");
9892
+ if (!proposal.validity) throw new Error(`FACT_VALIDITY_REQUIRED: proposal.validity \u5FC5\u586B \u2014 close \u7528 ${CLOSE_VALIDITY}`);
9831
9893
  normalizeValidity(proposal.validity);
9832
9894
  }
9833
9895
  if (!["retract", "close"].includes(proposal.changeKind)) {
9896
+ 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`);
9834
9897
  validatePredicateValue(proposal.predicate, proposal.value);
9835
- if (!proposal.validity) throw new Error("FACT_VALIDITY_REQUIRED");
9898
+ 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"}');
9836
9899
  normalizeValidity(proposal.validity);
9837
9900
  const objectKind = predicates[proposal.predicate].objectKind;
9838
9901
  if (objectKind && !matchesEntityKind(this.entities.get(scope, proposal.value.entityId)?.kind, objectKind)) throw new Error("OBJECT_SCOPE_MISMATCH");
@@ -9847,7 +9910,7 @@ var init_facts = __esm({
9847
9910
  const targets = (proposal.targetAssertionIds ?? []).map((assertionId) => this.db.prepare(`SELECT a.claim_kind,a.value_json,s.subject_id
9848
9911
  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));
9849
9912
  const perspective = value2?.relationshipId ? this.entities.get(scope, value2.perspectiveEntityId) : subject;
9850
- if (proposal.predicate !== "relation.open" || perspective?.kind !== "agent" || !["close", "retract"].includes(proposal.changeKind) && value2?.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");
9913
+ if (proposal.predicate !== "relation.open" || perspective?.kind !== "agent" || !["close", "retract"].includes(proposal.changeKind) && value2?.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");
9851
9914
  }
9852
9915
  if (proposal.predicate === "activity.schedule" && proposal.changeKind !== "retract") {
9853
9916
  const schedule = proposal.value;
@@ -9855,26 +9918,53 @@ var init_facts = __esm({
9855
9918
  if (proposal.contextKey !== "baseline" && !exception) throw new Error("INVALID_SCHEDULE_CONTEXT");
9856
9919
  if ((exception || proposal.changeKind === "exception") && (!exception || schedule.frequency !== "once")) throw new Error("OCCURRENCE_EXCEPTION_REQUIRED");
9857
9920
  }
9858
- for (const evidence of proposal.evidence) {
9921
+ for (const [index, evidence] of proposal.evidence.entries()) {
9922
+ const path37 = `evidence[${index}]`;
9923
+ if (!evidence || typeof evidence !== "object") throw new Error(`INVALID_EVIDENCE_SPAN: ${path37} \u2014 \u6BCF\u6761\u8BC1\u636E\u987B\u662F\u5BF9\u8C61 {sourceId, quote, relation}`);
9859
9924
  const source = this.db.prepare(`SELECT text,role,origin_class,interpretation_status FROM memory_sources s WHERE scope_id=? AND source_id=?
9860
9925
  AND NOT EXISTS (SELECT 1 FROM memory_sources newer WHERE newer.scope_id=s.scope_id
9861
- AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)`).get(scopeId(scope), evidence.sourceId);
9862
- 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");
9926
+ AND newer.origin_key=s.origin_key AND newer.source_version>s.source_version)`).get(scopeId(scope), evidence.sourceId ?? null);
9927
+ if (!source || source.interpretation_status === "deleted") throw new Error(`INVALID_EVIDENCE_SPAN: ${path37}.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`);
9928
+ if (typeof evidence.quote !== "string" || !evidence.quote) throw new Error(`INVALID_EVIDENCE_SPAN: ${path37}.quote \u2014 quote \u5FC5\u586B\uFF0C\u9010\u5B57\u51FA\u81EA\u6765\u6E90\u539F\u6587`);
9929
+ 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) {
9930
+ const count = occurrences(source.text, evidence.quote);
9931
+ throw new Error(count === 0 ? `INVALID_EVIDENCE_SPAN: ${path37}.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: ${path37} \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`);
9932
+ }
9933
+ if (!["supports", "refutes"].includes(evidence.relation)) throw new Error(`INVALID_EVIDENCE_SPAN: ${path37}.relation \u2014 \u53EA\u80FD\u662F supports\uFF08\u652F\u6301\uFF09\u6216 refutes\uFF08\u53CD\u9A73\uFF09`);
9863
9934
  const relationValue = proposal.value;
9864
9935
  if (proposal.predicate === "relation.open" && relationValue?.attribution === "reported" && (proposal.claimKind !== "reported_statement" || !hasReportedAttribution(source.text, relationValue, this.entities.sourceMentions(scope, evidence.sourceId)))) {
9865
- throw new Error("EVIDENCE_REPORTED_ATTRIBUTION_UNGROUNDED");
9936
+ 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");
9866
9937
  }
9938
+ const roleMismatch = () => new Error(`EVIDENCE_ROLE_MISMATCH: ${path37} \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`);
9867
9939
  if (proposal.claimKind !== "inference") {
9868
- if (proposal.claimKind === "user_statement" && (source.role !== "user" || !["host_user", "client_reported_user"].includes(source.origin_class))) throw new Error("EVIDENCE_ROLE_MISMATCH");
9869
- if (proposal.claimKind === "tool_observation" && (source.role !== "tool" || source.origin_class !== "tool_observation")) throw new Error("EVIDENCE_ROLE_MISMATCH");
9940
+ if (proposal.claimKind === "user_statement" && (source.role !== "user" || !["host_user", "client_reported_user"].includes(source.origin_class))) throw roleMismatch();
9941
+ if (proposal.claimKind === "tool_observation" && (source.role !== "tool" || source.origin_class !== "tool_observation")) throw roleMismatch();
9870
9942
  if (proposal.claimKind === "reported_statement" && (source.role !== "user" || !["third_party_report", "legacy_import"].includes(source.origin_class))) {
9871
9943
  const value2 = proposal.value;
9872
9944
  const attributed = proposal.predicate === "relation.open" && value2?.attribution === "reported" && ["user", "assistant"].includes(source.role) && ["host_user", "client_reported_user", "assistant"].includes(source.origin_class) && hasReportedAttribution(source.text, value2, this.entities.sourceMentions(scope, evidence.sourceId));
9873
- if (!attributed) throw new Error("EVIDENCE_ROLE_MISMATCH");
9945
+ if (!attributed) throw roleMismatch();
9874
9946
  }
9875
- 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");
9876
- }
9877
- }
9947
+ 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();
9948
+ }
9949
+ }
9950
+ }
9951
+ /** 1124:UTF-16 下标不是人能数准的——引文在原文中只出现一次时,start/end 可省略或写错,由引擎对齐;没有或重复的留给 validate() 说明。 */
9952
+ locateEvidence(scope, proposal) {
9953
+ const aligned = [];
9954
+ if (!Array.isArray(proposal.evidence)) return { proposal, aligned };
9955
+ const evidence = proposal.evidence.map((ref, index) => {
9956
+ const text2 = this.db.prepare("SELECT text FROM memory_sources WHERE scope_id=? AND source_id=?").get(scope, ref?.sourceId ?? null)?.text;
9957
+ if (typeof text2 !== "string" || typeof ref?.quote !== "string" || !ref.quote || occurrences(text2, ref.quote) !== 1) return ref;
9958
+ const start = text2.indexOf(ref.quote);
9959
+ if (Number.isSafeInteger(ref.start) && ref.start === start && ref.end === start + ref.quote.length) return ref;
9960
+ aligned.push({
9961
+ index,
9962
+ given: [Number.isSafeInteger(ref.start) ? ref.start : null, Number.isSafeInteger(ref.end) ? ref.end : null],
9963
+ located: [start, start + ref.quote.length]
9964
+ });
9965
+ return { ...ref, start, end: start + ref.quote.length };
9966
+ });
9967
+ return { proposal: { ...proposal, evidence }, aligned };
9878
9968
  }
9879
9969
  current(scope, slotId) {
9880
9970
  return this.versions(scope, slotId);
@@ -10123,7 +10213,7 @@ function summary(input) {
10123
10213
  try {
10124
10214
  const p = JSON.parse(input);
10125
10215
  if (!p || typeof p !== "object" || Array.isArray(p)) return input;
10126
- const small = Object.fromEntries(Object.entries(p).filter(([key2, value2]) => routing.has(key2) || Buffer.byteLength(JSON.stringify(value2)) <= 1024));
10216
+ const small = Object.fromEntries(Object.entries(p).filter(([key3, value2]) => routing.has(key3) || Buffer.byteLength(JSON.stringify(value2)) <= 1024));
10127
10217
  if (!Object.hasOwn(small, "basis") && p.basis?.scope) small.basis = { scope: p.basis.scope };
10128
10218
  return JSON.stringify(small);
10129
10219
  } catch {
@@ -11676,10 +11766,10 @@ ${e.outcome}
11676
11766
  ];
11677
11767
  if (revalidationKinds.length === 0) return 0;
11678
11768
  for (const scope of this.sources.scopes()) {
11679
- const received = this.sources.interpretationProgress(scope).received;
11769
+ const received2 = this.sources.interpretationProgress(scope).received;
11680
11770
  for (const artifact of this.dependencies.dirty(scope)) {
11681
11771
  if (!revalidationKinds.includes(artifact.kind)) continue;
11682
- if (received > 0 && !(artifact.updatedAt !== null && Date.now() - artifact.updatedAt >= STALE_ARTIFACT_FORCE_MS)) continue;
11772
+ if (received2 > 0 && !(artifact.updatedAt !== null && Date.now() - artifact.updatedAt >= STALE_ARTIFACT_FORCE_MS)) continue;
11683
11773
  const previous = this.db.prepare("SELECT kind,payload FROM ome_jobs WHERE id=?").all(artifactGenerationJobId(this.db, scope, artifact.kind, artifact.id, artifact.version));
11684
11774
  for (const row of previous) {
11685
11775
  const payload = JSON.parse(row.payload);
@@ -11985,6 +12075,28 @@ var init_timing = __esm({
11985
12075
  }
11986
12076
  });
11987
12077
 
12078
+ // src/mem7/core/lance-cache.ts
12079
+ function memoryLanceSession(lance) {
12080
+ if (typeof lance.Session !== "function") return void 0;
12081
+ let session = sessions.get(lance);
12082
+ if (!session) {
12083
+ session = new lance.Session(BigInt(LANCE_INDEX_CACHE_BYTES), BigInt(LANCE_METADATA_CACHE_BYTES));
12084
+ sessions.set(lance, session);
12085
+ }
12086
+ return session;
12087
+ }
12088
+ var LANCE_INDEX_CACHE_BYTES, LANCE_METADATA_CACHE_BYTES, key2, globals, sessions;
12089
+ var init_lance_cache = __esm({
12090
+ "src/mem7/core/lance-cache.ts"() {
12091
+ "use strict";
12092
+ LANCE_INDEX_CACHE_BYTES = 256 * 1024 * 1024;
12093
+ LANCE_METADATA_CACHE_BYTES = 64 * 1024 * 1024;
12094
+ key2 = Symbol.for("engine7.mem7.lanceCacheSessions");
12095
+ globals = globalThis;
12096
+ sessions = globals[key2] ??= /* @__PURE__ */ new WeakMap();
12097
+ }
12098
+ });
12099
+
11988
12100
  // src/mem7/core/vector-store.ts
11989
12101
  import { mkdirSync as mkdirSync9, existsSync as existsSync7 } from "node:fs";
11990
12102
  import { DatabaseSync as DatabaseSync10 } from "node:sqlite";
@@ -12134,6 +12246,7 @@ var init_vector_store = __esm({
12134
12246
  init_read_guard();
12135
12247
  init_timing();
12136
12248
  init_runtime_authority();
12249
+ init_lance_cache();
12137
12250
  isIntelMac = process.platform === "darwin" && process.arch === "x64";
12138
12251
  lancePromise = null;
12139
12252
  mem7VectorWarning = null;
@@ -12220,7 +12333,7 @@ var init_vector_store = __esm({
12220
12333
  /** Reuse expensive dependency walks, but bind each verdict to SQL, time and the actual indexed body. */
12221
12334
  cachedRowVisible(ledger, kind, row, dependencies2) {
12222
12335
  if (!dependencies2) return vectorRowVisible(ledger, kind, row);
12223
- const key2 = kind + ":" + String(row.id);
12336
+ const key3 = kind + ":" + String(row.id);
12224
12337
  let signature2;
12225
12338
  try {
12226
12339
  signature2 = JSON.stringify([
@@ -12244,11 +12357,11 @@ var init_vector_store = __esm({
12244
12357
  this.visibleCacheVersion = version;
12245
12358
  this.visibleCache.clear();
12246
12359
  }
12247
- const cached = this.visibleCache.get(key2);
12360
+ const cached = this.visibleCache.get(key3);
12248
12361
  if (cached?.signature === signature2) return cached.verdict;
12249
12362
  const verdict = vectorRowVisible(ledger, kind, row, dependencies2);
12250
12363
  if (dependencies2.cacheRevision() !== version) return false;
12251
- this.visibleCache.set(key2, { signature: signature2, verdict });
12364
+ this.visibleCache.set(key3, { signature: signature2, verdict });
12252
12365
  return verdict;
12253
12366
  }
12254
12367
  visibleCache = /* @__PURE__ */ new Map();
@@ -12269,7 +12382,8 @@ var init_vector_store = __esm({
12269
12382
  assertRuntimeAuthority(this.stateDir, "WRITE");
12270
12383
  mkdirSync9(this.dir, { recursive: true });
12271
12384
  }
12272
- this.db = await lance.connect(this.dir);
12385
+ const session = memoryLanceSession(lance);
12386
+ this.db = await lance.connect(this.dir, session ? { session } : void 0);
12273
12387
  }
12274
12388
  return this.db;
12275
12389
  }
@@ -12746,11 +12860,11 @@ var init_vector_store = __esm({
12746
12860
  const rrf = /* @__PURE__ */ new Map();
12747
12861
  const add = (list) => {
12748
12862
  list.forEach((h, i) => {
12749
- const key2 = h.text.replace(/\s+/g, "");
12863
+ const key3 = h.text.replace(/\s+/g, "");
12750
12864
  const contrib = 1 / (RRF_K + i + 1);
12751
- const cur = rrf.get(key2);
12865
+ const cur = rrf.get(key3);
12752
12866
  if (cur) cur.score += contrib;
12753
- else rrf.set(key2, { hit: h, score: contrib });
12867
+ else rrf.set(key3, { hit: h, score: contrib });
12754
12868
  });
12755
12869
  };
12756
12870
  add(dense);
@@ -13712,13 +13826,13 @@ ${items.join("\n")}` };
13712
13826
  ].join("\n");
13713
13827
  const history = ctx.toolResultHistory;
13714
13828
  if (history) {
13715
- const key2 = readResultKey({ id: "", type: "function", function: { name: "read", arguments: JSON.stringify(args) } }, result);
13829
+ const key3 = readResultKey({ id: "", type: "function", function: { name: "read", arguments: JSON.stringify(args) } }, result);
13716
13830
  const calls = readCalls(history);
13717
- for (let i = history.length - 1; key2 && i >= 0; i--) {
13831
+ for (let i = history.length - 1; key3 && i >= 0; i--) {
13718
13832
  const message = history[i];
13719
13833
  if (!("role" in message) || message.role !== "tool" || message.is_error || typeof message.content !== "string") continue;
13720
13834
  const call = calls.get(message.tool_call_id ?? "");
13721
- if (call && readResultKey(call, message.content) === key2) return { content: repeatedReadNotice(call.id) };
13835
+ if (call && readResultKey(call, message.content) === key3) return { content: repeatedReadNotice(call.id) };
13722
13836
  }
13723
13837
  }
13724
13838
  return { content: loopWarning ? `${loopWarning}
@@ -13751,8 +13865,8 @@ var init_writes = __esm({
13751
13865
  var write_exports = {};
13752
13866
  import * as fs5 from "node:fs";
13753
13867
  import * as path6 from "node:path";
13754
- function isBlockedPath(filePath) {
13755
- return BLOCKED_PATTERNS.some((p) => p.test(filePath));
13868
+ function isBlockedPath(filePath, memoryToolRoot) {
13869
+ return !memoryToolRoot && /\/root\//i.test(filePath) || BLOCKED_PATTERNS.some((p) => p.test(filePath));
13756
13870
  }
13757
13871
  function atomicWrite(filePath, content) {
13758
13872
  const tmpPath = filePath + ".tmp." + Date.now() + ".write";
@@ -13819,7 +13933,6 @@ var init_write = __esm({
13819
13933
  /\.env$/i,
13820
13934
  /\.git\//i,
13821
13935
  /\/etc\//i,
13822
- /\/root\//i,
13823
13936
  /passwd/i,
13824
13937
  /shadow/i,
13825
13938
  /\.pem$/i,
@@ -13851,7 +13964,7 @@ Usage:
13851
13964
  if (filePath.startsWith("\\\\") || filePath.startsWith("//")) {
13852
13965
  return { content: `UNC \u8DEF\u5F84\u4E0D\u652F\u6301: ${displayFilePath(filePath, ctx)}`, isError: true };
13853
13966
  }
13854
- if (isBlockedPath(filePath)) {
13967
+ if (isBlockedPath(filePath, ctx.memoryToolRoot)) {
13855
13968
  return {
13856
13969
  content: `\u5B89\u5168\u9650\u5236\uFF1A\u4E0D\u5141\u8BB8\u5199\u5165\u654F\u611F\u8DEF\u5F84\uFF08.ssh/.gnupg/.env/.git/\u7CFB\u7EDF\u76EE\u5F55\u7B49\uFF09: ${displayFilePath(filePath, ctx)}`,
13857
13970
  isError: true
@@ -14986,7 +15099,7 @@ import { promisify as promisify3 } from "node:util";
14986
15099
  async function listOpenCcSessions(workDir) {
14987
15100
  const configDir = process.env.CLAUDE_CONFIG_DIR || path12.join(os3.homedir(), ".claude");
14988
15101
  const dir = path12.join(configDir, "sessions");
14989
- const sessions = [];
15102
+ const sessions2 = [];
14990
15103
  let files = [];
14991
15104
  let warning;
14992
15105
  try {
@@ -15000,7 +15113,7 @@ async function listOpenCcSessions(workDir) {
15000
15113
  if (!Number.isInteger(info.pid) || info.pid < 1 || String(info.pid) !== file2.slice(0, -5) || typeof info.sessionId !== "string" || !uuid.test(info.sessionId) || typeof info.cwd !== "string" || !path12.isAbsolute(info.cwd) || info.kind !== "interactive" || !alive2(info.pid)) continue;
15001
15114
  const cwd = canonical4(info.cwd);
15002
15115
  if (workDir && canonical4(workDir) !== cwd) continue;
15003
- sessions.push({ sessionId: info.sessionId, workDir: cwd, pid: info.pid, connection: "unbridged" });
15116
+ sessions2.push({ sessionId: info.sessionId, workDir: cwd, pid: info.pid, connection: "unbridged" });
15004
15117
  } catch {
15005
15118
  }
15006
15119
  }
@@ -15009,10 +15122,10 @@ async function listOpenCcSessions(workDir) {
15009
15122
  desktops = await findDesktopTargets(workDir);
15010
15123
  } catch {
15011
15124
  warning = [warning, "\u684C\u9762\u6865\u67E5\u8BE2\u5931\u8D25\uFF0C\u63A5\u5165\u72B6\u6001\u672A\u77E5\uFF1B\u539F\u751F\u4F1A\u8BDD\u4ECD\u5217\u51FA\u3002"].filter(Boolean).join("\n");
15012
- for (const session of sessions) session.connection = "unknown";
15125
+ for (const session of sessions2) session.connection = "unknown";
15013
15126
  }
15014
15127
  for (const desktop of desktops) {
15015
- const matches = sessions.filter((s) => s.sessionId === desktop.sessionId && s.workDir === canonical4(desktop.workDir));
15128
+ const matches = sessions2.filter((s) => s.sessionId === desktop.sessionId && s.workDir === canonical4(desktop.workDir));
15016
15129
  const status = {
15017
15130
  connection: desktop.ready ? "ready" : "starting",
15018
15131
  busy: desktop.busy,
@@ -15020,30 +15133,30 @@ async function listOpenCcSessions(workDir) {
15020
15133
  };
15021
15134
  if (matches.length === 1) Object.assign(matches[0], status);
15022
15135
  else if (matches.length > 1) for (const match of matches) match.connection = "unknown";
15023
- else sessions.push({ sessionId: desktop.sessionId, workDir: canonical4(desktop.workDir), pid: desktop.pid, ...status });
15136
+ else sessions2.push({ sessionId: desktop.sessionId, workDir: canonical4(desktop.workDir), pid: desktop.pid, ...status });
15024
15137
  }
15025
- if (sessions.length && process.platform !== "win32") {
15138
+ if (sessions2.length && process.platform !== "win32") {
15026
15139
  try {
15027
15140
  const { stdout } = await execFileAsync(
15028
15141
  "ps",
15029
- ["-p", [...new Set(sessions.map((s) => s.pid))].join(","), "-o", "pid=,tty="],
15142
+ ["-p", [...new Set(sessions2.map((s) => s.pid))].join(","), "-o", "pid=,tty="],
15030
15143
  { timeout: 2e3, maxBuffer: 128 * 1024 }
15031
15144
  );
15032
15145
  const terminals = new Map(stdout.trim().split("\n").map((line) => {
15033
15146
  const [pid, tty] = line.trim().split(/\s+/);
15034
15147
  return [Number(pid), tty];
15035
15148
  }));
15036
- for (const session of sessions) session.tty = terminals.get(session.pid);
15149
+ for (const session of sessions2) session.tty = terminals.get(session.pid);
15037
15150
  } catch {
15038
15151
  }
15039
15152
  }
15040
- for (const session of sessions) {
15153
+ for (const session of sessions2) {
15041
15154
  if (!uuid.test(session.sessionId)) continue;
15042
15155
  const file2 = path12.join(configDir, "projects", mungeProjectKey(session.workDir), `${session.sessionId}.jsonl`);
15043
15156
  Object.assign(session, await readSessionActivity(file2));
15044
15157
  }
15045
- sessions.sort((a, b) => a.workDir.localeCompare(b.workDir) || a.sessionId.localeCompare(b.sessionId) || a.pid - b.pid);
15046
- return { sessions, warning };
15158
+ sessions2.sort((a, b) => a.workDir.localeCompare(b.workDir) || a.sessionId.localeCompare(b.sessionId) || a.pid - b.pid);
15159
+ return { sessions: sessions2, warning };
15047
15160
  }
15048
15161
  var execFileAsync, uuid, canonical4, alive2;
15049
15162
  var init_open_sessions = __esm({
@@ -15681,10 +15794,6 @@ var init_process_card = __esm({
15681
15794
  });
15682
15795
  return this.creation;
15683
15796
  }
15684
- /** Mode decisions can start native progress without awaiting any channel I/O. */
15685
- start() {
15686
- if (!this.ended && !this.started && (this.nativeCapable() || this.legacyCapable() || this.progressCapable())) this.beginInBackground();
15687
- }
15688
15797
  progressCapable() {
15689
15798
  return !!this.adapter.sendProgress && !!this.adapter.updateProgress && !!this.adapter.removeProgress;
15690
15799
  }
@@ -15825,8 +15934,7 @@ var init_process_card = __esm({
15825
15934
  }
15826
15935
  /** stream_event content_block_delta(thinking_delta):实时喂思考内容 */
15827
15936
  onThinkingDelta(chunk) {
15828
- if (!chunk || this.ended || this.disposed) return;
15829
- this.ensureStarted();
15937
+ if (!chunk || this.ended || this.disposed || !this.started) return;
15830
15938
  const lt = this.state.liveThink ??= { start: Date.now(), text: "" };
15831
15939
  lt.text += chunk;
15832
15940
  if (lt.text.length > 800) lt.text = lt.text.slice(-600);
@@ -15844,8 +15952,7 @@ var init_process_card = __esm({
15844
15952
  }
15845
15953
  /** assistant thinking 完整块(无增量流时的兜底;增量路径下与 Thought 行去重) */
15846
15954
  onThinking(text2) {
15847
- if (this.ended || this.disposed) return;
15848
- this.ensureStarted();
15955
+ if (this.ended || this.disposed || !this.started) return;
15849
15956
  if (this.state.liveThink) return;
15850
15957
  const last = this.state.rows[this.state.rows.length - 1];
15851
15958
  if (last?.kind === "think") return;
@@ -15982,7 +16089,7 @@ var init_process_card = __esm({
15982
16089
  return;
15983
16090
  }
15984
16091
  if (this.patchTimer) return;
15985
- const min = this.channelV === "cardkit" || this.channelV === "progress" ? CARDKIT_UPDATE_INTERVAL_MS : PATCH_MIN_INTERVAL_MS;
16092
+ const min = this.channelV === "cardkit" || this.channelV === "progress" ? this.adapter.progressThrottleMs ?? CARDKIT_UPDATE_INTERVAL_MS : PATCH_MIN_INTERVAL_MS;
15986
16093
  const wait = Math.max(0, min - (Date.now() - this.lastPatchAt));
15987
16094
  this.patchTimer = setTimeout(() => {
15988
16095
  this.patchTimer = null;
@@ -15997,10 +16104,6 @@ var init_process_card = __esm({
15997
16104
  await this.creation?.catch(() => {
15998
16105
  });
15999
16106
  if (this.disposed || this.ended && !final) return;
16000
- 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)) {
16001
- await this.removeCard().catch((error) => console.warn("[process-card] \u7A7A\u56DE\u5408\u6E05\u7406\u5931\u8D25:", error instanceof Error ? error.message : String(error)));
16002
- return;
16003
- }
16004
16107
  const pushed = await this.doPatch(final);
16005
16108
  if (final && !pushed && !this.disposed && this.options.sendSummary && !this.summarySent) {
16006
16109
  this.summarySent = true;
@@ -16024,8 +16127,8 @@ var init_process_card = __esm({
16024
16127
  }
16025
16128
  async doPatch(final = false) {
16026
16129
  if (this.degraded || !this.messageId && this.channelV !== "cardkit") return false;
16027
- const key2 = this.pushKey();
16028
- if (key2 === this.lastPushKey) return true;
16130
+ const key3 = this.pushKey();
16131
+ if (key3 === this.lastPushKey) return true;
16029
16132
  this.lastPatchAt = Date.now();
16030
16133
  const card = this.channelV === "progress" ? null : this.channelV === "patch-v1" ? buildProcessCard(this.state) : buildProcessCardV2(this.state) ?? (this.options.allowLegacyCard !== false ? buildProcessCard(this.state) : null);
16031
16134
  if (this.channelV !== "preview" && this.channelV !== "progress" && !card) return false;
@@ -16041,7 +16144,7 @@ var init_process_card = __esm({
16041
16144
  await this.adapter.patchCard(this.messageId, card);
16042
16145
  } else return false;
16043
16146
  this.patchFailures = 0;
16044
- this.lastPushKey = key2;
16147
+ this.lastPushKey = key3;
16045
16148
  return true;
16046
16149
  } catch (err) {
16047
16150
  if (this.channelV === "cardkit" && isPermissionDenied(err)) {
@@ -16051,7 +16154,7 @@ var init_process_card = __esm({
16051
16154
  await this.removeCard();
16052
16155
  if (this.disposed) return false;
16053
16156
  await this.createLegacyCard();
16054
- this.lastPushKey = key2;
16157
+ this.lastPushKey = key3;
16055
16158
  this.patchFailures = 0;
16056
16159
  if (!this.ended) this.startHeartbeat();
16057
16160
  return true;
@@ -16186,23 +16289,23 @@ var init_session_map = __esm({
16186
16289
  this.map = {};
16187
16290
  }
16188
16291
  }
16189
- get(key2) {
16190
- return this.map[key2];
16292
+ get(key3) {
16293
+ return this.map[key3];
16191
16294
  }
16192
- set(key2, sessionId, workDir) {
16193
- this.map[key2] = { sessionId, workDir, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
16295
+ set(key3, sessionId, workDir) {
16296
+ this.map[key3] = { sessionId, workDir, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
16194
16297
  this.save();
16195
16298
  }
16196
16299
  /** 清掉 binding 的会话绑定(/cc-new)。返回是否真的清了。 */
16197
- clear(key2) {
16198
- if (!(key2 in this.map)) return false;
16199
- delete this.map[key2];
16300
+ clear(key3) {
16301
+ if (!(key3 in this.map)) return false;
16302
+ delete this.map[key3];
16200
16303
  this.save();
16201
16304
  return true;
16202
16305
  }
16203
16306
  /** /cc-switch 直写目标会话 */
16204
- switchTo(key2, sessionId, workDir) {
16205
- this.set(key2, sessionId, workDir);
16307
+ switchTo(key3, sessionId, workDir) {
16308
+ this.set(key3, sessionId, workDir);
16206
16309
  }
16207
16310
  save() {
16208
16311
  try {
@@ -16321,9 +16424,9 @@ function sharedNodeModules() {
16321
16424
  function pkgDir(name) {
16322
16425
  return path14.join(sharedNodeModules(), ...name.split("/"));
16323
16426
  }
16324
- function readConfig(key2) {
16427
+ function readConfig(key3) {
16325
16428
  try {
16326
- return liveConfig.get(key2);
16429
+ return liveConfig.get(key3);
16327
16430
  } catch {
16328
16431
  }
16329
16432
  }
@@ -16338,9 +16441,9 @@ function downloadsEnabled() {
16338
16441
  function currentPlatformKey() {
16339
16442
  return `${process.platform}-${process.arch}`;
16340
16443
  }
16341
- function featureSpec(key2) {
16342
- const spec = OPTIONAL_FEATURES[key2];
16343
- if (!spec) throw new Error(`[dep-downloader] optional-deps.json \u91CC\u6CA1\u6709\u952E\uFF1A${key2}`);
16444
+ function featureSpec(key3) {
16445
+ const spec = OPTIONAL_FEATURES[key3];
16446
+ if (!spec) throw new Error(`[dep-downloader] optional-deps.json \u91CC\u6CA1\u6709\u952E\uFF1A${key3}`);
16344
16447
  return spec;
16345
16448
  }
16346
16449
  function markerPath(spec) {
@@ -16353,8 +16456,8 @@ function isPkgInstalled(spec) {
16353
16456
  return false;
16354
16457
  }
16355
16458
  }
16356
- function isOptionalFeatureInstalled(key2) {
16357
- const spec = featureSpec(key2);
16459
+ function isOptionalFeatureInstalled(key3) {
16460
+ const spec = featureSpec(key3);
16358
16461
  if (!isPkgInstalled(spec.main)) return false;
16359
16462
  const plat = spec.platform?.[currentPlatformKey()];
16360
16463
  if (plat && !isPkgInstalled(plat)) return false;
@@ -16458,9 +16561,9 @@ function notInstalledError(spec) {
16458
16561
  err.code = "ERR_MODULE_NOT_FOUND";
16459
16562
  return err;
16460
16563
  }
16461
- async function ensureOptionalFeature(key2, onProgress) {
16462
- const spec = featureSpec(key2);
16463
- if (isOptionalFeatureInstalled(key2)) return pkgDir(spec.main.name);
16564
+ async function ensureOptionalFeature(key3, onProgress) {
16565
+ const spec = featureSpec(key3);
16566
+ if (isOptionalFeatureInstalled(key3)) return pkgDir(spec.main.name);
16464
16567
  if (!downloadsEnabled()) throw notInstalledError(spec);
16465
16568
  const plat = spec.platform?.[currentPlatformKey()];
16466
16569
  const pkgs = [spec.main, ...plat ? [plat] : [], ...spec.extra ?? []];
@@ -16471,17 +16574,17 @@ function requireFromShared(name) {
16471
16574
  const req = createRequire7(path14.join(sharedNodeModules(), ".e7-resolve.js"));
16472
16575
  return req(name);
16473
16576
  }
16474
- async function loadOptionalModule(key2, onProgress) {
16475
- const spec = featureSpec(key2);
16577
+ async function loadOptionalModule(key3, onProgress) {
16578
+ const spec = featureSpec(key3);
16476
16579
  const notFound = (err) => err?.code === "ERR_MODULE_NOT_FOUND" || err?.code === "MODULE_NOT_FOUND";
16477
16580
  try {
16478
16581
  return nodeRequire(spec.main.name);
16479
16582
  } catch (err) {
16480
16583
  if (!notFound(err)) throw err;
16481
16584
  }
16482
- if (!isOptionalFeatureInstalled(key2)) {
16585
+ if (!isOptionalFeatureInstalled(key3)) {
16483
16586
  if (!downloadsEnabled()) throw notInstalledError(spec);
16484
- await ensureOptionalFeature(key2, onProgress);
16587
+ await ensureOptionalFeature(key3, onProgress);
16485
16588
  }
16486
16589
  const dir = pkgDir(spec.main.name);
16487
16590
  try {
@@ -16503,11 +16606,11 @@ var init_dep_downloader = __esm({
16503
16606
  OPTIONAL_FEATURES = (() => {
16504
16607
  const raw = optional_deps_default;
16505
16608
  const out = {};
16506
- for (const [key2, v] of Object.entries(raw)) {
16507
- if (key2 === "//") continue;
16609
+ for (const [key3, v] of Object.entries(raw)) {
16610
+ if (key3 === "//") continue;
16508
16611
  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-")));
16509
- 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`);
16510
- out[key2] = { key: key2, label: v.label ?? key2, main: v.main, platform: v.platform, extra: v.extra };
16612
+ if (bad) throw new Error(`[dep-downloader] optional-deps.json \u6761\u76EE ${key3} \u7F3A name/version/integrity\uFF08integrity \u53D6 npm view <name>@<version> dist.integrity\uFF09`);
16613
+ out[key3] = { key: key3, label: v.label ?? key3, main: v.main, platform: v.platform, extra: v.extra };
16511
16614
  }
16512
16615
  return out;
16513
16616
  })();
@@ -17169,7 +17272,7 @@ ${acc.textSoFar.slice(-FINAL_CHUNK_CHARS)}` : ""));
17169
17272
  const file2 = join28(dir, `${stamp2}-${tail}-${i + 1}${ext}`);
17170
17273
  mkdirSync16(dir, { recursive: true });
17171
17274
  writeFileSync17(file2, bytes);
17172
- const how = a.contentType.startsWith("image/") ? "\u56FE\u7247\u2014\u2014\u7528 Read \u5DE5\u5177\u6253\u5F00\u8FD9\u4E2A\u8DEF\u5F84\u5373\u53EF\u770B\u5230" : `\u6587\u4EF6\uFF08${a.contentType || "\u672A\u77E5\u7C7B\u578B"}\uFF09`;
17275
+ 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`;
17173
17276
  lines.push(`${i + 1}. ${label}\uFF0C${how}\uFF1A${file2}`);
17174
17277
  } catch (err) {
17175
17278
  lines.push(`${i + 1}. ${label} \u843D\u76D8\u5931\u8D25\uFF1A${err?.message || String(err)}`);
@@ -17199,10 +17302,10 @@ ${note}` : note)).catch((err) => session.enqueue(`${inbound.content}
17199
17302
  return this.sessions.get(`${channel}:${chatId}`);
17200
17303
  }
17201
17304
  /** 按 bindingKey(channel:chatId)找 session——卡片停止钮回调用(1119) */
17202
- forChatKey(key2) {
17203
- const idx = key2.indexOf(":");
17305
+ forChatKey(key3) {
17306
+ const idx = key3.indexOf(":");
17204
17307
  if (idx <= 0) return void 0;
17205
- return this.sessions.get(key2);
17308
+ return this.sessions.get(key3);
17206
17309
  }
17207
17310
  /** 全部绑定的工作目录(去重;cc-progress 工具省参推断用) */
17208
17311
  get bindingWorkDirs() {
@@ -17211,8 +17314,8 @@ ${note}` : note)).catch((err) => session.enqueue(`${inbound.content}
17211
17314
  get bindings() {
17212
17315
  return [...this.sessions.values()].map((s) => ({ key: s.key, workDir: s.workDir, sessionId: s.currentSessionId, busy: s.busy }));
17213
17316
  }
17214
- ask(key2, workDir, prompt, source, expectedSessionId, signal) {
17215
- const session = this.sessions.get(key2);
17317
+ ask(key3, workDir, prompt, source, expectedSessionId, signal) {
17318
+ const session = this.sessions.get(key3);
17216
17319
  if (!session) return Promise.reject(requestError("CC binding not found", 404));
17217
17320
  if (session.workDir !== workDir) return Promise.reject(requestError("CC binding workDir changed"));
17218
17321
  return session.ask(prompt, source, expectedSessionId, signal);
@@ -17245,7 +17348,7 @@ function registerCcHub(hub2, stateDir, port) {
17245
17348
  const dir = registryDir2();
17246
17349
  fs13.mkdirSync(dir, { recursive: true, mode: 448 });
17247
17350
  const file2 = path15.join(dir, `${process.pid}.json`);
17248
- const endpoint2 = { pid: process.pid, stateDir, port, bindings: hub2.bindings.map(({ key: key2, workDir }) => ({ key: key2, workDir })) };
17351
+ const endpoint2 = { pid: process.pid, stateDir, port, bindings: hub2.bindings.map(({ key: key3, workDir }) => ({ key: key3, workDir })) };
17249
17352
  const tmp = `${file2}.tmp`;
17250
17353
  fs13.writeFileSync(tmp, JSON.stringify(endpoint2), { mode: 384 });
17251
17354
  fs13.renameSync(tmp, file2);
@@ -17264,7 +17367,7 @@ function live(pid) {
17264
17367
  return error?.code === "EPERM";
17265
17368
  }
17266
17369
  }
17267
- async function findBoundCcTargets(workDir, key2) {
17370
+ async function findBoundCcTargets(workDir, key3) {
17268
17371
  let files;
17269
17372
  try {
17270
17373
  files = fs13.readdirSync(registryDir2());
@@ -17276,7 +17379,7 @@ async function findBoundCcTargets(workDir, key2) {
17276
17379
  try {
17277
17380
  const e = JSON.parse(fs13.readFileSync(path15.join(registryDir2(), file2), "utf8"));
17278
17381
  if (!Number.isInteger(e.pid) || e.pid <= 0 || !Number.isInteger(e.port) || e.port <= 0 || e.port > 65535 || typeof e.stateDir !== "string" || !Array.isArray(e.bindings) || !live(e.pid)) continue;
17279
- if (e.bindings.some((b) => typeof b.key === "string" && typeof b.workDir === "string" && (!key2 || b.key === key2) && (!workDir || canonical5(b.workDir) === canonical5(workDir)))) endpoints.push(e);
17382
+ if (e.bindings.some((b) => typeof b.key === "string" && typeof b.workDir === "string" && (!key3 || b.key === key3) && (!workDir || canonical5(b.workDir) === canonical5(workDir)))) endpoints.push(e);
17280
17383
  } catch {
17281
17384
  }
17282
17385
  }
@@ -17290,7 +17393,7 @@ async function findBoundCcTargets(workDir, key2) {
17290
17393
  if (body.pid !== endpoint2.pid || body.stateDir !== endpoint2.stateDir || !Array.isArray(body.bindings)) {
17291
17394
  throw new Error(`CC hub ${endpoint2.port} identity changed; refusing to use another engine`);
17292
17395
  }
17293
- return body.bindings.filter((b) => typeof b.key === "string" && typeof b.workDir === "string" && (b.sessionId === null || typeof b.sessionId === "string") && (!key2 || b.key === key2) && (!workDir || canonical5(b.workDir) === canonical5(workDir))).map((b) => ({ ...b, endpoint: endpoint2 }));
17396
+ return body.bindings.filter((b) => typeof b.key === "string" && typeof b.workDir === "string" && (b.sessionId === null || typeof b.sessionId === "string") && (!key3 || b.key === key3) && (!workDir || canonical5(b.workDir) === canonical5(workDir))).map((b) => ({ ...b, endpoint: endpoint2 }));
17294
17397
  }));
17295
17398
  return lists.flat();
17296
17399
  }
@@ -17585,8 +17688,8 @@ var init_cc_progress = __esm({
17585
17688
  let workDir = typeof args.workDir === "string" && args.workDir.trim() ? args.workDir.trim() : "";
17586
17689
  if (args.view !== void 0 && !["sessions", "progress"].includes(args.view)) return { content: "view \u9700\u8981 sessions \u6216 progress\u3002", isError: true };
17587
17690
  if (args.view === "sessions" || !args.view && !workDir) {
17588
- const { sessions: sessions2, warning } = await listOpenCcSessions(workDir || void 0);
17589
- const lines2 = sessions2.map((s, i) => {
17691
+ const { sessions: sessions3, warning } = await listOpenCcSessions(workDir || void 0);
17692
+ const lines2 = sessions3.map((s, i) => {
17590
17693
  const status = s.connection === "ready" ? `\u5DF2\u63A5\u5165\uFF0C\u53EF\u6295\u9012${s.busy ? "\uFF08\u5FD9\uFF0C\u6D88\u606F\u6392\u961F\uFF09" : ""}` : s.connection === "starting" ? "\u5DF2\u63A5\u5165\uFF0C\u5C1A\u672A\u5C31\u7EEA" : s.connection === "unknown" ? "\u63A5\u5165\u72B6\u6001\u672A\u77E5" : "\u672A\u63A5\u5165\uFF08\u53EA\u8BFB\u53EF\u89C1\uFF09";
17591
17694
  const activity = s.lastActiveAt === void 0 ? "\u672A\u77E5" : `${new Date(s.lastActiveAt).toISOString()}\uFF08${fmtTime(new Date(s.lastActiveAt).toISOString())}\uFF0C\u65E5\u5FD7\u5199\u5165\uFF09`;
17592
17695
  return `${i + 1}. ${s.sessionId}
@@ -17597,7 +17700,7 @@ var init_cc_progress = __esm({
17597
17700
  \u6700\u540E\u6D3B\u8DC3\uFF1A${activity}`;
17598
17701
  });
17599
17702
  return { content: [
17600
- sessions2.length ? `\u5F53\u524D\u53D1\u73B0 ${sessions2.length} \u4E2A\u6253\u5F00\u7684 CC \u4F1A\u8BDD\uFF1A` : "\u5F53\u524D\u6CA1\u6709\u53D1\u73B0\u5DF2\u767B\u8BB0\u4E14\u8FDB\u7A0B\u5B58\u6D3B\u7684\u4EA4\u4E92 CC \u4F1A\u8BDD\u3002",
17703
+ sessions3.length ? `\u5F53\u524D\u53D1\u73B0 ${sessions3.length} \u4E2A\u6253\u5F00\u7684 CC \u4F1A\u8BDD\uFF1A` : "\u5F53\u524D\u6CA1\u6709\u53D1\u73B0\u5DF2\u767B\u8BB0\u4E14\u8FDB\u7A0B\u5B58\u6D3B\u7684\u4EA4\u4E92 CC \u4F1A\u8BDD\u3002",
17601
17704
  warning,
17602
17705
  ...lines2,
17603
17706
  "\u4F1A\u8BDD\u6E05\u5355\u5305\u542B\u666E\u901A claude \u4E0E\u5DF2\u63A5\u5165\u7684 cc-desktop\uFF1B\u4E0D\u4EE3\u8868\u7A97\u53E3\u662F\u5426\u5728\u5C4F\u5E55\u524D\u53F0\u3002\u6700\u540E\u6D3B\u8DC3\u662F\u65E5\u5FD7\u5199\u5165\u65F6\u95F4\uFF0C\u957F\u671F\u65E0\u5199\u5165\u4E0D\u80FD\u5355\u72EC\u5224\u65AD\u6302\u6B7B\uFF0C\u8FDB\u7A0B\u5B58\u6D3B\u53E6\u5217\u3002\u672A\u63A5\u5165\u4F1A\u8BDD\u53EF\u4EE5\u53D1\u73B0\uFF0C\u4F46\u9700\u9996\u6B21\u7528 cc-desktop \u6062\u590D\u540E\u624D\u80FD\u5411\u539F\u8FDB\u7A0B\u53D1\u6D88\u606F\u3002\u672C\u6B21\u53EA\u8BFB\u67E5\u8BE2\uFF0C\u6CA1\u6709\u53D1\u9001\u6D88\u606F\u6216\u5207\u6362\u7ED1\u5B9A\u3002"
@@ -17615,11 +17718,11 @@ ${dirs.join("\n")}`, isError: true };
17615
17718
  if (!workDir) {
17616
17719
  return { content: "\u9700\u8981 workDir \u53C2\u6570\uFF08CC \u8DD1\u5728\u54EA\u4E2A\u9879\u76EE\u76EE\u5F55\uFF09\uFF0C\u4F8B\u5982 /Users/xxx/work/repo", isError: true };
17617
17720
  }
17618
- const sessions = listProjectSessions(workDir, void 0, 1);
17619
- if (sessions.length === 0) {
17721
+ const sessions2 = listProjectSessions(workDir, void 0, 1);
17722
+ if (sessions2.length === 0) {
17620
17723
  return { content: `${workDir} \u4E0B\u6CA1\u6709\u627E\u5230\u4EFB\u4F55 CC \u4F1A\u8BDD\u8BB0\u5F55\uFF08~/.claude/projects \u91CC\u6CA1\u6709\u8FD9\u4E2A\u76EE\u5F55\u7684\u4F1A\u8BDD\uFF09`, isError: true };
17621
17724
  }
17622
- const latest = sessions[0];
17725
+ const latest = sessions2[0];
17623
17726
  const lines = tailSessionLines(latest.file, 65536);
17624
17727
  const recent = [];
17625
17728
  let lastTs = "";
@@ -17845,8 +17948,8 @@ ${dirs.join("\n")}`, isError: true };
17845
17948
  if (forceNew) {
17846
17949
  store?.clear(mapKey);
17847
17950
  } else if (resumeLatest) {
17848
- const sessions = listProjectSessions(workDir, void 0, 3);
17849
- const candidate = sessions.find((s) => s.messageCount > 0);
17951
+ const sessions2 = listProjectSessions(workDir, void 0, 3);
17952
+ const candidate = sessions2.find((s) => s.messageCount > 0);
17850
17953
  if (!candidate) return { content: `${workDir} \u4E0B\u6CA1\u6709\u53EF\u63A5\u7EED\u7684 CC \u4F1A\u8BDD\uFF08\u53BB\u6389 resumeLatest \u5F00\u65B0\u4F1A\u8BDD\uFF09`, isError: true };
17851
17954
  if (await checkActive(candidate.file, 300)) {
17852
17955
  return { content: `\u8BE5\u9879\u76EE\u6700\u65B0\u4F1A\u8BDD\u6B63\u88AB\u522B\u5904\u9A71\u52A8\uFF08\u25CFlive\uFF1A\u63A7\u5236\u53F0\u6216\u98DE\u4E66 hub\uFF09\u2014\u2014\u7B49\u5B83\u7A7A\u95F2\u518D\u63A5\u624B\uFF0C\u6216\u53BB\u6389 resumeLatest \u5F00\u65B0\u4F1A\u8BDD\u3002`, isError: true };
@@ -17867,8 +17970,8 @@ ${dirs.join("\n")}`, isError: true };
17867
17970
  }
17868
17971
  }
17869
17972
  if (!sessionId) {
17870
- const sessions = listProjectSessions(workDir, void 0, 1);
17871
- const latest = sessions[0];
17973
+ const sessions2 = listProjectSessions(workDir, void 0, 1);
17974
+ const latest = sessions2[0];
17872
17975
  if (latest && await checkActive(latest.file, 300)) {
17873
17976
  return { content: `\u8BE5\u9879\u76EE\u6709\u4F1A\u8BDD\u6B63\u88AB\u522B\u5904\u9A71\u52A8\uFF08\u25CFlive\uFF09\u2014\u2014\u4E3A\u907F\u514D CC \u62FF\u7740\u8FC7\u65F6\u4E0A\u4E0B\u6587\u5E72\u6D3B\uFF0C\u7A0D\u7B49\u5B83\u7A7A\u95F2\uFF0C\u6216\u6307\u5B9A\u5176\u4ED6 workDir\u3002`, isError: true };
17874
17977
  }
@@ -18292,17 +18395,17 @@ function createNotificationStateReader() {
18292
18395
  const databases = /* @__PURE__ */ new Map();
18293
18396
  const checkers = /* @__PURE__ */ new Map();
18294
18397
  const open6 = (path37) => {
18295
- const key2 = resolve23(path37);
18296
- let db2 = databases.get(key2);
18398
+ const key3 = resolve23(path37);
18399
+ let db2 = databases.get(key3);
18297
18400
  if (!db2) {
18298
- db2 = new DatabaseSync16(key2, { readOnly: true });
18401
+ db2 = new DatabaseSync16(key3, { readOnly: true });
18299
18402
  try {
18300
18403
  db2.exec("BEGIN");
18301
18404
  } catch (error) {
18302
18405
  db2.close();
18303
18406
  throw error;
18304
18407
  }
18305
- databases.set(key2, db2);
18408
+ databases.set(key3, db2);
18306
18409
  }
18307
18410
  return db2;
18308
18411
  };
@@ -18460,6 +18563,35 @@ var init_notification_state = __esm({
18460
18563
  }
18461
18564
  });
18462
18565
 
18566
+ // src/travel/chunk-store.ts
18567
+ import { gunzipSync as gunzipSync2, gzip as gzip2 } from "node:zlib";
18568
+ import { promisify as promisify4 } from "node:util";
18569
+ var CHUNK_BYTES2, DATABASE_CHUNK_BYTES, compress2;
18570
+ var init_chunk_store = __esm({
18571
+ "src/travel/chunk-store.ts"() {
18572
+ "use strict";
18573
+ CHUNK_BYTES2 = 4 * 1024 * 1024;
18574
+ DATABASE_CHUNK_BYTES = 64 * 1024;
18575
+ compress2 = promisify4(gzip2);
18576
+ }
18577
+ });
18578
+
18579
+ // src/travel/capture-cache.ts
18580
+ var init_capture_cache = __esm({
18581
+ "src/travel/capture-cache.ts"() {
18582
+ "use strict";
18583
+ init_chunk_store();
18584
+ }
18585
+ });
18586
+
18587
+ // src/travel/apply-transaction.ts
18588
+ var init_apply_transaction = __esm({
18589
+ "src/travel/apply-transaction.ts"() {
18590
+ "use strict";
18591
+ init_capture_cache();
18592
+ }
18593
+ });
18594
+
18463
18595
  // src/mem7/boot-recovery.ts
18464
18596
  import { DatabaseSync as DatabaseSync17 } from "node:sqlite";
18465
18597
  var init_boot_recovery = __esm({
@@ -18467,6 +18599,7 @@ var init_boot_recovery = __esm({
18467
18599
  "use strict";
18468
18600
  init_store();
18469
18601
  init_mem7_replication();
18602
+ init_apply_transaction();
18470
18603
  }
18471
18604
  });
18472
18605
 
@@ -19848,7 +19981,7 @@ var init_steer_content = __esm({
19848
19981
 
19849
19982
  // src/models/provider-errors.ts
19850
19983
  function isQuotaExhaustedError(message) {
19851
- 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);
19984
+ 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);
19852
19985
  }
19853
19986
  var init_provider_errors = __esm({
19854
19987
  "src/models/provider-errors.ts"() {
@@ -20015,8 +20148,8 @@ function withTravelOutputKind(kind, run) {
20015
20148
  }
20016
20149
  function travelEventPermit(context) {
20017
20150
  const permit = context.permit(), original = context.originalPermit;
20018
- for (const key2 of ["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"]) {
20019
- if (permit[key2] !== original[key2]) throw new Error("TRAVEL_GATEWAY_STALE_CONTEXT");
20151
+ for (const key3 of ["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"]) {
20152
+ if (permit[key3] !== original[key3]) throw new Error("TRAVEL_GATEWAY_STALE_CONTEXT");
20020
20153
  }
20021
20154
  if (context.complete) throw new Error("TRAVEL_GATEWAY_EVENT_COMPLETED");
20022
20155
  return permit;
@@ -20195,7 +20328,10 @@ function isCpuModeHook(command2) {
20195
20328
  return (tokens[0] === process.execPath || /^(?:node|python[\d.]*|py)(?:\.exe)?$/i.test(executable2)) && /^emotion(?:_state_machine\.(?:mjs|py)|-hook-gate\.js)$/i.test(script);
20196
20329
  }
20197
20330
  function cpuModeHookOutput(command2, input, workspace) {
20198
- if (!isCpuModeHook(command2) || !["emotion", "work"].includes(input.cpu_router_mode)) return null;
20331
+ return isCpuModeHook(command2) ? cpuModeOutput(input, workspace) : null;
20332
+ }
20333
+ function cpuModeOutput(input, workspace) {
20334
+ if (!["emotion", "work"].includes(input.cpu_router_mode)) return null;
20199
20335
  const text2 = typeof input.prompt === "string" ? input.prompt : "";
20200
20336
  const internal = ["heartbeat", "cron", "system", "inner-voice", "mem7"];
20201
20337
  const marks = ["\u3010", "[\u5B9A\u65F6", "\u5F53\u524D\u65F6\u95F4\uFF1A", "[inner-voice]", "<calendar-notification>", "<nudge-notification>", "<task-notification>", "<system-reminder>"];
@@ -20453,10 +20589,10 @@ async function executeOneHook(hook, hookEvent, hookName, hookInput, toolUseID, s
20453
20589
  hook
20454
20590
  };
20455
20591
  }
20456
- const cpuModeOutput = hookEvent === "UserPromptSubmit" ? cpuModeHookOutput(hook.command, hookInput, ctx.workspace) : null;
20457
- if (cpuModeOutput) {
20458
- const processed = processHookJSONOutput({ json: cpuModeOutput, command: hook.command, hookEvent, durationMs: Date.now() - startMs });
20459
- console.log(`[cpu-router] mode-hook=${hookTimingLabel(hook, 0)} mode=${cpuModeOutput._mode ?? "skip"}`);
20592
+ const cpuModeOutput2 = hookEvent === "UserPromptSubmit" ? cpuModeHookOutput(hook.command, hookInput, ctx.workspace) : null;
20593
+ if (cpuModeOutput2) {
20594
+ const processed = processHookJSONOutput({ json: cpuModeOutput2, command: hook.command, hookEvent, durationMs: Date.now() - startMs });
20595
+ console.log(`[cpu-router] mode-hook=${hookTimingLabel(hook, 0)} mode=${cpuModeOutput2._mode ?? "skip"}`);
20460
20596
  return { ...processed, outcome: "success", hook };
20461
20597
  }
20462
20598
  const jsonInput = JSON.stringify(hookInput);
@@ -20585,10 +20721,10 @@ function matchesPromptHookCondition(hook, input) {
20585
20721
  if (hook.when === void 0) return true;
20586
20722
  const when = hook.when;
20587
20723
  if (!when || typeof when !== "object" || Array.isArray(when) || input.hook_event_name !== "UserPromptSubmit") return false;
20588
- if (Object.keys(when).some((key2) => !["channel", "channelType", "source", "excludeSenderIds"].includes(key2))) return false;
20724
+ if (Object.keys(when).some((key3) => !["channel", "channelType", "source", "excludeSenderIds"].includes(key3))) return false;
20589
20725
  if (!input.prompt.trim()) return false;
20590
- for (const [key2, actual] of [["channel", input.channel], ["channelType", input.channel_type], ["source", input.source]]) {
20591
- if (when[key2] !== void 0 && (typeof when[key2] !== "string" || when[key2] !== actual)) return false;
20726
+ for (const [key3, actual] of [["channel", input.channel], ["channelType", input.channel_type], ["source", input.source]]) {
20727
+ if (when[key3] !== void 0 && (typeof when[key3] !== "string" || when[key3] !== actual)) return false;
20592
20728
  }
20593
20729
  if (when.excludeSenderIds !== void 0) {
20594
20730
  if (!Array.isArray(when.excludeSenderIds) || when.excludeSenderIds.some((id2) => typeof id2 !== "string")) return false;
@@ -20726,6 +20862,7 @@ async function executeStopHooks(ctx, signal, lastAssistantMessage) {
20726
20862
  cwd: ctx.cwd,
20727
20863
  stop_hook_active: false,
20728
20864
  last_assistant_message: lastAssistantMessage,
20865
+ turn_evidence: ctx.stopTurnEvidence,
20729
20866
  channel: ctx.channel,
20730
20867
  // 让 callback hook 能判断来源
20731
20868
  channelTarget: ctx.channelTarget,
@@ -21017,13 +21154,17 @@ var init_on_demand_recall = __esm({
21017
21154
  OnDemandRecall = class {
21018
21155
  used = /* @__PURE__ */ new Set();
21019
21156
  cache = /* @__PURE__ */ new Map();
21157
+ /** Actual tool mutations invalidate this turn's snapshot without polling SQLite. */
21158
+ invalidate() {
21159
+ this.cache.clear();
21160
+ }
21020
21161
  // 1024 翀哥裁决:6 秒墙全撤。它界的是返回大小不是时延来源(检索耗时在 embedding/bm25/rerank),
21021
21162
  // 底层各有各的界(SQL overlay 死线 12s、embedding HTTP 30s、rerank 1500ms 竞速),1+1 配额防循环。
21022
21163
  // 这层墙当天制造了两次 timeout 假阴性 + 额度连坐,没拦住任何真问题。
21023
21164
  constructor(keywordAlreadySearched = false) {
21024
21165
  if (keywordAlreadySearched) this.used.add("keyword");
21025
21166
  }
21026
- async search(binding, args, captureGuard, run, signal) {
21167
+ async search(binding, args, run, signal) {
21027
21168
  const status = (value2, reason) => JSON.stringify({ historySearch: { status: value2, reason } });
21028
21169
  if (signal?.aborted) return status("aborted", "\u672C\u8F6E\u5DF2\u53D6\u6D88\u3002");
21029
21170
  if (args.mode === "agentic") return status("unavailable", "\u60C5\u611F\u8F6E\u8BF7\u7528 keyword \u6216 hybrid \u6709\u754C\u8865\u67E5\u3002");
@@ -21035,17 +21176,12 @@ var init_on_demand_recall = __esm({
21035
21176
  };
21036
21177
  for (const passthrough of ["known_at", "known_at_revision", "valid_at", "entity_ref", "after_receipt", "session_id"])
21037
21178
  if (args[passthrough] !== void 0) bounded[passthrough] = args[passthrough];
21038
- const key2 = JSON.stringify([binding, Object.entries(bounded).sort(([a], [b]) => a.localeCompare(b))]);
21039
- const cached = this.cache.get(key2);
21179
+ const key3 = JSON.stringify([binding, Object.entries(bounded).sort(([a], [b]) => a.localeCompare(b))]);
21180
+ const cached = this.cache.get(key3);
21040
21181
  if (cached) {
21041
- const result2 = await cached.result;
21182
+ const result2 = await cached;
21042
21183
  if (signal?.aborted) return status("aborted", "\u672C\u8F6E\u5DF2\u53D6\u6D88\u3002");
21043
- try {
21044
- cached.assertCurrent();
21045
- return result2;
21046
- } catch {
21047
- 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");
21048
- }
21184
+ return result2;
21049
21185
  }
21050
21186
  const kind = bounded.view === "current" || bounded.mode === "keyword" ? "keyword" : "semantic";
21051
21187
  if (kind === "keyword" && this.used.has("keyword") && !this.used.has("semantic")) {
@@ -21054,7 +21190,6 @@ var init_on_demand_recall = __esm({
21054
21190
  if (this.used.has(kind)) {
21055
21191
  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");
21056
21192
  }
21057
- const assertCurrent = captureGuard();
21058
21193
  this.used.add(kind);
21059
21194
  if (kind === "semantic") this.used.add("keyword");
21060
21195
  const controller = new AbortController();
@@ -21084,7 +21219,7 @@ ${error.stack.split("\n").slice(0, 6).join("\n")}` : ""
21084
21219
  controller.abort();
21085
21220
  }
21086
21221
  })();
21087
- this.cache.set(key2, { result, assertCurrent });
21222
+ this.cache.set(key3, result);
21088
21223
  return result;
21089
21224
  }
21090
21225
  };
@@ -21156,13 +21291,13 @@ async function materializeImageMessages(messages, store, signal, maxBase64Bytes
21156
21291
  continue;
21157
21292
  }
21158
21293
  if (!store) throw new Error("Image asset store is required to materialize image refs");
21159
- const key2 = JSON.stringify([block.image.sha256, block.image.bytes, block.image.mediaType]);
21160
- if (!cache2.has(key2)) cache2.set(key2, store.materialize(block.image).catch((error) => {
21294
+ const key3 = JSON.stringify([block.image.sha256, block.image.bytes, block.image.mediaType]);
21295
+ if (!cache2.has(key3)) cache2.set(key3, store.materialize(block.image).catch((error) => {
21161
21296
  if (strict) throw error;
21162
21297
  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)}`);
21163
21298
  return null;
21164
21299
  }));
21165
- content.push(await cache2.get(key2) ?? { type: "text", text: "[\u56FE\u7247\u6587\u4EF6\u5DF2\u4E0D\u5728\u672C\u673A\uFF0C\u5185\u5BB9\u4E0D\u53EF\u89C1]" });
21300
+ content.push(await cache2.get(key3) ?? { type: "text", text: "[\u56FE\u7247\u6587\u4EF6\u5DF2\u4E0D\u5728\u672C\u673A\uFF0C\u5185\u5BB9\u4E0D\u53EF\u89C1]" });
21166
21301
  signal?.throwIfAborted();
21167
21302
  }
21168
21303
  output.push({ ...message, content });
@@ -21238,8 +21373,8 @@ var init_steer_mailbox = __esm({
21238
21373
  SteerMailbox = class {
21239
21374
  constructor(stateDir, sessionId) {
21240
21375
  this.sessionId = sessionId;
21241
- const key2 = createHash33("sha256").update(sessionId).digest("hex");
21242
- this.path = path25.join(stateDir, "steer", `${key2}.json`);
21376
+ const key3 = createHash33("sha256").update(sessionId).digest("hex");
21377
+ this.path = path25.join(stateDir, "steer", `${key3}.json`);
21243
21378
  }
21244
21379
  path;
21245
21380
  list() {
@@ -21615,9 +21750,9 @@ function smartCompressToolResult(content, essentialFields, sizeLimit) {
21615
21750
  if (typeof item === "object" && item !== null && !Array.isArray(item)) {
21616
21751
  const extracted = {};
21617
21752
  if (fieldSet) {
21618
- for (const key2 of essentialFields) {
21619
- if (key2 in item) {
21620
- extracted[key2] = item[key2];
21753
+ for (const key3 of essentialFields) {
21754
+ if (key3 in item) {
21755
+ extracted[key3] = item[key3];
21621
21756
  }
21622
21757
  }
21623
21758
  } else {
@@ -23691,6 +23826,7 @@ var init_query = __esm({
23691
23826
  const mailbox = this.steerMailbox;
23692
23827
  this.attachmentScopeId = perTurnOptions?.attachmentScopeId;
23693
23828
  const queryId = this.steerQueryId;
23829
+ const hasPendingUserInput = () => this.pendingSteers.some((input) => !input.attachment);
23694
23830
  this.steerHistoryIds = new Set(messages.flatMap((m) => "steerInput" in m && m.steerInput ? [m.steerInput.id] : "attachment" in m ? [m.uuid] : []));
23695
23831
  try {
23696
23832
  for (const input of mailbox?.pending(this.steerRoute ?? void 0) ?? []) {
@@ -23724,6 +23860,13 @@ var init_query = __esm({
23724
23860
  const activeSystemStable = perTurnSystemStable || this.resolveOpt(this.options.systemStable) || this.resolveOpt(this.options.systemPrompt);
23725
23861
  for (const m of messages) if ("role" in m && hasMedia(m) && !m.imageInput) m.imageInput = { id: randomUUID14(), observed: hasImage(m) };
23726
23862
  let currentMessages = [...messages];
23863
+ const stopUserMessages = [];
23864
+ const stopToolResults = [];
23865
+ const collectStopEvidence = !this.options.skipStopHook && !perTurnEmotion;
23866
+ const currentUser = collectStopEvidence ? messages.findLast((m) => "role" in m && m.role === "user") : void 0;
23867
+ if (currentUser && "role" in currentUser) {
23868
+ stopUserMessages.push(currentUser.memoryOriginalText ?? (typeof currentUser.content === "string" ? currentUser.content : currentUser.content.filter((b) => b.type === "text").map((b) => b.text).join("\n")));
23869
+ }
23727
23870
  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\.$/;
23728
23871
  const historicalGateTools = new Set(currentMessages.flatMap((m) => {
23729
23872
  if (!("role" in m) || m.role !== "tool" || typeof m.content !== "string") return [];
@@ -23802,6 +23945,7 @@ var init_query = __esm({
23802
23945
  };
23803
23946
  let turnCount = 0;
23804
23947
  let recallContinuation = false;
23948
+ const stopReplies = [];
23805
23949
  let toolCalls = [];
23806
23950
  let streamRetries = 0;
23807
23951
  let maxTokensOverride = null;
@@ -23858,6 +24002,7 @@ var init_query = __esm({
23858
24002
  }
23859
24003
  const steerMsg = buildSteerMessage(input);
23860
24004
  currentMessages.push(steerMsg);
24005
+ if (collectStopEvidence) stopUserMessages.push(input.originalText ?? input.text);
23861
24006
  this.steerHistoryIds.add(input.id);
23862
24007
  steerConsumedThisTurn = true;
23863
24008
  yield {
@@ -24147,7 +24292,7 @@ ${hint}` : [...current2.content, { type: "text", text: hint }] };
24147
24292
  const fullSystemDynamic = deferredHint && perTurnSystemDynamic ? `${deferredHint}
24148
24293
 
24149
24294
  ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
24150
- if (!this.options.agentLabel || this.options.agentLabel === "main") {
24295
+ if (process.env.ENGINE_DUMP_REQUEST === "1" && (!this.options.agentLabel || this.options.agentLabel === "main")) {
24151
24296
  try {
24152
24297
  const ws = process.env.ENGINE7_WORKSPACE;
24153
24298
  if (ws) {
@@ -24369,20 +24514,22 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
24369
24514
  if (toolCalls.length === 0) {
24370
24515
  const carryReply = () => {
24371
24516
  if (!this.pendingSteers.some((input) => input.attachment)) return null;
24517
+ const replyId = randomUUID14();
24372
24518
  const reply = msg.assistant(textContent);
24373
24519
  if (turnThinking) reply.reasoning_content = turnThinking;
24374
24520
  if (turnThinkingSig) reply.thinking_signature = turnThinkingSig;
24375
24521
  if (turnResponsesReasoning) reply.responses_reasoning = turnResponsesReasoning;
24376
24522
  currentMessages.push(reply);
24377
- finalText = textContent;
24523
+ finalText = "";
24524
+ if (collectStopEvidence) stopReplies.push(textContent);
24378
24525
  recallContinuation = true;
24379
24526
  turnThinking = turnThinkingSig = turnResponsesReasoning = "";
24380
- return { type: "history", messages: [reply] };
24527
+ return [{ type: "history", messages: [reply], replyId }, { type: "reply", content: textContent, replyId }];
24381
24528
  };
24382
24529
  if (responseStopReason === "max_tokens" || responseStopReason === "length") {
24383
24530
  if (this.pendingSteers.length > 0) {
24384
24531
  const carried = carryReply();
24385
- if (carried) yield carried;
24532
+ if (carried) yield* carried;
24386
24533
  continue;
24387
24534
  }
24388
24535
  finalText = textContent;
@@ -24392,7 +24539,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
24392
24539
  if (this.options.skipStopHook || perTurnEmotion) {
24393
24540
  if (this.pendingSteers.length > 0) {
24394
24541
  const carried = carryReply();
24395
- if (carried) yield carried;
24542
+ if (carried) yield* carried;
24396
24543
  continue;
24397
24544
  }
24398
24545
  finalText = textContent;
@@ -24409,9 +24556,14 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
24409
24556
  // 'group' | 'dm',Stop hook 用来判断是否跳过 group
24410
24557
  cwd: context?.workspace || "",
24411
24558
  source: typeof context?.source === "string" ? context.source : "",
24412
- executionContext: context?.executionContext
24559
+ executionContext: context?.executionContext,
24560
+ stopTurnEvidence: { userMessages: stopUserMessages, toolResults: stopToolResults }
24413
24561
  };
24414
- const stopResult = await executeStopHooks(stopCtx, ac.signal, textContent);
24562
+ const stopResult = await executeStopHooks(
24563
+ stopCtx,
24564
+ ac.signal,
24565
+ stopReplies.length ? [...stopReplies, textContent].join("\n\n") : textContent
24566
+ );
24415
24567
  if (stopResult.preventContinuation) {
24416
24568
  console.log(`[hook] Stop blocked: ${stopResult.stopReason || "no reason"}`);
24417
24569
  if (stopResult.additionalContexts?.length) {
@@ -24426,7 +24578,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
24426
24578
  }
24427
24579
  if (this.pendingSteers.length > 0) {
24428
24580
  const carried = carryReply();
24429
- if (carried) yield carried;
24581
+ if (carried) yield* carried;
24430
24582
  continue;
24431
24583
  }
24432
24584
  finalText = textContent;
@@ -24506,6 +24658,12 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
24506
24658
  turnResponsesReasoning = "";
24507
24659
  currentMessages.push(gateAssistant);
24508
24660
  currentMessages.push(...blockResults);
24661
+ if (collectStopEvidence) for (let i = 0; i < toolCalls.length; i++) stopToolResults.push({
24662
+ tool: toolCalls[i].function.name,
24663
+ toolCallId: toolCalls[i].id,
24664
+ summary: String(blockResults[i].content),
24665
+ isError: true
24666
+ });
24509
24667
  for (const g of gatedCalls) {
24510
24668
  yield { type: "tool_result", tool: g.call.function?.name, tool_call_id: g.call.id, summary: g.text.slice(0, 200), isError: true };
24511
24669
  }
@@ -24526,7 +24684,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
24526
24684
  try {
24527
24685
  this.phase = "tools";
24528
24686
  this.toolYield = new AbortController();
24529
- if (this.pendingSteers.length) this.toolYield.abort("steer");
24687
+ if (hasPendingUserInput()) this.toolYield.abort("steer");
24530
24688
  toolCtx.yieldSignal = this.toolYield.signal;
24531
24689
  toolRes = await executeTools(toolCalls, ac.signal, { ...toolCtx, toolResultHistory: currentMessages });
24532
24690
  } finally {
@@ -24535,6 +24693,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
24535
24693
  if (vcDelivery) await vcDelivery;
24536
24694
  }
24537
24695
  const { messages: toolResults, summaries } = toolRes;
24696
+ if (collectStopEvidence) stopToolResults.push(...summaries);
24538
24697
  for (const s of summaries) {
24539
24698
  try {
24540
24699
  const postResult = await executePostToolUseHooks(s.tool, {}, s.summary, hookCtx, ac.signal);
@@ -24636,7 +24795,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
24636
24795
  this.toolYield = null;
24637
24796
  this.phase = "idle";
24638
24797
  this.loopAlive = false;
24639
- if (this.pendingSteers.length > 0 && completionReason !== "aborted") {
24798
+ if (hasPendingUserInput() && completionReason !== "aborted") {
24640
24799
  console.warn(`${this.logPrefix} [steer] ${this.pendingSteers.length} pending input(s) retained for same-route recovery (completionReason=${completionReason ?? "completed"})`);
24641
24800
  }
24642
24801
  this.pendingSteers.length = 0;
@@ -24761,7 +24920,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
24761
24920
  }
24762
24921
  }
24763
24922
  this.pendingSteers.push(receipt2.input);
24764
- this.toolYield?.abort("steer");
24923
+ if (!receipt2.input.attachment) this.toolYield?.abort("steer");
24765
24924
  if (opts.mode === "queue") {
24766
24925
  console.log(`${this.logPrefix} Steer queued (${this.pendingSteers.length} pending \u2014 next turn, no interrupt)`);
24767
24926
  return true;
@@ -26596,9 +26755,9 @@ var init_AgentTool = __esm({
26596
26755
  const agentId = `${(subagentType || "agent").toLowerCase()}-${++subAgentCounter}`;
26597
26756
  visualEmitter?.emitAgentSpawn(agentLabel, teamName || void 0, void 0, agentId);
26598
26757
  const onProgress = (event2) => {
26599
- const key2 = `${event2.agentType || agentType}:${event2.description || description}`;
26600
- const count = (toolCountMap.get(key2) || 0) + 1;
26601
- toolCountMap.set(key2, count);
26758
+ const key3 = `${event2.agentType || agentType}:${event2.description || description}`;
26759
+ const count = (toolCountMap.get(key3) || 0) + 1;
26760
+ toolCountMap.set(key3, count);
26602
26761
  const label = event2.description ? `${event2.agentType || agentType} \xB7 ${event2.description}` : event2.agentType || agentType;
26603
26762
  if (event2.type === "tool_call") {
26604
26763
  console.log(`[agent-progress:${label}] #${count} ${event2.toolName}: ${(event2.args || "").slice(0, 200)}`);
@@ -27312,9 +27471,9 @@ async function resolvePoolTavilyKey(opts = {}) {
27312
27471
  }
27313
27472
  }
27314
27473
  if (!cache.keys.length) return "";
27315
- const key2 = cache.keys[cursor % cache.keys.length];
27474
+ const key3 = cache.keys[cursor % cache.keys.length];
27316
27475
  cursor++;
27317
- return key2;
27476
+ return key3;
27318
27477
  }
27319
27478
  var CACHE_TTL_MS, RELAY_PROVIDER_DEFAULT, cache, cursor;
27320
27479
  var init_tavily_pool = __esm({
@@ -27706,11 +27865,11 @@ function parseFrontmatter(content) {
27706
27865
  i++;
27707
27866
  continue;
27708
27867
  }
27709
- const key2 = line.slice(0, colonIdx).trim();
27868
+ const key3 = line.slice(0, colonIdx).trim();
27710
27869
  let value2 = line.slice(colonIdx + 1).trim();
27711
27870
  if (value2.startsWith('"') && value2.endsWith('"') || value2.startsWith("'") && value2.endsWith("'")) {
27712
27871
  value2 = value2.slice(1, -1);
27713
- result[key2] = value2;
27872
+ result[key3] = value2;
27714
27873
  i++;
27715
27874
  continue;
27716
27875
  } else if (value2 === "|" || value2 === ">") {
@@ -27720,16 +27879,16 @@ function parseFrontmatter(content) {
27720
27879
  blockLines.push(lines[i].slice(2));
27721
27880
  i++;
27722
27881
  }
27723
- result[key2] = blockLines.join("\n").trim();
27882
+ result[key3] = blockLines.join("\n").trim();
27724
27883
  continue;
27725
27884
  } else if (value2.startsWith("[") && value2.endsWith("]")) {
27726
- result[key2] = value2.slice(1, -1).split(",").map((s) => s.trim());
27885
+ result[key3] = value2.slice(1, -1).split(",").map((s) => s.trim());
27727
27886
  i++;
27728
27887
  continue;
27729
27888
  } else if (value2.includes(" ") && !value2.startsWith('"')) {
27730
- result[key2] = value2;
27889
+ result[key3] = value2;
27731
27890
  } else {
27732
- result[key2] = value2;
27891
+ result[key3] = value2;
27733
27892
  }
27734
27893
  i++;
27735
27894
  }
@@ -27832,12 +27991,10 @@ function registerSkillTool(skillsDir, skills, contextWindowTokens) {
27832
27991
  cachedSkills = skills;
27833
27992
  cachedContextWindowTokens = contextWindowTokens;
27834
27993
  const descriptionText = buildSkillToolPrompt();
27835
- const listingText = formatSkillsListing(cachedSkills, contextWindowTokens);
27994
+ cachedListing = formatSkillsListing(cachedSkills, contextWindowTokens);
27836
27995
  registry.register({
27837
27996
  name: SKILL_TOOL_NAME,
27838
27997
  description: descriptionText,
27839
- // prompt 字段存 skills listing,供 dynamic prompt 读取注入 system-reminder
27840
- prompt: listingText,
27841
27998
  schema: {
27842
27999
  type: "object",
27843
28000
  properties: {
@@ -27891,7 +28048,7 @@ ${content.content}${argLine}` };
27891
28048
  function getSkillToolState() {
27892
28049
  return { skillsDirPath, contextWindowTokens: cachedContextWindowTokens, skillNames: cachedSkills.map((s) => s.name) };
27893
28050
  }
27894
- var COMMAND_NAME_TAG, MIN_DESC_LENGTH, skillsDirPath, cachedSkills, cachedContextWindowTokens;
28051
+ var COMMAND_NAME_TAG, MIN_DESC_LENGTH, skillsDirPath, cachedSkills, cachedListing, cachedContextWindowTokens;
27895
28052
  var init_SkillTool = __esm({
27896
28053
  "src/tools/SkillTool/SkillTool.ts"() {
27897
28054
  "use strict";
@@ -27903,6 +28060,7 @@ var init_SkillTool = __esm({
27903
28060
  MIN_DESC_LENGTH = 20;
27904
28061
  skillsDirPath = "";
27905
28062
  cachedSkills = [];
28063
+ cachedListing = "";
27906
28064
  }
27907
28065
  });
27908
28066
 
@@ -28440,17 +28598,17 @@ var init_orchestrator = __esm({
28440
28598
  console.warn(`[reload] entry "${entry.name}" already registered, replacing`);
28441
28599
  }
28442
28600
  let slice = null;
28443
- let key2 = "null";
28601
+ let key3 = "null";
28444
28602
  try {
28445
28603
  slice = liveConfig.isReady() ? entry.select(liveConfig.all()) : null;
28446
- key2 = stableKey(slice);
28604
+ key3 = stableKey(slice);
28447
28605
  } catch (err) {
28448
28606
  console.warn(`[reload] entry "${entry.name}" select() failed at register: ${err.message}`);
28449
28607
  }
28450
28608
  this.entries.set(entry.name, {
28451
28609
  entry,
28452
28610
  running: running ?? sliceEnabled(slice),
28453
- key: key2
28611
+ key: key3
28454
28612
  });
28455
28613
  }
28456
28614
  unregister(name) {
@@ -29507,10 +29665,10 @@ var init_registry2 = __esm({
29507
29665
  validate: (value2) => {
29508
29666
  if (!value2 || typeof value2 !== "object" || Array.isArray(value2)) return "\u4EBA\u7269\u5173\u7CFB\u9884\u7B97\u5FC5\u987B\u662F\u5BF9\u8C61";
29509
29667
  const bounds = { maxHops: [0, 8], maxNodes: [1, 1e3], maxTokens: [512, 64e3], maxExplorations: [0, 2], maxActive: [1, 1e3] };
29510
- for (const [key2, range] of Object.entries(bounds)) {
29511
- const number = value2[key2];
29668
+ for (const [key3, range] of Object.entries(bounds)) {
29669
+ const number = value2[key3];
29512
29670
  if (number !== void 0 && (typeof number !== "number" || !Number.isSafeInteger(number) || number < range[0] || number > range[1])) {
29513
- return `${key2} \u5FC5\u987B\u662F ${range[0]} \u5230 ${range[1]} \u7684\u6574\u6570`;
29671
+ return `${key3} \u5FC5\u987B\u662F ${range[0]} \u5230 ${range[1]} \u7684\u6574\u6570`;
29514
29672
  }
29515
29673
  }
29516
29674
  return null;
@@ -29885,7 +30043,7 @@ var init_cli_init_config = __esm({
29885
30043
  init_registry2();
29886
30044
  init_emotion_tools();
29887
30045
  init_context_window_policy();
29888
- FREE_TIER_RELAY_URL = "https://www.twinsun.top:8866";
30046
+ FREE_TIER_RELAY_URL = "https://7yi.engine7.ai";
29889
30047
  FREE_TIER_PROVIDER_ID = "7yi";
29890
30048
  FREE_TIER_NORT_MODEL = "engine7-free-nort";
29891
30049
  FREE_TIER_NORT_REF = `${FREE_TIER_PROVIDER_ID}/${FREE_TIER_NORT_MODEL}`;
@@ -31130,9 +31288,9 @@ async function collectInventory(options) {
31130
31288
  continue;
31131
31289
  }
31132
31290
  validateRelativePath(path37);
31133
- const key2 = root + "/" + path37.normalize("NFC").toLowerCase();
31134
- if (aliases.has(key2)) throw new Error("PORTABLE_PATH_COLLISION");
31135
- aliases.add(key2);
31291
+ const key3 = root + "/" + path37.normalize("NFC").toLowerCase();
31292
+ if (aliases.has(key3)) throw new Error("PORTABLE_PATH_COLLISION");
31293
+ aliases.add(key3);
31136
31294
  let info = await lstat2(source, { bigint: true }), linkSignature = "";
31137
31295
  if (options.selection === "core" && root === "workspace" && !prefix2 && !CORE_DIRECTORIES.has(name) && (info.isDirectory() || info.isSymbolicLink() && !/\.[a-z0-9]+$/i.test(name))) {
31138
31296
  exclusions.push({ root, path: path37, reason: "optional workspace material; outside core travel" });
@@ -31516,7 +31674,7 @@ var PublicationReplica = class _PublicationReplica {
31516
31674
  const replica = this.replicas.get(commit?.binding?.databaseId);
31517
31675
  if (!replica) throw new Error("PUBLICATION_UNREGISTERED_DATABASE");
31518
31676
  const content = await this.objects.putContent(encoded);
31519
- const received = replica.receive(commit);
31677
+ const received2 = replica.receive(commit);
31520
31678
  this.db.exec("BEGIN IMMEDIATE");
31521
31679
  try {
31522
31680
  const old = this.commitEvidence(commit.binding.databaseId, commit.sequence);
@@ -31531,7 +31689,7 @@ var PublicationReplica = class _PublicationReplica {
31531
31689
  while (this.commitEvidence(commit.binding.databaseId, replica.head().sequence + 1)) {
31532
31690
  if (!replica.applyNext()) break;
31533
31691
  }
31534
- return replica.appliedReceipt(commit.sequence) ?? received;
31692
+ return replica.appliedReceipt(commit.sequence) ?? received2;
31535
31693
  }
31536
31694
  databaseMissing(manifest) {
31537
31695
  const missing = [];
@@ -31653,7 +31811,7 @@ function canonical(value2) {
31653
31811
  if (typeof value2 === "number" && Number.isFinite(value2)) return value2;
31654
31812
  if (Array.isArray(value2)) return value2.map(canonical);
31655
31813
  if (value2 && typeof value2 === "object" && Object.getPrototypeOf(value2) === Object.prototype)
31656
- return Object.fromEntries(Object.keys(value2).sort().map((key2) => [key2, canonical(value2[key2])]));
31814
+ return Object.fromEntries(Object.keys(value2).sort().map((key3) => [key3, canonical(value2[key3])]));
31657
31815
  throw new Error("TREE_SOURCE_INVALID_ORIGIN");
31658
31816
  }
31659
31817
  var sha2 = (body) => createHash4("sha256").update(body).digest("hex");
@@ -32960,12 +33118,12 @@ var incarnation2 = (file2) => {
32960
33118
  return `${s.dev}:${s.ino}`;
32961
33119
  };
32962
33120
  function validateRecoveryArchiveEntry(entry, identity3) {
32963
- if (!entry || Object.keys(entry).some((key2) => !["format", "id", "kind", "manifest", "databases", "publication", "receipt"].includes(key2)) || entry.format !== FORMAT || !ID2.test(entry.id) || !["COMMON", "LOCAL", "REMOTE"].includes(entry.kind)) throw new Error("RECOVERY_ARCHIVE_CORRUPT");
33121
+ if (!entry || Object.keys(entry).some((key3) => !["format", "id", "kind", "manifest", "databases", "publication", "receipt"].includes(key3)) || entry.format !== FORMAT || !ID2.test(entry.id) || !["COMMON", "LOCAL", "REMOTE"].includes(entry.kind)) throw new Error("RECOVERY_ARCHIVE_CORRUPT");
32964
33122
  const manifest = normalizePublication(entry.manifest), manifestDigest = publicationDigest(manifest);
32965
33123
  if (!same3(manifest.profile.identity, identity3)) throw new Error("RECOVERY_IDENTITY_MISMATCH");
32966
33124
  if (!Array.isArray(entry.databases) || !same3(entry.databases.map((db2) => db2.databaseId), manifest.profile.databaseIds)) throw new Error("RECOVERY_INCOMPLETE_DATABASES");
32967
33125
  for (const db2 of entry.databases) {
32968
- if (Object.keys(db2).some((key2) => !["databaseId", "role", "schemaHash", "content"].includes(key2)) || db2.role !== (entry.kind === "LOCAL" ? "source" : "replica") || !/^[a-f0-9]{64}$/.test(db2.schemaHash)) throw new Error("RECOVERY_ARCHIVE_CORRUPT");
33126
+ if (Object.keys(db2).some((key3) => !["databaseId", "role", "schemaHash", "content"].includes(key3)) || db2.role !== (entry.kind === "LOCAL" ? "source" : "replica") || !/^[a-f0-9]{64}$/.test(db2.schemaHash)) throw new Error("RECOVERY_ARCHIVE_CORRUPT");
32969
33127
  validateFileContent(db2.content);
32970
33128
  }
32971
33129
  const publication = { state: "PUBLISHED", sequence: manifest.sequence, digest: manifestDigest, deletionWatermark: manifest.deletionWatermark, activationAllowed: false };
@@ -33362,11 +33520,11 @@ var EVENT_BYTES = 16 * 1024 * 1024;
33362
33520
  function sessionLimits(options) {
33363
33521
  if (!options || typeof options !== "object" || Array.isArray(options)) throw new Error("REPLICATION_INVALID_LIMIT");
33364
33522
  const limits2 = {};
33365
- for (const key2 of ["maximumPendingBytes", "maximumCommitBytes"]) {
33366
- const value2 = options[key2];
33523
+ for (const key3 of ["maximumPendingBytes", "maximumCommitBytes"]) {
33524
+ const value2 = options[key3];
33367
33525
  if (value2 !== void 0) {
33368
33526
  if (!Number.isSafeInteger(value2) || value2 < 1 || value2 > 256 * 1024 * 1024) throw new Error("REPLICATION_INVALID_LIMIT");
33369
- limits2[key2] = value2;
33527
+ limits2[key3] = value2;
33370
33528
  }
33371
33529
  }
33372
33530
  return limits2;
@@ -33443,16 +33601,16 @@ function* frames(bytes, kind) {
33443
33601
  }
33444
33602
  if (offset !== bytes.length) throw new Error("SESSION_EVENT_TORN_BASELINE");
33445
33603
  }
33446
- function rememberEvent(db2, key2, body, kind) {
33604
+ function rememberEvent(db2, key3, body, kind) {
33447
33605
  const id2 = eventId(body, kind), digest7 = sha5(body);
33448
- const old = db2.prepare("SELECT sequence,digest,body FROM session_events WHERE session_key=? AND event_id=?").get(key2, id2);
33606
+ const old = db2.prepare("SELECT sequence,digest,body FROM session_events WHERE session_key=? AND event_id=?").get(key3, id2);
33449
33607
  if (old) {
33450
33608
  if (old.digest !== digest7 || !(old.body instanceof Uint8Array) || !body.equals(Buffer.from(old.body))) throw new Error("SESSION_EVENT_ID_CONFLICT");
33451
33609
  return Number(old.sequence);
33452
33610
  }
33453
33611
  const sequence = Number(db2.prepare("SELECT COALESCE(max(sequence),0)+1 n FROM session_events").get().n);
33454
33612
  if (!Number.isSafeInteger(sequence) || sequence < 1) throw new Error("SESSION_EVENT_SEQUENCE_EXHAUSTED");
33455
- db2.prepare("INSERT INTO session_events VALUES(?,?,?,?,?)").run(sequence, key2, id2, body, digest7);
33613
+ db2.prepare("INSERT INTO session_events VALUES(?,?,?,?,?)").run(sequence, key3, id2, body, digest7);
33456
33614
  return sequence;
33457
33615
  }
33458
33616
  function nextRevision(db2) {
@@ -34057,7 +34215,7 @@ async function preparePairingMaterial(input) {
34057
34215
  }
34058
34216
  return prior;
34059
34217
  }
34060
- const resolveSecrets = (value2) => typeof value2 === "string" ? value2.startsWith("env:") ? process.env[value2.slice(4)] ?? value2 : value2.replace(/\{\{([A-Z_][A-Z_0-9]*)\}\}/g, (_, name) => process.env[name] ?? "{{" + name + "}}") : Array.isArray(value2) ? value2.map(resolveSecrets) : value2 && typeof value2 === "object" ? Object.fromEntries(Object.entries(value2).map(([key3, item]) => [key3, resolveSecrets(item)])) : value2;
34218
+ const resolveSecrets = (value2) => typeof value2 === "string" ? value2.startsWith("env:") ? process.env[value2.slice(4)] ?? value2 : value2.replace(/\{\{([A-Z_][A-Z_0-9]*)\}\}/g, (_, name) => process.env[name] ?? "{{" + name + "}}") : Array.isArray(value2) ? value2.map(resolveSecrets) : value2 && typeof value2 === "object" ? Object.fromEntries(Object.entries(value2).map(([key4, item]) => [key4, resolveSecrets(item)])) : value2;
34061
34219
  const effective = resolveSecrets(config);
34062
34220
  const channels = Object.fromEntries(Object.entries(effective.channels ?? {}).filter(([name]) => name !== "emotion"));
34063
34221
  for (const [name, block] of Object.entries(channels)) if (block.enabled && !["discord", "feishu", "wechat"].includes(name)) throw new Error("TRAVEL_CHANNEL_NOT_CONTROLLED");
@@ -34066,10 +34224,10 @@ async function preparePairingMaterial(input) {
34066
34224
  const identity3 = { tenantId: "self-hosted-" + sha6(homedir3()).slice(0, 20), companionId: companion, seatId: input.taskId };
34067
34225
  const tlsDirectory = join46(directory2, "tls");
34068
34226
  createPairingTLS(tlsDirectory, input.host);
34069
- const key2 = randomBytes4(32);
34070
- writeFileSync23(join46(directory2, "data.key"), key2, { mode: 384 });
34071
- const keySha256 = sha6(key2);
34072
- key2.fill(0);
34227
+ const key3 = randomBytes4(32);
34228
+ writeFileSync23(join46(directory2, "data.key"), key3, { mode: 384 });
34229
+ const keySha256 = sha6(key3);
34230
+ key3.fill(0);
34073
34231
  const ports = {};
34074
34232
  for (const name of names) ports[name] = await free();
34075
34233
  execFileSync2("/usr/bin/ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-f", join46(directory2, "relay.key")], { stdio: "ignore" });
@@ -34310,7 +34468,7 @@ function runtimeEngineConfig(original, stateDir, workspace) {
34310
34468
  return value2;
34311
34469
  }
34312
34470
  if (Array.isArray(value2)) return value2.map(relocate);
34313
- if (value2 && typeof value2 === "object") return Object.fromEntries(Object.entries(value2).map(([key2, item]) => [key2, relocate(item)]));
34471
+ if (value2 && typeof value2 === "object") return Object.fromEntries(Object.entries(value2).map(([key3, item]) => [key3, relocate(item)]));
34314
34472
  return value2;
34315
34473
  };
34316
34474
  const copy = relocate(original), copiedAgents = copy.agents;
@@ -34555,7 +34713,7 @@ init_scope();
34555
34713
  init_schema_migrations();
34556
34714
  import { DatabaseSync as DatabaseSync19 } from "node:sqlite";
34557
34715
  import { createHash as createHash37 } from "node:crypto";
34558
- import { gunzipSync as gunzipSync2 } from "node:zlib";
34716
+ import { gunzipSync as gunzipSync3 } from "node:zlib";
34559
34717
  import { isUtf8 } from "node:buffer";
34560
34718
  import { rmSync as rmSync4, writeFileSync as writeFileSync26, existsSync as existsSync29, unlinkSync as unlinkSync9 } from "node:fs";
34561
34719
  import { join as join51, dirname as dirname19 } from "node:path";
@@ -34585,7 +34743,7 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
34585
34743
  if (!source) throw new Error("RECOVERY_OVERLAY_SOURCE_PROVENANCE");
34586
34744
  originals.set(JSON.stringify([row.scope_id, row.origin_key, row.source_version]), source);
34587
34745
  }
34588
- const deletedOrigins = new Set([...originals].filter(([, row]) => blocked2(String(row.scope_id), String(row.source_id))).map(([key2]) => JSON.stringify(JSON.parse(key2).slice(0, 2))));
34746
+ const deletedOrigins = new Set([...originals].filter(([, row]) => blocked2(String(row.scope_id), String(row.source_id))).map(([key3]) => JSON.stringify(JSON.parse(key3).slice(0, 2))));
34589
34747
  const parse = (text2, limit = 16 * 1024 * 1024) => {
34590
34748
  if (Buffer.byteLength(text2) > limit) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
34591
34749
  try {
@@ -34648,7 +34806,7 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
34648
34806
  if (row.payload_archive !== null) {
34649
34807
  if (!(row.payload_archive instanceof Uint8Array) || row.payload_archive.byteLength > 16 * 1024 * 1024) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
34650
34808
  try {
34651
- input = gunzipSync2(row.payload_archive, { maxOutputLength: 16 * 1024 * 1024 }).toString("utf8");
34809
+ input = gunzipSync3(row.payload_archive, { maxOutputLength: 16 * 1024 * 1024 }).toString("utf8");
34652
34810
  } catch {
34653
34811
  throw new Error("RECOVERY_OVERLAY_JOB_ARCHIVE");
34654
34812
  }
@@ -34758,20 +34916,20 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
34758
34916
  if (++scanned > 1e6 || bytes > 64 * 1024 * 1024) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
34759
34917
  if (!identities.has(JSON.stringify([record.scope_id, record.source_id]))) throw new Error("RECOVERY_OVERLAY_SESSION_PROVENANCE");
34760
34918
  if (!blocked2(String(record.scope_id), String(record.source_id))) continue;
34761
- const key2 = JSON.stringify([record.session_file_id, record.session_id, record.record_id]), group = legacyRecords.get(key2) ?? [];
34919
+ const key3 = JSON.stringify([record.session_file_id, record.session_id, record.record_id]), group = legacyRecords.get(key3) ?? [];
34762
34920
  group.push(record);
34763
- legacyRecords.set(key2, group);
34921
+ legacyRecords.set(key3, group);
34764
34922
  }
34765
34923
  const headers = /* @__PURE__ */ new Map();
34766
34924
  for (const row of db2.prepare("SELECT session_key,body,digest FROM session_events WHERE event_id LIKE 'header:%'").iterate()) {
34767
34925
  if (!(row.body instanceof Uint8Array) || sha7(row.body) !== row.digest) throw new Error("SESSION_EVENT_CORRUPT");
34768
34926
  bytes += row.body.byteLength;
34769
34927
  if (++scanned > 1e6 || bytes > 64 * 1024 * 1024) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
34770
- const header = parse(Buffer.from(row.body).toString()), key2 = String(row.session_key);
34928
+ const header = parse(Buffer.from(row.body).toString()), key3 = String(row.session_key);
34771
34929
  if (header.type === "session" && typeof header.id === "string" && typeof header.engineSessionId === "string") {
34772
- const group = headers.get(key2) ?? [];
34930
+ const group = headers.get(key3) ?? [];
34773
34931
  group.push({ id: header.id, sessionId: header.engineSessionId });
34774
- headers.set(key2, group);
34932
+ headers.set(key3, group);
34775
34933
  }
34776
34934
  }
34777
34935
  const updates = [];
@@ -34782,7 +34940,7 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
34782
34940
  if (sha7(row.body) !== row.digest) throw new Error("SESSION_EVENT_CORRUPT");
34783
34941
  if (String(row.event_id).startsWith("blob:")) continue;
34784
34942
  const event2 = parse(Buffer.from(row.body).toString("utf8")), message = event2?.message;
34785
- const deletedEvent = () => Object.fromEntries(["id", "uuid", "parentId", "parentUuid", "timestamp"].filter((key2) => Object.hasOwn(event2, key2)).map((key2) => [key2, event2[key2]]));
34943
+ const deletedEvent = () => Object.fromEntries(["id", "uuid", "parentId", "parentUuid", "timestamp"].filter((key3) => Object.hasOwn(event2, key3)).map((key3) => [key3, event2[key3]]));
34786
34944
  if (object3(message)) {
34787
34945
  if (typeof message.memoryOriginKey === "string" && message.memoryScope !== void 0) {
34788
34946
  const scope = scopeKey(message.memoryScope), version = message.memorySourceVersion ?? (message.role === "assistant" ? 1 : void 0);
@@ -34887,8 +35045,8 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
34887
35045
  // src/continuity/recovery-deletion-overlay.ts
34888
35046
  var same4 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
34889
35047
  var sha8 = (value2) => createHash38("sha256").update(value2).digest("hex");
34890
- var evidenceRow = (row) => Object.fromEntries(Object.entries(row).map(([key2, value2]) => [
34891
- key2,
35048
+ var evidenceRow = (row) => Object.fromEntries(Object.entries(row).map(([key3, value2]) => [
35049
+ key3,
34892
35050
  value2 === null ? ["null"] : typeof value2 === "string" ? ["text", value2] : typeof value2 === "bigint" ? ["integer", String(value2)] : typeof value2 === "number" ? ["real", String(value2)] : ["blob", Buffer.from(value2).toString("base64")]
34893
35051
  ]));
34894
35052
  var applyRecoveryDeletionRuntimeCopies = (options) => deletionOverlay(options, true);
@@ -35461,7 +35619,7 @@ function supervisedRuntimeEnvironment(config, parent, environmentNames = []) {
35461
35619
  if (match) add(match[1] ?? match[2]);
35462
35620
  } else if (value2 && typeof value2 === "object") for (const child of Object.values(value2)) references(child, depth + 1);
35463
35621
  };
35464
- for (const [key2, value2] of Object.entries(config)) if (key2 !== "channels") references(value2);
35622
+ for (const [key3, value2] of Object.entries(config)) if (key3 !== "channels") references(value2);
35465
35623
  for (const name of environmentNames) add(name);
35466
35624
  const env = {};
35467
35625
  for (const [name, value2] of Object.entries(parent)) if (value2 !== void 0 && (systemEnvironment.has(name.toUpperCase()) || /^LC_[A-Z_]+$/.test(name))) env[name] = value2;
@@ -35801,7 +35959,7 @@ async function restoreRuntimePublication(options) {
35801
35959
  if (!status.published || !status.dataReady) throw new Error("PUBLICATION_NOT_READY");
35802
35960
  if (options.sequence !== void 0 && options.sequence !== status.published.sequence) throw new Error("PUBLICATION_STALE_PUBLICATION");
35803
35961
  const manifest = await receiver.manifest(status.published.sequence), destination = resolve33(options.destination);
35804
- const sessions = [];
35962
+ const sessions2 = [];
35805
35963
  for (const kind of manifest.profile.trees.filter((tree) => tree.kind === "session")) {
35806
35964
  const tree = manifest.trees.find((tree2) => tree2.id === kind.id);
35807
35965
  if (tree.directories.length || tree.files.length !== 1 || tree.files[0].path !== "manifest.json") throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
@@ -35814,7 +35972,7 @@ async function restoreRuntimePublication(options) {
35814
35972
  epoch: manifest.profile.epoch
35815
35973
  });
35816
35974
  if (metadata4.format !== "engine7-session-events-publication-v1" || !database || JSON.stringify(metadata4.binding) !== JSON.stringify(binding) || JSON.stringify(metadata4.head) !== JSON.stringify(database.head)) throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
35817
- sessions.push({ treeId: tree.id, databaseId: database.databaseId, head: database.head, binding });
35975
+ sessions2.push({ treeId: tree.id, databaseId: database.databaseId, head: database.head, binding });
35818
35976
  }
35819
35977
  await restorePublication({ ...options, destination, deferReceipt: true });
35820
35978
  const lance = [], sessionStates = [];
@@ -35828,7 +35986,7 @@ async function restoreRuntimePublication(options) {
35828
35986
  await syncDirectory(join57(destination, "lance"));
35829
35987
  lance.push({ treeId: tree.id, directory: `lance/${tree.id}` });
35830
35988
  }
35831
- for (const session of sessions) {
35989
+ for (const session of sessions2) {
35832
35990
  const directory2 = join57(destination, "sessions", session.treeId), db2 = new DatabaseSync25(join57(destination, "databases", session.databaseId + ".sqlite"), { readOnly: true });
35833
35991
  try {
35834
35992
  const head = db2.prepare("SELECT head,digest FROM e7_replication_control WHERE role='replica'").get();
@@ -36121,12 +36279,12 @@ async function fetchTravelKey(options) {
36121
36279
  const wanted = options.identity;
36122
36280
  if (value2?.protocolVersion !== 1 || !value2.identity || ["tenantId", "companionId", "seatId", "keyId", "generation"].some((k) => value2.identity[k] !== wanted[k]) || !Number.isSafeInteger(value2.deletionWatermark) || value2.deletionWatermark < options.minimumDeletionWatermark || typeof value2.key !== "string" || !/^[A-Za-z0-9+/]{43}=$/.test(value2.key))
36123
36281
  throw new Error("KEY_SERVICE_INVALID_RESPONSE");
36124
- const key2 = Buffer.from(value2.key, "base64");
36125
- if (key2.length !== 32 || key2.toString("base64") !== value2.key) {
36126
- key2.fill(0);
36282
+ const key3 = Buffer.from(value2.key, "base64");
36283
+ if (key3.length !== 32 || key3.toString("base64") !== value2.key) {
36284
+ key3.fill(0);
36127
36285
  throw new Error("KEY_SERVICE_INVALID_RESPONSE");
36128
36286
  }
36129
- return { key: key2, deletionWatermark: value2.deletionWatermark };
36287
+ return { key: key3, deletionWatermark: value2.deletionWatermark };
36130
36288
  }
36131
36289
 
36132
36290
  // src/continuity/node-agent.ts
@@ -36390,7 +36548,7 @@ var RuntimeCheckpointControl = class {
36390
36548
  constructor(options) {
36391
36549
  this.options = options;
36392
36550
  this.profile = normalizePublicationProfile(options.profile);
36393
- if (!hash7(options.parentCheckpointDigest) || ["tenantId", "companionId", "seatId"].some((key2) => this.profile.identity[key2] !== options.principal[key2]) || ![options.bootId, options.authorityBootId, options.principal.nodeId].every((value2) => typeof value2 === "string" && /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value2))) throw new Error("TRAVEL_CHECKPOINT_IDENTITY");
36551
+ if (!hash7(options.parentCheckpointDigest) || ["tenantId", "companionId", "seatId"].some((key3) => this.profile.identity[key3] !== options.principal[key3]) || ![options.bootId, options.authorityBootId, options.principal.nodeId].every((value2) => typeof value2 === "string" && /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value2))) throw new Error("TRAVEL_CHECKPOINT_IDENTITY");
36394
36552
  this.binding = JSON.stringify([this.profile, options.principal.nodeId, options.bootId, options.authorityBootId, options.parentCheckpointDigest]);
36395
36553
  preparePrivateDirectory(options.directory);
36396
36554
  this.files = ["checkpoints.json", "checkpoint-owner.sqlite", "checkpoints.sqlite"].map((file2) => join62(options.directory, file2));
@@ -36441,7 +36599,7 @@ var RuntimeCheckpointControl = class {
36441
36599
  }
36442
36600
  permit() {
36443
36601
  const permit = this.options.permit(), p = this.options.principal;
36444
- if (!permit || ["tenantId", "companionId", "seatId", "nodeId"].some((key2) => permit[key2] !== p[key2]) || permit.bootId !== this.options.bootId || permit.authorityBootId !== this.options.authorityBootId || permit.epoch !== this.profile.epoch) throw new Error("TRAVEL_CHECKPOINT_IDENTITY");
36602
+ if (!permit || ["tenantId", "companionId", "seatId", "nodeId"].some((key3) => permit[key3] !== p[key3]) || permit.bootId !== this.options.bootId || permit.authorityBootId !== this.options.authorityBootId || permit.epoch !== this.profile.epoch) throw new Error("TRAVEL_CHECKPOINT_IDENTITY");
36445
36603
  return permit;
36446
36604
  }
36447
36605
  advance(input) {
@@ -36484,7 +36642,7 @@ var RuntimeCheckpointControl = class {
36484
36642
 
36485
36643
  // src/continuity/recovery-archive-transfer.ts
36486
36644
  import { Agent, createServer as createServer2, request as request3 } from "node:https";
36487
- import { gzipSync, gunzipSync as gunzipSync3, createGunzip, brotliCompressSync, brotliDecompressSync, createBrotliCompress, createBrotliDecompress, constants as constants13 } from "node:zlib";
36645
+ import { gzipSync, gunzipSync as gunzipSync4, createGunzip, brotliCompressSync, brotliDecompressSync, createBrotliCompress, createBrotliDecompress, constants as constants13 } from "node:zlib";
36488
36646
  import { pipeline } from "node:stream";
36489
36647
  import { pipeline as pipelineAsync } from "node:stream/promises";
36490
36648
  init_publication_objects();
@@ -36541,9 +36699,9 @@ function validateCatalog(value2) {
36541
36699
  if (!Array.isArray(value2) || value2.length > 4096) throw new Error("RECOVERY_TRANSFER_INVALID_RESPONSE");
36542
36700
  const ids = /* @__PURE__ */ new Set();
36543
36701
  for (const receipt2 of value2) {
36544
- if (!receipt2 || !validId(receipt2.id) || ids.has(receipt2.id) || receipt2.state !== "PRESERVED" || receipt2.activationAllowed !== false || !["COMMON", "LOCAL", "REMOTE"].includes(receipt2.kind) || ![receipt2.digest, receipt2.manifestDigest].every((value3) => typeof value3 === "string" && /^[a-f0-9]{64}$/.test(value3)) || !Number.isSafeInteger(receipt2.deletionWatermark) || receipt2.deletionWatermark < 0 || Object.keys(receipt2).some((key2) => !["id", "state", "kind", "digest", "manifestDigest", "deletionWatermark", "activationAllowed", "publication"].includes(key2))) throw new Error("RECOVERY_TRANSFER_INVALID_RESPONSE");
36702
+ if (!receipt2 || !validId(receipt2.id) || ids.has(receipt2.id) || receipt2.state !== "PRESERVED" || receipt2.activationAllowed !== false || !["COMMON", "LOCAL", "REMOTE"].includes(receipt2.kind) || ![receipt2.digest, receipt2.manifestDigest].every((value3) => typeof value3 === "string" && /^[a-f0-9]{64}$/.test(value3)) || !Number.isSafeInteger(receipt2.deletionWatermark) || receipt2.deletionWatermark < 0 || Object.keys(receipt2).some((key3) => !["id", "state", "kind", "digest", "manifestDigest", "deletionWatermark", "activationAllowed", "publication"].includes(key3))) throw new Error("RECOVERY_TRANSFER_INVALID_RESPONSE");
36545
36703
  const publication = receipt2.publication;
36546
- if (receipt2.kind === "LOCAL" ? publication !== void 0 : !publication || publication.state !== "PUBLISHED" || publication.activationAllowed !== false || publication.digest !== receipt2.manifestDigest || publication.deletionWatermark !== receipt2.deletionWatermark || !Number.isSafeInteger(publication.sequence) || publication.sequence < 1 || Object.keys(publication).some((key2) => !["state", "sequence", "digest", "deletionWatermark", "activationAllowed"].includes(key2))) throw new Error("RECOVERY_TRANSFER_INVALID_RESPONSE");
36704
+ if (receipt2.kind === "LOCAL" ? publication !== void 0 : !publication || publication.state !== "PUBLISHED" || publication.activationAllowed !== false || publication.digest !== receipt2.manifestDigest || publication.deletionWatermark !== receipt2.deletionWatermark || !Number.isSafeInteger(publication.sequence) || publication.sequence < 1 || Object.keys(publication).some((key3) => !["state", "sequence", "digest", "deletionWatermark", "activationAllowed"].includes(key3))) throw new Error("RECOVERY_TRANSFER_INVALID_RESPONSE");
36547
36705
  ids.add(receipt2.id);
36548
36706
  }
36549
36707
  return value2;
@@ -36585,7 +36743,7 @@ function createRecoveryArchiveServer(options) {
36585
36743
  if (!identity3 || !fixedArchive && !resolveArchive || fixedArchive && resolveArchive) throw new Error("RECOVERY_TRANSFER_CONFIG");
36586
36744
  if (typeof assertAvailable !== "function" || !Number.isSafeInteger(bodyTimeoutMs) || bodyTimeoutMs < 10 || bodyTimeoutMs > 3e4) throw new Error("RECOVERY_TRANSFER_CONFIG");
36587
36745
  const peers = new Map(Object.entries(allowedPeers).map(([fingerprint2, credential]) => [fingerprint2.replaceAll(":", "").toLowerCase(), credential]));
36588
- if (!peers.size || [...peers.keys()].some((key2) => !/^[a-f0-9]{64}$/.test(key2))) throw new Error("RECOVERY_TRANSFER_CONFIG");
36746
+ if (!peers.size || [...peers.keys()].some((key3) => !/^[a-f0-9]{64}$/.test(key3))) throw new Error("RECOVERY_TRANSFER_CONFIG");
36589
36747
  const busy = /* @__PURE__ */ new Map();
36590
36748
  const server = createServer2({ ...tls2, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
36591
36749
  const started = Date.now(), timings = {};
@@ -36612,7 +36770,7 @@ function createRecoveryArchiveServer(options) {
36612
36770
  try {
36613
36771
  if (!socket.authorized || !credential) throw new Error();
36614
36772
  [principal] = await Promise.all([authority.authenticate(credential), assertAvailable()]);
36615
- if (["tenantId", "companionId", "seatId"].some((key2) => principal[key2] !== identity3[key2])) throw new Error();
36773
+ if (["tenantId", "companionId", "seatId"].some((key3) => principal[key3] !== identity3[key3])) throw new Error();
36616
36774
  } catch {
36617
36775
  refuse(403, "RECOVERY_TRANSFER_DENIED");
36618
36776
  req.resume();
@@ -36663,7 +36821,7 @@ function createRecoveryArchiveServer(options) {
36663
36821
  action = ["list", "read", "object", "objects", "parts", "stream", "manifests", "manifest-page"].includes(input?.action) ? input.action : "invalid";
36664
36822
  mark("resolve");
36665
36823
  if (input?.version === 1 && input.action === "list") {
36666
- if (Object.keys(input).some((key2) => !["version", "action"].includes(key2))) throw new Error();
36824
+ if (Object.keys(input).some((key3) => !["version", "action"].includes(key3))) throw new Error();
36667
36825
  const receipts = validateCatalog(await (listReceipts?.() ?? fixedArchive?.list({ maximum: 4096 }) ?? Promise.reject(new Error())));
36668
36826
  const [control3] = await Promise.all([authority.status(principal), assertAvailable()]), current2 = control3.deletionWatermark;
36669
36827
  if (receipts.some((receipt2) => receipt2.deletionWatermark < current2)) throw new Error();
@@ -36675,13 +36833,13 @@ function createRecoveryArchiveServer(options) {
36675
36833
  return;
36676
36834
  }
36677
36835
  const ancestry = ["manifests", "manifest-page"].includes(input?.action), paged = input?.action === "manifest-page";
36678
- if (!input || input.version !== 1 || !["read", "object", "objects", "parts", "stream", "manifests", "manifest-page"].includes(input.action) || !validId(input.id) || Object.keys(input).some((key2) => !["version", "action", "id", ...input.action === "object" ? ["ref"] : ["objects", "stream"].includes(input.action) ? ["refs"] : input.action === "parts" ? ["parts"] : ancestry ? ["common"] : []].includes(key2))) throw new Error();
36836
+ if (!input || input.version !== 1 || !["read", "object", "objects", "parts", "stream", "manifests", "manifest-page"].includes(input.action) || !validId(input.id) || Object.keys(input).some((key3) => !["version", "action", "id", ...input.action === "object" ? ["ref"] : ["objects", "stream"].includes(input.action) ? ["refs"] : input.action === "parts" ? ["parts"] : ancestry ? ["common"] : []].includes(key3))) throw new Error();
36679
36837
  await assertAvailable();
36680
36838
  if (ancestry && !validCommon(input.common)) throw new Error();
36681
36839
  const evidence = ancestry && readManifestEvidence ? await readManifestEvidence(input.id, input.common, paged ? 4 : void 0) : void 0;
36682
36840
  const archive = evidence ? void 0 : resolveArchive ? await resolveArchive(input.id) : fixedArchive;
36683
36841
  mark("entry");
36684
- if (archive && ["tenantId", "companionId", "seatId"].some((key2) => archive.objects.identity[key2] !== identity3[key2])) throw new Error();
36842
+ if (archive && ["tenantId", "companionId", "seatId"].some((key3) => archive.objects.identity[key3] !== identity3[key3])) throw new Error();
36685
36843
  const entry = evidence?.entry ?? await archive.read(input.id);
36686
36844
  if (entry.id !== input.id) throw new Error();
36687
36845
  if (archiveDigest) {
@@ -36951,7 +37109,7 @@ var RecoveryArchiveClient = class {
36951
37109
  try {
36952
37110
  const body2 = Buffer.concat(chunks), encoding = res.headers["content-encoding"];
36953
37111
  if (encoding !== void 0 && encoding !== "gzip" && encoding !== "br") throw new Error();
36954
- finish(void 0, encoding === "br" ? brotliDecompressSync(body2, { maxOutputLength: maximum }) : encoding === "gzip" ? gunzipSync3(body2, { maxOutputLength: maximum }) : body2);
37112
+ finish(void 0, encoding === "br" ? brotliDecompressSync(body2, { maxOutputLength: maximum }) : encoding === "gzip" ? gunzipSync4(body2, { maxOutputLength: maximum }) : body2);
36955
37113
  } catch {
36956
37114
  finish(new Error("RECOVERY_TRANSFER_INVALID_RESPONSE"));
36957
37115
  }
@@ -37407,7 +37565,7 @@ async function seedRuntimeReplica(options) {
37407
37565
  const identity3 = manifest.profile.identity, destination = resolve36(options.destination), dataDirectory = resolve36(options.dataDirectory);
37408
37566
  const check = async () => {
37409
37567
  const permit = await (options.permitSupplier?.() ?? options.permit);
37410
- if (!permit || ["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"].some((key2) => permit[key2] !== options.permit[key2])) throw new Error("TRAVEL_REPLICA_IDENTITY");
37568
+ if (!permit || ["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"].some((key3) => permit[key3] !== options.permit[key3])) throw new Error("TRAVEL_REPLICA_IDENTITY");
37411
37569
  const status = options.authority.assertPermitWithStatus ? await options.authority.assertPermitWithStatus(permit, "CONTROL") : (await options.authority.assertPermit(permit, "CONTROL"), await options.authority.status(options.principal));
37412
37570
  if (digest7 !== options.expectedDigest || manifest.sequence !== 1 || manifest.parentDigest !== "0".repeat(64)) throw new Error("TRAVEL_REPLICA_CHECKPOINT");
37413
37571
  if (status.checkpointDigest !== controlCheckpoint) await options.authority.verifyAncestor(options.principal, controlCheckpoint, String(status.checkpointDigest));
@@ -37680,7 +37838,7 @@ var RuntimeReplicaRepository = class _RuntimeReplicaRepository {
37680
37838
  this.assertOpen();
37681
37839
  const permit = await (request9.permitSupplier?.() ?? request9.permit);
37682
37840
  const status = request9.authority.assertPermitWithStatus ? await request9.authority.assertPermitWithStatus(permit, "CONTROL") : (await request9.authority.assertPermit(permit, "CONTROL"), await request9.authority.status(request9.principal));
37683
- if (["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"].some((key2) => permit[key2] !== request9.permit[key2]) || ["tenantId", "companionId", "seatId", "nodeId"].some((key2) => permit[key2] !== request9.principal[key2]) || JSON.stringify(entry.manifest.profile.identity) !== JSON.stringify(this.options.objects.identity) || entry.manifest.profile.epoch !== permit.epoch) throw new Error("TRAVEL_REPLICA_IDENTITY");
37841
+ if (["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"].some((key3) => permit[key3] !== request9.permit[key3]) || ["tenantId", "companionId", "seatId", "nodeId"].some((key3) => permit[key3] !== request9.principal[key3]) || JSON.stringify(entry.manifest.profile.identity) !== JSON.stringify(this.options.objects.identity) || entry.manifest.profile.epoch !== permit.epoch) throw new Error("TRAVEL_REPLICA_IDENTITY");
37684
37842
  if (status.deletionWatermark !== entry.manifest.deletionWatermark || this.options.deletionWatermark() !== entry.manifest.deletionWatermark) throw new Error("TRAVEL_REPLICA_DELETION_BARRIER");
37685
37843
  if (status.buildManifestId !== entry.manifest.profile.buildManifestId) throw new Error("TRAVEL_REPLICA_BUILD");
37686
37844
  };
@@ -38110,7 +38268,7 @@ async function compareRecoveryArchives(options) {
38110
38268
  if (readSchemaVersion(db2)?.component === "legacy-memory") loadLegacySQLiteVectorExtension(db2);
38111
38269
  db2.exec("PRAGMA temp_store=FILE; PRAGMA cache_size=-8192");
38112
38270
  db2.function("e7_recovery_key", { varargs: true, useBigIntArguments: true, deterministic: true }, (...cells) => JSON.stringify(cells.map(value)));
38113
- db2.function("e7_recovery_order", { deterministic: true }, (key2) => Buffer.from(String(key2), "utf16le").swap16().toString("hex"));
38271
+ db2.function("e7_recovery_order", { deterministic: true }, (key3) => Buffer.from(String(key3), "utf16le").swap16().toString("hex"));
38114
38272
  }
38115
38273
  const schemas = handles.map(tables);
38116
38274
  if (!same9(schemas[0], schemas[1]) || !same9(schemas[0], schemas[2])) throw new Error("RECOVERY_DIFF_SCHEMA_MISMATCH");
@@ -38118,10 +38276,10 @@ async function compareRecoveryArchives(options) {
38118
38276
  for (const table of schemas[0]) {
38119
38277
  await check();
38120
38278
  const records = handles.map((db2) => {
38121
- const key2 = "e7_recovery_key(" + table.keys.map(quote2).join(",") + ")";
38279
+ const key3 = "e7_recovery_key(" + table.keys.map(quote2).join(",") + ")";
38122
38280
  const sizes = table.columns.map((column) => "coalesce(length(CAST(" + quote2(column) + " AS BLOB)),0)").join("+");
38123
38281
  if (db2.prepare("SELECT 1 FROM " + quote2(table.name) + " WHERE (" + sizes + ")>16777216 LIMIT 1").get()) throw new Error("RECOVERY_DIFF_LIMIT");
38124
- const statement = db2.prepare("SELECT " + table.columns.map(quote2).join(",") + " FROM " + quote2(table.name) + " ORDER BY e7_recovery_order(" + key2 + ")");
38282
+ const statement = db2.prepare("SELECT " + table.columns.map(quote2).join(",") + " FROM " + quote2(table.name) + " ORDER BY e7_recovery_order(" + key3 + ")");
38125
38283
  statement.setReadBigInts(true);
38126
38284
  return statement.iterate()[Symbol.iterator]();
38127
38285
  });
@@ -38139,11 +38297,11 @@ async function compareRecoveryArchives(options) {
38139
38297
  try {
38140
38298
  const current2 = records.map((_, index) => next(index));
38141
38299
  while (current2.some(Boolean)) {
38142
- const key2 = current2.filter((row) => !!row).map((row) => row.key).sort()[0];
38143
- emit2({ databaseId, table: table.name, key: JSON.parse(key2) }, ...current2.map((row) => row?.key === key2 ? row.row : null));
38144
- for (let index = 0; index < current2.length; index++) if (current2[index]?.key === key2) {
38145
- if (previous[index] === key2) throw new Error("RECOVERY_DIFF_INVALID_KEY");
38146
- previous[index] = key2;
38300
+ const key3 = current2.filter((row) => !!row).map((row) => row.key).sort()[0];
38301
+ emit2({ databaseId, table: table.name, key: JSON.parse(key3) }, ...current2.map((row) => row?.key === key3 ? row.row : null));
38302
+ for (let index = 0; index < current2.length; index++) if (current2[index]?.key === key3) {
38303
+ if (previous[index] === key3) throw new Error("RECOVERY_DIFF_INVALID_KEY");
38304
+ previous[index] = key3;
38147
38305
  current2[index] = next(index);
38148
38306
  }
38149
38307
  if (scannedRecords % 128 === 0 || performance.now() - lastYield >= 25) {
@@ -38238,7 +38396,7 @@ function authReadinessHistory(body) {
38238
38396
  }
38239
38397
  for (const [id2, value2] of Object.entries(data.connections)) {
38240
38398
  providerId(id2);
38241
- if (!record(value2) || Object.keys(value2).some((key2) => !["status", "key"].includes(key2)) || !["connected", "pending", "not_connected", "disconnected", "expired", "denied", "failed"].includes(value2.status) || value2.key !== void 0 && typeof value2.key !== "string") return false;
38399
+ if (!record(value2) || Object.keys(value2).some((key3) => !["status", "key"].includes(key3)) || !["connected", "pending", "not_connected", "disconnected", "expired", "denied", "failed"].includes(value2.status) || value2.key !== void 0 && typeof value2.key !== "string") return false;
38242
38400
  }
38243
38401
  return true;
38244
38402
  } catch {
@@ -38266,12 +38424,12 @@ function schema4(db2, table) {
38266
38424
  if (!columns2.length || table.startsWith("e7_") || table.startsWith("sqlite_")) throw new Error("RECOVERY_UNSUPPORTED_TABLE");
38267
38425
  return { names: columns2.map((c) => String(c.name)), keys: columns2.filter((c) => Number(c.pk) > 0).sort((a, b) => Number(a.pk) - Number(b.pk)).map((c) => String(c.name)) };
38268
38426
  }
38269
- function read2(db2, table, key2, local) {
38427
+ function read2(db2, table, key3, local) {
38270
38428
  const s = schema4(db2, table);
38271
- if (!s.keys.length || key2.length !== s.keys.length || !same10(s.names.slice().sort(), Object.keys(local).sort())) throw new Error("RECOVERY_SCHEMA_MISMATCH");
38429
+ if (!s.keys.length || key3.length !== s.keys.length || !same10(s.names.slice().sort(), Object.keys(local).sort())) throw new Error("RECOVERY_SCHEMA_MISMATCH");
38272
38430
  const statement = db2.prepare("SELECT * FROM " + quote3(table) + " WHERE " + s.keys.map((k) => quote3(k) + "=?").join(" AND "));
38273
38431
  statement.setReadBigInts(true);
38274
- const row = statement.get(...key2.map(decode));
38432
+ const row = statement.get(...key3.map(decode));
38275
38433
  return row ? Object.fromEntries(s.names.map((k) => [k, encode(row[k])])) : null;
38276
38434
  }
38277
38435
  function executable(table) {
@@ -38309,8 +38467,8 @@ function socialReferences(db2, table, row, archived) {
38309
38467
  };
38310
38468
  const relation = (id2, version, historical = false) => {
38311
38469
  if (++budget > 4096) return null;
38312
- const key2 = JSON.stringify([id2, version]);
38313
- if (relationships.has(key2)) return null;
38470
+ const key3 = JSON.stringify([id2, version]);
38471
+ if (relationships.has(key3)) return null;
38314
38472
  const value2 = db2.prepare(`SELECT h.*,r.assertion_id,r.basis_refs,a.value_json,s.subject_id fact_subject,v.state
38315
38473
  FROM memory_relationship_versions r JOIN memory_relationship_heads h ON h.scope_id=r.scope_id AND h.relationship_id=r.relationship_id
38316
38474
  JOIN fact_assertions a ON a.scope_id=r.scope_id AND a.assertion_id=r.assertion_id
@@ -38320,14 +38478,14 @@ function socialReferences(db2, table, row, archived) {
38320
38478
  if (!value2 || !historical && Number(value2.semantic_version) !== version) return null;
38321
38479
  const semantic = JSON.parse(String(value2.value_json));
38322
38480
  if (semantic.relationshipId !== id2 || semantic.semanticVersion !== version || semantic.entityId !== value2.object_id || semantic.perspectiveEntityId !== value2.perspective_entity_id || value2.fact_subject !== value2.subject_id) return null;
38323
- relationships.add(key2);
38481
+ relationships.add(key3);
38324
38482
  try {
38325
38483
  if (!references(String(value2.basis_refs), historical)) return null;
38326
38484
  const evidence = db2.prepare("SELECT source_id FROM fact_evidence WHERE scope_id=? AND assertion_id=?").all(scope, value2.assertion_id);
38327
38485
  if (!evidence.length || !evidence.every((e) => source(String(e.source_id), historical))) return null;
38328
38486
  return value2;
38329
38487
  } finally {
38330
- relationships.delete(key2);
38488
+ relationships.delete(key3);
38331
38489
  }
38332
38490
  };
38333
38491
  const references = (json, historical = false) => {
@@ -38389,7 +38547,7 @@ function socialReferences(db2, table, row, archived) {
38389
38547
  }
38390
38548
  function nativeReferences(db2, table, row, common, branch, scopeProof, originalBinding, archived) {
38391
38549
  if (!socialReferences(db2, table, row, archived)) return false;
38392
- const text2 = (key2) => row[key2]?.[0] === "text" ? row[key2][1] : void 0;
38550
+ const text2 = (key3) => row[key3]?.[0] === "text" ? row[key3][1] : void 0;
38393
38551
  const scope = text2("scope_id");
38394
38552
  let refs2 = [];
38395
38553
  if (table === "entity_bindings") {
@@ -38697,7 +38855,7 @@ function recoveryScopeProof(db2, common, candidates, branch, originalBinding) {
38697
38855
  if (mapped && Number(mapped.current_value) !== currentVersion) return false;
38698
38856
  for (const table of tables2) {
38699
38857
  if (!common.prepare("SELECT 1 FROM sqlite_master WHERE name=?").get(table) || !db2.prepare("SELECT 1 FROM sqlite_master WHERE name=?").get(table)) return false;
38700
- const info = schema4(common, table), identity3 = JSON.stringify([scope, table, parent === "context"]), key2 = (row) => JSON.stringify(info.keys.map((field) => row[field]));
38858
+ const info = schema4(common, table), identity3 = JSON.stringify([scope, table, parent === "context"]), key3 = (row) => JSON.stringify(info.keys.map((field) => row[field]));
38701
38859
  let expected = originals.get(identity3);
38702
38860
  if (!expected) {
38703
38861
  expected = /* @__PURE__ */ new Map();
@@ -38705,7 +38863,7 @@ function recoveryScopeProof(db2, common, candidates, branch, originalBinding) {
38705
38863
  const statement2 = common.prepare("SELECT * FROM " + quote3(table) + " WHERE scope_id=?");
38706
38864
  statement2.setReadBigInts(true);
38707
38865
  for (const value2 of statement2.iterate(scope)) {
38708
- const row = Object.fromEntries(Object.entries(value2).map(([k, v]) => [k, encode(v)])), id2 = key2(row), item = proof(table, row, parent === "context");
38866
+ const row = Object.fromEntries(Object.entries(value2).map(([k, v]) => [k, encode(v)])), id2 = key3(row), item = proof(table, row, parent === "context");
38709
38867
  bytes += Buffer.byteLength(id2) + Buffer.byteLength(JSON.stringify(item));
38710
38868
  if (expected.size >= 1e5 || bytes > 64 * 1024 * 1024) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
38711
38869
  expected.set(id2, { ...item, baseline: item.positions });
@@ -38723,7 +38881,7 @@ function recoveryScopeProof(db2, common, candidates, branch, originalBinding) {
38723
38881
  const statement = db2.prepare("SELECT * FROM " + quote3(table) + " WHERE scope_id=?");
38724
38882
  statement.setReadBigInts(true);
38725
38883
  for (const value2 of statement.iterate(scope)) {
38726
- const row = Object.fromEntries(Object.entries(value2).map(([k, v]) => [k, encode(v)])), original = expected.get(key2(row));
38884
+ const row = Object.fromEntries(Object.entries(value2).map(([k, v]) => [k, encode(v)])), original = expected.get(key3(row));
38727
38885
  if (!original || original.digest !== proof(table, row, parent === "context", true).digest) return false;
38728
38886
  for (const [field, position] of Object.entries(original.positions)) {
38729
38887
  let projected = position;
@@ -38745,7 +38903,7 @@ function sessionRecovery(db2, common, candidates, branch) {
38745
38903
  const originalTables = /* @__PURE__ */ new Map();
38746
38904
  const originalRows = (table) => {
38747
38905
  if (originalTables.has(table)) return originalTables.get(table);
38748
- const keys = schema4(common, table).keys, key2 = (row) => JSON.stringify(keys.map((k) => row[k]));
38906
+ const keys = schema4(common, table).keys, key3 = (row) => JSON.stringify(keys.map((k) => row[k]));
38749
38907
  const s = common.prepare("SELECT * FROM " + quote3(table));
38750
38908
  s.setReadBigInts(true);
38751
38909
  const rows = /* @__PURE__ */ new Map();
@@ -38754,10 +38912,10 @@ function sessionRecovery(db2, common, candidates, branch) {
38754
38912
  const row = Object.fromEntries(Object.entries(value2).map(([k, v]) => [k, encode(v)]));
38755
38913
  bytes += Buffer.byteLength(JSON.stringify(row));
38756
38914
  if (rows.size >= 1e5 || bytes > 64 * 1024 * 1024) throw new Error("RECOVERY_DEPENDENCY_BUDGET");
38757
- rows.set(key2(row), row);
38915
+ rows.set(key3(row), row);
38758
38916
  }
38759
38917
  for (const item of candidates.filter((i) => i.table === table)) {
38760
- if (item.local) rows.set(key2(item.local), item.local);
38918
+ if (item.local) rows.set(key3(item.local), item.local);
38761
38919
  else rows.delete(JSON.stringify(item.key));
38762
38920
  }
38763
38921
  const result = [...rows.values()];
@@ -38832,20 +38990,20 @@ function supersededRecords(db2, common, candidates) {
38832
38990
  list.push(item);
38833
38991
  byTable.set(item.table, list);
38834
38992
  }
38835
- const text2 = (row, k) => row[k]?.[0] === "text" ? row[k][1] : void 0, key2 = (scope, id2) => JSON.stringify([scope, id2]);
38993
+ const text2 = (row, k) => row[k]?.[0] === "text" ? row[k][1] : void 0, key3 = (scope, id2) => JSON.stringify([scope, id2]);
38836
38994
  const originalSources = /* @__PURE__ */ new Map(), evidence = /* @__PURE__ */ new Map();
38837
38995
  for (const item of byTable.get("memory_sources") ?? []) {
38838
38996
  const row = item.local;
38839
- originalSources.set(key2(text2(row, "scope_id"), text2(row, "source_id")), row);
38997
+ originalSources.set(key3(text2(row, "scope_id"), text2(row, "source_id")), row);
38840
38998
  }
38841
38999
  for (const item of byTable.get("fact_evidence") ?? []) {
38842
- const row = item.local, id2 = key2(text2(row, "scope_id"), text2(row, "assertion_id")), list = evidence.get(id2) ?? [];
39000
+ const row = item.local, id2 = key3(text2(row, "scope_id"), text2(row, "assertion_id")), list = evidence.get(id2) ?? [];
38843
39001
  list.push(row);
38844
39002
  evidence.set(id2, list);
38845
39003
  }
38846
39004
  const olderSources = /* @__PURE__ */ new Map(), historicalFacts = /* @__PURE__ */ new Set(), historicalSlots = /* @__PURE__ */ new Set(), artifacts = /* @__PURE__ */ new Set();
38847
39005
  const older = (scope, id2) => {
38848
- const identity3 = key2(scope, id2);
39006
+ const identity3 = key3(scope, id2);
38849
39007
  if (olderSources.has(identity3)) return true;
38850
39008
  let row = originalSources.get(identity3);
38851
39009
  if (!row) {
@@ -38864,7 +39022,7 @@ function supersededRecords(db2, common, candidates) {
38864
39022
  };
38865
39023
  for (const item of byTable.get("fact_assertions") ?? []) {
38866
39024
  const row = item.local, scope = text2(row, "scope_id"), id2 = text2(row, "assertion_id"), slot = text2(row, "slot_id");
38867
- const refs2 = (evidence.get(key2(scope, id2)) ?? []).filter((row2) => row2.relation?.[1] === "supports");
39025
+ const refs2 = (evidence.get(key3(scope, id2)) ?? []).filter((row2) => row2.relation?.[1] === "supports");
38868
39026
  if (!refs2.length || !refs2.every((ref) => older(scope, text2(ref, "source_id")))) continue;
38869
39027
  const current2 = db2.prepare(`SELECT s.source_id,s.origin_key,s.source_version,s.actor_id,s.text,e.span_start,e.span_end,e.quote FROM fact_assertions a
38870
39028
  JOIN fact_versions v ON v.scope_id=a.scope_id AND v.assertion_id=a.assertion_id JOIN fact_evidence e ON e.scope_id=a.scope_id AND e.assertion_id=a.assertion_id
@@ -38873,22 +39031,22 @@ function supersededRecords(db2, common, candidates) {
38873
39031
  if (current2.some((source) => {
38874
39032
  if (String(source.text).slice(Number(source.span_start), Number(source.span_end)) !== source.quote) return false;
38875
39033
  if (!refs2.every((ref) => {
38876
- const old = olderSources.get(key2(scope, text2(ref, "source_id")));
39034
+ const old = olderSources.get(key3(scope, text2(ref, "source_id")));
38877
39035
  return decode(old.origin_key) === source.origin_key && decode(old.actor_id) === source.actor_id && Number(decode(old.source_version)) < Number(source.source_version);
38878
39036
  })) return false;
38879
39037
  return !!db2.prepare(`SELECT 1 FROM fact_changes c,json_each(c.proposal_json,'$.evidence') e WHERE c.scope_id=?
38880
39038
  AND json_extract(c.result_json,'$.slotId')=? AND json_extract(c.proposal_json,'$.changeKind')='correction'
38881
39039
  AND json_extract(e.value,'$.sourceId')=? AND json_extract(e.value,'$.quote')=?`).get(scope, slot, source.source_id, source.quote);
38882
39040
  })) {
38883
- historicalFacts.add(key2(scope, id2));
38884
- historicalSlots.add(key2(scope, slot));
39041
+ historicalFacts.add(key3(scope, id2));
39042
+ historicalSlots.add(key3(scope, slot));
38885
39043
  }
38886
39044
  }
38887
39045
  for (let progress = true; progress; ) {
38888
39046
  progress = false;
38889
39047
  for (const item of byTable.get("memory_dependencies") ?? []) {
38890
- const row = item.local, scope = text2(row, "scope_id"), kind = text2(row, "parent_kind"), parent = text2(row, "parent_id"), child = key2(scope, text2(row, "child_id"));
38891
- if (kind === "source" && older(scope, parent) || kind === "fact" && historicalFacts.has(key2(scope, parent)) || kind === "artifact" && artifacts.has(key2(scope, parent))) {
39048
+ const row = item.local, scope = text2(row, "scope_id"), kind = text2(row, "parent_kind"), parent = text2(row, "parent_id"), child = key3(scope, text2(row, "child_id"));
39049
+ if (kind === "source" && older(scope, parent) || kind === "fact" && historicalFacts.has(key3(scope, parent)) || kind === "artifact" && artifacts.has(key3(scope, parent))) {
38892
39050
  if (!artifacts.has(child)) {
38893
39051
  artifacts.add(child);
38894
39052
  progress = true;
@@ -38900,7 +39058,7 @@ function supersededRecords(db2, common, candidates) {
38900
39058
  const scope = text2(row, "scope_id");
38901
39059
  if (!scope) return false;
38902
39060
  const fact = text2(row, "assertion_id"), artifact = text2(row, "artifact_id") ?? text2(row, "child_id") ?? text2(row, "entry_id");
38903
- return !!fact && historicalFacts.has(key2(scope, fact)) || !!artifact && artifacts.has(key2(scope, artifact)) || item.table === "fact_slots" && historicalSlots.has(key2(scope, text2(row, "slot_id")));
39061
+ return !!fact && historicalFacts.has(key3(scope, fact)) || !!artifact && artifacts.has(key3(scope, artifact)) || item.table === "fact_slots" && historicalSlots.has(key3(scope, text2(row, "slot_id")));
38904
39062
  };
38905
39063
  }
38906
39064
  async function admitRecoveryArchives(options) {
@@ -39038,9 +39196,9 @@ async function admitRecoveryArchives(options) {
39038
39196
  return value2 ? Object.fromEntries(Object.entries(value2).map(([k, v]) => [k, encode(v)])) : null;
39039
39197
  };
39040
39198
  const priorRow = (table, current2) => {
39041
- const key2 = schema4(store.db, table).keys.map((field) => current2[field]);
39199
+ const key3 = schema4(store.db, table).keys.map((field) => current2[field]);
39042
39200
  for (const digest7 of chain.slice(1)) {
39043
- const id2 = hash8(JSON.stringify([digest7, databaseId, table, key2]));
39201
+ const id2 = hash8(JSON.stringify([digest7, databaseId, table, key3]));
39044
39202
  const saved = store.db.prepare("SELECT original_hash,result FROM e7_recovery_items WHERE item_id=?").get(id2);
39045
39203
  if (!saved) continue;
39046
39204
  const item = JSON.parse(String(saved.result)), original = item.local;
@@ -39080,8 +39238,8 @@ async function admitRecoveryArchives(options) {
39080
39238
  const historical = supersededRecords(store.db, commonDatabases.get(databaseId), candidates);
39081
39239
  const bindingCache = /* @__PURE__ */ new Map();
39082
39240
  const originalBinding = (row) => {
39083
- const scope = decode(row.scope_id), target = JSON.stringify([decode(row.namespace), decode(row.external_id)]), key2 = JSON.stringify([scope, target]);
39084
- if (bindingCache.has(key2)) return bindingCache.get(key2);
39241
+ const scope = decode(row.scope_id), target = JSON.stringify([decode(row.namespace), decode(row.external_id)]), key3 = JSON.stringify([scope, target]);
39242
+ if (bindingCache.has(key3)) return bindingCache.get(key3);
39085
39243
  const commonDb = commonDatabases.get(databaseId), exists = commonDb.prepare("SELECT 1 FROM sqlite_master WHERE name='memory_knowledge_history'").get();
39086
39244
  if (!exists) return null;
39087
39245
  const statement = commonDb.prepare("SELECT * FROM memory_knowledge_history WHERE scope_id=? AND target_kind='binding' AND target_id=? ORDER BY history_id DESC LIMIT 1");
@@ -39092,7 +39250,7 @@ async function admitRecoveryArchives(options) {
39092
39250
  const history = item.local;
39093
39251
  if (decode(history.scope_id) === scope && decode(history.target_kind) === "binding" && decode(history.target_id) === target && (!latest || BigInt(String(decode(history.history_id))) > BigInt(String(decode(latest.history_id))))) latest = history;
39094
39252
  }
39095
- bindingCache.set(key2, latest);
39253
+ bindingCache.set(key3, latest);
39096
39254
  return latest;
39097
39255
  };
39098
39256
  const scopeProof = recoveryScopeProof(store.db, commonDatabases.get(databaseId), candidates, local.receipt.manifestDigest, originalBinding);
@@ -39441,12 +39599,12 @@ async function projectRecoveryArtifacts(options) {
39441
39599
  };
39442
39600
  try {
39443
39601
  validateProjection();
39444
- const sessions = openSessionEvents(root);
39445
- if (!sessions) throw new Error("RECOVERY_CURRENT_LAYOUT");
39602
+ const sessions2 = openSessionEvents(root);
39603
+ if (!sessions2) throw new Error("RECOVERY_CURRENT_LAYOUT");
39446
39604
  try {
39447
- sessions.projectAll();
39605
+ sessions2.projectAll();
39448
39606
  } finally {
39449
- sessions.close();
39607
+ sessions2.close();
39450
39608
  }
39451
39609
  state2 = "HISTORY";
39452
39610
  reason = "original_session_history_projected";
@@ -39697,7 +39855,7 @@ async function verifyStoppedLocalExitProof(options) {
39697
39855
  }
39698
39856
  const { digest: digest7, ...body } = proof;
39699
39857
  const binding = await currentBinding(options.stateDir, options.authority, options.principal);
39700
- if (proof.format !== "engine7-stopped-local-exit-v1" || digest7 !== hash9(JSON.stringify(body)) || proof.checkpointDigest !== options.checkpointDigest || Object.entries(binding).some(([key2, value2]) => proof[key2] !== value2) || proof.filesDigest !== await localExitFilesDigest(options.stateDir)) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
39858
+ if (proof.format !== "engine7-stopped-local-exit-v1" || digest7 !== hash9(JSON.stringify(body)) || proof.checkpointDigest !== options.checkpointDigest || Object.entries(binding).some(([key3, value2]) => proof[key3] !== value2) || proof.filesDigest !== await localExitFilesDigest(options.stateDir)) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
39701
39859
  return { binding, filesDigest: String(proof.filesDigest), check: async () => {
39702
39860
  if (!equal2(binding, await currentBinding(options.stateDir, options.authority, options.principal)) || proof.filesDigest !== await localExitFilesDigest(options.stateDir)) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
39703
39861
  } };
@@ -39934,10 +40092,10 @@ var TravelNodeAgent = class _TravelNodeAgent {
39934
40092
  await this.refreshKey();
39935
40093
  await this.assertDataAvailable();
39936
40094
  if (token !== this.generationToken) throw new Error("TRAVEL_NODE_CANCELLED");
39937
- const key2 = Buffer.from(input.key);
40095
+ const key3 = Buffer.from(input.key);
39938
40096
  let server;
39939
40097
  try {
39940
- server = await createTravelNodeDataServer({ node: this, authority: this.options.authority, ...input, key: key2 });
40098
+ server = await createTravelNodeDataServer({ node: this, authority: this.options.authority, ...input, key: key3 });
39941
40099
  await new Promise((resolveListen, rejectListen) => {
39942
40100
  server.once("error", rejectListen);
39943
40101
  server.listen(input.port, input.host, () => {
@@ -39949,7 +40107,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
39949
40107
  const address = server.address();
39950
40108
  if (!address || typeof address === "string") throw new Error("TRAVEL_NODE_LISTENER_CONFIG");
39951
40109
  this.dataServer = server;
39952
- this.dataServerKey = key2;
40110
+ this.dataServerKey = key3;
39953
40111
  this.dataServerBinding = binding;
39954
40112
  return this.dataServerAddress = { host: input.host, port: address.port };
39955
40113
  } catch (error) {
@@ -39957,7 +40115,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
39957
40115
  server.closeAllConnections();
39958
40116
  await new Promise((resolveClose) => server.close(() => resolveClose()));
39959
40117
  }
39960
- key2.fill(0);
40118
+ key3.fill(0);
39961
40119
  throw error;
39962
40120
  }
39963
40121
  });
@@ -40479,7 +40637,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
40479
40637
  const boundedCheck = async () => {
40480
40638
  localCheck();
40481
40639
  const permit = currentPermit;
40482
- if (["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"].some((key2) => permit[key2] !== request9.permit[key2]) || ["tenantId", "companionId", "seatId", "nodeId"].some((key2) => permit[key2] !== request9.principal[key2]) || request9.principal.nodeId === this.principal.nodeId || ["tenantId", "companionId", "seatId"].some((key2) => request9.principal[key2] !== this.principal[key2])) throw new Error("TRAVEL_NODE_IDENTITY");
40640
+ if (["tenantId", "companionId", "seatId", "nodeId", "bootId", "authorityBootId", "epoch"].some((key3) => permit[key3] !== request9.permit[key3]) || ["tenantId", "companionId", "seatId", "nodeId"].some((key3) => permit[key3] !== request9.principal[key3]) || request9.principal.nodeId === this.principal.nodeId || ["tenantId", "companionId", "seatId"].some((key3) => request9.principal[key3] !== this.principal[key3])) throw new Error("TRAVEL_NODE_IDENTITY");
40483
40641
  const authority = this.options.authority, status = authority.assertPermitWithStatus ? await authority.assertPermitWithStatus(permit, "CONTROL") : (await authority.assertPermit(permit, "CONTROL"), await authority.status(this.principal));
40484
40642
  localCheck();
40485
40643
  if (status.expired || status.authorityBootId !== permit.authorityBootId || status.epoch !== permit.epoch || status.activeNodeId !== permit.nodeId || status.activeBootId !== permit.bootId) throw new Error("TRAVEL_NODE_CHECKPOINT");
@@ -41464,12 +41622,12 @@ var RemoteTravelNodeAuthority = class _RemoteTravelNodeAuthority extends RemoteT
41464
41622
  assertPermitWithStatus(...[permit, operation]) {
41465
41623
  const grant = this.nodeGrants.find((value2) => ["tenantId", "companionId", "seatId", "nodeId"].every((field) => permit[field] === value2.principal[field]));
41466
41624
  if (!grant) return Promise.reject(new Error("TRAVEL_AUTH_DENIED"));
41467
- const key2 = JSON.stringify([permit, operation]), pending = this.permitReads.get(key2);
41625
+ const key3 = JSON.stringify([permit, operation]), pending = this.permitReads.get(key3);
41468
41626
  if (pending) return pending;
41469
41627
  const read3 = grant.client.assertPermitWithStatus(permit, operation).then((current2) => current2 === void 0 ? this.status(grant.principal) : current2).finally(() => {
41470
- this.permitReads.delete(key2);
41628
+ this.permitReads.delete(key3);
41471
41629
  });
41472
- this.permitReads.set(key2, read3);
41630
+ this.permitReads.set(key3, read3);
41473
41631
  return read3;
41474
41632
  }
41475
41633
  async handoffStatus(principal, id2) {
@@ -41944,7 +42102,7 @@ var fields2 = {
41944
42102
  synchronize: []
41945
42103
  };
41946
42104
  function exact(value2, allowed, required = allowed) {
41947
- return Object.keys(value2).every((key2) => allowed.includes(key2)) && required.every((key2) => Object.hasOwn(value2, key2));
42105
+ return Object.keys(value2).every((key3) => allowed.includes(key3)) && required.every((key3) => Object.hasOwn(value2, key3));
41948
42106
  }
41949
42107
  var digest6 = (value2) => typeof value2 === "string" && /^[a-f0-9]{64}$/.test(value2);
41950
42108
  function validNodeSupervisorInput(value2) {
@@ -41953,7 +42111,7 @@ function validNodeSupervisorInput(value2) {
41953
42111
  if (!exact(value2, ["version", "nodeId", "bootId", "action", ...required, ...optional], ["version", "nodeId", "action", ...required])) return false;
41954
42112
  if (value2.action !== "observe" && !nodeSupervisorId(value2.bootId) || Object.hasOwn(value2, "bootId") && !nodeSupervisorId(value2.bootId)) return false;
41955
42113
  if (Object.hasOwn(value2, "checkpointDigest") && !digest6(value2.checkpointDigest) || Object.hasOwn(value2, "transferId") && !nodeSupervisorId(value2.transferId)) return false;
41956
- for (const key2 of ["permit", "expectedSource"]) if (Object.hasOwn(value2, key2) && !nodeSupervisorRecord(value2[key2])) return false;
42114
+ for (const key3 of ["permit", "expectedSource"]) if (Object.hasOwn(value2, key3) && !nodeSupervisorRecord(value2[key3])) return false;
41957
42115
  if (value2.action === "connectReplica") {
41958
42116
  const profile = value2.profile;
41959
42117
  if (!nodeSupervisorRecord(profile) || !exact(profile, ["identity", "baselineId", "epoch", "buildManifestId", "databaseIds", "trees"]) || !nodeSupervisorRecord(profile.identity) || !exact(profile.identity, ["tenantId", "companionId", "seatId"]) || !Array.isArray(profile.trees) || profile.trees.some((tree) => !nodeSupervisorRecord(tree) || !exact(tree, ["id", "kind"]))) return false;
@@ -42101,7 +42259,7 @@ var RemoteTravelNodeSupervisor = class {
42101
42259
  return this.observeQuery ??= (async () => {
42102
42260
  try {
42103
42261
  const result = await this.call("observe", {}, true);
42104
- if (!result || ["connected", "running", "busy"].some((key2) => typeof result[key2] !== "boolean")) throw new Error("TRAVEL_NODE_INVALID_RESPONSE");
42262
+ if (!result || ["connected", "running", "busy"].some((key3) => typeof result[key3] !== "boolean")) throw new Error("TRAVEL_NODE_INVALID_RESPONSE");
42105
42263
  return { connected: result.connected, running: result.running, busy: result.busy };
42106
42264
  } catch {
42107
42265
  return { connected: false, running: false, busy: false };
@@ -42172,8 +42330,8 @@ function createTravelNodeSupervisorServer(options) {
42172
42330
  const { node, bootId: bootId2, managementFingerprints, authorize, peer, bodyTimeoutMs = 5e3, ...tls2 } = options;
42173
42331
  const fingerprints = new Set(managementFingerprints.map((value2) => value2.replaceAll(":", "").toLowerCase()));
42174
42332
  if (!nodeSupervisorId(bootId2) || !fingerprints.size || [...fingerprints].some((value2) => !/^[a-f0-9]{64}$/.test(value2)) || !Number.isSafeInteger(bodyTimeoutMs) || bodyTimeoutMs < 100 || bodyTimeoutMs > 3e4) throw new Error("TRAVEL_NODE_LISTENER_CONFIG");
42175
- const samePrincipal = (principal) => ["tenantId", "companionId", "seatId", "nodeId", "role", "credentialHash"].every((key2) => principal[key2] === node.principal[key2]);
42176
- if (peer && (peer.principal.nodeId === node.principal.nodeId || ["tenantId", "companionId", "seatId"].some((key2) => peer.principal[key2] !== node.principal[key2]))) throw new Error("TRAVEL_NODE_LISTENER_IDENTITY");
42333
+ const samePrincipal = (principal) => ["tenantId", "companionId", "seatId", "nodeId", "role", "credentialHash"].every((key3) => principal[key3] === node.principal[key3]);
42334
+ if (peer && (peer.principal.nodeId === node.principal.nodeId || ["tenantId", "companionId", "seatId"].some((key3) => peer.principal[key3] !== node.principal[key3]))) throw new Error("TRAVEL_NODE_LISTENER_IDENTITY");
42177
42335
  const active = { read: 0, operation: 0, stop: 0 };
42178
42336
  const server = createServer6({ ...tls2, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
42179
42337
  res.setHeader("Content-Type", "application/json");
@@ -42269,7 +42427,7 @@ function createTravelNodeSupervisorServer(options) {
42269
42427
  break;
42270
42428
  case "bootstrapReplica": {
42271
42429
  const request9 = input.request;
42272
- if (!peer || !node.bootstrapReplica || ["tenantId", "companionId", "seatId", "nodeId", "role", "credentialHash"].some((key2) => request9.principal[key2] !== peer.principal[key2])) throw new Error("TRAVEL_NODE_IDENTITY");
42430
+ if (!peer || !node.bootstrapReplica || ["tenantId", "companionId", "seatId", "nodeId", "role", "credentialHash"].some((key3) => request9.principal[key3] !== peer.principal[key3])) throw new Error("TRAVEL_NODE_IDENTITY");
42273
42431
  await node.bootstrapReplica({ ...request9, permitSupplier: () => peer.permit() });
42274
42432
  break;
42275
42433
  }
@@ -42494,7 +42652,7 @@ var travelConsoleErrors = /* @__PURE__ */ new Set(["invalid_action", "invalid_re
42494
42652
 
42495
42653
  // src/continuity/console-server.ts
42496
42654
  var travelConsolePath = "/travel/console/v1";
42497
- var exact2 = (record, allowed) => Object.keys(record).every((key2) => allowed.includes(key2));
42655
+ var exact2 = (record, allowed) => Object.keys(record).every((key3) => allowed.includes(key3));
42498
42656
  var shutdowns = /* @__PURE__ */ new WeakMap();
42499
42657
  function closeTravelConsoleServer(server) {
42500
42658
  const close = shutdowns.get(server);
@@ -42566,7 +42724,7 @@ function createTravelConsoleServer(options) {
42566
42724
  return;
42567
42725
  }
42568
42726
  const requestIdentity = input.identity, action = String(input.action);
42569
- if (["tenantId", "companionId", "seatId"].some((key2) => requestIdentity[key2] !== identity3[key2])) {
42727
+ if (["tenantId", "companionId", "seatId"].some((key3) => requestIdentity[key3] !== identity3[key3])) {
42570
42728
  reply(403, { ok: false, error: "wrong_partner" });
42571
42729
  return;
42572
42730
  }
@@ -42717,7 +42875,7 @@ import { readFileSync as readFileSync35, existsSync as existsSync41 } from "node
42717
42875
  import { isAbsolute as isAbsolute16, resolve as resolve45 } from "node:path";
42718
42876
  import { fileURLToPath as fileURLToPath8 } from "node:url";
42719
42877
  import { execFile as execFile4 } from "node:child_process";
42720
- import { promisify as promisify4 } from "node:util";
42878
+ import { promisify as promisify5 } from "node:util";
42721
42879
  import { createHash as createHash54 } from "node:crypto";
42722
42880
 
42723
42881
  // src/continuity/user-seat-resource.ts
@@ -43115,7 +43273,7 @@ async function createOrdinaryLocalRecovery(options) {
43115
43273
  // src/continuity/retirement-main.ts
43116
43274
  init_key_service_store();
43117
43275
  init_key_service_store();
43118
- var command = promisify4(execFile4);
43276
+ var command = promisify5(execFile4);
43119
43277
  var sha14 = (value2) => createHash54("sha256").update(value2).digest("hex");
43120
43278
  var path36 = (value2) => {
43121
43279
  if (typeof value2 !== "string" || !isAbsolute16(value2) || resolve45(value2) !== value2) throw new Error("TRAVEL_RETIREMENT_PATH");
@@ -43452,7 +43610,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
43452
43610
  let baseline;
43453
43611
  if (!existsSync42(join73(baselineDir, "ready.json"))) {
43454
43612
  if (existsSync42(baselineDir)) renameSync12(baselineDir, join73(directory2, "failed-baseline-" + randomUUID23()));
43455
- const key2 = readPrivateFile(join73(directory2, "data.key"), 32);
43613
+ const key3 = readPrivateFile(join73(directory2, "data.key"), 32);
43456
43614
  let lastProgressSave = 0, lastPhase = "";
43457
43615
  try {
43458
43616
  await runInitialBaselineWorker({ stateDir: material.stateDir, workspace: material.workspace, selection: material.layout.inventorySelection, directory: baselineDir, objectsDirectory: join73(localConfig().directory, "data", "objects"), keyFile: join73(directory2, "data.key"), identity: material.identity, engineVersion: JSON.parse(readFileSync36(join73(material.engineDir, "package.json"), "utf8")).version, buildManifestId: material.buildManifestId }, (progress) => {
@@ -43471,7 +43629,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
43471
43629
  if (stopped) throw new Error("TRAVEL_INITIAL_CANCELLED");
43472
43630
  });
43473
43631
  } finally {
43474
- key2.fill(0);
43632
+ key3.fill(0);
43475
43633
  }
43476
43634
  }
43477
43635
  await baseline?.close();