snapshot-login-refinement.mjs 5.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /** 原账本缺失时保存当前工作树与本轮证据;明确不是完整业务/容器迁移。 */
  2. import fs from 'node:fs';
  3. import path from 'node:path';
  4. import assert from 'node:assert/strict';
  5. import { fileURLToPath } from 'node:url';
  6. import { createHash, randomUUID } from 'node:crypto';
  7. import { spawnSync } from 'node:child_process';
  8. const root = fileURLToPath(new URL('..', import.meta.url));
  9. const evidence = 'test-results/login-refinement-20261130';
  10. const ledger = 'test-results/real-account-20261130/state.json';
  11. const sha = bytes => createHash('sha256').update(bytes).digest('hex');
  12. const git = args => {
  13. const result = spawnSync('git', args, { cwd: root, encoding: 'utf8', windowsHide: true, maxBuffer: 32 * 1024 * 1024 });
  14. assert.equal(result.status, 0, result.stderr || 'Git只读检查失败');
  15. return result.stdout;
  16. };
  17. for (const file of ['docs/00-tracking/接续检查点.md.lock', 'test-results/real-account-20261130/runner.lock']) {
  18. assert.ok(!fs.existsSync(path.join(root, file)), '发现锁,须先核实,不能创建可能不一致的备份:' + file);
  19. }
  20. const head = git(['rev-parse', 'HEAD']).trim();
  21. const unstaged = git(['diff', '--binary']);
  22. const staged = git(['diff', '--cached', '--binary']);
  23. const names = new Set((git(['diff', '--name-only', '-z', 'HEAD']) + git(['ls-files', '--others', '--exclude-standard', '-z'])).split('\0').filter(Boolean));
  24. for (const name of ['AGENTS.md', 'CLAUDE.md', 'docs/00-tracking/active-task.json', 'docs/00-tracking/接续检查点.md', 'docs/00-tracking/操作追踪.md', ledger]) names.add(name);
  25. const walk = relative => {
  26. for (const entry of fs.readdirSync(path.join(root, relative), { withFileTypes: true })) {
  27. if (entry.name === 'mock-build') continue;
  28. const name = path.posix.join(relative, entry.name);
  29. if (entry.isDirectory()) walk(name);
  30. else names.add(name);
  31. }
  32. };
  33. walk(evidence);
  34. const id = new Date().toISOString().replace(/[:.]/g, '-') + '-' + randomUUID().slice(0, 8);
  35. const relativeDirectory = '.local-backup/login-refinement-20261130/' + id;
  36. const directory = path.join(root, relativeDirectory);
  37. fs.mkdirSync(path.join(directory, 'files'), { recursive: true });
  38. const manifest = { version: 1, createdAt: new Date().toISOString(), head, scope: 'changed_and_untracked_sources_with_current_login_evidence', fullBusinessRecovery: false, dockerVolumesIncluded: false, originalLedgerIncluded: false, completePrivateConfigurationIncluded: false, files: [], deletions: [], metadata: [] };
  39. for (const name of [...names].sort()) {
  40. const source = path.resolve(root, name);
  41. const relative = path.relative(root, source);
  42. assert.ok(relative && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative), '源路径不能越过项目根目录');
  43. if (!fs.existsSync(source)) { manifest.deletions.push(name); continue; }
  44. assert.ok(fs.lstatSync(source).isFile() && !fs.lstatSync(source).isSymbolicLink(), '仅备份项目内普通文件:' + name);
  45. const bytes = fs.readFileSync(source);
  46. const target = path.join(directory, 'files', name);
  47. fs.mkdirSync(path.dirname(target), { recursive: true });
  48. fs.writeFileSync(target, bytes, { flag: 'wx' });
  49. manifest.files.push({ path: name, bytes: bytes.length, sha256: sha(bytes) });
  50. }
  51. const metadata = { 'worktree.patch': unstaged, 'staged.patch': staged, 'git-status.txt': git(['status', '--short']), 'README.txt': '仅含当前变更/未跟踪源码、规则、接续记录和本轮登录验收证据,恢复还需Git基线。未包含原业务账本、完整私有配置、Docker数据卷或Mock构建输出;不能当作完整跨机器业务恢复。先验证manifest再人工合并,不自动覆盖现有工作区。\n' };
  52. for (const [name, text] of Object.entries(metadata)) {
  53. fs.writeFileSync(path.join(directory, name), text, { flag: 'wx' });
  54. manifest.metadata.push({ path: name, sha256: sha(Buffer.from(text)) });
  55. }
  56. assert.equal(git(['rev-parse', 'HEAD']).trim(), head);
  57. assert.equal(git(['diff', '--binary']), unstaged, '备份期间工作树变化');
  58. assert.equal(git(['diff', '--cached', '--binary']), staged, '备份期间暂存区变化');
  59. for (const item of manifest.files) {
  60. assert.equal(sha(fs.readFileSync(path.join(root, item.path))), item.sha256, '源文件变化:' + item.path);
  61. assert.equal(sha(fs.readFileSync(path.join(directory, 'files', item.path))), item.sha256, '备份回读不一致:' + item.path);
  62. }
  63. for (const item of manifest.metadata) assert.equal(sha(fs.readFileSync(path.join(directory, item.path))), item.sha256);
  64. const manifestBytes = Buffer.from(JSON.stringify(manifest, null, 2) + '\n');
  65. fs.writeFileSync(path.join(directory, 'manifest.json'), manifestBytes, { flag: 'wx' });
  66. const receipt = { directory: relativeDirectory, files: manifest.files.length, verified: true, manifestSha256: sha(fs.readFileSync(path.join(directory, 'manifest.json'))), scope: manifest.scope, fullBusinessRecovery: false, dockerVolumesIncluded: false };
  67. fs.writeFileSync(path.join(directory, 'snapshot-receipt.json'), JSON.stringify(receipt, null, 2) + '\n', { flag: 'wx' });
  68. fs.writeFileSync(path.join(root, evidence, 'snapshot-receipt.json'), JSON.stringify(receipt, null, 2) + '\n');
  69. console.log(JSON.stringify(receipt, null, 2));