| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230 |
- import test from 'node:test';
- import assert from 'node:assert/strict';
- import fs from 'node:fs';
- import os from 'node:os';
- import path from 'node:path';
- import { createHash } from 'node:crypto';
- import { spawnSync } from 'node:child_process';
- import { fileURLToPath } from 'node:url';
- import { actionStatus, collectRecovery, createSnapshot, projectPath, recordProgress, updateStep } from './lib/project-recovery.mjs';
- const sha = bytes => createHash('sha256').update(bytes).digest('hex');
- const put = (root, name, data) => {
- const file = path.join(root, name); fs.mkdirSync(path.dirname(file), { recursive: true });
- fs.writeFileSync(file, typeof data === 'string' ? data : JSON.stringify(data));
- };
- function fixture(t) {
- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'fmode-recovery-test-'));
- t.after(() => {
- assert.equal(path.dirname(root), os.tmpdir());
- assert.ok(path.basename(root).startsWith('fmode-recovery-test-'));
- fs.rmSync(root, { recursive: true, force: true });
- });
- const config = { version: 1, goal: '恢复测试', ledger: 'test-results/active/state.json', privateDirectory: '.local-backup/active', report: 'docs/00-tracking/report.md', previousCheckpoint: 'docs/00-tracking/history.md' };
- put(root, 'docs/00-tracking/active-task.json', config);
- put(root, 'docs/00-tracking/接续检查点.md', '# 接续检查点\n<!-- recovery-summary:start -->\n旧摘要\n<!-- recovery-summary:end -->\n\n## 固定资产\n不可覆盖\n\n## 最新操作\n\n- 旧操作\n\n下次接续指令:继续\n');
- for (const name of ['AGENTS.md', 'CLAUDE.md', 'docs/README.md', 'docs/00-tracking/操作追踪.md', config.report, config.previousCheckpoint]) put(root, name, '保留 ' + name);
- put(root, 'src/example.ts', 'existing source'); put(root, 'new.txt', 'untracked');
- put(root, '.local-backup/active/account.json', { token: 'private-fixture-token' });
- put(root, 'test-results/active/file-events.json', []);
- put(root, config.ledger, { run: 'fixture', phone: '18100000000', userId: 'fixture-owner', actions: { sms: { attempted: true, confirmedAt: 'receipt-time', receipt: { token: 'do-not-display' } }, file: { attempted: true, proof: { sent: ['a'], reply: ['b'], completion: 'c' } }, pending: { attempted: true }, build: { confirmedAt: 'old-build', sources: { 'src/example.ts': sha('existing source') } } }, checks: [{ name: '旧失败后复验', pass: false }, { name: '旧失败后复验', pass: true }], recovery: { currentStep: '核对文件', nextSteps: ['补验'] }, acceptance: [{ name: 'HTML 预览', status: '失败' }] });
- return { root, config };
- }
- function fakeRun(root, command, args) {
- if (command !== 'git') return { ok: false, stdout: '', error: command + ' unavailable' };
- if (args[0] === 'rev-parse') return { ok: true, stdout: 'abc123\n' };
- if (args[0] === 'status') return { ok: true, stdout: ' M src/example.ts\n?? new.txt\n' };
- if (args[0] === 'ls-files') return { ok: true, stdout: 'new.txt\0' };
- if (args.includes('--name-only')) return { ok: true, stdout: 'src/example.ts\0gone.txt\0' };
- if (args[0] === 'diff') return { ok: true, stdout: 'binary patch fixture\n' };
- throw Error('Unexpected command: ' + command + ' ' + args.join(' '));
- }
- function inventory(root) {
- const rows = [];
- const walk = name => {
- for (const item of fs.readdirSync(path.join(root, name), { withFileTypes: true })) {
- const rel = path.join(name, item.name);
- item.isDirectory() ? walk(rel) : rows.push([rel, sha(fs.readFileSync(path.join(root, rel)))]);
- }
- };
- walk(''); return rows;
- }
- test('default recovery is read-only, retains receipts and never exposes tokens', t => {
- const { root } = fixture(t); const before = inventory(root); const calls = [];
- const result = collectRecovery(root, { run: (...args) => { calls.push(args); return fakeRun(...args); } });
- assert.deepEqual(inventory(root), before);
- assert.ok(result.actions.find(x => x.key === 'sms').status.includes('不重复'));
- assert.ok(result.actions.find(x => x.key === 'file').status.includes('不重发'));
- assert.ok(result.actions.find(x => x.key === 'pending').status.includes('禁止盲重试'));
- assert.deepEqual(result.checks.map(x => x.status), ['通过']);
- assert.ok(result.warnings.some(x => x.includes('Docker')));
- assert.ok(calls.every(([, command, args]) => command === 'git' || (command === 'adb' && args[0] === 'devices') || (command === 'docker' && args[0] === 'version')));
- assert.ok(!JSON.stringify(result).includes('private-fixture-token'));
- assert.ok(!JSON.stringify(result).includes('do-not-display'));
- });
- test('CLI offline read also leaves the fixture unchanged without device dependencies', t => {
- const { root } = fixture(t); const before = inventory(root);
- const cli = fileURLToPath(new URL('./project-resume.mjs', import.meta.url));
- const r = spawnSync(process.execPath, [cli, '--root=' + root, '--offline', '--json'], { encoding: 'utf8', windowsHide: true });
- assert.equal(r.status, 0, r.stderr);
- assert.equal(JSON.parse(r.stdout).environment.checked, false);
- assert.deepEqual(inventory(root), before);
- });
- test('missing evidence, changed sources and damaged ledger are reported without reconstruction', t => {
- const { root, config } = fixture(t);
- fs.unlinkSync(path.join(root, 'test-results/active/file-events.json')); put(root, 'src/example.ts', 'changed');
- let result = collectRecovery(root, { probe: false, run: fakeRun });
- assert.equal(result.missingEvidence.length, 1); assert.equal(result.sourceChanges.length, 1);
- put(root, config.ledger, '{interrupted');
- result = collectRecovery(root, { probe: false, run: fakeRun });
- assert.ok(result.warnings.some(x => x.includes('账本缺失或损坏')));
- assert.equal(fs.readFileSync(path.join(root, config.ledger), 'utf8'), '{interrupted');
- });
- test('a stale lock is retained and prevents snapshots and step updates', t => {
- const { root } = fixture(t); const lock = path.join(root, 'test-results/active/runner.lock');
- put(root, 'test-results/active/runner.lock', { pid: 2147483647, stage: 'unknown-result' });
- assert.ok(collectRecovery(root, { probe: false, run: fakeRun }).lock);
- assert.throws(() => createSnapshot(root, { run: fakeRun }), /执行锁/);
- assert.throws(() => updateStep(root, 'cannot overwrite'), /EEXIST/);
- assert.ok(fs.existsSync(lock));
- });
- test('a checkpoint lock is visible in default recovery without being removed', t => {
- const { root } = fixture(t);
- put(root, 'docs/00-tracking/接续检查点.md.lock', { pid: 2147483647, stage: 'checkpoint' });
- const result = collectRecovery(root, { probe: false, run: fakeRun });
- assert.ok(result.checkpointLock); assert.ok(result.warnings.some(x => x.includes('检查点写入锁')));
- assert.ok(fs.existsSync(path.join(root, 'docs/00-tracking/接续检查点.md.lock')));
- });
- test('valid JSON with an invalid ledger shape degrades to a warning without reconstruction', t => {
- const { root, config } = fixture(t);
- for (const invalid of ['null', '[]', '{"actions":[]}', '{"actions":{"broken":null}}', '{"checks":{}}']) {
- put(root, config.ledger, invalid);
- const result = collectRecovery(root, { probe: false, run: fakeRun });
- assert.ok(result.warnings.some(x => x.includes('账本缺失或损坏')));
- assert.equal(fs.readFileSync(path.join(root, config.ledger), 'utf8'), invalid);
- }
- });
- test('read-only recovery does not refresh a real Git index even when file stat metadata changes', t => {
- const { root } = fixture(t);
- for (const args of [['init', '--quiet'], ['add', 'src/example.ts']]) {
- const r = spawnSync('git', args, { cwd: root, encoding: 'utf8', windowsHide: true });
- assert.equal(r.status, 0, r.stderr);
- }
- const file = path.join(root, 'src/example.ts');
- const old = new Date(Date.now() - 60000); fs.utimesSync(file, old, old);
- const index = path.join(root, '.git/index'); const before = sha(fs.readFileSync(index));
- collectRecovery(root, { probe: false });
- assert.equal(sha(fs.readFileSync(index)), before);
- });
- test('progress updates the live summary and log while preserving history, assets and receipts', t => {
- const { root, config } = fixture(t); const ledger = fs.readFileSync(path.join(root, config.ledger));
- recordProgress(root, '只读核实完成,无新消息');
- const document = fs.readFileSync(path.join(root, 'docs/00-tracking/接续检查点.md'), 'utf8');
- assert.ok(document.includes('当前步骤/最新真实记录:只读核实完成,无新消息'));
- assert.ok(document.includes('HTML 预览:失败'));
- assert.ok(document.includes('不可覆盖')); assert.ok(document.includes('旧操作'));
- assert.ok(fs.readFileSync(path.join(root, 'docs/00-tracking/操作追踪.md'), 'utf8').includes('无新消息'));
- assert.deepEqual(fs.readFileSync(path.join(root, config.ledger)), ledger);
- updateStep(root, '下一步');
- const updated = JSON.parse(fs.readFileSync(path.join(root, config.ledger)));
- assert.equal(updated.recovery.currentStep, '下一步'); assert.equal(updated.actions.sms.confirmedAt, 'receipt-time');
- });
- test('a later runner result replaces a stale manual step in a fresh read-only recovery', t => {
- const { root } = fixture(t);
- recordProgress(root, '最新真实结果:已取得验证码,等待用户输入,不再次发送');
- const before = inventory(root);
- const result = collectRecovery(root, { probe: false, run: fakeRun });
- assert.equal(result.currentStep, '最新真实结果:已取得验证码,等待用户输入,不再次发送');
- assert.deepEqual(inventory(root), before);
- });
- test('a persisted new step survives interruption before its progress index is updated', t => {
- const { root, config } = fixture(t);
- recordProgress(root, '旧结果,不能覆盖后续已落盘步骤');
- const file = path.join(root, config.ledger);
- const state = JSON.parse(fs.readFileSync(file, 'utf8'));
- state.recovery.currentStep = '新步骤已落盘,索引更新前中断';
- put(root, config.ledger, state);
- const before = inventory(root);
- const result = collectRecovery(root, { probe: false, run: fakeRun });
- assert.equal(result.currentStep, state.recovery.currentStep);
- assert.ok(result.warnings.some(x => x.includes('最新进度索引与活动账本不符')));
- assert.deepEqual(inventory(root), before);
- });
- test('checkpoint writer does not bypass an existing writer lock', t => {
- const { root } = fixture(t); put(root, 'docs/00-tracking/接续检查点.md.lock', 'other writer');
- assert.throws(() => recordProgress(root, 'must not write'), /EEXIST/);
- assert.equal(fs.readFileSync(path.join(root, 'docs/00-tracking/接续检查点.md.lock'), 'utf8'), 'other writer');
- });
- test('Windows CRLF checkpoints retain their manual sections and accept progress updates', t => {
- const { root } = fixture(t);
- const file = path.join(root, 'docs/00-tracking/接续检查点.md');
- fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(/\n/g, '\r\n'));
- recordProgress(root, 'Windows 换行验证');
- const document = fs.readFileSync(file, 'utf8');
- assert.ok(document.includes('不可覆盖')); assert.ok(document.includes('Windows 换行验证'));
- });
- test('snapshot preserves untracked files and ignored private evidence with verified hashes', t => {
- const { root } = fixture(t); const result = createSnapshot(root, { run: fakeRun });
- const manifest = JSON.parse(fs.readFileSync(path.join(root, result.manifest), 'utf8'));
- assert.equal(manifest.dockerVolumesIncluded, false); assert.ok(manifest.deletions.includes('gone.txt'));
- for (const name of ['new.txt', '.local-backup/active/account.json', 'test-results/active/state.json', 'AGENTS.md']) assert.ok(manifest.files.some(x => x.path === name));
- for (const file of manifest.files) assert.equal(sha(fs.readFileSync(path.join(root, result.directory, 'files', file.path))), file.sha256);
- assert.equal(fs.readFileSync(path.join(root, result.directory, 'unstaged.patch'), 'utf8'), 'binary patch fixture\n');
- });
- test('snapshot refuses a ledger changed during collection and does not mark partial data complete', t => {
- const { root, config } = fixture(t); let count = 0;
- const run = (...args) => {
- const output = fakeRun(...args);
- if (++count === 4) { const state = JSON.parse(fs.readFileSync(path.join(root, config.ledger))); state.concurrent = true; put(root, config.ledger, state); }
- return output;
- };
- assert.throws(() => createSnapshot(root, { run }), /账本在快照期间变化/);
- const parent = path.join(root, '.local-backup/handoff');
- assert.ok(fs.readdirSync(parent).every(name => name.endsWith('.partial')));
- });
- test('snapshot detects a new untracked source created after the initial file collection', t => {
- const { root } = fixture(t); let created = false;
- const run = (...args) => {
- const output = fakeRun(...args); const commandArgs = args[2];
- if (commandArgs[0] === 'diff' && commandArgs.includes('--binary') && !created) {
- created = true; put(root, 'scripts/new-critical.mjs', 'new implementation');
- }
- if (commandArgs[0] === 'ls-files' && created) output.stdout += 'scripts/new-critical.mjs\0';
- return output;
- };
- assert.throws(() => createSnapshot(root, { run }), /新增\/删除文件/);
- assert.ok(fs.readdirSync(path.join(root, '.local-backup/handoff')).every(name => name.endsWith('.partial')));
- });
- test('broad private directory never recursively includes old handoff snapshots', t => {
- const { root, config } = fixture(t); config.privateDirectory = '.local-backup';
- put(root, 'docs/00-tracking/active-task.json', config);
- createSnapshot(root, { run: fakeRun });
- const second = createSnapshot(root, { run: fakeRun });
- const manifest = JSON.parse(fs.readFileSync(path.join(root, second.manifest)));
- assert.ok(manifest.files.every(x => !x.path.startsWith('.local-backup/handoff/')));
- });
- test('normalized output-directory aliases cannot be used as private configuration directories', t => {
- const { root, config } = fixture(t); config.privateDirectory = '.local-backup/./handoff';
- put(root, 'docs/00-tracking/active-task.json', config);
- assert.throws(() => collectRecovery(root, { probe: false, run: fakeRun }), /交接快照输出目录/);
- });
- test('Windows case aliases also exclude historical handoff snapshots', { skip: process.platform !== 'win32' }, t => {
- const { root, config } = fixture(t); config.privateDirectory = '.LOCAL-BACKUP';
- put(root, 'docs/00-tracking/active-task.json', config);
- createSnapshot(root, { run: fakeRun });
- const second = createSnapshot(root, { run: fakeRun });
- const manifest = JSON.parse(fs.readFileSync(path.join(root, second.manifest)));
- assert.ok(manifest.files.every(x => !x.path.toLowerCase().includes('handoff/')));
- });
- test('path traversal and links outside the project are rejected', t => {
- const { root } = fixture(t);
- for (const name of ['../outside', 'docs/../../outside', path.resolve(root, '..', 'outside')]) assert.throws(() => projectPath(root, name), /项目目录/);
- const link = path.join(root, 'linked');
- try { fs.symlinkSync(os.tmpdir(), link, 'junction'); }
- catch (e) { if (['EPERM', 'EACCES'].includes(e.code)) return; throw e; }
- assert.throws(() => projectPath(root, 'linked/anything'), /符号链接/);
- });
- test('a partial event proof never counts as completion', () => {
- assert.match(actionStatus({ attempted: true, proof: { sent: ['a'], reply: ['b'] } }), /禁止盲重试/);
- });
|