chat-recall 0.7.51 → 0.7.54

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.
package/dist/cli.js CHANGED
@@ -8075,8 +8075,10 @@ var init_claude = __esm({
8075
8075
  const cutoff = opts.sinceMs ?? 0;
8076
8076
  const filter = opts.projectFilter?.toLowerCase();
8077
8077
  const byId = /* @__PURE__ */ new Map();
8078
- for (const root of claudeProjectDirs()) {
8079
- this.collectSessionsFromRoot(root, filter, byId, opts.previews !== false);
8078
+ const roots = claudeProjectDirs();
8079
+ const fresh = cutoff > 0 ? this.sessionIdsChangedSince(roots, cutoff) : null;
8080
+ for (const root of roots) {
8081
+ this.collectSessionsFromRoot(root, filter, byId, opts.previews !== false, fresh);
8080
8082
  }
8081
8083
  const out = [...byId.values()].filter((r) => r.mtime >= cutoff);
8082
8084
  out.sort((a, b) => b.mtime - a.mtime);
@@ -8092,7 +8094,48 @@ var init_claude = __esm({
8092
8094
  * handled both refs under one ledger row with two different mtimes, and the
8093
8095
  * row that shipped nothing stamped the other copy's mtime.
8094
8096
  */
8095
- collectSessionsFromRoot(root, filter, byId, previews) {
8097
+ /**
8098
+ * The ids of the sessions that have a transcript file with an mtime at or above
8099
+ * `cutoff`, in any home. One directory read per project and one stat per file,
8100
+ * with no file content read and no ref built. A session with a copy in two
8101
+ * homes is in the set when either copy is new, which is the rule the cutoff
8102
+ * of `listSessions` applies to the merged session.
8103
+ */
8104
+ sessionIdsChangedSince(roots, cutoff) {
8105
+ const ids = /* @__PURE__ */ new Set();
8106
+ for (const root of roots) {
8107
+ if (!existsSync9(root))
8108
+ continue;
8109
+ let projects;
8110
+ try {
8111
+ projects = readdirSync7(root, { withFileTypes: true });
8112
+ } catch {
8113
+ continue;
8114
+ }
8115
+ for (const proj of projects) {
8116
+ if (!proj.isDirectory())
8117
+ continue;
8118
+ const projPath = join10(root, proj.name);
8119
+ let files;
8120
+ try {
8121
+ files = readdirSync7(projPath);
8122
+ } catch {
8123
+ continue;
8124
+ }
8125
+ for (const f of files) {
8126
+ if (!f.endsWith(".jsonl") || f === "sessions-index.json")
8127
+ continue;
8128
+ try {
8129
+ if (statSync8(join10(projPath, f)).mtimeMs >= cutoff)
8130
+ ids.add(basename5(f, ".jsonl"));
8131
+ } catch {
8132
+ }
8133
+ }
8134
+ }
8135
+ }
8136
+ return ids;
8137
+ }
8138
+ collectSessionsFromRoot(root, filter, byId, previews, fresh = null) {
8096
8139
  const add = (ref) => {
8097
8140
  const prior = byId.get(ref.rawId);
8098
8141
  if (!prior) {
@@ -8120,6 +8163,10 @@ var init_claude = __esm({
8120
8163
  const indexData = JSON.parse(readFileSync7(indexPath, "utf-8"));
8121
8164
  const entries = indexData.entries || [];
8122
8165
  for (const entry of entries) {
8166
+ if (fresh && !fresh.has(entry.sessionId)) {
8167
+ indexed.add(entry.sessionId);
8168
+ continue;
8169
+ }
8123
8170
  if (!entry.fullPath || !existsSync9(entry.fullPath))
8124
8171
  continue;
8125
8172
  indexed.add(entry.sessionId);
@@ -8152,6 +8199,8 @@ var init_claude = __esm({
8152
8199
  const sessionId = basename5(f, ".jsonl");
8153
8200
  if (indexed.has(sessionId))
8154
8201
  continue;
8202
+ if (fresh && !fresh.has(sessionId))
8203
+ continue;
8155
8204
  const fullPath = join10(projPath, f);
8156
8205
  let stat3;
8157
8206
  try {
@@ -16191,7 +16240,657 @@ var init_walk_budget = __esm({
16191
16240
  "src/walk-budget.ts"() {
16192
16241
  "use strict";
16193
16242
  DEFAULT_WALK_MAX_SESSIONS = 2e3;
16194
- FULL_WALK_INTERVAL_MS = 6 * 60 * 6e4;
16243
+ FULL_WALK_INTERVAL_MS = 24 * 60 * 6e4;
16244
+ }
16245
+ });
16246
+
16247
+ // src/tombstone-rule.ts
16248
+ function tombstoneMode(env = process.env) {
16249
+ const raw = env.CHAT_RECALL_TOMBSTONES?.trim().toLowerCase();
16250
+ if (raw === "act" || raw === "off" || raw === "report") return raw;
16251
+ return "report";
16252
+ }
16253
+ function planTombstones(opts) {
16254
+ const ids = [];
16255
+ let ledgerSize = 0;
16256
+ for (const id of opts.ledgerIds) {
16257
+ ledgerSize++;
16258
+ if (opts.visited.has(id)) continue;
16259
+ let answer;
16260
+ try {
16261
+ answer = opts.probe(id);
16262
+ } catch {
16263
+ answer = "unknown";
16264
+ }
16265
+ if (answer === "missing") ids.push(id);
16266
+ }
16267
+ const tooLarge = ids.length > TOMBSTONE_MIN_GUARDED_BATCH && ids.length > ledgerSize * TOMBSTONE_MAX_SHARE;
16268
+ return { ids, refused: tooLarge ? "batch_too_large" : null };
16269
+ }
16270
+ function describeTombstonePlan(plan, mode) {
16271
+ const first = plan.ids.slice(0, 5).join(", ");
16272
+ if (plan.refused) {
16273
+ return `[sync] ${plan.ids.length} session(s) have no source and the batch is too large to send (more than ${TOMBSTONE_MAX_SHARE * 100}% of the ledger); first ids: ${first}`;
16274
+ }
16275
+ return `[sync] ${plan.ids.length} session(s) have no source (mode ${mode}); first ids: ${first}`;
16276
+ }
16277
+ var TOMBSTONE_MAX_SHARE, TOMBSTONE_MIN_GUARDED_BATCH;
16278
+ var init_tombstone_rule = __esm({
16279
+ "src/tombstone-rule.ts"() {
16280
+ "use strict";
16281
+ TOMBSTONE_MAX_SHARE = 0.05;
16282
+ TOMBSTONE_MIN_GUARDED_BATCH = 50;
16283
+ }
16284
+ });
16285
+
16286
+ // src/session-source-probe.ts
16287
+ function probeSessionSource(id) {
16288
+ const backend = getBackendForId(id);
16289
+ if (!backend || !backend.isAvailable()) return "unknown";
16290
+ try {
16291
+ return backend.findSession(id) ? "present" : "missing";
16292
+ } catch {
16293
+ return "unknown";
16294
+ }
16295
+ }
16296
+ var init_session_source_probe = __esm({
16297
+ "src/session-source-probe.ts"() {
16298
+ "use strict";
16299
+ init_tool_backend();
16300
+ }
16301
+ });
16302
+
16303
+ // src/http.ts
16304
+ var http_exports = {};
16305
+ __export(http_exports, {
16306
+ cliVersion: () => cliVersion,
16307
+ clientHeaders: () => clientHeaders,
16308
+ fetchWithTimeout: () => fetchWithTimeout
16309
+ });
16310
+ import { readFileSync as readFileSync20 } from "node:fs";
16311
+ function cliVersion() {
16312
+ return CLI_VERSION;
16313
+ }
16314
+ function clientHeaders() {
16315
+ return {
16316
+ "x-chat-recall-cli": CLI_VERSION,
16317
+ "x-chat-recall-os": `${process.platform}-${process.arch}`
16318
+ };
16319
+ }
16320
+ function fetchWithTimeout(url, init = {}, ms = 15e3) {
16321
+ const headers = new Headers(clientHeaders());
16322
+ new Headers(init.headers ?? {}).forEach((v, k) => headers.set(k, v));
16323
+ return fetch(url, { ...init, headers, signal: init.signal ?? AbortSignal.timeout(ms) });
16324
+ }
16325
+ var CLI_VERSION;
16326
+ var init_http = __esm({
16327
+ "src/http.ts"() {
16328
+ "use strict";
16329
+ CLI_VERSION = "0.0.0";
16330
+ try {
16331
+ CLI_VERSION = JSON.parse(readFileSync20(new URL("../package.json", import.meta.url), "utf-8")).version || CLI_VERSION;
16332
+ } catch {
16333
+ try {
16334
+ if (typeof __CLI_VERSION__ === "string") CLI_VERSION = __CLI_VERSION__;
16335
+ } catch {
16336
+ }
16337
+ }
16338
+ }
16339
+ });
16340
+
16341
+ // ../engine/dist/core/extractor-version.js
16342
+ function extractorVersionForItem(id, sourceType) {
16343
+ const tool = toolOfId(id);
16344
+ return extractorVersionForTool(tool) + (ITEM_SOURCE_BUMP[sourceType] ?? 0) + (ITEM_TOOL_SOURCE_BUMP[`${tool}:${sourceType}`] ?? 0);
16345
+ }
16346
+ function toolOfId(id) {
16347
+ if (id.startsWith("agy_"))
16348
+ return "agy";
16349
+ if (id.startsWith("gemini_"))
16350
+ return "gemini";
16351
+ if (id.startsWith("opencode_"))
16352
+ return "opencode";
16353
+ if (id.startsWith("codex_"))
16354
+ return "codex";
16355
+ if (id.startsWith("cursor_"))
16356
+ return "cursor";
16357
+ if (id.startsWith("hermes_"))
16358
+ return "hermes";
16359
+ if (id.startsWith("pi_"))
16360
+ return "pi";
16361
+ return "claude";
16362
+ }
16363
+ function extractorVersionForTool(tool) {
16364
+ return BASE_EXTRACTOR_VERSION + (TOOL_EXTRACTOR_BUMP[tool ?? ""] ?? 0);
16365
+ }
16366
+ function extractorVersionForId(id) {
16367
+ return extractorVersionForTool(toolOfId(id));
16368
+ }
16369
+ var BASE_EXTRACTOR_VERSION, ITEM_SOURCE_BUMP, ITEM_TOOL_SOURCE_BUMP, TOOL_EXTRACTOR_BUMP, EXTRACTOR_VERSION;
16370
+ var init_extractor_version = __esm({
16371
+ "../engine/dist/core/extractor-version.js"() {
16372
+ "use strict";
16373
+ BASE_EXTRACTOR_VERSION = 2;
16374
+ ITEM_SOURCE_BUMP = {
16375
+ mcp: 2,
16376
+ skill: 1,
16377
+ agent: 1,
16378
+ command: 1
16379
+ };
16380
+ ITEM_TOOL_SOURCE_BUMP = {
16381
+ "codex:skill": 1,
16382
+ "codex:plugin": 1
16383
+ };
16384
+ TOOL_EXTRACTOR_BUMP = {
16385
+ agy: 3,
16386
+ claude: 1,
16387
+ codex: 1
16388
+ };
16389
+ EXTRACTOR_VERSION = BASE_EXTRACTOR_VERSION;
16390
+ }
16391
+ });
16392
+
16393
+ // src/sync-ledger.ts
16394
+ var sync_ledger_exports = {};
16395
+ __export(sync_ledger_exports, {
16396
+ SETTLE_QUIET_MS: () => SETTLE_QUIET_MS,
16397
+ _resetLedgerCacheForTests: () => _resetLedgerCacheForTests,
16398
+ _resetUnackedCursorCount: () => _resetUnackedCursorCount,
16399
+ fieldNeedsFullPass: () => fieldNeedsFullPass,
16400
+ fieldNeedsScan: () => fieldNeedsScan,
16401
+ flushLedger: () => flushLedger,
16402
+ forceFieldRescan: () => forceFieldRescan,
16403
+ forgetFullCoverage: () => forgetFullCoverage,
16404
+ forgetSessions: () => forgetSessions,
16405
+ fullCoveredOffset: () => fullCoveredOffset,
16406
+ getLedgerData: () => getLedgerData,
16407
+ getSyncedMtimes: () => getSyncedMtimes,
16408
+ getSyncedRows: () => getSyncedRows,
16409
+ ledgerFilePath: () => ledgerFilePath,
16410
+ loadInventoryHashes: () => loadInventoryHashes,
16411
+ loadItemVersions: () => loadItemVersions,
16412
+ markFieldCoverage: () => markFieldCoverage,
16413
+ markFieldFullPassDone: () => markFieldFullPassDone,
16414
+ markFullResync: () => markFullResync,
16415
+ markSynced: () => markSynced,
16416
+ persistLedgerData: () => persistLedgerData,
16417
+ pruneLedgerTargets: () => pruneLedgerTargets,
16418
+ saveInventoryHashes: () => saveInventoryHashes,
16419
+ saveItemVersions: () => saveItemVersions,
16420
+ syncMode: () => syncMode,
16421
+ unackedCursorAttemptCount: () => unackedCursorAttemptCount
16422
+ });
16423
+ import { readFileSync as readFileSync21, writeFileSync as writeFileSync6, renameSync as renameSync4, mkdirSync as mkdirSync6, statSync as statSync20 } from "node:fs";
16424
+ import { join as join26, dirname as dirname15 } from "node:path";
16425
+ function toRow(entry) {
16426
+ if (entry === void 0) return void 0;
16427
+ return typeof entry === "number" ? { m: entry, v: 0 } : entry;
16428
+ }
16429
+ function ledgerFilePath() {
16430
+ return ledgerPath();
16431
+ }
16432
+ function stampOf(path) {
16433
+ try {
16434
+ const st = statSync20(path);
16435
+ return `${st.mtimeMs}:${st.size}`;
16436
+ } catch {
16437
+ return null;
16438
+ }
16439
+ }
16440
+ function readDisk(path) {
16441
+ try {
16442
+ const parsed = JSON.parse(readFileSync21(path, "utf-8"));
16443
+ return parsed && typeof parsed === "object" ? parsed : {};
16444
+ } catch {
16445
+ return {};
16446
+ }
16447
+ }
16448
+ function snapshot(data) {
16449
+ const out = /* @__PURE__ */ new Map();
16450
+ for (const [server, rows] of Object.entries(data)) {
16451
+ for (const [id, entry] of Object.entries(rows)) out.set(rowKey(server, id), JSON.stringify(entry));
16452
+ }
16453
+ return out;
16454
+ }
16455
+ function mergeOnto(disk) {
16456
+ const out = {};
16457
+ const put = (server, id, entry) => {
16458
+ (out[server] ??= {})[id] = entry;
16459
+ };
16460
+ const mine = cache2 ?? {};
16461
+ for (const [server, rows] of Object.entries(disk)) {
16462
+ for (const [id, entry] of Object.entries(rows)) {
16463
+ const k = rowKey(server, id);
16464
+ const own = mine[server]?.[id];
16465
+ const was = base.get(k);
16466
+ if (own === void 0) {
16467
+ if (was === void 0) put(server, id, entry);
16468
+ } else {
16469
+ put(server, id, JSON.stringify(own) === was ? entry : own);
16470
+ }
16471
+ }
16472
+ }
16473
+ for (const [server, rows] of Object.entries(mine)) {
16474
+ for (const [id, entry] of Object.entries(rows)) {
16475
+ if (disk[server]?.[id] !== void 0) continue;
16476
+ if (JSON.stringify(entry) !== base.get(rowKey(server, id))) put(server, id, entry);
16477
+ }
16478
+ }
16479
+ return out;
16480
+ }
16481
+ function load() {
16482
+ const path = ledgerPath();
16483
+ const stamp = stampOf(path);
16484
+ if (cache2 && stamp === diskStamp) return cache2;
16485
+ const disk = readDisk(path);
16486
+ const merged = cache2 ? mergeOnto(disk) : disk;
16487
+ if (cache2) {
16488
+ for (const server of Object.keys(cache2)) if (!(server in merged)) delete cache2[server];
16489
+ for (const [server, rows] of Object.entries(merged)) {
16490
+ const target = cache2[server] ?? (cache2[server] = {});
16491
+ for (const id of Object.keys(target)) if (!(id in rows)) delete target[id];
16492
+ Object.assign(target, rows);
16493
+ }
16494
+ } else {
16495
+ cache2 = merged;
16496
+ }
16497
+ base = snapshot(disk);
16498
+ diskStamp = stamp;
16499
+ return cache2;
16500
+ }
16501
+ function persistNow() {
16502
+ const path = ledgerPath();
16503
+ mkdirSync6(dirname15(path), { recursive: true });
16504
+ load();
16505
+ const tmp = `${path}.tmp-${process.pid}`;
16506
+ writeFileSync6(tmp, JSON.stringify(cache2 ?? {}));
16507
+ renameSync4(tmp, path);
16508
+ base = snapshot(cache2 ?? {});
16509
+ diskStamp = stampOf(path);
16510
+ pendingWrite = false;
16511
+ }
16512
+ function persist(_data) {
16513
+ pendingWrite = true;
16514
+ if (flushTimer) return;
16515
+ flushTimer = setTimeout(() => {
16516
+ flushTimer = null;
16517
+ if (pendingWrite) {
16518
+ try {
16519
+ persistNow();
16520
+ } catch {
16521
+ }
16522
+ }
16523
+ }, LEDGER_FLUSH_MS);
16524
+ flushTimer.unref?.();
16525
+ }
16526
+ function pruneLedgerTargets(configuredServers) {
16527
+ const data = load();
16528
+ const keep = new Set(configuredServers);
16529
+ const orphans = {};
16530
+ for (const server of Object.keys(data)) {
16531
+ if (!keep.has(server)) {
16532
+ orphans[server] = data[server];
16533
+ delete data[server];
16534
+ }
16535
+ }
16536
+ const names = Object.keys(orphans);
16537
+ if (names.length === 0) return 0;
16538
+ const path = ledgerPath();
16539
+ const side = `${path}.orphans.json`;
16540
+ try {
16541
+ let prior = {};
16542
+ try {
16543
+ prior = JSON.parse(readFileSync21(side, "utf-8"));
16544
+ } catch {
16545
+ }
16546
+ writeFileSync6(side, JSON.stringify({ ...prior, ...orphans }));
16547
+ } catch {
16548
+ for (const n of names) data[n] = orphans[n];
16549
+ return 0;
16550
+ }
16551
+ const rows = names.reduce((n, s) => n + Object.keys(orphans[s]).length, 0);
16552
+ console.error(`[sync] tidied local bookkeeping: ${rows} already-synced marker(s) for ${names.length} server(s) you no longer sync to (${names.join(", ")}) moved to ${side}. Nothing was uploaded there; the file is kept so logging back in re-ships nothing.`);
16553
+ persistNow();
16554
+ return names.length;
16555
+ }
16556
+ function flushLedger() {
16557
+ if (flushTimer) {
16558
+ clearTimeout(flushTimer);
16559
+ flushTimer = null;
16560
+ }
16561
+ if (!pendingWrite || !cache2) return;
16562
+ persistNow();
16563
+ }
16564
+ function loadItemVersionsAll() {
16565
+ if (itemVersionsCache) return itemVersionsCache;
16566
+ try {
16567
+ const parsed = JSON.parse(readFileSync21(itemVersionsPath(), "utf-8"));
16568
+ itemVersionsCache = parsed && typeof parsed === "object" ? parsed : {};
16569
+ } catch {
16570
+ itemVersionsCache = {};
16571
+ }
16572
+ return itemVersionsCache;
16573
+ }
16574
+ function loadItemVersions(server) {
16575
+ return { ...loadItemVersionsAll()[server] || {} };
16576
+ }
16577
+ function saveItemVersions(server, versions) {
16578
+ const all = loadItemVersionsAll();
16579
+ all[server] = { ...all[server] || {}, ...versions };
16580
+ const path = itemVersionsPath();
16581
+ mkdirSync6(dirname15(path), { recursive: true });
16582
+ const tmp = `${path}.tmp`;
16583
+ writeFileSync6(tmp, JSON.stringify(all));
16584
+ renameSync4(tmp, path);
16585
+ }
16586
+ function loadInventoryHashes(server) {
16587
+ try {
16588
+ const parsed = JSON.parse(readFileSync21(inventoryPath(), "utf-8"));
16589
+ return { ...(parsed && typeof parsed === "object" ? parsed[server] : null) || {} };
16590
+ } catch {
16591
+ return {};
16592
+ }
16593
+ }
16594
+ function saveInventoryHashes(server, hashes) {
16595
+ let all = {};
16596
+ try {
16597
+ all = JSON.parse(readFileSync21(inventoryPath(), "utf-8"));
16598
+ } catch {
16599
+ }
16600
+ if (!all || typeof all !== "object") all = {};
16601
+ all[server] = { ...all[server] || {}, ...hashes };
16602
+ const path = inventoryPath();
16603
+ mkdirSync6(dirname15(path), { recursive: true });
16604
+ const tmp = `${path}.tmp`;
16605
+ writeFileSync6(tmp, JSON.stringify(all));
16606
+ renameSync4(tmp, path);
16607
+ }
16608
+ function getSyncedMtimes(server) {
16609
+ const data = load();
16610
+ const out = /* @__PURE__ */ new Map();
16611
+ for (const [id, entry] of Object.entries(data[server] || {})) out.set(id, toRow(entry).m);
16612
+ return out;
16613
+ }
16614
+ function getSyncedRows(server) {
16615
+ const data = load();
16616
+ const out = /* @__PURE__ */ new Map();
16617
+ for (const [id, entry] of Object.entries(data[server] || {})) out.set(id, toRow(entry));
16618
+ return out;
16619
+ }
16620
+ function getLedgerData(server) {
16621
+ const data = load();
16622
+ return data[server] || {};
16623
+ }
16624
+ function persistLedgerData(server, serverData) {
16625
+ const data = load();
16626
+ data[server] = serverData;
16627
+ persist(data);
16628
+ flushLedger();
16629
+ }
16630
+ function unackedCursorAttemptCount() {
16631
+ return unackedCursorAttempts;
16632
+ }
16633
+ function _resetUnackedCursorCount() {
16634
+ unackedCursorAttempts = 0;
16635
+ }
16636
+ function markSynced(server, rows) {
16637
+ if (rows.length === 0) return;
16638
+ const data = load();
16639
+ const forServer = data[server] || (data[server] = {});
16640
+ for (const r of rows) {
16641
+ const prev = toRow(forServer[r.id]);
16642
+ const prevF = prev?.f;
16643
+ const prevOS = prev && (prev.o !== void 0 || prev.s !== void 0) ? { o: prev.o, s: prev.s } : {};
16644
+ const cursorFromCaller = r.acked === true;
16645
+ if (!cursorFromCaller && (r.offset !== void 0 || r.size !== void 0)) {
16646
+ unackedCursorAttempts++;
16647
+ }
16648
+ const o = (cursorFromCaller ? r.offset : void 0) ?? prevOS.o ?? 0;
16649
+ const s = (cursorFromCaller ? r.size : void 0) ?? prevOS.s ?? 0;
16650
+ const ev = extractorVersionForId(r.id);
16651
+ const base4 = prevF ? { m: Math.floor(r.mtime), v: ev, f: prevF } : { m: Math.floor(r.mtime), v: ev };
16652
+ if (o > 0 || s > 0) {
16653
+ base4.o = o;
16654
+ base4.s = s;
16655
+ }
16656
+ if (r.hash !== void 0) base4.h = r.hash;
16657
+ const completesChunked = cursorFromCaller && r.chunkFinal === true && prev?.k === 1;
16658
+ if (cursorFromCaller && (r.full || completesChunked) && o > 0) base4.F = o;
16659
+ else if (prev?.F !== void 0) base4.F = prev.F;
16660
+ if (cursorFromCaller && r.chunkedHead) base4.k = 1;
16661
+ else if (prev?.k && !completesChunked && !(cursorFromCaller && r.full)) base4.k = 1;
16662
+ const layout = cursorFromCaller ? r.layout : prev?.L;
16663
+ if (layout) base4.L = layout;
16664
+ forServer[r.id] = base4;
16665
+ }
16666
+ persist(data);
16667
+ }
16668
+ function fieldNeedsScan(row, field, mtime, force = false) {
16669
+ if (force) return true;
16670
+ const cov = row?.f?.[field.name];
16671
+ if (!cov) return true;
16672
+ if (cov.v < field.version) return true;
16673
+ if (field.mtimeSensitive && (cov.m ?? 0) < Math.floor(mtime)) return true;
16674
+ return false;
16675
+ }
16676
+ function markFieldCoverage(server, field, rows) {
16677
+ if (rows.length === 0) return;
16678
+ const data = load();
16679
+ const forServer = data[server] || (data[server] = {});
16680
+ for (const r of rows) {
16681
+ const row = toRow(forServer[r.id]) ?? { m: 0, v: 0 };
16682
+ const f = row.f ? { ...row.f } : {};
16683
+ f[field.name] = { v: field.version, p: r.present ? 1 : 0, m: Math.floor(r.mtime) };
16684
+ forServer[r.id] = { ...row, f };
16685
+ }
16686
+ persist(data);
16687
+ }
16688
+ function loadReconcile() {
16689
+ if (reconcileCache) return reconcileCache;
16690
+ try {
16691
+ const parsed = JSON.parse(readFileSync21(reconcilePath(), "utf-8"));
16692
+ reconcileCache = parsed && typeof parsed === "object" ? parsed : {};
16693
+ } catch {
16694
+ reconcileCache = {};
16695
+ }
16696
+ return reconcileCache;
16697
+ }
16698
+ function persistReconcile(data) {
16699
+ const path = reconcilePath();
16700
+ mkdirSync6(dirname15(path), { recursive: true });
16701
+ const tmp = `${path}.tmp`;
16702
+ writeFileSync6(tmp, JSON.stringify(data));
16703
+ renameSync4(tmp, path);
16704
+ }
16705
+ function stateFor(server) {
16706
+ const data = loadReconcile();
16707
+ return data[server] || (data[server] = { reconciled: {}, force: {} });
16708
+ }
16709
+ function fieldNeedsFullPass(server, field) {
16710
+ const st = stateFor(server);
16711
+ return st.force[field.name] === true || (st.reconciled[field.name] ?? 0) < field.version;
16712
+ }
16713
+ function markFieldFullPassDone(server, field) {
16714
+ const data = loadReconcile();
16715
+ const st = data[server] || (data[server] = { reconciled: {}, force: {} });
16716
+ st.reconciled[field.name] = field.version;
16717
+ delete st.force[field.name];
16718
+ persistReconcile(data);
16719
+ }
16720
+ function forceFieldRescan(fieldName, server) {
16721
+ const data = loadReconcile();
16722
+ const servers = server ? [server] : Object.keys(data);
16723
+ if (servers.length === 0 && server) servers.push(server);
16724
+ for (const s of servers) {
16725
+ const st = data[s] || (data[s] = { reconciled: {}, force: {} });
16726
+ st.force[fieldName] = true;
16727
+ }
16728
+ persistReconcile(data);
16729
+ }
16730
+ function _resetLedgerCacheForTests() {
16731
+ flushLedger();
16732
+ cache2 = null;
16733
+ base = /* @__PURE__ */ new Map();
16734
+ diskStamp = null;
16735
+ reconcileCache = null;
16736
+ }
16737
+ function forgetFullCoverage(server, sessionId) {
16738
+ const data = load();
16739
+ const row = data[server]?.[sessionId];
16740
+ if (!row || typeof row !== "object") return;
16741
+ delete row.F;
16742
+ delete row.h;
16743
+ persist(data);
16744
+ }
16745
+ function markFullResync(server, sessionId) {
16746
+ const data = load();
16747
+ const forServer = data[server];
16748
+ if (!forServer) return;
16749
+ if (!(sessionId in forServer)) return;
16750
+ delete forServer[sessionId];
16751
+ persist(data);
16752
+ }
16753
+ function forgetSessions(server, sessionIds) {
16754
+ const data = load();
16755
+ const forServer = data[server];
16756
+ if (!forServer) return 0;
16757
+ let removed = 0;
16758
+ for (const id of sessionIds) {
16759
+ if (id in forServer) {
16760
+ delete forServer[id];
16761
+ removed++;
16762
+ }
16763
+ }
16764
+ if (removed > 0) {
16765
+ persist(data);
16766
+ flushLedger();
16767
+ }
16768
+ return removed;
16769
+ }
16770
+ function fullCoveredOffset(row) {
16771
+ if (row.F !== void 0) return row.F;
16772
+ return row.h ? row.s ?? 0 : 0;
16773
+ }
16774
+ function syncMode(row, mtime, fileSize, extractorVersion, isAppendOnly, nowMs = Date.now()) {
16775
+ if (!row) return "full";
16776
+ if (row.v < extractorVersion) return "full";
16777
+ const offset = row.o ?? 0;
16778
+ if (isAppendOnly && offset > 0 && fileSize > 0 && fileSize < offset) return "full";
16779
+ if (process.env.CHAT_RECALL_TAIL_APPEND !== "0" && isAppendOnly && fileSize > 0 && offset > 0 && fileSize > (row.s ?? 0)) {
16780
+ return "append";
16781
+ }
16782
+ if (isAppendOnly && offset > 0 && fileSize > 0 && fileSize === (row.s ?? 0) && !row.k && fullCoveredOffset(row) < offset && nowMs - Math.floor(mtime) >= SETTLE_QUIET_MS) {
16783
+ return "full";
16784
+ }
16785
+ if (row.m >= Math.floor(mtime)) return "skip";
16786
+ return "full";
16787
+ }
16788
+ var ledgerPath, cache2, base, diskStamp, rowKey, LEDGER_FLUSH_MS, pendingWrite, flushTimer, itemVersionsPath, itemVersionsCache, inventoryPath, unackedCursorAttempts, reconcilePath, reconcileCache, SETTLE_QUIET_MS;
16789
+ var init_sync_ledger = __esm({
16790
+ "src/sync-ledger.ts"() {
16791
+ "use strict";
16792
+ init_paths();
16793
+ init_extractor_version();
16794
+ ledgerPath = () => join26(getDataDir(), "sync-ledger.json");
16795
+ cache2 = null;
16796
+ base = /* @__PURE__ */ new Map();
16797
+ diskStamp = null;
16798
+ rowKey = (server, id) => `${server}\0${id}`;
16799
+ LEDGER_FLUSH_MS = 2e3;
16800
+ pendingWrite = false;
16801
+ flushTimer = null;
16802
+ itemVersionsPath = () => join26(getDataDir(), "item-versions.json");
16803
+ itemVersionsCache = null;
16804
+ inventoryPath = () => join26(getDataDir(), "toolkit-inventory.json");
16805
+ unackedCursorAttempts = 0;
16806
+ reconcilePath = () => join26(getDataDir(), "sync-field-reconcile.json");
16807
+ reconcileCache = null;
16808
+ SETTLE_QUIET_MS = 2 * 60 * 60 * 1e3;
16809
+ }
16810
+ });
16811
+
16812
+ // src/ledger-reconcile.ts
16813
+ var ledger_reconcile_exports = {};
16814
+ __export(ledger_reconcile_exports, {
16815
+ RECONCILE_INTERVAL_MS: () => RECONCILE_INTERVAL_MS,
16816
+ RECONCILE_MAX_PER_RUN: () => RECONCILE_MAX_PER_RUN,
16817
+ _resetReconcileClockForTests: () => _resetReconcileClockForTests,
16818
+ fetchServerSessions: () => fetchServerSessions,
16819
+ planReconcile: () => planReconcile,
16820
+ reconcileLedger: () => reconcileLedger,
16821
+ reconcileLedgerIfDue: () => reconcileLedgerIfDue,
16822
+ reconcileMode: () => reconcileMode
16823
+ });
16824
+ function reconcileMode(env = process.env) {
16825
+ const raw = env.CHAT_RECALL_LEDGER_RECONCILE?.trim().toLowerCase();
16826
+ if (raw === "off" || raw === "report" || raw === "act") return raw;
16827
+ return "act";
16828
+ }
16829
+ function planReconcile(opts) {
16830
+ const limit = opts.limit ?? RECONCILE_MAX_PER_RUN;
16831
+ const missing = [];
16832
+ for (const [id, row] of opts.ledger) {
16833
+ if (opts.serverIds.has(id) || opts.deletedIds?.has(id)) continue;
16834
+ missing.push([id, row.m]);
16835
+ }
16836
+ missing.sort((a, b) => b[1] - a[1]);
16837
+ const ids = missing.map(([id]) => id);
16838
+ return { missing: ids, queued: ids.slice(0, limit) };
16839
+ }
16840
+ async function fetchServerSessions(server, token, fetcher = fetchWithTimeout) {
16841
+ const headers = {};
16842
+ if (token) headers.authorization = `Bearer ${token}`;
16843
+ const res = await fetcher(`${server}/api/status/sessions`, { headers }, 12e4);
16844
+ if (!res.ok) throw new Error(`HTTP ${res.status} from /api/status/sessions`);
16845
+ const body2 = await res.json();
16846
+ if (!Array.isArray(body2.sessions)) throw new Error("/api/status/sessions did not return a session list");
16847
+ const ids = /* @__PURE__ */ new Set();
16848
+ for (const s of body2.sessions) if (typeof s.id === "string") ids.add(s.id);
16849
+ for (const e of body2.empty ?? []) if (typeof e === "string") ids.delete(e);
16850
+ const deleted = /* @__PURE__ */ new Set();
16851
+ for (const d of body2.deleted ?? []) if (typeof d === "string") deleted.add(d);
16852
+ return { ids, deleted };
16853
+ }
16854
+ async function reconcileLedger(server, token, mode = reconcileMode(), deps = {}) {
16855
+ const log6 = deps.log ?? ((l) => console.error(l));
16856
+ if (mode === "off") return { mode, missing: 0, cleared: 0, first: [] };
16857
+ const list = await (deps.listServer ?? fetchServerSessions)(server, token);
16858
+ const plan = planReconcile({
16859
+ ledger: (deps.ledgerRows ?? getSyncedRows)(server),
16860
+ serverIds: list.ids,
16861
+ deletedIds: list.deleted
16862
+ });
16863
+ const first = plan.queued.slice(0, 5);
16864
+ if (plan.missing.length === 0) return { mode, missing: 0, cleared: 0, first };
16865
+ log6(`[sync] the server lacks ${plan.missing.length} session(s) that the ledger marks as synced (mode ${mode}); first ids: ${first.join(", ")}`);
16866
+ if (mode === "report") return { mode, missing: plan.missing.length, cleared: 0, first };
16867
+ (deps.forget ?? forgetSessions)(server, plan.queued);
16868
+ return { mode, missing: plan.missing.length, cleared: plan.queued.length, first };
16869
+ }
16870
+ async function reconcileLedgerIfDue(server, token, now = Date.now(), deps = {}) {
16871
+ const last = lastRunAt.get(server);
16872
+ if (last !== void 0 && now - last < RECONCILE_INTERVAL_MS) return null;
16873
+ lastRunAt.set(server, now);
16874
+ try {
16875
+ return await reconcileLedger(server, token, reconcileMode(), deps);
16876
+ } catch (err) {
16877
+ lastRunAt.delete(server);
16878
+ (deps.log ?? ((l) => console.error(l)))(`[sync] ledger check against the server failed (the walk goes on): ${err instanceof Error ? err.message : err}`);
16879
+ return null;
16880
+ }
16881
+ }
16882
+ function _resetReconcileClockForTests() {
16883
+ lastRunAt.clear();
16884
+ }
16885
+ var RECONCILE_MAX_PER_RUN, RECONCILE_INTERVAL_MS, lastRunAt;
16886
+ var init_ledger_reconcile = __esm({
16887
+ "src/ledger-reconcile.ts"() {
16888
+ "use strict";
16889
+ init_http();
16890
+ init_sync_ledger();
16891
+ RECONCILE_MAX_PER_RUN = 2e3;
16892
+ RECONCILE_INTERVAL_MS = 24 * 60 * 6e4;
16893
+ lastRunAt = /* @__PURE__ */ new Map();
16195
16894
  }
16196
16895
  });
16197
16896
 
@@ -16343,7 +17042,7 @@ __export(transcript_exports, {
16343
17042
  writeShadowContainer: () => writeShadowContainer,
16344
17043
  writeTranscriptEnvelope: () => writeTranscriptEnvelope
16345
17044
  });
16346
- import { statSync as statSync20 } from "fs";
17045
+ import { statSync as statSync21 } from "fs";
16347
17046
  async function parseTranscript(sessionId) {
16348
17047
  const tool = detectTool(sessionId);
16349
17048
  if (tool === "claude") {
@@ -16411,7 +17110,7 @@ async function parseTranscript(sessionId) {
16411
17110
  }
16412
17111
  function safeMtime(path) {
16413
17112
  try {
16414
- return statSync20(path).mtimeMs;
17113
+ return statSync21(path).mtimeMs;
16415
17114
  } catch {
16416
17115
  return 0;
16417
17116
  }
@@ -16914,17 +17613,17 @@ var init_entity_extractor = __esm({
16914
17613
  });
16915
17614
 
16916
17615
  // ../engine/dist/core/source-policy.js
16917
- import { statSync as statSync21 } from "fs";
17616
+ import { statSync as statSync22 } from "fs";
16918
17617
  function settings() {
16919
17618
  let mtimeMs = -1;
16920
17619
  try {
16921
- mtimeMs = statSync21(settingsFilePath()).mtimeMs;
17620
+ mtimeMs = statSync22(settingsFilePath()).mtimeMs;
16922
17621
  } catch {
16923
17622
  }
16924
- if (cache2 && cache2.mtimeMs === mtimeMs)
16925
- return cache2.settings;
17623
+ if (cache3 && cache3.mtimeMs === mtimeMs)
17624
+ return cache3.settings;
16926
17625
  const s = loadSettings();
16927
- cache2 = { mtimeMs, settings: s };
17626
+ cache3 = { mtimeMs, settings: s };
16928
17627
  return s;
16929
17628
  }
16930
17629
  function toolOf(item) {
@@ -17005,13 +17704,13 @@ function isItemAllowed(item) {
17005
17704
  return false;
17006
17705
  return true;
17007
17706
  }
17008
- var cache2, TOOLS;
17707
+ var cache3, TOOLS;
17009
17708
  var init_source_policy = __esm({
17010
17709
  "../engine/dist/core/source-policy.js"() {
17011
17710
  "use strict";
17012
17711
  init_project_path_match();
17013
17712
  init_settings();
17014
- cache2 = null;
17713
+ cache3 = null;
17015
17714
  TOOLS = ["claude", "opencode", "codex", "agy", "cursor", "hermes", "pi"];
17016
17715
  }
17017
17716
  });
@@ -17109,7 +17808,7 @@ var init_source_registry = __esm({
17109
17808
  // ../engine/dist/core/utils.js
17110
17809
  import { existsSync as existsSync22, readdirSync as readdirSync16 } from "fs";
17111
17810
  import { homedir as homedir7 } from "os";
17112
- import { join as join26 } from "path";
17811
+ import { join as join27 } from "path";
17113
17812
  function splitByHeaders(markdown) {
17114
17813
  const lines = markdown.split("\n");
17115
17814
  const sections = [];
@@ -17152,17 +17851,17 @@ function getClaudeDirs() {
17152
17851
  for (const d of process.env.CLAUDE_DIRS.split(",")) {
17153
17852
  const trimmed = d.trim();
17154
17853
  if (trimmed) {
17155
- add(trimmed.startsWith("~/") ? join26(home, trimmed.slice(2)) : trimmed);
17854
+ add(trimmed.startsWith("~/") ? join27(home, trimmed.slice(2)) : trimmed);
17156
17855
  }
17157
17856
  }
17158
17857
  }
17159
- add(join26(home, ".claude"));
17858
+ add(join27(home, ".claude"));
17160
17859
  try {
17161
17860
  const entries = readdirSync16(home, { withFileTypes: true });
17162
17861
  for (const entry of entries) {
17163
17862
  if (entry.isDirectory() && entry.name.startsWith(".claude-") && entry.name !== ".claude-code") {
17164
- const candidate = join26(home, entry.name);
17165
- if (existsSync22(join26(candidate, "projects"))) {
17863
+ const candidate = join27(home, entry.name);
17864
+ if (existsSync22(join27(candidate, "projects"))) {
17166
17865
  add(candidate);
17167
17866
  }
17168
17867
  }
@@ -17174,12 +17873,12 @@ function getClaudeDirs() {
17174
17873
  function discoverSubdirs(subdir) {
17175
17874
  const result = [];
17176
17875
  for (const claudeDir of getClaudeDirs()) {
17177
- const path = join26(claudeDir, subdir);
17876
+ const path = join27(claudeDir, subdir);
17178
17877
  if (existsSync22(path)) {
17179
17878
  result.push(path);
17180
17879
  }
17181
17880
  }
17182
- return result.length > 0 ? result : [join26(homedir7(), ".claude", subdir)];
17881
+ return result.length > 0 ? result : [join27(homedir7(), ".claude", subdir)];
17183
17882
  }
17184
17883
  var init_utils = __esm({
17185
17884
  "../engine/dist/core/utils.js"() {
@@ -17188,9 +17887,9 @@ var init_utils = __esm({
17188
17887
  });
17189
17888
 
17190
17889
  // ../engine/dist/parsers/plan-source.js
17191
- import { existsSync as existsSync23, readdirSync as readdirSync17, readFileSync as readFileSync20, statSync as statSync22 } from "fs";
17890
+ import { existsSync as existsSync23, readdirSync as readdirSync17, readFileSync as readFileSync22, statSync as statSync23 } from "fs";
17192
17891
  import { homedir as homedir8 } from "os";
17193
- import { join as join27, basename as basename14 } from "path";
17892
+ import { join as join28, basename as basename14 } from "path";
17194
17893
  function parseFrontmatter(content) {
17195
17894
  if (!content.startsWith("---"))
17196
17895
  return { body: content };
@@ -17285,12 +17984,12 @@ var init_plan_source = __esm({
17285
17984
  if (seenClaude.has(file))
17286
17985
  continue;
17287
17986
  seenClaude.add(file);
17288
- const filePath = join27(plansDir, file);
17987
+ const filePath = join28(plansDir, file);
17289
17988
  try {
17290
- const stat3 = statSync22(filePath);
17989
+ const stat3 = statSync23(filePath);
17291
17990
  const planName = basename14(file, ".md");
17292
17991
  const isAgentPlan = planName.includes("-agent-");
17293
- const content = readFileSync20(filePath, "utf-8");
17992
+ const content = readFileSync22(filePath, "utf-8");
17294
17993
  const fm = parseFrontmatter(content);
17295
17994
  const body2 = fm.body;
17296
17995
  const firstLine = body2.split("\n").find((l) => l.trim())?.replace(/^#+\s*/, "").trim() || planName;
@@ -17329,10 +18028,10 @@ var init_plan_source = __esm({
17329
18028
  return;
17330
18029
  }
17331
18030
  for (const file of files) {
17332
- const filePath = join27(plansDir, file);
18031
+ const filePath = join28(plansDir, file);
17333
18032
  try {
17334
- const stat3 = statSync22(filePath);
17335
- const content = readFileSync20(filePath, "utf-8");
18033
+ const stat3 = statSync23(filePath);
18034
+ const content = readFileSync22(filePath, "utf-8");
17336
18035
  const firstLine = content.split("\n").find((l) => l.trim())?.replace(/^#+\s*/, "").trim() || file;
17337
18036
  const planName = `${opencodeBackend.idPrefix}plan_${basename14(file, ".md")}`;
17338
18037
  const projectPath = this.extractProjectPath(content);
@@ -17360,7 +18059,7 @@ var init_plan_source = __esm({
17360
18059
  for (const match of content.matchAll(fullPathPattern)) {
17361
18060
  let path = (match[1] || "").trim();
17362
18061
  if (path.startsWith("~/")) {
17363
- path = join27(homedir8(), path.slice(2));
18062
+ path = join28(homedir8(), path.slice(2));
17364
18063
  }
17365
18064
  for (const projectDir of knownProjects) {
17366
18065
  if (path.startsWith(projectDir)) {
@@ -17409,7 +18108,7 @@ var init_plan_source = __esm({
17409
18108
  async parse(item) {
17410
18109
  if (!existsSync23(item.filePath))
17411
18110
  return [];
17412
- const content = readFileSync20(item.filePath, "utf-8");
18111
+ const content = readFileSync22(item.filePath, "utf-8");
17413
18112
  const chunks = [];
17414
18113
  const { body: body2 } = parseFrontmatter(content);
17415
18114
  const sections = splitByHeaders(body2);
@@ -17445,9 +18144,9 @@ var init_plan_source = __esm({
17445
18144
  const map = /* @__PURE__ */ new Map();
17446
18145
  const root = claudeBackend.projectsDir();
17447
18146
  for (const proj of safeReaddir(root)) {
17448
- const projPath = join27(root, proj);
18147
+ const projPath = join28(root, proj);
17449
18148
  for (const sessionEntry of safeReaddir(projPath)) {
17450
- const subDir = join27(projPath, sessionEntry, "subagents");
18149
+ const subDir = join28(projPath, sessionEntry, "subagents");
17451
18150
  if (!existsSync23(subDir))
17452
18151
  continue;
17453
18152
  for (const f of safeReaddir(subDir)) {
@@ -17522,7 +18221,7 @@ var init_plan_source = __esm({
17522
18221
  return links;
17523
18222
  }
17524
18223
  async *discoverAgyPlans() {
17525
- const brainDir = join27(agyBackend.homeDir(), "brain");
18224
+ const brainDir = join28(agyBackend.homeDir(), "brain");
17526
18225
  if (!existsSync23(brainDir))
17527
18226
  return;
17528
18227
  let sessionDirs;
@@ -17532,9 +18231,9 @@ var init_plan_source = __esm({
17532
18231
  return;
17533
18232
  }
17534
18233
  for (const rawId of sessionDirs) {
17535
- const sessionPath = join27(brainDir, rawId);
18234
+ const sessionPath = join28(brainDir, rawId);
17536
18235
  try {
17537
- if (!statSync22(sessionPath).isDirectory())
18236
+ if (!statSync23(sessionPath).isDirectory())
17538
18237
  continue;
17539
18238
  } catch {
17540
18239
  continue;
@@ -17546,10 +18245,10 @@ var init_plan_source = __esm({
17546
18245
  continue;
17547
18246
  }
17548
18247
  for (const file of files) {
17549
- const filePath = join27(sessionPath, file);
18248
+ const filePath = join28(sessionPath, file);
17550
18249
  try {
17551
- const stat3 = statSync22(filePath);
17552
- const content = readFileSync20(filePath, "utf-8");
18250
+ const stat3 = statSync23(filePath);
18251
+ const content = readFileSync22(filePath, "utf-8");
17553
18252
  const firstLine = content.split("\n").find((l) => l.trim())?.replace(/^#+\s*/, "").trim() || file;
17554
18253
  const sessionLoc = agyBackend.findSession(rawId);
17555
18254
  const projectPath = sessionLoc?.projectPath || this.extractProjectPath(content);
@@ -17578,8 +18277,8 @@ var init_plan_source = __esm({
17578
18277
  });
17579
18278
 
17580
18279
  // ../engine/dist/parsers/task-source.js
17581
- import { existsSync as existsSync24, readdirSync as readdirSync18, readFileSync as readFileSync21, statSync as statSync23 } from "fs";
17582
- import { join as join28 } from "path";
18280
+ import { existsSync as existsSync24, readdirSync as readdirSync18, readFileSync as readFileSync23, statSync as statSync24 } from "fs";
18281
+ import { join as join29 } from "path";
17583
18282
  var MAX_CHUNK_CHARS2, TaskSource;
17584
18283
  var init_task_source = __esm({
17585
18284
  "../engine/dist/parsers/task-source.js"() {
@@ -17617,10 +18316,10 @@ var init_task_source = __esm({
17617
18316
  return;
17618
18317
  }
17619
18318
  for (const file of files) {
17620
- const filePath = join28(todosDir, file);
18319
+ const filePath = join29(todosDir, file);
17621
18320
  let stat3;
17622
18321
  try {
17623
- stat3 = statSync23(filePath);
18322
+ stat3 = statSync24(filePath);
17624
18323
  } catch {
17625
18324
  continue;
17626
18325
  }
@@ -17628,7 +18327,7 @@ var init_task_source = __esm({
17628
18327
  continue;
17629
18328
  let parsed;
17630
18329
  try {
17631
- const raw = readFileSync21(filePath, "utf-8");
18330
+ const raw = readFileSync23(filePath, "utf-8");
17632
18331
  parsed = JSON.parse(raw);
17633
18332
  if (!Array.isArray(parsed) || parsed.length === 0)
17634
18333
  continue;
@@ -17666,9 +18365,9 @@ var init_task_source = __esm({
17666
18365
  if (!entry.isDirectory())
17667
18366
  continue;
17668
18367
  const sessionUuid = entry.name;
17669
- const taskDir = join28(tasksDir, sessionUuid);
18368
+ const taskDir = join29(tasksDir, sessionUuid);
17670
18369
  try {
17671
- const stat3 = statSync23(taskDir);
18370
+ const stat3 = statSync24(taskDir);
17672
18371
  const taskFiles = readdirSync18(taskDir).filter((f) => f.endsWith(".json"));
17673
18372
  if (taskFiles.length === 0)
17674
18373
  continue;
@@ -17741,7 +18440,7 @@ ${task.description}`.slice(0, MAX_CHUNK_CHARS2);
17741
18440
  text,
17742
18441
  chunkType: "task_detail",
17743
18442
  projectPath: item.projectPath,
17744
- filePath: join28(taskDir, `${task.id}.json`),
18443
+ filePath: join29(taskDir, `${task.id}.json`),
17745
18444
  mtime: item.mtime
17746
18445
  });
17747
18446
  }
@@ -17766,7 +18465,7 @@ ${task.description}`.slice(0, MAX_CHUNK_CHARS2);
17766
18465
  return [];
17767
18466
  let parsed;
17768
18467
  try {
17769
- parsed = JSON.parse(readFileSync21(item.filePath, "utf-8"));
18468
+ parsed = JSON.parse(readFileSync23(item.filePath, "utf-8"));
17770
18469
  } catch {
17771
18470
  return [];
17772
18471
  }
@@ -17798,7 +18497,7 @@ ${task.description}`.slice(0, MAX_CHUNK_CHARS2);
17798
18497
  });
17799
18498
  for (const file of sorted) {
17800
18499
  try {
17801
- const content = readFileSync21(join28(taskDir, file), "utf-8");
18500
+ const content = readFileSync23(join29(taskDir, file), "utf-8");
17802
18501
  const task = JSON.parse(content);
17803
18502
  if (task.subject) {
17804
18503
  tasks2.push(task);
@@ -17814,9 +18513,9 @@ ${task.description}`.slice(0, MAX_CHUNK_CHARS2);
17814
18513
  });
17815
18514
 
17816
18515
  // ../engine/dist/parsers/claude-md-source.js
17817
- import { existsSync as existsSync25, readFileSync as readFileSync22, readdirSync as readdirSync19, statSync as statSync24 } from "fs";
18516
+ import { existsSync as existsSync25, readFileSync as readFileSync24, readdirSync as readdirSync19, statSync as statSync25 } from "fs";
17818
18517
  import { homedir as homedir9 } from "os";
17819
- import { join as join29, basename as basename15, dirname as dirname15 } from "path";
18518
+ import { join as join30, basename as basename15, dirname as dirname16 } from "path";
17820
18519
  import { createHash as createHash9 } from "crypto";
17821
18520
  function discoverProjectDirs(claudeDir) {
17822
18521
  const dirs = [];
@@ -17842,7 +18541,7 @@ function discoverProjectDirs(claudeDir) {
17842
18541
  }
17843
18542
  };
17844
18543
  if (claudeDir) {
17845
- scanProjectsDir(join29(claudeDir, "projects"));
18544
+ scanProjectsDir(join30(claudeDir, "projects"));
17846
18545
  return dirs;
17847
18546
  }
17848
18547
  const home = homedir9();
@@ -17850,7 +18549,7 @@ function discoverProjectDirs(claudeDir) {
17850
18549
  try {
17851
18550
  for (const entry of readdirSync19(home, { withFileTypes: true })) {
17852
18551
  if (entry.isDirectory() && entry.name.startsWith(".claude-") && entry.name !== ".claude-code") {
17853
- scanProjectsDir(join29(home, entry.name, "projects"));
18552
+ scanProjectsDir(join30(home, entry.name, "projects"));
17854
18553
  }
17855
18554
  }
17856
18555
  } catch {
@@ -17858,7 +18557,7 @@ function discoverProjectDirs(claudeDir) {
17858
18557
  const gemProjects = agyBackend.sharedProjectsJson();
17859
18558
  if (existsSync25(gemProjects)) {
17860
18559
  try {
17861
- const data = JSON.parse(readFileSync22(gemProjects, "utf-8"));
18560
+ const data = JSON.parse(readFileSync24(gemProjects, "utf-8"));
17862
18561
  for (const path of Object.keys(data.projects || {}))
17863
18562
  addProject(path);
17864
18563
  } catch {
@@ -17914,7 +18613,7 @@ var init_claude_md_source = __esm({
17914
18613
  const seen = /* @__PURE__ */ new Set();
17915
18614
  const seenKey = (path, tool) => `${tool}:${path}`;
17916
18615
  for (const note of NOTE_FILES) {
17917
- const p = join29(homedir9(), note.filename);
18616
+ const p = join30(homedir9(), note.filename);
17918
18617
  const key2 = seenKey(p, note.tool);
17919
18618
  if (existsSync25(p) && !seen.has(key2)) {
17920
18619
  seen.add(key2);
@@ -17926,7 +18625,7 @@ var init_claude_md_source = __esm({
17926
18625
  const projectDirs = discoverProjectDirs(this.claudeDir);
17927
18626
  for (const projectDir of projectDirs) {
17928
18627
  for (const note of NOTE_FILES) {
17929
- const p = join29(projectDir, note.filename);
18628
+ const p = join30(projectDir, note.filename);
17930
18629
  const key2 = seenKey(p, note.tool);
17931
18630
  if (existsSync25(p) && !seen.has(key2)) {
17932
18631
  seen.add(key2);
@@ -17940,7 +18639,7 @@ var init_claude_md_source = __esm({
17940
18639
  if (!existsSync25(searchDir))
17941
18640
  continue;
17942
18641
  for (const note of NOTE_FILES) {
17943
- const directPath = join29(searchDir, note.filename);
18642
+ const directPath = join30(searchDir, note.filename);
17944
18643
  const key2 = seenKey(directPath, note.tool);
17945
18644
  if (existsSync25(directPath) && !seen.has(key2)) {
17946
18645
  seen.add(key2);
@@ -17955,7 +18654,7 @@ var init_claude_md_source = __esm({
17955
18654
  if (!entry.isDirectory())
17956
18655
  continue;
17957
18656
  for (const note of NOTE_FILES) {
17958
- const p = join29(searchDir, entry.name, note.filename);
18657
+ const p = join30(searchDir, entry.name, note.filename);
17959
18658
  const key2 = seenKey(p, note.tool);
17960
18659
  if (existsSync25(p) && !seen.has(key2)) {
17961
18660
  seen.add(key2);
@@ -17973,7 +18672,7 @@ var init_claude_md_source = __esm({
17973
18672
  async parse(item) {
17974
18673
  if (!existsSync25(item.filePath))
17975
18674
  return [];
17976
- const content = readFileSync22(item.filePath, "utf-8");
18675
+ const content = readFileSync24(item.filePath, "utf-8");
17977
18676
  const chunks = [];
17978
18677
  const sections = splitByHeaders(content);
17979
18678
  for (let i = 0; i < sections.length; i++) {
@@ -18011,11 +18710,11 @@ var init_claude_md_source = __esm({
18011
18710
  }
18012
18711
  fileToItem(filePath, filename, tool) {
18013
18712
  try {
18014
- const stat3 = statSync24(filePath);
18015
- const projectDir = dirname15(filePath);
18713
+ const stat3 = statSync25(filePath);
18714
+ const projectDir = dirname16(filePath);
18016
18715
  const projectName = basename15(projectDir);
18017
18716
  const projectPath = projectDir;
18018
- const content = readFileSync22(filePath, "utf-8");
18717
+ const content = readFileSync24(filePath, "utf-8");
18019
18718
  const firstLine = content.split("\n").find((l) => l.trim() && !l.startsWith("#"))?.trim()?.slice(0, 200) || `${filename} for ${projectName}`;
18020
18719
  const id = tool === "claude" ? projectName : `${projectName}_${tool}`;
18021
18720
  return {
@@ -18040,9 +18739,9 @@ var init_claude_md_source = __esm({
18040
18739
  });
18041
18740
 
18042
18741
  // ../engine/dist/parsers/agent-memory-source.js
18043
- import { existsSync as existsSync26, readFileSync as readFileSync23, readdirSync as readdirSync20, statSync as statSync25 } from "fs";
18742
+ import { existsSync as existsSync26, readFileSync as readFileSync25, readdirSync as readdirSync20, statSync as statSync26 } from "fs";
18044
18743
  import { homedir as homedir10 } from "os";
18045
- import { join as join30, basename as basename16 } from "path";
18744
+ import { join as join31, basename as basename16 } from "path";
18046
18745
  function parseFrontmatter2(content) {
18047
18746
  const fm = {};
18048
18747
  let body2 = content;
@@ -18084,7 +18783,7 @@ function discoverMemoryDirs() {
18084
18783
  try {
18085
18784
  for (const entry of readdirSync20(home, { withFileTypes: true })) {
18086
18785
  if (entry.isDirectory() && entry.name.startsWith(".claude-") && entry.name !== ".claude-code") {
18087
- claudeRoots.push(join30(home, entry.name, "projects"));
18786
+ claudeRoots.push(join31(home, entry.name, "projects"));
18088
18787
  }
18089
18788
  }
18090
18789
  } catch {
@@ -18096,7 +18795,7 @@ function discoverMemoryDirs() {
18096
18795
  for (const entry of readdirSync20(projectsDir, { withFileTypes: true })) {
18097
18796
  if (!entry.isDirectory() || entry.name.startsWith("."))
18098
18797
  continue;
18099
- add(join30(projectsDir, entry.name, "memory"), entry.name);
18798
+ add(join31(projectsDir, entry.name, "memory"), entry.name);
18100
18799
  }
18101
18800
  } catch {
18102
18801
  }
@@ -18125,7 +18824,7 @@ var init_agent_memory_source = __esm({
18125
18824
  for (const entry of readdirSync20(memoryDir, { withFileTypes: true })) {
18126
18825
  if (!entry.isFile() || !entry.name.endsWith(".md"))
18127
18826
  continue;
18128
- const filePath = join30(memoryDir, entry.name);
18827
+ const filePath = join31(memoryDir, entry.name);
18129
18828
  if (seen.has(filePath))
18130
18829
  continue;
18131
18830
  seen.add(filePath);
@@ -18141,7 +18840,7 @@ var init_agent_memory_source = __esm({
18141
18840
  async parse(item) {
18142
18841
  if (!existsSync26(item.filePath))
18143
18842
  return [];
18144
- const content = readFileSync23(item.filePath, "utf-8");
18843
+ const content = readFileSync25(item.filePath, "utf-8");
18145
18844
  const { body: body2 } = parseFrontmatter2(content);
18146
18845
  const chunks = [];
18147
18846
  const sections = splitByHeaders(body2);
@@ -18193,8 +18892,8 @@ var init_agent_memory_source = __esm({
18193
18892
  }
18194
18893
  fileToItem(filePath, filename, projectPath, _projectHash) {
18195
18894
  try {
18196
- const stat3 = statSync25(filePath);
18197
- const content = readFileSync23(filePath, "utf-8");
18895
+ const stat3 = statSync26(filePath);
18896
+ const content = readFileSync25(filePath, "utf-8");
18198
18897
  const { fm } = parseFrontmatter2(content);
18199
18898
  const stem = filename.replace(/\.md$/, "");
18200
18899
  const idBase = fm.name || stem;
@@ -18225,11 +18924,11 @@ var init_agent_memory_source = __esm({
18225
18924
  });
18226
18925
 
18227
18926
  // ../engine/dist/parsers/history-source.js
18228
- import { existsSync as existsSync27, readdirSync as readdirSync21, statSync as statSync26 } from "fs";
18927
+ import { existsSync as existsSync27, readdirSync as readdirSync21, statSync as statSync27 } from "fs";
18229
18928
  import { createReadStream as createReadStream3 } from "fs";
18230
18929
  import { createInterface as createInterface2 } from "readline";
18231
18930
  import { homedir as homedir11 } from "os";
18232
- import { join as join31 } from "path";
18931
+ import { join as join32 } from "path";
18233
18932
  var MAX_CHUNK_CHARS5, HistorySource;
18234
18933
  var init_history_source = __esm({
18235
18934
  "../engine/dist/parsers/history-source.js"() {
@@ -18254,12 +18953,12 @@ var init_history_source = __esm({
18254
18953
  try {
18255
18954
  for (const entry of readdirSync21(home, { withFileTypes: true })) {
18256
18955
  if (entry.isDirectory() && entry.name.startsWith(".claude-") && entry.name !== ".claude-code") {
18257
- tryAdd(join31(home, entry.name, "history.jsonl"));
18956
+ tryAdd(join32(home, entry.name, "history.jsonl"));
18258
18957
  }
18259
18958
  }
18260
18959
  } catch {
18261
18960
  }
18262
- this.historyPaths = paths.length > 0 ? paths : [join31(home, ".claude", "history.jsonl")];
18961
+ this.historyPaths = paths.length > 0 ? paths : [join32(home, ".claude", "history.jsonl")];
18263
18962
  }
18264
18963
  }
18265
18964
  async *discover() {
@@ -18268,7 +18967,7 @@ var init_history_source = __esm({
18268
18967
  const historyPath = this.historyPaths.find((p) => existsSync27(p));
18269
18968
  if (!historyPath)
18270
18969
  return;
18271
- const stat3 = statSync26(historyPath);
18970
+ const stat3 = statSync27(historyPath);
18272
18971
  const groups = await this.groupByProject();
18273
18972
  for (const [project, group] of groups) {
18274
18973
  const projectId = project.replace(/\//g, "-").replace(/^-/, "");
@@ -18409,9 +19108,9 @@ var init_history_source = __esm({
18409
19108
  });
18410
19109
 
18411
19110
  // ../engine/dist/parsers/paste-source.js
18412
- import { existsSync as existsSync28, readdirSync as readdirSync22, readFileSync as readFileSync24, statSync as statSync27 } from "fs";
19111
+ import { existsSync as existsSync28, readdirSync as readdirSync22, readFileSync as readFileSync26, statSync as statSync28 } from "fs";
18413
19112
  import { homedir as homedir12 } from "os";
18414
- import { join as join32, basename as basename17 } from "path";
19113
+ import { join as join33, basename as basename17 } from "path";
18415
19114
  var MAX_CHUNK_CHARS6, MAX_FILE_SIZE, PasteSource;
18416
19115
  var init_paste_source = __esm({
18417
19116
  "../engine/dist/parsers/paste-source.js"() {
@@ -18437,7 +19136,7 @@ var init_paste_source = __esm({
18437
19136
  try {
18438
19137
  for (const entry of readdirSync22(home, { withFileTypes: true })) {
18439
19138
  if (entry.isDirectory() && entry.name.startsWith(".claude-") && entry.name !== ".claude-code") {
18440
- tryAdd(join32(home, entry.name, "paste-cache"));
19139
+ tryAdd(join33(home, entry.name, "paste-cache"));
18441
19140
  }
18442
19141
  }
18443
19142
  } catch {
@@ -18457,15 +19156,15 @@ var init_paste_source = __esm({
18457
19156
  if (seen.has(file))
18458
19157
  continue;
18459
19158
  seen.add(file);
18460
- const filePath = join32(cacheDir, file);
19159
+ const filePath = join33(cacheDir, file);
18461
19160
  try {
18462
- const stat3 = statSync27(filePath);
19161
+ const stat3 = statSync28(filePath);
18463
19162
  if (stat3.size > MAX_FILE_SIZE)
18464
19163
  continue;
18465
19164
  if (stat3.size < 10)
18466
19165
  continue;
18467
19166
  const hash = basename17(file, ".txt");
18468
- const content = readFileSync24(filePath, "utf-8");
19167
+ const content = readFileSync26(filePath, "utf-8");
18469
19168
  const firstLine = content.split("\n").find((l) => l.trim().length > 5)?.trim()?.slice(0, 100) || `Paste ${hash.slice(0, 8)}`;
18470
19169
  yield {
18471
19170
  id: hash,
@@ -18486,7 +19185,7 @@ var init_paste_source = __esm({
18486
19185
  async parse(item) {
18487
19186
  if (!existsSync28(item.filePath))
18488
19187
  return [];
18489
- const content = readFileSync24(item.filePath, "utf-8");
19188
+ const content = readFileSync26(item.filePath, "utf-8");
18490
19189
  if (content.trim().length < 20)
18491
19190
  return [];
18492
19191
  return [{
@@ -18509,8 +19208,8 @@ var init_paste_source = __esm({
18509
19208
  });
18510
19209
 
18511
19210
  // ../engine/dist/parsers/antigravity-brain-source.js
18512
- import { existsSync as existsSync29, readdirSync as readdirSync23, readFileSync as readFileSync25, statSync as statSync28 } from "fs";
18513
- import { join as join33 } from "path";
19211
+ import { existsSync as existsSync29, readdirSync as readdirSync23, readFileSync as readFileSync27, statSync as statSync29 } from "fs";
19212
+ import { join as join34 } from "path";
18514
19213
  var MAX_CHUNK_CHARS7, AntigravityBrainSource;
18515
19214
  var init_antigravity_brain_source = __esm({
18516
19215
  "../engine/dist/parsers/antigravity-brain-source.js"() {
@@ -18534,22 +19233,22 @@ var init_antigravity_brain_source = __esm({
18534
19233
  for (const entry of sessions) {
18535
19234
  if (!entry.isDirectory())
18536
19235
  continue;
18537
- const sessionDir = join33(this.brainDir, entry.name);
19236
+ const sessionDir = join34(this.brainDir, entry.name);
18538
19237
  const files = readdirSync23(sessionDir).filter((f) => f.endsWith(".md") && !f.includes(".resolved") && !f.includes(".metadata"));
18539
19238
  if (files.length === 0)
18540
19239
  continue;
18541
19240
  for (const file of files) {
18542
- const filePath = join33(sessionDir, file);
19241
+ const filePath = join34(sessionDir, file);
18543
19242
  try {
18544
- const stat3 = statSync28(filePath);
18545
- const content = readFileSync25(filePath, "utf-8");
19243
+ const stat3 = statSync29(filePath);
19244
+ const content = readFileSync27(filePath, "utf-8");
18546
19245
  const firstLine = content.split("\n").find((l) => l.trim() && !l.startsWith("#"))?.trim() || "";
18547
19246
  const heading = content.split("\n").find((l) => l.startsWith("#"))?.replace(/^#+\s*/, "").trim() || file;
18548
19247
  const metaPath = `${filePath}.metadata.json`;
18549
19248
  let metaSummary = "";
18550
19249
  if (existsSync29(metaPath)) {
18551
19250
  try {
18552
- const meta = JSON.parse(readFileSync25(metaPath, "utf-8"));
19251
+ const meta = JSON.parse(readFileSync27(metaPath, "utf-8"));
18553
19252
  metaSummary = meta.summary || "";
18554
19253
  } catch {
18555
19254
  }
@@ -18580,7 +19279,7 @@ var init_antigravity_brain_source = __esm({
18580
19279
  async parse(item) {
18581
19280
  if (!existsSync29(item.filePath))
18582
19281
  return [];
18583
- const content = readFileSync25(item.filePath, "utf-8");
19282
+ const content = readFileSync27(item.filePath, "utf-8");
18584
19283
  const chunks = [];
18585
19284
  const sections = splitByHeaders(content);
18586
19285
  for (let i = 0; i < sections.length; i++) {
@@ -18923,8 +19622,8 @@ var init_opencode_todo_source = __esm({
18923
19622
  });
18924
19623
 
18925
19624
  // ../engine/dist/parsers/codex-session-source.js
18926
- import { existsSync as existsSync32, readdirSync as readdirSync24, readFileSync as readFileSync26, statSync as statSync29 } from "fs";
18927
- import { join as join34, basename as basename18 } from "path";
19625
+ import { existsSync as existsSync32, readdirSync as readdirSync24, readFileSync as readFileSync28, statSync as statSync30 } from "fs";
19626
+ import { join as join35, basename as basename18 } from "path";
18928
19627
  function getCodexSessionsDir() {
18929
19628
  return codexBackend.sessionsDir();
18930
19629
  }
@@ -18951,7 +19650,7 @@ function extractReasoningText(event) {
18951
19650
  return "";
18952
19651
  }
18953
19652
  function readJsonlLines(filePath) {
18954
- const text = readFileSync26(filePath, "utf-8");
19653
+ const text = readFileSync28(filePath, "utf-8");
18955
19654
  const lines = text.split("\n");
18956
19655
  const events = [];
18957
19656
  for (const line of lines) {
@@ -18985,8 +19684,8 @@ var init_codex_session_source = __esm({
18985
19684
  const jsonlFiles = this.collectJsonlFiles(this.sessionsDir);
18986
19685
  for (const filePath of jsonlFiles) {
18987
19686
  try {
18988
- const stat3 = statSync29(filePath);
18989
- const lines = readFileSync26(filePath, "utf-8").split("\n");
19687
+ const stat3 = statSync30(filePath);
19688
+ const lines = readFileSync28(filePath, "utf-8").split("\n");
18990
19689
  const firstLine = lines.find((l) => l.trim());
18991
19690
  if (!firstLine)
18992
19691
  continue;
@@ -19145,7 +19844,7 @@ var init_codex_session_source = __esm({
19145
19844
  if (!existsSync32(dir))
19146
19845
  return results;
19147
19846
  for (const entry of readdirSync24(dir, { withFileTypes: true })) {
19148
- const fullPath = join34(dir, entry.name);
19847
+ const fullPath = join35(dir, entry.name);
19149
19848
  if (entry.isDirectory()) {
19150
19849
  results.push(...this.collectJsonlFiles(fullPath));
19151
19850
  } else if (entry.isFile() && entry.name.startsWith("rollout-") && entry.name.endsWith(".jsonl")) {
@@ -19159,8 +19858,8 @@ var init_codex_session_source = __esm({
19159
19858
  });
19160
19859
 
19161
19860
  // ../engine/dist/parsers/diary-source.js
19162
- import { existsSync as existsSync33, mkdirSync as mkdirSync6, readdirSync as readdirSync25, readFileSync as readFileSync27, writeFileSync as writeFileSync6, statSync as statSync30 } from "fs";
19163
- import { join as join35, basename as basename19 } from "path";
19861
+ import { existsSync as existsSync33, mkdirSync as mkdirSync7, readdirSync as readdirSync25, readFileSync as readFileSync29, writeFileSync as writeFileSync7, statSync as statSync31 } from "fs";
19862
+ import { join as join36, basename as basename19 } from "path";
19164
19863
  var MAX_CHUNK_CHARS10, DiarySource;
19165
19864
  var init_diary_source = __esm({
19166
19865
  "../engine/dist/parsers/diary-source.js"() {
@@ -19179,13 +19878,13 @@ var init_diary_source = __esm({
19179
19878
  return;
19180
19879
  const agents = readdirSync25(this.diaryDir, { withFileTypes: true }).filter((d) => d.isDirectory());
19181
19880
  for (const agentDir of agents) {
19182
- const agentPath2 = join35(this.diaryDir, agentDir.name);
19881
+ const agentPath2 = join36(this.diaryDir, agentDir.name);
19183
19882
  const files = readdirSync25(agentPath2).filter((f) => f.endsWith(".json"));
19184
19883
  for (const file of files) {
19185
- const filePath = join35(agentPath2, file);
19884
+ const filePath = join36(agentPath2, file);
19186
19885
  try {
19187
- const stat3 = statSync30(filePath);
19188
- const raw = readFileSync27(filePath, "utf-8");
19886
+ const stat3 = statSync31(filePath);
19887
+ const raw = readFileSync29(filePath, "utf-8");
19189
19888
  const entry = JSON.parse(raw);
19190
19889
  const entryId = basename19(file, ".json");
19191
19890
  const title = `[${entry.agent}] ${entry.topic}: ${entry.content.slice(0, 80)}`;
@@ -19212,7 +19911,7 @@ var init_diary_source = __esm({
19212
19911
  async parse(item) {
19213
19912
  if (!existsSync33(item.filePath))
19214
19913
  return [];
19215
- const raw = readFileSync27(item.filePath, "utf-8");
19914
+ const raw = readFileSync29(item.filePath, "utf-8");
19216
19915
  const entry = JSON.parse(raw);
19217
19916
  if (!entry.content || entry.content.trim().length < 10)
19218
19917
  return [];
@@ -19249,18 +19948,18 @@ var init_diary_source = __esm({
19249
19948
  */
19250
19949
  static write(entry, diaryDir) {
19251
19950
  const dir = diaryDir || getDiaryDir();
19252
- const agentDir = join35(dir, entry.agent.toLowerCase().replace(/[^a-z0-9_-]/g, "_"));
19951
+ const agentDir = join36(dir, entry.agent.toLowerCase().replace(/[^a-z0-9_-]/g, "_"));
19253
19952
  if (!existsSync33(agentDir)) {
19254
- mkdirSync6(agentDir, { recursive: true });
19953
+ mkdirSync7(agentDir, { recursive: true });
19255
19954
  }
19256
19955
  const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
19257
19956
  const entryId = `diary_${entry.agent.toLowerCase()}_${ts}`;
19258
- const filePath = join35(agentDir, `${entryId}.json`);
19957
+ const filePath = join36(agentDir, `${entryId}.json`);
19259
19958
  const full = {
19260
19959
  ...entry,
19261
19960
  timestamp: entry.timestamp || (/* @__PURE__ */ new Date()).toISOString()
19262
19961
  };
19263
- writeFileSync6(filePath, JSON.stringify(full, null, 2), "utf-8");
19962
+ writeFileSync7(filePath, JSON.stringify(full, null, 2), "utf-8");
19264
19963
  return entryId;
19265
19964
  }
19266
19965
  /**
@@ -19268,14 +19967,14 @@ var init_diary_source = __esm({
19268
19967
  */
19269
19968
  static read(agentName, lastN = 10, diaryDir) {
19270
19969
  const dir = diaryDir || getDiaryDir();
19271
- const agentDir = join35(dir, agentName.toLowerCase().replace(/[^a-z0-9_-]/g, "_"));
19970
+ const agentDir = join36(dir, agentName.toLowerCase().replace(/[^a-z0-9_-]/g, "_"));
19272
19971
  if (!existsSync33(agentDir))
19273
19972
  return [];
19274
19973
  const files = readdirSync25(agentDir).filter((f) => f.endsWith(".json")).sort().reverse().slice(0, lastN);
19275
19974
  const entries = [];
19276
19975
  for (const file of files) {
19277
19976
  try {
19278
- const raw = readFileSync27(join35(agentDir, file), "utf-8");
19977
+ const raw = readFileSync29(join36(agentDir, file), "utf-8");
19279
19978
  entries.push(JSON.parse(raw));
19280
19979
  } catch {
19281
19980
  continue;
@@ -19320,9 +20019,9 @@ var init_redact_inline = __esm({
19320
20019
  });
19321
20020
 
19322
20021
  // ../engine/dist/parsers/skills-source.js
19323
- import { existsSync as existsSync34, readdirSync as readdirSync26, readFileSync as readFileSync28, statSync as statSync31 } from "fs";
20022
+ import { existsSync as existsSync34, readdirSync as readdirSync26, readFileSync as readFileSync30, statSync as statSync32 } from "fs";
19324
20023
  import { homedir as homedir13 } from "os";
19325
- import { join as join36 } from "path";
20024
+ import { join as join37 } from "path";
19326
20025
  function rebuildBody(content) {
19327
20026
  const { text, redacted } = redactInlineSecrets(content);
19328
20027
  const out = {};
@@ -19340,31 +20039,31 @@ function resolveRoots() {
19340
20039
  const home = homedir13();
19341
20040
  const all = [];
19342
20041
  if (isSourceEnabled("shared", "skills")) {
19343
- all.push({ path: join36(home, ".agents", "skills"), tool: "shared" });
20042
+ all.push({ path: join37(home, ".agents", "skills"), tool: "shared" });
19344
20043
  }
19345
20044
  if (isSourceEnabled("claude", "skills")) {
19346
20045
  all.push({ path: claudeBackend.skillsDir(), tool: "claude" });
19347
20046
  }
19348
20047
  if (isSourceEnabled("hermes", "skills")) {
19349
- all.push({ path: join36(hermesBackend.homeDir(), "skills"), tool: "hermes", nested: true });
20048
+ all.push({ path: join37(hermesBackend.homeDir(), "skills"), tool: "hermes", nested: true });
19350
20049
  }
19351
20050
  if (isSourceEnabled("pi", "skills")) {
19352
20051
  all.push({ path: piBackend.skillsDir(), tool: "pi" });
19353
20052
  }
19354
20053
  if (isSourceEnabled("agy", "skills")) {
19355
- all.push({ path: join36(agyBackend.homeDir(), "skills"), tool: "agy" });
20054
+ all.push({ path: join37(agyBackend.homeDir(), "skills"), tool: "agy" });
19356
20055
  all.push({ path: agyBackend.sharedSkillsDir(), tool: "agy" });
19357
20056
  }
19358
20057
  if (isSourceEnabled("opencode", "skills")) {
19359
- all.push({ path: join36(home, ".config", "opencode", "skills"), tool: "opencode" }, { path: join36(home, ".config", "opencode", "skill"), tool: "opencode" }, { path: join36(home, ".opencode", "skill"), tool: "opencode" }, { path: join36(home, ".opencode", "skills"), tool: "opencode" });
20058
+ all.push({ path: join37(home, ".config", "opencode", "skills"), tool: "opencode" }, { path: join37(home, ".config", "opencode", "skill"), tool: "opencode" }, { path: join37(home, ".opencode", "skill"), tool: "opencode" }, { path: join37(home, ".opencode", "skills"), tool: "opencode" });
19360
20059
  }
19361
20060
  if (isSourceEnabled("codex", "skills")) {
19362
20061
  all.push({ path: codexBackend.skillsDir(), tool: "codex", skipChildren: [".system"] });
19363
20062
  all.push({ path: codexBackend.skillsSystemDir(), tool: "codex", readonly: true });
19364
20063
  }
19365
20064
  if (isSourceEnabled("cursor", "skills")) {
19366
- all.push({ path: join36(cursorHomeDir(), "skills"), tool: "cursor" });
19367
- all.push({ path: join36(cursorHomeDir(), "skills-cursor"), tool: "cursor", readonly: true });
20065
+ all.push({ path: join37(cursorHomeDir(), "skills"), tool: "cursor" });
20066
+ all.push({ path: join37(cursorHomeDir(), "skills-cursor"), tool: "cursor", readonly: true });
19368
20067
  }
19369
20068
  return all.filter((r) => existsSync34(r.path));
19370
20069
  }
@@ -19409,7 +20108,7 @@ var init_skills_source = __esm({
19409
20108
  if (!isSourceEnabled("codex", "skills"))
19410
20109
  return;
19411
20110
  for (const { name: pluginName, dir } of codexBackend.installedPluginDirs()) {
19412
- const skillsDir = join36(dir, "skills");
20111
+ const skillsDir = join37(dir, "skills");
19413
20112
  if (!existsSync34(skillsDir))
19414
20113
  continue;
19415
20114
  yield* this.fromSkillRoot({ path: skillsDir, tool: "codex" }, pluginName);
@@ -19425,16 +20124,16 @@ var init_skills_source = __esm({
19425
20124
  for (const name of entries) {
19426
20125
  if (root.skipChildren?.includes(name))
19427
20126
  continue;
19428
- const skillDir = join36(root.path, name);
20127
+ const skillDir = join37(root.path, name);
19429
20128
  let st;
19430
20129
  try {
19431
- st = statSync31(skillDir);
20130
+ st = statSync32(skillDir);
19432
20131
  } catch {
19433
20132
  continue;
19434
20133
  }
19435
20134
  if (!st.isDirectory())
19436
20135
  continue;
19437
- const skillMd = join36(skillDir, "SKILL.md");
20136
+ const skillMd = join37(skillDir, "SKILL.md");
19438
20137
  if (!existsSync34(skillMd)) {
19439
20138
  if (root.nested)
19440
20139
  yield* this.fromSkillRoot({ ...root, path: skillDir, nested: false });
@@ -19442,7 +20141,7 @@ var init_skills_source = __esm({
19442
20141
  }
19443
20142
  let content;
19444
20143
  try {
19445
- content = readFileSync28(skillMd, "utf-8");
20144
+ content = readFileSync30(skillMd, "utf-8");
19446
20145
  } catch {
19447
20146
  continue;
19448
20147
  }
@@ -19450,15 +20149,15 @@ var init_skills_source = __esm({
19450
20149
  const skillName = fm.name || name;
19451
20150
  let mtime = st.mtimeMs;
19452
20151
  try {
19453
- mtime = statSync31(skillMd).mtimeMs;
20152
+ mtime = statSync32(skillMd).mtimeMs;
19454
20153
  } catch {
19455
20154
  }
19456
20155
  const subdirs = {};
19457
20156
  try {
19458
20157
  for (const sub of readdirSync26(skillDir)) {
19459
- const subPath = join36(skillDir, sub);
20158
+ const subPath = join37(skillDir, sub);
19460
20159
  try {
19461
- const ss = statSync31(subPath);
20160
+ const ss = statSync32(subPath);
19462
20161
  if (ss.isDirectory()) {
19463
20162
  let count = 0;
19464
20163
  try {
@@ -19505,7 +20204,7 @@ var init_skills_source = __esm({
19505
20204
  async parse(item) {
19506
20205
  if (!existsSync34(item.filePath))
19507
20206
  return [];
19508
- const content = readFileSync28(item.filePath, "utf-8");
20207
+ const content = readFileSync30(item.filePath, "utf-8");
19509
20208
  if (!content.trim())
19510
20209
  return [];
19511
20210
  return [{
@@ -26858,16 +27557,16 @@ var require_dist = __commonJS({
26858
27557
  });
26859
27558
 
26860
27559
  // ../engine/dist/core/hermes-config.js
26861
- import { existsSync as existsSync35, readFileSync as readFileSync29 } from "fs";
26862
- import { join as join37 } from "path";
27560
+ import { existsSync as existsSync35, readFileSync as readFileSync31 } from "fs";
27561
+ import { join as join38 } from "path";
26863
27562
  function hermesConfigPath() {
26864
- return join37(hermesHomeDir(), "config.yaml");
27563
+ return join38(hermesHomeDir(), "config.yaml");
26865
27564
  }
26866
27565
  function readHermesMcpServers(path = hermesConfigPath()) {
26867
27566
  if (!existsSync35(path))
26868
27567
  return null;
26869
27568
  try {
26870
- const cfg = (0, import_yaml.parse)(readFileSync29(path, "utf-8"));
27569
+ const cfg = (0, import_yaml.parse)(readFileSync31(path, "utf-8"));
26871
27570
  return cfg?.mcp_servers && typeof cfg.mcp_servers === "object" ? cfg.mcp_servers : null;
26872
27571
  } catch {
26873
27572
  return null;
@@ -26917,14 +27616,14 @@ var init_hermes_config = __esm({
26917
27616
  });
26918
27617
 
26919
27618
  // ../engine/dist/parsers/mcps-source.js
26920
- import { existsSync as existsSync36, readFileSync as readFileSync30, statSync as statSync32 } from "fs";
27619
+ import { existsSync as existsSync36, readFileSync as readFileSync32, statSync as statSync33 } from "fs";
26921
27620
  import { homedir as homedir14 } from "os";
26922
- import { join as join38 } from "path";
27621
+ import { join as join39 } from "path";
26923
27622
  function readJson(path) {
26924
27623
  if (!existsSync36(path))
26925
27624
  return null;
26926
27625
  try {
26927
- const raw = readFileSync30(path, "utf-8");
27626
+ const raw = readFileSync32(path, "utf-8");
26928
27627
  const stripped = path.endsWith(".jsonc") ? raw.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1").replace(/,(\s*[}\]])/g, "$1") : raw;
26929
27628
  return JSON.parse(stripped);
26930
27629
  } catch {
@@ -26986,23 +27685,23 @@ var init_mcps_source = __esm({
26986
27685
  if (!isSourceEnabled("common", "mcps"))
26987
27686
  return;
26988
27687
  const home = homedir14();
26989
- yield* this.fromObject(readJson(join38(home, ".mcp.json"))?.mcpServers, {
27688
+ yield* this.fromObject(readJson(join39(home, ".mcp.json"))?.mcpServers, {
26990
27689
  tool: "claude",
26991
- filePath: join38(home, ".mcp.json"),
27690
+ filePath: join39(home, ".mcp.json"),
26992
27691
  scope: "global"
26993
27692
  });
26994
- yield* this.fromObject(readJson(join38(home, ".claude.json"))?.mcpServers, {
27693
+ yield* this.fromObject(readJson(join39(home, ".claude.json"))?.mcpServers, {
26995
27694
  tool: "claude",
26996
- filePath: join38(home, ".claude.json"),
27695
+ filePath: join39(home, ".claude.json"),
26997
27696
  scope: "user"
26998
27697
  });
26999
27698
  for (const path of [
27000
- join38(home, ".config", "opencode", "opencode.json"),
27001
- join38(home, ".config", "opencode", "opencode.jsonc"),
27002
- join38(home, ".config", "opencode", "config.json"),
27003
- join38(home, ".opencode", "opencode.json"),
27004
- join38(home, ".opencode", "opencode.jsonc"),
27005
- join38(home, ".opencode", "config.json")
27699
+ join39(home, ".config", "opencode", "opencode.json"),
27700
+ join39(home, ".config", "opencode", "opencode.jsonc"),
27701
+ join39(home, ".config", "opencode", "config.json"),
27702
+ join39(home, ".opencode", "opencode.json"),
27703
+ join39(home, ".opencode", "opencode.jsonc"),
27704
+ join39(home, ".opencode", "config.json")
27006
27705
  ]) {
27007
27706
  yield* this.fromObject(readJson(path)?.mcp, {
27008
27707
  tool: "opencode",
@@ -27017,7 +27716,7 @@ var init_mcps_source = __esm({
27017
27716
  filePath: geminiSettings,
27018
27717
  scope: "user"
27019
27718
  });
27020
- const cursorMcp = join38(cursorHomeDir(), "mcp.json");
27719
+ const cursorMcp = join39(cursorHomeDir(), "mcp.json");
27021
27720
  yield* this.fromObject(readJson(cursorMcp)?.mcpServers, {
27022
27721
  tool: "cursor",
27023
27722
  filePath: cursorMcp,
@@ -27035,7 +27734,7 @@ var init_mcps_source = __esm({
27035
27734
  filePath: piMcp,
27036
27735
  scope: "user"
27037
27736
  });
27038
- const agyMcp = join38(home, ".gemini", "config", "mcp_config.json");
27737
+ const agyMcp = join39(home, ".gemini", "config", "mcp_config.json");
27039
27738
  yield* this.fromObject(readJson(agyMcp)?.mcpServers, {
27040
27739
  tool: "agy",
27041
27740
  filePath: agyMcp,
@@ -27043,7 +27742,7 @@ var init_mcps_source = __esm({
27043
27742
  });
27044
27743
  yield* this.fromCodexToml(codexBackend.configToml());
27045
27744
  for (const { dir } of codexBackend.installedPluginDirs()) {
27046
- const mcpPath = join38(dir, ".mcp.json");
27745
+ const mcpPath = join39(dir, ".mcp.json");
27047
27746
  yield* this.fromObject(readJson(mcpPath)?.mcpServers, {
27048
27747
  tool: "codex",
27049
27748
  filePath: mcpPath,
@@ -27056,7 +27755,7 @@ var init_mcps_source = __esm({
27056
27755
  return;
27057
27756
  let mtime = 0;
27058
27757
  try {
27059
- mtime = statSync32(ctx.filePath).mtimeMs;
27758
+ mtime = statSync33(ctx.filePath).mtimeMs;
27060
27759
  } catch {
27061
27760
  }
27062
27761
  for (const [name, cfgRaw] of Object.entries(obj2)) {
@@ -27101,7 +27800,7 @@ var init_mcps_source = __esm({
27101
27800
  return;
27102
27801
  let content;
27103
27802
  try {
27104
- content = readFileSync30(path, "utf-8");
27803
+ content = readFileSync32(path, "utf-8");
27105
27804
  } catch {
27106
27805
  return;
27107
27806
  }
@@ -27270,8 +27969,8 @@ var init_toolkit_format = __esm({
27270
27969
  });
27271
27970
 
27272
27971
  // ../engine/dist/parsers/slash-commands-source.js
27273
- import { existsSync as existsSync37, readdirSync as readdirSync27, readFileSync as readFileSync31, statSync as statSync33 } from "fs";
27274
- import { join as join39, basename as basename20 } from "path";
27972
+ import { existsSync as existsSync37, readdirSync as readdirSync27, readFileSync as readFileSync33, statSync as statSync34 } from "fs";
27973
+ import { join as join40, basename as basename20 } from "path";
27275
27974
  function rebuildBody2(content) {
27276
27975
  const { text, redacted } = redactInlineSecrets(content);
27277
27976
  const out = {};
@@ -27330,7 +28029,7 @@ var init_slash_commands_source = __esm({
27330
28029
  if (!entry.isDirectory() || entry.name.startsWith("."))
27331
28030
  continue;
27332
28031
  const projectPath = resolveProjectDirName(entry.name);
27333
- const cmdDir = join39(projectPath, ".claude", "commands");
28032
+ const cmdDir = join40(projectPath, ".claude", "commands");
27334
28033
  if (existsSync37(cmdDir))
27335
28034
  roots.push({ path: cmdDir, tool: "claude", scope: "project", projectPath, format: "md" });
27336
28035
  }
@@ -27339,7 +28038,7 @@ var init_slash_commands_source = __esm({
27339
28038
  }
27340
28039
  }
27341
28040
  if (isSourceEnabled("agy", "commands")) {
27342
- roots.push({ path: join39(agyBackend.homeDir(), "commands"), tool: "agy", scope: "user", projectPath: "", format: "toml" });
28041
+ roots.push({ path: join40(agyBackend.homeDir(), "commands"), tool: "agy", scope: "user", projectPath: "", format: "toml" });
27343
28042
  roots.push({ path: agyBackend.sharedCommandsDir(), tool: "agy", scope: "user", projectPath: "", format: "toml" });
27344
28043
  }
27345
28044
  if (isSourceEnabled("opencode", "commands")) {
@@ -27349,7 +28048,7 @@ var init_slash_commands_source = __esm({
27349
28048
  roots.push({ path: codexBackend.promptsDir(), tool: "codex", scope: "user", projectPath: "", format: "md" });
27350
28049
  }
27351
28050
  if (isSourceEnabled("cursor", "commands")) {
27352
- roots.push({ path: join39(cursorHomeDir(), "commands"), tool: "cursor", scope: "user", projectPath: "", format: "md" });
28051
+ roots.push({ path: join40(cursorHomeDir(), "commands"), tool: "cursor", scope: "user", projectPath: "", format: "md" });
27353
28052
  }
27354
28053
  if (isSourceEnabled("pi", "commands")) {
27355
28054
  roots.push({ path: piBackend.promptsDir(), tool: "pi", scope: "user", projectPath: "", format: "md" });
@@ -27366,10 +28065,10 @@ var init_slash_commands_source = __esm({
27366
28065
  continue;
27367
28066
  }
27368
28067
  for (const file of files) {
27369
- const filePath = join39(root.path, file);
28068
+ const filePath = join40(root.path, file);
27370
28069
  try {
27371
- const stat3 = statSync33(filePath);
27372
- const content = readFileSync31(filePath, "utf-8");
28070
+ const stat3 = statSync34(filePath);
28071
+ const content = readFileSync33(filePath, "utf-8");
27373
28072
  const parsed = parseCommand(content, basename20(file, ext), root.format);
27374
28073
  yield {
27375
28074
  id: `${root.tool}_cmd_${root.scope}_${parsed.name}`,
@@ -27398,7 +28097,7 @@ var init_slash_commands_source = __esm({
27398
28097
  async parse(item) {
27399
28098
  if (!existsSync37(item.filePath))
27400
28099
  return [];
27401
- const content = readFileSync31(item.filePath, "utf-8");
28100
+ const content = readFileSync33(item.filePath, "utf-8");
27402
28101
  if (!content.trim())
27403
28102
  return [];
27404
28103
  return [{
@@ -27421,8 +28120,8 @@ var init_slash_commands_source = __esm({
27421
28120
  });
27422
28121
 
27423
28122
  // ../engine/dist/parsers/subagents-source.js
27424
- import { existsSync as existsSync38, readdirSync as readdirSync28, readFileSync as readFileSync32, statSync as statSync34 } from "fs";
27425
- import { join as join40, basename as basename21 } from "path";
28123
+ import { existsSync as existsSync38, readdirSync as readdirSync28, readFileSync as readFileSync34, statSync as statSync35 } from "fs";
28124
+ import { join as join41, basename as basename21 } from "path";
27426
28125
  function rebuildBody3(content) {
27427
28126
  const { text, redacted } = redactInlineSecrets(content);
27428
28127
  const out = {};
@@ -27482,7 +28181,7 @@ var init_subagents_source = __esm({
27482
28181
  if (!entry.isDirectory() || entry.name.startsWith("."))
27483
28182
  continue;
27484
28183
  const projectPath = resolveProjectDirName(entry.name);
27485
- const agentDir = join40(projectPath, ".claude", "agents");
28184
+ const agentDir = join41(projectPath, ".claude", "agents");
27486
28185
  if (existsSync38(agentDir))
27487
28186
  roots.push({ path: agentDir, tool: "claude", scope: "project", projectPath, format: "md" });
27488
28187
  }
@@ -27491,7 +28190,7 @@ var init_subagents_source = __esm({
27491
28190
  }
27492
28191
  }
27493
28192
  if (isSourceEnabled("agy", "agents")) {
27494
- roots.push({ path: join40(agyBackend.homeDir(), "agents"), tool: "agy", scope: "user", projectPath: "", format: "md" });
28193
+ roots.push({ path: join41(agyBackend.homeDir(), "agents"), tool: "agy", scope: "user", projectPath: "", format: "md" });
27495
28194
  roots.push({ path: agyBackend.sharedAgentsDir(), tool: "agy", scope: "user", projectPath: "", format: "md" });
27496
28195
  }
27497
28196
  if (isSourceEnabled("opencode", "agents")) {
@@ -27501,7 +28200,7 @@ var init_subagents_source = __esm({
27501
28200
  roots.push({ path: codexBackend.agentsDir(), tool: "codex", scope: "user", projectPath: "", format: "toml" });
27502
28201
  }
27503
28202
  if (isSourceEnabled("cursor", "agents")) {
27504
- roots.push({ path: join40(cursorHomeDir(), "agents"), tool: "cursor", scope: "user", projectPath: "", format: "md" });
28203
+ roots.push({ path: join41(cursorHomeDir(), "agents"), tool: "cursor", scope: "user", projectPath: "", format: "md" });
27505
28204
  }
27506
28205
  return roots;
27507
28206
  }
@@ -27515,10 +28214,10 @@ var init_subagents_source = __esm({
27515
28214
  continue;
27516
28215
  }
27517
28216
  for (const file of files) {
27518
- const filePath = join40(root.path, file);
28217
+ const filePath = join41(root.path, file);
27519
28218
  try {
27520
- const stat3 = statSync34(filePath);
27521
- const content = readFileSync32(filePath, "utf-8");
28219
+ const stat3 = statSync35(filePath);
28220
+ const content = readFileSync34(filePath, "utf-8");
27522
28221
  const parsed = parseAgent(content, basename21(file, ext), root.format);
27523
28222
  yield {
27524
28223
  id: `${root.tool}_agent_${root.scope}_${parsed.name}`,
@@ -27548,7 +28247,7 @@ var init_subagents_source = __esm({
27548
28247
  async parse(item) {
27549
28248
  if (!existsSync38(item.filePath))
27550
28249
  return [];
27551
- const content = readFileSync32(item.filePath, "utf-8");
28250
+ const content = readFileSync34(item.filePath, "utf-8");
27552
28251
  if (!content.trim())
27553
28252
  return [];
27554
28253
  return [{
@@ -27571,13 +28270,13 @@ var init_subagents_source = __esm({
27571
28270
  });
27572
28271
 
27573
28272
  // ../engine/dist/parsers/hooks-source.js
27574
- import { existsSync as existsSync39, readFileSync as readFileSync33, readdirSync as readdirSync29, statSync as statSync35 } from "fs";
27575
- import { join as join41 } from "path";
28273
+ import { existsSync as existsSync39, readFileSync as readFileSync35, readdirSync as readdirSync29, statSync as statSync36 } from "fs";
28274
+ import { join as join42 } from "path";
27576
28275
  function readJson2(path) {
27577
28276
  if (!existsSync39(path))
27578
28277
  return null;
27579
28278
  try {
27580
- return JSON.parse(readFileSync33(path, "utf-8"));
28279
+ return JSON.parse(readFileSync35(path, "utf-8"));
27581
28280
  } catch {
27582
28281
  return null;
27583
28282
  }
@@ -27602,7 +28301,7 @@ var init_hooks_source = __esm({
27602
28301
  if (!entry.isDirectory() || entry.name.startsWith("."))
27603
28302
  continue;
27604
28303
  const projectPath = resolveProjectDirName(entry.name);
27605
- const settingsPath2 = join41(projectPath, ".claude", "settings.json");
28304
+ const settingsPath2 = join42(projectPath, ".claude", "settings.json");
27606
28305
  if (existsSync39(settingsPath2)) {
27607
28306
  yield* this.fromSettings(settingsPath2, "project", projectPath);
27608
28307
  }
@@ -27620,7 +28319,7 @@ var init_hooks_source = __esm({
27620
28319
  return;
27621
28320
  let mtime = 0;
27622
28321
  try {
27623
- mtime = statSync35(settingsPath2).mtimeMs;
28322
+ mtime = statSync36(settingsPath2).mtimeMs;
27624
28323
  } catch {
27625
28324
  }
27626
28325
  for (const [event, groups] of Object.entries(hooks)) {
@@ -27694,14 +28393,14 @@ var init_hooks_source = __esm({
27694
28393
  });
27695
28394
 
27696
28395
  // ../engine/dist/parsers/plugins-source.js
27697
- import { existsSync as existsSync40, readFileSync as readFileSync34, readdirSync as readdirSync30, statSync as statSync36 } from "fs";
28396
+ import { existsSync as existsSync40, readFileSync as readFileSync36, readdirSync as readdirSync30, statSync as statSync37 } from "fs";
27698
28397
  import { homedir as homedir15 } from "os";
27699
- import { join as join42 } from "path";
28398
+ import { join as join43 } from "path";
27700
28399
  function readJson3(path) {
27701
28400
  if (!existsSync40(path))
27702
28401
  return null;
27703
28402
  try {
27704
- return JSON.parse(readFileSync34(path, "utf-8"));
28403
+ return JSON.parse(readFileSync36(path, "utf-8"));
27705
28404
  } catch {
27706
28405
  return null;
27707
28406
  }
@@ -27723,7 +28422,7 @@ var init_plugins_source = __esm({
27723
28422
  if (claudeJson?.plugins && typeof claudeJson.plugins === "object") {
27724
28423
  let mtime = 0;
27725
28424
  try {
27726
- mtime = statSync36(claudePluginsManifest).mtimeMs;
28425
+ mtime = statSync37(claudePluginsManifest).mtimeMs;
27727
28426
  } catch {
27728
28427
  }
27729
28428
  for (const [pluginRef, installs] of Object.entries(claudeJson.plugins)) {
@@ -27761,22 +28460,22 @@ var init_plugins_source = __esm({
27761
28460
  entries = [];
27762
28461
  }
27763
28462
  for (const name of entries) {
27764
- const dir = join42(gemRoot, name);
28463
+ const dir = join43(gemRoot, name);
27765
28464
  let st;
27766
28465
  try {
27767
- st = statSync36(dir);
28466
+ st = statSync37(dir);
27768
28467
  } catch {
27769
28468
  continue;
27770
28469
  }
27771
28470
  if (!st.isDirectory())
27772
28471
  continue;
27773
- const manifestPath = join42(dir, "gemini-extension.json");
28472
+ const manifestPath = join43(dir, "gemini-extension.json");
27774
28473
  const manifest = readJson3(manifestPath);
27775
28474
  if (!manifest || typeof manifest !== "object")
27776
28475
  continue;
27777
28476
  let mtime = st.mtimeMs;
27778
28477
  try {
27779
- mtime = statSync36(manifestPath).mtimeMs;
28478
+ mtime = statSync37(manifestPath).mtimeMs;
27780
28479
  } catch {
27781
28480
  }
27782
28481
  const mcpServers = manifest.mcpServers ? Object.keys(manifest.mcpServers) : [];
@@ -27804,17 +28503,17 @@ var init_plugins_source = __esm({
27804
28503
  for (const { name, dir: pluginDir } of codexBackend.installedPluginDirs()) {
27805
28504
  let st;
27806
28505
  try {
27807
- st = statSync36(pluginDir);
28506
+ st = statSync37(pluginDir);
27808
28507
  } catch {
27809
28508
  continue;
27810
28509
  }
27811
28510
  if (!st.isDirectory())
27812
28511
  continue;
27813
- const appJson = readJson3(join42(pluginDir, ".codex-plugin", ".app.json"));
27814
- const pluginJson = readJson3(join42(pluginDir, ".codex-plugin", "plugin.json"));
28512
+ const appJson = readJson3(join43(pluginDir, ".codex-plugin", ".app.json"));
28513
+ const pluginJson = readJson3(join43(pluginDir, ".codex-plugin", "plugin.json"));
27815
28514
  const manifest = pluginJson || appJson || {};
27816
28515
  let mcpServers = [];
27817
- const mcpJson = readJson3(join42(pluginDir, ".mcp.json"));
28516
+ const mcpJson = readJson3(join43(pluginDir, ".mcp.json"));
27818
28517
  if (mcpJson?.mcpServers)
27819
28518
  mcpServers = Object.keys(mcpJson.mcpServers);
27820
28519
  yield {
@@ -27822,7 +28521,7 @@ var init_plugins_source = __esm({
27822
28521
  sourceType: "plugin",
27823
28522
  title: manifest.name || name,
27824
28523
  projectPath: "",
27825
- filePath: join42(pluginDir, ".codex-plugin"),
28524
+ filePath: join43(pluginDir, ".codex-plugin"),
27826
28525
  mtime: st.mtimeMs,
27827
28526
  contentPreview: (manifest.description || "").slice(0, 300),
27828
28527
  extra: {
@@ -27913,402 +28612,6 @@ var init_all_sources = __esm({
27913
28612
  }
27914
28613
  });
27915
28614
 
27916
- // ../engine/dist/core/extractor-version.js
27917
- function extractorVersionForItem(id, sourceType) {
27918
- const tool = toolOfId(id);
27919
- return extractorVersionForTool(tool) + (ITEM_SOURCE_BUMP[sourceType] ?? 0) + (ITEM_TOOL_SOURCE_BUMP[`${tool}:${sourceType}`] ?? 0);
27920
- }
27921
- function toolOfId(id) {
27922
- if (id.startsWith("agy_"))
27923
- return "agy";
27924
- if (id.startsWith("gemini_"))
27925
- return "gemini";
27926
- if (id.startsWith("opencode_"))
27927
- return "opencode";
27928
- if (id.startsWith("codex_"))
27929
- return "codex";
27930
- if (id.startsWith("cursor_"))
27931
- return "cursor";
27932
- if (id.startsWith("hermes_"))
27933
- return "hermes";
27934
- if (id.startsWith("pi_"))
27935
- return "pi";
27936
- return "claude";
27937
- }
27938
- function extractorVersionForTool(tool) {
27939
- return BASE_EXTRACTOR_VERSION + (TOOL_EXTRACTOR_BUMP[tool ?? ""] ?? 0);
27940
- }
27941
- function extractorVersionForId(id) {
27942
- return extractorVersionForTool(toolOfId(id));
27943
- }
27944
- var BASE_EXTRACTOR_VERSION, ITEM_SOURCE_BUMP, ITEM_TOOL_SOURCE_BUMP, TOOL_EXTRACTOR_BUMP, EXTRACTOR_VERSION;
27945
- var init_extractor_version = __esm({
27946
- "../engine/dist/core/extractor-version.js"() {
27947
- "use strict";
27948
- BASE_EXTRACTOR_VERSION = 2;
27949
- ITEM_SOURCE_BUMP = {
27950
- mcp: 2,
27951
- skill: 1,
27952
- agent: 1,
27953
- command: 1
27954
- };
27955
- ITEM_TOOL_SOURCE_BUMP = {
27956
- "codex:skill": 1,
27957
- "codex:plugin": 1
27958
- };
27959
- TOOL_EXTRACTOR_BUMP = {
27960
- agy: 3,
27961
- claude: 1,
27962
- codex: 1
27963
- };
27964
- EXTRACTOR_VERSION = BASE_EXTRACTOR_VERSION;
27965
- }
27966
- });
27967
-
27968
- // src/sync-ledger.ts
27969
- import { readFileSync as readFileSync35, writeFileSync as writeFileSync7, renameSync as renameSync4, mkdirSync as mkdirSync7, statSync as statSync37 } from "node:fs";
27970
- import { join as join43, dirname as dirname16 } from "node:path";
27971
- function toRow(entry) {
27972
- if (entry === void 0) return void 0;
27973
- return typeof entry === "number" ? { m: entry, v: 0 } : entry;
27974
- }
27975
- function ledgerFilePath() {
27976
- return ledgerPath();
27977
- }
27978
- function stampOf(path) {
27979
- try {
27980
- const st = statSync37(path);
27981
- return `${st.mtimeMs}:${st.size}`;
27982
- } catch {
27983
- return null;
27984
- }
27985
- }
27986
- function readDisk(path) {
27987
- try {
27988
- const parsed = JSON.parse(readFileSync35(path, "utf-8"));
27989
- return parsed && typeof parsed === "object" ? parsed : {};
27990
- } catch {
27991
- return {};
27992
- }
27993
- }
27994
- function snapshot(data) {
27995
- const out = /* @__PURE__ */ new Map();
27996
- for (const [server, rows] of Object.entries(data)) {
27997
- for (const [id, entry] of Object.entries(rows)) out.set(rowKey(server, id), JSON.stringify(entry));
27998
- }
27999
- return out;
28000
- }
28001
- function mergeOnto(disk) {
28002
- const out = {};
28003
- const put = (server, id, entry) => {
28004
- (out[server] ??= {})[id] = entry;
28005
- };
28006
- const mine = cache3 ?? {};
28007
- for (const [server, rows] of Object.entries(disk)) {
28008
- for (const [id, entry] of Object.entries(rows)) {
28009
- const k = rowKey(server, id);
28010
- const own = mine[server]?.[id];
28011
- const was = base.get(k);
28012
- if (own === void 0) {
28013
- if (was === void 0) put(server, id, entry);
28014
- } else {
28015
- put(server, id, JSON.stringify(own) === was ? entry : own);
28016
- }
28017
- }
28018
- }
28019
- for (const [server, rows] of Object.entries(mine)) {
28020
- for (const [id, entry] of Object.entries(rows)) {
28021
- if (disk[server]?.[id] !== void 0) continue;
28022
- if (JSON.stringify(entry) !== base.get(rowKey(server, id))) put(server, id, entry);
28023
- }
28024
- }
28025
- return out;
28026
- }
28027
- function load() {
28028
- const path = ledgerPath();
28029
- const stamp = stampOf(path);
28030
- if (cache3 && stamp === diskStamp) return cache3;
28031
- const disk = readDisk(path);
28032
- const merged = cache3 ? mergeOnto(disk) : disk;
28033
- if (cache3) {
28034
- for (const server of Object.keys(cache3)) if (!(server in merged)) delete cache3[server];
28035
- for (const [server, rows] of Object.entries(merged)) {
28036
- const target = cache3[server] ?? (cache3[server] = {});
28037
- for (const id of Object.keys(target)) if (!(id in rows)) delete target[id];
28038
- Object.assign(target, rows);
28039
- }
28040
- } else {
28041
- cache3 = merged;
28042
- }
28043
- base = snapshot(disk);
28044
- diskStamp = stamp;
28045
- return cache3;
28046
- }
28047
- function persistNow() {
28048
- const path = ledgerPath();
28049
- mkdirSync7(dirname16(path), { recursive: true });
28050
- load();
28051
- const tmp = `${path}.tmp-${process.pid}`;
28052
- writeFileSync7(tmp, JSON.stringify(cache3 ?? {}));
28053
- renameSync4(tmp, path);
28054
- base = snapshot(cache3 ?? {});
28055
- diskStamp = stampOf(path);
28056
- pendingWrite = false;
28057
- }
28058
- function persist(_data) {
28059
- pendingWrite = true;
28060
- if (flushTimer) return;
28061
- flushTimer = setTimeout(() => {
28062
- flushTimer = null;
28063
- if (pendingWrite) {
28064
- try {
28065
- persistNow();
28066
- } catch {
28067
- }
28068
- }
28069
- }, LEDGER_FLUSH_MS);
28070
- flushTimer.unref?.();
28071
- }
28072
- function pruneLedgerTargets(configuredServers) {
28073
- const data = load();
28074
- const keep = new Set(configuredServers);
28075
- const orphans = {};
28076
- for (const server of Object.keys(data)) {
28077
- if (!keep.has(server)) {
28078
- orphans[server] = data[server];
28079
- delete data[server];
28080
- }
28081
- }
28082
- const names = Object.keys(orphans);
28083
- if (names.length === 0) return 0;
28084
- const path = ledgerPath();
28085
- const side = `${path}.orphans.json`;
28086
- try {
28087
- let prior = {};
28088
- try {
28089
- prior = JSON.parse(readFileSync35(side, "utf-8"));
28090
- } catch {
28091
- }
28092
- writeFileSync7(side, JSON.stringify({ ...prior, ...orphans }));
28093
- } catch {
28094
- for (const n of names) data[n] = orphans[n];
28095
- return 0;
28096
- }
28097
- const rows = names.reduce((n, s) => n + Object.keys(orphans[s]).length, 0);
28098
- console.error(`[sync] tidied local bookkeeping: ${rows} already-synced marker(s) for ${names.length} server(s) you no longer sync to (${names.join(", ")}) moved to ${side}. Nothing was uploaded there; the file is kept so logging back in re-ships nothing.`);
28099
- persistNow();
28100
- return names.length;
28101
- }
28102
- function flushLedger() {
28103
- if (flushTimer) {
28104
- clearTimeout(flushTimer);
28105
- flushTimer = null;
28106
- }
28107
- if (!pendingWrite || !cache3) return;
28108
- persistNow();
28109
- }
28110
- function loadItemVersionsAll() {
28111
- if (itemVersionsCache) return itemVersionsCache;
28112
- try {
28113
- const parsed = JSON.parse(readFileSync35(itemVersionsPath(), "utf-8"));
28114
- itemVersionsCache = parsed && typeof parsed === "object" ? parsed : {};
28115
- } catch {
28116
- itemVersionsCache = {};
28117
- }
28118
- return itemVersionsCache;
28119
- }
28120
- function loadItemVersions(server) {
28121
- return { ...loadItemVersionsAll()[server] || {} };
28122
- }
28123
- function saveItemVersions(server, versions) {
28124
- const all = loadItemVersionsAll();
28125
- all[server] = { ...all[server] || {}, ...versions };
28126
- const path = itemVersionsPath();
28127
- mkdirSync7(dirname16(path), { recursive: true });
28128
- const tmp = `${path}.tmp`;
28129
- writeFileSync7(tmp, JSON.stringify(all));
28130
- renameSync4(tmp, path);
28131
- }
28132
- function loadInventoryHashes(server) {
28133
- try {
28134
- const parsed = JSON.parse(readFileSync35(inventoryPath(), "utf-8"));
28135
- return { ...(parsed && typeof parsed === "object" ? parsed[server] : null) || {} };
28136
- } catch {
28137
- return {};
28138
- }
28139
- }
28140
- function saveInventoryHashes(server, hashes) {
28141
- let all = {};
28142
- try {
28143
- all = JSON.parse(readFileSync35(inventoryPath(), "utf-8"));
28144
- } catch {
28145
- }
28146
- if (!all || typeof all !== "object") all = {};
28147
- all[server] = { ...all[server] || {}, ...hashes };
28148
- const path = inventoryPath();
28149
- mkdirSync7(dirname16(path), { recursive: true });
28150
- const tmp = `${path}.tmp`;
28151
- writeFileSync7(tmp, JSON.stringify(all));
28152
- renameSync4(tmp, path);
28153
- }
28154
- function getSyncedRows(server) {
28155
- const data = load();
28156
- const out = /* @__PURE__ */ new Map();
28157
- for (const [id, entry] of Object.entries(data[server] || {})) out.set(id, toRow(entry));
28158
- return out;
28159
- }
28160
- function getLedgerData(server) {
28161
- const data = load();
28162
- return data[server] || {};
28163
- }
28164
- function persistLedgerData(server, serverData) {
28165
- const data = load();
28166
- data[server] = serverData;
28167
- persist(data);
28168
- flushLedger();
28169
- }
28170
- function markSynced(server, rows) {
28171
- if (rows.length === 0) return;
28172
- const data = load();
28173
- const forServer = data[server] || (data[server] = {});
28174
- for (const r of rows) {
28175
- const prev = toRow(forServer[r.id]);
28176
- const prevF = prev?.f;
28177
- const prevOS = prev && (prev.o !== void 0 || prev.s !== void 0) ? { o: prev.o, s: prev.s } : {};
28178
- const cursorFromCaller = r.acked === true;
28179
- if (!cursorFromCaller && (r.offset !== void 0 || r.size !== void 0)) {
28180
- unackedCursorAttempts++;
28181
- }
28182
- const o = (cursorFromCaller ? r.offset : void 0) ?? prevOS.o ?? 0;
28183
- const s = (cursorFromCaller ? r.size : void 0) ?? prevOS.s ?? 0;
28184
- const ev = extractorVersionForId(r.id);
28185
- const base4 = prevF ? { m: Math.floor(r.mtime), v: ev, f: prevF } : { m: Math.floor(r.mtime), v: ev };
28186
- if (o > 0 || s > 0) {
28187
- base4.o = o;
28188
- base4.s = s;
28189
- }
28190
- if (r.hash !== void 0) base4.h = r.hash;
28191
- const completesChunked = cursorFromCaller && r.chunkFinal === true && prev?.k === 1;
28192
- if (cursorFromCaller && (r.full || completesChunked) && o > 0) base4.F = o;
28193
- else if (prev?.F !== void 0) base4.F = prev.F;
28194
- if (cursorFromCaller && r.chunkedHead) base4.k = 1;
28195
- else if (prev?.k && !completesChunked && !(cursorFromCaller && r.full)) base4.k = 1;
28196
- const layout = cursorFromCaller ? r.layout : prev?.L;
28197
- if (layout) base4.L = layout;
28198
- forServer[r.id] = base4;
28199
- }
28200
- persist(data);
28201
- }
28202
- function fieldNeedsScan(row, field, mtime, force = false) {
28203
- if (force) return true;
28204
- const cov = row?.f?.[field.name];
28205
- if (!cov) return true;
28206
- if (cov.v < field.version) return true;
28207
- if (field.mtimeSensitive && (cov.m ?? 0) < Math.floor(mtime)) return true;
28208
- return false;
28209
- }
28210
- function markFieldCoverage(server, field, rows) {
28211
- if (rows.length === 0) return;
28212
- const data = load();
28213
- const forServer = data[server] || (data[server] = {});
28214
- for (const r of rows) {
28215
- const row = toRow(forServer[r.id]) ?? { m: 0, v: 0 };
28216
- const f = row.f ? { ...row.f } : {};
28217
- f[field.name] = { v: field.version, p: r.present ? 1 : 0, m: Math.floor(r.mtime) };
28218
- forServer[r.id] = { ...row, f };
28219
- }
28220
- persist(data);
28221
- }
28222
- function loadReconcile() {
28223
- if (reconcileCache) return reconcileCache;
28224
- try {
28225
- const parsed = JSON.parse(readFileSync35(reconcilePath(), "utf-8"));
28226
- reconcileCache = parsed && typeof parsed === "object" ? parsed : {};
28227
- } catch {
28228
- reconcileCache = {};
28229
- }
28230
- return reconcileCache;
28231
- }
28232
- function persistReconcile(data) {
28233
- const path = reconcilePath();
28234
- mkdirSync7(dirname16(path), { recursive: true });
28235
- const tmp = `${path}.tmp`;
28236
- writeFileSync7(tmp, JSON.stringify(data));
28237
- renameSync4(tmp, path);
28238
- }
28239
- function stateFor(server) {
28240
- const data = loadReconcile();
28241
- return data[server] || (data[server] = { reconciled: {}, force: {} });
28242
- }
28243
- function fieldNeedsFullPass(server, field) {
28244
- const st = stateFor(server);
28245
- return st.force[field.name] === true || (st.reconciled[field.name] ?? 0) < field.version;
28246
- }
28247
- function markFieldFullPassDone(server, field) {
28248
- const data = loadReconcile();
28249
- const st = data[server] || (data[server] = { reconciled: {}, force: {} });
28250
- st.reconciled[field.name] = field.version;
28251
- delete st.force[field.name];
28252
- persistReconcile(data);
28253
- }
28254
- function forgetFullCoverage(server, sessionId) {
28255
- const data = load();
28256
- const row = data[server]?.[sessionId];
28257
- if (!row || typeof row !== "object") return;
28258
- delete row.F;
28259
- delete row.h;
28260
- persist(data);
28261
- }
28262
- function markFullResync(server, sessionId) {
28263
- const data = load();
28264
- const forServer = data[server];
28265
- if (!forServer) return;
28266
- if (!(sessionId in forServer)) return;
28267
- delete forServer[sessionId];
28268
- persist(data);
28269
- }
28270
- function fullCoveredOffset(row) {
28271
- if (row.F !== void 0) return row.F;
28272
- return row.h ? row.s ?? 0 : 0;
28273
- }
28274
- function syncMode(row, mtime, fileSize, extractorVersion, isAppendOnly, nowMs = Date.now()) {
28275
- if (!row) return "full";
28276
- if (row.v < extractorVersion) return "full";
28277
- const offset = row.o ?? 0;
28278
- if (isAppendOnly && offset > 0 && fileSize > 0 && fileSize < offset) return "full";
28279
- if (process.env.CHAT_RECALL_TAIL_APPEND !== "0" && isAppendOnly && fileSize > 0 && offset > 0 && fileSize > (row.s ?? 0)) {
28280
- return "append";
28281
- }
28282
- if (isAppendOnly && offset > 0 && fileSize > 0 && fileSize === (row.s ?? 0) && !row.k && fullCoveredOffset(row) < offset && nowMs - Math.floor(mtime) >= SETTLE_QUIET_MS) {
28283
- return "full";
28284
- }
28285
- if (row.m >= Math.floor(mtime)) return "skip";
28286
- return "full";
28287
- }
28288
- var ledgerPath, cache3, base, diskStamp, rowKey, LEDGER_FLUSH_MS, pendingWrite, flushTimer, itemVersionsPath, itemVersionsCache, inventoryPath, unackedCursorAttempts, reconcilePath, reconcileCache, SETTLE_QUIET_MS;
28289
- var init_sync_ledger = __esm({
28290
- "src/sync-ledger.ts"() {
28291
- "use strict";
28292
- init_paths();
28293
- init_extractor_version();
28294
- ledgerPath = () => join43(getDataDir(), "sync-ledger.json");
28295
- cache3 = null;
28296
- base = /* @__PURE__ */ new Map();
28297
- diskStamp = null;
28298
- rowKey = (server, id) => `${server}\0${id}`;
28299
- LEDGER_FLUSH_MS = 2e3;
28300
- pendingWrite = false;
28301
- flushTimer = null;
28302
- itemVersionsPath = () => join43(getDataDir(), "item-versions.json");
28303
- itemVersionsCache = null;
28304
- inventoryPath = () => join43(getDataDir(), "toolkit-inventory.json");
28305
- unackedCursorAttempts = 0;
28306
- reconcilePath = () => join43(getDataDir(), "sync-field-reconcile.json");
28307
- reconcileCache = null;
28308
- SETTLE_QUIET_MS = 2 * 60 * 60 * 1e3;
28309
- }
28310
- });
28311
-
28312
28615
  // ../engine/dist/core/sync-fields.js
28313
28616
  var SYNC_FIELDS;
28314
28617
  var init_sync_fields = __esm({
@@ -28335,7 +28638,7 @@ var init_sync_fields = __esm({
28335
28638
  });
28336
28639
 
28337
28640
  // ../engine/dist/core/index-lock.js
28338
- import { existsSync as existsSync41, mkdirSync as mkdirSync8, openSync as openSync9, writeFileSync as writeFileSync8, readFileSync as readFileSync36, rmSync as rmSync4, statSync as statSync38, closeSync as closeSync9 } from "fs";
28641
+ import { existsSync as existsSync41, mkdirSync as mkdirSync8, openSync as openSync9, writeFileSync as writeFileSync8, readFileSync as readFileSync37, rmSync as rmSync4, statSync as statSync38, closeSync as closeSync9 } from "fs";
28339
28642
  import { dirname as dirname17, join as join44 } from "path";
28340
28643
  function acquireIndexLock(opts) {
28341
28644
  const lockPath = lockFilePath(opts.file);
@@ -28367,7 +28670,7 @@ function acquireIndexLock(opts) {
28367
28670
  return;
28368
28671
  released = true;
28369
28672
  try {
28370
- const current = JSON.parse(readFileSync36(lockPath, "utf-8"));
28673
+ const current = JSON.parse(readFileSync37(lockPath, "utf-8"));
28371
28674
  if (current.pid !== holder.pid || current.startedAt !== holder.startedAt)
28372
28675
  return;
28373
28676
  } catch {
@@ -28389,7 +28692,7 @@ function stealStaleLock(lockPath, staleAfterMs) {
28389
28692
  const age = Date.now() - s.mtimeMs;
28390
28693
  let payload;
28391
28694
  try {
28392
- payload = JSON.parse(readFileSync36(lockPath, "utf-8"));
28695
+ payload = JSON.parse(readFileSync37(lockPath, "utf-8"));
28393
28696
  } catch {
28394
28697
  rmSync4(lockPath, { force: true });
28395
28698
  return true;
@@ -28426,44 +28729,6 @@ var init_index_lock = __esm({
28426
28729
  }
28427
28730
  });
28428
28731
 
28429
- // src/http.ts
28430
- var http_exports = {};
28431
- __export(http_exports, {
28432
- cliVersion: () => cliVersion,
28433
- clientHeaders: () => clientHeaders,
28434
- fetchWithTimeout: () => fetchWithTimeout
28435
- });
28436
- import { readFileSync as readFileSync37 } from "node:fs";
28437
- function cliVersion() {
28438
- return CLI_VERSION;
28439
- }
28440
- function clientHeaders() {
28441
- return {
28442
- "x-chat-recall-cli": CLI_VERSION,
28443
- "x-chat-recall-os": `${process.platform}-${process.arch}`
28444
- };
28445
- }
28446
- function fetchWithTimeout(url, init = {}, ms = 15e3) {
28447
- const headers = new Headers(clientHeaders());
28448
- new Headers(init.headers ?? {}).forEach((v, k) => headers.set(k, v));
28449
- return fetch(url, { ...init, headers, signal: init.signal ?? AbortSignal.timeout(ms) });
28450
- }
28451
- var CLI_VERSION;
28452
- var init_http = __esm({
28453
- "src/http.ts"() {
28454
- "use strict";
28455
- CLI_VERSION = "0.0.0";
28456
- try {
28457
- CLI_VERSION = JSON.parse(readFileSync37(new URL("../package.json", import.meta.url), "utf-8")).version || CLI_VERSION;
28458
- } catch {
28459
- try {
28460
- if (typeof __CLI_VERSION__ === "string") CLI_VERSION = __CLI_VERSION__;
28461
- } catch {
28462
- }
28463
- }
28464
- }
28465
- });
28466
-
28467
28732
  // src/redact-deep.ts
28468
28733
  function redactDeep(v, count) {
28469
28734
  if (typeof v === "string") return redactSecrets(v, { force: true, count });
@@ -30624,6 +30889,7 @@ async function syncToTargetInScope(cred, opts = {}) {
30624
30889
  };
30625
30890
  };
30626
30891
  const base4 = cred.serverUrl.replace(/\/$/, "");
30892
+ if (opts.useLedger) await reconcileLedgerIfDue(base4, cred.token);
30627
30893
  const ledger = opts.useLedger ? getSyncedRows(base4) : null;
30628
30894
  const convBatch = makeBatcher("conversations", 25, false, (rows) => {
30629
30895
  try {
@@ -30722,7 +30988,10 @@ async function syncToTargetInScope(cred, opts = {}) {
30722
30988
  };
30723
30989
  let appendBatch = [];
30724
30990
  let appendBatchBytes = 0;
30725
- const APPEND_BATCH_SIZE = 50;
30991
+ const APPEND_BATCH_SIZE = (() => {
30992
+ const n = Number(process.env.CHAT_RECALL_APPEND_BATCH_MAX);
30993
+ return Number.isInteger(n) && n > 0 ? n : 10;
30994
+ })();
30726
30995
  const APPEND_BATCH_MAX_BYTES = SYNC_CHUNK_BYTES;
30727
30996
  const appendFlush = async () => {
30728
30997
  if (appendBatch.length === 0) return;
@@ -31148,16 +31417,18 @@ async function syncToTargetInScope(cred, opts = {}) {
31148
31417
  }
31149
31418
  }
31150
31419
  if (ledger && mayTombstone({ changedWalk, listed: refs.length, sliceSize: slice.length, paused: walkPaused })) {
31151
- const tombstones = [];
31152
- for (const [sessionId] of ledger) {
31153
- if (!localSessionIds.has(sessionId)) {
31154
- tombstones.push({ session_id: sessionId, deleted_at: Date.now() });
31155
- }
31156
- }
31157
- if (tombstones.length > 0) {
31158
- await post({ tombstones });
31420
+ const mode = tombstoneMode();
31421
+ const plan = mode === "off" ? { ids: [], refused: null } : planTombstones({
31422
+ ledgerIds: ledger.keys(),
31423
+ visited: localSessionIds,
31424
+ probe: probeSessionSource
31425
+ });
31426
+ if (plan.ids.length > 0) console.error(describeTombstonePlan(plan, mode));
31427
+ if (mode === "act" && plan.refused === null && plan.ids.length > 0) {
31428
+ const deletedAt = Date.now();
31429
+ await post({ tombstones: plan.ids.map((session_id) => ({ session_id, deleted_at: deletedAt })) });
31159
31430
  const data = getLedgerData(base4);
31160
- for (const t of tombstones) delete data[t.session_id];
31431
+ for (const id of plan.ids) delete data[id];
31161
31432
  persistLedgerData(base4, data);
31162
31433
  }
31163
31434
  }
@@ -31658,6 +31929,9 @@ var init_sync_client = __esm({
31658
31929
  init_settings();
31659
31930
  init_paths();
31660
31931
  init_walk_budget();
31932
+ init_tombstone_rule();
31933
+ init_session_source_probe();
31934
+ init_ledger_reconcile();
31661
31935
  init_tool_backend();
31662
31936
  init_transcript();
31663
31937
  init_claude2();
@@ -41676,6 +41950,30 @@ ${t.serverUrl}`));
41676
41950
  }
41677
41951
  }
41678
41952
  }
41953
+ try {
41954
+ const { fetchServerSessions: fetchServerSessions2, planReconcile: planReconcile2 } = await Promise.resolve().then(() => (init_ledger_reconcile(), ledger_reconcile_exports));
41955
+ const { getSyncedRows: getSyncedRows2 } = await Promise.resolve().then(() => (init_sync_ledger(), sync_ledger_exports));
41956
+ const list = await fetchServerSessions2(t.serverUrl, t.token);
41957
+ const plan = planReconcile2({ ledger: getSyncedRows2(t.serverUrl), serverIds: list.ids, deletedIds: list.deleted, limit: Infinity });
41958
+ if (plan.missing.length === 0) {
41959
+ console.log(chalk2.green(" \u2713 the server lists every session the ledger marks as synced"));
41960
+ } else {
41961
+ exitCode = 2;
41962
+ console.log(chalk2.red(` \u2717 ${plan.missing.length} session(s) are in the ledger and not on the server:`));
41963
+ for (const id of plan.missing.slice(0, 25)) console.log(` ${id}`);
41964
+ if (plan.missing.length > 25) console.log(chalk2.dim(` \u2026and ${plan.missing.length - 25} more`));
41965
+ if (opts.repair) {
41966
+ const { forgetSessions: forgetSessions2 } = await Promise.resolve().then(() => (init_sync_ledger(), sync_ledger_exports));
41967
+ const n = forgetSessions2(t.serverUrl, plan.missing);
41968
+ console.log(chalk2.green(` \u21BB cleared ${n} ledger row(s) \u2014 run \`chat-recall sync\` to send them`));
41969
+ } else {
41970
+ console.log(chalk2.dim(" Re-run with --repair to clear their ledger rows and send them."));
41971
+ }
41972
+ }
41973
+ } catch (e) {
41974
+ console.error(chalk2.red(` could not list the sessions of ${t.serverUrl}: ${e instanceof Error ? e.message : e}`));
41975
+ exitCode = 1;
41976
+ }
41679
41977
  if (opts.repair && report.stranded.length > 0) {
41680
41978
  const n = forceFullResync2(t.serverUrl, report.stranded.map((f) => f.sessionId));
41681
41979
  console.log(chalk2.green(` \u21BB cleared ${n} ledger cursor(s) \u2014 run \`chat-recall sync\` to re-ship`));