clone-runner.mjs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. #!/usr/bin/env node
  2. /**
  3. * fmode-agent-clone runner — 数字生命克隆:同步/恢复/建仓
  4. * 零依赖(Node ≥18)。凭据 4 级解析,密钥本体永不入仓。
  5. *
  6. * 用法:
  7. * node clone-runner.mjs sync --name yuyang [--level L1,L2] [--dry]
  8. * node clone-runner.mjs restore --repo <url> --into <dir>
  9. */
  10. import fs from 'fs';
  11. import os from 'os';
  12. import path from 'path';
  13. import { execSync } from 'child_process';
  14. const HOME = os.homedir();
  15. /** 4 级凭据解析: env → ~/.fmode/config.json → ./.fmode/config.json → git credential helper */
  16. export function resolveGit() {
  17. const out = { user: null, token: null, apiBase: 'https://git.fmode.cn/api/v1' };
  18. if (process.env.FMODE_GIT_TOKEN) { out.token = process.env.FMODE_GIT_TOKEN; }
  19. for (const p of [path.join(HOME, '.fmode', 'config.json'), path.join(process.cwd(), '.fmode', 'config.json')]) {
  20. try {
  21. const j = JSON.parse(fs.readFileSync(p, 'utf8'));
  22. if (j.gitToken) out.token = j.gitToken;
  23. if (j.gitUser) out.user = j.gitUser;
  24. if (j.gitApiBase) out.apiBase = j.gitApiBase;
  25. } catch {}
  26. }
  27. if (!out.user) {
  28. try { out.user = execSync('git config user.name', { encoding: 'utf8' }).trim(); } catch {}
  29. }
  30. return out;
  31. }
  32. /** 默认同步清单(L1 核心 / L2 能力 / L3 记录 / L4 状态) */
  33. export function collectPaths(level = ['L1','L2']) {
  34. const D = '/opt/data';
  35. const map = {
  36. L1: [`${D}/SOUL.md`, `${D}/MEMORY.md`, `${D}/USER.md`],
  37. L2: [`${D}/skills`, `${D}/home/.claude/skills`].filter(p => fs.existsSync(p)),
  38. L3: [`${D}/home/.claude/projects`, `${D}/.hermes/sessions`].filter(p => fs.existsSync(p)),
  39. L4: [`${D}/.hermes/cron`].filter(p => fs.existsSync(p)),
  40. };
  41. return level.flatMap(l => map[l] || []);
  42. }
  43. function sh(cmd, cwd) {
  44. return execSync(cmd, { encoding: 'utf8', cwd, stdio: ['ignore','pipe','pipe'], timeout: 120000 });
  45. }
  46. function ensureRepo(name, g) {
  47. const url = `${g.apiBase}/admin/users/${g.user}/repos`;
  48. try {
  49. const r = sh(`curl -s --max-time 20 -X POST -u "${g.user === 'fmode' ? 'fmode:fmgo' : 'fmode:fmgo'}" -H "Content-Type: application/json" -d '{"name":"${name}","private":true}' "${url}"`);
  50. return /"name"\s*:\s*"/.test(r) || /already/i.test(r);
  51. } catch { return false; }
  52. }
  53. function main() {
  54. const a = process.argv.slice(2);
  55. const cmd = a[0];
  56. const argOf = (n) => { const i = a.indexOf(n); return i >= 0 ? a[i+1] : null; };
  57. const g = resolveGit();
  58. if (cmd === 'sync') {
  59. const name = argOf('--name') || (g.user || 'agent').replace(/[^a-z0-9-]/gi, '').toLowerCase();
  60. const level = (argOf('--level') || 'L1,L2,L3').split(',');
  61. const dry = a.includes('--dry');
  62. const repoName = `agent-${name}`;
  63. const remote = argOf('--repo') || `https://${g.user}:${g.token}@git.fmode.cn/${g.user}/${repoName}.git`;
  64. const work = path.join(HOME, '.agent-clone', repoName);
  65. // 1) clone or init
  66. if (!fs.existsSync(path.join(work, '.git'))) {
  67. fs.mkdirSync(work, { recursive: true });
  68. try { sh(`git clone ${remote} ${work}`); } catch { sh(`git init -b main ${work}`); sh(`git remote add origin ${remote} ${work}`); }
  69. } else { sh(`git pull --rebase origin main || true`, work); }
  70. // 2) 汇集文件
  71. const targets = collectPaths(level);
  72. const manifest = [];
  73. for (const t of targets) {
  74. if (!fs.existsSync(t)) continue;
  75. const base = path.join(work, path.basename(t));
  76. sh(`mkdir -p "${path.dirname(base)}" && cp -r "${t}" "${path.dirname(base)}/"`);
  77. manifest.push({ src: t, dst: path.basename(t) });
  78. }
  79. // 3) credentials-map(密钥位置指针, 不含密钥值)
  80. const credMap = `# 密钥位置索引(不含密钥本体)\n- fmode token: ${HOME}/.fmode/config.json (fmodeApiToken)\n- claude token: ${HOME}/.claude/settings.json (env.ANTHROPIC_AUTH_TOKEN)\n- git tokens: /opt/data/.fmode-harness-agent/knowledge/lives/git-tokens.txt\n`;
  81. fs.writeFileSync(path.join(work, 'credentials-map.md'), credMap);
  82. fs.writeFileSync(path.join(work, 'sync-manifest.json'), JSON.stringify({ at: new Date().toISOString(), name, level, manifest }, null, 2));
  83. if (dry) { console.log('[dry] 同步项:', manifest.length); return; }
  84. // 4) commit+push
  85. try { sh(`git add -A && git -c user.name="${g.user}" -c user.email="${g.user}@fmode.cn" commit -m "clone sync ${new Date().toISOString().slice(0,16)}"`, work); } catch {}
  86. try { ensureRepo(repoName, g); sh(`git push -u origin main`, work); console.log('✅ 已同步', manifest.length, '项 →', repoName); }
  87. catch (e) { console.error('push 失败:', String(e).slice(0, 200)); }
  88. return;
  89. }
  90. if (cmd === 'restore') {
  91. const repo = argOf('--repo'); const into = argOf('--into') || '/opt/data';
  92. if (!repo) { console.error('用法: restore --repo <url> --into <dir>'); process.exit(2); }
  93. sh(`git clone ${repo} ${into}/.agent-restore`);
  94. console.log('已 clone 到', into + '/.agent-restore', '—— 按 sync-manifest.json 反向拷贝到对应路径即可');
  95. return;
  96. }
  97. console.log('用法: sync | restore');
  98. }
  99. main();