- backup.mjs restore(relPaths): SCOPED per-fil-rollback erstatter hel-tre rmSync(srcDir)+cpSync. Ruller kun tilbake kjøringens egne skriv; parallelle økters skriv til søsken-filer overlever; intet destruktivt rm→cp-vindu. Nyskapte filer slettes; prior bytes gjenopprettes atomisk. - migrate-corpus.mjs: returnert restore() er nå en null-arg closure bundet til kjøringens skrive- liste (public API uendret) → scoped. detectStaleRollback aborterer ved forrige krasj-sentinel; cleanupOldBackups pruner backups forbi retention etter vellykket batch. - 5 drivere (backfill-status/-category, dedup-plain-header, relabel-dato/-dialect): writeFileSync → atomicWriteSync (crash-safe tmp+rename) + recovery-kontrakt i header. - backfill-category.mjs: refaktorert importerbar (isMain-guard + run()/planCategoryBackfill/ categoryForFile/FOLDER_CATEGORY-eksporter, parameterisert root) → testbar uten scan-side-effekt. - Tester (+16): 6 scoped-restore (parallel-preservering, ny-fil-sletting, throws-guard) erstatter 2 hel-tre; test-backfill-category (frosset taxonomi + hermetisk plan); test-driver-atomic-writes (5 drivere); migrate stale-abort + cleanup-wiring. Suite 859→875 exit 0. validate-plugin 250/0.
328 lines
12 KiB
JavaScript
328 lines
12 KiB
JavaScript
// tests/kb-update/test-backup-restore.test.mjs
|
|
// Unit tests for scripts/kb-update/lib/backup.mjs
|
|
|
|
import { test } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import {
|
|
mkdtempSync,
|
|
mkdirSync,
|
|
rmSync,
|
|
writeFileSync,
|
|
readFileSync,
|
|
readdirSync,
|
|
existsSync,
|
|
utimesSync,
|
|
} from 'node:fs';
|
|
import { tmpdir } from 'node:os';
|
|
import { join } from 'node:path';
|
|
import {
|
|
backupDir,
|
|
backupFile,
|
|
detectStaleRollback,
|
|
cleanupOldBackups,
|
|
backupTimestamp,
|
|
} from '../../scripts/kb-update/lib/backup.mjs';
|
|
|
|
function withTmp(fn) {
|
|
const dir = mkdtempSync(join(tmpdir(), 'bk-test-'));
|
|
try {
|
|
return fn(dir);
|
|
} finally {
|
|
rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
}
|
|
|
|
function makeSrc(root, files) {
|
|
mkdirSync(root, { recursive: true });
|
|
for (const [rel, content] of Object.entries(files)) {
|
|
const path = join(root, rel);
|
|
mkdirSync(join(path, '..'), { recursive: true });
|
|
writeFileSync(path, content, 'utf8');
|
|
}
|
|
}
|
|
|
|
function readAll(root) {
|
|
const out = {};
|
|
function walk(dir, prefix) {
|
|
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
const full = join(dir, entry.name);
|
|
const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
if (entry.isDirectory()) {
|
|
walk(full, rel);
|
|
} else if (entry.isFile()) {
|
|
out[rel] = readFileSync(full, 'utf8');
|
|
}
|
|
}
|
|
}
|
|
walk(root, '');
|
|
return out;
|
|
}
|
|
|
|
test('backupTimestamp — produces filesystem-safe ISO-ish format', () => {
|
|
const ts = backupTimestamp(new Date('2026-05-05T10:32:13.456Z'));
|
|
assert.equal(ts, '2026-05-05T10-32-13');
|
|
assert.match(ts, /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}$/);
|
|
});
|
|
|
|
test('backupDir — creates timestamped subdir under backupRoot', () => {
|
|
withTmp((tmp) => {
|
|
const src = join(tmp, 'skills');
|
|
const root = join(tmp, '.kb-backup');
|
|
makeSrc(src, { 'foo.md': 'A' });
|
|
|
|
const { backupPath } = backupDir(src, root);
|
|
assert.match(
|
|
backupPath,
|
|
/\.kb-backup\/\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}$/
|
|
);
|
|
assert.equal(existsSync(backupPath), true);
|
|
});
|
|
});
|
|
|
|
test('backupDir — copies content faithfully (deep equal)', () => {
|
|
withTmp((tmp) => {
|
|
const src = join(tmp, 'skills');
|
|
const root = join(tmp, '.kb-backup');
|
|
makeSrc(src, {
|
|
'a.md': 'alpha',
|
|
'sub/b.md': 'beta',
|
|
'sub/deep/c.md': 'gamma',
|
|
});
|
|
|
|
const { backupPath } = backupDir(src, root);
|
|
const original = readAll(src);
|
|
const copied = readAll(backupPath);
|
|
// The backup also contains .backup-meta.json — strip it before comparing.
|
|
delete copied['.backup-meta.json'];
|
|
assert.deepEqual(copied, original);
|
|
});
|
|
});
|
|
|
|
// --- backupFile: precise single-file backup (C2.3 config-write guard) ---
|
|
|
|
test('backupFile — copies one file into a timestamped subdir, preserving content', () => {
|
|
withTmp((tmp) => {
|
|
const file = join(tmp, 'ms-ai-architect.local.md');
|
|
const root = join(tmp, '.backups');
|
|
writeFileSync(file, 'PRIOR CONTENT', 'utf8');
|
|
|
|
const res = backupFile(file, root);
|
|
assert.ok(res && res.backupPath, 'returns the backup path');
|
|
assert.match(res.backupPath, /\.backups\/\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}\/ms-ai-architect\.local\.md$/);
|
|
assert.equal(readFileSync(res.backupPath, 'utf8'), 'PRIOR CONTENT');
|
|
});
|
|
});
|
|
|
|
test('backupFile — no-op (returns null) when the source file is absent', () => {
|
|
withTmp((tmp) => {
|
|
const res = backupFile(join(tmp, 'does-not-exist.md'), join(tmp, '.backups'));
|
|
assert.equal(res, null);
|
|
assert.equal(existsSync(join(tmp, '.backups')), false, 'no backup dir created when nothing to back up');
|
|
});
|
|
});
|
|
|
|
test('backupFile — throws on missing args', () => {
|
|
assert.throws(() => backupFile('', '/tmp/x'), /filePath/);
|
|
assert.throws(() => backupFile('/tmp/x', ''), /backupRoot/);
|
|
});
|
|
|
|
test('backupDir — writes .backup-meta.json sentinel inside backup', () => {
|
|
withTmp((tmp) => {
|
|
const src = join(tmp, 'skills');
|
|
const root = join(tmp, '.kb-backup');
|
|
makeSrc(src, { 'foo.md': 'A' });
|
|
const { backupPath } = backupDir(src, root);
|
|
const metaPath = join(backupPath, '.backup-meta.json');
|
|
assert.equal(existsSync(metaPath), true);
|
|
const meta = JSON.parse(readFileSync(metaPath, 'utf8'));
|
|
assert.equal(meta.schema_version, 1);
|
|
assert.equal(meta.src_dir, src);
|
|
assert.match(meta.created_at, /^\d{4}-\d{2}-\d{2}T/);
|
|
});
|
|
});
|
|
|
|
// --- restore(relPaths): SCOPED per-file rollback (RX-OPS2) ---
|
|
// The old restore() rm+cp'd the WHOLE srcDir, which deletes a parallel session's
|
|
// writes made after the backup and opens a destructive rm→cp window. restore() now
|
|
// takes the explicit list of relative paths THIS run wrote and rolls back only those.
|
|
|
|
test('restore(relPaths) — scoped: rolls back only listed files, preserves parallel writes', () => {
|
|
withTmp((tmp) => {
|
|
const src = join(tmp, 'skills');
|
|
const root = join(tmp, '.kb-backup');
|
|
makeSrc(src, { 'a.md': 'orig-a', 'b.md': 'orig-b' });
|
|
|
|
const handle = backupDir(src, root);
|
|
|
|
// This run mutates a.md; a PARALLEL session writes b.md AFTER the backup.
|
|
writeFileSync(join(src, 'a.md'), 'mutated-a', 'utf8');
|
|
writeFileSync(join(src, 'b.md'), 'parallel-b', 'utf8');
|
|
|
|
handle.restore(['a.md']); // roll back ONLY this run's own write
|
|
|
|
assert.equal(readFileSync(join(src, 'a.md'), 'utf8'), 'orig-a', 'listed file rolled back');
|
|
assert.equal(readFileSync(join(src, 'b.md'), 'utf8'), 'parallel-b', "parallel session's write preserved");
|
|
});
|
|
});
|
|
|
|
test('restore(relPaths) — scoped: deletes a file newly created this run', () => {
|
|
withTmp((tmp) => {
|
|
const src = join(tmp, 'skills');
|
|
const root = join(tmp, '.kb-backup');
|
|
makeSrc(src, { 'a.md': 'orig-a' });
|
|
|
|
const handle = backupDir(src, root);
|
|
writeFileSync(join(src, 'new.md'), 'created', 'utf8'); // absent at backup time
|
|
|
|
handle.restore(['new.md']);
|
|
|
|
assert.equal(existsSync(join(src, 'new.md')), false, 'file created this run removed on rollback');
|
|
assert.equal(readFileSync(join(src, 'a.md'), 'utf8'), 'orig-a', 'sibling untouched');
|
|
});
|
|
});
|
|
|
|
test('restore(relPaths) — scoped: restores a nested file to its pre-write bytes', () => {
|
|
withTmp((tmp) => {
|
|
const src = join(tmp, 'skills');
|
|
const root = join(tmp, '.kb-backup');
|
|
makeSrc(src, { 'sub/deep/c.md': 'orig-c', 'sub/other.md': 'orig-other' });
|
|
|
|
const handle = backupDir(src, root);
|
|
writeFileSync(join(src, 'sub/deep/c.md'), 'mutated-c', 'utf8');
|
|
writeFileSync(join(src, 'sub/other.md'), 'parallel-other', 'utf8');
|
|
|
|
handle.restore(['sub/deep/c.md']);
|
|
assert.equal(readFileSync(join(src, 'sub/deep/c.md'), 'utf8'), 'orig-c', 'nested file rolled back');
|
|
assert.equal(readFileSync(join(src, 'sub/other.md'), 'utf8'), 'parallel-other', 'unlisted nested sibling preserved');
|
|
});
|
|
});
|
|
|
|
test('restore(relPaths) — leaves no atomic-write temp file behind', () => {
|
|
withTmp((tmp) => {
|
|
const src = join(tmp, 'skills');
|
|
const root = join(tmp, '.kb-backup');
|
|
makeSrc(src, { 'a.md': 'orig-a' });
|
|
const handle = backupDir(src, root);
|
|
writeFileSync(join(src, 'a.md'), 'mutated-a', 'utf8');
|
|
handle.restore(['a.md']);
|
|
const names = Object.keys(readAll(src));
|
|
assert.equal(names.some((n) => /\.tmp\./.test(n)), false, 'no restore temp file survived');
|
|
});
|
|
});
|
|
|
|
test('restore — throws when relPaths is not an array (rollback must be scoped)', () => {
|
|
withTmp((tmp) => {
|
|
const src = join(tmp, 'skills');
|
|
const root = join(tmp, '.kb-backup');
|
|
makeSrc(src, { 'a.md': 'A' });
|
|
const handle = backupDir(src, root);
|
|
assert.throws(() => handle.restore(), /relPaths|scoped/i);
|
|
assert.throws(() => handle.restore('a.md'), /relPaths|scoped/i);
|
|
});
|
|
});
|
|
|
|
test('restore — sentinel is written then removed after a successful scoped restore', () => {
|
|
withTmp((tmp) => {
|
|
const src = join(tmp, 'skills');
|
|
const root = join(tmp, '.kb-backup');
|
|
makeSrc(src, { 'a.md': 'orig-a' });
|
|
const handle = backupDir(src, root);
|
|
writeFileSync(join(src, 'a.md'), 'mut', 'utf8');
|
|
handle.restore(['a.md']);
|
|
assert.equal(detectStaleRollback(root), false, 'sentinel cleared on success');
|
|
});
|
|
});
|
|
|
|
test('detectStaleRollback — true when sentinel exists, false when absent', () => {
|
|
withTmp((tmp) => {
|
|
const root = join(tmp, '.kb-backup');
|
|
mkdirSync(root, { recursive: true });
|
|
assert.equal(detectStaleRollback(root), false);
|
|
writeFileSync(join(root, '.rollback-in-progress'), '{}', 'utf8');
|
|
assert.equal(detectStaleRollback(root), true);
|
|
});
|
|
});
|
|
|
|
test('detectStaleRollback — sentinel persists when restore is interrupted', () => {
|
|
withTmp((tmp) => {
|
|
const root = join(tmp, '.kb-backup');
|
|
mkdirSync(root, { recursive: true });
|
|
// Simulate a crashed restore: sentinel was written but never removed.
|
|
writeFileSync(
|
|
join(root, '.rollback-in-progress'),
|
|
JSON.stringify({ started_at: new Date().toISOString() }),
|
|
'utf8'
|
|
);
|
|
// Sentinel must still be there until something explicitly clears it.
|
|
assert.equal(detectStaleRollback(root), true);
|
|
});
|
|
});
|
|
|
|
test('cleanupOldBackups — deletes backups older than retentionDays', () => {
|
|
withTmp((tmp) => {
|
|
const src = join(tmp, 'skills');
|
|
const root = join(tmp, '.kb-backup');
|
|
makeSrc(src, { 'foo.md': 'A' });
|
|
|
|
// Two backups. Age the first by overwriting its meta.created_at.
|
|
const oldHandle = backupDir(src, root);
|
|
const oldMetaPath = join(oldHandle.backupPath, '.backup-meta.json');
|
|
const oldMeta = JSON.parse(readFileSync(oldMetaPath, 'utf8'));
|
|
const tenDaysAgo = new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString();
|
|
oldMeta.created_at = tenDaysAgo;
|
|
writeFileSync(oldMetaPath, JSON.stringify(oldMeta, null, 2), 'utf8');
|
|
|
|
// Sleep-equivalent: bump to ensure distinct backup-id.
|
|
const newHandle = backupDir(src, root, { now: new Date(Date.now() + 1000) });
|
|
|
|
const result = cleanupOldBackups(root, 7);
|
|
assert.deepEqual(result.deleted, [oldHandle.backupPath]);
|
|
assert.deepEqual(result.kept, [newHandle.backupPath]);
|
|
assert.equal(existsSync(oldHandle.backupPath), false);
|
|
assert.equal(existsSync(newHandle.backupPath), true);
|
|
});
|
|
});
|
|
|
|
test('cleanupOldBackups — falls back to dir mtime when meta is missing', () => {
|
|
withTmp((tmp) => {
|
|
const root = join(tmp, '.kb-backup');
|
|
const oldDir = join(root, '2026-04-01T00-00-00');
|
|
mkdirSync(oldDir, { recursive: true });
|
|
writeFileSync(join(oldDir, 'orphan.md'), 'no meta', 'utf8');
|
|
// No .backup-meta.json. Set dir mtime to 30 days ago.
|
|
const past = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
|
|
utimesSync(oldDir, past, past);
|
|
|
|
const result = cleanupOldBackups(root, 7);
|
|
assert.deepEqual(result.deleted, [oldDir]);
|
|
assert.equal(existsSync(oldDir), false);
|
|
});
|
|
});
|
|
|
|
test('cleanupOldBackups — skips dirs with unresolvable age', () => {
|
|
withTmp((tmp) => {
|
|
const root = join(tmp, '.kb-backup');
|
|
const odd = join(root, 'questionable');
|
|
mkdirSync(odd, { recursive: true });
|
|
// Stub statSync via making the file behave normally; fallback to mtime
|
|
// works on real fs. To genuinely exercise the skip path we stub the warn
|
|
// hook and make the meta unparseable + mtime fresh enough to not delete.
|
|
writeFileSync(join(odd, '.backup-meta.json'), 'not json', 'utf8');
|
|
// mtime fresh → kept (not deleted), so the skip path is not hit. The
|
|
// skip-path guard only fires when statSync ALSO throws, which on real fs
|
|
// requires deletion mid-iteration. Simulate with a dir that exists but
|
|
// becomes inaccessible — out of scope for portable tests. Instead verify
|
|
// the documented contract: unparseable meta with fresh mtime → kept.
|
|
const result = cleanupOldBackups(root, 7);
|
|
assert.deepEqual(result.kept, [odd]);
|
|
assert.deepEqual(result.deleted, []);
|
|
});
|
|
});
|
|
|
|
test('cleanupOldBackups — handles non-existent backupRoot gracefully', () => {
|
|
withTmp((tmp) => {
|
|
const root = join(tmp, 'never-created');
|
|
const result = cleanupOldBackups(root, 7);
|
|
assert.deepEqual(result, { kept: [], deleted: [], skipped: [] });
|
|
});
|
|
});
|