dsh-brain/lib/skill-sync.js

592 lines
27 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Bidirectional skill sync between the cloud skill center and the local
* DSH skills directory (`$DSH_HOME/skills` by default).
*
* The cloud center is the hub, the local directory is a working copy, and
* the DSH skills manager keeps owning local management — this module only
* moves files, in both directions:
*
* - DOWN: cloud skills are installed exactly like the platform's own
* `skills-sync` tool does it — bundle hash and per-file checksums are
* verified before anything lands, writes are atomic per file, and a
* per-skill `.manifest.json` records what the cloud delivered.
* - UP: skills that originated locally (installed by the skills manager,
* imported, or written by hand) are published to the center as new
* revisions, guarded by the center's `expected_revision` check.
*
* Safety rules (deliberate, in order):
* 1. A cloud-delivered skill is never re-uploaded. If its local files no
* longer match the delivery manifest, the skill is flagged as a
* conflict and left completely alone.
* 2. A local deletion never deletes the cloud copy.
* 3. A name that already exists on the other side is never hijacked;
* it is reported as a conflict for a human to resolve.
* 4. Bundles whose scripts changed on the cloud side are not installed
* until the change is acknowledged in the dashboard, mirroring the
* center's own review flag.
* 5. Only the center's file layout is uploadable (SKILL.md at the root,
* everything else under references/, scripts/ or assets/, with the
* center's extension allowlist). Anything else is reported, never
* silently trimmed.
*/
import { randomUUID } from 'node:crypto';
import { CLOUD_SKILL_NAME, isCloudSkillPath, linkedSkillManifest, MAX_FILE_BYTES, MAX_FILES, MAX_SKILL_BYTES, parseSkillFrontmatter, TEXT_EXT } from "./skills/shared.js";
import { mkdir, readFile, rename, stat, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { describeError } from "./api.js";
import { dshHome, migrateLegacyFile } from "./store.js";
// Compatibility re-exports: these format helpers lived here before the
// skill/cloud-sync seam; the skill bundle owns them now (skills/shared.ts).
// Re-exported so existing import sites keep working during the migration.
export { CLOUD_SKILL_NAME, MAX_FILES, MAX_FILE_BYTES, MAX_SKILL_BYTES, MAX_DEPTH, TEXT_EXT, BINARY_EXT, SCRIPT_EXT, sha256Hex, linkedSkillManifest, isCloudSkillPath, parseSkillFrontmatter, } from "./skills/shared.js";
/** Sidecar state: `$DSH_HOME/dsh-brain-skills.json` (legacy `cloud-memory-skills.json` migrates on first use). */
/** Absolute sidecar path, carrying the pre-rename file over on first use. */
export function skillsStatePath() {
const target = join(dshHome(), 'dsh-brain-skills.json');
migrateLegacyFile(target, join(dshHome(), 'cloud-memory-skills.json'));
return target;
}
export class SkillSync {
deps;
running = false;
current = {
running: false, downloaded: [], uploaded: [], updated: [], conflicts: [], skipped: 0,
};
constructor(deps) {
this.deps = deps;
}
/** Stats of the latest pass, for the status endpoint. */
stats() {
return this.current;
}
/** SkillSyncGate: true while a pass is in flight. */
isRunning() {
return this.running || this.current.running;
}
/**
* SkillSyncGate: where one skill folder came from. `null` means the
* folder is not known to the sync; the sidecar is read through an
* mtime memo so panel listing stays cheap.
*/
async provenance(name) {
const state = await this.loadStateCached();
for (const record of Object.values(state.uploaded)) {
if (record.folder === name) {
return { name, origin: 'uploaded', revision: record.revision, manifest: record.manifest, syncedAt: record.syncedAt };
}
}
const delivered = state.delivered[name];
if (delivered !== undefined) {
return { name, origin: 'cloud-delivered', manifest: delivered.manifest };
}
return null;
}
stateCache;
async loadStateCached() {
const info = await stat(this.statePath()).catch(() => undefined);
const mtimeMs = info?.mtimeMs ?? -1;
if (this.stateCache !== undefined && this.stateCache.mtimeMs === mtimeMs)
return this.stateCache.state;
const state = await this.loadState();
this.stateCache = { mtimeMs, state };
return state;
}
/** True when a cloud-delivered bundle still matches its receipt. */
deliveredIntact(local, delivery) {
if (local === undefined)
return false;
const recorded = delivery.files ?? [];
if (local.files.length !== recorded.length)
return false;
const byPath = new Map(local.files.map((file) => [file.path, file.sha256]));
return recorded.every((file) => byPath.get(file.path) === file.sha256);
}
statePath() {
return skillsStatePath();
}
/**
* Record a cloud-delivered skill. Upload provenance is cleared in the same
* transition: a skill has exactly one source of truth. Keeping both marks
* makes the DOWN pass skip the name (uploaded) while the UP pass skips its
* local folder (delivery manifest), so neither side ever syncs again.
*/
markDelivered(state, name, manifest) {
state.delivered[name] = { manifest };
delete state.uploaded[name];
}
/**
* Record a locally-originated upload. The delivery marker is cleared in the
* same transition, so the next local edit is uploaded again instead of being
* skipped as cloud-origin.
*/
markUploaded(state, name, record) {
state.uploaded[name] = record;
delete state.delivered[name];
}
async loadState() {
const clean = { version: 1, uploaded: {}, delivered: {}, removed: {} };
try {
const parsed = JSON.parse(await readFile(this.statePath(), 'utf8'));
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
const raw = parsed;
const map = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
return {
version: 1,
uploaded: map(raw.uploaded),
delivered: map(raw.delivered),
removed: map(raw.removed),
};
}
}
catch {
// Missing or corrupt sidecar: start clean; the cloud is the truth.
}
return clean;
}
async saveState(state) {
const path = this.statePath();
await mkdir(dirname(path), { recursive: true });
const temporary = `${path}.tmp-${process.pid}`;
await writeFile(temporary, JSON.stringify(state, null, 2));
await rename(temporary, path);
}
/** One full pass; never throws — outcomes land in the stats. */
async syncOnce() {
if (this.running)
return this.current;
const settings = this.deps.settings();
if (!settings.enabled || !settings.skillsSyncEnabled)
return this.current;
this.running = true;
const stats = {
running: true, downloaded: [], uploaded: [], updated: [], conflicts: [], skipped: 0,
};
this.current = stats;
try {
await this.pass(stats);
stats.lastRunAt = new Date().toISOString();
}
catch (error) {
stats.lastError = error instanceof Error ? error.message : String(error);
this.deps.log(`skill sync failed: ${stats.lastError}`);
}
finally {
stats.running = false;
this.running = false;
this.current = stats;
}
return this.current;
}
/** Record a conflict once per pass, however many rules trip over it. */
conflict(stats, name, reason) {
if (!stats.conflicts.some((item) => item.name === name && item.reason === reason)) {
stats.conflicts.push({ name, reason });
}
}
/** One full pass; never throws — outcomes land in the stats. */
async pass(stats) {
const repo = this.deps.repository();
const client = this.deps.client();
const listing = await client.listSkills();
if (!listing.ok)
throw new Error(`skill listing failed: ${describeError(listing.error)}`);
const items = (listing.data.items ?? []).filter((item) => typeof item.name === 'string' && CLOUD_SKILL_NAME.test(item.name));
const cloudByName = new Map(items.map((item) => [item.name, item]));
const state = await this.loadState();
let stateDirty = false;
// Self-heal: an uploaded folder whose delivery receipt reappeared (a
// restore, a hand copy) counts as cloud-delivered from now on.
for (const name of Object.keys(state.uploaded)) {
const local = await repo.read(name);
const delivery = local?.delivery;
if (delivery !== undefined) {
this.markDelivered(state, name, delivery.manifest ?? '');
stateDirty = true;
}
}
// DOWN: cloud is the truth. Locally modified deliveries and name
// collisions are reported, never overwritten silently.
for (const item of items) {
if (item.enabled === false) {
stats.skipped += 1;
continue;
}
if (state.uploaded[item.name] !== undefined) {
stats.skipped += 1;
continue;
}
const removed = state.removed[item.name];
const local = await repo.read(item.name);
const exists = local !== undefined;
const delivery = local?.delivery;
if (removed !== undefined && exists) {
delete state.removed[item.name];
stateDirty = true;
}
else if (removed !== undefined && item.manifest_sha256 === removed.manifest) {
stats.skipped += 1;
continue;
}
else if (removed !== undefined) {
delete state.removed[item.name];
stateDirty = true;
}
if (exists && delivery !== undefined) {
if (!this.deliveredIntact(local, delivery)) {
this.conflict(stats, item.name, 'locally_modified');
continue;
}
if (delivery.manifest === item.manifest_sha256) {
if (state.delivered[item.name]?.manifest !== item.manifest_sha256) {
this.markDelivered(state, item.name, item.manifest_sha256 ?? '');
stateDirty = true;
}
stats.skipped += 1;
continue;
}
}
else if (exists) {
this.conflict(stats, item.name, 'name_collision');
continue;
}
if (item.script_changed === true) {
this.conflict(stats, item.name, 'script_review_required');
continue;
}
const bundle = await client.skillBundle(item.name);
if (!bundle.ok) {
this.conflict(stats, item.name, `bundle_failed: ${describeError(bundle.error)}`);
continue;
}
if (linkedSkillManifest(bundle.data.files) !== bundle.data.manifest_sha256) {
this.conflict(stats, item.name, 'manifest_mismatch');
continue;
}
if (bundle.data.script_changed === true) {
this.conflict(stats, item.name, 'script_review_required');
continue;
}
await repo.write(item.name, bundle.data);
this.markDelivered(state, item.name, bundle.data.manifest_sha256);
stateDirty = true;
if (exists)
stats.updated.push(item.name);
else
stats.downloaded.push(item.name);
}
// UP: only local-origin folders ride. A delivery receipt means the
// cloud owns the name, so its local edits go through conflicts.
for (const entry of await repo.list()) {
if (entry.area !== 'root')
continue;
const local = await repo.read(entry.name);
if (local === undefined)
continue;
if (local.delivery !== undefined)
continue;
const skill = await this.readLocalSkill(local, entry.name);
if (skill === undefined)
continue;
if (typeof skill === 'string') {
this.conflict(stats, entry.name, skill);
continue;
}
const record = state.uploaded[skill.name];
const cloud = cloudByName.get(skill.name);
if (cloud !== undefined && record === undefined) {
this.conflict(stats, skill.name, 'name_collision');
continue;
}
if (record !== undefined && record.manifest === skill.manifest) {
stats.skipped += 1;
continue;
}
const files = skill.files.map((file) => {
const ext = file.path.slice(file.path.lastIndexOf('.')).toLowerCase();
return TEXT_EXT.has(ext)
? { path: file.path, content: Buffer.from(file.data, 'base64').toString('utf8') }
: { path: file.path, base64: file.data };
});
const operationId = `dsh-skill-${randomUUID()}`;
if (record === undefined || cloud === undefined) {
const created = await client.createSkill({
name: skill.name,
description: skill.description,
execution_mode: skill.hasScripts ? 'local-bundle' : 'prompt-only',
files,
expected_revision: 0,
operation_id: operationId,
});
if (!created.ok) {
this.conflict(stats, skill.name, `upload_failed: ${describeError(created.error)}`);
continue;
}
this.markUploaded(state, skill.name, {
folder: entry.name,
revision: created.data.skill?.revision ?? created.data.revision ?? 1,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
});
stateDirty = true;
stats.uploaded.push(skill.name);
}
else {
if (cloud.revision !== undefined && cloud.revision !== record.revision) {
this.conflict(stats, skill.name, 'cloud_newer');
continue;
}
const updated = await client.updateSkill(skill.name, {
description: skill.description,
files,
expected_revision: record.revision,
operation_id: operationId,
});
if (!updated.ok) {
const reason = updated.error.code === 'revision_conflict' ? 'cloud_newer' : `upload_failed: ${describeError(updated.error)}`;
this.conflict(stats, skill.name, reason);
continue;
}
this.markUploaded(state, skill.name, {
folder: entry.name,
revision: updated.data.skill?.revision ?? updated.data.revision ?? record.revision + 1,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
});
stateDirty = true;
stats.updated.push(skill.name);
}
}
// Presence counts the parking area too: a parked skill is disabled,
// not deleted. Anything missing from both is a deliberate removal
// (remembered, so it is not resurrected); the cloud copy stays.
const presentFolders = new Set((await repo.list()).map((entry) => entry.name));
for (const [name, record] of Object.entries(state.uploaded)) {
if (!presentFolders.has(record.folder)) {
state.removed[name] = { manifest: cloudByName.get(name)?.manifest_sha256 ?? record.manifest };
delete state.uploaded[name];
stateDirty = true;
}
}
for (const [name, record] of Object.entries(state.delivered)) {
if (!presentFolders.has(name)) {
state.removed[name] = { manifest: record.manifest };
delete state.delivered[name];
stateDirty = true;
}
}
if (stateDirty)
await this.saveState(state);
const changed = stats.downloaded.length + stats.uploaded.length + stats.updated.length;
if (changed > 0 || stats.conflicts.length > 0) {
this.deps.log(`skill sync: ${stats.downloaded.length} downloaded, ${stats.uploaded.length} uploaded, ${stats.updated.length} updated, ${stats.conflicts.length} conflict(s)}`);
}
}
/**
* Read one repository bundle into the sync shape. Returns undefined
* when the folder is not a skill at all, or a machine-readable reason.
*/
async readLocalSkill(local, folder) {
const markdown = local.files.find((file) => file.path === 'SKILL.md');
if (markdown === undefined)
return undefined;
if (local.files.length > MAX_FILES)
return 'too_many_files';
for (const file of local.files) {
if (file.size > MAX_FILE_BYTES)
return 'file_too_large';
}
for (const file of local.files) {
if (!isCloudSkillPath(file.path))
return 'unsupported_layout';
}
let total = 0;
for (const file of local.files)
total += file.size;
if (total > MAX_SKILL_BYTES)
return 'skill_too_large';
const raw = Buffer.from(markdown.data, 'base64').toString('utf8');
const frontmatter = parseSkillFrontmatter(raw);
const name = frontmatter.name !== undefined && CLOUD_SKILL_NAME.test(frontmatter.name)
? frontmatter.name
: CLOUD_SKILL_NAME.test(folder) ? folder : undefined;
if (name === undefined)
return 'invalid_name';
const heading = /^#\s+(.+)$/m.exec(raw);
const description = (frontmatter.description ?? heading?.[1] ?? name).slice(0, 500);
const manifest = linkedSkillManifest(local.files.map((file) => ({ path: file.path, sha256: file.sha256 })));
return {
name,
description,
files: local.files,
manifest,
hasScripts: local.files.some((file) => file.path.startsWith('scripts/')),
};
}
/** Encode repository files into the platform upload format. */
toUploadFiles(files) {
return files.map((file) => {
const ext = file.path.slice(file.path.lastIndexOf('.')).toLowerCase();
return TEXT_EXT.has(ext)
? { path: file.path, content: Buffer.from(file.data, 'base64').toString('utf8') }
: { path: file.path, base64: file.data };
});
}
dropConflict(name) {
this.current = { ...this.current, conflicts: this.current.conflicts.filter((conflict) => conflict.name !== name) };
}
async conflictDetails() {
const conflicts = this.current.conflicts;
if (conflicts.length === 0)
return [];
const repo = this.deps.repository();
let cloudItems = [];
try {
const listing = await this.deps.client().listSkills();
if (listing.ok)
cloudItems = listing.data.items ?? [];
}
catch {
// Offline: report local sides only, never throw the list away.
}
const byName = new Map(cloudItems.map((item) => [item.name, item]));
const out = [];
for (const conflict of conflicts) {
const local = await repo.read(conflict.name);
const location = local?.area ?? 'none';
const files = local?.files.length ?? 0;
const bytes = (local?.files ?? []).reduce((sum, file) => sum + file.size, 0);
let modified = false;
if (local !== undefined) {
modified = local.delivery === undefined ? true : !this.deliveredIntact(local, local.delivery);
}
const cloudItem = byName.get(conflict.name);
out.push({
name: conflict.name,
reason: conflict.reason,
local: { exists: location !== 'none', location, files, bytes, modified },
cloud: cloudItem === undefined
? null
: {
...(cloudItem.revision === undefined ? {} : { revision: cloudItem.revision }),
...(cloudItem.manifest_sha256 === undefined ? {} : { manifest: cloudItem.manifest_sha256 }),
...(cloudItem.files === undefined ? {} : { files: cloudItem.files }),
...(cloudItem.bytes === undefined ? {} : { bytes: cloudItem.bytes }),
...(cloudItem.enabled === undefined ? {} : { enabled: cloudItem.enabled }),
},
canKeepLocal: location !== 'none',
canTakeCloud: cloudItem !== undefined,
note: '“保留本地”把本地版本上传成新的云端版本;“采用云端”先备份本地再覆盖;“手动合并”只返回两侧信息,不改文件。',
});
}
return out;
}
async resolveConflict(nameInput, actionInput) {
const name = typeof nameInput === 'string' ? nameInput : '';
if (name === '' || !CLOUD_SKILL_NAME.test(name))
throw new Error('invalid_name');
const action = actionInput === 'keep_local' || actionInput === 'take_cloud' || actionInput === 'manual' ? actionInput : '';
if (action === '')
throw new Error('invalid_action');
if (this.running)
throw new Error('sync_running');
const repo = this.deps.repository();
const client = this.deps.client();
const listing = await client.listSkills();
if (!listing.ok)
throw new Error(`skill listing failed: ${describeError(listing.error)}`);
const cloud = (listing.data.items ?? []).find((item) => item.name === name);
const state = await this.loadState();
if (action === 'manual') {
return {
name,
action,
applied: false,
note: '已返回两侧信息,未改动任何文件;手工编辑后在下次同步前保存即可。',
...(cloud?.revision === undefined ? {} : { revision: cloud.revision }),
};
}
if (action === 'keep_local') {
const local = await repo.read(name);
if (local === undefined)
throw new Error('no_local_copy');
const skill = await this.readLocalSkill(local, name);
if (skill === undefined)
throw new Error('not_a_skill');
if (typeof skill === 'string')
throw new Error(skill);
const files = this.toUploadFiles(skill.files);
const operationId = `dsh-skill-${randomUUID()}`;
if (cloud === undefined) {
const created = await client.createSkill({
name: skill.name,
description: skill.description,
execution_mode: skill.hasScripts ? 'local-bundle' : 'prompt-only',
files,
expected_revision: 0,
operation_id: operationId,
});
if (!created.ok)
throw new Error(`upload_failed: ${describeError(created.error)}`);
const revision = created.data.skill?.revision ?? created.data.revision ?? 1;
await repo.write(name, {
name: skill.name,
revision,
manifest_sha256: skill.manifest,
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256, size: file.size, data: file.data })),
}, { delivery: false });
this.markUploaded(state, name, { folder: name, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() });
delete state.removed[name];
await this.saveState(state);
this.dropConflict(name);
return { name, action, applied: true, revision, note: '已把本地版本新建到云端。' };
}
const updated = await client.updateSkill(skill.name, {
description: skill.description,
files,
expected_revision: cloud.revision ?? 0,
operation_id: operationId,
});
if (!updated.ok) {
if (updated.error.code === 'revision_conflict')
throw new Error('stale_revision');
throw new Error(`upload_failed: ${describeError(updated.error)}`);
}
const revision = updated.data.skill?.revision ?? updated.data.revision ?? (cloud.revision ?? 0) + 1;
await repo.write(name, {
name: skill.name,
revision,
manifest_sha256: skill.manifest,
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256, size: file.size, data: file.data })),
}, { delivery: false });
this.markUploaded(state, name, { folder: name, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() });
delete state.removed[name];
await this.saveState(state);
this.dropConflict(name);
return { name, action, applied: true, revision, note: '已用本地版本覆盖云端(revision 已更新)。' };
}
if (cloud === undefined)
throw new Error('no_cloud_copy');
const bundle = await client.skillBundle(name);
if (!bundle.ok)
throw new Error(`bundle_failed: ${describeError(bundle.error)}`);
if (linkedSkillManifest(bundle.data.files) !== bundle.data.manifest_sha256) {
throw new Error('manifest_mismatch');
}
const local = await repo.read(name);
const backup = local !== undefined ? (await repo.snapshot(name)) ?? '' : '';
await repo.write(name, bundle.data);
this.markDelivered(state, name, bundle.data.manifest_sha256);
delete state.removed[name];
await this.saveState(state);
this.dropConflict(name);
return {
name,
action,
applied: true,
revision: bundle.data.revision,
...(backup === '' ? {} : { backup }),
note: '已采用云端版本覆盖本地(本地已备份)。',
};
}
}