engine7 7.1.137 → 7.1.140

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.
@@ -3077,14 +3077,9 @@ import {
3077
3077
  fstatSync as fstatSync4,
3078
3078
  fsyncSync as fsyncSync4,
3079
3079
  readSync,
3080
- writeSync as writeSync2,
3081
3080
  lstatSync as lstatSync6,
3082
3081
  realpathSync as realpathSync3,
3083
- mkdirSync as mkdirSync10,
3084
- readFileSync as readFileSync10,
3085
- writeFileSync as writeFileSync8,
3086
- linkSync,
3087
- unlinkSync as unlinkSync3
3082
+ mkdirSync as mkdirSync10
3088
3083
  } from "node:fs";
3089
3084
  import { join as join13, dirname as dirname5, resolve as resolve8 } from "node:path";
3090
3085
  function assertPrivateDirectory2(path2) {
@@ -3126,18 +3121,19 @@ function preparePrivateDirectory(path2) {
3126
3121
  }
3127
3122
  assertPrivateDirectory2(path2);
3128
3123
  }
3129
- var PUBLICATION_CHUNK_BYTES, MAGIC, noFollow;
3124
+ var PUBLICATION_CHUNK_BYTES, MAGIC, INLINE_BYTES, noFollow;
3130
3125
  var init_publication_objects = __esm({
3131
3126
  "src/continuity/publication-objects.ts"() {
3132
3127
  "use strict";
3133
3128
  PUBLICATION_CHUNK_BYTES = 1024 * 1024;
3134
3129
  MAGIC = Buffer.from("E7P1");
3130
+ INLINE_BYTES = 64 * 1024;
3135
3131
  noFollow = constants5.O_NOFOLLOW ?? 0;
3136
3132
  }
3137
3133
  });
3138
3134
 
3139
3135
  // src/continuity/mem7-replication.ts
3140
- import { closeSync as closeSync6, fsyncSync as fsyncSync5, lstatSync as lstatSync7, openSync as openSync6, writeFileSync as writeFileSync9 } from "node:fs";
3136
+ import { closeSync as closeSync6, fsyncSync as fsyncSync5, lstatSync as lstatSync7, openSync as openSync6, writeFileSync as writeFileSync8 } from "node:fs";
3141
3137
  import { dirname as dirname6, join as join14 } from "node:path";
