File size: 8,519 Bytes
d739b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// ์‹ค์ œ ํ…Œ์ŠคํŠธ ์„ฑ๊ณต๊ณผ ์˜ˆ์•ฝ ํ™œ์„ฑํ™”์˜ ์„ค์ • ์—ฐ๊ฒฐ์„ ๊ฒ€์‚ฌํ•œ๋‹ค.
const { test, after } = require('node:test'), assert = require('node:assert/strict');
const fs = require('fs'), path = require('path'), os = require('os');
const temp = fs.mkdtempSync(path.resolve(__dirname, '../../scratch/wrapper-certification-')), oldHome = os.homedir;
os.homedir = () => temp;
const ctx = require('../../src/context'); ctx.currentCwd = temp;
require('../../src/services/governance-client').cachedPolicy = { enabled: false };
require('../../src/wiki-run-archiver').archiveBatchRun = async () => ({ success: true });
const db = require('../../knowledge-db'), manager = require('../../src/batch-manager');
after(() => { manager.getScheduledJobsList().forEach(id => manager.unscheduleTask(id)); manager.cleanupAllActiveRuns(); os.homedir = oldHome; process.once('exit', () => fs.rmSync(temp, { recursive: true, force: true })); });
function task(id) { return { id, project_id: temp, name: id, is_active: 0, cron_expr: '0 0 1 JAN *', timezone: 'UTC', steps: [{ id: 'transform', type: 'transform', config: { script: 'return { ok: true };' } }] }; }
const saved = id => db.getBatchTasks(temp).find(t => t.id === id);
async function certify(item) { await manager.saveScheduledTask(temp, item); assert.equal((await manager.runTask(item, true)).success, true); return saved(item.id); }
test('a supplied success flag cannot create an active untested schedule', async () => {
  const item = { ...task('forged'), is_active: 1, is_tested_success: 1, tested_fingerprint: 'forged' };
  await assert.rejects(manager.saveScheduledTask(temp, item), /ํ…Œ์ŠคํŠธ|๊ฒ€์ฆ/);
  assert.equal(saved(item.id), undefined); assert.ok(!manager.getScheduledJobsList().includes(item.id));
});
test('editing tested steps cannot retain approval or activate the replacement', async () => {
  const item = task('edited'), before = await certify(item);
  const changed = { ...before, steps_json: JSON.stringify([{ ...item.steps[0], config: { script: 'return { untested: true };' } }]), is_active: 1 };
  await assert.rejects(manager.saveScheduledTask(temp, changed), /ํ…Œ์ŠคํŠธ|๊ฒ€์ฆ/);
  assert.equal(saved(item.id).steps_json, before.steps_json);
  await manager.saveScheduledTask(temp, { ...changed, is_active: 0 });
  assert.equal(saved(item.id).is_tested_success, 0); assert.equal(saved(item.id).tested_fingerprint, null);
});
test('a successful dry run persists a definition fingerprint and survives a schedule-only edit', async () => {
  const item = task('certified'), before = await certify(item);
  assert.match(before.tested_fingerprint, /^[a-f0-9]{64}$/);
  await manager.saveScheduledTask(temp, { ...before, name: 'renamed', cron_expr: '0 1 1 JAN *', is_active: 1 });
  assert.equal(saved(item.id).tested_fingerprint, before.tested_fingerprint); assert.equal(saved(item.id).is_tested_success, 1);
  const source = `require('os').homedir=()=>${JSON.stringify(temp)};const db=require(${JSON.stringify(path.resolve(__dirname,'../../knowledge-db'))});process.stdout.write(JSON.stringify(db.getBatchTasks(${JSON.stringify(temp)}).find(t=>t.id==='certified')));`;
  const output = require('child_process').execFileSync(process.execPath, ['-e', source], { env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' }, encoding: 'utf8', timeout: 5000 });
  const record = JSON.parse(output.trim().split('\n').at(-1)); assert.equal(record.tested_fingerprint, before.tested_fingerprint);
});
test('changing loop settings invalidates the certificate and copying it cannot approve a new task', async () => {
  const item = task('loop-change'), before = await certify(item);
  await assert.rejects(manager.saveScheduledTask(temp, { ...before, id: 'copied', is_active: 1 }), /ํ…Œ์ŠคํŠธ/);
  await manager.saveScheduledTask(temp, { ...before, loop_config: JSON.stringify({ max_iterations: 2 }), is_active: 0 });
  assert.equal(saved(item.id).is_tested_success, 0); assert.equal(saved(item.id).tested_fingerprint, null);
  db.runInTransaction(() => db.saveBatchTask(temp, { ...saved(item.id), is_active: 1 }));
  const runs = db.getBatchRuns(item.id).length;
  await assert.rejects(manager.fireScheduledTask(before), /ํ…Œ์ŠคํŠธ/);
  assert.equal(db.getBatchRuns(item.id).length, runs);
});
test('a later failed dry run clears previously successful evidence for the same definition', async () => {
  const item = task('failed-retest'), script = path.join(temp, 'retest.cjs');
  fs.writeFileSync(script, `if(require('fs').existsSync(${JSON.stringify(path.join(temp,'fail-retest'))}))process.exit(3);console.log('done');`);
  const cp = require('child_process'), node = process.versions.electron ? cp.execFileSync('node', ['-p', 'process.execPath'], { encoding: 'utf8' }).trim() : process.execPath;
  const quote = require('../../src/config/claude-execution-config').quoteShellArgument;
  item.steps = [{ id: 'cli', type: 'pty_agent', config: { is_oneshot: true, cli_engine: quote(node) + ' ' + quote(script), prompt: 'fixture', timeout: 5 } }];
  const before = await certify(item); assert.equal(before.is_tested_success, 1);
  fs.writeFileSync(path.join(temp, 'fail-retest'), 'fail');
  assert.equal((await manager.runTask(item, true)).success, false);
  assert.equal(saved(item.id).is_tested_success, 0); assert.equal(saved(item.id).tested_fingerprint, null);
});
test('legacy JSON success flags are not displayed as certified and reading preserves the file', () => {
  const file = path.join(temp, 'legacy.json'), item = { ...task('legacy'), is_tested_success: 1, is_active: 1 };
  const original = JSON.stringify({ batch_tasks: [item] }); fs.writeFileSync(file, original);
  const store = new (require('../../src/db/json-fallback-db'))({ filePath: file });
  try { assert.equal(store.getBatchTasks(temp)[0].is_tested_success, 0); }
  finally { store.close(); }
  assert.equal(fs.readFileSync(file, 'utf8'), original);
});
test('JSON certificate publication failure rolls back both memory and disk', () => {
  const file = path.join(temp, 'cert-write.json'), item = task('write-failure');
  const store = new (require('../../src/db/json-fallback-db'))({ filePath: file });
  store.saveBatchTask(temp, item); store.save(true); const original = fs.readFileSync(file, 'utf8');
  const files = require('../../src/utils/protected-file-write'), write = files.writeProtected;
  files.writeProtected = (...args) => { if (args[1]?.includes('cert-write.json')) throw new Error('fixture certificate disk failure'); return write(...args); };
  try {
    assert.throws(() => store.updateBatchTaskTestStatus(item.id, 1, require('../../src/utils/batch-definition').fingerprint(item)), /certificate disk failure/);
    assert.equal(store.getBatchTasks(temp)[0].is_tested_success, 0); assert.equal(store.getBatchTasks(temp)[0].tested_fingerprint, null);
    assert.equal(fs.readFileSync(file, 'utf8'), original);
  } finally { files.writeProtected = write; store.close(); }
});
test('a successful execution reports certificate storage failure without granting verification', async () => {
  const item = task('publication-failed'); await manager.saveScheduledTask(temp, item);
  const update = db.updateBatchTaskTestStatus;
  db.updateBatchTaskTestStatus = (...args) => { if (args[1] === 1) throw new Error('fixture certification publication failed'); return update(...args); };
  try {
    const result = await manager.runTask(item, true);
    assert.equal(result.success, true); assert.equal(result.testVerified, false); assert.match(result.certificationError, /publication failed/);
    assert.equal(saved(item.id).is_tested_success, 0);
  } finally { db.updateBatchTaskTestStatus = update; }
});
test('scheduled execution rechecks certification after waiting for its workspace', async () => {
  const item = await certify(task('revoked')); await manager.saveScheduledTask(temp, { ...item, is_active: 1 });
  const lease = await require('../../src/utils/workspace-lease').acquire(temp, 'fixture hold'); let pending;
  try {
    pending = manager.fireScheduledTask(saved(item.id), Date.UTC(new Date().getUTCFullYear() + 1, 0, 1));
    const end = Date.now() + 3000;
    while (db.getBatchRuns(item.id).length < 2) { if (Date.now() >= end) throw new Error('scheduled wait fixture timeout'); await new Promise(resolve => setTimeout(resolve, 10)); }
    db.updateBatchTaskTestStatus(item.id, 0);
  } finally { lease.release(); }
  const result = await pending; assert.equal(result.success, false); assert.match(result.error, /ํ…Œ์ŠคํŠธ/); assert.deepEqual(result.stepOutputs, {});
});