| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271 |
- /** 项目内恢复工具:默认只读;写入仅由显式记录/快照操作调用。 */
- import fs from 'node:fs';
- import path from 'node:path';
- import os from 'node:os';
- import assert from 'node:assert/strict';
- import { createHash, randomUUID } from 'node:crypto';
- import { spawnSync } from 'node:child_process';
- const INDEX = 'docs/00-tracking/active-task.json';
- const CHECKPOINT = 'docs/00-tracking/接续检查点.md';
- const OPERATIONS = 'docs/00-tracking/操作追踪.md';
- const digest = bytes => createHash('sha256').update(bytes).digest('hex');
- const relative = (root, file) => path.relative(root, file).split(path.sep).join('/');
- export const beijingTime = () => new Date().toLocaleString('sv-SE', { timeZone: 'Asia/Shanghai' }) + '+08:00';
- export function projectPath(root, name) {
- assert.equal(typeof name, 'string', '恢复路径必须为项目内相对路径');
- assert.ok(name && !path.isAbsolute(name) && !name.split(/[\\/]/).includes('..'), '恢复路径不能越过项目目录');
- const file = path.resolve(root, name);
- const rel = path.relative(path.resolve(root), file);
- assert.ok(rel && !rel.startsWith('..' + path.sep) && !path.isAbsolute(rel), '恢复路径不能指向项目目录外');
- let part = path.resolve(root);
- for (const component of rel.split(path.sep)) {
- part = path.join(part, component);
- assert.ok(!fs.existsSync(part) || !fs.lstatSync(part).isSymbolicLink(), '恢复路径不支持符号链接:' + name);
- }
- return file;
- }
- export function readCommand(root, command, args) {
- const r = spawnSync(command, args, { cwd: root, env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' }, encoding: 'utf8', timeout: 15000, maxBuffer: 16 * 1024 * 1024, windowsHide: true });
- return { ok: !r.error && r.status === 0, stdout: r.stdout || '', error: r.error?.message || r.stderr?.trim().slice(0, 350) || '' };
- }
- function isHandoffPath(root, name) {
- const normalized = relative(path.resolve(root), projectPath(root, name));
- const comparable = process.platform === 'win32' ? normalized.toLowerCase() : normalized;
- return comparable === '.local-backup/handoff' || comparable.startsWith('.local-backup/handoff/');
- }
- export function loadTask(root) {
- const config = JSON.parse(fs.readFileSync(projectPath(root, INDEX), 'utf8'));
- assert.equal(config.version, 1, '不支持的活动任务索引版本');
- for (const key of ['ledger', 'privateDirectory', 'report', 'previousCheckpoint']) projectPath(root, config[key]);
- assert.ok(!isHandoffPath(root, config.privateDirectory), '私有配置目录不能位于交接快照输出目录');
- return config;
- }
- export function actionStatus(action) {
- if (action.confirmedAt) return '已有回执,不重复执行';
- if (action.proof?.sent?.length && action.proof?.reply?.length && action.proof?.completion) return '已有完整事件证据,核对完成字段,不重发';
- if (action.attempted) return '结果待核实,禁止盲重试';
- return '未执行';
- }
- function readLedger(file, bytes = fs.readFileSync(file)) {
- const state = JSON.parse(bytes.toString('utf8'));
- const object = value => value && typeof value === 'object' && !Array.isArray(value);
- assert.ok(object(state), '账本根节点必须为对象');
- assert.ok(state.actions === undefined || (object(state.actions) && Object.values(state.actions).every(object)), '账本动作必须为对象');
- assert.ok(state.checks === undefined || (Array.isArray(state.checks) && state.checks.every(object)), '账本检查项必须为数组');
- assert.ok(state.acceptance === undefined || (Array.isArray(state.acceptance) && state.acceptance.every(object)), '账本验收项目必须为数组');
- return state;
- }
- function lockStatus(file) {
- if (!fs.existsSync(file)) return null;
- let data;
- try { data = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return { state: '锁文件不可解析;先人工核对,不自动删除' }; }
- let alive = '未知';
- if (data.host && data.host !== os.hostname()) alive = '其他机器,不能按本机 PID 判定';
- else if (Number.isInteger(data.pid) && data.pid > 0) {
- try { process.kill(data.pid, 0); alive = '进程存在'; } catch (e) { alive = e.code === 'ESRCH' ? '本机进程不存在,仍须核对回执' : '无法确认'; }
- }
- return { pid: data.pid, stage: data.stage, at: data.at || data.startedAt, state: alive };
- }
- export function collectRecovery(root, { probe = true, run = readCommand } = {}) {
- root = path.resolve(root);
- const config = loadTask(root);
- const warnings = [];
- let state = {};
- let ledgerSha256;
- try {
- const file = projectPath(root, config.ledger);
- const bytes = fs.readFileSync(file);
- state = readLedger(file, bytes);
- ledgerSha256 = digest(bytes);
- }
- catch (e) { warnings.push('活动账本缺失或损坏;不能通过创建业务资产来恢复:' + e.message); }
- let latestProgress;
- const progressFile = path.join(path.dirname(projectPath(root, config.ledger)), 'latest-progress.json');
- if (fs.existsSync(progressFile)) {
- try {
- const value = JSON.parse(fs.readFileSync(progressFile, 'utf8'));
- if (value?.run === state.run && value?.ledger === config.ledger && value?.ledgerSha256 === ledgerSha256 && typeof value?.message === 'string') latestProgress = value;
- else warnings.push('最新进度索引与活动账本不符,忽略该摘要并核对原回执');
- } catch { warnings.push('最新进度索引损坏,回退到账本,不能重新执行业务动作'); }
- }
- const git = args => run(root, 'git', args);
- const status = git(['status', '--short', '--untracked-files=normal']);
- const head = git(['rev-parse', '--verify', 'HEAD']);
- if (!status.ok) warnings.push('工作树状态读取失败:' + status.error);
- const actions = Object.entries(state.actions || {}).map(([key, action]) => ({ key, target: action.target, status: actionStatus(action), at: action.confirmedAt || action.at }));
- const lastChecks = new Map();
- for (const c of state.checks || []) lastChecks.set(c.name, { name: c.name, status: c.pass ? '通过' : '失败', at: c.at });
- const missingEvidence = [];
- for (const name of [CHECKPOINT, config.report, config.previousCheckpoint]) {
- if (!fs.existsSync(projectPath(root, name))) missingEvidence.push(name);
- }
- for (const [key, action] of Object.entries(state.actions || {})) {
- if (action.proof) {
- const name = path.posix.join(path.posix.dirname(config.ledger), key + '-events.json');
- if (!fs.existsSync(projectPath(root, name))) missingEvidence.push(name);
- }
- }
- if (missingEvidence.length) warnings.push('部分证据缺失;原有结论不能当作本轮重新验证通过');
- const sourceChanges = [];
- for (const [key, action] of Object.entries(state.actions || {})) {
- for (const [name, expected] of Object.entries(action.sources || {})) {
- const file = projectPath(root, name);
- const actual = fs.existsSync(file) ? digest(fs.readFileSync(file)) : null;
- if (actual !== expected) sourceChanges.push({ action: key, file: name, expected, actual });
- }
- }
- if (sourceChanges.length) warnings.push('源码与部分历史构建证据不同,相关旧测试不能替代修改后重测');
- const lock = lockStatus(path.join(path.dirname(projectPath(root, config.ledger)), 'runner.lock'));
- if (lock) warnings.push('发现执行锁;先核对原进程和真实结果,不自动清锁');
- const checkpointLock = lockStatus(projectPath(root, CHECKPOINT) + '.lock');
- if (checkpointLock) warnings.push('发现检查点写入锁;先核对原进程与记录,不自动清锁');
- let environment = { checked: false };
- if (probe) {
- const adb = run(root, 'adb', ['devices', '-l']);
- const docker = run(root, 'docker', ['version', '--format', '{{.Server.Version}}']);
- 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: [] };
- if (!docker.ok) warnings.push('Docker 当前不可用,历史 running 不代表当前在线;不自动启动或重建容器');
- if (docker.ok) {
- const names = new Set((state.assets || []).filter(x => x.kind === 'local-docker-container').map(x => x.name));
- for (const name of names) {
- const inspected = run(root, 'docker', ['inspect', '--format', '{{json .State}}', name]);
- let value = null;
- try { if (inspected.ok) value = JSON.parse(inspected.stdout); } catch { /* Report incomplete read, never create an instance. */ }
- environment.containers.push({ name, state: value ? { status: value.Status, running: value.Running, startedAt: value.StartedAt } : null, error: inspected.ok ? undefined : inspected.error });
- }
- }
- }
- 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 };
- }
- function atomicWrite(file, contents) {
- const next = file + '.' + randomUUID() + '.next';
- fs.writeFileSync(next, contents, { flag: 'wx' });
- try { fs.renameSync(next, file); }
- catch (e) { fs.unlinkSync(next); throw e; }
- }
- /** 调用者仍持有原账本执行锁;此锁仅保护检查点与操作日志。 */
- export function recordProgress(root, text) {
- const checkpoint = projectPath(root, CHECKPOINT);
- const lockFile = checkpoint + '.lock';
- const lock = fs.openSync(lockFile, 'wx');
- try {
- fs.writeFileSync(lock, JSON.stringify({ pid: process.pid, host: os.hostname(), at: beijingTime() }));
- const task = loadTask(root);
- const ledgerFile = projectPath(root, task.ledger);
- const ledgerBytes = fs.readFileSync(ledgerFile);
- const state = readLedger(ledgerFile, ledgerBytes);
- let document = fs.readFileSync(checkpoint, 'utf8');
- const checks = new Map((state.checks || []).map(x => [x.name, x.pass]));
- const passed = [...checks.values()].filter(Boolean).length;
- const failed = [...checks.values()].filter(x => !x).length;
- const acceptance = (state.acceptance || []).map(x => `- ${x.name}:${x.status}${x.evidence ? ';' + x.evidence : ''}`).join('\n');
- const currentMessage = String(text).replace(/\r?\n/g, ' ').slice(0, 600);
- 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 -->`;
- assert.ok(/<!-- recovery-summary:start -->[\s\S]*?<!-- recovery-summary:end -->/.test(document), '检查点缺少当前摘要边界,停止写入');
- document = document.replace(/<!-- recovery-summary:start -->[\s\S]*?<!-- recovery-summary:end -->/, () => summary);
- const entry = `- ${beijingTime()}:${String(text).replace(/\r?\n/g, ' ').slice(0, 600)}`;
- const section = /\r?\n## 最新操作\r?\n([\s\S]*?)(?=\r?\n下次接续指令:|$)/;
- assert.ok(section.test(document), '检查点缺少最新操作区,停止写入');
- document = document.replace(section, (_, previous) => '\n## 最新操作\n\n' + [...previous.split(/\r?\n/).filter(x => x.startsWith('- ')), entry].slice(-12).join('\n') + '\n');
- 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');
- atomicWrite(checkpoint, document);
- fs.appendFileSync(projectPath(root, OPERATIONS), '\n- ' + beijingTime() + ':' + text + '\n');
- } finally { fs.closeSync(lock); fs.unlinkSync(lockFile); }
- }
- export function updateStep(root, currentStep) {
- const task = loadTask(root);
- const stateFile = projectPath(root, task.ledger);
- const lockFile = path.join(path.dirname(stateFile), 'runner.lock');
- const lock = fs.openSync(lockFile, 'wx');
- try {
- fs.writeFileSync(lock, JSON.stringify({ pid: process.pid, host: os.hostname(), stage: 'record-step', at: beijingTime() }));
- const state = readLedger(stateFile);
- state.recovery = { ...state.recovery, currentStep, updatedAt: beijingTime() };
- atomicWrite(stateFile, JSON.stringify(state, null, 2) + '\n');
- recordProgress(root, currentStep);
- } finally { fs.closeSync(lock); fs.unlinkSync(lockFile); }
- }
- export function createSnapshot(root, { run = readCommand } = {}) {
- root = path.resolve(root);
- const task = loadTask(root);
- const stateFile = projectPath(root, task.ledger);
- assert.ok(!fs.existsSync(path.join(path.dirname(stateFile), 'runner.lock')), '发现执行锁;先核实原进程与真实回执,不创建可能不一致的快照');
- assert.ok(!fs.existsSync(projectPath(root, CHECKPOINT) + '.lock'), '检查点正在更新,稍后再保存快照');
- const beforeLedger = digest(fs.readFileSync(stateFile));
- const git = args => { const r = run(root, 'git', args); assert.ok(r.ok, '无法保存工作树:' + r.error); return r.stdout; };
- const collectNames = () => {
- const changed = git(['diff', '--name-only', '-z', 'HEAD']);
- const untracked = git(['ls-files', '--others', '--exclude-standard', '-z']);
- const names = new Set([INDEX, CHECKPOINT, OPERATIONS, 'AGENTS.md', 'CLAUDE.md', 'docs/README.md', task.report, task.previousCheckpoint]);
- for (const file of (changed + untracked).split('\0').filter(Boolean)) names.add(file);
- for (const directory of [path.posix.dirname(task.ledger), task.privateDirectory]) {
- const walk = file => {
- if (isHandoffPath(root, file)) return;
- const full = projectPath(root, file);
- if (fs.statSync(full).isDirectory()) for (const child of fs.readdirSync(full)) walk(path.posix.join(file, child));
- else names.add(file);
- };
- assert.ok(fs.existsSync(projectPath(root, directory)), '快照所需目录不存在:' + directory);
- walk(directory);
- }
- if (fs.existsSync(projectPath(root, '.claude/dev-login.json'))) names.add('.claude/dev-login.json');
- return [...names].filter(name => !isHandoffPath(root, name)).sort();
- };
- const names = collectNames();
- const beforeHead = git(['rev-parse', 'HEAD']).trim();
- const beforeUnstaged = git(['diff', '--binary']);
- const beforeStaged = git(['diff', '--cached', '--binary']);
- const id = new Date().toISOString().replace(/[:.]/g, '-') + '-' + randomUUID().slice(0, 8);
- const directory = projectPath(root, '.local-backup/handoff/' + id);
- const partial = directory + '.partial';
- fs.mkdirSync(path.join(partial, 'files'), { recursive: true });
- const manifest = { version: 1, createdAt: beijingTime(), head: beforeHead, run: readLedger(stateFile).run, ledger: task.ledger, dockerVolumesIncluded: false, files: [], deletions: [] };
- for (const name of names) {
- const source = projectPath(root, name);
- if (!fs.existsSync(source)) { manifest.deletions.push(name); continue; }
- assert.ok(fs.statSync(source).isFile(), '快照中存在非普通文件:' + name);
- const bytes = fs.readFileSync(source);
- const dest = path.join(partial, 'files', name);
- fs.mkdirSync(path.dirname(dest), { recursive: true });
- fs.writeFileSync(dest, bytes, { flag: 'wx' });
- manifest.files.push({ path: name, bytes: bytes.length, sha256: digest(bytes) });
- }
- const metadata = {
- 'unstaged.patch': beforeUnstaged,
- 'staged.patch': beforeStaged,
- 'worktree-status.txt': git(['status', '--short']),
- 'README.txt': '本目录是显式交接快照,包含必要私有配置。先核对 manifest.json 的所有文件摘要及 Git 基线,再人工合并恢复;禁止自动覆盖现有工作区。\n未备份 Docker 数据卷:跨机器恢复容器前,需另行导出并校验本轮指定卷,不能新建同名空卷冒充恢复。\n',
- };
- manifest.metadata = [];
- for (const [name, text] of Object.entries(metadata)) {
- fs.writeFileSync(path.join(partial, name), text, { flag: 'wx' });
- manifest.metadata.push({ path: name, sha256: digest(Buffer.from(text)) });
- }
- assert.equal(digest(fs.readFileSync(stateFile)), beforeLedger, '账本在快照期间变化,保留 .partial 供核对,不交付为完整快照');
- assert.ok(!fs.existsSync(path.join(path.dirname(stateFile), 'runner.lock')), '快照期间出现执行器,需重新核对');
- assert.ok(!fs.existsSync(projectPath(root, CHECKPOINT) + '.lock'), '快照期间出现检查点写入器,需重新核对');
- assert.deepEqual(collectNames(), names, '快照期间出现新增/删除文件,保留 .partial 供核对');
- assert.equal(git(['rev-parse', 'HEAD']).trim(), beforeHead, '快照期间 Git 基线变化');
- assert.equal(git(['diff', '--binary']), beforeUnstaged, '快照期间未暂存差异变化');
- assert.equal(git(['diff', '--cached', '--binary']), beforeStaged, '快照期间暂存差异变化');
- for (const file of manifest.files) {
- assert.equal(digest(fs.readFileSync(projectPath(root, file.path))), file.sha256, '源文件在快照期间变化:' + file.path);
- assert.equal(digest(fs.readFileSync(path.join(partial, 'files', file.path))), file.sha256, '快照回读不一致:' + file.path);
- }
- fs.writeFileSync(path.join(partial, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n');
- fs.renameSync(partial, directory);
- return { directory: relative(root, directory), files: manifest.files.length, manifest: relative(root, path.join(directory, 'manifest.json')), dockerVolumesIncluded: false };
- }
|