engine7 7.1.147 → 7.1.149

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4261,6 +4261,45 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
4261
4261
  }
4262
4262
  });
4263
4263
 
4264
+ // src/mem7/core/state/watermarks.ts
4265
+ function readRetractionSeq(db2, scope) {
4266
+ return Number(db2.prepare(`SELECT COALESCE(MAX(event_seq),0) seq FROM memory_state_outbox WHERE scope_id=? AND ${RETRACTED}`).get(scope)?.seq ?? 0);
4267
+ }
4268
+ function readRetractionsSince(db2, scope, sinceSeq) {
4269
+ return db2.prepare(`SELECT event_seq, payload_json FROM memory_state_outbox WHERE scope_id=? AND ${RETRACTED} AND event_seq>? ORDER BY event_seq`).all(scope, sinceSeq).map((row) => {
4270
+ const payload = JSON.parse(row.payload_json);
4271
+ const aggregate = !payload.targetKind || payload.targetKind === "source" ? [payload.aggregateId] : [];
4272
+ return { eventSeq: Number(row.event_seq), sourceIds: [.../* @__PURE__ */ new Set([...payload.sourceIds ?? [], ...aggregate])].filter((id2) => Boolean(id2)) };
4273
+ });
4274
+ }
4275
+ function readSourceSeq(db2, scope, sourceId) {
4276
+ const row = db2.prepare("SELECT source_seq FROM memory_sources WHERE scope_id=? AND source_id=?").get(scope, sourceId);
4277
+ return row && Number.isSafeInteger(row.source_seq) ? Number(row.source_seq) : null;
4278
+ }
4279
+ function deletionHits(db2, scope, events, sourceWatermark, sourceSeqs) {
4280
+ return events.some((event2) => event2.sourceIds.some((id2) => {
4281
+ const key3 = JSON.stringify([scope, id2]);
4282
+ if (!sourceSeqs.has(key3)) sourceSeqs.set(key3, readSourceSeq(db2, scope, id2));
4283
+ const seq = sourceSeqs.get(key3);
4284
+ return seq === null || seq <= sourceWatermark;
4285
+ }));
4286
+ }
4287
+ function deletedWithinView(db2, scope, sinceSeq, sourceWatermark, cache2) {
4288
+ if (!cache2.latest.has(scope)) cache2.latest.set(scope, readRetractionSeq(db2, scope));
4289
+ if (cache2.latest.get(scope) <= sinceSeq) return false;
4290
+ const key3 = JSON.stringify([scope, sinceSeq]);
4291
+ if (!cache2.events.has(key3)) cache2.events.set(key3, readRetractionsSince(db2, scope, sinceSeq));
4292
+ return deletionHits(db2, scope, cache2.events.get(key3), sourceWatermark, cache2.sourceSeqs);
4293
+ }
4294
+ var emptyRetractionCache, RETRACTED;
4295
+ var init_watermarks = __esm({
4296
+ "src/mem7/core/state/watermarks.ts"() {
4297
+ "use strict";
4298
+ emptyRetractionCache = () => ({ latest: /* @__PURE__ */ new Map(), events: /* @__PURE__ */ new Map(), sourceSeqs: /* @__PURE__ */ new Map() });
4299
+ RETRACTED = `kind IN ('evidence.retracted','memory.deleted')`;
4300
+ }
4301
+ });
4302
+
4264
4303
  // src/mem7/core/state/predicates.ts
