Spaces:
Paused

8900 commited on
Commit
cf3629f
·
verified ·
1 Parent(s): 4528361

Delete hf-sync-manager.mjs

Browse files
Files changed (1) hide show
  1. hf-sync-manager.mjs +0 -324
hf-sync-manager.mjs DELETED
@@ -1,324 +0,0 @@
1
- // ============================================================
2
- // HF Sync Manager - Full Mirror
3
- //
4
- // Goal: Dataset = OpenClaw runtime data, always in sync.
5
- //
6
- // Boot: Dataset -> ~/.openclaw/ (full restore, then setup patches env vars)
7
- // Runtime: ~/.openclaw/ -> Dataset every 30 min (full mirror)
8
- // On die: SIGTERM uploads immediately
9
- //
10
- // SYNCED (all OpenClaw runtime data):
11
- // openclaw.json - gateway config (user settings preserved via patch mode)
12
- // workspace/ - agent brain
13
- // agents/*/sessions/ - conversation history (bot remembers you)
14
- // agents/*/agent/ - agent state
15
- // devices/ - sub-agent pairing info (survives restart)
16
- // credentials/ - auth
17
- // skills/ - installed skills
18
- // cron/ - scheduled tasks
19
- // memory/ - vector DB
20
- //
21
- // NOT SYNCED (auto-rebuilt):
22
- // agents/*/qmd/ - vector index (rebuilt from markdown)
23
- // canvas/ - UI temp files
24
- // *.tmp *.log
25
- // ============================================================
26
-
27
- import fs from "node:fs";
28
- import path from "node:path";
29
- import { execSync } from "node:child_process";
30
-
31
- var HOME = process.env.OPENCLAW_HOME || process.env.HOME || "/home/user";
32
- var OPENCLAW_DIR = path.join(HOME, ".openclaw");
33
- var WORKSPACE = path.join(OPENCLAW_DIR, "workspace");
34
- var HF_TOKEN = (process.env.HF_TOKEN || "").trim();
35
- var DATASET_ID = (process.env.HF_DATASET_ID || "").trim();
36
- var REPO_DIR = "/tmp/oc-dataset";
37
- var INTERVAL_MS = 30 * 60 * 1000;
38
-
39
- var EXCLUDE_DIRS = ["qmd", "canvas", ".git"];
40
- var EXCLUDE_EXTS = [".tmp", ".log"];
41
-
42
- function log(msg) {
43
- var ts = new Date().toISOString().substring(11, 19);
44
- console.log("[hf-sync " + ts + "] " + msg);
45
- }
46
- function sleep(ms) { return new Promise(function(r) { setTimeout(r, ms); }); }
47
-
48
- function repoUrl() {
49
- return "https://user:" + HF_TOKEN + "@huggingface.co/datasets/" + DATASET_ID;
50
- }
51
-
52
- function git(args, ms) {
53
- return execSync("git " + args, {
54
- cwd: REPO_DIR, stdio: "pipe", timeout: ms || 120000,
55
- env: Object.assign({}, process.env, { GIT_TERMINAL_PROMPT: "0" })
56
- }).toString().trim();
57
- }
58
-
59
- function shouldSkip(name) {
60
- var i;
61
- for (i = 0; i < EXCLUDE_DIRS.length; i++) { if (name === EXCLUDE_DIRS[i]) return true; }
62
- for (i = 0; i < EXCLUDE_EXTS.length; i++) {
63
- if (name.slice(-EXCLUDE_EXTS[i].length) === EXCLUDE_EXTS[i]) return true;
64
- }
65
- return false;
66
- }
67
-
68
- function ensureRepo() {
69
- if (fs.existsSync(path.join(REPO_DIR, ".git"))) return;
70
- execSync("rm -rf " + REPO_DIR, { stdio: "pipe" });
71
- try {
72
- execSync("git clone --depth 1 " + repoUrl() + " " + REPO_DIR, {
73
- stdio: "pipe", timeout: 60000,
74
- env: Object.assign({}, process.env, { GIT_TERMINAL_PROMPT: "0" })
75
- });
76
- log("Cloned Dataset");
77
- } catch (e) {
78
- log("Clone failed, init: " + e.message);
79
- fs.mkdirSync(REPO_DIR, { recursive: true });
80
- execSync("git init " + REPO_DIR, { stdio: "pipe" });
81
- git("remote add origin " + repoUrl());
82
- }
83
- try {
84
- git("config user.email openclaw@hf.space");
85
- git("config user.name OpenClaw-Mirror");
86
- git("config pull.rebase false");
87
- } catch (e) { /* ok */ }
88
- }
89
-
90
- function pullLatest() {
91
- try { git("fetch --quiet origin", 30000); } catch (e) { /* ok */ }
92
- try { git("pull --quiet --no-rebase origin main", 30000); }
93
- catch (e) {
94
- try { git("pull --quiet --no-rebase origin master", 30000); }
95
- catch (e2) { /* empty repo */ }
96
- }
97
- }
98
-
99
- function commitAndPush(label) {
100
- try {
101
- git("add -A");
102
- var changed = git("diff --cached --name-only");
103
- if (!changed) return 0;
104
- var n = changed.split("\n").filter(Boolean).length;
105
- var ts = new Date().toISOString().replace("T", " ").substring(0, 19);
106
- git("commit -m \"" + label + " " + ts + "\"");
107
- try { git("push --quiet origin HEAD:main", 30000); }
108
- catch (e) { git("push --quiet origin HEAD:master", 30000); }
109
- return n;
110
- } catch (e) {
111
- log("Push failed: " + e.message);
112
- return 0;
113
- }
114
- }
115
-
116
- function copyToRepo(src, dst) {
117
- if (!fs.existsSync(src)) return 0;
118
- if (!fs.statSync(src).isDirectory()) {
119
- fs.mkdirSync(path.dirname(dst), { recursive: true });
120
- fs.copyFileSync(src, dst);
121
- return 1;
122
- }
123
- fs.mkdirSync(dst, { recursive: true });
124
- var count = 0;
125
- fs.readdirSync(src).forEach(function(name) {
126
- if (shouldSkip(name)) return;
127
- try { count += copyToRepo(path.join(src, name), path.join(dst, name)); }
128
- catch (e) { log("Copy error [" + name + "]: " + e.message); }
129
- });
130
- return count;
131
- }
132
-
133
- function copyFromRepo(src, dst) {
134
- if (!fs.existsSync(src)) return 0;
135
- if (!fs.statSync(src).isDirectory()) {
136
- fs.mkdirSync(path.dirname(dst), { recursive: true });
137
- fs.copyFileSync(src, dst);
138
- return 1;
139
- }
140
- fs.mkdirSync(dst, { recursive: true });
141
- var count = 0;
142
- fs.readdirSync(src).forEach(function(name) {
143
- if (shouldSkip(name)) return;
144
- try { count += copyFromRepo(path.join(src, name), path.join(dst, name)); }
145
- catch (e) { log("Restore error [" + name + "]: " + e.message); }
146
- });
147
- return count;
148
- }
149
-
150
- function seedWorkspace() {
151
- fs.mkdirSync(WORKSPACE, { recursive: true });
152
- fs.mkdirSync(path.join(WORKSPACE, "memory"), { recursive: true });
153
-
154
- var soul = path.join(WORKSPACE, "SOUL.md");
155
- if (!fs.existsSync(soul)) {
156
- fs.writeFileSync(soul, [
157
- "# Soul", "",
158
- "You are a helpful, warm, concise AI assistant.", "",
159
- "## Language", "",
160
- "Default language: Simplified Chinese.",
161
- "Always reply in Chinese unless the user writes in another language first.", "",
162
- "## Tone", "",
163
- "- Natural and friendly, not overly formal",
164
- "- Concise and to the point"
165
- ].join("\n") + "\n", "utf-8");
166
- log("Seeded SOUL.md");
167
- }
168
- var mem = path.join(WORKSPACE, "MEMORY.md");
169
- if (!fs.existsSync(mem)) {
170
- fs.writeFileSync(mem, [
171
- "# Long-term Memory", "",
172
- "<!-- OpenClaw writes important facts here. -->"
173
- ].join("\n") + "\n", "utf-8");
174
- log("Seeded MEMORY.md");
175
- }
176
- }
177
-
178
- function writeReadme() {
179
- var ts = new Date().toISOString().replace("T", " ").substring(0, 19);
180
- var dirs = [];
181
- try {
182
- dirs = fs.readdirSync(REPO_DIR).filter(function(n) {
183
- if (n === ".git" || n === "README.md") return false;
184
- return fs.statSync(path.join(REPO_DIR, n)).isDirectory();
185
- });
186
- } catch (e) { /* ok */ }
187
- var lines = [
188
- "# OpenClaw Dataset Mirror",
189
- "",
190
- "Full mirror of ~/.openclaw/ - auto-managed, do not edit.",
191
- "",
192
- "Last sync: " + ts,
193
- "",
194
- "## Structure (mirrors ~/.openclaw/ exactly)",
195
- "",
196
- "`",
197
- "openclaw.json <- gateway config (preserved across restarts)",
198
- "workspace/ <- agent brain: SOUL.md, MEMORY.md, daily logs",
199
- "agents/ <- all agent data",
200
- " main/",
201
- " sessions/ <- conversation history (bot memory)",
202
- " agent/ <- agent state",
203
- "devices/ <- sub-agent pairing (survives restart)",
204
- "credentials/ <- auth",
205
- "skills/ <- installed skills",
206
- "cron/ <- scheduled tasks",
207
- "memory/ <- vector database",
208
- "`",
209
- "",
210
- "Found: " + (dirs.length > 0 ? dirs.join(", ") : "(pending first sync)"),
211
- "",
212
- "Not synced: agents/*/qmd/ (vector index, rebuilt on boot), canvas/ (UI temp)"
213
- ];
214
- fs.writeFileSync(path.join(REPO_DIR, "README.md"), lines.join("\n") + "\n", "utf-8");
215
- }
216
-
217
- function bootRestore() {
218
- if (!HF_TOKEN || !DATASET_ID) {
219
- log("No HF_TOKEN/HF_DATASET_ID - skip restore");
220
- seedWorkspace();
221
- return;
222
- }
223
- log("Boot restore from " + DATASET_ID + "…");
224
- try {
225
- ensureRepo();
226
- pullLatest();
227
- } catch (e) {
228
- log("Repo init failed: " + e.message + " - starting fresh");
229
- seedWorkspace();
230
- return;
231
- }
232
- var n = copyFromRepo(REPO_DIR, OPENCLAW_DIR);
233
- if (n > 0) {
234
- log("Restored " + n + " file(s) to " + OPENCLAW_DIR);
235
- log("Includes: conversations, device pairings, skills, config");
236
- } else {
237
- log("No data in Dataset yet - starting fresh");
238
- }
239
- seedWorkspace();
240
- log("Boot restore complete");
241
- }
242
-
243
- function runMirror(label) {
244
- if (!HF_TOKEN || !DATASET_ID) return;
245
- label = label || "mirror";
246
- var ts = new Date().toISOString().replace("T", " ").substring(0, 19);
247
- log("Mirror [" + label + "] at " + ts + "…");
248
- try {
249
- ensureRepo();
250
- pullLatest();
251
-
252
- // Clear all content (except .git and README) then re-copy fresh
253
- fs.readdirSync(REPO_DIR).forEach(function(name) {
254
- if (name === ".git" || name === "README.md") return;
255
- try { execSync("rm -rf " + path.join(REPO_DIR, name), { stdio: "pipe" }); }
256
- catch (e) { /* ok */ }
257
- });
258
-
259
- var n = copyToRepo(OPENCLAW_DIR, REPO_DIR);
260
- log("Copied " + n + " file(s) from local");
261
-
262
- writeReadme();
263
-
264
- var pushed = commitAndPush(label);
265
- if (pushed > 0) {
266
- log("Pushed " + pushed + " file(s) to Dataset");
267
- } else {
268
- log("No changes since last mirror");
269
- }
270
-
271
- } catch (e) {
272
- log("Mirror failed (will retry): " + e.message);
273
- }
274
- }
275
-
276
- var emergencyDone = false;
277
- function emergencyUpload() {
278
- if (emergencyDone) return;
279
- emergencyDone = true;
280
- log("SIGTERM - emergency upload…");
281
- try { runMirror("emergency"); log("Emergency done"); }
282
- catch (e) { log("Emergency failed: " + e.message); }
283
- }
284
-
285
- process.on("SIGTERM", function() { emergencyUpload(); process.exit(0); });
286
- process.on("SIGINT", function() { process.exit(0); });
287
-
288
- (async function() {
289
- log("Starting…");
290
- log("OPENCLAW_DIR : " + OPENCLAW_DIR);
291
- log("DATASET : " + (DATASET_ID || "NOT SET"));
292
- log("Syncing : sessions + devices + skills + config + workspace");
293
-
294
- fs.mkdirSync(OPENCLAW_DIR, { recursive: true });
295
- fs.mkdirSync(WORKSPACE, { recursive: true });
296
-
297
- try {
298
- execSync("git config --global user.email openclaw@hf.space", { stdio: "pipe" });
299
- execSync("git config --global user.name OpenClaw-Mirror", { stdio: "pipe" });
300
- execSync("git config --global http.postBuffer 52428800", { stdio: "pipe" });
301
- execSync("git config --global pull.rebase false", { stdio: "pipe" });
302
- } catch (e) { /* ok */ }
303
-
304
- bootRestore();
305
-
306
- if (!HF_TOKEN || !DATASET_ID) {
307
- log("Sync disabled: set HF_TOKEN and HF_DATASET_ID in Secrets");
308
- return;
309
- }
310
-
311
- log("First mirror in 10 min…");
312
- await sleep(10 * 60 * 1000);
313
-
314
- var cycle = 0;
315
- while (true) {
316
- cycle++;
317
- try { runMirror("mirror-" + cycle); }
318
- catch (e) { log("Cycle " + cycle + " error: " + e.message); }
319
- await sleep(INTERVAL_MS);
320
- }
321
- })().catch(function(e) {
322
- log("Fatal: " + e.message);
323
- emergencyUpload();
324
- });