@wipcomputer/memory-crystal 0.7.32 → 0.7.34-alpha.1

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.
Files changed (155) hide show
  1. package/SKILL.md +1 -1
  2. package/cloud/wrangler.toml +30 -0
  3. package/dist/bridge.d.ts +7 -0
  4. package/dist/bridge.js +14 -0
  5. package/dist/bulk-copy.d.ts +17 -0
  6. package/dist/bulk-copy.js +90 -0
  7. package/dist/cc-hook.d.ts +8 -0
  8. package/dist/cc-hook.js +368 -0
  9. package/dist/cc-poller.d.ts +1 -0
  10. package/dist/cc-poller.js +550 -0
  11. package/dist/chunk-25LXQJ4Z.js +110 -0
  12. package/dist/chunk-2DRXIRQW.js +97 -0
  13. package/dist/chunk-2GBYLMEF.js +1385 -0
  14. package/dist/chunk-2ZNH5F6E.js +1281 -0
  15. package/dist/chunk-3G3SFYYI.js +288 -0
  16. package/dist/chunk-3RG5ZIWI.js +10 -0
  17. package/dist/chunk-3S6TI23B.js +97 -0
  18. package/dist/chunk-3VFIJYS4.js +818 -0
  19. package/dist/chunk-437F27T6.js +97 -0
  20. package/dist/chunk-52QE3YI3.js +1169 -0
  21. package/dist/chunk-57RP3DIN.js +1205 -0
  22. package/dist/chunk-5HSZ4W2P.js +62 -0
  23. package/dist/chunk-5I7GMRDN.js +146 -0
  24. package/dist/chunk-645IPXW3.js +290 -0
  25. package/dist/chunk-7A7ELD4C.js +1205 -0
  26. package/dist/chunk-7FYY4GZM.js +1205 -0
  27. package/dist/chunk-7IUE7ODU.js +254 -0
  28. package/dist/chunk-7RMLKZIS.js +108 -0
  29. package/dist/chunk-AA3OPP4Z.js +432 -0
  30. package/dist/chunk-AEWLSYPH.js +72 -0
  31. package/dist/chunk-ASSZDR6I.js +108 -0
  32. package/dist/chunk-AYRJVWUC.js +1205 -0
  33. package/dist/chunk-CCYI5O3D.js +148 -0
  34. package/dist/chunk-CGIDSAJB.js +288 -0
  35. package/dist/chunk-D3I3ZSE2.js +411 -0
  36. package/dist/chunk-D3MACYZ4.js +108 -0
  37. package/dist/chunk-DACSKLY6.js +219 -0
  38. package/dist/chunk-DFQ72B7M.js +248 -0
  39. package/dist/chunk-DW5B4BL7.js +108 -0
  40. package/dist/chunk-EKSACBTJ.js +1070 -0
  41. package/dist/chunk-EXEZZADG.js +248 -0
  42. package/dist/chunk-F3Y7EL7K.js +83 -0
  43. package/dist/chunk-FBQWSDPC.js +1328 -0
  44. package/dist/chunk-FHRZNOMW.js +1205 -0
  45. package/dist/chunk-IM7N24MT.js +129 -0
  46. package/dist/chunk-IPNYIXFK.js +1178 -0
  47. package/dist/chunk-J7MRSZIO.js +167 -0
  48. package/dist/chunk-JITKI2OI.js +106 -0
  49. package/dist/chunk-JWZXYVET.js +1068 -0
  50. package/dist/chunk-KCQUXVYT.js +108 -0
  51. package/dist/chunk-KOQ43OX6.js +1281 -0
  52. package/dist/chunk-KYVWO6ZM.js +1069 -0
  53. package/dist/chunk-L3VHARQH.js +413 -0
  54. package/dist/chunk-LBWDS6BE.js +288 -0
  55. package/dist/chunk-LOVAHSQV.js +411 -0
  56. package/dist/chunk-LQOYCAGG.js +446 -0
  57. package/dist/chunk-LWAIPJ2W.js +146 -0
  58. package/dist/chunk-M5DHKW7M.js +127 -0
  59. package/dist/chunk-MBKCIJHM.js +1328 -0
  60. package/dist/chunk-MK42FMEG.js +147 -0
  61. package/dist/chunk-MOBMYHKL.js +1205 -0
  62. package/dist/chunk-MPLTNMRG.js +67 -0
  63. package/dist/chunk-NIJCVN3O.js +147 -0
  64. package/dist/chunk-NX647OM3.js +310 -0
  65. package/dist/chunk-NZCFSZQ7.js +1205 -0
  66. package/dist/chunk-O2UITJGH.js +465 -0
  67. package/dist/chunk-OCRA44AZ.js +108 -0
  68. package/dist/chunk-P3KJR66H.js +117 -0
  69. package/dist/chunk-PEK6JH65.js +432 -0
  70. package/dist/chunk-PJ6FFKEX.js +77 -0
  71. package/dist/chunk-PLUBBZYR.js +800 -0
  72. package/dist/chunk-PNKVD2UK.js +26 -0
  73. package/dist/chunk-PSQZURHO.js +229 -0
  74. package/dist/chunk-SGL6ISBJ.js +1061 -0
  75. package/dist/chunk-SJABZZT5.js +97 -0
  76. package/dist/chunk-TD3P3K32.js +1199 -0
  77. package/dist/chunk-TMDZJJKV.js +288 -0
  78. package/dist/chunk-UNHVZB5G.js +411 -0
  79. package/dist/chunk-VAFTWSTE.js +1061 -0
  80. package/dist/chunk-VNFXFQBB.js +217 -0
  81. package/dist/chunk-X3GVFKSJ.js +1205 -0
  82. package/dist/chunk-XZ3S56RQ.js +1061 -0
  83. package/dist/chunk-Y72C7F6O.js +148 -0
  84. package/dist/chunk-YLICP577.js +1205 -0
  85. package/dist/chunk-YX6AXLVK.js +159 -0
  86. package/dist/chunk-ZCQYHTNU.js +146 -0
  87. package/dist/cli.d.ts +1 -0
  88. package/dist/cli.js +1160 -0
  89. package/dist/cloud-crystal.js +6 -0
  90. package/dist/core.d.ts +252 -0
  91. package/dist/core.js +12 -0
  92. package/dist/crypto.d.ts +20 -0
  93. package/dist/crypto.js +27 -0
  94. package/dist/crystal-capture.sh +29 -0
  95. package/dist/crystal-serve.d.ts +4 -0
  96. package/dist/crystal-serve.js +252 -0
  97. package/dist/dev-update-SZ2Z4WCQ.js +6 -0
  98. package/dist/discover.d.ts +30 -0
  99. package/dist/discover.js +177 -0
  100. package/dist/doctor.d.ts +9 -0
  101. package/dist/doctor.js +342 -0
  102. package/dist/dream-weaver.d.ts +8 -0
  103. package/dist/dream-weaver.js +56 -0
  104. package/dist/file-sync.d.ts +48 -0
  105. package/dist/file-sync.js +18 -0
  106. package/dist/installer.d.ts +61 -0
  107. package/dist/installer.js +772 -0
  108. package/dist/ldm-backup.sh +116 -0
  109. package/dist/ldm.d.ts +50 -0
  110. package/dist/ldm.js +32 -0
  111. package/dist/llm-XXLYPIOF.js +16 -0
  112. package/dist/mcp-server.d.ts +1 -0
  113. package/dist/mcp-server.js +277 -0
  114. package/dist/migrate.d.ts +1 -0
  115. package/dist/migrate.js +89 -0
  116. package/dist/mirror-sync.d.ts +1 -0
  117. package/dist/mirror-sync.js +159 -0
  118. package/dist/mlx-setup-XKU67WCT.js +289 -0
  119. package/dist/oc-backfill.d.ts +19 -0
  120. package/dist/oc-backfill.js +74 -0
  121. package/dist/openclaw.d.ts +5 -0
  122. package/dist/openclaw.js +434 -0
  123. package/dist/pair.d.ts +4 -0
  124. package/dist/pair.js +75 -0
  125. package/dist/poller.d.ts +1 -0
  126. package/dist/poller.js +634 -0
  127. package/dist/role.d.ts +24 -0
  128. package/dist/role.js +13 -0
  129. package/dist/search-pipeline-4K4OJSSS.js +255 -0
  130. package/dist/search-pipeline-4PRS6LI7.js +280 -0
  131. package/dist/search-pipeline-7UJMXPLO.js +280 -0
  132. package/dist/search-pipeline-CBV25NX7.js +99 -0
  133. package/dist/search-pipeline-DQTRLGBH.js +74 -0
  134. package/dist/search-pipeline-HNG37REH.js +282 -0
  135. package/dist/search-pipeline-IZFPLBUB.js +280 -0
  136. package/dist/search-pipeline-MID6F26Q.js +73 -0
  137. package/dist/search-pipeline-N52JZFNN.js +282 -0
  138. package/dist/search-pipeline-OPB2PRQQ.js +280 -0
  139. package/dist/search-pipeline-VXTE5HAD.js +262 -0
  140. package/dist/search-pipeline-XHFKADRG.js +73 -0
  141. package/dist/staging.d.ts +29 -0
  142. package/dist/staging.js +21 -0
  143. package/dist/summarize.d.ts +19 -0
  144. package/dist/summarize.js +10 -0
  145. package/dist/worker-demo.js +186 -0
  146. package/dist/worker-mcp.js +404 -0
  147. package/dist/worker.js +137 -0
  148. package/package.json +15 -1
  149. package/.env.example +0 -20
  150. package/.publish-skill.json +0 -1
  151. package/CHANGELOG.md +0 -1372
  152. package/README-ENTERPRISE.md +0 -226
  153. package/RELAY.md +0 -199
  154. package/wrangler-demo.toml +0 -8
  155. package/wrangler-mcp.toml +0 -24
