test-project-resume.mjs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. import test from 'node:test';
  2. import assert from 'node:assert/strict';
  3. import fs from 'node:fs';
  4. import os from 'node:os';
  5. import path from 'node:path';
  6. import { createHash } from 'node:crypto';
  7. import { spawnSync } from 'node:child_process';
  8. import { fileURLToPath } from 'node:url';
  9. import { actionStatus, collectRecovery, createSnapshot, projectPath, recordProgress, updateStep } from './lib/project-recovery.mjs';
  10. const sha = bytes => createHash('sha256').update(bytes).digest('hex');
  11. const put = (root, name, data) => {
  12. const file = path.join(root, name); fs.mkdirSync(path.dirname(file), { recursive: true });
  13. fs.writeFileSync(file, typeof data === 'string' ? data : JSON.stringify(data));
  14. };
  15. function fixture(t) {
  16. const root = fs.mkdtempSync(path.join(os.tmpdir(), 'fmode-recovery-test-'));
  17. t.after(() => {
  18. assert.equal(path.dirname(root), os.tmpdir());
  19. assert.ok(path.basename(root).startsWith('fmode-recovery-test-'));
  20. fs.rmSync(root, { recursive: true, force: true });
  21. });
  22. 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' };
  23. put(root, 'docs/00-tracking/active-task.json', config);
  24. 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');
  25. for (const name of ['AGENTS.md', 'CLAUDE.md', 'docs/README.md', 'docs/00-tracking/操作追踪.md', config.report, config.previousCheckpoint]) put(root, name, '保留 ' + name);
  26. put(root, 'src/example.ts', 'existing source'); put(root, 'new.txt', 'untracked');
  27. put(root, '.local-backup/active/account.json', { token: 'private-fixture-token' });
  28. put(root, 'test-results/active/file-events.json', []);
  29. 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: '失败' }] });
  30. return { root, config };
  31. }
  32. function fakeRun(root, command, args) {
  33. if (command !== 'git') return { ok: false, stdout: '', error: command + ' unavailable' };
  34. if (args[0] === 'rev-parse') return { ok: true, stdout: 'abc123\n' };
  35. if (args[0] === 'status') return { ok: true, stdout: ' M src/example.ts\n?? new.txt\n' };
  36. if (args[0] === 'ls-files') return { ok: true, stdout: 'new.txt\0' };
  37. if (args.includes('--name-only')) return { ok: true, stdout: 'src/example.ts\0gone.txt\0' };
  38. if (args[0] === 'diff') return { ok: true, stdout: 'binary patch fixture\n' };
  39. throw Error('Unexpected command: ' + command + ' ' + args.join(' '));
  40. }
  41. function inventory(root) {
  42. const rows = [];
  43. const walk = name => {
  44. for (const item of fs.readdirSync(path.join(root, name), { withFileTypes: true })) {
  45. const rel = path.join(name, item.name);
  46. item.isDirectory() ? walk(rel) : rows.push([rel, sha(fs.readFileSync(path.join(root, rel)))]);
  47. }
  48. };
  49. walk(''); return rows;
  50. }
  51. test('default recovery is read-only, retains receipts and never exposes tokens', t => {
  52. const { root } = fixture(t); const before = inventory(root); const calls = [];
  53. const result = collectRecovery(root, { run: (...args) => { calls.push(args); return fakeRun(...args); } });
  54. assert.deepEqual(inventory(root), before);
  55. assert.ok(result.actions.find(x => x.key === 'sms').status.includes('不重复'));
  56. assert.ok(result.actions.find(x => x.key === 'file').status.includes('不重发'));
  57. assert.ok(result.actions.find(x => x.key === 'pending').status.includes('禁止盲重试'));
  58. assert.deepEqual(result.checks.map(x => x.status), ['通过']);
  59. assert.ok(result.warnings.some(x => x.includes('Docker')));
  60. assert.ok(calls.every(([, command, args]) => command === 'git' || (command === 'adb' && args[0] === 'devices') || (command === 'docker' && args[0] === 'version')));
  61. assert.ok(!JSON.stringify(result).includes('private-fixture-token'));
  62. assert.ok(!JSON.stringify(result).includes('do-not-display'));
  63. });
  64. test('CLI offline read also leaves the fixture unchanged without device dependencies', t => {
  65. const { root } = fixture(t); const before = inventory(root);
  66. const cli = fileURLToPath(new URL('./project-resume.mjs', import.meta.url));
  67. const r = spawnSync(process.execPath, [cli, '--root=' + root, '--offline', '--json'], { encoding: 'utf8', windowsHide: true });
  68. assert.equal(r.status, 0, r.stderr);
  69. assert.equal(JSON.parse(r.stdout).environment.checked, false);
  70. assert.deepEqual(inventory(root), before);
  71. });
  72. test('missing evidence, changed sources and damaged ledger are reported without reconstruction', t => {
  73. const { root, config } = fixture(t);
  74. fs.unlinkSync(path.join(root, 'test-results/active/file-events.json')); put(root, 'src/example.ts', 'changed');
  75. let result = collectRecovery(root, { probe: false, run: fakeRun });
  76. assert.equal(result.missingEvidence.length, 1); assert.equal(result.sourceChanges.length, 1);
  77. put(root, config.ledger, '{interrupted');
  78. result = collectRecovery(root, { probe: false, run: fakeRun });
  79. assert.ok(result.warnings.some(x => x.includes('账本缺失或损坏')));
  80. assert.equal(fs.readFileSync(path.join(root, config.ledger), 'utf8'), '{interrupted');
  81. });
  82. test('a stale lock is retained and prevents snapshots and step updates', t => {
  83. const { root } = fixture(t); const lock = path.join(root, 'test-results/active/runner.lock');
  84. put(root, 'test-results/active/runner.lock', { pid: 2147483647, stage: 'unknown-result' });
  85. assert.ok(collectRecovery(root, { probe: false, run: fakeRun }).lock);
  86. assert.throws(() => createSnapshot(root, { run: fakeRun }), /执行锁/);
  87. assert.throws(() => updateStep(root, 'cannot overwrite'), /EEXIST/);
  88. assert.ok(fs.existsSync(lock));
  89. });
  90. test('a checkpoint lock is visible in default recovery without being removed', t => {
  91. const { root } = fixture(t);
  92. put(root, 'docs/00-tracking/接续检查点.md.lock', { pid: 2147483647, stage: 'checkpoint' });
  93. const result = collectRecovery(root, { probe: false, run: fakeRun });
  94. assert.ok(result.checkpointLock); assert.ok(result.warnings.some(x => x.includes('检查点写入锁')));
  95. assert.ok(fs.existsSync(path.join(root, 'docs/00-tracking/接续检查点.md.lock')));
  96. });
  97. test('valid JSON with an invalid ledger shape degrades to a warning without reconstruction', t => {
  98. const { root, config } = fixture(t);
  99. for (const invalid of ['null', '[]', '{"actions":[]}', '{"actions":{"broken":null}}', '{"checks":{}}']) {
  100. put(root, config.ledger, invalid);
  101. const result = collectRecovery(root, { probe: false, run: fakeRun });
  102. assert.ok(result.warnings.some(x => x.includes('账本缺失或损坏')));
  103. assert.equal(fs.readFileSync(path.join(root, config.ledger), 'utf8'), invalid);
  104. }
  105. });
  106. test('read-only recovery does not refresh a real Git index even when file stat metadata changes', t => {
  107. const { root } = fixture(t);
  108. for (const args of [['init', '--quiet'], ['add', 'src/example.ts']]) {
  109. const r = spawnSync('git', args, { cwd: root, encoding: 'utf8', windowsHide: true });
  110. assert.equal(r.status, 0, r.stderr);
  111. }
  112. const file = path.join(root, 'src/example.ts');
  113. const old = new Date(Date.now() - 60000); fs.utimesSync(file, old, old);
  114. const index = path.join(root, '.git/index'); const before = sha(fs.readFileSync(index));
  115. collectRecovery(root, { probe: false });
  116. assert.equal(sha(fs.readFileSync(index)), before);
  117. });
  118. test('progress updates the live summary and log while preserving history, assets and receipts', t => {
  119. const { root, config } = fixture(t); const ledger = fs.readFileSync(path.join(root, config.ledger));
  120. recordProgress(root, '只读核实完成,无新消息');
  121. const document = fs.readFileSync(path.join(root, 'docs/00-tracking/接续检查点.md'), 'utf8');
  122. assert.ok(document.includes('当前步骤/最新真实记录:只读核实完成,无新消息'));
  123. assert.ok(document.includes('HTML 预览:失败'));
  124. assert.ok(document.includes('不可覆盖')); assert.ok(document.includes('旧操作'));
  125. assert.ok(fs.readFileSync(path.join(root, 'docs/00-tracking/操作追踪.md'), 'utf8').includes('无新消息'));
  126. assert.deepEqual(fs.readFileSync(path.join(root, config.ledger)), ledger);
  127. updateStep(root, '下一步');
  128. const updated = JSON.parse(fs.readFileSync(path.join(root, config.ledger)));
  129. assert.equal(updated.recovery.currentStep, '下一步'); assert.equal(updated.actions.sms.confirmedAt, 'receipt-time');
  130. });
  131. test('a later runner result replaces a stale manual step in a fresh read-only recovery', t => {
  132. const { root } = fixture(t);
  133. recordProgress(root, '最新真实结果:已取得验证码,等待用户输入,不再次发送');
  134. const before = inventory(root);
  135. const result = collectRecovery(root, { probe: false, run: fakeRun });
  136. assert.equal(result.currentStep, '最新真实结果:已取得验证码,等待用户输入,不再次发送');
  137. assert.deepEqual(inventory(root), before);
  138. });
  139. test('a persisted new step survives interruption before its progress index is updated', t => {
  140. const { root, config } = fixture(t);
  141. recordProgress(root, '旧结果,不能覆盖后续已落盘步骤');
  142. const file = path.join(root, config.ledger);
  143. const state = JSON.parse(fs.readFileSync(file, 'utf8'));
  144. state.recovery.currentStep = '新步骤已落盘,索引更新前中断';
  145. put(root, config.ledger, state);
  146. const before = inventory(root);
  147. const result = collectRecovery(root, { probe: false, run: fakeRun });
  148. assert.equal(result.currentStep, state.recovery.currentStep);
  149. assert.ok(result.warnings.some(x => x.includes('最新进度索引与活动账本不符')));
  150. assert.deepEqual(inventory(root), before);
  151. });
  152. test('checkpoint writer does not bypass an existing writer lock', t => {
  153. const { root } = fixture(t); put(root, 'docs/00-tracking/接续检查点.md.lock', 'other writer');
  154. assert.throws(() => recordProgress(root, 'must not write'), /EEXIST/);
  155. assert.equal(fs.readFileSync(path.join(root, 'docs/00-tracking/接续检查点.md.lock'), 'utf8'), 'other writer');
  156. });
  157. test('Windows CRLF checkpoints retain their manual sections and accept progress updates', t => {
  158. const { root } = fixture(t);
  159. const file = path.join(root, 'docs/00-tracking/接续检查点.md');
  160. fs.writeFileSync(file, fs.readFileSync(file, 'utf8').replace(/\n/g, '\r\n'));
  161. recordProgress(root, 'Windows 换行验证');
  162. const document = fs.readFileSync(file, 'utf8');
  163. assert.ok(document.includes('不可覆盖')); assert.ok(document.includes('Windows 换行验证'));
  164. });
  165. test('snapshot preserves untracked files and ignored private evidence with verified hashes', t => {
  166. const { root } = fixture(t); const result = createSnapshot(root, { run: fakeRun });
  167. const manifest = JSON.parse(fs.readFileSync(path.join(root, result.manifest), 'utf8'));
  168. assert.equal(manifest.dockerVolumesIncluded, false); assert.ok(manifest.deletions.includes('gone.txt'));
  169. 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));
  170. for (const file of manifest.files) assert.equal(sha(fs.readFileSync(path.join(root, result.directory, 'files', file.path))), file.sha256);
  171. assert.equal(fs.readFileSync(path.join(root, result.directory, 'unstaged.patch'), 'utf8'), 'binary patch fixture\n');
  172. });
  173. test('snapshot refuses a ledger changed during collection and does not mark partial data complete', t => {
  174. const { root, config } = fixture(t); let count = 0;
  175. const run = (...args) => {
  176. const output = fakeRun(...args);
  177. if (++count === 4) { const state = JSON.parse(fs.readFileSync(path.join(root, config.ledger))); state.concurrent = true; put(root, config.ledger, state); }
  178. return output;
  179. };
  180. assert.throws(() => createSnapshot(root, { run }), /账本在快照期间变化/);
  181. const parent = path.join(root, '.local-backup/handoff');
  182. assert.ok(fs.readdirSync(parent).every(name => name.endsWith('.partial')));
  183. });
  184. test('snapshot detects a new untracked source created after the initial file collection', t => {
  185. const { root } = fixture(t); let created = false;
  186. const run = (...args) => {
  187. const output = fakeRun(...args); const commandArgs = args[2];
  188. if (commandArgs[0] === 'diff' && commandArgs.includes('--binary') && !created) {
  189. created = true; put(root, 'scripts/new-critical.mjs', 'new implementation');
  190. }
  191. if (commandArgs[0] === 'ls-files' && created) output.stdout += 'scripts/new-critical.mjs\0';
  192. return output;
  193. };
  194. assert.throws(() => createSnapshot(root, { run }), /新增\/删除文件/);
  195. assert.ok(fs.readdirSync(path.join(root, '.local-backup/handoff')).every(name => name.endsWith('.partial')));
  196. });
  197. test('broad private directory never recursively includes old handoff snapshots', t => {
  198. const { root, config } = fixture(t); config.privateDirectory = '.local-backup';
  199. put(root, 'docs/00-tracking/active-task.json', config);
  200. createSnapshot(root, { run: fakeRun });
  201. const second = createSnapshot(root, { run: fakeRun });
  202. const manifest = JSON.parse(fs.readFileSync(path.join(root, second.manifest)));
  203. assert.ok(manifest.files.every(x => !x.path.startsWith('.local-backup/handoff/')));
  204. });
  205. test('normalized output-directory aliases cannot be used as private configuration directories', t => {
  206. const { root, config } = fixture(t); config.privateDirectory = '.local-backup/./handoff';
  207. put(root, 'docs/00-tracking/active-task.json', config);
  208. assert.throws(() => collectRecovery(root, { probe: false, run: fakeRun }), /交接快照输出目录/);
  209. });
  210. test('Windows case aliases also exclude historical handoff snapshots', { skip: process.platform !== 'win32' }, t => {
  211. const { root, config } = fixture(t); config.privateDirectory = '.LOCAL-BACKUP';
  212. put(root, 'docs/00-tracking/active-task.json', config);
  213. createSnapshot(root, { run: fakeRun });
  214. const second = createSnapshot(root, { run: fakeRun });
  215. const manifest = JSON.parse(fs.readFileSync(path.join(root, second.manifest)));
  216. assert.ok(manifest.files.every(x => !x.path.toLowerCase().includes('handoff/')));
  217. });
  218. test('path traversal and links outside the project are rejected', t => {
  219. const { root } = fixture(t);
  220. for (const name of ['../outside', 'docs/../../outside', path.resolve(root, '..', 'outside')]) assert.throws(() => projectPath(root, name), /项目目录/);
  221. const link = path.join(root, 'linked');
  222. try { fs.symlinkSync(os.tmpdir(), link, 'junction'); }
  223. catch (e) { if (['EPERM', 'EACCES'].includes(e.code)) return; throw e; }
  224. assert.throws(() => projectPath(root, 'linked/anything'), /符号链接/);
  225. });
  226. test('a partial event proof never counts as completion', () => {
  227. assert.match(actionStatus({ attempted: true, proof: { sent: ['a'], reply: ['b'] } }), /禁止盲重试/);
  228. });