4265
4304
  function hasReportedAttribution(text2, value2, mentions) {
4266
4305
  const ref = value2.attributionQuote;
@@ -4374,6 +4413,7 @@ var init_source_store = __esm({
4374
4413
  init_dependencies();
4375
4414
  init_knowledge_history();
4376
4415
  init_read_budget();
4416
+ init_watermarks();
4377
4417
  init_interpretation_impact();
4378
4418
  init_conversation_text();
4379
4419
  SOURCE_SCHEMA = `
@@ -4704,6 +4744,20 @@ CREATE TABLE IF NOT EXISTS memory_source_aliases (
4704
4744
  const row = this.db.prepare("SELECT fact_revision,source_seq,interpreted_seq FROM memory_scopes WHERE scope_id=?").get(scopeId(scope));
4705
4745
  return { factRevision: Number(row?.fact_revision ?? 0), sourceSeq: Number(row?.source_seq ?? 0), interpretedSeq: Number(row?.interpreted_seq ?? 0) };
4706
4746
  }
4747
+ /** Latest deletion or retraction event of the scope; 0 when none ever happened. */
4748
+ retractionSeq(scope) {
4749
+ return readRetractionSeq(this.db, scopeId(scope));
4750
+ }
4751
+ /** Sequence of a source whatever its status. get() hides deleted sources; this does not. */
4752
+ sourceSeqOf(scope, sourceId) {
4753
+ return readSourceSeq(this.db, scopeId(scope), sourceId);
4754
+ }
4755
+ /** A deletion after `sinceSeq` removed a source the node could have seen. One indexed lookup per scope
4756
+ * for the latest deletion, then one event query per (scope, watermark) per cache. */
4757
+ deletedWithinView(scope, sinceSeq, sourceWatermark, cache2) {
4758
+ checkMemoryReadBudget();
4759
+ return deletedWithinView(this.db, scopeId(scope), sinceSeq, sourceWatermark, cache2);
4760
+ }
4707
4761
  contextRevision(scope) {
4708
4762
  return Number(this.db.prepare("SELECT context_revision FROM memory_scopes WHERE scope_id=?").get(scopeId(scope))?.context_revision ?? 0);
4709
4763
  }
@@ -5969,16 +6023,15 @@ function stripInjectedContext(text2) {
5969
6023
  function escapeRegExp(s) {
5970
6024
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5971
6025
  }
5972
- var SKILL_GATE_HINT_PREFIX, SYSTEM_REMINDER_BLOCK, INJECT_SECTION_HEADS, KNOWN_INJECTED_TEXT, INJECTED_LINE_PREFIXES, XML_BLOCK;
6026
+ var SYSTEM_REMINDER_BLOCK, INJECT_SECTION_HEADS, KNOWN_INJECTED_TEXT, INJECTED_LINE_PREFIXES, XML_BLOCK;
5973
6027
  var init_strip_injected = __esm({
5974
6028
  "src/messages/strip-injected.ts"() {
5975
6029
  "use strict";
5976
- SKILL_GATE_HINT_PREFIX = "\u8FD9\u6761\u6D88\u606F\u662F\u5F00\u53D1\u4EFB\u52A1";
5977
6030
  SYSTEM_REMINDER_BLOCK = /<system-reminder>[\s\S]*?<\/system-reminder>/g;
5978
6031
  INJECT_SECTION_HEADS = /^(本轮对话|当前情绪状态|当前模式)/;
5979
6032
  KNOWN_INJECTED_TEXT = [
5980
- SKILL_GATE_HINT_PREFIX,
5981
- // skill-gate hint 默认/自定义前缀(1007 现行)
6033
+ "\u8FD9\u6761\u6D88\u606F\u662F\u5F00\u53D1\u4EFB\u52A1",
6034
+ // 旧版 skill-gate 提示前缀,兼容未打标签的历史
5982
6035
  "\u5F00\u53D1\u4EFB\u52A1\u8DEF\u6807\uFF0C\u6309\u573A\u666F\u5BF9\u53F7\u5165\u5EA7",
5983
6036
  // skill-gate hint(0912 老文案,历史 JSONL 兼容)
5984
6037
  "\u3010\u5B9A\u65F6\u5FC3\u8DF3\u3011\u8BF7 read HEARTBEAT.md"
@@ -6312,7 +6365,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6312
6365
  };
6313
6366
  const candidates = [];
6314
6367
  const duplicateIds = /* @__PURE__ */ new Set();
6315
- const inside2 = (path37) => path37 && !isAbsolute2(path37) && path37 !== ".." && !path37.startsWith(`..${sep2}`);
6368
+ const inside = (path37) => path37 && !isAbsolute2(path37) && path37 !== ".." && !path37.startsWith(`..${sep2}`);
6316
6369
  for (const relativePath of input.files) {
6317
6370
  const logical = resolve12(root, relativePath);
6318
6371
  let canonical6;
@@ -6322,7 +6375,7 @@ function recoverLegacyProjections(db2, store, input, apply = false) {
6322
6375
  gap("projection_file_missing");
6323
6376
  continue;
6324
6377
  }
6325
- if (!inside2(relative3(root, canonical6)) || relative3(logical, canonical6) || statSync(canonical6).size > 4 * 1024 * 1024) {
6378
+ if (!inside(relative3(root, canonical6)) || relative3(logical, canonical6) || statSync(canonical6).size > 4 * 1024 * 1024) {
6326
6379
  gap("projection_path_unverified");
6327
6380
  continue;
6328
6381
  }
@@ -7849,7 +7902,7 @@ function topicRecordingTime(metadata4) {
7849
7902
  if (!value2 || !validTopicDate(value2.slice(0, 10))) return void 0;
7850
7903
  return validTopicDate(value2) || /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/.test(value2) && Number.isFinite(Date.parse(value2)) ? value2 : void 0;
7851
7904
  }
7852
- function stampTopicContent(content, now2 = (/* @__PURE__ */ new Date()).toISOString(), previous = content, fallbackDate) {
7905
+ function stampTopicContent(content, now2 = (/* @__PURE__ */ new Date()).toISOString(), previous = content, fallbackDate, recordedAt) {
7853
7906
  if (!Number.isFinite(Date.parse(now2))) throw new Error("INVALID_TOPIC_RECORDING_TIME");
7854
7907
  const priorMetadata = topicMetadata(previous);
7855
7908
  const recorded = topicRecordingTime(priorMetadata);
@@ -7859,12 +7912,14 @@ function stampTopicContent(content, now2 = (/* @__PURE__ */ new Date()).toISOStr
7859
7912
  const date2 = /^date:\s*["']?(\d{4}-\d{2}-\d{2})["']?\s*$/m.exec(header)?.[1];
7860
7913
  return date2 && validTopicDate(date2) ? date2 : void 0;
7861
7914
  };
7862
- const suppliedDate = yamlDate(content), priorDate = yamlDate(previous);
7915
+ const priorDate = yamlDate(previous);
7863
7916
  const filenameDate = fallbackDate && validTopicDate(fallbackDate) ? fallbackDate : void 0;
7864
7917
  const suppliedRecorded = /^date_kind:[ \t]*recorded[ \t]*$/m.test(topicMetadata(content));
7918
+ const suppliedDate = suppliedRecorded ? void 0 : yamlDate(content);
7865
7919
  const legacy = previous !== null && (/^legacy_undated:[ \t]*true[ \t]*$/m.test(priorMetadata) || !recorded && !priorDate && !filenameDate && (!suppliedDate || suppliedRecorded));
7866
- const date = suppliedDate ?? priorDate ?? filenameDate ?? todayKey(now2);
7867
- const recordedKind = priorDate ? /^date_kind:[ \t]*recorded[ \t]*$/m.test(priorMetadata) : !filenameDate;
7920
+ const recordedKind = priorDate ? /^date_kind:[ \t]*recorded[ \t]*$/m.test(priorMetadata) : suppliedRecorded || !filenameDate;
7921
+ const recordedDay = todayKey(recordedAt && Number.isFinite(Date.parse(recordedAt)) ? recordedAt : now2);
7922
+ const date = suppliedDate ?? priorDate ?? (recordedKind ? recordedDay : filenameDate) ?? recordedDay;
7868
7923
  const dateFields = suppliedDate ? "" : `date: ${date}
7869
7924
  ${recordedKind ? "date_kind: recorded\n" : ""}`;
7870
7925
  const fields3 = `${dateFields}${legacy ? "legacy_undated: true\n" : ""}recorded_at: ${recorded ?? now2}
@@ -9670,11 +9725,13 @@ var init_facts = __esm({
9670
9725
  if (subjectIds?.length === 0) return [];
9671
9726
  const placeholders = subjectIds?.map(() => "?").join(",");
9672
9727
  const relations = relationshipPredicates.map((predicate) => `'${predicate}'`).join(",");
9728
+ const key3 = scopeId(scope);
9729
+ const incomingIds = includeIncoming ? subjectIds : void 0;
9673
9730
  return this.readTransaction(() => {
9674
- const slots = this.db.prepare(`SELECT * FROM fact_slots s WHERE scope_id=?${subjectIds ? ` AND (subject_id IN (${placeholders})${includeIncoming ? ` OR (predicate IN (${relations}) AND EXISTS (
9675
- SELECT 1 FROM fact_assertions a WHERE a.scope_id=s.scope_id AND a.slot_id=s.slot_id AND json_extract(a.value_json,'$.entityId') IN (${placeholders})))` : ""})` : ""} ORDER BY slot_id`).all(scopeId(scope), ...subjectIds ?? [], ...includeIncoming ? subjectIds ?? [] : []);
9676
- const assertionsBySlot = this.versionsBySlot(scopeId(scope), knownAtRevision);
9677
- const revisions = knownAtRevision === void 0 ? null : this.slotRevisionsAt(scopeId(scope), knownAtRevision);
9731
+ const slots = this.db.prepare(`SELECT * FROM fact_slots s WHERE scope_id=?${subjectIds ? ` AND (subject_id IN (${placeholders})${incomingIds ? ` OR (predicate IN (${relations}) AND s.slot_id IN (
9732
+ SELECT a.slot_id FROM fact_assertions a WHERE a.scope_id=? AND json_extract(a.value_json,'$.entityId') IN (${placeholders})))` : ""})` : ""} ORDER BY slot_id`).all(key3, ...subjectIds ?? [], ...incomingIds ? [key3, ...incomingIds] : []);
9733
+ const assertionsBySlot = this.versionsBySlot(key3, knownAtRevision);
9734
+ const revisions = knownAtRevision === void 0 ? null : this.slotRevisionsAt(key3, knownAtRevision);
9678
9735
  return slots.map((slot) => ({
9679
9736
  subjectId: slot.subject_id,
9680
9737
  predicate: slot.predicate,
@@ -10416,6 +10473,7 @@ var init_store = __esm({
10416
10473
  init_change_feed();
10417
10474
  init_dependencies();
10418
10475
  init_tombstones();
10476
+ init_watermarks();
10419
10477
  init_scope();
10420
10478
  init_knowledge_history();
10421
10479
  init_host_turns();
@@ -10703,32 +10761,32 @@ CREATE TABLE IF NOT EXISTS cluster_members (
10703
10761
  return { built: !hasStats, ms: Date.now() - started };
10704
10762
  }
10705
10763
  async close() {
10706
- const errors = [];
10764
+ const errors2 = [];
10707
10765
  try {
10708
10766
  this.capture?.close();
10709
10767
  } catch (error) {
10710
- errors.push(error);
10768
+ errors2.push(error);
10711
10769
  }
10712
10770
  try {
10713
10771
  this.db.close();
10714
10772
  } catch (error) {
10715
- errors.push(error);
10773
+ errors2.push(error);
10716
10774
  }
10717
10775
  try {
10718
10776
  await this.vectors?.close();
10719
10777
  } catch (error) {
10720
- errors.push(error);
10778
+ errors2.push(error);
10721
10779
  } finally {
10722
10780
  this.vectors = null;
10723
10781
  }
10724
10782
  try {
10725
10783
  this.releaseRuntimeWriter?.();
10726
10784
  } catch (error) {
10727
- errors.push(error);
10785
+ errors2.push(error);
10728
10786
  } finally {
10729
10787
  this.releaseRuntimeWriter = void 0;
10730
10788
  }
10731
- if (errors.length) throw new AggregateError(errors, "MEM7_CLOSE_FAILED");
10789
+ if (errors2.length) throw new AggregateError(errors2, "MEM7_CLOSE_FAILED");
10732
10790
  }
10733
10791
  // ── memcell 账本 ──────────────────────────────────────────
10734
10792
  insertMemcell(cell) {
@@ -11124,13 +11182,13 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11124
11182
  /** Interpretation reads entities, facts and confirmed mentions, independently of later chat intake. */
11125
11183
  interpretationReadStamp(scope, sourceIds, excludedPredicates = []) {
11126
11184
  return this.readTransaction(() => {
11127
- const retractions = this.db.prepare("SELECT COALESCE(MAX(event_seq),0) seq FROM memory_state_outbox WHERE scope_id=? AND kind IN ('evidence.retracted','memory.deleted')").get(scopeId(scope));
11185
+ const retractions = readRetractionSeq(this.db, scopeId(scope));
11128
11186
  const factRevision = excludedPredicates.length ? this.db.prepare(`SELECT slot_id,revision FROM fact_slots
11129
11187
  WHERE scope_id=? AND predicate NOT IN (${excludedPredicates.map(() => "?").join(",")}) ORDER BY slot_id`).all(scopeId(scope), ...excludedPredicates) : this.facts.revision(scope);
11130
11188
  return JSON.stringify([
11131
11189
  this.entities.revision(scope),
11132
11190
  factRevision,
11133
- retractions.seq,
11191
+ retractions,
11134
11192
  sourceIds.map((id2) => this.entities.sourceMentions(scope, id2))
11135
11193
  ]);
11136
11194
  });
@@ -11147,7 +11205,7 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11147
11205
  }
11148
11206
  /** History retrieval validates each publication; unrelated received/interpreted prose is not its basis. */
11149
11207
  captureHistoricalReadGuard(scope) {
11150
- const stamp2 = () => this.db.prepare("SELECT COALESCE(MAX(event_seq),0) seq FROM memory_state_outbox WHERE scope_id=? AND kind IN ('evidence.retracted','memory.deleted')").get(scopeId(scope)).seq;
11208
+ const stamp2 = () => readRetractionSeq(this.db, scopeId(scope));
11151
11209
  const captured = stamp2();
11152
11210
  return () => {
11153
11211
  if (stamp2() !== captured) throw new MemoryReadSupersededError();
@@ -12234,7 +12292,7 @@ function textColumnOf(kind) {
12234
12292
  return "fact";
12235
12293
  }
12236
12294
  }
12237
- var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, RRF_K, warnedFts, warnedVecIdx, bootAt, schemasCache, Mem7VectorStore;
12295
+ var isIntelMac, lancePromise, mem7VectorWarning, arrowPromise, Mem7VectorUnavailableError, VECTOR_DIM, BM25_FIELDS, RRF_K, warnedFts, warnedVecIdx, incompatibleIndexSegments, bootAt, schemasCache, Mem7VectorStore;
12238
12296
  var init_vector_store = __esm({
12239
12297
  "src/mem7/core/vector-store.ts"() {
12240
12298
  "use strict";
@@ -12268,6 +12326,7 @@ var init_vector_store = __esm({
12268
12326
  RRF_K = 60;
12269
12327
  warnedFts = /* @__PURE__ */ new Set();
12270
12328
  warnedVecIdx = /* @__PURE__ */ new Set();
12329
+ incompatibleIndexSegments = (error) => error instanceof Error && error.message.includes("Index type URL should be present and identical across all segments");
12271
12330
  bootAt = Date.now();
12272
12331
  schemasCache = null;
12273
12332
  Mem7VectorStore = class {
@@ -12437,18 +12496,18 @@ var init_vector_store = __esm({
12437
12496
  * 快照版本——18:46 实测:香港相关 episode 在库、探针 BM25 可召回,线上 hybrid 却
12438
12497
  * 0 命中,时序与连续 3 次 conflict 吻合)。
12439
12498
  */
12440
- async ensureFtsIndexes(kind, tbl) {
12499
+ async ensureFtsIndexes(kind, tbl, indices) {
12441
12500
  const lance = await loadLance();
12442
12501
  if (!lance) return;
12443
- let existing = null;
12502
+ let existing;
12503
+ try {
12504
+ existing = new Set((indices ?? await tbl.listIndices()).filter((index) => index.indexType === "FTS").flatMap((index) => index.columns));
12505
+ } catch (err) {
12506
+ console.warn(`[mem7] FTS index check failed for ${kind}: ${err instanceof Error ? err.message : err}`);
12507
+ return;
12508
+ }
12444
12509
  for (const col of BM25_FIELDS[kind]) {
12445
12510
  try {
12446
- if (existing === null) {
12447
- existing = /* @__PURE__ */ new Set();
12448
- for (const idx of await tbl.listIndices()) {
12449
- if (idx.indexType === "FTS") for (const c of idx.columns) existing.add(c);
12450
- }
12451
- }
12452
12511
  if (existing.has(col)) continue;
12453
12512
  assertRuntimeAuthority(this.stateDir, "WRITE");
12454
12513
  await tbl.createIndex(col, {
@@ -12467,6 +12526,34 @@ var init_vector_store = __esm({
12467
12526
  }
12468
12527
  }
12469
12528
  }
12529
+ /** Called by the idle writer. Intel's all-in-one optimize can append an unreadable ANN delta
12530
+ * to a returned table, even with no new rows. Keep the existing ANN and let queries scan its tail. */
12531
+ async maintainIndexes(kind, canStart) {
12532
+ if (this.options.readOnly) throw new Error("MEM7_VECTOR_READ_ONLY");
12533
+ const tbl = await this.table(kind);
12534
+ if (!canStart()) return;
12535
+ let indices;
12536
+ try {
12537
+ indices = await tbl.listIndices();
12538
+ } catch (error) {
12539
+ if (isIntelMac || !incompatibleIndexSegments(error)) throw error;
12540
+ const statsError = await tbl.indexStats("vector_idx").then(() => void 0, (failure2) => failure2);
12541
+ if (!incompatibleIndexSegments(statsError)) throw error;
12542
+ const lance = await loadLance();
12543
+ if (!lance || typeof lance.Index?.hnswSq !== "function") throw error;
12544
+ if (!canStart()) return;
12545
+ assertRuntimeAuthority(this.stateDir, "WRITE");
12546
+ await tbl.createIndex("vector", { config: lance.Index.hnswSq({ distanceType: "cosine" }), replace: true });
12547
+ if (this.tables.get(kind) === tbl) this.vectorIndexesReady.add(kind);
12548
+ await this.ensureFtsIndexes(kind, tbl, await tbl.listIndices());
12549
+ console.log(`[mem7] ANN \u7D22\u5F15\u517C\u5BB9\u4FEE\u590D\u5B8C\u6210\uFF08${kind}.vector\uFF09`);
12550
+ return "repaired";
12551
+ }
12552
+ if (isIntelMac && indices.some((index) => index.columns.includes("vector"))) return "preserved";
12553
+ if (!canStart()) return;
12554
+ assertRuntimeAuthority(this.stateDir, "WRITE");
12555
+ return tbl.optimize();
12556
+ }
12470
12557
  /**
12471
12558
  * ANN 向量索引(1004 妹妹 review 版):
12472
12559
  * - ★ **HNSW_SQ + distanceType:'cosine'**——距离必须配 cosine,不传默认 L2 与查询不兼容会
@@ -13046,8 +13133,47 @@ var init_registry = __esm({
13046
13133
  }
13047
13134
  });
13048
13135
 
13136
+ // src/utils/file-transaction.ts
13137
+ import { mkdir } from "node:fs/promises";
13138
+ import { dirname as dirname12 } from "node:path";
13139
+ import { DatabaseSync as DatabaseSync16 } from "node:sqlite";
13140
+ import { setTimeout as delay } from "node:timers/promises";
13141
+ async function withFileTransaction(file2, action, signal, waitMs = 5e3) {
13142
+ await mkdir(dirname12(file2), { recursive: true });
13143
+ const db2 = new DatabaseSync16(file2);
13144
+ try {
13145
+ const deadline = waitMs === null ? Infinity : Date.now() + waitMs;
13146
+ const retryMs = waitMs === null ? 50 : waitMs > 5e3 ? 200 : 15;
13147
+ for (; ; ) {
13148
+ signal?.throwIfAborted();
13149
+ try {
13150
+ db2.exec("BEGIN IMMEDIATE");
13151
+ break;
13152
+ } catch (error) {
13153
+ const code = error.errcode;
13154
+ if (code !== 5 || Date.now() >= deadline) throw error;
13155
+ await delay(retryMs, void 0, { signal });
13156
+ }
13157
+ }
13158
+ const result = await action();
13159
+ db2.exec("COMMIT");
13160
+ return result;
13161
+ } finally {
13162
+ db2.close();
13163
+ }
13164
+ }
13165
+ var init_file_transaction = __esm({
13166
+ "src/utils/file-transaction.ts"() {
13167
+ "use strict";
13168
+ }
13169
+ });
13170
+
13049
13171
  // src/utils/path.ts
13050
13172
  import * as path3 from "node:path";
13173
+ function isWithin2(root, target) {
13174
+ const name = path3.relative(root, target);
13175
+ return !path3.isAbsolute(name) && name !== ".." && !name.startsWith(".." + path3.sep);
13176
+ }
13051
13177
  function fixMsysPath(p) {
13052
13178
  let fixed = p.includes("\\") ? p.replace(/\\/g, "/") : p;
13053
13179
  if (process.platform === "win32") {
@@ -13128,12 +13254,9 @@ var init_paths = __esm({
13128
13254
  });
13129
13255
 
13130
13256
  // src/tools/file-path.ts
13257
+ import { createHash as createHash30 } from "node:crypto";
13131
13258
  import fs3 from "node:fs";
13132
13259
  import path4 from "node:path";
13133
- function inside(root, target) {
13134
- const relative14 = path4.relative(root, target);
13135
- return relative14 === "" || !path4.isAbsolute(relative14) && relative14 !== ".." && !relative14.startsWith(".." + path4.sep);
13136
- }
13137
13260
  function physicalPath(target) {
13138
13261
  let ancestor = target;
13139
13262
  for (; ; ) {
@@ -13149,40 +13272,54 @@ function physicalPath(target) {
13149
13272
  }
13150
13273
  return path4.resolve(fs3.realpathSync(ancestor), path4.relative(ancestor, target));
13151
13274
  }
13152
- function withoutRepeatedDirectories(relative14) {
13153
- const parts = relative14.split(path4.sep);
13275
+ function withoutRepeatedDirectories(relative16) {
13276
+ const parts = relative16.split(path4.sep);
13154
13277
  while (parts.length > 1 && parts[0].toLowerCase() === AUTO_MEM_DIRNAME) parts.shift();
13155
13278
  return parts.filter((part, index) => index === parts.length - 1 || index === 0 || part.toLowerCase() !== parts[index - 1].toLowerCase()).join(path4.sep);
13156
13279
  }
13157
13280
  function resolveFilePath(requested, context, writing = false) {
13158
- if (!context.memoryToolRoot) return resolvePath3(requested, context.workspace);
13281
+ if (!context.memoryToolRoot) {
13282
+ if (!context.projectTask) return resolvePath3(requested, context.workspace);
13283
+ const target = path4.resolve(context.workspace, requested.replaceAll("\\", "/"));
13284
+ const roots = [context.projectTask.topicsDir, ...!writing && context.taskSessionsDir ? [context.taskSessionsDir] : [], context.workspace];
13285
+ const root2 = roots.find((directory2) => isWithin2(directory2, target));
13286
+ const physical = physicalPath(target);
13287
+ if (!root2 || !isWithin2(physicalPath(root2), physical)) throw new Error("Path is outside this task workspace and project context");
13288
+ if (root2 === context.workspace && context.stateDir && isWithin2(physicalPath(path4.join(context.stateDir, "agents")), physical)) {
13289
+ throw new Error("Path is outside this task\u2019s project storage");
13290
+ }
13291
+ if (root2 !== context.workspace && path4.relative(root2, target).split(path4.sep).some((part) => part.startsWith("."))) {
13292
+ throw new Error("Project task storage metadata is internal");
13293
+ }
13294
+ return target;
13295
+ }
13159
13296
  const root = path4.resolve(context.memoryToolRoot);
13160
13297
  const resolved = resolvePath3(requested, root);
13161
- if (!inside(root, resolved) || !inside(physicalPath(root), physicalPath(resolved))) {
13298
+ if (!isWithin2(root, resolved) || !isWithin2(physicalPath(root), physicalPath(resolved))) {
13162
13299
  throw new Error("\u8DEF\u5F84\u8D85\u51FA\u5F53\u524D\u8BB0\u5FC6\u76EE\u5F55\uFF1B\u8BF7\u4F7F\u7528\u76F8\u5BF9\u8BB0\u5FC6\u76EE\u5F55\u7684\u8DEF\u5F84\u3002");
13163
13300
  }
13164
- const relative14 = path4.relative(root, resolved);
13301
+ const relative16 = path4.relative(root, resolved);
13165
13302
  if (writing) {
13166
13303
  if (path4.basename(resolved).toUpperCase() === "MEMORY.MD") {
13167
13304
  const canonicalIndex = path4.join(root, "MEMORY.md");
13168
13305
  const indexNames = fs3.existsSync(root) ? fs3.readdirSync(root).filter((name) => name.toUpperCase() === "MEMORY.MD") : [];
13169
13306
  let sameIndex = false;
13170
- if (path4.dirname(relative14) === "." && indexNames.length === 1 && fs3.existsSync(resolved) && fs3.existsSync(canonicalIndex)) {
13307
+ if (path4.dirname(relative16) === "." && indexNames.length === 1 && fs3.existsSync(resolved) && fs3.existsSync(canonicalIndex)) {
13171
13308
  const requestedEntry = fs3.lstatSync(resolved);
13172
13309
  const canonicalEntry = fs3.lstatSync(canonicalIndex);
13173
13310
  sameIndex = requestedEntry.dev === canonicalEntry.dev && requestedEntry.ino === canonicalEntry.ino;
13174
13311
  }
13175
- if (relative14 !== "MEMORY.md" && !sameIndex || relative14 === "MEMORY.md" && indexNames.length > 0 && !fs3.existsSync(canonicalIndex)) {
13312
+ if (relative16 !== "MEMORY.md" && !sameIndex || relative16 === "MEMORY.md" && indexNames.length > 0 && !fs3.existsSync(canonicalIndex)) {
13176
13313
  throw new Error("\u8BB0\u5FC6\u7D22\u5F15\u53EA\u80FD\u4F7F\u7528\u6839\u76EE\u5F55\u7684 MEMORY.md\uFF0C\u4E0D\u80FD\u521B\u5EFA\u6216\u66F4\u65B0\u7B2C\u4E8C\u4EFD\u7D22\u5F15\u3002");
13177
13314
  }
13178
13315
  }
13179
13316
  if (!fs3.existsSync(resolved)) {
13180
- const parts = relative14.split(path4.sep);
13317
+ const parts = relative16.split(path4.sep);
13181
13318
  if (parts[0].toLowerCase() === AUTO_MEM_DIRNAME || parts.some((part, index) => index > 0 && index < parts.length - 1 && part.toLowerCase() === parts[index - 1].toLowerCase())) {
13182
13319
  throw new Error("\u91CD\u590D\u8BB0\u5FC6\u76EE\u5F55\u524D\u7F00\uFF1B\u8DEF\u5F84\u4ECE\u8BB0\u5FC6\u76EE\u5F55\u5185\u5F00\u59CB\uFF0C\u4F8B\u5982 project/project_YYYY-MM-DD_name.md\u3002");
13183
13320
  }
13184
13321
  if (fs3.existsSync(root)) {
13185
- const existing = fs3.readdirSync(root, { recursive: true }).filter((entry) => typeof entry === "string" && entry.endsWith(".md") && entry !== relative14 && path4.basename(entry).toUpperCase() !== "MEMORY.MD" && withoutRepeatedDirectories(entry) === relative14);
13322
+ const existing = fs3.readdirSync(root, { recursive: true }).filter((entry) => typeof entry === "string" && entry.endsWith(".md") && entry !== relative16 && path4.basename(entry).toUpperCase() !== "MEMORY.MD" && withoutRepeatedDirectories(entry) === relative16);
13186
13323
  if (existing.length > 0) {
13187
13324
  throw new Error(`\u5DF2\u6709\u8BB0\u5FC6\u6587\u4EF6\u4F4D\u4E8E ${existing.map((entry) => entry.replace(/\\/g, "/")).join("\u3001")}\uFF1B\u4E0D\u80FD\u901A\u8FC7\u7F29\u77ED\u65E7\u5206\u53C9\u8DEF\u5F84\u521B\u5EFA\u53E6\u4E00\u4EFD\u6587\u4EF6\u3002\u8BF7\u6309\u539F\u8DEF\u5F84\u8BFB\u53D6\u540E\u66F4\u65B0\u3002`);
13188
13325
  }
@@ -13194,16 +13331,64 @@ function resolveFilePath(requested, context, writing = false) {
13194
13331
  function displayFilePath(resolved, context) {
13195
13332
  return context.memoryToolRoot ? path4.relative(path4.resolve(context.memoryToolRoot), resolved).replace(/\\/g, "/") || "." : resolved;
13196
13333
  }
13334
+ function topicRoot(context) {
13335
+ return context.memoryToolRoot ?? context.projectTask?.topicsDir ?? (context.onTopicWrite ? getAutoMemPath(context.workspace) : void 0);
13336
+ }
13337
+ function noteTopicWrite(file2, context) {
13338
+ const root = topicRoot(context);
13339
+ if (!root || !isWithin2(path4.resolve(root), file2)) return;
13340
+ if (!/\.md$/i.test(file2)) return;
13341
+ context.onTopicWrite?.();
13342
+ }
13343
+ function indexVersion(file2) {
13344
+ try {
13345
+ return createHash30("sha256").update(fs3.readFileSync(file2)).digest("hex");
13346
+ } catch (error) {
13347
+ if (error.code !== "ENOENT" && error.code !== "EISDIR") throw error;
13348
+ }
13349
+ }
13350
+ async function runFileTool(tool, requested, context, action, signal) {
13351
+ const root = context.memoryToolRoot ?? context.projectTask?.topicsDir;
13352
+ if (!root || typeof requested !== "string" || !["read", "write", "edit"].includes(tool)) return action();
13353
+ let file2;
13354
+ try {
13355
+ file2 = resolveFilePath(requested, context);
13356
+ } catch {
13357
+ return action();
13358
+ }
13359
+ if (!isWithin2(path4.resolve(root), file2)) return action();
13360
+ if (tool === "read") {
13361
+ return withFileTransaction(path4.join(root, ".write-lock.sqlite"), async () => {
13362
+ const result = await action();
13363
+ const version = indexVersion(file2);
13364
+ if (version !== void 0 && !result.isError) context.topicReads?.set(file2, version);
13365
+ return result;
13366
+ }, signal);
13367
+ }
13368
+ return withFileTransaction(path4.join(root, ".write-lock.sqlite"), async () => {
13369
+ const current2 = indexVersion(file2);
13370
+ if (current2 !== void 0 && context.topicReads?.get(file2) !== current2) {
13371
+ throw new Error("Project topic changed or has not been read. Read it again before updating.");
13372
+ }
13373
+ const result = await action();
13374
+ if (!result.isError) {
13375
+ const version = indexVersion(file2);
13376
+ if (version !== void 0) context.topicReads?.set(file2, version);
13377
+ }
13378
+ return result;
13379
+ }, signal);
13380
+ }
13197
13381
  var init_file_path = __esm({
13198
13382
  "src/tools/file-path.ts"() {
13199
13383
  "use strict";
13384
+ init_file_transaction();
13200
13385
  init_path();
13201
13386
  init_paths();
13202
13387
  }
13203
13388
  });
13204
13389
 
13205
13390
  // src/tools/read-result.ts
13206
- import { createHash as createHash30 } from "node:crypto";
13391
+ import { createHash as createHash31 } from "node:crypto";
13207
13392
  function readResultKey(call, content) {
13208
13393
  if (call.function.name !== "read") return null;
13209
13394
  let args;
@@ -13215,7 +13400,7 @@ function readResultKey(call, content) {
13215
13400
  if (!args || typeof args.path !== "string") return null;
13216
13401
  const body = content.replace(/^\[历史工具观察[^\n]*\]\n/, "").replace(/^(?:⚠️ 你已连续[^\n]*\n\n|⚠️ 重复读取检测:[^\n]*\n\n)+/, "");
13217
13402
  if (!body.includes("\n" + "\u2500".repeat(60) + "\n")) return null;
13218
- return JSON.stringify([args.path, args.offset || 1, args.limit || null]) + ":" + createHash30("sha256").update(body).digest("hex");
13403
+ return JSON.stringify([args.path, args.offset || 1, args.limit || null]) + ":" + createHash31("sha256").update(body).digest("hex");
13219
13404
  }
13220
13405
  function repeatedReadNotice(toolCallId) {
13221
13406
  return `[\u91CD\u590D\u8BFB\u53D6\uFF1A\u76F8\u540C\u7248\u672C\u4E0E\u8303\u56F4\u7684\u6B63\u6587\u89C1\u5DE5\u5177\u7ED3\u679C ${toolCallId}\uFF1B\u539F\u59CB\u7ED3\u679C\u4FDD\u7559\u5728\u4F1A\u8BDD\u8BB0\u5F55\u3002]`;
@@ -13405,7 +13590,7 @@ var init_image_input_protection = __esm({
13405
13590
  });
13406
13591
 
13407
13592
  // src/tools/result-snapshot.ts
13408
- import { createHash as createHash31 } from "node:crypto";
13593
+ import { createHash as createHash32 } from "node:crypto";
13409
13594
  function visibleArchive(message) {
13410
13595
  const a = message.resultArchive;
13411
13596
  if (!a || message.role !== "user" || typeof message.content !== "string" || !Array.isArray(a.entries) || typeof a.sessionId !== "string" || typeof a.id !== "string" || !a.entries.every((e) => e && typeof e.id === "string" && typeof e.index === "string" && typeof e.content === "string") || !message.content.includes(archiveNotice(a)) || archiveId(a.sessionId, a.entries) !== a.id) return;
@@ -13558,7 +13743,7 @@ var init_result_snapshot = __esm({
13558
13743
  init_image_input_protection();
13559
13744
  MIN_SNAPSHOT_CHARS = 8e3;
13560
13745
  URI = /^tool-result:\/\/([a-f0-9]{64})$/;
13561
- digest5 = (sessionId, content) => createHash31("sha256").update(sessionId).update("\0").update(content).digest("hex");
13746
+ digest5 = (sessionId, content) => createHash32("sha256").update(sessionId).update("\0").update(content).digest("hex");
13562
13747
  archiveNotice = (a) => `[\u5386\u53F2\u5DE5\u5177\u539F\u6587\u76EE\u5F55\uFF1Aread tool-result://${a.id}\uFF1B\u5171 ${a.entries.length} \u4EFD\uFF0C\u53EF\u6309\u76EE\u5F55\u4E2D\u7684\u5F15\u7528\u53D6\u56DE\u539F\u6587\u3002\u8FD9\u4E9B\u662F\u5F53\u65F6\u89C2\u5BDF\uFF0C\u4E0D\u4EE3\u8868\u5F53\u524D\u72B6\u6001\u3002]`;
13563
13748
  archiveId = (sessionId, entries) => digest5(sessionId, JSON.stringify(entries.map((e) => [e.id, e.index])));
13564
13749
  }
@@ -13846,12 +14031,14 @@ ${result}` : result };
13846
14031
  });
13847
14032
 
13848
14033
  // src/memory/topics-history/writes.ts
13849
- import { basename as basename7 } from "node:path";
13850
- function stampTopicWrite(file2, workspace, text2, previous) {
13851
- if (!workspace || !isAutoMemPath(file2, workspace) || !/\.md$/i.test(file2) || basename7(file2).toUpperCase() === "MEMORY.MD") return text2;
14034
+ import { basename as basename7, relative as relative10, isAbsolute as isAbsolute5, sep as sep5 } from "node:path";
14035
+ function stampTopicWrite(file2, workspace, text2, previous, topicsDir, recordedAt) {
14036
+ const rel = topicsDir ? relative10(topicsDir, file2) : "";
14037
+ const isTopic = topicsDir ? !!rel && !isAbsolute5(rel) && rel !== ".." && !rel.startsWith(".." + sep5) : workspace && isAutoMemPath(file2, workspace);
14038
+ if (!isTopic || !/\.md$/i.test(file2) || basename7(file2).toUpperCase() === "MEMORY.MD") return text2;
13852
14039
  const date = /(?<!\d)(\d{4}-\d{2}-\d{2})(?!\d)/.exec(basename7(file2))?.[1];
13853
14040
  if (previous === null && (!date || !validTopicDate(date))) throw new Error("\u6BCF\u4E2A\u65B0 topics \u6587\u4EF6\u540D\u5FC5\u987B\u5305\u542B\u6709\u6548\u65E5\u671F YYYY-MM-DD\uFF0C\u4F8B\u5982 user_role_2026-10-24.md\u3002");
13854
- return stampTopicContent(text2, (/* @__PURE__ */ new Date()).toISOString(), previous, date);
14041
+ return stampTopicContent(text2, (/* @__PURE__ */ new Date()).toISOString(), previous, date, recordedAt);
13855
14042
  }
13856
14043
  var init_writes = __esm({
13857
14044
  "src/memory/topics-history/writes.ts"() {
@@ -14015,8 +14202,9 @@ Usage:
14015
14202
  return { content: `\u65E0\u6CD5\u521B\u5EFA\u76EE\u5F55: ${dir} \u2014 ${e.message}`, isError: true };
14016
14203
  }
14017
14204
  try {
14018
- content = stampTopicWrite(filePath, ctx.workspace, content, oldContent);
14205
+ content = stampTopicWrite(filePath, ctx.workspace, content, oldContent, ctx.projectTask?.topicsDir ?? ctx.memoryToolRoot, ctx.topicSourceTime);
14019
14206
  atomicWrite(filePath, content);
14207
+ noteTopicWrite(filePath, ctx);
14020
14208
  } catch (e) {
14021
14209
  return { content: `\u5199\u5165\u5931\u8D25: ${e.message}`, isError: true };
14022
14210
  }
@@ -14211,7 +14399,8 @@ Usage:
14211
14399
  if (oldString === "") {
14212
14400
  const dir = path7.dirname(filePath);
14213
14401
  fs6.mkdirSync(dir, { recursive: true });
14214
- fs6.writeFileSync(filePath, stampTopicWrite(filePath, ctx.workspace, newString, null), "utf-8");
14402
+ fs6.writeFileSync(filePath, stampTopicWrite(filePath, ctx.workspace, newString, null, ctx.projectTask?.topicsDir ?? ctx.memoryToolRoot, ctx.topicSourceTime), "utf-8");
14403
+ noteTopicWrite(filePath, ctx);
14215
14404
  readFileState.set(filePath, { timestamp: fs6.statSync(filePath).mtimeMs });
14216
14405
  return { content: `\u521B\u5EFA\u6587\u4EF6: ${displayFilePath(filePath, ctx)} (${newString.split("\n").length} \u884C)` };
14217
14406
  }
@@ -14222,7 +14411,8 @@ Usage:
14222
14411
  const rawContent = fs6.readFileSync(filePath, "utf-8");
14223
14412
  fileContent = rawContent.replaceAll("\r\n", "\n");
14224
14413
  if (oldString === "" && fileContent.trim() === "") {
14225
- fs6.writeFileSync(filePath, stampTopicWrite(filePath, ctx.workspace, newString, fileContent), "utf-8");
14414
+ fs6.writeFileSync(filePath, stampTopicWrite(filePath, ctx.workspace, newString, fileContent, ctx.projectTask?.topicsDir ?? ctx.memoryToolRoot, ctx.topicSourceTime), "utf-8");
14415
+ noteTopicWrite(filePath, ctx);
14226
14416
  readFileState.set(filePath, { timestamp: fs6.statSync(filePath).mtimeMs });
14227
14417
  return { content: `\u5199\u5165\u7A7A\u6587\u4EF6: ${displayFilePath(filePath, ctx)} (${newString.split("\n").length} \u884C)` };
14228
14418
  }
@@ -14269,7 +14459,9 @@ ${preview}
14269
14459
  const actualNewString = preserveQuoteStyle(oldString, actualOldString, newString);
14270
14460
  const diffView = generateEditDiff(fileContent, actualOldString, actualNewString);
14271
14461
  const newContent = applyEditToFile(fileContent, actualOldString, actualNewString, replaceAll);
14272
- fs6.writeFileSync(filePath, stampTopicWrite(filePath, ctx.workspace, newContent, fileContent), "utf-8");
14462
+ if (newContent === fileContent) return { content: "\u6587\u4EF6\u5185\u5BB9\u672A\u53D8\u5316\uFF0C\u65E0\u987B\u5199\u5165\u3002" };
14463
+ fs6.writeFileSync(filePath, stampTopicWrite(filePath, ctx.workspace, newContent, fileContent, ctx.projectTask?.topicsDir ?? ctx.memoryToolRoot, ctx.topicSourceTime), "utf-8");
14464
+ noteTopicWrite(filePath, ctx);
14273
14465
  readFileState.set(filePath, { timestamp: fs6.statSync(filePath).mtimeMs });
14274
14466
  const strategy = actualOldString === oldString ? "\u7CBE\u786E\u5339\u914D" : "\u5F15\u53F7\u89C4\u8303\u5316\u5339\u914D";
14275
14467
  const count = replaceAll ? matchCount : 1;
@@ -18066,10 +18258,10 @@ function installSQLiteWriteCapture(db2, source) {
18066
18258
  if (db2.isTransaction) throw new Error("REPLICATION_TRANSACTION_ALREADY_OPEN");
18067
18259
  const exec3 = db2.exec, prepare = db2.prepare;
18068
18260
  let active, failed = false, closed = false, reading = false;
18069
- let direct;
18261
+ let direct2;
18070
18262
  const check = () => {
18071
18263
  if (closed) throw new Error("REPLICATION_TRANSACTION_CLOSED");
18072
- direct?.assertOpen();
18264
+ direct2?.assertOpen();
18073
18265
  };
18074
18266
  const wrappedExec = function(sql) {
18075
18267
  check();
@@ -18140,10 +18332,10 @@ function installSQLiteWriteCapture(db2, source) {
18140
18332
  db2.prepare = checkedPrepare;
18141
18333
  const transaction = (operation) => {
18142
18334
  check();
18143
- if (db2.isTransaction) return direct.scope(operation);
18335
+ if (db2.isTransaction) return direct2.scope(operation);
18144
18336
  db2.exec("BEGIN IMMEDIATE");
18145
18337
  try {
18146
- const result = direct.scope(operation);
18338
+ const result = direct2.scope(operation);
18147
18339
  if (result && typeof result.then === "function") throw new Error("REPLICATION_ASYNC_TRANSACTION");
18148
18340
  db2.exec("COMMIT");
18149
18341
  return result;
@@ -18152,10 +18344,10 @@ function installSQLiteWriteCapture(db2, source) {
18152
18344
  throw error;
18153
18345
  }
18154
18346
  };
18155
- direct = installAutocommitCapture(db2, transaction);
18347
+ direct2 = installAutocommitCapture(db2, transaction);
18156
18348
  return {
18157
18349
  assertOpen: check,
18158
- scope: (operation) => direct.scope(operation),
18350
+ scope: (operation) => direct2.scope(operation),
18159
18351
  transaction,
18160
18352
  close() {
18161
18353
  if (closed) return;
@@ -18164,7 +18356,7 @@ function installSQLiteWriteCapture(db2, source) {
18164
18356
  source.endCapture(active);
18165
18357
  active = void 0;
18166
18358
  }
18167
- direct.close();
18359
+ direct2.close();
18168
18360
  db2.prepare = prepare;
18169
18361
  db2.exec = exec3;
18170
18362
  closed = true;
@@ -18214,7 +18406,7 @@ function openDb(workspace, options = {}) {
18214
18406
  let db2;
18215
18407
  try {
18216
18408
  fs14.mkdirSync(dir, { recursive: true });
18217
- db2 = new DatabaseSync16(dbPath);
18409
+ db2 = new DatabaseSync17(dbPath);
18218
18410
  } catch (error) {
18219
18411
  release?.();
18220
18412
  throw error;
@@ -18365,7 +18557,7 @@ function migrate(db2) {
18365
18557
  db2.exec("ALTER TABLE events ADD COLUMN doc_path TEXT");
18366
18558
  }
18367
18559
  }
18368
- var CALENDAR_SCHEMA_VERSION, _sqlite, DatabaseSync16;
18560
+ var CALENDAR_SCHEMA_VERSION, _sqlite, DatabaseSync17;
18369
18561
  var init_db = __esm({
18370
18562
  "src/calendar/db.ts"() {
18371
18563
  "use strict";
@@ -18377,7 +18569,7 @@ var init_db = __esm({
18377
18569
  init_runtime_lock();
18378
18570
  CALENDAR_SCHEMA_VERSION = 6;
18379
18571
  _sqlite = null;
18380
- DatabaseSync16 = new Proxy(function() {
18572
+ DatabaseSync17 = new Proxy(function() {
18381
18573
  }, {
18382
18574
  construct(_t, args) {
18383
18575
  return new (getSqlite()).DatabaseSync(...args);
@@ -18398,7 +18590,7 @@ function createNotificationStateReader() {
18398
18590
  const key3 = resolve23(path37);
18399
18591
  let db2 = databases.get(key3);
18400
18592
  if (!db2) {
18401
- db2 = new DatabaseSync16(key3, { readOnly: true });
18593
+ db2 = new DatabaseSync17(key3, { readOnly: true });
18402
18594
  try {
18403
18595
  db2.exec("BEGIN");
18404
18596
  } catch (error) {
@@ -18464,6 +18656,7 @@ function readNotificationState(route, queueStateDir, open6, relationshipChecker)
18464
18656
  }
18465
18657
  if (context.actionVersions && Object.keys(context.actionVersions).length) {
18466
18658
  const ledgerDependencies = new MemoryDependencies(memory, (operation) => operation());
18659
+ const retractions = emptyRetractionCache();
18467
18660
  proactive = open6(join30(runtime.workspace, ".proactive", "proactive.db"));
18468
18661
  for (const id2 of Object.keys(context.actionVersions)) {
18469
18662
  const action = proactive.prepare("SELECT scope_id,intent_id FROM actions WHERE id=?").get(id2);
@@ -18477,6 +18670,9 @@ function readNotificationState(route, queueStateDir, open6, relationshipChecker)
18477
18670
  const row = proactive.prepare("SELECT data FROM nodes WHERE id=?").get(nodeId);
18478
18671
  const data = row && JSON.parse(row.data);
18479
18672
  if (!data || data.scopeId !== context.scopeId || data.evidenceState === "deleted") return { state: "blocked", reason: "memory_deleted", redact: true };
18673
+ if (typeof data.sourceWatermark === "number" && typeof data.retractionWatermark === "number" && deletedWithinView(memory, context.scopeId, data.retractionWatermark, data.sourceWatermark, retractions)) {
18674
+ return { state: "blocked", reason: "memory_deleted", redact: true };
18675
+ }
18480
18676
  for (const evidence of [...data.sourceRefs ?? [], ...data.sourceEvidence ?? []]) {
18481
18677
  if (evidence.sourceId && deletedSource(evidence.sourceId)) return { state: "blocked", reason: "memory_deleted", redact: true };
18482
18678
  if (evidence.sourceId && Number.isSafeInteger(evidence.sourceVersion)) {
@@ -18551,6 +18747,7 @@ var init_notification_state = __esm({
18551
18747
  init_dependencies();
18552
18748
  init_basis_check();
18553
18749
  init_relationship_notice_check();
18750
+ init_watermarks();
18554
18751
  init_scope();
18555
18752
  contextIdentity = (context) => canonicalJson({
18556
18753
  scopeId: context.scopeId,
@@ -18593,7 +18790,7 @@ var init_apply_transaction = __esm({
18593
18790
  });
18594
18791
 
18595
18792
  // src/mem7/boot-recovery.ts
18596
- import { DatabaseSync as DatabaseSync17 } from "node:sqlite";
18793
+ import { DatabaseSync as DatabaseSync18 } from "node:sqlite";
18597
18794
  var init_boot_recovery = __esm({
18598
18795
  "src/mem7/boot-recovery.ts"() {
18599
18796
  "use strict";
@@ -19453,7 +19650,7 @@ var init_BashTool = __esm({
19453
19650
  "src/tools/BashTool/BashTool.ts"() {
19454
19651
  "use strict";
19455
19652
  init_registry();
19456
- init_path();
19653
+ init_file_path();
19457
19654
  init_task_manager();
19458
19655
  init_prompt();
19459
19656
  init_bashSecurity();
@@ -19498,7 +19695,7 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
19498
19695
  const runInBackground = args.run_in_background || false;
19499
19696
  let cwd;
19500
19697
  try {
19501
- cwd = args.cwd ? resolvePath3(args.cwd, ctx.workspace) : ctx.workspace;
19698
+ cwd = args.cwd ? resolveFilePath(args.cwd, ctx, true) : ctx.workspace;
19502
19699
  } catch (e) {
19503
19700
  return { content: e.message, isError: true };
19504
19701
  }
@@ -19997,7 +20194,7 @@ function checkMemoryExecution(stateDir, workspace, context, activeDispatchKey) {
19997
20194
  let calendar;
19998
20195
  try {
19999
20196
  if (!stateDir || !context.scopeId || !Array.isArray(context.basisRefs)) return { ok: false, reason: "EXECUTION_CONTEXT_INVALID" };
20000
- memory = new DatabaseSync16(join33(stateDir, "mem7", "index", "mem7.db"), { readOnly: true });
20197
+ memory = new DatabaseSync17(join33(stateDir, "mem7", "index", "mem7.db"), { readOnly: true });
20001
20198
  memory.exec("PRAGMA query_only=ON; BEGIN");
20002
20199
  const schema5 = readSchemaVersion(memory);
20003
20200
  if (schema5?.component !== "mem7" || schema5.version !== MEM7_SCHEMA_VERSION) return { ok: false, reason: "MEMORY_SCHEMA_UNSUPPORTED" };
@@ -20012,7 +20209,7 @@ function checkMemoryExecution(stateDir, workspace, context, activeDispatchKey) {
20012
20209
  if (!result.ok) return result;
20013
20210
  }
20014
20211
  if (context.calendarBinding) {
20015
- calendar = new DatabaseSync16(join33(workspace, ".calendar", "calendar.db"), { readOnly: true });
20212
+ calendar = new DatabaseSync17(join33(workspace, ".calendar", "calendar.db"), { readOnly: true });
20016
20213
  calendar.exec("PRAGMA query_only=ON; BEGIN");
20017
20214
  const binding = calendar.prepare(`SELECT b.*,e.status event_status,e.memory_version current_event_version FROM calendar_memory_bindings b
20018
20215
  JOIN events e ON e.id=b.event_id WHERE b.event_id=?`).get(context.calendarBinding.eventId);
@@ -20030,8 +20227,9 @@ function checkMemoryExecution(stateDir, workspace, context, activeDispatchKey) {
20030
20227
  if (!bound.ok) return bound;
20031
20228
  }
20032
20229
  if (context.actionVersions && Object.keys(context.actionVersions).length) {
20033
- proactive = new DatabaseSync16(join33(workspace, ".proactive", "proactive.db"), { readOnly: true });
20230
+ proactive = new DatabaseSync17(join33(workspace, ".proactive", "proactive.db"), { readOnly: true });
20034
20231
  proactive.exec("PRAGMA query_only=ON; BEGIN");
20232
+ const retractions = emptyRetractionCache();
20035
20233
  for (const [id2, version] of Object.entries(context.actionVersions)) {
20036
20234
  const action = proactive.prepare("SELECT * FROM actions WHERE id=?").get(id2);
20037
20235
  if (action?.dispatch_state === "delivery_unknown" || action?.dispatch_state === "started" && action.dispatch_key !== activeDispatchKey) {
@@ -20067,6 +20265,9 @@ function checkMemoryExecution(stateDir, workspace, context, activeDispatchKey) {
20067
20265
  }
20068
20266
  }
20069
20267
  if (!data || data.scopeId !== context.scopeId || ["resolved", "rejected", "expired"].includes(data.status) && !(handled && data.status === "resolved" && ["notification_completed", "calendar_accepted"].includes(data.reasonCode)) || ["candidate", "needs_revalidation", "deleted"].includes(data.evidenceState) || data.automationState === "pending_execution_guard") return { ok: false, reason: "INTENT_BASIS_INVALID" };
20268
+ if (typeof data.sourceWatermark === "number" && typeof data.retractionWatermark === "number" && deletedWithinView(memory, context.scopeId, data.retractionWatermark, data.sourceWatermark, retractions)) {
20269
+ return { ok: false, reason: "INTENT_BASIS_INVALID" };
20270
+ }
20070
20271
  }
20071
20272
  }
20072
20273
  return { ok: true };
@@ -20094,6 +20295,7 @@ var init_execution_guard = __esm({
20094
20295
  init_context_time();
20095
20296
  init_relationship_notice_check();
20096
20297
  init_dependencies();
20298
+ init_watermarks();
20097
20299
  MemoryExecutionBlockedError = class extends Error {
20098
20300
  constructor(reason) {
20099
20301
  super(`MEMORY_EXECUTION_BLOCKED: ${reason}`);
@@ -20297,6 +20499,45 @@ var init_events = __esm({
20297
20499
  }
20298
20500
  });
20299
20501
 
20502
+ // src/router/cpu-router-scene.ts
20503
+ var init_cpu_router_scene = __esm({
20504
+ "src/router/cpu-router-scene.ts"() {
20505
+ "use strict";
20506
+ }
20507
+ });
20508
+
20509
+ // src/skills/skill-gate.ts
20510
+ function beginSkillGate(sessionId) {
20511
+ if (loadedBySession.size >= MAX_TRACKED_SESSIONS && !loadedBySession.has(sessionId)) {
20512
+ const oldest = loadedBySession.keys().next().value;
20513
+ if (oldest !== void 0) loadedBySession.delete(oldest);
20514
+ }
20515
+ loadedBySession.set(sessionId, /* @__PURE__ */ new Set());
20516
+ }
20517
+ function isUserChannel(ch) {
20518
+ return !!ch && USER_CHANNELS.has(ch);
20519
+ }
20520
+ var USER_CHANNELS, SKILL_CHANNELS, loadedBySession, MAX_TRACKED_SESSIONS;
20521
+ var init_skill_gate = __esm({
20522
+ "src/skills/skill-gate.ts"() {
20523
+ "use strict";
20524
+ init_strip_injected();
20525
+ init_writer();
20526
+ init_cpu_router_scene();
20527
+ USER_CHANNELS = /* @__PURE__ */ new Set(["discord", "feishu", "wechat", "telegram", "cli", "console", "voice-chat", "deskBuddy", "ccBridge"]);
20528
+ SKILL_CHANNELS = /* @__PURE__ */ new Set([...USER_CHANNELS, "chan7", "webhook"]);
20529
+ loadedBySession = /* @__PURE__ */ new Map();
20530
+ MAX_TRACKED_SESSIONS = 100;
20531
+ }
20532
+ });
20533
+
20534
+ // src/skills/legacy-session-start.ts
20535
+ var init_legacy_session_start = __esm({
20536
+ "src/skills/legacy-session-start.ts"() {
20537
+ "use strict";
20538
+ }
20539
+ });
20540
+
20300
20541
  // src/router/cpu-router.ts
20301
20542
  import fs18 from "node:fs";
20302
20543
  import path22 from "node:path";
@@ -20310,13 +20551,6 @@ var init_cpu_router = __esm({
20310
20551
  }
20311
20552
  });
20312
20553
 
20313
- // src/router/cpu-router-scene.ts
20314
- var init_cpu_router_scene = __esm({
20315
- "src/router/cpu-router-scene.ts"() {
20316
- "use strict";
20317
- }
20318
- });
20319
-
20320
20554
  // src/router/cpu-router-mode-hook.ts
20321
20555
  import fs19 from "node:fs";
20322
20556
  import path23 from "node:path";
@@ -20878,6 +21112,8 @@ var TOOL_HOOK_EXECUTION_TIMEOUT_MS;
20878
21112
  var init_executor = __esm({
20879
21113
  "src/hooks/executor.ts"() {
20880
21114
  "use strict";
21115
+ init_skill_gate();
21116
+ init_legacy_session_start();
20881
21117
  init_runtime_authority();
20882
21118
  init_config3();
20883
21119
  init_events();
@@ -20936,6 +21172,9 @@ async function executeOne(tc, ctx, signal) {
20936
21172
  if (ctx.yieldSignal?.aborted) {
20937
21173
  return { call: tc, result: { content: "[not executed: new user input received; reconsider this call after reading it]", isError: false }, summary: null };
20938
21174
  }
21175
+ if (ctx.projectTask && /^(?:memory_|calendar_memory_|calendar_delivery_|calendar_reconcile_|goal_|proactive_|chat_history$)/.test(tc.function.name)) {
21176
+ return { call: tc, result: { content: "This tool has no project-task memory or conversation context. Use the project topics and task records.", isError: true }, summary: null };
21177
+ }
20939
21178
  const tool = registry.get(tc.function.name);
20940
21179
  if (!tool) {
20941
21180
  return { call: tc, result: { content: `Unknown tool: ${tc.function.name}`, isError: true }, summary: null };
@@ -21038,7 +21277,13 @@ async function executeOne(tc, ctx, signal) {
21038
21277
  workspace: ctx.workspace,
21039
21278
  executionContext: guardContext,
21040
21279
  effectId: `tool:${tc.id}`
21041
- }, () => tool.handler(args, { ...ctx, toolCallId: tc.id }, signal));
21280
+ }, () => runFileTool(
21281
+ tc.function.name,
21282
+ args.file_path ?? args.path,
21283
+ ctx,
21284
+ () => tool.handler(args, { ...ctx, toolCallId: tc.id }, signal),
21285
+ signal
21286
+ ));
21042
21287
  assertRuntimeTool(ctx.stateDir, tc.function.name);
21043
21288
  await executePostToolUseHooks(tc.function.name, args, result.content, hookCtx, signal);
21044
21289
  if (repeatN >= LOOP_SOFT_AT) {
@@ -21111,6 +21356,7 @@ var PLAN_BLOCKED_TOOLS, LOOP_SOFT_AT, LOOP_HARD_AT, _lastCallSig, _lastCallCount
21111
21356
  var init_executor2 = __esm({
21112
21357
  "src/tools/BashTool/executor.ts"() {
21113
21358
  "use strict";
21359
+ init_file_path();
21114
21360
  init_registry();
21115
21361
  init_types();
21116
21362
  init_execution_guard();
@@ -21318,6 +21564,9 @@ var init_image_assets = __esm({
21318
21564
  // src/utils/context-dump.ts
21319
21565
  import * as fs20 from "node:fs";
21320
21566
  import * as path24 from "node:path";
21567
+ function isContextDumpEnabled() {
21568
+ return process.env.ENGINE7_DUMP_CONTEXT === "1" || process.env.ENGINE_DUMP_REQUEST === "1";
21569
+ }
21321
21570
  function dumpApiRequest(opts) {
21322
21571
  const lines = [
21323
21572
  "=== API Request Debug\uFF08\u53D1\u7ED9 LLM \u7684\u6700\u7EC8\u8BF7\u6C42\u4F53\uFF0C\u6BCF\u6B21\u8986\u76D6\u5199\uFF09===",
@@ -21361,7 +21610,7 @@ var init_context_dump = __esm({
21361
21610
  // src/core/steer-mailbox.ts
21362
21611
  import * as fs21 from "node:fs";
21363
21612
  import * as path25 from "node:path";
21364
- import { createHash as createHash33, randomUUID as randomUUID13 } from "node:crypto";
21613
+ import { createHash as createHash34, randomUUID as randomUUID13 } from "node:crypto";
21365
21614
  var MAX_FILE, MAX_PENDING, MAX_PENDING_BYTES, SteerMailbox;
21366
21615
  var init_steer_mailbox = __esm({
21367
21616
  "src/core/steer-mailbox.ts"() {
@@ -21373,7 +21622,7 @@ var init_steer_mailbox = __esm({
21373
21622
  SteerMailbox = class {
21374
21623
  constructor(stateDir, sessionId) {
21375
21624
  this.sessionId = sessionId;
21376
- const key3 = createHash33("sha256").update(sessionId).digest("hex");
21625
+ const key3 = createHash34("sha256").update(sessionId).digest("hex");
21377
21626
  this.path = path25.join(stateDir, "steer", `${key3}.json`);
21378
21627
  }
21379
21628
  path;
@@ -21407,7 +21656,7 @@ var init_steer_mailbox = __esm({
21407
21656
  if (input.attachment) this.assertAttachment(input);
21408
21657
  input.images?.forEach(assertImageAssetRef);
21409
21658
  const records = this.list();
21410
- const id2 = input.messageId ? createHash33("sha256").update(JSON.stringify([
21659
+ const id2 = input.messageId ? createHash34("sha256").update(JSON.stringify([
21411
21660
  this.sessionId,
21412
21661
  input.channel,
21413
21662
  input.channelTarget ?? "",
@@ -21507,7 +21756,7 @@ var init_steer_mailbox = __esm({
21507
21756
  });
21508
21757
 
21509
21758
  // src/compact/recent-tail.ts
21510
- function splitRecentHistory(messages, keepRecentTokens, budget) {
21759
+ function splitRecentHistory(messages, keepRecentTokens, budget, activeQueryId) {
21511
21760
  const protectedHistory = splitProtectedCompactHistory(messages, budget);
21512
21761
  let start = protectedHistory.prefix.length;
21513
21762
  if (keepRecentTokens > 0) {
@@ -21520,6 +21769,10 @@ function splitRecentHistory(messages, keepRecentTokens, budget) {
21520
21769
  }
21521
21770
  start = Math.min(start, recentStart);
21522
21771
  }
21772
+ if (activeQueryId) {
21773
+ const activeStart = messages.findIndex((m) => "role" in m && m.role === "user" && (m.inputSource?.queryId === activeQueryId || m.steerInput?.queryId === activeQueryId));
21774
+ if (activeStart >= 0) start = Math.min(start, activeStart);
21775
+ }
21523
21776
  const suffix = messages.slice(start);
21524
21777
  if (estimateMessageTokens(suffix) > budget) {
21525
21778
  const fused = fitProtectedTail(suffix, budget);
@@ -22086,14 +22339,14 @@ function shouldAutoCompact(messages, config) {
22086
22339
  compactLog(TAG3, `tokens=${tokenCount} threshold=${threshold} triggered=${result}`);
22087
22340
  return result;
22088
22341
  }
22089
- async function autoCompactIfNeeded(messages, config, tracking, provider, model, signal, hookCtx, snapshotContext, deferPostCompact = false) {
22342
+ async function autoCompactIfNeeded(messages, config, tracking, provider, model, signal, hookCtx, snapshotContext, deferPostCompact = false, activeQueryId) {
22090
22343
  const starts = messages.filter((m) => isAttachmentMessage(m) && m.attachment.type === "session_start");
22091
22344
  if (starts.length) {
22092
22345
  const body = messages.filter((m) => !starts.includes(m));
22093
22346
  const result = await autoCompactIfNeeded(body, {
22094
22347
  ...config,
22095
22348
  systemOverheadTokens: (config.systemOverheadTokens ?? 0) + estimateMessageTokens(starts)
22096
- }, tracking, provider, model, signal, hookCtx, snapshotContext, deferPostCompact);
22349
+ }, tracking, provider, model, signal, hookCtx, snapshotContext, deferPostCompact, activeQueryId);
22097
22350
  const retained = result.wasCompacted ? [...starts, ...result.messages] : messages;
22098
22351
  return { ...result, messages: retained, ...result.compactionResult ? { compactionResult: {
22099
22352
  ...result.compactionResult,
@@ -22102,8 +22355,8 @@ async function autoCompactIfNeeded(messages, config, tracking, provider, model,
22102
22355
  postCompactTokenCount: estimateMessageTokens(retained)
22103
22356
  } } : {} };
22104
22357
  }
22105
- if ((config.keepRecentTokens ?? 0) > 0 && config.enabled !== false) {
22106
- const { prefix: prefix3, suffix: suffix2 } = splitRecentHistory(messages, config.keepRecentTokens, getAutoCompactThreshold(config));
22358
+ if (((config.keepRecentTokens ?? 0) > 0 || activeQueryId) && config.enabled !== false) {
22359
+ const { prefix: prefix3, suffix: suffix2 } = splitRecentHistory(messages, config.keepRecentTokens ?? 0, getAutoCompactThreshold(config), activeQueryId);
22107
22360
  if (suffix2.length) {
22108
22361
  if (!prefix3.length) return { wasCompacted: false, messages, consecutiveFailures: tracking.consecutiveFailures };
22109
22362
  const result = await autoCompactIfNeeded(prefix3, {
@@ -22644,7 +22897,7 @@ var init_compact2 = __esm({
22644
22897
  });
22645
22898
 
22646
22899
  // src/compact/background.ts
22647
- import { createHash as createHash34 } from "node:crypto";
22900
+ import { createHash as createHash35 } from "node:crypto";
22648
22901
  var historyFingerprint;
22649
22902
  var init_background = __esm({
22650
22903
  "src/compact/background.ts"() {
@@ -22654,7 +22907,7 @@ var init_background = __esm({
22654
22907
  init_tokenEstimate();
22655
22908
  init_hooks();
22656
22909
  init_host_turn();
22657
- historyFingerprint = (messages) => createHash34("sha256").update(JSON.stringify(messages)).digest("hex");
22910
+ historyFingerprint = (messages) => createHash35("sha256").update(JSON.stringify(messages)).digest("hex");
22658
22911
  }
22659
22912
  });
22660
22913
 
@@ -22893,28 +23146,6 @@ var init_store2 = __esm({
22893
23146
  }
22894
23147
  });
22895
23148
 
22896
- // src/skills/skill-gate.ts
22897
- function beginSkillGate(sessionId) {
22898
- if (loadedBySession.size >= MAX_TRACKED_SESSIONS && !loadedBySession.has(sessionId)) {
22899
- const oldest = loadedBySession.keys().next().value;
22900
- if (oldest !== void 0) loadedBySession.delete(oldest);
22901
- }
22902
- loadedBySession.set(sessionId, /* @__PURE__ */ new Set());
22903
- }
22904
- function isUserChannel(ch) {
22905
- return !!ch && USER_CHANNELS.has(ch);
22906
- }
22907
- var USER_CHANNELS, loadedBySession, MAX_TRACKED_SESSIONS;
22908
- var init_skill_gate = __esm({
22909
- "src/skills/skill-gate.ts"() {
22910
- "use strict";
22911
- init_strip_injected();
22912
- USER_CHANNELS = /* @__PURE__ */ new Set(["discord", "feishu", "wechat", "telegram", "cli", "console", "voice-chat", "deskBuddy", "ccBridge"]);
22913
- loadedBySession = /* @__PURE__ */ new Map();
22914
- MAX_TRACKED_SESSIONS = 100;
22915
- }
22916
- });
22917
-
22918
23149
  // src/memory/memdir/memoryTypes.ts
22919
23150
  var MEMORY_TYPES, TYPES_SECTION_INDIVIDUAL, WHAT_NOT_TO_SAVE_SECTION, MEMORY_DRIFT_CAVEAT, WHEN_TO_ACCESS_SECTION, TRUSTING_RECALL_SECTION, MEMORY_FRONTMATTER_EXAMPLE;
22920
23151
  var init_memoryTypes = __esm({
@@ -23174,10 +23405,12 @@ function buildMemoryLines(displayName, memoryDir, extraGuidelines, skipIndex = f
23174
23405
  function buildMemoryPrompt(params) {
23175
23406
  const { displayName, memoryDir, extraGuidelines } = params;
23176
23407
  const entrypoint = join36(memoryDir, ENTRYPOINT_NAME);
23177
- let entrypointContent = "";
23178
- try {
23179
- entrypointContent = readFileSync19(entrypoint, { encoding: "utf-8" });
23180
- } catch {
23408
+ let entrypointContent = params.entrypointContent ?? "";
23409
+ if (params.entrypointContent === void 0) {
23410
+ try {
23411
+ entrypointContent = readFileSync19(entrypoint, "utf-8");
23412
+ } catch {
23413
+ }
23181
23414
  }
23182
23415
  const lines = buildMemoryLines(displayName, memoryDir, extraGuidelines);
23183
23416
  if (entrypointContent.trim()) {
@@ -23862,7 +24095,7 @@ var init_query = __esm({
23862
24095
  let currentMessages = [...messages];
23863
24096
  const stopUserMessages = [];
23864
24097
  const stopToolResults = [];
23865
- const collectStopEvidence = !this.options.skipStopHook && !perTurnEmotion;
24098
+ const collectStopEvidence = !context?.projectTask && !this.options.skipStopHook && !perTurnEmotion;
23866
24099
  const currentUser = collectStopEvidence ? messages.findLast((m) => "role" in m && m.role === "user") : void 0;
23867
24100
  if (currentUser && "role" in currentUser) {
23868
24101
  stopUserMessages.push(currentUser.memoryOriginalText ?? (typeof currentUser.content === "string" ? currentUser.content : currentUser.content.filter((b) => b.type === "text").map((b) => b.text).join("\n")));
@@ -24156,6 +24389,7 @@ var init_query = __esm({
24156
24389
  provider: queryProvider,
24157
24390
  model: queryModel,
24158
24391
  identity: identity3,
24392
+ activeQueryId: queryId,
24159
24393
  hookContext: context ? {
24160
24394
  sessionId: compactSessionId,
24161
24395
  workspace: context.workspace || "",
@@ -24206,7 +24440,9 @@ var init_query = __esm({
24206
24440
  channel: context.channel || "console",
24207
24441
  cwd: context.workspace || process.env.ENGINE_WORKSPACE || ""
24208
24442
  } : void 0,
24209
- snapshotContext
24443
+ snapshotContext,
24444
+ false,
24445
+ queryId
24210
24446
  ).catch((error) => {
24211
24447
  throw new Error(`\u4E0A\u4E0B\u6587\u6574\u7406\u5931\u8D25\uFF08\u5BF9\u8BDD\u5DF2\u4FDD\u7559\uFF0C\u53EF\u7A0D\u540E\u91CD\u8BD5\u6216 /compact\uFF09\uFF1A${error instanceof Error ? error.message : error}`);
24212
24448
  });
@@ -24292,7 +24528,7 @@ ${hint}` : [...current2.content, { type: "text", text: hint }] };
24292
24528
  const fullSystemDynamic = deferredHint && perTurnSystemDynamic ? `${deferredHint}
24293
24529
 
24294
24530
  ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
24295
- if (process.env.ENGINE_DUMP_REQUEST === "1" && (!this.options.agentLabel || this.options.agentLabel === "main")) {
24531
+ if ((!this.options.agentLabel || this.options.agentLabel === "main") && isContextDumpEnabled()) {
24296
24532
  try {
24297
24533
  const ws = process.env.ENGINE7_WORKSPACE;
24298
24534
  if (ws) {
@@ -24393,13 +24629,13 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
24393
24629
  yield { type: "error", error: `\u4E0A\u4E0B\u6587\u8D85\u51FA\u6A21\u578B\u7A97\u53E3\uFF08\u8F93\u5165 ${overflow.inputTokens} / \u7A97\u53E3 ${overflow.contextLimit}\uFF09\uFF0C\u9700\u8981\u538B\u7F29\u540E\u624D\u80FD\u7EE7\u7EED\u3002` };
24394
24630
  return;
24395
24631
  }
24396
- const delay2 = Math.min(1e3 * Math.pow(2, streamRetries), 16e3);
24632
+ const delay3 = Math.min(1e3 * Math.pow(2, streamRetries), 16e3);
24397
24633
  if (streamRetries < MAX_STREAM_RETRIES && !ac.signal.aborted) {
24398
- console.log(`${this.logPrefix} Turn ${turnCount}: stream retry ${streamRetries + 1}/${MAX_STREAM_RETRIES}, delay=${delay2}ms`);
24634
+ console.log(`${this.logPrefix} Turn ${turnCount}: stream retry ${streamRetries + 1}/${MAX_STREAM_RETRIES}, delay=${delay3}ms`);
24399
24635
  yield { type: "status", text: `\u26A0\uFE0F API error, retrying (${streamRetries + 1}/${MAX_STREAM_RETRIES})...` };
24400
24636
  this.phase = "tools";
24401
24637
  try {
24402
- await waitForRetry(delay2, void 0, { signal: ac.signal });
24638
+ await waitForRetry(delay3, void 0, { signal: ac.signal });
24403
24639
  } catch (error) {
24404
24640
  if (!ac.signal.aborted) throw error;
24405
24641
  }
@@ -24536,7 +24772,7 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
24536
24772
  completionReason = "output_limit";
24537
24773
  break;
24538
24774
  }
24539
- if (this.options.skipStopHook || perTurnEmotion) {
24775
+ if (context?.projectTask || this.options.skipStopHook || perTurnEmotion) {
24540
24776
  if (this.pendingSteers.length > 0) {
24541
24777
  const carried = carryReply();
24542
24778
  if (carried) yield* carried;
@@ -24845,8 +25081,8 @@ ${perTurnSystemDynamic}` : deferredHint || perTurnSystemDynamic;
24845
25081
  return this.provider;
24846
25082
  }
24847
25083
  /** Share model configuration, but give concurrent sessions their own abort/steer/compact state. */
24848
- fork(agentLabel) {
24849
- const fork2 = new _QueryEngine(this.provider, { ...this.options, agentLabel });
25084
+ fork(agentLabel, prompts) {
25085
+ const fork2 = new _QueryEngine(this.provider, { ...this.options, ...prompts, agentLabel });
24850
25086
  fork2.backgroundOwners = this.backgroundOwners;
24851
25087
  return fork2;
24852
25088
  }
@@ -25761,7 +25997,7 @@ __export(teamHelpers_exports, {
25761
25997
  writeTeamFileAsync: () => writeTeamFileAsync
25762
25998
  });
25763
25999
  import { mkdirSync as mkdirSync21, readFileSync as readFileSync21, writeFileSync as writeFileSync21 } from "node:fs";
25764
- import { mkdir, readFile, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
26000
+ import { mkdir as mkdir2, readFile, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
25765
26001
  import { join as join38 } from "node:path";
25766
26002
  function initTeamDirs(stateDir) {
25767
26003
  _stateDir = stateDir;
@@ -25808,7 +26044,7 @@ function writeTeamFile(teamName, teamFile) {
25808
26044
  }
25809
26045
  async function writeTeamFileAsync(teamName, teamFile) {
25810
26046
  const teamDir = getTeamDir(teamName);
25811
- await mkdir(teamDir, { recursive: true });
26047
+ await mkdir2(teamDir, { recursive: true });
25812
26048
  await writeFile3(getTeamFilePath(teamName), JSON.stringify(teamFile, null, 2));
25813
26049
  }
25814
26050
  async function withTeamFileLock(teamName, fn) {
@@ -26073,7 +26309,7 @@ The user interacts primarily with the team lead. Your work is coordinated throug
26073
26309
  });
26074
26310
 
26075
26311
  // src/swarm/teammateMailbox.ts
26076
- import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile4 } from "node:fs/promises";
26312
+ import { mkdir as mkdir3, readFile as readFile2, writeFile as writeFile4 } from "node:fs/promises";
26077
26313
  import { join as join39 } from "node:path";
26078
26314
  function getTeamsDir2() {
26079
26315
  return join39(process.env.ENGINE_STATE_DIR || ".", "teams");
@@ -26091,7 +26327,7 @@ async function ensureInboxDir(teamName) {
26091
26327
  const team = teamName || "default";
26092
26328
  const safeTeam = sanitizePathComponent(team);
26093
26329
  const inboxDir = join39(getTeamsDir2(), safeTeam, "inboxes");
26094
- await mkdir2(inboxDir, { recursive: true });
26330
+ await mkdir3(inboxDir, { recursive: true });
26095
26331
  }
26096
26332
  async function sleep2(ms) {
26097
26333
  return new Promise((resolve47) => setTimeout(resolve47, ms));
@@ -27944,7 +28180,7 @@ function formatSkillsListing(skills, contextWindowTokens) {
27944
28180
  function buildSkillToolPrompt() {
27945
28181
  return `Execute a skill within the main conversation
27946
28182
 
27947
- When users ask you to perform tasks, check if any of the available skills match. Skills provide specialized capabilities and domain knowledge.
28183
+ Skills provide specialized capabilities and domain knowledge.
27948
28184
 
27949
28185
  When users reference a "slash command" or "/<something>" (e.g., "/commit", "/review-pr"), they are referring to a skill. Use this tool to invoke it.
27950
28186
 
@@ -27958,16 +28194,13 @@ How to invoke:
27958
28194
 
27959
28195
  Important:
27960
28196
  - Available skills are listed in system-reminder messages in the conversation
27961
- - When a skill matches the user's request, this is a BLOCKING REQUIREMENT: invoke the relevant Skill tool BEFORE generating any other response about the task
27962
- - NEVER mention a skill without actually calling this tool
27963
28197
  - Do not invoke a skill that is already running
27964
28198
  - Do not use this tool for built-in CLI commands (like /help, /clear, etc.)
27965
28199
  - If you see a <${COMMAND_NAME_TAG}> tag in the current conversation turn, the skill has ALREADY been loaded - follow the instructions directly instead of calling this tool again
27966
28200
  `;
27967
28201
  }
27968
- function loadSkillContent(skillName) {
27969
- const entry = cachedSkills.find((s) => s.name === skillName);
27970
- const skillMdPath = entry?.location ? path29.join(skillsDirPath, entry.location.slice("skills/".length)) : path29.join(skillsDirPath, skillName, "SKILL.md");
28202
+ function loadSkillContent(skillsDir, skill) {
28203
+ const skillMdPath = skill.location ? path29.join(skillsDir, skill.location.slice("skills/".length)) : path29.join(skillsDir, skill.name, "SKILL.md");
27971
28204
  if (!fs25.existsSync(skillMdPath)) return null;
27972
28205
  const content = fs25.readFileSync(skillMdPath, "utf-8");
27973
28206
  const dependencies2 = parseFrontmatter(content)["requires-tools"];
@@ -27990,6 +28223,13 @@ function registerSkillTool(skillsDir, skills, contextWindowTokens) {
27990
28223
  skillsDirPath = skillsDir;
27991
28224
  cachedSkills = skills;
27992
28225
  cachedContextWindowTokens = contextWindowTokens;
28226
+ const groupedSkills = /* @__PURE__ */ new Map();
28227
+ for (const skill of skills) {
28228
+ const parts = skill.location?.split("/");
28229
+ if (!parts || parts[0] !== "skills" || parts.length < 4 || skill.name.includes(":")) continue;
28230
+ const qualifiedName = `${parts[1]}:${skill.name}`;
28231
+ if (!groupedSkills.has(qualifiedName)) groupedSkills.set(qualifiedName, skill);
28232
+ }
27993
28233
  const descriptionText = buildSkillToolPrompt();
27994
28234
  cachedListing = formatSkillsListing(cachedSkills, contextWindowTokens);
27995
28235
  registry.register({
@@ -28011,12 +28251,12 @@ function registerSkillTool(skillsDir, skills, contextWindowTokens) {
28011
28251
  return { content: "Invalid skill: empty name", isError: true };
28012
28252
  }
28013
28253
  const normalizedName = skillName.startsWith("/") ? skillName.substring(1) : skillName;
28014
- const skill = cachedSkills.find((s) => s.name === normalizedName);
28254
+ const skill = skills.find((s) => s.name === normalizedName) ?? groupedSkills.get(normalizedName);
28015
28255
  if (!skill) {
28016
- const available = cachedSkills.map((s) => s.name).join(", ");
28256
+ const available = skills.map((s) => s.name).join(", ");
28017
28257
  return { content: `Unknown skill: ${normalizedName}. Available: ${available}`, isError: true };
28018
28258
  }
28019
- const content = loadSkillContent(normalizedName);
28259
+ const content = loadSkillContent(skillsDir, skill);
28020
28260
  if (!content) {
28021
28261
  return { content: `Skill file not found: ${normalizedName}`, isError: true };
28022
28262
  }
@@ -28034,7 +28274,7 @@ ${loaded.content}
28034
28274
  const argLine = skillArgs ? `
28035
28275
 
28036
28276
  User arguments: ${skillArgs}` : "";
28037
- return { content: `Skill "${normalizedName}" loaded.${dependencyContent}
28277
+ return { content: `Skill "${skill.name}" loaded.${dependencyContent}
28038
28278
 
28039
28279
  ${content.content}${argLine}` };
28040
28280
  },
@@ -29384,6 +29624,13 @@ var init_registry2 = __esm({
29384
29624
  label: "\u60C5\u611F\u8F6E\u9759\u9ED8\u9608\u503C(\u8D85\u65F6\u4EAE\u5361)",
29385
29625
  effect: "hot"
29386
29626
  },
29627
+ {
29628
+ path: "display.preview.emotionWaitText",
29629
+ type: "string",
29630
+ group: "display",
29631
+ label: "\u79C1\u804A\u6162\u67E5\u8BE2\u65F6\u81EA\u9009\u7684\u4E00\u53E5\u8BDD",
29632
+ effect: "hot"
29633
+ },
29387
29634
  {
29388
29635
  path: "display.typing.enabled",
29389
29636
  type: "boolean",
@@ -30318,12 +30565,23 @@ var init_provider = __esm({
30318
30565
  }
30319
30566
  });
30320
30567
 
30568
+ // src/services/adaptive-proxy.ts
30569
+ import { HttpsProxyAgent } from "https-proxy-agent";
30570
+ import { Agent, Client, ProxyAgent, errors } from "undici";
30571
+ var direct;
30572
+ var init_adaptive_proxy = __esm({
30573
+ "src/services/adaptive-proxy.ts"() {
30574
+ "use strict";
30575
+ direct = new Agent();
30576
+ }
30577
+ });
30578
+
30321
30579
  // src/services/withRetry.ts
30322
- import { ProxyAgent } from "undici";
30323
30580
  var FIRST_READ_TIMEOUT_MS, NO_PROGRESS_TIMEOUT_MS;
30324
30581
  var init_withRetry = __esm({
30325
30582
  "src/services/withRetry.ts"() {
30326
30583
  "use strict";
30584
+ init_adaptive_proxy();
30327
30585
  FIRST_READ_TIMEOUT_MS = parseInt(process.env.API_TIMEOUT_MS || "", 10) || 6e5;
30328
30586
  NO_PROGRESS_TIMEOUT_MS = parseInt(process.env.STREAM_NO_PROGRESS_TIMEOUT_MS || "", 10) || 3e5;
30329
30587
  }
@@ -31113,7 +31371,7 @@ var init_wx_query = __esm({
31113
31371
  // src/continuity/pairing-host.ts
31114
31372
  init_publication_objects();
31115
31373
  init_key_service_store();
31116
- import { DatabaseSync as DatabaseSync41 } from "node:sqlite";
31374
+ import { DatabaseSync as DatabaseSync42 } from "node:sqlite";
31117
31375
  import { existsSync as existsSync42, readFileSync as readFileSync36, writeFileSync as writeFileSync42, renameSync as renameSync12, realpathSync as realpathSync30, openSync as openSync21, closeSync as closeSync20 } from "node:fs";
31118
31376
  import { join as join73, resolve as resolve46 } from "node:path";
31119
31377
  import { fileURLToPath as fileURLToPath9, pathToFileURL as pathToFileURL2 } from "node:url";
@@ -31124,7 +31382,7 @@ import { request as request8 } from "node:https";
31124
31382
  import { existsSync as existsSync26, mkdirSync as mkdirSync24, readFileSync as readFileSync26, writeFileSync as writeFileSync23, readdirSync as readdirSync11, cpSync, realpathSync as realpathSync13, symlinkSync, lstatSync as lstatSync18 } from "node:fs";
31125
31383
  import { join as join46 } from "node:path";
31126
31384
  import { homedir as homedir3 } from "node:os";
31127
- import { randomBytes as randomBytes4, createHash as createHash35, X509Certificate } from "node:crypto";
31385
+ import { randomBytes as randomBytes4, createHash as createHash36, X509Certificate } from "node:crypto";
31128
31386
  import { execFileSync as execFileSync2 } from "node:child_process";
31129
31387
  import { createServer } from "node:net";
31130
31388
 
@@ -33443,7 +33701,7 @@ var RuntimeRecoveryArchive = class _RuntimeRecoveryArchive {
33443
33701
  }
33444
33702
  };
33445
33703
  async function verifyContent(objects, content) {
33446
- const { createHash: createHash55 } = await import("node:crypto"), hash12 = createHash55("sha256");
33704
+ const { createHash: createHash56 } = await import("node:crypto"), hash12 = createHash56("sha256");
33447
33705
  for (const ref of content.chunks) hash12.update(await objects.read(ref));
33448
33706
  if (hash12.digest("hex") !== content.sha256) throw new Error("RECOVERY_CONTENT_CORRUPT");
33449
33707
  }
@@ -34155,7 +34413,7 @@ function resolveRequiredTools(features, licensedFeatures) {
34155
34413
  }
34156
34414
 
34157
34415
  // src/continuity/pairing-setup.ts
34158
- var sha6 = (value2) => createHash35("sha256").update(value2).digest("hex");
34416
+ var sha6 = (value2) => createHash36("sha256").update(value2).digest("hex");
34159
34417
  var write = (file2, value2) => writeFileSync23(file2, JSON.stringify(value2), { mode: 384, flush: true });
34160
34418
  var free = () => new Promise((done, reject) => {
34161
34419
  const server = createServer();
@@ -34442,13 +34700,13 @@ function publicPairingError(error) {
34442
34700
 
34443
34701
  // src/continuity/node-main.ts
34444
34702
  import { readFileSync as readFileSync32, lstatSync as lstatSync29, realpathSync as realpathSync27 } from "node:fs";
34445
- import { DatabaseSync as DatabaseSync36 } from "node:sqlite";
34446
- import { isAbsolute as isAbsolute12, resolve as resolve41 } from "node:path";
34703
+ import { DatabaseSync as DatabaseSync37 } from "node:sqlite";
34704
+ import { isAbsolute as isAbsolute13, resolve as resolve41 } from "node:path";
34447
34705
  import { fileURLToPath as fileURLToPath7 } from "node:url";
34448
- import { randomUUID as randomUUID22, createHash as createHash49 } from "node:crypto";
34706
+ import { randomUUID as randomUUID22, createHash as createHash50 } from "node:crypto";
34449
34707
 
34450
34708
  // src/continuity/node-agent.ts
34451
- import { DatabaseSync as DatabaseSync35 } from "node:sqlite";
34709
+ import { DatabaseSync as DatabaseSync36 } from "node:sqlite";
34452
34710
 
34453
34711
  // src/continuity/runtime-engine-config.ts
34454
34712
  import { join as join48, posix, win32 } from "node:path";
@@ -34477,14 +34735,14 @@ function runtimeEngineConfig(original, stateDir, workspace) {
34477
34735
 
34478
34736
  // src/continuity/node-agent.ts
34479
34737
  import { existsSync as existsSync38, lstatSync as lstatSync28, mkdirSync as mkdirSync31, readFileSync as readFileSync31, realpathSync as realpathSync26, writeFileSync as writeFileSync40 } from "node:fs";
34480
- import { isAbsolute as isAbsolute11, join as join70, resolve as resolve40 } from "node:path";
34481
- import { createHash as createHash47, randomUUID as randomUUID21 } from "node:crypto";
34738
+ import { isAbsolute as isAbsolute12, join as join70, resolve as resolve40 } from "node:path";
34739
+ import { createHash as createHash48, randomUUID as randomUUID21 } from "node:crypto";
34482
34740
  import { isIP as isIP2 } from "node:net";
34483
34741
 
34484
34742
  // src/continuity/activation.ts
34485
- import { DatabaseSync as DatabaseSync22 } from "node:sqlite";
34743
+ import { DatabaseSync as DatabaseSync23 } from "node:sqlite";
34486
34744
  import { constants as constants12, existsSync as existsSync32, mkdirSync as mkdirSync25, realpathSync as realpathSync17, unlinkSync as unlinkSync12, writeFileSync as writeFileSync29 } from "node:fs";
34487
- import { lstat as lstat4, mkdir as mkdir3, readdir as readdir2 } from "node:fs/promises";
34745
+ import { lstat as lstat4, mkdir as mkdir4, readdir as readdir2 } from "node:fs/promises";
34488
34746
 
34489
34747
  // src/continuity/activation-database-worker.ts
34490
34748
  import { spawn as spawn5 } from "node:child_process";
@@ -34493,7 +34751,7 @@ import { join as join49 } from "node:path";
34493
34751
  import { fileURLToPath as fileURLToPath6 } from "node:url";
34494
34752
 
34495
34753
  // src/continuity/activation-database.ts
34496
- import { DatabaseSync as DatabaseSync18 } from "node:sqlite";
34754
+ import { DatabaseSync as DatabaseSync19 } from "node:sqlite";
34497
34755
  init_sqlite_replication();
34498
34756
  init_mem7_replication();
34499
34757
  init_runtime_replication();
@@ -34523,7 +34781,7 @@ function initializeRecoveryAdmission(db2) {
34523
34781
  function initializeActivationDatabase(file2, raw) {
34524
34782
  const binding = normalizeBinding(raw), place = sqliteStoreLocation(file2);
34525
34783
  if (!place) throw Error("TRAVEL_ACTIVATION_SCHEMA");
34526
- const db2 = new DatabaseSync18(file2, { allowExtension: place.component === "legacy-memory" });
34784
+ const db2 = new DatabaseSync19(file2, { allowExtension: place.component === "legacy-memory" });
34527
34785
  try {
34528
34786
  if (place.component === "legacy-memory") loadLegacySQLiteVectorExtension(db2);
34529
34787
  const version = readSchemaVersion(db2);
@@ -34587,12 +34845,12 @@ async function runActivationDatabaseWorker(root, file2, binding, assertCurrent)
34587
34845
 
34588
34846
  // src/continuity/activation.ts
34589
34847
  init_runtime_authority();
34590
- import { dirname as dirname21, isAbsolute as isAbsolute5, join as join54, resolve as resolve31 } from "node:path";
34848
+ import { dirname as dirname22, isAbsolute as isAbsolute6, join as join54, resolve as resolve31 } from "node:path";
34591
34849
  init_schema_migrations();
34592
34850
  init_key_service_store();
34593
34851
 
34594
34852
  // src/continuity/generation-integrity.ts
34595
- import { createHash as createHash36 } from "node:crypto";
34853
+ import { createHash as createHash37 } from "node:crypto";
34596
34854
  import { constants as constants11, closeSync as closeSync17, fstatSync as fstatSync7, lstatSync as lstatSync19, openSync as openSync18, readSync as readSync6, readdirSync as readdirSync12, realpathSync as realpathSync14 } from "node:fs";
34597
34855
  import { join as join50, resolve as resolve28 } from "node:path";
34598
34856
  import { open as open5 } from "node:fs/promises";
@@ -34626,7 +34884,7 @@ function runtimeGenerationIntegrity(directory2) {
34626
34884
  const files = generationFiles(root);
34627
34885
  for (const { path: path37, stat: before } of files) {
34628
34886
  const file2 = join50(root, path37);
34629
- const fd = openSync18(file2, constants11.O_RDONLY | (constants11.O_NOFOLLOW ?? 0)), hash12 = createHash36("sha256");
34887
+ const fd = openSync18(file2, constants11.O_RDONLY | (constants11.O_NOFOLLOW ?? 0)), hash12 = createHash37("sha256");
34630
34888
  let bytes = 0;
34631
34889
  try {
34632
34890
  while (true) {
@@ -34649,7 +34907,7 @@ async function runtimeGenerationIntegrityAsync(directory2) {
34649
34907
  const root = resolve28(directory2), result = [], buffer = Buffer.allocUnsafe(1024 * 1024);
34650
34908
  const files = generationFiles(root);
34651
34909
  for (const { path: path37, stat: before } of files) {
34652
- const file2 = join50(root, path37), handle = await open5(file2, constants11.O_RDONLY | (constants11.O_NOFOLLOW ?? 0)), hash12 = createHash36("sha256");
34910
+ const file2 = join50(root, path37), handle = await open5(file2, constants11.O_RDONLY | (constants11.O_NOFOLLOW ?? 0)), hash12 = createHash37("sha256");
34653
34911
  let bytes = 0;
34654
34912
  try {
34655
34913
  while (true) {
@@ -34685,16 +34943,16 @@ async function verifyRuntimeGenerationIntegrityAsync(directory2, expected) {
34685
34943
 
34686
34944
  // src/continuity/recovery-deletion-visibility.ts
34687
34945
  init_key_service_store();
34688
- import { DatabaseSync as DatabaseSync21 } from "node:sqlite";
34689
- import { createHash as createHash39, randomUUID as randomUUID17 } from "node:crypto";
34946
+ import { DatabaseSync as DatabaseSync22 } from "node:sqlite";
34947
+ import { createHash as createHash40, randomUUID as randomUUID17 } from "node:crypto";
34690
34948
  import { existsSync as existsSync31, realpathSync as realpathSync16, renameSync as renameSync11, unlinkSync as unlinkSync11, writeFileSync as writeFileSync28 } from "node:fs";
34691
34949
  import { join as join53, resolve as resolve30 } from "node:path";
34692
34950
 
34693
34951
  // src/continuity/recovery-deletion-overlay.ts
34694
- import { DatabaseSync as DatabaseSync20 } from "node:sqlite";
34695
- import { createHash as createHash38, randomUUID as randomUUID16 } from "node:crypto";
34952
+ import { DatabaseSync as DatabaseSync21 } from "node:sqlite";
34953
+ import { createHash as createHash39, randomUUID as randomUUID16 } from "node:crypto";
34696
34954
  import { existsSync as existsSync30, realpathSync as realpathSync15, renameSync as renameSync10, unlinkSync as unlinkSync10, writeFileSync as writeFileSync27 } from "node:fs";
34697
- import { dirname as dirname20, join as join52, resolve as resolve29 } from "node:path";
34955
+ import { dirname as dirname21, join as join52, resolve as resolve29 } from "node:path";
34698
34956
  init_key_service_store();
34699
34957
  init_recovery_deletion_sources();
34700
34958
  init_recovery_deletion();
@@ -34711,17 +34969,17 @@ init_vector_publications();
34711
34969
  // src/continuity/recovery-deletion-runtime-copies.ts
34712
34970
  init_scope();
34713
34971
  init_schema_migrations();
34714
- import { DatabaseSync as DatabaseSync19 } from "node:sqlite";
34715
- import { createHash as createHash37 } from "node:crypto";
34972
+ import { DatabaseSync as DatabaseSync20 } from "node:sqlite";
34973
+ import { createHash as createHash38 } from "node:crypto";
34716
34974
  import { gunzipSync as gunzipSync3 } from "node:zlib";
34717
34975
  import { isUtf8 } from "node:buffer";
34718
34976
  import { rmSync as rmSync4, writeFileSync as writeFileSync26, existsSync as existsSync29, unlinkSync as unlinkSync9 } from "node:fs";
34719
- import { join as join51, dirname as dirname19 } from "node:path";
34977
+ import { join as join51, dirname as dirname20 } from "node:path";
34720
34978
  init_sqlite_replication();
34721
34979
  init_key_service_store();
34722
34980
  init_attachments();
34723
34981
  init_result_snapshot();
34724
- var sha7 = (bytes) => createHash37("sha256").update(bytes).digest("hex");
34982
+ var sha7 = (bytes) => createHash38("sha256").update(bytes).digest("hex");
34725
34983
  var object3 = (value2) => !!value2 && typeof value2 === "object" && !Array.isArray(value2);
34726
34984
  var currentDebugCaches = /* @__PURE__ */ new Set([".context-debug.txt", ".system-prompt.txt"]);
34727
34985
  async function cleanRecoveryDeletionRuntimeCopies(options) {
@@ -34867,7 +35125,7 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
34867
35125
  if (existsSync29(path38)) {
34868
35126
  check();
34869
35127
  unlinkSync9(path38);
34870
- await syncDirectory(dirname19(path38));
35128
+ await syncDirectory(dirname20(path38));
34871
35129
  check();
34872
35130
  debugCaches++;
34873
35131
  }
@@ -34893,7 +35151,7 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
34893
35151
  writeFileSync26(path37, retained, { flush: true });
34894
35152
  const cursor2 = path37 + ".cursor";
34895
35153
  if (file2.path === "mem7/spool/intake.processing.jsonl" && existsSync29(cursor2)) unlinkSync9(cursor2);
34896
- await syncDirectory(dirname19(path37));
35154
+ await syncDirectory(dirname20(path37));
34897
35155
  check();
34898
35156
  intakeRecords += removed;
34899
35157
  }
@@ -35000,7 +35258,7 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
35000
35258
  }
35001
35259
  if (!updates.length) continue;
35002
35260
  const directory2 = join51(options.root, "sessions", tree.id);
35003
- const copy = new DatabaseSync19(join51(directory2, ".continuity/session-events.db"), { readOnly: true });
35261
+ const copy = new DatabaseSync20(join51(directory2, ".continuity/session-events.db"), { readOnly: true });
35004
35262
  try {
35005
35263
  validateRecoveryDatabase(copy, options.manifest, databaseId, "replica");
35006
35264
  } finally {
@@ -35044,7 +35302,7 @@ async function cleanRecoveryDeletionRuntimeCopies(options) {
35044
35302
 
35045
35303
  // src/continuity/recovery-deletion-overlay.ts
35046
35304
  var same4 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
35047
- var sha8 = (value2) => createHash38("sha256").update(value2).digest("hex");
35305
+ var sha8 = (value2) => createHash39("sha256").update(value2).digest("hex");
35048
35306
  var evidenceRow = (row) => Object.fromEntries(Object.entries(row).map(([key3, value2]) => [
35049
35307
  key3,
35050
35308
  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")]
@@ -35095,20 +35353,20 @@ async function deletionOverlay(options, runtimeCopies) {
35095
35353
  if (floor <= manifest.deletionWatermark) throw new Error("RECOVERY_OVERLAY_NOT_REQUIRED");
35096
35354
  const handles = [], databases = /* @__PURE__ */ new Map();
35097
35355
  const closeHandles = () => {
35098
- const errors = [];
35356
+ const errors2 = [];
35099
35357
  while (handles.length) {
35100
35358
  try {
35101
35359
  handles.pop().close();
35102
35360
  } catch (error) {
35103
- errors.push(error);
35361
+ errors2.push(error);
35104
35362
  }
35105
35363
  }
35106
- if (errors.length) throw new AggregateError(errors, "RECOVERY_OVERLAY_CLOSE_FAILED");
35364
+ if (errors2.length) throw new AggregateError(errors2, "RECOVERY_OVERLAY_CLOSE_FAILED");
35107
35365
  };
35108
35366
  let memory, capture2 = false;
35109
35367
  try {
35110
35368
  for (const d of manifest.databases) {
35111
- const db3 = new DatabaseSync20(join52(root, "databases", d.databaseId + ".sqlite"), { readOnly: d.databaseId !== "memory" && (!runtimeCopies || d.databaseId !== "sessions") });
35369
+ const db3 = new DatabaseSync21(join52(root, "databases", d.databaseId + ".sqlite"), { readOnly: d.databaseId !== "memory" && (!runtimeCopies || d.databaseId !== "sessions") });
35112
35370
  handles.push(db3);
35113
35371
  databases.set(d.databaseId, db3);
35114
35372
  validateRecoveryDatabase(db3, manifest, d.databaseId, "replica");
@@ -35201,7 +35459,7 @@ async function deletionOverlay(options, runtimeCopies) {
35201
35459
  await check();
35202
35460
  if (empty) unlinkSync10(file2);
35203
35461
  else writeFileSync27(file2, text2, { flush: true });
35204
- await syncDirectory(dirname20(file2));
35462
+ await syncDirectory(dirname21(file2));
35205
35463
  await check();
35206
35464
  removedFiles.push("trees/" + matches[0].id + "/mem7/" + path37);
35207
35465
  }
@@ -35277,7 +35535,7 @@ async function deletionOverlay(options, runtimeCopies) {
35277
35535
  // src/continuity/recovery-deletion-visibility.ts
35278
35536
  init_schema_migrations();
35279
35537
  var same5 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
35280
- var sha9 = (value2) => createHash39("sha256").update(value2).digest("hex");
35538
+ var sha9 = (value2) => createHash40("sha256").update(value2).digest("hex");
35281
35539
  var format = "engine7-current-h-deletion-visibility-v1";
35282
35540
  function receipt(options) {
35283
35541
  const root = resolve30(options.snapshot);
@@ -35291,7 +35549,7 @@ async function effectsCheckAsync(options, floor) {
35291
35549
  }
35292
35550
  function validateAuxiliaryState(options) {
35293
35551
  for (const id2 of options.manifest.profile.databaseIds) {
35294
- const db2 = new DatabaseSync21(join53(options.snapshot, "databases", id2 + ".sqlite"), { readOnly: true });
35552
+ const db2 = new DatabaseSync22(join53(options.snapshot, "databases", id2 + ".sqlite"), { readOnly: true });
35295
35553
  try {
35296
35554
  const component = readSchemaVersion(db2)?.component;
35297
35555
  if (component === "mem7") continue;
@@ -35375,7 +35633,7 @@ async function verifyCurrentHDeletionVisibilityAsync(options) {
35375
35633
  init_publication_objects();
35376
35634
  async function verifyRuntimeDirectory(directory2) {
35377
35635
  try {
35378
- if (!isAbsolute5(directory2) || resolve31(directory2) !== directory2) return false;
35636
+ if (!isAbsolute6(directory2) || resolve31(directory2) !== directory2) return false;
35379
35637
  assertPrivateDirectory(directory2);
35380
35638
  return true;
35381
35639
  } catch {
@@ -35437,7 +35695,7 @@ function validateRuntimeActivationLayout(destination, raw, layout) {
35437
35695
  function validateRuntimeActivationSnapshot(snapshot, manifest, locations) {
35438
35696
  const sourceRoots = [];
35439
35697
  for (const d of manifest.databases) {
35440
- const db2 = new DatabaseSync22(join54(snapshot, "databases", d.databaseId + ".sqlite"), { readOnly: true });
35698
+ const db2 = new DatabaseSync23(join54(snapshot, "databases", d.databaseId + ".sqlite"), { readOnly: true });
35441
35699
  try {
35442
35700
  validateRecoveryDatabase(db2, manifest, d.databaseId, "replica", void 0, false);
35443
35701
  const place = locations.get(d.databaseId);
@@ -35460,7 +35718,7 @@ async function copyTree(from, to, skipControl = false) {
35460
35718
  }
35461
35719
  return;
35462
35720
  }
35463
- await mkdir3(to, { recursive: true, mode: 448 });
35721
+ await mkdir4(to, { recursive: true, mode: 448 });
35464
35722
  for (const name of await readdir2(from)) {
35465
35723
  if (skipControl && (name.startsWith(".") || name === "databases" || name === "trees" || name === "lance")) continue;
35466
35724
  await copyTree(join54(from, name), join54(to, name));
@@ -35488,8 +35746,8 @@ async function activateRuntimeGeneration(options) {
35488
35746
  return floor;
35489
35747
  };
35490
35748
  await checkDeletion();
35491
- if (!await (options.verifyDirectory ?? verifyRuntimeDirectory)(dirname21(destination))) throw new Error("TRAVEL_ACTIVATION_DIRECTORY");
35492
- if (realpathSync17(snapshot) !== snapshot || realpathSync17(dirname21(destination)) !== dirname21(destination) || existsSync32(destination)) throw new Error("TRAVEL_ACTIVATION_NEW_DIRECTORY_REQUIRED");
35749
+ if (!await (options.verifyDirectory ?? verifyRuntimeDirectory)(dirname22(destination))) throw new Error("TRAVEL_ACTIVATION_DIRECTORY");
35750
+ if (realpathSync17(snapshot) !== snapshot || realpathSync17(dirname22(destination)) !== dirname22(destination) || existsSync32(destination)) throw new Error("TRAVEL_ACTIVATION_NEW_DIRECTORY_REQUIRED");
35493
35751
  const proof = JSON.parse(readPrivateFile(join54(snapshot, ".runtime-publication-receipt.json"), 4 * 1024 * 1024).toString());
35494
35752
  if (proof.format !== "engine7-runtime-publication-restore-v1" || !same6(proof.profile, manifest.profile) || proof.receipt?.digest !== digest7 || proof.receipt?.sequence !== manifest.sequence || proof.receipt?.state !== "PUBLISHED" || proof.activationAllowed !== false || !same6(proof.databases, manifest.databases)) throw new Error("TRAVEL_ACTIVATION_RECEIPT");
35495
35753
  await verifyRuntimeGenerationIntegrityAsync(snapshot, proof.integrity);
@@ -35513,7 +35771,7 @@ async function activateRuntimeGeneration(options) {
35513
35771
  await checkDeletion();
35514
35772
  await options.authority.assertPermit(runtime.assert("CONTROL"), "CONTROL");
35515
35773
  const path37 = join54(destination, options.layout.databases[d.databaseId]), place = locations.get(d.databaseId);
35516
- mkdirSync25(dirname21(path37), { recursive: true, mode: 448 });
35774
+ mkdirSync25(dirname22(path37), { recursive: true, mode: 448 });
35517
35775
  try {
35518
35776
  await copyNativeFile(join54(snapshot, "databases", d.databaseId + ".sqlite"), path37, copyFlags);
35519
35777
  } catch (error) {
@@ -35524,7 +35782,7 @@ async function activateRuntimeGeneration(options) {
35524
35782
  options.assertStaging?.();
35525
35783
  runtime.assert("CONTROL");
35526
35784
  });
35527
- await syncDirectory(dirname21(path37));
35785
+ await syncDirectory(dirname22(path37));
35528
35786
  }
35529
35787
  const receipt2 = {
35530
35788
  format: "engine7-runtime-activation-v1",
@@ -35565,10 +35823,10 @@ init_runtime_authority();
35565
35823
  init_publication_objects();
35566
35824
  init_key_service_store();
35567
35825
  import { fork } from "node:child_process";
35568
- import { DatabaseSync as DatabaseSync23 } from "node:sqlite";
35826
+ import { DatabaseSync as DatabaseSync24 } from "node:sqlite";
35569
35827
  import { closeSync as closeSync18, lstatSync as lstatSync20, openSync as openSync19, readFileSync as readFileSync29, realpathSync as realpathSync18 } from "node:fs";
35570
- import { isAbsolute as isAbsolute6, join as join55 } from "node:path";
35571
- import { createHash as createHash40, randomUUID as randomUUID18 } from "node:crypto";
35828
+ import { isAbsolute as isAbsolute7, join as join55 } from "node:path";
35829
+ import { createHash as createHash41, randomUUID as randomUUID18 } from "node:crypto";
35572
35830
 
35573
35831
  // src/continuity/engine-control.ts
35574
35832
  init_runtime_authority();
@@ -35630,13 +35888,13 @@ function supervisedRuntimeEnvironment(config, parent, environmentNames = []) {
35630
35888
  var SupervisedRuntimeProcess = class {
35631
35889
  constructor(options) {
35632
35890
  this.options = options;
35633
- if (![options.directory, options.entry, options.configFile].every(isAbsolute6) || !/^[a-f0-9]{64}$/.test(options.entrySha256)) throw new Error("TRAVEL_PROCESS_CONFIG");
35891
+ if (![options.directory, options.entry, options.configFile].every(isAbsolute7) || !/^[a-f0-9]{64}$/.test(options.entrySha256)) throw new Error("TRAVEL_PROCESS_CONFIG");
35634
35892
  this.timeout = options.timeoutMs ?? 6e4;
35635
35893
  if (!Number.isSafeInteger(this.timeout) || this.timeout < 100 || this.timeout > 6e5) throw new Error("TRAVEL_PROCESS_CONFIG");
35636
35894
  preparePrivateDirectory(options.directory);
35637
35895
  const ownerFile = join55(options.directory, "process-owner.sqlite");
35638
35896
  preparePrivateDatabase(ownerFile);
35639
- this.owner = new DatabaseSync23(ownerFile);
35897
+ this.owner = new DatabaseSync24(ownerFile);
35640
35898
  try {
35641
35899
  this.owner.exec("CREATE TABLE IF NOT EXISTS owner(id INTEGER PRIMARY KEY);BEGIN IMMEDIATE");
35642
35900
  } catch {
@@ -35646,7 +35904,7 @@ var SupervisedRuntimeProcess = class {
35646
35904
  try {
35647
35905
  const file2 = join55(options.directory, "process.sqlite");
35648
35906
  preparePrivateDatabase(file2);
35649
- this.db = new DatabaseSync23(file2);
35907
+ this.db = new DatabaseSync24(file2);
35650
35908
  this.db.exec("PRAGMA synchronous=FULL;CREATE TABLE IF NOT EXISTS generations(binding TEXT PRIMARY KEY,entry_hash TEXT NOT NULL);CREATE TABLE IF NOT EXISTS recovery_continuations(binding TEXT PRIMARY KEY,entry_hash TEXT NOT NULL,authority_boot_id TEXT NOT NULL,state TEXT NOT NULL CHECK(state IN ('SUSPENDED','RESUMING','RESUMED')))");
35651
35909
  if (this.db.prepare("PRAGMA quick_check").get()?.quick_check !== "ok") throw new Error("TRAVEL_PROCESS_RECOVERY_REQUIRED");
35652
35910
  } catch (error) {
@@ -35682,7 +35940,7 @@ var SupervisedRuntimeProcess = class {
35682
35940
  if (retired && (!recovery || continuation?.state !== "SUSPENDED" || continuation.entry_hash !== this.options.entrySha256 || continuation.authority_boot_id !== permit.authorityBootId)) throw new Error("TRAVEL_PROCESS_GENERATION_RETIRED");
35683
35941
  if (recovery && !retired) throw new Error("TRAVEL_PROCESS_GENERATION_RETIRED");
35684
35942
  const info = lstatSync20(this.options.entry);
35685
- if (!info.isFile() || info.isSymbolicLink() || info.size > 64 * 1024 * 1024 || realpathSync18(this.options.entry) !== this.options.entry || createHash40("sha256").update(readFileSync29(this.options.entry)).digest("hex") !== this.options.entrySha256) throw new Error("TRAVEL_PROCESS_BUILD");
35943
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 64 * 1024 * 1024 || realpathSync18(this.options.entry) !== this.options.entry || createHash41("sha256").update(readFileSync29(this.options.entry)).digest("hex") !== this.options.entrySha256) throw new Error("TRAVEL_PROCESS_BUILD");
35686
35944
  let environment;
35687
35945
  try {
35688
35946
  environment = supervisedRuntimeEnvironment(JSON.parse(readPrivateFile(this.options.configFile, 1024 * 1024).toString()), process.env, this.options.environmentNames);
@@ -35865,21 +36123,21 @@ var SupervisedRuntimeProcess = class {
35865
36123
  };
35866
36124
 
35867
36125
  // src/continuity/runtime-publication-restore.ts
35868
- import { DatabaseSync as DatabaseSync25 } from "node:sqlite";
36126
+ import { DatabaseSync as DatabaseSync26 } from "node:sqlite";
35869
36127
  import { mkdirSync as mkdirSync27, writeFileSync as writeFileSync31 } from "node:fs";
35870
36128
  import { join as join57, resolve as resolve33 } from "node:path";
35871
36129
 
35872
36130
  // src/continuity/publication-files.ts
35873
- import { DatabaseSync as DatabaseSync24 } from "node:sqlite";
36131
+ import { DatabaseSync as DatabaseSync25 } from "node:sqlite";
35874
36132
  import { lstatSync as lstatSync21, readdirSync as readdirSync13, realpathSync as realpathSync19, mkdirSync as mkdirSync26, writeFileSync as writeFileSync30, chmodSync as chmodSync7, openSync as openSync20, closeSync as closeSync19, fsyncSync as fsyncSync11 } from "node:fs";
35875
- import { join as join56, resolve as resolve32, dirname as dirname22 } from "node:path";
36133
+ import { join as join56, resolve as resolve32, dirname as dirname23 } from "node:path";
35876
36134
  async function restorePublication(options) {
35877
36135
  const { receiver } = options, status = await receiver.status(false);
35878
36136
  if (!status.published || !status.dataReady) throw new Error("PUBLICATION_NOT_READY");
35879
36137
  const manifest = await receiver.manifest(status.published.sequence);
35880
36138
  if (JSON.stringify(Object.keys(options.databases).sort()) !== JSON.stringify(manifest.profile.databaseIds)) throw new Error("PUBLICATION_INCOMPLETE_DATABASES");
35881
36139
  const destination = resolve32(options.destination);
35882
- if (realpathSync19(dirname22(destination)) !== dirname22(destination)) throw new Error("SYMLINK_REFUSED");
36140
+ if (realpathSync19(dirname23(destination)) !== dirname23(destination)) throw new Error("SYMLINK_REFUSED");
35883
36141
  if (isWithin(receiver.objects.directory, destination) || isWithin(destination, receiver.objects.directory)) throw new Error("PUBLICATION_OVERLAPPING_PATHS");
35884
36142
  try {
35885
36143
  mkdirSync26(destination, { mode: 448 });
@@ -35887,7 +36145,7 @@ async function restorePublication(options) {
35887
36145
  if (error.code === "EEXIST") throw new Error("CONTINUITY_DESTINATION_EXISTS");
35888
36146
  throw error;
35889
36147
  }
35890
- await syncDirectory(dirname22(destination));
36148
+ await syncDirectory(dirname23(destination));
35891
36149
  writeFileSync30(join56(destination, ".travel-restored.json"), JSON.stringify({
35892
36150
  format: "engine7-publication-restore-v1",
35893
36151
  activationAllowed: false,
@@ -35898,7 +36156,7 @@ async function restorePublication(options) {
35898
36156
  const created = /* @__PURE__ */ new Set([destination]);
35899
36157
  const directory2 = (path37) => {
35900
36158
  const missing = [];
35901
- for (let current2 = path37; isWithin(destination, current2) && !created.has(current2); current2 = dirname22(current2)) missing.push(current2);
36159
+ for (let current2 = path37; isWithin(destination, current2) && !created.has(current2); current2 = dirname23(current2)) missing.push(current2);
35902
36160
  for (const current2 of missing.reverse()) {
35903
36161
  mkdirSync26(current2, { mode: 448 });
35904
36162
  created.add(current2);
@@ -35910,7 +36168,7 @@ async function restorePublication(options) {
35910
36168
  const path37 = join56(destination, "databases", item.databaseId + ".sqlite");
35911
36169
  await snapshotNativeDatabase(options.databases[item.databaseId], path37);
35912
36170
  chmodSync7(path37, 384);
35913
- const copy = new DatabaseSync24(path37, { readOnly: true });
36171
+ const copy = new DatabaseSync25(path37, { readOnly: true });
35914
36172
  try {
35915
36173
  const row = copy.prepare("SELECT head,digest,binding FROM e7_replication_control WHERE role='replica'").get();
35916
36174
  const identity3 = manifest.profile.identity;
@@ -35934,7 +36192,7 @@ async function restorePublication(options) {
35934
36192
  for (const path37 of tree.directories) directory2(join56(root, path37));
35935
36193
  for (const file2 of tree.files) {
35936
36194
  const path37 = join56(root, file2.path);
35937
- directory2(dirname22(path37));
36195
+ directory2(dirname23(path37));
35938
36196
  files.push({ content: file2.content, destination: path37, mode: file2.mode });
35939
36197
  }
35940
36198
  }
@@ -35987,7 +36245,7 @@ async function restoreRuntimePublication(options) {
35987
36245
  lance.push({ treeId: tree.id, directory: `lance/${tree.id}` });
35988
36246
  }
35989
36247
  for (const session of sessions2) {
35990
- const directory2 = join57(destination, "sessions", session.treeId), db2 = new DatabaseSync25(join57(destination, "databases", session.databaseId + ".sqlite"), { readOnly: true });
36248
+ const directory2 = join57(destination, "sessions", session.treeId), db2 = new DatabaseSync26(join57(destination, "databases", session.databaseId + ".sqlite"), { readOnly: true });
35991
36249
  try {
35992
36250
  const head = db2.prepare("SELECT head,digest FROM e7_replication_control WHERE role='replica'").get();
35993
36251
  if (head?.head !== session.head.sequence || head.digest !== session.head.digest) throw new Error("PUBLICATION_DATABASE_SNAPSHOT_MISMATCH");
@@ -36021,17 +36279,17 @@ import { join as join59 } from "node:path";
36021
36279
  // src/continuity/runtime-generation-source.ts
36022
36280
  init_key_service_store();
36023
36281
  init_publication_objects();
36024
- import { DatabaseSync as DatabaseSync26 } from "node:sqlite";
36282
+ import { DatabaseSync as DatabaseSync27 } from "node:sqlite";
36025
36283
  import { existsSync as existsSync33, lstatSync as lstatSync22, realpathSync as realpathSync20 } from "node:fs";
36026
- import { createHash as createHash41 } from "node:crypto";
36027
- import { isAbsolute as isAbsolute7, join as join58, resolve as resolve34 } from "node:path";
36284
+ import { createHash as createHash42 } from "node:crypto";
36285
+ import { isAbsolute as isAbsolute8, join as join58, resolve as resolve34 } from "node:path";
36028
36286
  init_sqlite_replication();
36029
36287
  init_schema_migrations();
36030
36288
  init_runtime_lock();
36031
36289
  init_runtime_authority();
36032
36290
  var same7 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
36033
36291
  async function openRuntimeGenerationSource(options) {
36034
- for (const path37 of [options.stateDir, options.dataDirectory]) if (!isAbsolute7(path37) || resolve34(path37) !== path37) throw new Error("TRAVEL_SOURCE_PATH");
36292
+ for (const path37 of [options.stateDir, options.dataDirectory]) if (!isAbsolute8(path37) || resolve34(path37) !== path37) throw new Error("TRAVEL_SOURCE_PATH");
36035
36293
  const stateDir = options.stateDir, dataDirectory = options.dataDirectory;
36036
36294
  assertPrivateDirectory(stateDir);
36037
36295
  if (realpathSync20(stateDir) !== stateDir || realpathSync20(join58(dataDirectory, "..")) !== resolve34(dataDirectory, "..") || isWithin(stateDir, dataDirectory) || isWithin(dataDirectory, stateDir) || isWithin(stateDir, options.objects.directory)) throw new Error("TRAVEL_SOURCE_PATH");
@@ -36082,7 +36340,7 @@ async function openRuntimeGenerationSource(options) {
36082
36340
  validatePublicationPath(path37);
36083
36341
  const file2 = join58(stateDir, path37), place = sqliteStoreLocation(file2), info = lstatSync22(file2);
36084
36342
  if (!place || !isWithin(stateDir, place.stateDir) || !info.isFile() || info.isSymbolicLink() || realpathSync20(file2) !== file2 || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid())) throw new Error("TRAVEL_SOURCE_LAYOUT");
36085
- const db2 = new DatabaseSync26(file2, { readOnly: options.mode === "SEALED", allowExtension: options.mode === "LIVE" && place.component === "legacy-memory" });
36343
+ const db2 = new DatabaseSync27(file2, { readOnly: options.mode === "SEALED", allowExtension: options.mode === "LIVE" && place.component === "legacy-memory" });
36086
36344
  handles[id2] = db2;
36087
36345
  const schema5 = readSchemaVersion(db2), registration = readSQLiteStoreRegistration(place), actual = readSQLiteReplicationSource(db2);
36088
36346
  const binding = normalizeBinding({ ...profile.identity, databaseId: id2, baselineId: profile.baselineId, epoch: profile.epoch });
@@ -36106,7 +36364,7 @@ async function openRuntimeGenerationSource(options) {
36106
36364
  }
36107
36365
  if (sessionTrees.length !== profile.trees.filter((tree) => tree.kind === "session").length) throw new Error("TRAVEL_SOURCE_LAYOUT");
36108
36366
  const lanceStores = profile.trees.filter((tree) => tree.kind === "vector").map((tree) => ({ treeId: tree.id, directory: join58(stateDir, layout.trees[tree.id]) }));
36109
- const layoutDigest = createHash41("sha256").update(JSON.stringify([stateDir, profile, layout])).digest("hex");
36367
+ const layoutDigest = createHash42("sha256").update(JSON.stringify([stateDir, profile, layout])).digest("hex");
36110
36368
  trees = await RuntimeTreeSource.open({ directory: join58(dataDirectory, "runtime-trees"), profile, objects: options.objects, initialize: options.initialize });
36111
36369
  source = await RuntimePublicationSource.open({ directory: join58(dataDirectory, "runtime-publications"), profile, objects: options.objects, trees, layoutDigest, initialize: options.initialize });
36112
36370
  const capture2 = () => {
@@ -36292,7 +36550,7 @@ init_publication_objects();
36292
36550
 
36293
36551
  // src/optional/reporting/travel.ts
36294
36552
  init_publication_objects();
36295
- import { DatabaseSync as DatabaseSync27 } from "node:sqlite";
36553
+ import { DatabaseSync as DatabaseSync28 } from "node:sqlite";
36296
36554
  import { join as join60 } from "node:path";
36297
36555
  function startTravelHeartbeatReporting(options) {
36298
36556
  const interval = options.intervalMs ?? 1e4, clock2 = options.monotonicNow ?? (() => Number(process.hrtime.bigint() / 1000000n));
@@ -36301,7 +36559,7 @@ function startTravelHeartbeatReporting(options) {
36301
36559
  preparePrivateDirectory(options.directory);
36302
36560
  const ownerFile = join60(options.directory, "heartbeat-owner.sqlite");
36303
36561
  preparePrivateDatabase(ownerFile);
36304
- const owner = new DatabaseSync27(ownerFile);
36562
+ const owner = new DatabaseSync28(ownerFile);
36305
36563
  try {
36306
36564
  owner.exec("CREATE TABLE IF NOT EXISTS owner(id INTEGER PRIMARY KEY);BEGIN IMMEDIATE");
36307
36565
  } catch {
@@ -36312,7 +36570,7 @@ function startTravelHeartbeatReporting(options) {
36312
36570
  try {
36313
36571
  const file2 = join60(options.directory, "heartbeat.sqlite");
36314
36572
  preparePrivateDatabase(file2);
36315
- db2 = new DatabaseSync27(file2);
36573
+ db2 = new DatabaseSync28(file2);
36316
36574
  db2.exec("PRAGMA synchronous=FULL;CREATE TABLE IF NOT EXISTS sequences(node TEXT NOT NULL,boot TEXT NOT NULL,sequence INTEGER NOT NULL,PRIMARY KEY(node,boot))");
36317
36575
  if (db2.prepare("PRAGMA quick_check").get()?.quick_check !== "ok") throw new Error("TRAVEL_REPORTING_RECOVERY_REQUIRED");
36318
36576
  db2.prepare("INSERT OR IGNORE INTO sequences VALUES(?,?,0)").run(options.nodeId, options.bootId);
@@ -36440,9 +36698,9 @@ function startTravelHeartbeatReporting(options) {
36440
36698
  init_key_service_store();
36441
36699
 
36442
36700
  // src/continuity/recovery-archive-restore.ts
36443
- import { DatabaseSync as DatabaseSync28 } from "node:sqlite";
36701
+ import { DatabaseSync as DatabaseSync29 } from "node:sqlite";
36444
36702
  import { mkdirSync as mkdirSync28, writeFileSync as writeFileSync32, realpathSync as realpathSync21 } from "node:fs";
36445
- import { dirname as dirname23, join as join61, resolve as resolve35 } from "node:path";
36703
+ import { dirname as dirname24, join as join61, resolve as resolve35 } from "node:path";
36446
36704
  init_sqlite_replication();
36447
36705
  async function restoreRecoveryArchive(options) {
36448
36706
  return restoreOriginal(options);
@@ -36459,7 +36717,7 @@ async function restoreOriginal(options, original, currentHCheck) {
36459
36717
  const verify4 = async () => currentHCheck ? currentHCheck() : await checkRecoveryDeletionAsync(manifest, options.deletionWatermark, floor);
36460
36718
  floor = await verify4();
36461
36719
  const destination = resolve35(options.destination);
36462
- if (realpathSync21(dirname23(destination)) !== dirname23(destination)) throw new Error("SYMLINK_REFUSED");
36720
+ if (realpathSync21(dirname24(destination)) !== dirname24(destination)) throw new Error("SYMLINK_REFUSED");
36463
36721
  for (const root of [objects.directory, options.archive.directory]) if (isWithin(root, destination) || isWithin(destination, root)) throw new Error("RECOVERY_OVERLAPPING_PATHS");
36464
36722
  try {
36465
36723
  mkdirSync28(destination, { mode: 448 });
@@ -36468,12 +36726,12 @@ async function restoreOriginal(options, original, currentHCheck) {
36468
36726
  throw error;
36469
36727
  }
36470
36728
  writeFileSync32(join61(destination, ".travel-restored.json"), JSON.stringify({ format: "engine7-recovery-restore-v1", id: entry.id, activationAllowed: false }), { mode: 384, flag: "wx", flush: true });
36471
- await syncDirectory(dirname23(destination));
36729
+ await syncDirectory(dirname24(destination));
36472
36730
  await syncDirectory(destination);
36473
36731
  const created = /* @__PURE__ */ new Set([destination]);
36474
36732
  const directory2 = (path37) => {
36475
36733
  const missing = [];
36476
- for (let current2 = path37; !created.has(current2) && isWithin(destination, current2); current2 = dirname23(current2)) missing.push(current2);
36734
+ for (let current2 = path37; !created.has(current2) && isWithin(destination, current2); current2 = dirname24(current2)) missing.push(current2);
36477
36735
  for (const p of missing.reverse()) {
36478
36736
  mkdirSync28(p, { mode: 448 });
36479
36737
  created.add(p);
@@ -36484,7 +36742,7 @@ async function restoreOriginal(options, original, currentHCheck) {
36484
36742
  await objects.restoreFiles(entry.databases.map((d) => ({ content: d.content, destination: join61(destination, "databases", d.databaseId + ".sqlite") })));
36485
36743
  for (const d of entry.databases) {
36486
36744
  const path37 = join61(destination, "databases", d.databaseId + ".sqlite");
36487
- const db2 = new DatabaseSync28(path37, { readOnly: true });
36745
+ const db2 = new DatabaseSync29(path37, { readOnly: true });
36488
36746
  try {
36489
36747
  validateRecoveryDatabase(db2, manifest, d.databaseId, d.role, d.schemaHash, options.verifyDatabases !== false);
36490
36748
  } finally {
@@ -36498,7 +36756,7 @@ async function restoreOriginal(options, original, currentHCheck) {
36498
36756
  for (const path37 of tree.directories) directory2(join61(root, path37));
36499
36757
  for (const file2 of tree.files) {
36500
36758
  const path37 = join61(root, file2.path);
36501
- directory2(dirname23(path37));
36759
+ directory2(dirname24(path37));
36502
36760
  files.push({ content: file2.content, destination: path37, mode: file2.mode });
36503
36761
  }
36504
36762
  }
@@ -36514,7 +36772,7 @@ async function restoreOriginal(options, original, currentHCheck) {
36514
36772
  const d = entry.databases.find((d2) => d2.databaseId === metadata4.databaseId);
36515
36773
  const binding = normalizeBinding({ ...manifest.profile.identity, databaseId: metadata4.databaseId, baselineId: manifest.profile.baselineId, epoch: manifest.profile.epoch });
36516
36774
  if (metadata4.format !== "engine7-session-events-publication-v1" || !d || JSON.stringify(metadata4.binding) !== JSON.stringify(binding) || JSON.stringify(metadata4.head) !== JSON.stringify(manifest.databases.find((v) => v.databaseId === d.databaseId).head)) throw new Error("RUNTIME_INCOMPLETE_SESSIONS");
36517
- const db2 = new DatabaseSync28(join61(destination, "databases", d.databaseId + ".sqlite"), { readOnly: true });
36775
+ const db2 = new DatabaseSync29(join61(destination, "databases", d.databaseId + ".sqlite"), { readOnly: true });
36518
36776
  try {
36519
36777
  await restoreSessionEvents({ db: db2, binding, destination: join61(destination, "sessions", tree.id), replicationRole: d.role });
36520
36778
  } finally {
@@ -36533,7 +36791,7 @@ async function restoreOriginal(options, original, currentHCheck) {
36533
36791
  // src/continuity/runtime-checkpoints.ts
36534
36792
  init_publication_objects();
36535
36793
  init_key_service_store();
36536
- import { DatabaseSync as DatabaseSync29 } from "node:sqlite";
36794
+ import { DatabaseSync as DatabaseSync30 } from "node:sqlite";
36537
36795
  import { existsSync as existsSync34, lstatSync as lstatSync23, writeFileSync as writeFileSync33 } from "node:fs";
36538
36796
  import { join as join62 } from "node:path";
36539
36797
  var zero = "0".repeat(64);
@@ -36558,7 +36816,7 @@ var RuntimeCheckpointControl = class {
36558
36816
  const marker = JSON.parse(readPrivateFile(this.files[0], 65536).toString());
36559
36817
  if (marker.format !== format3 || marker.binding !== this.binding || Object.keys(marker).length !== 2) throw new Error("TRAVEL_CHECKPOINT_IDENTITY");
36560
36818
  preparePrivateDatabase(this.files[1]);
36561
- this.owner = new DatabaseSync29(this.files[1]);
36819
+ this.owner = new DatabaseSync30(this.files[1]);
36562
36820
  try {
36563
36821
  this.owner.exec("CREATE TABLE IF NOT EXISTS owner(id INTEGER PRIMARY KEY);BEGIN IMMEDIATE");
36564
36822
  } catch {
@@ -36567,7 +36825,7 @@ var RuntimeCheckpointControl = class {
36567
36825
  }
36568
36826
  try {
36569
36827
  preparePrivateDatabase(this.files[2]);
36570
- this.db = new DatabaseSync29(this.files[2]);
36828
+ this.db = new DatabaseSync30(this.files[2]);
36571
36829
  this.db.exec("PRAGMA synchronous=FULL;PRAGMA journal_mode=WAL");
36572
36830
  if (fresh) {
36573
36831
  this.db.exec("CREATE TABLE progress(id INTEGER PRIMARY KEY CHECK(id=1),binding TEXT NOT NULL,sequence INTEGER NOT NULL,digest TEXT NOT NULL)");
@@ -36641,7 +36899,7 @@ var RuntimeCheckpointControl = class {
36641
36899
  };
36642
36900
 
36643
36901
  // src/continuity/recovery-archive-transfer.ts
36644
- import { Agent, createServer as createServer2, request as request3 } from "node:https";
36902
+ import { Agent as Agent2, createServer as createServer2, request as request3 } from "node:https";
36645
36903
  import { gzipSync, gunzipSync as gunzipSync4, createGunzip, brotliCompressSync, brotliDecompressSync, createBrotliCompress, createBrotliDecompress, constants as constants13 } from "node:zlib";
36646
36904
  import { pipeline } from "node:stream";
36647
36905
  import { pipeline as pipelineAsync } from "node:stream/promises";
@@ -37050,7 +37308,7 @@ var RecoveryArchiveClient = class {
37050
37308
  this.timeout = options.timeoutMs ?? 15e3;
37051
37309
  if (!Number.isSafeInteger(this.timeout) || this.timeout < 1 || this.timeout > 6e4) throw new Error("RECOVERY_TRANSFER_CONFIG");
37052
37310
  this.key = Buffer.from(options.key);
37053
- this.agent = new Agent({ ca: options.ca, cert: options.cert, key: this.key, minVersion: "TLSv1.3", rejectUnauthorized: true, keepAlive: true, maxSockets: 2 });
37311
+ this.agent = new Agent2({ ca: options.ca, cert: options.cert, key: this.key, minVersion: "TLSv1.3", rejectUnauthorized: true, keepAlive: true, maxSockets: 2 });
37054
37312
  }
37055
37313
  call(input, maximum, archiveDigest) {
37056
37314
  if (this.closed) return Promise.reject(new Error("RECOVERY_TRANSFER_CLOSED"));
@@ -37529,15 +37787,15 @@ async function transferRecoveryArchive(options) {
37529
37787
  // src/continuity/runtime-replica-repository.ts
37530
37788
  init_publication_objects();
37531
37789
  init_key_service_store();
37532
- import { DatabaseSync as DatabaseSync31 } from "node:sqlite";
37790
+ import { DatabaseSync as DatabaseSync32 } from "node:sqlite";
37533
37791
  import { existsSync as existsSync36, lstatSync as lstatSync25, realpathSync as realpathSync23, writeFileSync as writeFileSync35 } from "node:fs";
37534
- import { isAbsolute as isAbsolute9, join as join64, resolve as resolve37 } from "node:path";
37792
+ import { isAbsolute as isAbsolute10, join as join64, resolve as resolve37 } from "node:path";
37535
37793
  import { randomUUID as randomUUID19 } from "node:crypto";
37536
37794
 
37537
37795
  // src/continuity/runtime-replica-seed.ts
37538
- import { DatabaseSync as DatabaseSync30 } from "node:sqlite";
37796
+ import { DatabaseSync as DatabaseSync31 } from "node:sqlite";
37539
37797
  import { existsSync as existsSync35, writeFileSync as writeFileSync34, realpathSync as realpathSync22, lstatSync as lstatSync24 } from "node:fs";
37540
- import { dirname as dirname24, isAbsolute as isAbsolute8, join as join63, resolve as resolve36 } from "node:path";
37798
+ import { dirname as dirname25, isAbsolute as isAbsolute9, join as join63, resolve as resolve36 } from "node:path";
37541
37799
  init_publication_objects();
37542
37800
  init_sqlite_replication();
37543
37801
  init_schema_migrations();
@@ -37546,7 +37804,7 @@ function acquireReplicaOwner(directory2, initialize2 = false) {
37546
37804
  const file2 = join63(directory2, "replica-owner.sqlite");
37547
37805
  if (!initialize2 && !existsSync35(file2)) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
37548
37806
  preparePrivateDatabase(file2);
37549
- const owner = new DatabaseSync30(file2);
37807
+ const owner = new DatabaseSync31(file2);
37550
37808
  try {
37551
37809
  if (initialize2) owner.exec("CREATE TABLE owner(id INTEGER PRIMARY KEY)");
37552
37810
  if (owner.prepare("PRAGMA quick_check").get()?.quick_check !== "ok" || !owner.prepare("SELECT 1 FROM sqlite_master WHERE name='owner' AND type='table'").get()) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
@@ -37574,10 +37832,10 @@ async function seedRuntimeReplica(options) {
37574
37832
  if (status.buildManifestId !== manifest.profile.buildManifestId) throw new Error("TRAVEL_REPLICA_BUILD");
37575
37833
  };
37576
37834
  await check();
37577
- for (const path37 of [options.destination, options.dataDirectory]) if (!isAbsolute8(path37) || resolve36(path37) !== path37 || realpathSync22(dirname24(path37)) !== dirname24(path37)) throw new Error("TRAVEL_REPLICA_PATH");
37835
+ for (const path37 of [options.destination, options.dataDirectory]) if (!isAbsolute9(path37) || resolve36(path37) !== path37 || realpathSync22(dirname25(path37)) !== dirname25(path37)) throw new Error("TRAVEL_REPLICA_PATH");
37578
37836
  if (existsSync35(destination) || existsSync35(dataDirectory) || isWithin(destination, dataDirectory) || isWithin(dataDirectory, destination)) throw new Error("TRAVEL_REPLICA_NEW_DIRECTORY_REQUIRED");
37579
37837
  for (const path37 of [destination, dataDirectory]) for (const root of [options.objects.directory, options.archive.directory, options.archive.objects.directory]) if (isWithin(root, path37) || isWithin(path37, root)) throw new Error("TRAVEL_REPLICA_PATH");
37580
- if (!await (options.verifyDirectory ?? verifyRuntimeDirectory)(dirname24(destination))) throw new Error("TRAVEL_REPLICA_DIRECTORY");
37838
+ if (!await (options.verifyDirectory ?? verifyRuntimeDirectory)(dirname25(destination))) throw new Error("TRAVEL_REPLICA_DIRECTORY");
37581
37839
  await check();
37582
37840
  preparePrivateDirectory(dataDirectory);
37583
37841
  const databases = {}, replicas = {};
@@ -37610,7 +37868,7 @@ async function seedRuntimeReplica(options) {
37610
37868
  }
37611
37869
  for (const d of entry.databases) {
37612
37870
  const file2 = join63(destination, "databases", d.databaseId + ".sqlite");
37613
- const probe = new DatabaseSync30(file2, { readOnly: true });
37871
+ const probe = new DatabaseSync31(file2, { readOnly: true });
37614
37872
  let component, version;
37615
37873
  try {
37616
37874
  const schema5 = readSchemaVersion(probe);
@@ -37620,7 +37878,7 @@ async function seedRuntimeReplica(options) {
37620
37878
  probe.close();
37621
37879
  }
37622
37880
  if (!component || !version) throw new Error("TRAVEL_REPLICA_SCHEMA");
37623
- const db2 = new DatabaseSync30(file2, { allowExtension: component === "legacy-memory" });
37881
+ const db2 = new DatabaseSync31(file2, { allowExtension: component === "legacy-memory" });
37624
37882
  databases[d.databaseId] = db2;
37625
37883
  if (component === "legacy-memory") loadLegacySQLiteVectorExtension(db2);
37626
37884
  authorizeMemoryWriter(db2, version);
@@ -37648,7 +37906,7 @@ async function seedRuntimeReplica(options) {
37648
37906
  }
37649
37907
  async function openSeededRuntimeReplica(options) {
37650
37908
  for (const path37 of [options.destination, options.dataDirectory]) {
37651
- if (!isAbsolute8(path37) || resolve36(path37) !== path37) throw new Error("TRAVEL_REPLICA_PATH");
37909
+ if (!isAbsolute9(path37) || resolve36(path37) !== path37) throw new Error("TRAVEL_REPLICA_PATH");
37652
37910
  assertPrivateDirectory(path37);
37653
37911
  if (realpathSync22(path37) !== path37) throw new Error("TRAVEL_REPLICA_PATH");
37654
37912
  }
@@ -37665,7 +37923,7 @@ async function openSeededRuntimeReplica(options) {
37665
37923
  return value2;
37666
37924
  };
37667
37925
  floor();
37668
- if (!await (options.verifyDirectory ?? verifyRuntimeDirectory)(dirname24(options.destination))) throw new Error("TRAVEL_REPLICA_DIRECTORY");
37926
+ if (!await (options.verifyDirectory ?? verifyRuntimeDirectory)(dirname25(options.destination))) throw new Error("TRAVEL_REPLICA_DIRECTORY");
37669
37927
  const owner = acquireReplicaOwner(options.dataDirectory), databases = {}, replicas = {};
37670
37928
  let receiver, closed = false;
37671
37929
  const close = () => {
@@ -37679,7 +37937,7 @@ async function openSeededRuntimeReplica(options) {
37679
37937
  }
37680
37938
  };
37681
37939
  try {
37682
- const publicationProbe = new DatabaseSync30(publicationFile, { readOnly: true });
37940
+ const publicationProbe = new DatabaseSync31(publicationFile, { readOnly: true });
37683
37941
  try {
37684
37942
  const control2 = publicationProbe.prepare("SELECT profile,head,digest FROM control WHERE id=1").get();
37685
37943
  if (publicationProbe.prepare("PRAGMA quick_check").get()?.quick_check !== "ok" || !control2 || control2.profile !== JSON.stringify(profile) || !Number.isSafeInteger(control2.head) || Number(control2.head) < 1 || !/^[a-f0-9]{64}$/.test(String(control2.digest))) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
@@ -37692,7 +37950,7 @@ async function openSeededRuntimeReplica(options) {
37692
37950
  if (!existsSync35(file2)) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
37693
37951
  const stat3 = lstatSync24(file2);
37694
37952
  if (!stat3.isFile() || stat3.isSymbolicLink() || realpathSync22(file2) !== file2 || process.platform !== "win32" && (stat3.uid !== process.getuid() || stat3.mode & 63)) throw new Error("TRAVEL_REPLICA_PATH");
37695
- const probe = new DatabaseSync30(file2, { readOnly: true }), binding = normalizeBinding({ ...profile.identity, databaseId: d.databaseId, baselineId: profile.baselineId, epoch: profile.epoch });
37953
+ const probe = new DatabaseSync31(file2, { readOnly: true }), binding = normalizeBinding({ ...profile.identity, databaseId: d.databaseId, baselineId: profile.baselineId, epoch: profile.epoch });
37696
37954
  let component, version;
37697
37955
  try {
37698
37956
  const control2 = probe.prepare("SELECT binding,schema_hash FROM e7_replication_control WHERE role='replica'").get(), schema5 = readSchemaVersion(probe);
@@ -37703,14 +37961,14 @@ async function openSeededRuntimeReplica(options) {
37703
37961
  probe.close();
37704
37962
  }
37705
37963
  if (!component || !version) throw new Error("TRAVEL_REPLICA_SCHEMA");
37706
- const db2 = new DatabaseSync30(file2, { allowExtension: component === "legacy-memory" });
37964
+ const db2 = new DatabaseSync31(file2, { allowExtension: component === "legacy-memory" });
37707
37965
  databases[d.databaseId] = db2;
37708
37966
  if (component === "legacy-memory") loadLegacySQLiteVectorExtension(db2);
37709
37967
  authorizeMemoryWriter(db2, version);
37710
37968
  const suppressTriggers = db2.prepare("SELECT name FROM sqlite_master WHERE type='trigger' AND name NOT GLOB 'writer_guard_*' AND name NOT GLOB 'e7_replication_guard_*'").all().map((row) => String(row.name));
37711
37969
  replicas[d.databaseId] = new SQLiteReplicationReplica(db2, binding, { schemaHash: d.schemaHash, baseline: manifest.databases.find((value2) => value2.databaseId === d.databaseId).head, suppressTriggers });
37712
37970
  }
37713
- receiver = await PublicationReplica.open({ directory: dirname24(publicationFile), profile, objects: options.objects, replicas, minimumDeletionWatermark: floor() });
37971
+ receiver = await PublicationReplica.open({ directory: dirname25(publicationFile), profile, objects: options.objects, replicas, minimumDeletionWatermark: floor() });
37714
37972
  const status = await receiver.status(false);
37715
37973
  if (!status.published || status.published.sequence < manifest.sequence) throw new Error("TRAVEL_REPLICA_RECOVERY_REQUIRED");
37716
37974
  if (status.dataReady) {
@@ -37734,7 +37992,7 @@ var incarnation4 = (file2) => {
37734
37992
  var RuntimeReplicaRepository = class _RuntimeReplicaRepository {
37735
37993
  constructor(options) {
37736
37994
  this.options = options;
37737
- if (!validId2(options.nodeId) || !isAbsolute9(options.directory) || resolve37(options.directory) !== options.directory || !isAbsolute9(options.generationsDirectory) || resolve37(options.generationsDirectory) !== options.generationsDirectory || isWithin(options.directory, options.generationsDirectory) || isWithin(options.generationsDirectory, options.directory)) throw new Error("TRAVEL_REPLICA_PATH");
37995
+ if (!validId2(options.nodeId) || !isAbsolute10(options.directory) || resolve37(options.directory) !== options.directory || !isAbsolute10(options.generationsDirectory) || resolve37(options.generationsDirectory) !== options.generationsDirectory || isWithin(options.directory, options.generationsDirectory) || isWithin(options.generationsDirectory, options.directory)) throw new Error("TRAVEL_REPLICA_PATH");
37738
37996
  assertPrivateDirectory(options.generationsDirectory);
37739
37997
  if (realpathSync23(options.generationsDirectory) !== options.generationsDirectory) throw new Error("TRAVEL_REPLICA_PATH");
37740
37998
  preparePrivateDirectory(options.directory);
@@ -37746,7 +38004,7 @@ var RuntimeReplicaRepository = class _RuntimeReplicaRepository {
37746
38004
  const marker = JSON.parse(readPrivateFile(this.files[0], 65536).toString());
37747
38005
  if (marker.format !== "engine7-runtime-replica-repository-v1" || marker.binding !== binding || Object.keys(marker).length !== 2) throw new Error("TRAVEL_REPLICA_IDENTITY");
37748
38006
  preparePrivateDatabase(this.files[1]);
37749
- this.owner = new DatabaseSync31(this.files[1]);
38007
+ this.owner = new DatabaseSync32(this.files[1]);
37750
38008
  try {
37751
38009
  this.owner.exec("CREATE TABLE IF NOT EXISTS owner(id INTEGER PRIMARY KEY);PRAGMA busy_timeout=0;BEGIN IMMEDIATE");
37752
38010
  } catch {
@@ -37755,7 +38013,7 @@ var RuntimeReplicaRepository = class _RuntimeReplicaRepository {
37755
38013
  }
37756
38014
  try {
37757
38015
  preparePrivateDatabase(this.files[2]);
37758
- this.db = new DatabaseSync31(this.files[2]);
38016
+ this.db = new DatabaseSync32(this.files[2]);
37759
38017
  this.db.exec("PRAGMA synchronous=FULL;PRAGMA journal_mode=WAL");
37760
38018
  if (fresh) this.db.exec(`
37761
38019
  CREATE TABLE seeds(id TEXT PRIMARY KEY,binding TEXT NOT NULL,archive_id TEXT NOT NULL,archive_digest TEXT NOT NULL,profile TEXT NOT NULL,state TEXT NOT NULL CHECK(state IN ('PREPARING','READY')),attempt_id TEXT NOT NULL,destination TEXT NOT NULL,data_directory TEXT NOT NULL);
@@ -37948,8 +38206,8 @@ var RuntimeReplicaRepository = class _RuntimeReplicaRepository {
37948
38206
  import { createServer as createServer4 } from "node:https";
37949
38207
 
37950
38208
  // src/continuity/publication-transport.ts
37951
- import { createServer as createServer3, request as request4, Agent as Agent2 } from "node:https";
37952
- import { createHash as createHash42 } from "node:crypto";
38209
+ import { createServer as createServer3, request as request4, Agent as Agent3 } from "node:https";
38210
+ import { createHash as createHash43 } from "node:crypto";
37953
38211
  init_publication_objects();
37954
38212
  var BODY_LIMIT = PUBLICATION_MANIFEST_BYTES + 65536;
37955
38213
  var safeCode = (error) => error instanceof Error && /^(PUBLICATION|REPLICATION)_[A-Z_]+$/.test(error.message) ? error.message : "PUBLICATION_OPERATION_FAILED";
@@ -38059,7 +38317,7 @@ function createPublicationServer(options) {
38059
38317
  case "object": {
38060
38318
  validateObjectRef(value2.ref);
38061
38319
  const body = decodeChunk(value2.body);
38062
- if (body.length !== value2.ref.bytes || createHash42("sha256").update(body).digest("hex") !== value2.ref.sha256) throw new Error("PUBLICATION_OBJECT_MISMATCH");
38320
+ if (body.length !== value2.ref.bytes || createHash43("sha256").update(body).digest("hex") !== value2.ref.sha256) throw new Error("PUBLICATION_OBJECT_MISMATCH");
38063
38321
  await check();
38064
38322
  result = await receiver.objects.put(body);
38065
38323
  break;
@@ -38150,19 +38408,19 @@ async function createTravelNodeDataServer(options) {
38150
38408
  // src/continuity/recovery-runtime-adapter.ts
38151
38409
  init_store();
38152
38410
  init_schema_migrations();
38153
- import { DatabaseSync as DatabaseSync34 } from "node:sqlite";
38411
+ import { DatabaseSync as DatabaseSync35 } from "node:sqlite";
38154
38412
  import { lstatSync as lstatSync27, realpathSync as realpathSync25 } from "node:fs";
38155
- import { isAbsolute as isAbsolute10, join as join68, resolve as resolve39 } from "node:path";
38413
+ import { isAbsolute as isAbsolute11, join as join68, resolve as resolve39 } from "node:path";
38156
38414
 
38157
38415
  // src/continuity/recovery-admission.ts
38158
- import { DatabaseSync as DatabaseSync33 } from "node:sqlite";
38159
- import { createHash as createHash44 } from "node:crypto";
38416
+ import { DatabaseSync as DatabaseSync34 } from "node:sqlite";
38417
+ import { createHash as createHash45 } from "node:crypto";
38160
38418
  import { mkdtempSync as mkdtempSync3, rmSync as rmSync6, writeFileSync as writeFileSync37 } from "node:fs";
38161
38419
  import { join as join66 } from "node:path";
38162
38420
 
38163
38421
  // src/continuity/recovery-diff.ts
38164
- import { DatabaseSync as DatabaseSync32 } from "node:sqlite";
38165
- import { createHash as createHash43 } from "node:crypto";
38422
+ import { DatabaseSync as DatabaseSync33 } from "node:sqlite";
38423
+ import { createHash as createHash44 } from "node:crypto";
38166
38424
  import { mkdtempSync as mkdtempSync2, rmSync as rmSync5, writeFileSync as writeFileSync36 } from "node:fs";
38167
38425
  import { join as join65 } from "node:path";
38168
38426
  init_legacy_sqlite_indexes();
@@ -38238,7 +38496,7 @@ async function compareRecoveryArchives(options) {
38238
38496
  counts[s]++;
38239
38497
  scannedRecords++;
38240
38498
  if (s !== "UNCHANGED") {
38241
- const item = { ...identity3, state: s, common: c, local: l, remote: r, originalHash: createHash43("sha256").update(JSON.stringify(l)).digest("hex") };
38499
+ const item = { ...identity3, state: s, common: c, local: l, remote: r, originalHash: createHash44("sha256").update(JSON.stringify(l)).digest("hex") };
38242
38500
  resultBytes += Buffer.byteLength(JSON.stringify(item));
38243
38501
  if (resultBytes > maximumResultBytes) throw new Error("RECOVERY_DIFF_LIMIT");
38244
38502
  items.push(item);
@@ -38262,7 +38520,7 @@ async function compareRecoveryArchives(options) {
38262
38520
  writeFileSync36(join65(temporary, ".travel-restored.json"), JSON.stringify({ activationAllowed: false }), { mode: 384, flush: true });
38263
38521
  const file2 = join65(temporary, databaseId + ".sqlite");
38264
38522
  await ref.archive.objects.restoreFile(d.content, file2);
38265
- const db2 = new DatabaseSync32(file2, { readOnly: true, allowExtension: true });
38523
+ const db2 = new DatabaseSync33(file2, { readOnly: true, allowExtension: true });
38266
38524
  handles.push(db2);
38267
38525
  validateRecoveryDatabase(db2, entry.manifest, databaseId, d.role, d.schemaHash);
38268
38526
  if (readSchemaVersion(db2)?.component === "legacy-memory") loadLegacySQLiteVectorExtension(db2);
@@ -38338,7 +38596,7 @@ async function compareRecoveryArchives(options) {
38338
38596
  return map;
38339
38597
  });
38340
38598
  for (let i = 0; i < entries.length; i++) for (const file2 of entries[i].manifest.trees.find((t) => t.id === treeId).files) {
38341
- const hash12 = createHash43("sha256");
38599
+ const hash12 = createHash44("sha256");
38342
38600
  for (const chunk of file2.content.chunks) {
38343
38601
  await check();
38344
38602
  hash12.update(await references[i].archive.objects.read(chunk));
@@ -38369,7 +38627,7 @@ async function compareRecoveryArchives(options) {
38369
38627
  activationAllowed: false,
38370
38628
  ancestryVerified: false
38371
38629
  };
38372
- return { ...body, digest: createHash43("sha256").update(JSON.stringify(body)).digest("hex") };
38630
+ return { ...body, digest: createHash44("sha256").update(JSON.stringify(body)).digest("hex") };
38373
38631
  } finally {
38374
38632
  for (const dir of temporaries) rmSync5(dir, { recursive: true, force: true });
38375
38633
  }
@@ -38381,7 +38639,7 @@ init_artifact_history();
38381
38639
  init_recovery_deletion();
38382
38640
  init_job_retention();
38383
38641
  init_protocol();
38384
- var hash8 = (value2) => createHash44("sha256").update(value2).digest("hex");
38642
+ var hash8 = (value2) => createHash45("sha256").update(value2).digest("hex");
38385
38643
  var same10 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
38386
38644
  var quote3 = (s) => '"' + s.replaceAll('"', '""') + '"';
38387
38645
  function authReadinessHistory(body) {
@@ -39176,7 +39434,7 @@ async function admitRecoveryArchives(options) {
39176
39434
  await active();
39177
39435
  const path37 = join66(commonDirectory, d.databaseId + ".sqlite");
39178
39436
  await options.common.archive.objects.restoreFile(d.content, path37);
39179
- const db2 = new DatabaseSync33(path37, { readOnly: true });
39437
+ const db2 = new DatabaseSync34(path37, { readOnly: true });
39180
39438
  commonDatabases.set(d.databaseId, db2);
39181
39439
  validateRecoveryDatabase(db2, common.manifest, d.databaseId, d.role, d.schemaHash);
39182
39440
  }
@@ -39452,19 +39710,19 @@ async function admitRecoveryArchives(options) {
39452
39710
  }
39453
39711
 
39454
39712
  // src/continuity/recovery-artifact-projection.ts
39455
- import { createHash as createHash45, randomUUID as randomUUID20 } from "node:crypto";
39713
+ import { createHash as createHash46, randomUUID as randomUUID20 } from "node:crypto";
39456
39714
  import { existsSync as existsSync37, linkSync, lstatSync as lstatSync26, mkdirSync as mkdirSync29, readFileSync as readFileSync30, realpathSync as realpathSync24, unlinkSync as unlinkSync13, writeFileSync as writeFileSync38 } from "node:fs";
39457
- import { dirname as dirname25, join as join67, resolve as resolve38 } from "node:path";
39715
+ import { dirname as dirname26, join as join67, resolve as resolve38 } from "node:path";
39458
39716
  import { createRequire as createRequire9 } from "node:module";
39459
39717
  init_runtime_authority();
39460
39718
  init_dependencies();
39461
- var sha10 = (bytes) => createHash45("sha256").update(bytes).digest("hex");
39719
+ var sha10 = (bytes) => createHash46("sha256").update(bytes).digest("hex");
39462
39720
  var require5 = createRequire9(import.meta.url);
39463
39721
  function privateParents(root, path37) {
39464
39722
  if (realpathSync24(root) !== root) throw new Error("RECOVERY_PROJECTION_UNSAFE_PATH");
39465
39723
  const visit = (directory2) => {
39466
39724
  if (!isWithin(root, directory2)) throw new Error("RECOVERY_PROJECTION_UNSAFE_PATH");
39467
- if (directory2 !== root) visit(dirname25(directory2));
39725
+ if (directory2 !== root) visit(dirname26(directory2));
39468
39726
  if (!existsSync37(directory2)) mkdirSync29(directory2, { mode: 448 });
39469
39727
  const s = lstatSync26(directory2);
39470
39728
  if (!s.isDirectory() || s.isSymbolicLink() || process.platform !== "win32" && (s.uid !== process.getuid() || directory2 === root && s.mode & 63)) throw new Error("RECOVERY_PROJECTION_UNSAFE_PATH");
@@ -39566,7 +39824,7 @@ async function projectRecoveryArtifacts(options) {
39566
39824
  await checkRemote();
39567
39825
  commit();
39568
39826
  } else {
39569
- privateParents(root, dirname25(path37));
39827
+ privateParents(root, dirname26(path37));
39570
39828
  active();
39571
39829
  if (existsSync37(path37)) {
39572
39830
  const s = lstatSync26(path37);
@@ -39574,7 +39832,7 @@ async function projectRecoveryArtifacts(options) {
39574
39832
  commit();
39575
39833
  continue;
39576
39834
  }
39577
- const temporary = join67(dirname25(path37), ".recovery-" + randomUUID20()), original = Buffer.from(body);
39835
+ const temporary = join67(dirname26(path37), ".recovery-" + randomUUID20()), original = Buffer.from(body);
39578
39836
  writeFileSync38(temporary, original, { mode: local.mode, flag: "wx", flush: true });
39579
39837
  let created = false;
39580
39838
  try {
@@ -39582,7 +39840,7 @@ async function projectRecoveryArtifacts(options) {
39582
39840
  linkSync(temporary, path37);
39583
39841
  created = true;
39584
39842
  unlinkSync13(temporary);
39585
- await syncDirectory(dirname25(path37));
39843
+ await syncDirectory(dirname26(path37));
39586
39844
  await checkRemote();
39587
39845
  commit();
39588
39846
  } catch (error) {
@@ -39696,7 +39954,7 @@ function policies(version) {
39696
39954
  async function admitNormalRecoveryArchives(options) {
39697
39955
  if (options.policyUpgrade !== void 0 && options.policyUpgrade !== "normal-v1") throw new Error("RECOVERY_INVALID_RESOLUTION");
39698
39956
  const stateDir = options.stateDir;
39699
- if (!isAbsolute10(stateDir) || resolve39(stateDir) !== stateDir || realpathSync25(stateDir) !== stateDir || typeof options.withSafeBoundary !== "function") throw new Error("RECOVERY_CURRENT_LAYOUT");
39957
+ if (!isAbsolute11(stateDir) || resolve39(stateDir) !== stateDir || realpathSync25(stateDir) !== stateDir || typeof options.withSafeBoundary !== "function") throw new Error("RECOVERY_CURRENT_LAYOUT");
39700
39958
  assertPrivateDirectory(stateDir);
39701
39959
  const runtime = runtimeAuthorityFor(stateDir);
39702
39960
  if (!runtime) throw new Error("RECOVERY_AUTHORITY_BARRIER");
@@ -39723,7 +39981,7 @@ async function admitNormalRecoveryArchives(options) {
39723
39981
  continue;
39724
39982
  }
39725
39983
  releases2.push(registerRuntimeWriter(place.stateDir, "travel-recovery-adapter"));
39726
- const db2 = new DatabaseSync34(file2, { allowExtension: place.component === "legacy-memory" });
39984
+ const db2 = new DatabaseSync35(file2, { allowExtension: place.component === "legacy-memory" });
39727
39985
  handles.push(db2);
39728
39986
  const schema5 = readSchemaVersion(db2), registration = readSQLiteStoreRegistration(place), actual = readSQLiteReplicationSource(db2);
39729
39987
  if (schema5?.component !== place.component || !registration || !actual || !same11(registration, actual) || actual.binding.databaseId !== id2 || actual.binding.baselineId !== profile.baselineId || actual.binding.epoch !== profile.epoch || !same11({ tenantId: actual.binding.tenantId, companionId: actual.binding.companionId, seatId: actual.binding.seatId }, profile.identity)) throw new Error("RECOVERY_CURRENT_SOURCE");
@@ -39761,27 +40019,27 @@ async function admitNormalRecoveryArchives(options) {
39761
40019
  failure2 = error;
39762
40020
  throw error;
39763
40021
  } finally {
39764
- const errors = [];
40022
+ const errors2 = [];
39765
40023
  try {
39766
40024
  await memory?.close();
39767
40025
  } catch (error) {
39768
- errors.push(error);
40026
+ errors2.push(error);
39769
40027
  }
39770
40028
  for (const db2 of handles.reverse()) {
39771
40029
  try {
39772
40030
  db2.close();
39773
40031
  } catch (error) {
39774
- errors.push(error);
40032
+ errors2.push(error);
39775
40033
  }
39776
40034
  }
39777
40035
  for (const release of releases2.reverse()) {
39778
40036
  try {
39779
40037
  release();
39780
40038
  } catch (error) {
39781
- errors.push(error);
40039
+ errors2.push(error);
39782
40040
  }
39783
40041
  }
39784
- if (errors.length) throw new AggregateError(failure2 === void 0 ? errors : [failure2, ...errors], "RECOVERY_CURRENT_CLOSE_FAILED");
40042
+ if (errors2.length) throw new AggregateError(failure2 === void 0 ? errors2 : [failure2, ...errors2], "RECOVERY_CURRENT_CLOSE_FAILED");
39785
40043
  }
39786
40044
  });
39787
40045
  }
@@ -39792,13 +40050,13 @@ init_runtime_lock();
39792
40050
  // src/continuity/local-exit-proof.ts
39793
40051
  init_runtime_lock();
39794
40052
  init_key_service_store();
39795
- import { createHash as createHash46, verify as verify2 } from "node:crypto";
40053
+ import { createHash as createHash47, verify as verify2 } from "node:crypto";
39796
40054
  import { createReadStream, mkdirSync as mkdirSync30, readdirSync as readdirSync14, writeFileSync as writeFileSync39 } from "node:fs";
39797
- import { join as join69, relative as relative12 } from "node:path";
39798
- var hash9 = (value2) => createHash46("sha256").update(value2).digest("hex");
40055
+ import { join as join69, relative as relative14 } from "node:path";
40056
+ var hash9 = (value2) => createHash47("sha256").update(value2).digest("hex");
39799
40057
  var equal2 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
39800
40058
  function copyLocalExitPath(source, path37) {
39801
- const name = relative12(source, path37).replaceAll("\\", "/");
40059
+ const name = relative14(source, path37).replaceAll("\\", "/");
39802
40060
  return !/^(?:\.travel-|\.runtime-publication)|^(?:\.engine\.pid|\.bg-worker\.pid)$|(?:^|\/)\.continuity\/(?:travel-|runtime\.sqlite|(?:engine|data)-config\.json$|(?:mem7|calendar|proactive|session-events|legacy-memory-[^/]+|topics-vectors-[^/]+)-replication\.json$)/.test(name);
39803
40061
  }
39804
40062
  async function localExitFilesDigest(root, ordinary = false) {
@@ -39806,16 +40064,16 @@ async function localExitFilesDigest(root, ordinary = false) {
39806
40064
  const visit = async (directory2) => {
39807
40065
  for (const entry of readdirSync14(directory2, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
39808
40066
  const file2 = join69(directory2, entry.name);
39809
- if (ordinary ? relative12(root, file2).replaceAll("\\", "/") === ".continuity/travel-exit-receipt.json" : !copyLocalExitPath(root, file2)) continue;
40067
+ if (ordinary ? relative14(root, file2).replaceAll("\\", "/") === ".continuity/travel-exit-receipt.json" : !copyLocalExitPath(root, file2)) continue;
39810
40068
  if (entry.isSymbolicLink()) throw new Error("TRAVEL_EXIT_PATH");
39811
40069
  if (entry.isDirectory()) {
39812
40070
  await visit(file2);
39813
40071
  continue;
39814
40072
  }
39815
40073
  if (!entry.isFile() || files.length >= 1e6) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
39816
- const digest7 = createHash46("sha256");
40074
+ const digest7 = createHash47("sha256");
39817
40075
  for await (const chunk of createReadStream(file2)) digest7.update(chunk);
39818
- files.push({ path: relative12(root, file2).replaceAll("\\", "/"), sha256: digest7.digest("hex") });
40076
+ files.push({ path: relative14(root, file2).replaceAll("\\", "/"), sha256: digest7.digest("hex") });
39819
40077
  }
39820
40078
  };
39821
40079
  await visit(root);
@@ -39863,7 +40121,7 @@ async function verifyStoppedLocalExitProof(options) {
39863
40121
 
39864
40122
  // src/continuity/node-agent.ts
39865
40123
  var clock = () => Number(process.hrtime.bigint() / 1000000n);
39866
- var hash10 = (value2) => createHash47("sha256").update(value2).digest("hex");
40124
+ var hash10 = (value2) => createHash48("sha256").update(value2).digest("hex");
39867
40125
  var same12 = (a, b) => JSON.stringify(a) === JSON.stringify(b);
39868
40126
  var TravelNodeAgent = class _TravelNodeAgent {
39869
40127
  constructor(options) {
@@ -39875,7 +40133,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
39875
40133
  this.objects = objects;
39876
40134
  if (!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(options.bootId) || !/^[a-f0-9]{64}$/.test(options.keySha256) || ["tenantId", "companionId", "seatId"].some((field) => options.principal[field] !== options.keyService.identity[field])) throw new Error("TRAVEL_NODE_IDENTITY");
39877
40135
  if (!options.dataBuild) throw new Error("TRAVEL_NODE_BUILD");
39878
- for (const path37 of [options.directory, options.generationsDirectory, options.build.entry, options.dataBuild.entry]) if (!isAbsolute11(path37) || resolve40(path37) !== path37) throw new Error("TRAVEL_NODE_PATH");
40136
+ for (const path37 of [options.directory, options.generationsDirectory, options.build.entry, options.dataBuild.entry]) if (!isAbsolute12(path37) || resolve40(path37) !== path37) throw new Error("TRAVEL_NODE_PATH");
39879
40137
  if (options.dataIntervalMs !== void 0 && (!Number.isSafeInteger(options.dataIntervalMs) || options.dataIntervalMs < 250 || options.dataIntervalMs > 6e4)) throw new Error("TRAVEL_DATA_CONFIG");
39880
40138
  assertPrivateDirectory(options.generationsDirectory);
39881
40139
  if (realpathSync26(options.generationsDirectory) !== options.generationsDirectory || isWithin(options.directory, options.generationsDirectory) || isWithin(options.generationsDirectory, options.directory)) throw new Error("TRAVEL_NODE_PATH");
@@ -39890,7 +40148,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
39890
40148
  const present = [existsSync38(ownerFile), existsSync38(file2)], fresh = present.every((value2) => !value2);
39891
40149
  if (!fresh && !present.every(Boolean) || fresh && existsSync38(join70(options.directory, "recovery"))) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
39892
40150
  preparePrivateDatabase(ownerFile);
39893
- this.owner = new DatabaseSync35(ownerFile);
40151
+ this.owner = new DatabaseSync36(ownerFile);
39894
40152
  try {
39895
40153
  this.owner.exec("CREATE TABLE IF NOT EXISTS owner(id INTEGER PRIMARY KEY);BEGIN IMMEDIATE");
39896
40154
  } catch {
@@ -39899,7 +40157,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
39899
40157
  }
39900
40158
  try {
39901
40159
  preparePrivateDatabase(file2);
39902
- this.db = new DatabaseSync35(file2);
40160
+ this.db = new DatabaseSync36(file2);
39903
40161
  this.db.exec("PRAGMA synchronous=FULL;PRAGMA journal_mode=WAL");
39904
40162
  const binding = JSON.stringify([options.principal.tenantId, options.principal.companionId, options.principal.seatId, options.principal.nodeId, options.principal.role]);
39905
40163
  if (fresh) {
@@ -40210,7 +40468,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
40210
40468
  if (realpathSync26(directory2) !== directory2 || !existsSync38(file2)) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
40211
40469
  const stat3 = lstatSync28(file2, { bigint: true });
40212
40470
  if (!stat3.isFile() || stat3.isSymbolicLink()) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
40213
- const db2 = new DatabaseSync35(file2, { readOnly: true });
40471
+ const db2 = new DatabaseSync36(file2, { readOnly: true });
40214
40472
  try {
40215
40473
  if (db2.prepare("PRAGMA quick_check").get()?.quick_check !== "ok" || db2.prepare("SELECT count(*) AS n FROM identity WHERE id=1").get()?.n !== 1) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
40216
40474
  } finally {
@@ -40735,7 +40993,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
40735
40993
  let pending = 0;
40736
40994
  for (const id2 of prepared.manifest.profile.databaseIds) {
40737
40995
  const file2 = this.runtime ? join70(this.runtime.stateDir, this.options.layout.databases[id2]) : join70(prepared.snapshot, "databases", id2 + ".sqlite");
40738
- const db2 = new DatabaseSync35(file2, { readOnly: true });
40996
+ const db2 = new DatabaseSync36(file2, { readOnly: true });
40739
40997
  try {
40740
40998
  if (!db2.prepare("SELECT 1 FROM sqlite_master WHERE name='e7_recovery_items'").get()) continue;
40741
40999
  if (db2.prepare("SELECT 1 FROM e7_recovery_items WHERE NOT json_valid(result) LIMIT 1").get()) throw new Error("TRAVEL_NODE_RECOVERY_REQUIRED");
@@ -41539,7 +41797,7 @@ var TravelNodeAgent = class _TravelNodeAgent {
41539
41797
  import { createPublicKey } from "node:crypto";
41540
41798
 
41541
41799
  // src/continuity/node-data-authority.ts
41542
- import { createHash as createHash48 } from "node:crypto";
41800
+ import { createHash as createHash49 } from "node:crypto";
41543
41801
  var fields = ["tenantId", "companionId", "seatId", "nodeId", "role", "credentialHash"];
41544
41802
  var equal3 = (left, right) => !!left && fields.every((field) => left[field] === right[field]);
41545
41803
  var RemoteTravelDataAuthority = class {
@@ -41547,7 +41805,7 @@ var RemoteTravelDataAuthority = class {
41547
41805
  reads = /* @__PURE__ */ new Map();
41548
41806
  grants;
41549
41807
  constructor(grants) {
41550
- if (!grants.length || grants.length > 2 || new Set(grants.map((grant) => grant.credential)).size !== grants.length || grants.some((grant) => !/^e7t_[a-f0-9]{64}$/.test(grant.credential) || createHash48("sha256").update(grant.credential).digest("hex") !== grant.principal.credentialHash)) throw new Error("TRAVEL_AUTH_DENIED");
41808
+ if (!grants.length || grants.length > 2 || new Set(grants.map((grant) => grant.credential)).size !== grants.length || grants.some((grant) => !/^e7t_[a-f0-9]{64}$/.test(grant.credential) || createHash49("sha256").update(grant.credential).digest("hex") !== grant.principal.credentialHash)) throw new Error("TRAVEL_AUTH_DENIED");
41551
41809
  this.grants = grants.map((grant) => ({ ...grant, principal: Object.freeze({ ...grant.principal }) }));
41552
41810
  }
41553
41811
  async authenticate(credential) {
@@ -41658,7 +41916,7 @@ var RemoteTravelNodeAuthority = class _RemoteTravelNodeAuthority extends RemoteT
41658
41916
  };
41659
41917
 
41660
41918
  // src/continuity/authority-client.ts
41661
- import { Agent as Agent3, request as request5 } from "node:https";
41919
+ import { Agent as Agent4, request as request5 } from "node:https";
41662
41920
  var publicErrors = /* @__PURE__ */ new Set([
41663
41921
  "TRAVEL_HEARTBEAT_REPLAY",
41664
41922
  "TRAVEL_BOOT_MISMATCH",
@@ -41695,8 +41953,8 @@ var TravelReportClient = class {
41695
41953
  if (!Number.isSafeInteger(this.timeout) || this.timeout < 1 || this.timeout > 6e4) throw new Error("TRAVEL_CONTROL_INVALID_CONFIG");
41696
41954
  this.key = options.key ? Buffer.from(options.key) : void 0;
41697
41955
  const tls2 = { ca: options.ca, cert: options.cert, key: this.key, minVersion: "TLSv1.3", rejectUnauthorized: true, maxSockets: 1 };
41698
- this.agent = new Agent3({ ...tls2, keepAlive: true });
41699
- this.mutationAgent = new Agent3({ ...tls2, keepAlive: false });
41956
+ this.agent = new Agent4({ ...tls2, keepAlive: true });
41957
+ this.mutationAgent = new Agent4({ ...tls2, keepAlive: false });
41700
41958
  }
41701
41959
  agent;
41702
41960
  mutationAgent;
@@ -41885,7 +42143,7 @@ var TravelManagementClient = class extends TravelReportClient {
41885
42143
  };
41886
42144
 
41887
42145
  // src/continuity/gateway-server.ts
41888
- import { Agent as Agent4, createServer as createServer5, request as request6 } from "node:https";
42146
+ import { Agent as Agent5, createServer as createServer5, request as request6 } from "node:https";
41889
42147
  var prefix = "/travel/gateway/v1/";
41890
42148
  var requestLimit2 = 24 * 1024 * 1024;
41891
42149
  var responseLimit = 48 * 1024 * 1024;
@@ -41930,7 +42188,7 @@ var TravelGatewayClient = class {
41930
42188
  this.timeout = options.timeoutMs ?? 15e3;
41931
42189
  if (!Number.isSafeInteger(this.timeout) || this.timeout < 1 || this.timeout > 6e4) throw new Error("TRAVEL_GATEWAY_INVALID_TIMEOUT");
41932
42190
  this.key = Buffer.from(options.key);
41933
- this.agent = new Agent4({ ca: options.ca, cert: options.cert, key: this.key, minVersion: "TLSv1.3", rejectUnauthorized: true, keepAlive: true, maxSockets: 4 });
42191
+ this.agent = new Agent5({ ca: options.ca, cert: options.cert, key: this.key, minVersion: "TLSv1.3", rejectUnauthorized: true, keepAlive: true, maxSockets: 4 });
41934
42192
  }
41935
42193
  async call(action, input, retryStale = true, deadline = performance.now() + this.timeout) {
41936
42194
  const body = Buffer.from(JSON.stringify(input));
@@ -42053,7 +42311,7 @@ var TravelGatewayClient = class {
42053
42311
  };
42054
42312
 
42055
42313
  // src/continuity/node-supervisor-client.ts
42056
- import { Agent as Agent5, request as request7 } from "node:https";
42314
+ import { Agent as Agent6, request as request7 } from "node:https";
42057
42315
 
42058
42316
  // src/continuity/node-supervisor-protocol.ts
42059
42317
  var nodeSupervisorPath = "/travel/node/v1";
@@ -42143,7 +42401,7 @@ var RemoteTravelNodeSupervisor = class {
42143
42401
  this.timeout = options.timeoutMs ?? 18e4;
42144
42402
  if (!Number.isSafeInteger(this.timeout) || this.timeout < 1 || this.timeout > 6e5) throw new Error("TRAVEL_NODE_CLIENT_CONFIG");
42145
42403
  this.key = Buffer.from(options.key);
42146
- const agent = () => new Agent5({ ca: options.ca, cert: options.cert, key: this.key, minVersion: "TLSv1.3", rejectUnauthorized: true, keepAlive: true, maxSockets: 1 });
42404
+ const agent = () => new Agent6({ ca: options.ca, cert: options.cert, key: this.key, minVersion: "TLSv1.3", rejectUnauthorized: true, keepAlive: true, maxSockets: 1 });
42147
42405
  this.agents = { observe: agent(), permit: agent(), operation: agent(), stop: agent() };
42148
42406
  }
42149
42407
  principal;
@@ -42476,7 +42734,7 @@ init_sqlite_replication();
42476
42734
  init_schema_migrations();
42477
42735
  init_key_service_store();
42478
42736
  var path34 = (value2) => {
42479
- if (typeof value2 !== "string" || !isAbsolute12(value2) || resolve41(value2) !== value2) throw new Error("TRAVEL_NODE_PATH");
42737
+ if (typeof value2 !== "string" || !isAbsolute13(value2) || resolve41(value2) !== value2) throw new Error("TRAVEL_NODE_PATH");
42480
42738
  return value2;
42481
42739
  };
42482
42740
  var tls = (value2) => ({ ca: readFileSync32(path34(value2?.caFile)), cert: readFileSync32(path34(value2?.certFile)), key: readPrivateFile(path34(value2?.keyFile), 65536) });
@@ -42542,7 +42800,7 @@ async function startTravelNodeService(input) {
42542
42800
  const keyService = { ...clientTls, url: config.keyService?.url, identity: config.keyService?.identity, minimumDeletionWatermark: (await authority.status(config.principal)).deletionWatermark };
42543
42801
  const material = await fetchTravelKey(keyService);
42544
42802
  try {
42545
- if (createHash49("sha256").update(material.key).digest("hex") !== config.keySha256) throw new Error("TRAVEL_NODE_KEY_BARRIER");
42803
+ if (createHash50("sha256").update(material.key).digest("hex") !== config.keySha256) throw new Error("TRAVEL_NODE_KEY_BARRIER");
42546
42804
  objects = await PublicationObjects.open({ directory: path34(config.objectsDirectory), identity: { tenantId: config.principal.tenantId, companionId: config.principal.companionId, seatId: config.principal.seatId }, key: material.key });
42547
42805
  } finally {
42548
42806
  material.key.fill(0);
@@ -42585,7 +42843,7 @@ async function startTravelNodeService(input) {
42585
42843
  for (const id2 of profile.databaseIds) {
42586
42844
  const file2 = path34(config.initialReplica.databases[id2]), stat3 = lstatSync29(file2);
42587
42845
  if (!stat3.isFile() || stat3.isSymbolicLink() || realpathSync27(file2) !== file2 || process.platform !== "win32" && (stat3.uid !== process.getuid() || stat3.mode & 63)) throw new Error("TRAVEL_NODE_PATH");
42588
- const db2 = new DatabaseSync36(file2, { allowExtension: id2 === "legacy" });
42846
+ const db2 = new DatabaseSync37(file2, { allowExtension: id2 === "legacy" });
42589
42847
  replicaHandles.push(db2);
42590
42848
  databases[id2] = db2;
42591
42849
  const schema5 = readSchemaVersion(db2);
@@ -42645,7 +42903,7 @@ import { createServer as createServer7 } from "node:https";
42645
42903
  import { timingSafeEqual } from "node:crypto";
42646
42904
 
42647
42905
  // src/continuity/console-manager.ts
42648
- import { DatabaseSync as DatabaseSync37 } from "node:sqlite";
42906
+ import { DatabaseSync as DatabaseSync38 } from "node:sqlite";
42649
42907
  init_publication_objects();
42650
42908
  var travelConsoleActions = ["status", "auto_on", "auto_off", "sync", "to_cloud", "to_local", "recover", "finish"];
42651
42909
  var travelConsoleErrors = /* @__PURE__ */ new Set(["invalid_action", "invalid_request", "wrong_partner", "service_unavailable", "busy", "recovery_required", "recovery_unavailable", "confirmation_required", "not_ready", "retired"]);
@@ -42872,23 +43130,23 @@ async function waitForPidGone(pid, timeoutMs = 5e3) {
42872
43130
 
42873
43131
  // src/continuity/retirement-main.ts
42874
43132
  import { readFileSync as readFileSync35, existsSync as existsSync41 } from "node:fs";
42875
- import { isAbsolute as isAbsolute16, resolve as resolve45 } from "node:path";
43133
+ import { isAbsolute as isAbsolute17, resolve as resolve45 } from "node:path";
42876
43134
  import { fileURLToPath as fileURLToPath8 } from "node:url";
42877
43135
  import { execFile as execFile4 } from "node:child_process";
42878
43136
  import { promisify as promisify5 } from "node:util";
42879
- import { createHash as createHash54 } from "node:crypto";
43137
+ import { createHash as createHash55 } from "node:crypto";
42880
43138
 
42881
43139
  // src/continuity/user-seat-resource.ts
42882
43140
  import { spawn as spawn6 } from "node:child_process";
42883
- import { createHash as createHash50 } from "node:crypto";
42884
- import { isAbsolute as isAbsolute13, resolve as resolve42 } from "node:path";
43141
+ import { createHash as createHash51 } from "node:crypto";
43142
+ import { isAbsolute as isAbsolute14, resolve as resolve42 } from "node:path";
42885
43143
  var UserSeatResource = class {
42886
43144
  constructor(config) {
42887
43145
  this.config = config;
42888
- if (!/^[a-z_][a-z0-9_-]{0,31}$/.test(config.runAs.user) || [config.directory, config.runAs.node, config.runAs.entry, config.runAs.configFile].some((path37) => !isAbsolute13(path37) || resolve42(path37) !== path37 || /[\r\n\0]/.test(path37))) throw new Error("TRAVEL_RETIREMENT_CONFIG");
43146
+ if (!/^[a-z_][a-z0-9_-]{0,31}$/.test(config.runAs.user) || [config.directory, config.runAs.node, config.runAs.entry, config.runAs.configFile].some((path37) => !isAbsolute14(path37) || resolve42(path37) !== path37 || /[\r\n\0]/.test(path37))) throw new Error("TRAVEL_RETIREMENT_CONFIG");
42889
43147
  this.identity = config.identity;
42890
43148
  this.path = config.directory;
42891
- this.id = "directory-" + createHash50("sha256").update(this.path).digest("hex");
43149
+ this.id = "directory-" + createHash51("sha256").update(this.path).digest("hex");
42892
43150
  }
42893
43151
  id;
42894
43152
  path;
@@ -42940,18 +43198,18 @@ var UserSeatResource = class {
42940
43198
  // src/continuity/retirement.ts
42941
43199
  init_publication_objects();
42942
43200
  init_key_service_store();
42943
- import { DatabaseSync as DatabaseSync38 } from "node:sqlite";
42944
- import { createHash as createHash51 } from "node:crypto";
43201
+ import { DatabaseSync as DatabaseSync39 } from "node:sqlite";
43202
+ import { createHash as createHash52 } from "node:crypto";
42945
43203
  import { existsSync as existsSync39 } from "node:fs";
42946
43204
  import { accessSync, constants as constants14, lstatSync as lstatSync30, readdirSync as readdirSync15, readFileSync as readFileSync33, readlinkSync, realpathSync as realpathSync28, rmSync as rmSync7 } from "node:fs";
42947
- import { dirname as dirname26, isAbsolute as isAbsolute14, join as join71, resolve as resolve43, relative as relative13 } from "node:path";
43205
+ import { dirname as dirname27, isAbsolute as isAbsolute15, join as join71, resolve as resolve43, relative as relative15 } from "node:path";
42948
43206
  var identity = (value2) => JSON.stringify([value2.tenantId, value2.companionId, value2.seatId]);
42949
- var sha11 = (value2) => createHash51("sha256").update(value2).digest("hex");
43207
+ var sha11 = (value2) => createHash52("sha256").update(value2).digest("hex");
42950
43208
  var LocalSeatResource = class {
42951
43209
  constructor(path37, identity3) {
42952
43210
  this.path = path37;
42953
43211
  this.identity = identity3;
42954
- if (!isAbsolute14(path37) || resolve43(path37) !== path37 || path37.split("/").filter(Boolean).length < 3) throw new Error("TRAVEL_RETIREMENT_PATH");
43212
+ if (!isAbsolute15(path37) || resolve43(path37) !== path37 || path37.split("/").filter(Boolean).length < 3) throw new Error("TRAVEL_RETIREMENT_PATH");
42955
43213
  this.id = "directory-" + sha11(path37);
42956
43214
  }
42957
43215
  id;
@@ -42970,7 +43228,7 @@ var LocalSeatResource = class {
42970
43228
  const result = [];
42971
43229
  const visit = (directory2) => {
42972
43230
  for (const item of readdirSync15(directory2, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
42973
- const path37 = join71(directory2, item.name), version = relative13(this.path, path37);
43231
+ const path37 = join71(directory2, item.name), version = relative15(this.path, path37);
42974
43232
  if (item.isSymbolicLink()) result.push({ version, digest: sha11(readlinkSync(path37)) });
42975
43233
  else if (item.isDirectory()) visit(path37);
42976
43234
  else if (item.isFile()) {
@@ -42989,7 +43247,7 @@ var LocalSeatResource = class {
42989
43247
  if (this.check()) {
42990
43248
  let removeRoot = true;
42991
43249
  try {
42992
- accessSync(dirname26(this.path), constants14.W_OK);
43250
+ accessSync(dirname27(this.path), constants14.W_OK);
42993
43251
  } catch (error) {
42994
43252
  if (error.code !== "EACCES") throw error;
42995
43253
  removeRoot = false;
@@ -43007,7 +43265,7 @@ var TravelRetirement = class {
43007
43265
  preparePrivateDirectory(options.directory);
43008
43266
  const ownerFile = join71(options.directory, "owner.sqlite");
43009
43267
  preparePrivateDatabase(ownerFile);
43010
- this.owner = new DatabaseSync38(ownerFile);
43268
+ this.owner = new DatabaseSync39(ownerFile);
43011
43269
  try {
43012
43270
  this.owner.exec("CREATE TABLE IF NOT EXISTS owner(id INTEGER);BEGIN IMMEDIATE");
43013
43271
  } catch (error) {
@@ -43016,7 +43274,7 @@ var TravelRetirement = class {
43016
43274
  }
43017
43275
  const file2 = join71(options.directory, "retirement.sqlite");
43018
43276
  preparePrivateDatabase(file2);
43019
- this.db = new DatabaseSync38(file2);
43277
+ this.db = new DatabaseSync39(file2);
43020
43278
  try {
43021
43279
  this.db.exec("PRAGMA synchronous=FULL;CREATE TABLE IF NOT EXISTS job(id TEXT PRIMARY KEY,binding TEXT NOT NULL,state TEXT NOT NULL,stopped INTEGER NOT NULL DEFAULT 0);CREATE TABLE IF NOT EXISTS resources(id TEXT PRIMARY KEY,inventory TEXT,state TEXT NOT NULL)");
43022
43280
  const binding = JSON.stringify([identity(options.identity), options.resources.map((resource) => [resource.id, resource.path ?? null]).sort(), options.accountOwnerRequestedKeyDestruction === true]);
@@ -43059,7 +43317,7 @@ var TravelRetirement = class {
43059
43317
  if (required) throw new Error("TRAVEL_RETIREMENT_RECOVERY_REQUIRED");
43060
43318
  return null;
43061
43319
  }
43062
- if (recovered.loaded !== true || identity(recovered.identity) !== identity(this.options.identity) || !isAbsolute14(recovered.ordinaryStateDir) || ![recovered.checkpointDigest, recovered.channelReceiptsDigest].every((value2) => /^[a-f0-9]{64}$/.test(value2))) throw new Error("TRAVEL_RETIREMENT_RECOVERY_REQUIRED");
43320
+ if (recovered.loaded !== true || identity(recovered.identity) !== identity(this.options.identity) || !isAbsolute15(recovered.ordinaryStateDir) || ![recovered.checkpointDigest, recovered.channelReceiptsDigest].every((value2) => /^[a-f0-9]{64}$/.test(value2))) throw new Error("TRAVEL_RETIREMENT_RECOVERY_REQUIRED");
43063
43321
  for (const resource of this.options.resources) {
43064
43322
  if (resource.path) {
43065
43323
  const local = resolve43(recovered.ordinaryStateDir), path37 = resolve43(resource.path), journal = resolve43(this.options.directory);
@@ -43112,24 +43370,24 @@ var TravelRetirement = class {
43112
43370
  // src/continuity/local-exit.ts
43113
43371
  init_runtime_lock();
43114
43372
  import { cpSync as cpSync2, existsSync as existsSync40, mkdirSync as mkdirSync32, readFileSync as readFileSync34, readdirSync as readdirSync16, realpathSync as realpathSync29, rmSync as rmSync8, writeFileSync as writeFileSync41 } from "node:fs";
43115
- import { DatabaseSync as DatabaseSync40 } from "node:sqlite";
43116
- import { isAbsolute as isAbsolute15, join as join72, dirname as dirname28, resolve as resolve44 } from "node:path";
43117
- import { createHash as createHash53, verify as verify3 } from "node:crypto";
43373
+ import { DatabaseSync as DatabaseSync41 } from "node:sqlite";
43374
+ import { isAbsolute as isAbsolute16, join as join72, dirname as dirname29, resolve as resolve44 } from "node:path";
43375
+ import { createHash as createHash54, verify as verify3 } from "node:crypto";
43118
43376
 
43119
43377
  // src/continuity/local-dedupe.ts
43120
43378
  init_publication_objects();
43121
- import { DatabaseSync as DatabaseSync39 } from "node:sqlite";
43122
- import { createHash as createHash52 } from "node:crypto";
43123
- import { dirname as dirname27 } from "node:path";
43124
- var sha12 = (value2) => createHash52("sha256").update(value2).digest("hex");
43379
+ import { DatabaseSync as DatabaseSync40 } from "node:sqlite";
43380
+ import { createHash as createHash53 } from "node:crypto";
43381
+ import { dirname as dirname28 } from "node:path";
43382
+ var sha12 = (value2) => createHash53("sha256").update(value2).digest("hex");
43125
43383
  var hash11 = (value2) => typeof value2 === "string" && /^[a-f0-9]{64}$/.test(value2);
43126
43384
  var PlatformReceiptStore = class {
43127
43385
  db;
43128
43386
  constructor(file2, namespace) {
43129
43387
  if (!namespace || namespace.length > 1024) throw new Error("PLATFORM_RECEIPT_IDENTITY");
43130
- preparePrivateDirectory(dirname27(file2));
43388
+ preparePrivateDirectory(dirname28(file2));
43131
43389
  preparePrivateDatabase(file2);
43132
- this.db = new DatabaseSync39(file2);
43390
+ this.db = new DatabaseSync40(file2);
43133
43391
  try {
43134
43392
  this.db.exec("PRAGMA synchronous=FULL;CREATE TABLE IF NOT EXISTS binding(namespace TEXT NOT NULL);CREATE TABLE IF NOT EXISTS inputs(id TEXT PRIMARY KEY,state TEXT NOT NULL);CREATE TABLE IF NOT EXISTS effects(id TEXT PRIMARY KEY,body TEXT NOT NULL);CREATE TABLE IF NOT EXISTS imports(digest TEXT PRIMARY KEY,identity TEXT NOT NULL)");
43135
43393
  const binding = this.db.prepare("SELECT namespace FROM binding").all();
@@ -43189,7 +43447,7 @@ var PlatformReceiptStore = class {
43189
43447
  // src/continuity/local-exit.ts
43190
43448
  init_key_service_store();
43191
43449
  var identity2 = (value2) => JSON.stringify([value2.tenantId, value2.companionId, value2.seatId]);
43192
- var sha13 = (value2) => createHash53("sha256").update(value2).digest("hex");
43450
+ var sha13 = (value2) => createHash54("sha256").update(value2).digest("hex");
43193
43451
  function detachReplication(directory2) {
43194
43452
  for (const entry of readdirSync16(directory2, { withFileTypes: true })) {
43195
43453
  const file2 = join72(directory2, entry.name);
@@ -43200,7 +43458,7 @@ function detachReplication(directory2) {
43200
43458
  }
43201
43459
  if (!entry.isFile()) throw new Error("TRAVEL_EXIT_PATH");
43202
43460
  if (!/\.(?:db|sqlite)$/.test(entry.name)) continue;
43203
- const db2 = new DatabaseSync40(file2);
43461
+ const db2 = new DatabaseSync41(file2);
43204
43462
  try {
43205
43463
  if (!db2.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='e7_replication_control'").get()) continue;
43206
43464
  db2.exec("BEGIN IMMEDIATE");
@@ -43218,7 +43476,7 @@ function detachReplication(directory2) {
43218
43476
  }
43219
43477
  async function createOrdinaryLocalRecovery(options) {
43220
43478
  const source = resolve44(options.stateDir), destination = resolve44(options.destination);
43221
- if (!isAbsolute15(options.destination) || source !== options.stateDir || destination !== options.destination || realpathSync29(source) !== source || destination === source || destination.startsWith(source + "/") || source.startsWith(destination + "/") || realpathSync29(dirname28(destination)) !== dirname28(destination)) throw new Error("TRAVEL_EXIT_PATH");
43479
+ if (!isAbsolute16(options.destination) || source !== options.stateDir || destination !== options.destination || realpathSync29(source) !== source || destination === source || destination.startsWith(source + "/") || source.startsWith(destination + "/") || realpathSync29(dirname29(destination)) !== dirname29(destination)) throw new Error("TRAVEL_EXIT_PATH");
43222
43480
  const activation = JSON.parse(readFileSync34(join72(source, ".travel-active.json"), "utf8")), permit = activation.permit, { signature: signature2, ...signed } = permit;
43223
43481
  if (activation.format !== "engine7-runtime-activation-v1" || identity2(activation.identity) !== identity2(options.identity) || identity2(permit) !== identity2(options.identity) || permit.nodeId !== options.localNodeId || activation.nodeId !== options.localNodeId || !verify3(null, Buffer.from(JSON.stringify(signed)), options.publicKey, Buffer.from(signature2, "base64")) || identity2(options.dedupeReceipt.identity) !== identity2(options.identity) || options.dedupeReceipt.checkpointDigest !== options.checkpointDigest || options.dedupeReceipt.deletionWatermark !== permit.deletionWatermark) throw new Error("TRAVEL_EXIT_RECOVERY_REQUIRED");
43224
43482
  return withCheckpointLock(source, async () => {
@@ -43274,9 +43532,9 @@ async function createOrdinaryLocalRecovery(options) {
43274
43532
  init_key_service_store();
43275
43533
  init_key_service_store();
43276
43534
  var command = promisify5(execFile4);
43277
- var sha14 = (value2) => createHash54("sha256").update(value2).digest("hex");
43535
+ var sha14 = (value2) => createHash55("sha256").update(value2).digest("hex");
43278
43536
  var path36 = (value2) => {
43279
- if (typeof value2 !== "string" || !isAbsolute16(value2) || resolve45(value2) !== value2) throw new Error("TRAVEL_RETIREMENT_PATH");
43537
+ if (typeof value2 !== "string" || !isAbsolute17(value2) || resolve45(value2) !== value2) throw new Error("TRAVEL_RETIREMENT_PATH");
43280
43538
  return value2;
43281
43539
  };
43282
43540
  async function runTravelRetirementCli(args) {
@@ -43408,7 +43666,7 @@ function initialPairingSnapshot(options) {
43408
43666
  };
43409
43667
  }
43410
43668
  var write2 = (file2, value2) => writeFileSync42(file2, JSON.stringify(value2), { mode: 384, flush: true });
43411
- var delay = (ms) => new Promise((done) => setTimeout(done, ms));
43669
+ var delay2 = (ms) => new Promise((done) => setTimeout(done, ms));
43412
43670
  function rpc(url, tls2, token, body, timeout = 6e5) {
43413
43671
  return new Promise((done, reject) => {
43414
43672
  const req = request8(url, { method: "POST", ...tls2, minVersion: "TLSv1.3", headers: { Authorization: "Bearer " + token, "Content-Type": "application/json" } }, (res) => {
@@ -43474,7 +43732,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
43474
43732
  if (JSON.stringify(binding.identity) !== JSON.stringify(material.identity)) throw new Error("TRAVEL_PAIRING_IDENTITY");
43475
43733
  const ownerFile = join73(directory2, "host-owner.sqlite");
43476
43734
  preparePrivateDatabase(ownerFile);
43477
- const owner = new DatabaseSync41(ownerFile);
43735
+ const owner = new DatabaseSync42(ownerFile);
43478
43736
  try {
43479
43737
  owner.exec("CREATE TABLE IF NOT EXISTS owner(id INTEGER PRIMARY KEY);BEGIN IMMEDIATE");
43480
43738
  } catch {
@@ -43569,7 +43827,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
43569
43827
  break;
43570
43828
  } catch (error) {
43571
43829
  if (attempt >= 30 || !["busy", "not_ready", "service_unavailable"].includes(error.message)) throw error;
43572
- await delay(1e3);
43830
+ await delay2(1e3);
43573
43831
  }
43574
43832
  }
43575
43833
  lifecycle.state = "MANAGED";
@@ -43652,7 +43910,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
43652
43910
  if (current2.activeNodeId !== null) {
43653
43911
  for (let attempt = 0; !(await authority.status()).expired; attempt++) {
43654
43912
  if (attempt >= 120) throw new Error("TRAVEL_INITIAL_SOURCE_RUNNING");
43655
- await delay(500);
43913
+ await delay2(500);
43656
43914
  }
43657
43915
  }
43658
43916
  await startInitialPairingRuntime(localService.node, { acquire: (ready) => {
@@ -43749,7 +44007,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
43749
44007
  break;
43750
44008
  } catch (error) {
43751
44009
  if (attempt >= 20) throw error;
43752
- await delay(500);
44010
+ await delay2(500);
43753
44011
  }
43754
44012
  }
43755
44013
  if (lifecycle.state === "PAIRED") await pauseInitialPairingIngress(lifecycle.state, gatewayIngress, pair);
@@ -43757,7 +44015,7 @@ async function startPairingHost(material, startRelays = startPairingRelays) {
43757
44015
  for (let attempt = 0; ; attempt++) {
43758
44016
  if ((await cloudClient.observe()).connected) break;
43759
44017
  if (attempt >= 30) throw new Error("TRAVEL_PAIRING_HEALTH");
43760
- await delay(500);
44018
+ await delay2(500);
43761
44019
  }
43762
44020
  hostServer = createTravelConsoleServer({ manager: { execute }, identity: material.identity, token: consoleToken, startInitial, cert: readFileSync36(join73(directory2, "tls/local-server.pem")), key: readPrivateFile(join73(directory2, "tls/local-server.key"), 65536) });
43763
44021
  await new Promise((done, reject) => {