@@ -0,0 +1,62 @@
1
+ // src/bridge.ts
2
+ import { existsSync, readFileSync, writeFileSync } from "fs";
3
+ import { execSync } from "child_process";
4
+ import { join } from "path";
5
+ var HOME = process.env.HOME || "";
6
+ function isBridgeInstalled() {
7
+ try {
8
+ execSync("which lesa 2>/dev/null", { encoding: "utf-8" });
9
+ return true;
10
+ } catch {
11
+ return false;
12
+ }
13
+ }
14
+ function isBridgeRegistered() {
15
+ const mcpPath = join(HOME, ".claude", ".mcp.json");
16
+ try {
17
+ if (existsSync(mcpPath)) {
18
+ const config = JSON.parse(readFileSync(mcpPath, "utf-8"));
19
+ if (config.mcpServers && config.mcpServers["lesa-bridge"]) return true;
20
+ }
21
+ } catch {
22
+ }
23
+ return false;
24
+ }
25
+ function isBridgeDesktopRegistered() {
26
+ const desktopConfig = join(HOME, "Library", "Application Support", "Claude", "claude_desktop_config.json");
27
+ try {
28
+ if (existsSync(desktopConfig)) {
29
+ const config = JSON.parse(readFileSync(desktopConfig, "utf-8"));
30
+ if (config.mcpServers && config.mcpServers["lesa-bridge"]) return true;
31
+ }
32
+ } catch {
33
+ }
34
+ return false;
35
+ }
36
+ function registerBridgeMcp() {
37
+ execSync("claude mcp add --scope user lesa-bridge -- lesa", {
38
+ encoding: "utf-8",
39
+ stdio: "pipe"
40
+ });
41
+ }
42
+ function registerBridgeDesktop() {
43
+ const desktopConfig = join(HOME, "Library", "Application Support", "Claude", "claude_desktop_config.json");
44
+ if (!existsSync(desktopConfig)) return false;
45
+ try {
46
+ const config = JSON.parse(readFileSync(desktopConfig, "utf-8"));
47
+ if (!config.mcpServers) config.mcpServers = {};
48
+ config.mcpServers["lesa-bridge"] = { command: "lesa" };
49
+ writeFileSync(desktopConfig, JSON.stringify(config, null, 2) + "\n");
50
+ return true;
51
+ } catch {
52
+ return false;
53
+ }
54
+ }
55
+
56
+ export {
57
+ isBridgeInstalled,
58
+ isBridgeRegistered,
59
+ isBridgeDesktopRegistered,
60
+ registerBridgeMcp,
61
+ registerBridgeDesktop
62
+ };
@@ -0,0 +1,146 @@
1
+ import {
2
+ ensureLdm,
3
+ ldmPaths
4
+ } from "./chunk-DFQ72B7M.js";
5
+
6
+ // src/staging.ts
7
+ import {
8
+ existsSync,
9
+ mkdirSync,
10
+ readdirSync,
11
+ renameSync,
12
+ unlinkSync,
13
+ writeFileSync
14
+ } from "fs";
15
+ import { join } from "path";
16
+ import { execSync } from "child_process";
17
+ var HOME = process.env.HOME || "";
18
+ var STAGING_ROOT = join(HOME, ".ldm", "staging");
19
+ function stagingPaths(agentId) {
20
+ const root = join(STAGING_ROOT, agentId);
21
+ return {
22
+ root,
23
+ transcripts: join(root, "transcripts"),
24
+ readyFile: join(root, "READY")
25
+ };
26
+ }
27
+ function ensureStaging(agentId) {
28
+ const paths = stagingPaths(agentId);
29
+ mkdirSync(paths.transcripts, { recursive: true });
30
+ return paths;
31
+ }
32
+ function markReady(agentId) {
33
+ const paths = stagingPaths(agentId);
34
+ writeFileSync(paths.readyFile, JSON.stringify({
35
+ markedAt: (/* @__PURE__ */ new Date()).toISOString(),
36
+ agentId
37
+ }));
38
+ }
39
+ function isNewAgent(agentId) {
40
+ const paths = ldmPaths(agentId);
41
+ return !existsSync(paths.agentRoot);
42
+ }
43
+ function hasStagedData(agentId) {
44
+ const paths = stagingPaths(agentId);
45
+ return existsSync(paths.readyFile);
46
+ }
47
+ function listStagedAgents() {
48
+ if (!existsSync(STAGING_ROOT)) return [];
49
+ const agents = [];
50
+ for (const entry of readdirSync(STAGING_ROOT, { withFileTypes: true })) {
51
+ if (!entry.isDirectory()) continue;
52
+ if (existsSync(join(STAGING_ROOT, entry.name, "READY"))) {
53
+ agents.push(entry.name);
54
+ }
55
+ }
56
+ return agents;
57
+ }
58
+ async function processStagedAgent(agentId) {
59
+ const startTime = Date.now();
60
+ const staging = stagingPaths(agentId);
61
+ if (!existsSync(staging.readyFile)) {
62
+ throw new Error(`No READY file for agent ${agentId}`);
63
+ }
64
+ const agentPaths = ensureLdm(agentId);
65
+ const stagedFiles = existsSync(staging.transcripts) ? readdirSync(staging.transcripts).filter((f) => f.endsWith(".jsonl")) : [];
66
+ if (stagedFiles.length === 0) {
67
+ unlinkSync(staging.readyFile);
68
+ return {
69
+ agentId,
70
+ transcriptsProcessed: 0,
71
+ backfillChunks: 0,
72
+ dreamWeaverRan: false,
73
+ durationMs: Date.now() - startTime
74
+ };
75
+ }
76
+ for (const file of stagedFiles) {
77
+ const src = join(staging.transcripts, file);
78
+ const dest = join(agentPaths.transcripts, file);
79
+ try {
80
+ renameSync(src, dest);
81
+ } catch {
82
+ const { copyFileSync } = await import("fs");
83
+ copyFileSync(src, dest);
84
+ unlinkSync(src);
85
+ }
86
+ }
87
+ let backfillChunks = 0;
88
+ let dreamWeaverRan = false;
89
+ try {
90
+ const output = execSync(
91
+ `crystal backfill --agent ${agentId}`,
92
+ { encoding: "utf-8", timeout: 6e5 }
93
+ );
94
+ const match = output.match(/(\d+) chunks embedded/);
95
+ if (match) backfillChunks = parseInt(match[1], 10);
96
+ } catch (err) {
97
+ process.stderr.write(`[staging] backfill failed for ${agentId}: ${err.message}
98
+ `);
99
+ }
100
+ try {
101
+ execSync(
102
+ `crystal dream-weave --agent ${agentId} --mode full`,
103
+ { encoding: "utf-8", timeout: 6e5 }
104
+ );
105
+ dreamWeaverRan = true;
106
+ } catch (err) {
107
+ process.stderr.write(`[staging] dream-weave failed for ${agentId}: ${err.message}
108
+ `);
109
+ }
110
+ try {
111
+ unlinkSync(staging.readyFile);
112
+ } catch {
113
+ }
114
+ return {
115
+ agentId,
116
+ transcriptsProcessed: stagedFiles.length,
117
+ backfillChunks,
118
+ dreamWeaverRan,
119
+ durationMs: Date.now() - startTime
120
+ };
121
+ }
122
+ async function processAllStaged() {
123
+ const agents = listStagedAgents();
124
+ const results = [];
125
+ for (const agentId of agents) {
126
+ try {
127
+ const result = await processStagedAgent(agentId);
128
+ results.push(result);
129
+ } catch (err) {
130
+ process.stderr.write(`[staging] failed to process ${agentId}: ${err.message}
131
+ `);
132
+ }
133
+ }
134
+ return results;
135
+ }
136
+
137
+ export {
138
+ stagingPaths,
139
+ ensureStaging,
140
+ markReady,
141
+ isNewAgent,
142
+ hasStagedData,
143
+ listStagedAgents,
144
+ processStagedAgent,
145
+ processAllStaged
146
+ };
@@ -0,0 +1,290 @@
1
+ import {
2
+ decrypt,
3
+ decryptJSON,
4
+ encrypt,
5
+ encryptJSON,
6
+ loadRelayKey
7
+ } from "./chunk-25LXQJ4Z.js";
8
+ import {
9
+ init_ldm,
10
+ ldmPaths,
11
+ resolveStatePath,
12
+ stateWritePath
13
+ } from "./chunk-PSQZURHO.js";
14
+
15
+ // src/file-sync.ts
16
+ init_ldm();
17
+ import { createHash } from "crypto";
18
+ import {
19
+ existsSync,
20
+ mkdirSync,
21
+ readFileSync,
22
+ writeFileSync,
23
+ unlinkSync,
24
+ readdirSync,
25
+ statSync
26
+ } from "fs";
27
+ import { join, relative, dirname } from "path";
28
+ var RELAY_URL = process.env.CRYSTAL_RELAY_URL || "";
29
+ var RELAY_TOKEN = process.env.CRYSTAL_RELAY_TOKEN || "";
30
+ var EXCLUDE_PATTERNS = [
31
+ "memory/crystal.db",
32
+ // DB syncs via delta chunks, not file copy
33
+ "memory/crystal.db-wal",
34
+ "memory/crystal.db-shm",
35
+ "memory/crystal.db.bak",
36
+ "memory/crystal.db.tmp",
37
+ "memory/lance/",
38
+ // LanceDB (deprecated, not synced)
39
+ "state/",
40
+ // Local state files (watermarks, etc.)
41
+ "secrets/",
42
+ // Encryption keys, tokens
43
+ "staging/",
44
+ // Staging pipeline (Core-only)
45
+ "bin/",
46
+ // Local scripts
47
+ ".DS_Store"
48
+ ];
49
+ function shouldExclude(relativePath) {
50
+ for (const pattern of EXCLUDE_PATTERNS) {
51
+ if (relativePath === pattern || relativePath.startsWith(pattern)) return true;
52
+ }
53
+ const parts = relativePath.split("/");
54
+ for (const part of parts) {
55
+ if (part.startsWith(".") && part !== ".ldm") return true;
56
+ }
57
+ return false;
58
+ }
59
+ function scanDir(baseDir, currentDir, entries) {
60
+ if (!existsSync(currentDir)) return;
61
+ const items = readdirSync(currentDir);
62
+ for (const item of items) {
63
+ const fullPath = join(currentDir, item);
64
+ const relPath = relative(baseDir, fullPath);
65
+ if (shouldExclude(relPath)) continue;
66
+ let stat;
67
+ try {
68
+ stat = statSync(fullPath);
69
+ } catch {
70
+ continue;
71
+ }
72
+ if (stat.isDirectory()) {
73
+ scanDir(baseDir, fullPath, entries);
74
+ } else if (stat.isFile()) {
75
+ if (stat.size > 50 * 1024 * 1024) continue;
76
+ const content = readFileSync(fullPath);
77
+ const sha256 = createHash("sha256").update(content).digest("hex");
78
+ entries.push({ path: relPath, sha256, size: stat.size });
79
+ }
80
+ }
81
+ }
82
+ function generateManifest() {
83
+ const paths = ldmPaths();
84
+ const entries = [];
85
+ scanDir(paths.root, paths.root, entries);
86
+ return {
87
+ version: 1,
88
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
89
+ fileCount: entries.length,
90
+ entries
91
+ };
92
+ }
93
+ function compareManifest(coreManifest) {
94
+ const paths = ldmPaths();
95
+ const upsert = [];
96
+ const toDelete = [];
97
+ const localManifest = generateManifest();
98
+ const localMap = new Map(localManifest.entries.map((e) => [e.path, e]));
99
+ const coreMap = new Map(coreManifest.entries.map((e) => [e.path, e]));
100
+ for (const entry of coreManifest.entries) {
101
+ const local = localMap.get(entry.path);
102
+ if (!local || local.sha256 !== entry.sha256) {
103
+ upsert.push({ path: entry.path, sha256: entry.sha256 });
104
+ }
105
+ }
106
+ for (const entry of localManifest.entries) {
107
+ if (!coreMap.has(entry.path)) {
108
+ toDelete.push(entry.path);
109
+ }
110
+ }
111
+ return { upsert, delete: toDelete };
112
+ }
113
+ function loadFileSyncState() {
114
+ const statePath = resolveStatePath("file-sync-state.json");
115
+ try {
116
+ if (existsSync(statePath)) {
117
+ return JSON.parse(readFileSync(statePath, "utf-8"));
118
+ }
119
+ } catch {
120
+ }
121
+ return { lastSync: null, lastManifestHash: null, filesTransferred: 0, filesDeleted: 0 };
122
+ }
123
+ function saveFileSyncState(state) {
124
+ const writePath = stateWritePath("file-sync-state.json");
125
+ writeFileSync(writePath, JSON.stringify(state, null, 2));
126
+ }
127
+ async function pushFileSync() {
128
+ if (!RELAY_URL || !RELAY_TOKEN) {
129
+ throw new Error("CRYSTAL_RELAY_URL and CRYSTAL_RELAY_TOKEN must be set");
130
+ }
131
+ const relayKey = loadRelayKey();
132
+ const paths = ldmPaths();
133
+ const manifest = generateManifest();
134
+ const manifestJson = JSON.stringify(manifest.entries.map((e) => `${e.path}:${e.sha256}`));
135
+ const manifestHash = createHash("sha256").update(manifestJson).digest("hex");
136
+ const state = loadFileSyncState();
137
+ if (state.lastManifestHash === manifestHash) {
138
+ return { manifest: 0, files: 0 };
139
+ }
140
+ const encryptedManifest = encryptJSON(manifest, relayKey);
141
+ const manifestResp = await fetch(`${RELAY_URL}/drop/files`, {
142
+ method: "POST",
143
+ headers: {
144
+ "Authorization": `Bearer ${RELAY_TOKEN}`,
145
+ "Content-Type": "application/octet-stream",
146
+ "X-File-Type": "manifest"
147
+ },
148
+ body: JSON.stringify(encryptedManifest)
149
+ });
150
+ if (!manifestResp.ok) {
151
+ throw new Error(`Manifest push failed: ${manifestResp.status} ${await manifestResp.text()}`);
152
+ }
153
+ let filesPushed = 0;
154
+ for (const entry of manifest.entries) {
155
+ const fullPath = join(paths.root, entry.path);
156
+ if (!existsSync(fullPath)) continue;
157
+ const content = readFileSync(fullPath);
158
+ const encrypted = encrypt(content, relayKey);
159
+ const filePayload = JSON.stringify({
160
+ path: entry.path,
161
+ sha256: entry.sha256,
162
+ size: entry.size,
163
+ data: encrypted
164
+ });
165
+ const fileResp = await fetch(`${RELAY_URL}/drop/files`, {
166
+ method: "POST",
167
+ headers: {
168
+ "Authorization": `Bearer ${RELAY_TOKEN}`,
169
+ "Content-Type": "application/octet-stream",
170
+ "X-File-Type": "file"
171
+ },
172
+ body: filePayload
173
+ });
174
+ if (fileResp.ok) filesPushed++;
175
+ }
176
+ state.lastSync = (/* @__PURE__ */ new Date()).toISOString();
177
+ state.lastManifestHash = manifestHash;
178
+ state.filesTransferred += filesPushed;
179
+ saveFileSyncState(state);
180
+ return { manifest: manifest.fileCount, files: filesPushed };
181
+ }
182
+ async function pullFileSync() {
183
+ if (!RELAY_URL || !RELAY_TOKEN) {
184
+ throw new Error("CRYSTAL_RELAY_URL and CRYSTAL_RELAY_TOKEN must be set");
185
+ }
186
+ const relayKey = loadRelayKey();
187
+ const paths = ldmPaths();
188
+ const listResp = await fetch(`${RELAY_URL}/pickup/files`, {
189
+ headers: { "Authorization": `Bearer ${RELAY_TOKEN}` }
190
+ });
191
+ if (!listResp.ok) {
192
+ throw new Error(`File sync list failed: ${listResp.status} ${await listResp.text()}`);
193
+ }
194
+ const listData = await listResp.json();
195
+ if (listData.count === 0) {
196
+ return { imported: 0, deleted: 0 };
197
+ }
198
+ let coreManifest = null;
199
+ const fileBlobs = [];
200
+ for (const blob of listData.blobs) {
201
+ try {
202
+ const blobResp = await fetch(`${RELAY_URL}/pickup/files/${blob.id}`, {
203
+ headers: { "Authorization": `Bearer ${RELAY_TOKEN}` }
204
+ });
205
+ if (!blobResp.ok) continue;
206
+ const text = await blobResp.text();
207
+ const parsed = JSON.parse(text);
208
+ if (parsed.v !== void 0 && parsed.nonce !== void 0) {
209
+ try {
210
+ const manifest = decryptJSON(parsed, relayKey);
211
+ if (manifest.version && manifest.entries) {
212
+ coreManifest = manifest;
213
+ }
214
+ } catch {
215
+ }
216
+ } else if (parsed.path && parsed.data) {
217
+ fileBlobs.push({
218
+ id: blob.id,
219
+ path: parsed.path,
220
+ sha256: parsed.sha256,
221
+ data: parsed.data
222
+ });
223
+ }
224
+ await fetch(`${RELAY_URL}/confirm/files/${blob.id}`, {
225
+ method: "DELETE",
226
+ headers: { "Authorization": `Bearer ${RELAY_TOKEN}` }
227
+ });
228
+ } catch (err) {
229
+ process.stderr.write(`[file-sync] error processing blob ${blob.id}: ${err.message}
230
+ `);
231
+ }
232
+ }
233
+ if (!coreManifest) {
234
+ process.stderr.write("[file-sync] no manifest found in relay\n");
235
+ return { imported: 0, deleted: 0 };
236
+ }
237
+ const delta = compareManifest(coreManifest);
238
+ const fileBlobMap = new Map(fileBlobs.map((f) => [f.path, f]));
239
+ let imported = 0;
240
+ for (const entry of delta.upsert) {
241
+ const fileBlob = fileBlobMap.get(entry.path);
242
+ if (!fileBlob) {
243
+ continue;
244
+ }
245
+ try {
246
+ const content = decrypt(fileBlob.data, relayKey);
247
+ const actualHash = createHash("sha256").update(content).digest("hex");
248
+ if (actualHash !== entry.sha256) {
249
+ process.stderr.write(`[file-sync] hash mismatch for ${entry.path}, skipping
250
+ `);
251
+ continue;
252
+ }
253
+ const destPath = join(paths.root, entry.path);
254
+ mkdirSync(dirname(destPath), { recursive: true });
255
+ writeFileSync(destPath, content);
256
+ imported++;
257
+ } catch (err) {
258
+ process.stderr.write(`[file-sync] failed to write ${entry.path}: ${err.message}
259
+ `);
260
+ }
261
+ }
262
+ let deleted = 0;
263
+ for (const path of delta.delete) {
264
+ const destPath = join(paths.root, path);
265
+ if (existsSync(destPath)) {
266
+ try {
267
+ unlinkSync(destPath);
268
+ deleted++;
269
+ } catch (err) {
270
+ process.stderr.write(`[file-sync] failed to delete ${path}: ${err.message}
271
+ `);
272
+ }
273
+ }
274
+ }
275
+ const state = loadFileSyncState();
276
+ state.lastSync = (/* @__PURE__ */ new Date()).toISOString();
277
+ state.filesTransferred += imported;
278
+ state.filesDeleted += deleted;
279
+ saveFileSyncState(state);
280
+ return { imported, deleted };
281
+ }
282
+
283
+ export {
284
+ generateManifest,
285
+ compareManifest,
286
+ loadFileSyncState,
287
+ saveFileSyncState,
288
+ pushFileSync,
289
+ pullFileSync
290
+ };