163 lines
6.5 KiB
JavaScript
163 lines
6.5 KiB
JavaScript
// Skill bundle member — SkillRepository over the skill admin.
|
|
// Directory layout, atomic writes, the delivery receipt and park/unpark
|
|
// moves live here, so the sync engine never builds a skill path itself.
|
|
import { cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
import { dirname, join } from 'node:path';
|
|
import { dshHome } from "../store.js";
|
|
import { sha256Hex } from "./shared.js";
|
|
const RECEIPT = '.manifest.json';
|
|
async function isDirectory(path) {
|
|
try {
|
|
return (await stat(path)).isDirectory();
|
|
}
|
|
catch {
|
|
return false;
|
|
}
|
|
}
|
|
/** Walk a skill folder skipping dot-prefixed names — the reserved-file rule. */
|
|
async function walkSkillFiles(dir) {
|
|
const files = [];
|
|
const walk = async (current, depth) => {
|
|
let entries;
|
|
try {
|
|
entries = await readdir(current, { withFileTypes: true });
|
|
}
|
|
catch {
|
|
return;
|
|
}
|
|
for (const entry of entries) {
|
|
if (entry.name.startsWith('.'))
|
|
continue;
|
|
const full = join(current, entry.name);
|
|
if (entry.isDirectory()) {
|
|
await walk(full, depth + 1);
|
|
continue;
|
|
}
|
|
if (!entry.isFile())
|
|
continue;
|
|
files.push({
|
|
rel: full.slice(dir.length + 1).replace(/\\/g, '/'),
|
|
bytes: await readFile(full),
|
|
mtimeMs: (await stat(full)).mtimeMs,
|
|
});
|
|
}
|
|
};
|
|
await walk(dir, 0);
|
|
return files.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
|
|
}
|
|
/** Parse the `.manifest.json` delivery receipt of one folder. */
|
|
async function readDeliveryReceipt(dir) {
|
|
try {
|
|
const raw = JSON.parse(await readFile(join(dir, RECEIPT), 'utf8'));
|
|
if (typeof raw !== 'object' || raw === null)
|
|
return undefined;
|
|
const record = raw;
|
|
if (typeof record.name !== 'string' || typeof record.revision !== 'number' || typeof record.manifest_sha256 !== 'string')
|
|
return undefined;
|
|
const files = Array.isArray(record.files)
|
|
? record.files.filter((file) => typeof file === 'object' && file !== null && typeof file.path === 'string' && typeof file.sha256 === 'string')
|
|
: undefined;
|
|
const delivery = { name: record.name, revision: record.revision, manifest: record.manifest_sha256 };
|
|
if (files !== undefined && files.length > 0)
|
|
delivery.files = files;
|
|
if (typeof record.synced_at === 'string')
|
|
delivery.syncedAt = record.synced_at;
|
|
return delivery;
|
|
}
|
|
catch {
|
|
return undefined;
|
|
}
|
|
}
|
|
export class AdminSkillRepository {
|
|
deps;
|
|
constructor(deps) {
|
|
this.deps = deps;
|
|
}
|
|
async list() {
|
|
const entries = [];
|
|
// Root skips dot-prefixed folders, mirroring the upload scan; holding
|
|
// takes every folder, mirroring the sync presence sweep.
|
|
for (const entry of await readdir(this.deps.skillsRoot(), { withFileTypes: true }).catch(() => [])) {
|
|
if (!entry.isDirectory() || entry.name.startsWith('.'))
|
|
continue;
|
|
entries.push({ name: entry.name, area: 'root', enabled: true });
|
|
}
|
|
for (const entry of await readdir(this.deps.holdingDir(), { withFileTypes: true }).catch(() => [])) {
|
|
if (!entry.isDirectory())
|
|
continue;
|
|
entries.push({ name: entry.name, area: 'holding', enabled: false });
|
|
}
|
|
return entries;
|
|
}
|
|
async read(name) {
|
|
const found = await this.deps.admin.locate(name);
|
|
if (found === undefined)
|
|
return undefined;
|
|
const area = found.area;
|
|
const files = (await walkSkillFiles(found.dir)).map((file) => ({
|
|
path: file.rel,
|
|
sha256: sha256Hex(file.bytes),
|
|
size: file.bytes.length,
|
|
data: file.bytes.toString('base64'),
|
|
mtimeMs: file.mtimeMs,
|
|
}));
|
|
return { name, area, files, delivery: await readDeliveryReceipt(found.dir) };
|
|
}
|
|
async write(name, bundle, options) {
|
|
const found = await this.deps.admin.locate(name);
|
|
// New skills land in root; a parked folder is written in place.
|
|
const dir = found?.dir ?? join(this.deps.skillsRoot(), name);
|
|
const previous = await readDeliveryReceipt(dir);
|
|
await mkdir(dir, { recursive: true });
|
|
const keep = new Set(bundle.files.map((file) => file.path));
|
|
const written = [];
|
|
let n = 0;
|
|
for (const file of bundle.files) {
|
|
const bytes = Buffer.from(file.data, 'base64');
|
|
if (sha256Hex(bytes) !== file.sha256)
|
|
throw new Error('checksum mismatch for ' + file.path);
|
|
const target = join(dir, ...file.path.split('/'));
|
|
await mkdir(dirname(target), { recursive: true });
|
|
const tmp = target + '.tmp-' + String(n++);
|
|
await writeFile(tmp, bytes);
|
|
await rename(tmp, target);
|
|
written.push({ path: file.path, sha256: file.sha256, size: bytes.length });
|
|
}
|
|
// Remove files the previous delivery owned but the new bundle does not.
|
|
if (previous?.files !== undefined) {
|
|
for (const file of previous.files) {
|
|
if (!keep.has(file.path))
|
|
await rm(join(dir, ...file.path.split('/')), { force: true });
|
|
}
|
|
}
|
|
const receipt = join(dir, RECEIPT);
|
|
if (options?.delivery === false) {
|
|
await rm(receipt, { force: true });
|
|
return;
|
|
}
|
|
const payload = { name, revision: bundle.revision, manifest_sha256: bundle.manifest_sha256, files: written, synced_at: new Date().toISOString() };
|
|
const tmp = receipt + '.tmp';
|
|
await writeFile(tmp, JSON.stringify(payload, null, 2) + '\n');
|
|
await rename(tmp, receipt);
|
|
}
|
|
async park(name) {
|
|
await this.deps.admin.setEnabled(name, false);
|
|
}
|
|
async unpark(name) {
|
|
await this.deps.admin.setEnabled(name, true);
|
|
}
|
|
async snapshot(name) {
|
|
const found = await this.deps.admin.locate(name);
|
|
if (found === undefined)
|
|
return undefined;
|
|
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
const target = join(dshHome(), '.dsh-brain-backups', 'sync', name, stamp);
|
|
await mkdir(dirname(target), { recursive: true });
|
|
await cp(found.dir, target, {
|
|
recursive: true,
|
|
filter: (source) => !source.split(/[\\/]/).includes('.git'),
|
|
});
|
|
return target;
|
|
}
|
|
}
|