3142
3138
  function normalize4(value) {
3143
3139
  if (!value || !/^[a-f0-9]{64}$/.test(value.schemaHash)) throw new Error("REPLICATION_REGISTRATION_INVALID");
@@ -3170,7 +3166,7 @@ function ensureMem7ReplicationRegistration(stateDir, input) {
3170
3166
  const file = location2(stateDir);
3171
3167
  preparePrivateDirectory(dirname6(file));
3172
3168
  try {
3173
- writeFileSync9(file, JSON.stringify(registration), { mode: 384, flag: "wx", flush: true });
3169
+ writeFileSync8(file, JSON.stringify(registration), { mode: 384, flag: "wx", flush: true });
3174
3170
  } catch (error) {
3175
3171
  if (error.code !== "EEXIST") throw error;
3176
3172
  if (JSON.stringify(readMem7ReplicationRegistration(stateDir)) !== JSON.stringify(registration)) throw new Error("REPLICATION_REGISTRATION_MISMATCH");
@@ -5036,7 +5032,7 @@ var init_prompt_render = __esm({
5036
5032
 
5037
5033
  // src/mem7/core/change-feed.ts
5038
5034
  import { createHash as createHash7, randomUUID as randomUUID9 } from "node:crypto";
5039
- import { existsSync as existsSync9, readFileSync as readFileSync11, renameSync as renameSync5, unlinkSync as unlinkSync4, writeFileSync as writeFileSync10 } from "node:fs";
5035
+ import { existsSync as existsSync9, readFileSync as readFileSync10, renameSync as renameSync5, unlinkSync as unlinkSync3, writeFileSync as writeFileSync9 } from "node:fs";
5040
5036
  function isBusyError(error) {
5041
5037
  if (!error || typeof error !== "object") return false;
5042
5038
  if (error.errcode === 5) return true;
@@ -5202,7 +5198,7 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
5202
5198
  let ledger = {};
5203
5199
  if (ledgerPath) {
5204
5200
  try {
5205
- ledger = JSON.parse(readFileSync11(ledgerPath, "utf8"))?.heals ?? {};
5201
+ ledger = JSON.parse(readFileSync10(ledgerPath, "utf8"))?.heals ?? {};
5206
5202
  } catch {
5207
5203
  }
5208
5204
  if (Number.isFinite(ledger[key3])) {
@@ -5227,11 +5223,11 @@ CREATE INDEX idx_memory_dependency_slot ON memory_dependencies(scope_id,slot_id)
5227
5223
  retained[key3] = now2;
5228
5224
  const temp = `${ledgerPath}.${randomUUID9()}.tmp`;
5229
5225
  try {
5230
- writeFileSync10(temp, JSON.stringify({ version: 1, heals: retained }));
5226
+ writeFileSync9(temp, JSON.stringify({ version: 1, heals: retained }));
5231
5227
  renameSync5(temp, ledgerPath);
5232
5228
  } catch (error) {
5233
5229
  try {
5234
- if (existsSync9(temp)) unlinkSync4(temp);
5230
+ if (existsSync9(temp)) unlinkSync3(temp);
5235
5231
  } catch {
5236
5232
  }
5237
5233
  console.warn(`[mem7] \u7F3A\u53E3\u81EA\u6108\u8D26\u672C\u5199\u5165\u5931\u8D25\uFF08\u672C\u8FDB\u7A0B\u5185\u4ECD\u53BB\u91CD\uFF0C\u91CD\u542F\u540E\u53EF\u80FD\u591A\u6CBB\u4E00\u6B21\uFF0C\u5E42\u7B49\u65E0\u5BB3\uFF09\uFF1A${error.message}`);
@@ -6350,12 +6346,20 @@ CREATE TABLE memory_tombstones (
6350
6346
  has(scope, kind, id) {
6351
6347
  return Boolean(this.db.prepare("SELECT 1 FROM memory_tombstones WHERE scope_id=? AND target_kind=? AND target_id=?").get(scopeId(scope), kind, id));
6352
6348
  }
6349
+ /** 1117:deep-recall 的引用只存 scopeId 字符串(无 scope 对象),同判定按 id 直查。 */
6350
+ hasByScopeId(scopeIdValue, kind, id) {
6351
+ return Boolean(this.db.prepare("SELECT 1 FROM memory_tombstones WHERE scope_id=? AND target_kind=? AND target_id=?").get(scopeIdValue, kind, id));
6352
+ }
6353
6353
  any(scope) {
6354
6354
  return Boolean(this.db.prepare("SELECT 1 FROM memory_tombstones WHERE scope_id=? LIMIT 1").get(scopeId(scope)));
6355
6355
  }
6356
6356
  anyForOwner(ownerId) {
6357
6357
  return Boolean(this.db.prepare("SELECT 1 FROM memory_tombstones t JOIN memory_scopes s ON s.scope_id=t.scope_id WHERE s.owner_id=? LIMIT 1").get(ownerId));
6358
6358
  }
6359
+ /** 1117:撤回校验的快速门——墓碑可挂在任意 scope(如旧 default 池)下,不看 owner。 */
6360
+ exists() {
6361
+ return Boolean(this.db.prepare("SELECT 1 FROM memory_tombstones LIMIT 1").get());
6362
+ }
6359
6363
  deleteSource(scope, sourceId, expectedVersion, requestKey, reason) {
6360
6364
  if (!requestKey || !reason.trim()) throw new Error("INVALID_DELETE_REQUEST");
6361
6365
  this.transaction(() => {
@@ -7082,7 +7086,7 @@ var init_ingest = __esm({
7082
7086
 
7083
7087
  // src/mem7/core/legacy-recovery.ts
7084
7088
  import { createHash as createHash13 } from "node:crypto";
7085
- import { readFileSync as readFileSync12, realpathSync as realpathSync4, statSync } from "node:fs";
7089
+ import { readFileSync as readFileSync11, realpathSync as realpathSync4, statSync } from "node:fs";
7086
7090
  import { isAbsolute as isAbsolute2, join as join16, relative as relative2, resolve as resolve9, sep as sep2 } from "node:path";
7087
7091
  function sessionCandidates(files, mapping) {
7088
7092
  const candidates = /* @__PURE__ */ new Map();
@@ -7092,7 +7096,7 @@ function sessionCandidates(files, mapping) {
7092
7096
  rejected++;
7093
7097
  continue;
7094
7098
  }
7095
- const bytes = readFileSync12(file);
7099
+ const bytes = readFileSync11(file);
7096
7100
  const records = [];
7097
7101
  let header;
7098
7102
  let invalid = false;
@@ -7338,7 +7342,7 @@ function recoverLegacyProjections(db, store, input, apply = false) {
7338
7342
  gap("projection_kind_or_owner_unverified");
7339
7343
  continue;
7340
7344
  }
7341
- const bytes = readFileSync12(canonical2);
7345
+ const bytes = readFileSync11(canonical2);
7342
7346
  const text2 = bytes.toString("utf8").replace(/\r\n/g, "\n");
7343
7347
  const fileHash = hash3(bytes);
7344
7348
  const entries = [...text2.matchAll(/<!-- entry:([^\s<>]+) -->([\s\S]*?)<!-- \/entry:\1 -->/g)];
@@ -7408,7 +7412,7 @@ function recoverLegacyProjections(db, store, input, apply = false) {
7408
7412
  if (!apply || !candidates.length) return report;
7409
7413
  for (const file of new Set(candidates.map((candidate) => candidate.file))) {
7410
7414
  const candidate = candidates.find((candidate2) => candidate2.file === file);
7411
- if (hash3(readFileSync12(file)) !== candidate.fileHash) throw new Error("LEGACY_PROJECTION_CHANGED_DURING_RECOVERY");
7415
+ if (hash3(readFileSync11(file)) !== candidate.fileHash) throw new Error("LEGACY_PROJECTION_CHANGED_DURING_RECOVERY");
7412
7416
  if (realpathSync4(store.mem7RootPath()) !== root) throw new Error("LEGACY_PROJECTION_COPY_REQUIRED");
7413
7417
  }
7414
7418
  store.transaction(() => {
@@ -8651,7 +8655,7 @@ var init_job_runner = __esm({
8651
8655
  });
8652
8656
 
8653
8657
  // src/mem7/core/episode.ts
8654
- import { readFileSync as readFileSync13 } from "node:fs";
8658
+ import { readFileSync as readFileSync12 } from "node:fs";
8655
8659
  import { join as join17, dirname as dirname7 } from "node:path";
8656
8660
  import { fileURLToPath } from "node:url";
8657
8661
  var PROMPT;
@@ -8660,7 +8664,7 @@ var init_episode = __esm({
8660
8664
  "use strict";
8661
8665
  init_prompt_render();
8662
8666
  init_job_runner();
8663
- PROMPT = readFileSync13(join17(dirname7(fileURLToPath(import.meta.url)), "prompts", "episode.md"), "utf8");
8667
+ PROMPT = readFileSync12(join17(dirname7(fileURLToPath(import.meta.url)), "prompts", "episode.md"), "utf8");
8664
8668
  }
8665
8669
  });
8666
8670
 
@@ -10745,7 +10749,7 @@ var init_retire_graph_audits = __esm({
10745
10749
 
10746
10750
  // src/mem7/core/store.ts
10747
10751
  import { DatabaseSync as DatabaseSync8 } from "node:sqlite";
10748
- import { mkdirSync as mkdirSync12, readFileSync as readFileSync14, writeFileSync as writeFileSync11, renameSync as renameSync6, existsSync as existsSync10, readdirSync as readdirSync3, lstatSync as lstatSync8, unlinkSync as unlinkSync5 } from "node:fs";
10752
+ import { mkdirSync as mkdirSync12, readFileSync as readFileSync13, writeFileSync as writeFileSync10, renameSync as renameSync6, existsSync as existsSync10, readdirSync as readdirSync3, lstatSync as lstatSync8, unlinkSync as unlinkSync4 } from "node:fs";
10749
10753
  import { join as join18, relative as relative3 } from "node:path";
10750
10754
  import { createHash as createHash19, randomUUID as randomUUID13 } from "node:crypto";
10751
10755
  function contentHash(text2) {
@@ -11238,7 +11242,7 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11238
11242
  let existingBlocks = "";
11239
11243
  let count;
11240
11244
  if (existsSync10(file)) {
11241
- const text2 = readFileSync14(file, "utf8");
11245
+ const text2 = readFileSync13(file, "utf8");
11242
11246
  const fmEnd = text2.indexOf("\n---", 3);
11243
11247
  const split = fmEnd >= 0 ? fmEnd + 4 : text2.length;
11244
11248
  head = text2.slice(0, split);
@@ -11295,7 +11299,7 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11295
11299
  let existingBlocks = "";
11296
11300
  let count;
11297
11301
  if (existsSync10(file)) {
11298
- const text2 = readFileSync14(file, "utf8");
11302
+ const text2 = readFileSync13(file, "utf8");
11299
11303
  const fmEnd = text2.indexOf("\n---", 3);
11300
11304
  const split = fmEnd >= 0 ? fmEnd + 4 : text2.length;
11301
11305
  head = text2.slice(0, split);
@@ -11343,11 +11347,11 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11343
11347
  assertRuntimeAuthority(this.stateDir, "WRITE");
11344
11348
  const temporary = `${file}.${randomUUID13()}.tmp`;
11345
11349
  try {
11346
- writeFileSync11(temporary, content, "utf8");
11350
+ writeFileSync10(temporary, content, "utf8");
11347
11351
  assertRuntimeAuthority(this.stateDir, "WRITE");
11348
11352
  renameSync6(temporary, file);
11349
11353
  } finally {
11350
- if (existsSync10(temporary)) unlinkSync5(temporary);
11354
+ if (existsSync10(temporary)) unlinkSync4(temporary);
11351
11355
  }
11352
11356
  }
11353
11357
  recordProjection(scope, kind, id, file, content, body, expectedVersion) {
@@ -11390,7 +11394,7 @@ CREATE TABLE IF NOT EXISTS cluster_members (
11390
11394
  let max = 0;
11391
11395
  if (existsSync10(file)) {
11392
11396
  const re = new RegExp(`${prefix}_${dateStr.replace(/-/g, "")}_(\\d+)`, "g");
11393
- for (const m of readFileSync14(file, "utf8").matchAll(re)) max = Math.max(max, Number(m[1]));
11397
+ for (const m of readFileSync13(file, "utf8").matchAll(re)) max = Math.max(max, Number(m[1]));
11394
11398
  }
11395
11399
  return max;
11396
11400
  }
@@ -11613,7 +11617,7 @@ ${e.outcome}
11613
11617
  for (const f of files) {
11614
11618
  let text2;
11615
11619
  try {
11616
- text2 = readFileSync14(join18(dir, f), "utf8");
11620
+ text2 = readFileSync13(join18(dir, f), "utf8");
11617
11621
  } catch {
11618
11622
  continue;
11619
11623
  }
@@ -11647,7 +11651,7 @@ ${e.outcome}
11647
11651
  for (const d of dirs) {
11648
11652
  let text2;
11649
11653
  try {
11650
- text2 = readFileSync14(join18(base, d, "SKILL.md"), "utf8");
11654
+ text2 = readFileSync13(join18(base, d, "SKILL.md"), "utf8");
11651
11655
  } catch {
11652
11656
  continue;
11653
11657
  }
@@ -11712,7 +11716,7 @@ ${e.outcome}
11712
11716
  let text2;
11713
11717
  const file = join18(this.root, this.ownerProjectionPath("users", ownerId, scope), "user.md");
11714
11718
  try {
11715
- text2 = readFileSync14(file, "utf8");
11719
+ text2 = readFileSync13(file, "utf8");
11716
11720
  } catch {
11717
11721
  return null;
11718
11722
  }
@@ -12284,7 +12288,7 @@ ${e.outcome}
12284
12288
  if (!/^foresight-\d{4}-\d{2}-\d{2}\.md$/.test(f)) continue;
12285
12289
  let content;
12286
12290
  try {
12287
- content = readFileSync14(join18(dir, f), "utf8");
12291
+ content = readFileSync13(join18(dir, f), "utf8");
12288
12292
  } catch {
12289
12293
  continue;
12290
12294
  }
@@ -12342,7 +12346,7 @@ var init_rerank = __esm({
12342
12346
  });
12343
12347
 
12344
12348
  // src/mem7/core/rank/arank.ts
12345
- import { readFileSync as readFileSync15 } from "node:fs";
12349
+ import { readFileSync as readFileSync14 } from "node:fs";
12346
12350
  import { join as join19, dirname as dirname8 } from "node:path";
12347
12351
  import { fileURLToPath as fileURLToPath2 } from "node:url";
12348
12352
  var PROMPT_DIR, EPISODIC_PROMPT, CASE_PROMPT, SKILL_PROMPT;
@@ -12353,9 +12357,9 @@ var init_arank = __esm({
12353
12357
  init_rerank();
12354
12358
  init_read_guard();
12355
12359
  PROMPT_DIR = join19(dirname8(fileURLToPath2(import.meta.url)), "prompts");
12356
- EPISODIC_PROMPT = readFileSync15(join19(PROMPT_DIR, "episodic-rerank.md"), "utf8");
12357
- CASE_PROMPT = readFileSync15(join19(PROMPT_DIR, "case-rerank.md"), "utf8");
12358
- SKILL_PROMPT = readFileSync15(join19(PROMPT_DIR, "skill-rerank.md"), "utf8");
12360
+ EPISODIC_PROMPT = readFileSync14(join19(PROMPT_DIR, "episodic-rerank.md"), "utf8");
12361
+ CASE_PROMPT = readFileSync14(join19(PROMPT_DIR, "case-rerank.md"), "utf8");
12362
+ SKILL_PROMPT = readFileSync14(join19(PROMPT_DIR, "skill-rerank.md"), "utf8");
12359
12363
  }
12360
12364
  });
12361
12365
 
@@ -12421,7 +12425,7 @@ var init_rerank_bridge = __esm({
12421
12425
  });
12422
12426
 
12423
12427
  // src/mem7/core/rank/agentic.ts
12424
- import { readFileSync as readFileSync16 } from "node:fs";
12428
+ import { readFileSync as readFileSync15 } from "node:fs";
12425
12429
  import { join as join20, dirname as dirname9 } from "node:path";
12426
12430
  import { fileURLToPath as fileURLToPath3 } from "node:url";
12427
12431
  var PROMPT_DIR2, SUFFICIENCY_PROMPT, MULTI_QUERY_PROMPT, REFINED_QUERY_PROMPT;
@@ -12431,9 +12435,9 @@ var init_agentic = __esm({
12431
12435
  init_read_guard();
12432
12436
  init_fusion();
12433
12437
  PROMPT_DIR2 = join20(dirname9(fileURLToPath3(import.meta.url)), "prompts");
12434
- SUFFICIENCY_PROMPT = readFileSync16(join20(PROMPT_DIR2, "sufficiency.md"), "utf8");
12435
- MULTI_QUERY_PROMPT = readFileSync16(join20(PROMPT_DIR2, "multi-query.md"), "utf8");
12436
- REFINED_QUERY_PROMPT = readFileSync16(join20(PROMPT_DIR2, "refined-query.md"), "utf8");
12438
+ SUFFICIENCY_PROMPT = readFileSync15(join20(PROMPT_DIR2, "sufficiency.md"), "utf8");
12439
+ MULTI_QUERY_PROMPT = readFileSync15(join20(PROMPT_DIR2, "multi-query.md"), "utf8");
12440
+ REFINED_QUERY_PROMPT = readFileSync15(join20(PROMPT_DIR2, "refined-query.md"), "utf8");
12437
12441
  }
12438
12442
  });
12439
12443
 
@@ -12502,7 +12506,7 @@ var init_search = __esm({
12502
12506
  // src/memory/topics-history/import-backups.ts
12503
12507
  import { DatabaseSync as DatabaseSync9, backup as backupSqlite } from "node:sqlite";
12504
12508
  import { randomUUID as randomUUID14 } from "node:crypto";
12505
- import { existsSync as existsSync11, mkdirSync as mkdirSync13, readFileSync as readFileSync17, renameSync as renameSync7, unlinkSync as unlinkSync6, writeFileSync as writeFileSync12 } from "node:fs";
12509
+ import { existsSync as existsSync11, mkdirSync as mkdirSync13, readFileSync as readFileSync16, renameSync as renameSync7, unlinkSync as unlinkSync5, writeFileSync as writeFileSync11 } from "node:fs";
12506
12510
  import { cp, readdir, rm } from "node:fs/promises";
12507
12511
  import { basename as basename5, dirname as dirname10, join as join21, resolve as resolve10 } from "node:path";
12508
12512
  import { fileURLToPath as fileURLToPath4 } from "node:url";
@@ -12510,10 +12514,10 @@ import { execFile } from "node:child_process";
12510
12514
  function atomicJson(path2, value) {
12511
12515
  const target = unlinked(path2), temp = unlinked(`${target}.${randomUUID14()}.tmp`);
12512
12516
  try {
12513
- writeFileSync12(temp, JSON.stringify(seal(value)) + "\n", { flag: "wx" });
12517
+ writeFileSync11(temp, JSON.stringify(seal(value)) + "\n", { flag: "wx" });
12514
12518
  renameSync7(temp, target);
12515
12519
  } finally {
12516
- if (existsSync11(temp)) unlinkSync6(temp);
12520
+ if (existsSync11(temp)) unlinkSync5(temp);
12517
12521
  }
12518
12522
  }
12519
12523
  function alive(pid) {
@@ -12540,10 +12544,10 @@ async function withTopicsImportLock(historyRoot2, action) {
12540
12544
  const path2 = unlinked(join21(root, ".topics-import.lock")), token = randomUUID14();
12541
12545
  const body = JSON.stringify({ pid: process.pid, token });
12542
12546
  try {
12543
- writeFileSync12(path2, body, { flag: "wx" });
12547
+ writeFileSync11(path2, body, { flag: "wx" });
12544
12548
  } catch (error) {
12545
12549
  if (error.code !== "EEXIST") throw error;
12546
- const original = readFileSync17(path2, "utf8");
12550
+ const original = readFileSync16(path2, "utf8");
12547
12551
  let owner;
12548
12552
  try {
12549
12553
  owner = JSON.parse(original);
@@ -12551,14 +12555,14 @@ async function withTopicsImportLock(historyRoot2, action) {
12551
12555
  throw new Error("TOPICS_IMPORT_BUSY: invalid lock");
12552
12556
  }
12553
12557
  if (alive(owner.pid)) throw new Error("TOPICS_IMPORT_BUSY");
12554
- if (readFileSync17(path2, "utf8") !== original) throw new Error("TOPICS_IMPORT_BUSY");
12555
- unlinkSync6(path2);
12556
- writeFileSync12(path2, body, { flag: "wx" });
12558
+ if (readFileSync16(path2, "utf8") !== original) throw new Error("TOPICS_IMPORT_BUSY");
12559
+ unlinkSync5(path2);
12560
+ writeFileSync11(path2, body, { flag: "wx" });
12557
12561
  }
12558
12562
  try {
12559
12563
  return await action();
12560
12564
  } finally {
12561
- if (existsSync11(path2) && readFileSync17(path2, "utf8") === body) unlinkSync6(path2);
12565
+ if (existsSync11(path2) && readFileSync16(path2, "utf8") === body) unlinkSync5(path2);
12562
12566
  }
12563
12567
  }
12564
12568
  function registryPath(stateDir) {
@@ -12665,7 +12669,7 @@ async function completeTopicsImportBackup(stateDir, historyRoot2) {
12665
12669
  const state = unlinked(stateDir), history = unlinked(historyRoot2), current2 = pending(state, history);
12666
12670
  if (!current2) return;
12667
12671
  atomicJson(join21(current2.path, receiptName), { ...current2.receipt, status: "complete", completedAt: Date.now() });
12668
- unlinkSync6(unlinked(join21(history, pointerName)));
12672
+ unlinkSync5(unlinked(join21(history, pointerName)));
12669
12673
  }
12670
12674
  async function removeBackup(state, root, name) {
12671
12675
  if (!receiptAt(state, root, name)) return false;
@@ -12917,7 +12921,7 @@ __export(import_mem7_exports, {
12917
12921
  topicsImported: () => topicsImported
12918
12922
  });
12919
12923
  import { DatabaseSync as DatabaseSync10 } from "node:sqlite";
12920
- import { existsSync as existsSync12, writeFileSync as writeFileSync13 } from "node:fs";
12924
+ import { existsSync as existsSync12, writeFileSync as writeFileSync12 } from "node:fs";
12921
12925
  import { join as join22 } from "node:path";
12922
12926
  function loadIndexFragments(b) {
12923
12927
  const root = topicsHistoryRoot(b);
@@ -13089,7 +13093,7 @@ ${fragment.body}`;
13089
13093
  pendingHashes.push(b2.hash);
13090
13094
  }
13091
13095
  if (pendingEmbeddings.length >= EMBED_SLICE) await flushEmbeddings();
13092
- writeFileSync13(join22(root, ".topics-import-progress.json"), JSON.stringify({ ...report, completedAt: (/* @__PURE__ */ new Date()).toISOString() }));
13096
+ writeFileSync12(join22(root, ".topics-import-progress.json"), JSON.stringify({ ...report, completedAt: (/* @__PURE__ */ new Date()).toISOString() }));
13093
13097
  } catch (error) {
13094
13098
  report.failed += batch.length;
13095
13099
  console.warn(`[topics-import] ${date} \u6279\u5931\u8D25\uFF08\u4FDD\u7559\u65AD\u70B9\uFF0C\u91CD\u8DD1\u7EED\u704C\uFF09:`, error instanceof Error ? error.message : String(error));
@@ -13097,7 +13101,7 @@ ${fragment.body}`;
13097
13101
  }
13098
13102
  await flushEmbeddings();
13099
13103
  if (report.failed === 0) {
13100
- writeFileSync13(doneMarker, JSON.stringify({ hashes: [.../* @__PURE__ */ new Set([...done, ...completed])], completedAt: (/* @__PURE__ */ new Date()).toISOString(), report }, null, 1));
13104
+ writeFileSync12(doneMarker, JSON.stringify({ hashes: [.../* @__PURE__ */ new Set([...done, ...completed])], completedAt: (/* @__PURE__ */ new Date()).toISOString(), report }, null, 1));
13101
13105
  try {
13102
13106
  await completeTopicsImportBackup(b.stateDir, root);
13103
13107
  await pruneTopicsImportBackups(b.stateDir);
@@ -13181,7 +13185,7 @@ var init_import_mem7 = __esm({
13181
13185
  });
13182
13186
 
13183
13187
  // src/memory/topics-history/worker.ts
13184
- import { readFileSync as readFileSync18 } from "node:fs";
13188
+ import { readFileSync as readFileSync17 } from "node:fs";
13185
13189
  import { setTimeout as delay } from "node:timers/promises";
13186
13190
 
13187
13191
  // src/config/secrets-env.ts
@@ -15712,7 +15716,7 @@ async function waitForIdle() {
15712
15716
  for (; ; ) {
15713
15717
  try {
15714
15718
  await waitForIdle();
15715
- const raw = JSON.parse(readFileSync18(configPath, "utf8").replace(/^\uFEFF/, ""));
15719
+ const raw = JSON.parse(readFileSync17(configPath, "utf8").replace(/^\uFEFF/, ""));
15716
15720
  loadSecretsEnvForConfig(configPath, { overwrite: true });
15717
15721
  const { liveConfig: liveConfig2 } = await Promise.resolve().then(() => (init_live(), live_exports));
15718
15722
  liveConfig2.init(raw);
@@ -1,14 +1,14 @@
1
1
  const require=(await import('node:module')).createRequire(import.meta.url)
2
2
 
3
3
  // src/continuity/authority-main.ts
4
- import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
5
- import { isAbsolute, join as join3, resolve as resolve2 } from "node:path";
4
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
5
+ import { isAbsolute as isAbsolute2, join as join4, resolve as resolve3 } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
 
8
8
  // src/continuity/authority.ts
9
9
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
10
10
  import { createHash, createPublicKey, generateKeyPairSync, randomBytes, randomUUID, sign, verify } from "node:crypto";
11
- import { existsSync, writeFileSync as writeFileSync2 } from "node:fs";
11
+ import { existsSync, writeFileSync } from "node:fs";
12
12
  import { join as join2 } from "node:path";
13
13
 
14
14
  // src/continuity/publication-objects.ts
@@ -20,19 +20,15 @@ import {
20
20
  fstatSync,
21
21
  fsyncSync,
22
22
  readSync,
23
- writeSync,
24
23
  lstatSync,
25
24
  realpathSync,
26
- mkdirSync,
27
- readFileSync,
28
- writeFileSync,
29
- linkSync,
30
- unlinkSync
25
+ mkdirSync
31
26
  } from "node:fs";
32
27
  import { join, dirname, resolve } from "node:path";
33
28
  var PUBLICATION_CHUNK_BYTES = 1024 * 1024;
34
29
  var HASH = /^[a-f0-9]{64}$/;
35
30
  var MAGIC = Buffer.from("E7P1");
31
+ var INLINE_BYTES = 64 * 1024;
36
32
  var noFollow = constants.O_NOFOLLOW ?? 0;
37
33
  function validateObjectRef(ref) {
38
34
  if (!ref || !HASH.test(ref.sha256) || !Number.isSafeInteger(ref.bytes) || ref.bytes < 1 || ref.bytes > PUBLICATION_CHUNK_BYTES)
@@ -110,7 +106,7 @@ function preparePrivateDatabase(path2) {
110
106
 
111
107
  // src/continuity/key-service-store.ts
112
108
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
113
- import { constants as constants2, lstatSync as lstatSync2, mkdirSync as mkdirSync2, openSync as openSync2, closeSync as closeSync2, readFileSync as readFileSync2, writeSync as writeSync2, fstatSync as fstatSync2, fsyncSync as fsyncSync2, unlinkSync as unlinkSync2 } from "node:fs";
109
+ import { constants as constants2, lstatSync as lstatSync2, mkdirSync as mkdirSync2, openSync as openSync2, closeSync as closeSync2, readFileSync, writeSync, fstatSync as fstatSync2, fsyncSync as fsyncSync2, unlinkSync } from "node:fs";
114
110
  function assertPrivateStat(stat, directory) {
115
111
  if ((directory ? !stat.isDirectory() : !stat.isFile()) || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
116
112
  throw new Error("KEY_SERVICE_PRIVATE_PATH_REQUIRED");
@@ -122,7 +118,7 @@ function readPrivateFile(path2, maximumBytes = 65536) {
122
118
  const stat = fstatSync2(fd);
123
119
  assertPrivateStat(stat, false);
124
120
  if (stat.size > maximumBytes) throw new Error("KEY_SERVICE_INVALID_FILE_SIZE");
125
- return readFileSync2(fd);
121
+ return readFileSync(fd);
126
122
  } finally {
127
123
  closeSync2(fd);
128
124
  }
@@ -191,7 +187,7 @@ var TravelAuthority = class {
191
187
  if (present !== keyPresent) throw new Error("TRAVEL_AUTHORITY_RECOVERY_REQUIRED");
192
188
  if (!keyPresent) {
193
189
  const keys = generateKeyPairSync("ed25519");
194
- writeFileSync2(keyFile, keys.privateKey.export({ format: "pem", type: "pkcs8" }), { mode: 384, flag: "wx", flush: true });
190
+ writeFileSync(keyFile, keys.privateKey.export({ format: "pem", type: "pkcs8" }), { mode: 384, flag: "wx", flush: true });
195
191
  }
196
192
  this.signingKey = readPrivateFile(keyFile).toString();
197
193
  this.publicKey = createPublicKey(this.signingKey).export({ format: "pem", type: "spki" }).toString();
@@ -274,6 +270,23 @@ var TravelAuthority = class {
274
270
  authenticate(credential) {
275
271
  return this.authenticateNode(credential, false);
276
272
  }
273
+ /** Trusted pairing owner binds the first real H to an unused reservation.
274
+ * This does not grant a lease and never rewrites a used seat's history. */
275
+ bindInitialCheckpoint(principal, digest, buildManifestId) {
276
+ if (!HASH2.test(digest) || digest === "0".repeat(64)) throw new Error("TRAVEL_INITIAL_BASELINE");
277
+ id(buildManifestId);
278
+ const text = identityText(principal);
279
+ this.transaction(() => {
280
+ const row = this.db.prepare("SELECT * FROM seats WHERE identity=?").get(text);
281
+ this.principal(principal);
282
+ if (!row || row.active_node !== null || row.active_boot !== null || row.frozen || row.retired !== null || row.floor !== 0 || row.build !== buildManifestId || this.db.prepare("SELECT 1 FROM handoffs WHERE identity=? LIMIT 1").get(text)) throw new Error("TRAVEL_INITIAL_BASELINE");
283
+ if (row.checkpoint === digest) return;
284
+ if (row.checkpoint !== "0".repeat(64)) throw new Error("TRAVEL_INITIAL_BASELINE");
285
+ this.db.prepare("DELETE FROM checkpoints WHERE identity=?").run(text);
286
+ this.db.prepare("INSERT INTO checkpoints VALUES(?,?,NULL,1)").run(text, digest);
287
+ this.db.prepare("UPDATE seats SET checkpoint=? WHERE identity=?").run(digest, text);
288
+ });
289
+ }
277
290
  authenticateRetirement(credential) {
278
291
  return this.authenticateNode(credential, true);
279
292
  }
@@ -329,6 +342,7 @@ var TravelAuthority = class {
329
342
  return { ...body, signature: sign(null, Buffer.from(JSON.stringify(body)), this.signingKey).toString("base64") };
330
343
  }
331
344
  acquire(principal, ready) {
345
+ if (ready.checkpointDigest === "0".repeat(64)) throw new Error("TRAVEL_INITIAL_BASELINE");
332
346
  return this.transaction(() => {
333
347
  const node = this.principal(principal), text = identityText(principal), row = this.seat(principal);
334
348
  if (!node.boot) throw new Error("TRAVEL_BOOT_REQUIRED");
@@ -628,7 +642,22 @@ var TravelAuthority = class {
628
642
  // src/continuity/publication.ts
629
643
  import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
630
644
  import { createHash as createHash2 } from "node:crypto";
631
- var PUBLICATION_MANIFEST_BYTES = 4 * 1024 * 1024;
645
+
646
+ // src/continuity/inventory.ts
647
+ import { isAbsolute, join as join3, relative, resolve as resolve2, sep } from "node:path";
648
+ var STATE = new Set(`workspace agents auth configs cron media mem7 memory runtime session-memory steer tasks teams todos tools topics topics-history .everos .calendar calendar proactive skills prompts goals.json goal-events.jsonl SESSION-STATE.md install-identity.json license.json report-failures.jsonl report-state.json service-suggestions.json weixin cc-driver engines.json settings.json onboarding.json onboarding-tips.json remote-watchers.json plans telegram state`.split(" "));
649
+ var CORE_DIRECTORIES = new Set(`agents auth configs cron mem7 memory runtime session-memory steer tasks teams todos tools .everos .calendar calendar .proactive proactive skills prompts .nudge hooks inner-voice goals plans private scripts state .voice-chat .desktopBuddy body`.split(" "));
650
+ var CORE_OMITTED = new Set(`media images videos audio content content-library docs output outputs dogfood-output backup backups topics-history node_modules .venvs venv .venv asr .cache cache caches tmp temp .playwright-mcp lancedb`.split(" "));
651
+ function validateRelativePath(path2) {
652
+ if (typeof path2 !== "string" || !path2 || path2.length > 2048 || isAbsolute(path2)) throw new Error("INVALID_ARTIFACT_PATH");
653
+ for (const part of path2.split("/")) {
654
+ if (!part || part === "." || part === ".." || /[\x00-\x1f]/.test(part) || Buffer.byteLength(part) > 255 || process.platform === "win32" && (/[<>:"|?*\\]/.test(part) || /[. ]$/.test(part) || /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(part)))
655
+ throw new Error("INVALID_ARTIFACT_PATH");
656
+ }
657
+ }
658
+
659
+ // src/continuity/publication.ts
660
+ var PUBLICATION_MANIFEST_BYTES = 32 * 1024 * 1024;
632
661
  var PUBLICATION_COMMIT_BYTES = 24 * 1024 * 1024;
633
662
  var ZERO = "0".repeat(64);
634
663
  var HASH3 = /^[a-f0-9]{64}$/;
@@ -669,8 +698,12 @@ function normalizePublicationProfile(value) {
669
698
  return Object.freeze(profile);
670
699
  }
671
700
  function validatePublicationPath(path2) {
672
- if (typeof path2 !== "string" || !path2 || path2.length > 2048 || path2.normalize("NFC") !== path2 || /[\x00-\x1f<>:"|?*\\]/.test(path2) || path2.split("/").some((p) => !p || p === "." || p === ".." || /[. ]$/.test(p) || /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(p)))
701
+ if (typeof path2 !== "string" || path2.normalize("NFC") !== path2) throw new Error("PUBLICATION_INVALID_PATH");
702
+ try {
703
+ validateRelativePath(path2);
704
+ } catch {
673
705
  throw new Error("PUBLICATION_INVALID_PATH");
706
+ }
674
707
  }
675
708
  function normalizePublication(value) {
676
709
  if (!value || value.format !== "engine7-publication-v1" || !natural2(value.sequence) || !value.sequence || !HASH3.test(value.parentDigest) || !natural2(value.deletionWatermark) || !Array.isArray(value.databases) || !Array.isArray(value.trees)) throw new Error("PUBLICATION_INVALID_MANIFEST");
@@ -756,6 +789,7 @@ var errors = /* @__PURE__ */ new Set([
756
789
  "TRAVEL_ANCESTRY_GAP"
757
790
  ]);
758
791
  var managementFields = {
792
+ bindInitialCheckpoint: ["digest", "buildManifestId"],
759
793
  retire: ["jobId"],
760
794
  retirementStatus: [],
761
795
  status: [],
@@ -777,6 +811,7 @@ var managementFields = {
777
811
  var retirementAction = (value) => value === "retire" || value === "retirementStatus";
778
812
  var record = (value) => !!value && typeof value === "object" && !Array.isArray(value);
779
813
  function validManagement(input) {
814
+ if (input.action === "bindInitialCheckpoint" && !(typeof input.buildManifestId === "string" && identifier.test(input.buildManifestId))) return false;
780
815
  if (input.action === "retire" && !(typeof input.jobId === "string" && identifier.test(input.jobId))) return false;
781
816
  if (!Object.hasOwn(managementFields, String(input.action))) return false;
782
817
  const fields = managementFields[String(input.action)];
@@ -792,7 +827,7 @@ function validManagement(input) {
792
827
  return true;
793
828
  }
794
829
  function createTravelAuthorityServer(options) {
795
- const { authority, proxyFingerprints = [], allowedPeers = {}, managementPeers = {}, recoveryPeers = {}, retirementPeers = {}, maximumInFlight = 16, requestTimeoutMs = 8e3, ...tls } = options;
830
+ const { authority, proxyFingerprints = [], allowedPeers = {}, managementPeers = {}, recoveryPeers = {}, retirementPeers = {}, bootstrapPeers = {}, maximumInFlight = 16, requestTimeoutMs = 8e3, ...tls } = options;
796
831
  const proxies = /* @__PURE__ */ new Set(), peers = /* @__PURE__ */ new Map(), managers = /* @__PURE__ */ new Map();
797
832
  const fingerprint = (value) => {
798
833
  const normalized = value.replaceAll(":", "").toLowerCase();
@@ -824,6 +859,12 @@ function createTravelAuthorityServer(options) {
824
859
  if (!Array.isArray(credentials) || !credentials.length || credentials.some((credential) => !managers.get(fp)?.has(authority.authenticateRetirement(credential).credentialHash))) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
825
860
  recoveryGrants.set(fp, new Set(credentials.map((credential) => authority.authenticateRetirement(credential).credentialHash)));
826
861
  }
862
+ const bootstrapGrants = /* @__PURE__ */ new Map();
863
+ for (const [value, credentials] of Object.entries(bootstrapPeers)) {
864
+ const fp = fingerprint(value);
865
+ if (!Array.isArray(credentials) || !credentials.length || credentials.some((credential) => !managers.get(fp)?.has(authority.authenticateRetirement(credential).credentialHash))) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
866
+ bootstrapGrants.set(fp, new Set(credentials.map((credential) => authority.authenticateRetirement(credential).credentialHash)));
867
+ }
827
868
  const retirees = /* @__PURE__ */ new Map();
828
869
  for (const [value, credentials] of Object.entries(retirementPeers)) {
829
870
  const fp = fingerprint(value);
@@ -908,6 +949,11 @@ function createTravelAuthorityServer(options) {
908
949
  if (managing) {
909
950
  if (input.permit && ["tenantId", "companionId", "seatId", "nodeId"].some((key) => input.permit[key] !== principal[key])) throw new Error("TRAVEL_AUTH_DENIED");
910
951
  switch (input.action) {
952
+ case "bindInitialCheckpoint":
953
+ if (!bootstrapGrants.get(peerFingerprint)?.has(principal.credentialHash)) throw new Error("TRAVEL_AUTH_DENIED");
954
+ authority.bindInitialCheckpoint(principal, input.digest, input.buildManifestId);
955
+ result = {};
956
+ break;
911
957
  case "retire":
912
958
  authority.retire(principal, input.jobId);
913
959
  result = {};
@@ -946,7 +992,7 @@ function createTravelAuthorityServer(options) {
946
992
  }
947
993
  case "assertPermit":
948
994
  authority.assertPermit(input.permit, input.operation);
949
- result = {};
995
+ result = { status: authority.status(principal) };
950
996
  break;
951
997
  case "acquire":
952
998
  result = { permit: authority.acquire(principal, input.ready) };
@@ -996,20 +1042,20 @@ function createTravelAuthorityServer(options) {
996
1042
 
997
1043
  // src/continuity/authority-main.ts
998
1044
  function path(value) {
999
- if (typeof value !== "string" || !isAbsolute(value)) throw new Error("TRAVEL_CONTROL_ABSOLUTE_PATH_REQUIRED");
1000
- return resolve2(value);
1045
+ if (typeof value !== "string" || !isAbsolute2(value)) throw new Error("TRAVEL_CONTROL_ABSOLUTE_PATH_REQUIRED");
1046
+ return resolve3(value);
1001
1047
  }
1002
1048
  async function startTravelAuthorityService(config) {
1003
1049
  if (!Number.isSafeInteger(config?.port) || config.port < 0 || config.port > 65535 || typeof config.host !== "string" || !config.host) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
1004
1050
  const directory = path(config.authorityDir);
1005
- if (!existsSync2(join3(directory, "authority.sqlite")) || !existsSync2(join3(directory, "authority-signing.pem"))) throw new Error("TRAVEL_CONTROL_REGISTRATION_REQUIRED");
1051
+ if (!existsSync2(join4(directory, "authority.sqlite")) || !existsSync2(join4(directory, "authority-signing.pem"))) throw new Error("TRAVEL_CONTROL_REGISTRATION_REQUIRED");
1006
1052
  const authority = new TravelAuthority({ directory, leaseMs: config.leaseMs });
1007
1053
  let server, key, closing;
1008
1054
  const close = () => closing ??= (async () => {
1009
1055
  try {
1010
1056
  if (server) {
1011
1057
  server.closeAllConnections();
1012
- await new Promise((resolve3) => server.close(() => resolve3()));
1058
+ await new Promise((resolve4) => server.close(() => resolve4()));
1013
1059
  }
1014
1060
  } finally {
1015
1061
  authority.close();
@@ -1021,8 +1067,8 @@ async function startTravelAuthorityService(config) {
1021
1067
  server = createTravelAuthorityServer({
1022
1068
  authority,
1023
1069
  key,
1024
- cert: readFileSync3(path(config.tls?.certFile)),
1025
- ca: readFileSync3(path(config.tls?.caFile)),
1070
+ cert: readFileSync2(path(config.tls?.certFile)),
1071
+ ca: readFileSync2(path(config.tls?.caFile)),
1026
1072
  proxyFingerprints: config.proxyFingerprints,
1027
1073
  allowedPeers: config.allowedPeers,
1028
1074
  managementPeers: config.managementPeers,
@@ -1031,9 +1077,9 @@ async function startTravelAuthorityService(config) {
1031
1077
  maximumInFlight: config.maximumInFlight,
1032
1078
  requestTimeoutMs: config.requestTimeoutMs
1033
1079
  });
1034
- await new Promise((resolve3, reject) => {
1080
+ await new Promise((resolve4, reject) => {
1035
1081
  server.once("error", reject);
1036
- server.listen(config.port, config.host, resolve3);
1082
+ server.listen(config.port, config.host, resolve4);
1037
1083
  });
1038
1084
  const status = () => ({ ready: true, port: server.address().port, authorityBootId: authority.authorityBootId });
1039
1085
  return { server, authority, close, status };
@@ -1056,7 +1102,7 @@ async function runTravelAuthorityCli(args) {
1056
1102
  process.once("SIGINT", stop);
1057
1103
  return service.status();
1058
1104
  }
1059
- if (process.argv[1] && resolve2(process.argv[1]) === fileURLToPath(import.meta.url)) {
1105
+ if (process.argv[1] && resolve3(process.argv[1]) === fileURLToPath(import.meta.url)) {
1060
1106
  runTravelAuthorityCli(process.argv.slice(2)).then((result) => process.stdout.write(JSON.stringify(result) + "\n")).catch(() => {
1061
1107
  process.stderr.write("TRAVEL_CONTROL_REFUSED\n");
1062
1108
  process.exitCode = 1;