project-recovery.mjs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. /** 项目内恢复工具:默认只读;写入仅由显式记录/快照操作调用。 */
  2. import fs from 'node:fs';
  3. import path from 'node:path';
  4. import os from 'node:os';
  5. import assert from 'node:assert/strict';
  6. import { createHash, randomUUID } from 'node:crypto';
  7. import { spawnSync } from 'node:child_process';
  8. const INDEX = 'docs/00-tracking/active-task.json';
  9. const CHECKPOINT = 'docs/00-tracking/接续检查点.md';
  10. const OPERATIONS = 'docs/00-tracking/操作追踪.md';
  11. const digest = bytes => createHash('sha256').update(bytes).digest('hex');
  12. const relative = (root, file) => path.relative(root, file).split(path.sep).join('/');
  13. export const beijingTime = () => new Date().toLocaleString('sv-SE', { timeZone: 'Asia/Shanghai' }) + '+08:00';
  14. export function projectPath(root, name) {
  15. assert.equal(typeof name, 'string', '恢复路径必须为项目内相对路径');
  16. assert.ok(name && !path.isAbsolute(name) && !name.split(/[\\/]/).includes('..'), '恢复路径不能越过项目目录');
  17. const file = path.resolve(root, name);
  18. const rel = path.relative(path.resolve(root), file);
  19. assert.ok(rel && !rel.startsWith('..' + path.sep) && !path.isAbsolute(rel), '恢复路径不能指向项目目录外');
  20. let part = path.resolve(root);
  21. for (const component of rel.split(path.sep)) {
  22. part = path.join(part, component);
  23. assert.ok(!fs.existsSync(part) || !fs.lstatSync(part).isSymbolicLink(), '恢复路径不支持符号链接:' + name);
  24. }
  25. return file;
  26. }
  27. export function readCommand(root, command, args) {
  28. const r = spawnSync(command, args, { cwd: root, env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' }, encoding: 'utf8', timeout: 15000, maxBuffer: 16 * 1024 * 1024, windowsHide: true });
  29. return { ok: !r.error && r.status === 0, stdout: r.stdout || '', error: r.error?.message || r.stderr?.trim().slice(0, 350) || '' };
  30. }
  31. function isHandoffPath(root, name) {
  32. const normalized = relative(path.resolve(root), projectPath(root, name));
  33. const comparable = process.platform === 'win32' ? normalized.toLowerCase() : normalized;
  34. return comparable === '.local-backup/handoff' || comparable.startsWith('.local-backup/handoff/');
  35. }
  36. export function loadTask(root) {
  37. const config = JSON.parse(fs.readFileSync(projectPath(root, INDEX), 'utf8'));
  38. assert.equal(config.version, 1, '不支持的活动任务索引版本');
  39. for (const key of ['ledger', 'privateDirectory', 'report', 'previousCheckpoint']) projectPath(root, config[key]);
  40. assert.ok(!isHandoffPath(root, config.privateDirectory), '私有配置目录不能位于交接快照输出目录');
  41. return config;
  42. }
  43. export function actionStatus(action) {
  44. if (action.confirmedAt) return '已有回执,不重复执行';
  45. if (action.proof?.sent?.length && action.proof?.reply?.length && action.proof?.completion) return '已有完整事件证据,核对完成字段,不重发';
  46. if (action.attempted) return '结果待核实,禁止盲重试';
  47. return '未执行';
  48. }
  49. function readLedger(file, bytes = fs.readFileSync(file)) {
  50. const state = JSON.parse(bytes.toString('utf8'));
  51. const object = value => value && typeof value === 'object' && !Array.isArray(value);
  52. assert.ok(object(state), '账本根节点必须为对象');
  53. assert.ok(state.actions === undefined || (object(state.actions) && Object.values(state.actions).every(object)), '账本动作必须为对象');
  54. assert.ok(state.checks === undefined || (Array.isArray(state.checks) && state.checks.every(object)), '账本检查项必须为数组');
  55. assert.ok(state.acceptance === undefined || (Array.isArray(state.acceptance) && state.acceptance.every(object)), '账本验收项目必须为数组');
  56. return state;
  57. }
  58. function lockStatus(file) {
  59. if (!fs.existsSync(file)) return null;
  60. let data;
  61. try { data = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return { state: '锁文件不可解析;先人工核对,不自动删除' }; }
  62. let alive = '未知';
  63. if (data.host && data.host !== os.hostname()) alive = '其他机器,不能按本机 PID 判定';
  64. else if (Number.isInteger(data.pid) && data.pid > 0) {
  65. try { process.kill(data.pid, 0); alive = '进程存在'; } catch (e) { alive = e.code === 'ESRCH' ? '本机进程不存在,仍须核对回执' : '无法确认'; }
  66. }
  67. return { pid: data.pid, stage: data.stage, at: data.at || data.startedAt, state: alive };
  68. }
  69. export function collectRecovery(root, { probe = true, run = readCommand } = {}) {
  70. root = path.resolve(root);
  71. const config = loadTask(root);
  72. const warnings = [];
  73. let state = {};
  74. let ledgerSha256;
  75. try {
  76. const file = projectPath(root, config.ledger);
  77. const bytes = fs.readFileSync(file);
  78. state = readLedger(file, bytes);
  79. ledgerSha256 = digest(bytes);
  80. }
  81. catch (e) { warnings.push('活动账本缺失或损坏;不能通过创建业务资产来恢复:' + e.message); }
  82. let latestProgress;
  83. const progressFile = path.join(path.dirname(projectPath(root, config.ledger)), 'latest-progress.json');
  84. if (fs.existsSync(progressFile)) {
  85. try {
  86. const value = JSON.parse(fs.readFileSync(progressFile, 'utf8'));
  87. if (value?.run === state.run && value?.ledger === config.ledger && value?.ledgerSha256 === ledgerSha256 && typeof value?.message === 'string') latestProgress = value;
  88. else warnings.push('最新进度索引与活动账本不符,忽略该摘要并核对原回执');
  89. } catch { warnings.push('最新进度索引损坏,回退到账本,不能重新执行业务动作'); }
  90. }
  91. const git = args => run(root, 'git', args);
  92. const status = git(['status', '--short', '--untracked-files=normal']);
  93. const head = git(['rev-parse', '--verify', 'HEAD']);
  94. if (!status.ok) warnings.push('工作树状态读取失败:' + status.error);
  95. const actions = Object.entries(state.actions || {}).map(([key, action]) => ({ key, target: action.target, status: actionStatus(action), at: action.confirmedAt || action.at }));
  96. const lastChecks = new Map();
  97. for (const c of state.checks || []) lastChecks.set(c.name, { name: c.name, status: c.pass ? '通过' : '失败', at: c.at });
  98. const missingEvidence = [];
  99. for (const name of [CHECKPOINT, config.report, config.previousCheckpoint]) {
  100. if (!fs.existsSync(projectPath(root, name))) missingEvidence.push(name);
  101. }
  102. for (const [key, action] of Object.entries(state.actions || {})) {
  103. if (action.proof) {
  104. const name = path.posix.join(path.posix.dirname(config.ledger), key + '-events.json');
  105. if (!fs.existsSync(projectPath(root, name))) missingEvidence.push(name);
  106. }
  107. }
  108. if (missingEvidence.length) warnings.push('部分证据缺失;原有结论不能当作本轮重新验证通过');
  109. const sourceChanges = [];
  110. for (const [key, action] of Object.entries(state.actions || {})) {
  111. for (const [name, expected] of Object.entries(action.sources || {})) {
  112. const file = projectPath(root, name);
  113. const actual = fs.existsSync(file) ? digest(fs.readFileSync(file)) : null;
  114. if (actual !== expected) sourceChanges.push({ action: key, file: name, expected, actual });
  115. }
  116. }
  117. if (sourceChanges.length) warnings.push('源码与部分历史构建证据不同,相关旧测试不能替代修改后重测');
  118. const lock = lockStatus(path.join(path.dirname(projectPath(root, config.ledger)), 'runner.lock'));
  119. if (lock) warnings.push('发现执行锁;先核对原进程和真实结果,不自动清锁');
  120. const checkpointLock = lockStatus(projectPath(root, CHECKPOINT) + '.lock');
  121. if (checkpointLock) warnings.push('发现检查点写入锁;先核对原进程与记录,不自动清锁');
  122. let environment = { checked: false };
  123. if (probe) {
  124. const adb = run(root, 'adb', ['devices', '-l']);
  125. const docker = run(root, 'docker', ['version', '--format', '{{.Server.Version}}']);
  126. environment = { checked: true, adb: { available: adb.ok, detail: adb.ok ? adb.stdout.trim() : adb.error }, docker: { available: docker.ok, detail: docker.ok ? docker.stdout.trim() : docker.error }, containers: [] };
  127. if (!docker.ok) warnings.push('Docker 当前不可用,历史 running 不代表当前在线;不自动启动或重建容器');
  128. if (docker.ok) {
  129. const names = new Set((state.assets || []).filter(x => x.kind === 'local-docker-container').map(x => x.name));
  130. for (const name of names) {
  131. const inspected = run(root, 'docker', ['inspect', '--format', '{{json .State}}', name]);
  132. let value = null;
  133. try { if (inspected.ok) value = JSON.parse(inspected.stdout); } catch { /* Report incomplete read, never create an instance. */ }
  134. environment.containers.push({ name, state: value ? { status: value.Status, running: value.Running, startedAt: value.StartedAt } : null, error: inspected.ok ? undefined : inspected.error });
  135. }
  136. }
  137. }
  138. return { version: 1, observedAt: beijingTime(), goal: config.goal, run: state.run, account: { userId: state.userId, phone: state.phone }, ledger: config.ledger, currentStep: latestProgress?.message || state.recovery?.currentStep || '先核实最近失败和未确认动作', latestProgress, nextSteps: state.recovery?.nextSteps || [], lastFailure: state.lastFailure, acceptance: state.acceptance || [], actions, checks: [...lastChecks.values()], missingEvidence, sourceChanges, lock, checkpointLock, worktree: { head: head.ok ? head.stdout.trim() : null, status: status.stdout.trimEnd() }, environment, warnings };
  139. }
  140. function atomicWrite(file, contents) {
  141. const next = file + '.' + randomUUID() + '.next';
  142. fs.writeFileSync(next, contents, { flag: 'wx' });
  143. try { fs.renameSync(next, file); }
  144. catch (e) { fs.unlinkSync(next); throw e; }
  145. }
  146. /** 调用者仍持有原账本执行锁;此锁仅保护检查点与操作日志。 */
  147. export function recordProgress(root, text) {
  148. const checkpoint = projectPath(root, CHECKPOINT);
  149. const lockFile = checkpoint + '.lock';
  150. const lock = fs.openSync(lockFile, 'wx');
  151. try {
  152. fs.writeFileSync(lock, JSON.stringify({ pid: process.pid, host: os.hostname(), at: beijingTime() }));
  153. const task = loadTask(root);
  154. const ledgerFile = projectPath(root, task.ledger);
  155. const ledgerBytes = fs.readFileSync(ledgerFile);
  156. const state = readLedger(ledgerFile, ledgerBytes);
  157. let document = fs.readFileSync(checkpoint, 'utf8');
  158. const checks = new Map((state.checks || []).map(x => [x.name, x.pass]));
  159. const passed = [...checks.values()].filter(Boolean).length;
  160. const failed = [...checks.values()].filter(x => !x).length;
  161. const acceptance = (state.acceptance || []).map(x => `- ${x.name}:${x.status}${x.evidence ? ';' + x.evidence : ''}`).join('\n');
  162. const currentMessage = String(text).replace(/\r?\n/g, ' ').slice(0, 600);
  163. const summary = `<!-- recovery-summary:start -->\n更新时间:${beijingTime()}(北京时间)\n\n当前任务:${task.goal}\n\n当前步骤/最新真实记录:${currentMessage}\n\n当前账本:${task.ledger};已留存检查通过 ${passed} 项、失败 ${failed} 项(历史证据,不代表当前环境重测)。\n\n最近留存失败:${state.lastFailure ? state.lastFailure.stage + ':' + state.lastFailure.message : '无'};是否已闭环以验收项目和更新后的回执为准。\n\n${acceptance}\n\n下一步:${(state.recovery?.nextSteps || []).join(' → ') || '核对账本和真实回执后继续'}\n<!-- recovery-summary:end -->`;
  164. assert.ok(/<!-- recovery-summary:start -->[\s\S]*?<!-- recovery-summary:end -->/.test(document), '检查点缺少当前摘要边界,停止写入');
  165. document = document.replace(/<!-- recovery-summary:start -->[\s\S]*?<!-- recovery-summary:end -->/, () => summary);
  166. const entry = `- ${beijingTime()}:${String(text).replace(/\r?\n/g, ' ').slice(0, 600)}`;
  167. const section = /\r?\n## 最新操作\r?\n([\s\S]*?)(?=\r?\n下次接续指令:|$)/;
  168. assert.ok(section.test(document), '检查点缺少最新操作区,停止写入');
  169. document = document.replace(section, (_, previous) => '\n## 最新操作\n\n' + [...previous.split(/\r?\n/).filter(x => x.startsWith('- ')), entry].slice(-12).join('\n') + '\n');
  170. atomicWrite(path.join(path.dirname(ledgerFile), 'latest-progress.json'), JSON.stringify({ at: beijingTime(), run: state.run, ledger: task.ledger, ledgerSha256: digest(ledgerBytes), message: currentMessage }, null, 2) + '\n');
  171. atomicWrite(checkpoint, document);
  172. fs.appendFileSync(projectPath(root, OPERATIONS), '\n- ' + beijingTime() + ':' + text + '\n');
  173. } finally { fs.closeSync(lock); fs.unlinkSync(lockFile); }
  174. }
  175. export function updateStep(root, currentStep) {
  176. const task = loadTask(root);
  177. const stateFile = projectPath(root, task.ledger);
  178. const lockFile = path.join(path.dirname(stateFile), 'runner.lock');
  179. const lock = fs.openSync(lockFile, 'wx');
  180. try {
  181. fs.writeFileSync(lock, JSON.stringify({ pid: process.pid, host: os.hostname(), stage: 'record-step', at: beijingTime() }));
  182. const state = readLedger(stateFile);
  183. state.recovery = { ...state.recovery, currentStep, updatedAt: beijingTime() };
  184. atomicWrite(stateFile, JSON.stringify(state, null, 2) + '\n');
  185. recordProgress(root, currentStep);
  186. } finally { fs.closeSync(lock); fs.unlinkSync(lockFile); }
  187. }
  188. export function createSnapshot(root, { run = readCommand } = {}) {
  189. root = path.resolve(root);
  190. const task = loadTask(root);
  191. const stateFile = projectPath(root, task.ledger);
  192. assert.ok(!fs.existsSync(path.join(path.dirname(stateFile), 'runner.lock')), '发现执行锁;先核实原进程与真实回执,不创建可能不一致的快照');
  193. assert.ok(!fs.existsSync(projectPath(root, CHECKPOINT) + '.lock'), '检查点正在更新,稍后再保存快照');
  194. const beforeLedger = digest(fs.readFileSync(stateFile));
  195. const git = args => { const r = run(root, 'git', args); assert.ok(r.ok, '无法保存工作树:' + r.error); return r.stdout; };
  196. const collectNames = () => {
  197. const changed = git(['diff', '--name-only', '-z', 'HEAD']);
  198. const untracked = git(['ls-files', '--others', '--exclude-standard', '-z']);
  199. const names = new Set([INDEX, CHECKPOINT, OPERATIONS, 'AGENTS.md', 'CLAUDE.md', 'docs/README.md', task.report, task.previousCheckpoint]);
  200. for (const file of (changed + untracked).split('\0').filter(Boolean)) names.add(file);
  201. for (const directory of [path.posix.dirname(task.ledger), task.privateDirectory]) {
  202. const walk = file => {
  203. if (isHandoffPath(root, file)) return;
  204. const full = projectPath(root, file);
  205. if (fs.statSync(full).isDirectory()) for (const child of fs.readdirSync(full)) walk(path.posix.join(file, child));
  206. else names.add(file);
  207. };
  208. assert.ok(fs.existsSync(projectPath(root, directory)), '快照所需目录不存在:' + directory);
  209. walk(directory);
  210. }
  211. if (fs.existsSync(projectPath(root, '.claude/dev-login.json'))) names.add('.claude/dev-login.json');
  212. return [...names].filter(name => !isHandoffPath(root, name)).sort();
  213. };
  214. const names = collectNames();
  215. const beforeHead = git(['rev-parse', 'HEAD']).trim();
  216. const beforeUnstaged = git(['diff', '--binary']);
  217. const beforeStaged = git(['diff', '--cached', '--binary']);
  218. const id = new Date().toISOString().replace(/[:.]/g, '-') + '-' + randomUUID().slice(0, 8);
  219. const directory = projectPath(root, '.local-backup/handoff/' + id);
  220. const partial = directory + '.partial';
  221. fs.mkdirSync(path.join(partial, 'files'), { recursive: true });
  222. const manifest = { version: 1, createdAt: beijingTime(), head: beforeHead, run: readLedger(stateFile).run, ledger: task.ledger, dockerVolumesIncluded: false, files: [], deletions: [] };
  223. for (const name of names) {
  224. const source = projectPath(root, name);
  225. if (!fs.existsSync(source)) { manifest.deletions.push(name); continue; }
  226. assert.ok(fs.statSync(source).isFile(), '快照中存在非普通文件:' + name);
  227. const bytes = fs.readFileSync(source);
  228. const dest = path.join(partial, 'files', name);
  229. fs.mkdirSync(path.dirname(dest), { recursive: true });
  230. fs.writeFileSync(dest, bytes, { flag: 'wx' });
  231. manifest.files.push({ path: name, bytes: bytes.length, sha256: digest(bytes) });
  232. }
  233. const metadata = {
  234. 'unstaged.patch': beforeUnstaged,
  235. 'staged.patch': beforeStaged,
  236. 'worktree-status.txt': git(['status', '--short']),
  237. 'README.txt': '本目录是显式交接快照,包含必要私有配置。先核对 manifest.json 的所有文件摘要及 Git 基线,再人工合并恢复;禁止自动覆盖现有工作区。\n未备份 Docker 数据卷:跨机器恢复容器前,需另行导出并校验本轮指定卷,不能新建同名空卷冒充恢复。\n',
  238. };
  239. manifest.metadata = [];
  240. for (const [name, text] of Object.entries(metadata)) {
  241. fs.writeFileSync(path.join(partial, name), text, { flag: 'wx' });
  242. manifest.metadata.push({ path: name, sha256: digest(Buffer.from(text)) });
  243. }
  244. assert.equal(digest(fs.readFileSync(stateFile)), beforeLedger, '账本在快照期间变化,保留 .partial 供核对,不交付为完整快照');
  245. assert.ok(!fs.existsSync(path.join(path.dirname(stateFile), 'runner.lock')), '快照期间出现执行器,需重新核对');
  246. assert.ok(!fs.existsSync(projectPath(root, CHECKPOINT) + '.lock'), '快照期间出现检查点写入器,需重新核对');
  247. assert.deepEqual(collectNames(), names, '快照期间出现新增/删除文件,保留 .partial 供核对');
  248. assert.equal(git(['rev-parse', 'HEAD']).trim(), beforeHead, '快照期间 Git 基线变化');
  249. assert.equal(git(['diff', '--binary']), beforeUnstaged, '快照期间未暂存差异变化');
  250. assert.equal(git(['diff', '--cached', '--binary']), beforeStaged, '快照期间暂存差异变化');
  251. for (const file of manifest.files) {
  252. assert.equal(digest(fs.readFileSync(projectPath(root, file.path))), file.sha256, '源文件在快照期间变化:' + file.path);
  253. assert.equal(digest(fs.readFileSync(path.join(partial, 'files', file.path))), file.sha256, '快照回读不一致:' + file.path);
  254. }
  255. fs.writeFileSync(path.join(partial, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n');
  256. fs.renameSync(partial, directory);
  257. return { directory: relative(root, directory), files: manifest.files.length, manifest: relative(root, path.join(directory, 'manifest.json')), dockerVolumesIncluded: false };
  258. }