dsh-brain/lib/skill-sync.js

1103 lines
53 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 silently. When its
* local files stop matching the delivery manifest, the sides are
* compared by content and modification time: identical bytes just
* refresh the receipt, a clearly newer side wins (the losing local
* copy is backed up under $DSH_HOME/.dsh-brain-backups/sync/), and an
* equal or missing timestamp stays a conflict, untouched.
* 2. A local deletion never deletes the cloud copy.
* 3. A name that already exists on the other side is never hijacked
* blindly: identical bytes adopt the cloud identity, a clearly newer
* side wins automatically, and anything ambiguous 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, sha256Hex, TEXT_EXT } from "./skills/shared.js";
import { mkdir, readFile, rename, rm, 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";
/** Parse an ISO string or epoch number into epoch milliseconds. */
function timestampMs(value) {
if (typeof value === 'number')
return Number.isFinite(value) ? value : undefined;
if (typeof value === 'string') {
const parsed = Date.parse(value);
return Number.isNaN(parsed) ? undefined : parsed;
}
return undefined;
}
/** Newest local modification time across a bundle, 0 when unknown. */
function newestMtime(files) {
let newest = 0;
for (const file of files) {
if (file.mtimeMs > newest)
newest = file.mtimeMs;
}
return newest;
}
/** 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;
/** Tail of the serialization queue shared by every skill write transaction. */
queueTail = Promise.resolve();
/** Jobs accepted into the queue but not settled yet; makes busy() honest. */
pendingWrites = 0;
stateCache;
runRepository;
runScopeKey;
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 any sync/resolve/admin write transaction is queued or running. */
isRunning() {
return this.busy();
}
/** SkillSyncGate: richer busy signal covering queued writes too. */
busy() {
return this.running || this.current.running || this.pendingWrites > 0;
}
/**
* SkillSyncGate: the one shared write lock. Every mutating entry point —
* sync passes, resolves, admin moves/installs/deletes, update and rollback
* — enters through this queue, so their async bodies never interleave.
*/
async runExclusive(job) {
this.pendingWrites += 1;
try {
return await this.enqueue(job);
}
finally {
this.pendingWrites -= 1;
}
}
/**
* 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;
}
async loadStateCached() {
const info = await stat(this.statePath()).catch(() => undefined);
const mtimeMs = info?.mtimeMs ?? -1;
const scopeKey = this.scopeKey(this.scopeIdentity());
if (this.stateCache !== undefined && this.stateCache.mtimeMs === mtimeMs && this.stateCache.scopeKey === scopeKey) {
return this.stateCache.state;
}
const state = await this.loadState();
this.stateCache = { mtimeMs, scopeKey, 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, folder) {
state.delivered[name] = {
manifest,
...(folder === undefined || folder === name ? {} : { folder }),
syncedAt: new Date().toISOString(),
endpoint: state.scope.endpoint,
account: state.scope.account,
root: state.scope.root,
};
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,
endpoint: state.scope.endpoint,
account: state.scope.account,
root: state.scope.root,
};
delete state.delivered[name];
}
/** Active scope identity, derived from the live endpoint/account/root. */
scopeIdentity(rawScope) {
const raw = rawScope ?? this.deps.scope?.();
if (raw === undefined)
return { endpoint: 'default', account: sha256Hex(''), root: 'default' };
const endpoint = raw.endpoint.trim().replace(/\/+$/, '') || 'default';
return { endpoint, account: sha256Hex(raw.accountToken), root: raw.root };
}
scopeKey(scope) {
return sha256Hex(`${scope.endpoint}\n${scope.account}\n${scope.root}`).slice(0, 32);
}
/**
* True when this exact local bundle was uploaded under another endpoint,
* account or local root. Switching accounts must never silently publish the
* previous account's source content into the new account.
*/
foreignUpload(state, folder, manifest) {
for (const [key, scope] of Object.entries(state.scopes)) {
if (key === state.key)
continue;
for (const record of Object.values(scope.uploaded)) {
if (record.folder === folder)
return true;
}
}
const legacy = state.legacy?.uploaded ?? {};
return Object.values(legacy).some((record) => record.folder === folder);
}
emptyState(scope = this.scopeIdentity()) {
return {
version: 2,
key: this.scopeKey(scope),
scope,
uploaded: {},
delivered: {},
removed: {},
scopes: {},
};
}
static mapOf(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
}
static scopeOf(value) {
if (value === null || typeof value !== 'object' || Array.isArray(value))
return undefined;
const raw = value;
if (typeof raw.endpoint !== 'string' || typeof raw.account !== 'string' || typeof raw.root !== 'string')
return undefined;
return {
endpoint: raw.endpoint,
account: raw.account,
root: raw.root,
uploaded: SkillSync.mapOf(raw.uploaded),
delivered: SkillSync.mapOf(raw.delivered),
removed: SkillSync.mapOf(raw.removed),
};
}
async loadState(scope = this.scopeIdentity()) {
const clean = this.emptyState(scope);
try {
const parsed = JSON.parse(await readFile(this.statePath(), 'utf8'));
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
return clean;
const raw = parsed;
const scopes = {};
if (raw.scopes !== null && typeof raw.scopes === 'object' && !Array.isArray(raw.scopes)) {
for (const [key, value] of Object.entries(raw.scopes)) {
const scope = SkillSync.scopeOf(value);
if (scope !== undefined)
scopes[key] = scope;
}
}
if (raw.version === 2) {
const active = scopes[clean.key];
const legacy = raw.legacy !== null && typeof raw.legacy === 'object' && !Array.isArray(raw.legacy)
? raw.legacy
: undefined;
return {
...clean,
scopes,
uploaded: active?.uploaded ?? {},
delivered: active?.delivered ?? {},
removed: active?.removed ?? {},
...(legacy === undefined ? {} : {
legacy: {
uploaded: SkillSync.mapOf(legacy.uploaded),
delivered: SkillSync.mapOf(legacy.delivered),
removed: SkillSync.mapOf(legacy.removed),
},
}),
};
}
// v1 sidecar: no way to prove which endpoint/account/root wrote it.
// Keep it as a read-only quarantine so old-origin content can never be
// auto-uploaded into a newly configured account.
const legacy = {
uploaded: SkillSync.mapOf(raw.uploaded),
delivered: SkillSync.mapOf(raw.delivered),
removed: SkillSync.mapOf(raw.removed),
};
return {
...clean,
// A local deletion is user intent, not account content, so the marker
// itself may carry forward; uploaded/delivered records stay quarantined.
removed: { ...legacy.removed },
legacy,
};
}
catch {
// Missing or corrupt sidecar: start clean; the cloud is the truth.
}
return clean;
}
async saveState(state) {
state.scopes[state.key] = {
endpoint: state.scope.endpoint,
account: state.scope.account,
root: state.scope.root,
uploaded: state.uploaded,
delivered: state.delivered,
removed: state.removed,
};
const path = this.statePath();
await mkdir(dirname(path), { recursive: true });
const temporary = `${path}.tmp-${process.pid}-${randomUUID()}`;
// Top-level uploaded/delivered/removed mirror the active scope: the file
// remains readable by older dashboards and verification scripts, while
// scopes{} is the authoritative, account-isolated copy.
const payload = {
version: 2,
scope: { ...state.scope, key: state.key },
scopes: state.scopes,
uploaded: state.uploaded,
delivered: state.delivered,
removed: state.removed,
...(state.legacy === undefined ? {} : { legacy: state.legacy }),
};
try {
await writeFile(temporary, JSON.stringify(payload, null, 2));
await rename(temporary, path);
}
catch (error) {
await rm(temporary, { force: true }).catch(() => { });
throw error;
}
}
/** 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;
return this.runExclusive(() => this.syncOnceLocked());
}
/**
* Serialized job runner: every mutating entry point (sync pass, single
* resolve, batch resolve) queues here, so an in-flight pass and a UI resolve
* can never interleave their awaits over the same skill files and state.
*/
enqueue(job) {
const next = this.queueTail.then(job, job);
this.queueTail = next.catch(() => { });
return next;
}
async syncOnceLocked() {
if (this.running)
return this.current;
const run = this.captureRun();
const scope = run.scope;
const client = run.client;
const repo = run.repo;
this.runScopeKey = this.scopeKey(scope);
this.running = true;
const stats = {
running: true, downloaded: [], uploaded: [], updated: [], conflicts: [], skipped: 0,
};
this.current = stats;
try {
await this.pass(stats, { scope, client, repo });
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.runRepository = undefined;
this.runScopeKey = undefined;
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, ...(this.runScopeKey === undefined ? {} : { scopeKey: this.runScopeKey }) });
}
}
/** One full pass; never throws — outcomes land in the stats. */
captureRun() {
const rawScope = this.deps.scope?.() ?? { endpoint: 'default', accountToken: '', root: 'default' };
const scope = this.scopeIdentity(rawScope);
return { scope, client: this.deps.clientForScope?.(rawScope) ?? this.deps.client(), repo: this.deps.repositoryForScope?.(scope) ?? this.currentRepository() };
}
currentRepository() { return this.runRepository ?? this.deps.repository(); }
async pass(stats, run) {
this.runRepository = run.repo;
const repo = run.repo;
const client = run.client;
const state = await this.loadState(run.scope);
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]));
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 record = state.uploaded[name];
if (record === undefined)
continue;
const local = await repo.read(record.folder);
const delivery = local?.delivery;
if (delivery !== undefined) {
this.markDelivered(state, name, delivery.manifest ?? '', record.folder);
stateDirty = true;
}
}
// Local presence is scanned BEFORE DOWN. A cloud-delivered skill the user
// deleted must be tombstoned before the cloud listing can resurrect it.
// The parking area counts as present (a parked skill is disabled, not
// deleted), and a first download has no receipt yet, so it can never be
// mistaken for a deletion.
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(record.folder ?? name)) {
state.removed[name] = { manifest: record.manifest };
delete state.delivered[name];
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 uploaded = state.uploaded[item.name];
const localFolder = uploaded?.folder ?? state.delivered[item.name]?.folder ?? item.name;
const local = await repo.read(localFolder);
const exists = local !== undefined;
const delivery = local?.delivery;
if (removed !== undefined) {
if (exists) {
// The user re-created the folder locally: lift the tombstone and let
// the normal collision rules decide what happens next.
delete state.removed[item.name];
stateDirty = true;
}
else {
// A tombstone is name-based, not manifest-based: a later cloud
// revision must not silently resurrect something the user deleted.
// An explicit take_cloud/reinstall clears the marker instead.
stats.skipped += 1;
continue;
}
}
if (exists && delivery !== undefined) {
if (!this.deliveredIntact(local, delivery)) {
const auto = await this.autoResolveLocalDrift(item, local, state, stats, client);
if (auto !== 'unresolved') {
stateDirty = true;
continue;
}
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 ?? '', localFolder);
stateDirty = true;
}
stats.skipped += 1;
continue;
}
}
else if (exists) {
const auto = await this.autoResolveCollision(item, local, state, stats, client);
if (auto !== 'unresolved') {
stateDirty = true;
continue;
}
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, { folder: localFolder });
this.markDelivered(state, item.name, bundle.data.manifest_sha256, localFolder);
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; collisions and revision drift auto-resolve by
// content and modification time, and only an equal or missing
// timestamp stays a human conflict.
const knownConflicts = new Set(stats.conflicts.map((conflict) => conflict.name));
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') {
if (!knownConflicts.has(entry.name))
this.conflict(stats, entry.name, skill);
continue;
}
const record = state.uploaded[skill.name];
const cloud = cloudByName.get(skill.name);
if (record === undefined && this.foreignUpload(state, entry.name, skill.manifest)) {
// Quarantined content from another endpoint/account/root: never upload
// it automatically. A user can still explicitly import/edit it later.
stats.skipped += 1;
continue;
}
if (record !== undefined && record.manifest === skill.manifest) {
const cloudRevision = cloud?.revision;
const cloudManifest = cloud?.manifest_sha256;
const remoteChanged = cloud !== undefined && ((cloudRevision !== undefined && cloudRevision !== record.revision) ||
(cloudManifest !== undefined && cloudManifest !== record.manifest));
if (!remoteChanged) {
stats.skipped += 1;
continue;
}
if (cloudManifest === skill.manifest) {
// Same bytes, newer cloud revision: re-pin the receipt only.
this.markUploaded(state, skill.name, {
folder: entry.name,
revision: cloudRevision ?? record.revision,
manifest: skill.manifest,
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })),
syncedAt: new Date().toISOString(),
});
stateDirty = true;
stats.skipped += 1;
continue;
}
// Local is byte-for-byte what we last uploaded, but the center moved
// on: the local copy is stale, so take the cloud revision instead of
// re-uploading the old bytes over it. Script changes still wait for
// explicit review inside autoTakeCloud.
const auto = await this.autoTakeCloud(cloud, local, state, stats, client, entry.name);
if (auto !== 'unresolved') {
stateDirty = true;
continue;
}
if (!knownConflicts.has(skill.name))
this.conflict(stats, skill.name, 'cloud_newer');
continue;
}
if (cloud !== undefined && record === undefined) {
if (knownConflicts.has(skill.name))
continue;
if (cloud.manifest_sha256 !== undefined && cloud.manifest_sha256 === skill.manifest) {
// Same bytes are already in the center: adopt the cloud identity
// without an upload, so the next pass compares revisions, not names.
this.markUploaded(state, skill.name, {
folder: entry.name,
revision: cloud.revision ?? 1,
manifest: skill.manifest,
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })),
syncedAt: new Date().toISOString(),
});
stateDirty = true;
stats.skipped += 1;
continue;
}
const cloudAt = this.cloudUpdatedAt(cloud);
const localAt = newestMtime(skill.files);
if (cloudAt !== undefined && localAt > 0 && localAt > cloudAt) {
const auto = await this.autoUploadLocal(skill, entry.name, cloud, state, stats, client);
if (auto !== 'unresolved') {
stateDirty = true;
continue;
}
}
this.conflict(stats, skill.name, 'name_collision');
continue;
}
const files = this.toUploadFiles(skill.files);
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,
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })),
syncedAt: new Date().toISOString(),
});
stateDirty = true;
stats.uploaded.push(skill.name);
}
else {
if (cloud.revision !== undefined && cloud.revision !== record.revision) {
// The center moved on since the last upload. Identical bytes
// re-pin the revision; otherwise the newer side wins, and only
// an equal or missing timestamp stays a conflict.
if (cloud.manifest_sha256 !== undefined && cloud.manifest_sha256 === skill.manifest) {
this.markUploaded(state, skill.name, {
folder: entry.name,
revision: cloud.revision,
manifest: skill.manifest,
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })),
syncedAt: new Date().toISOString(),
});
stateDirty = true;
stats.skipped += 1;
continue;
}
const cloudAt = this.cloudUpdatedAt(cloud);
const localAt = newestMtime(skill.files);
if (cloudAt !== undefined && localAt > 0 && cloudAt !== localAt) {
const auto = cloudAt > localAt
? await this.autoTakeCloud(cloud, local, state, stats, client)
: await this.autoUploadLocal(skill, entry.name, cloud, state, stats, client);
if (auto !== 'unresolved') {
stateDirty = true;
continue;
}
}
if (!knownConflicts.has(skill.name))
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,
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })),
syncedAt: new Date().toISOString(),
});
stateDirty = true;
stats.updated.push(skill.name);
}
}
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 };
});
}
/** The center's last-change time for one listed skill (ISO or epoch). */
cloudUpdatedAt(item) {
return timestampMs(item.updated_at) ?? timestampMs(item.created_at);
}
/** Manifest over every local file, in the linked form. */
localManifest(files) {
return linkedSkillManifest(files.map((file) => ({ path: file.path, sha256: file.sha256 })));
}
/**
* Local and cloud already carry the same bytes: refresh the delivery
* receipt without a transfer, so the next pass treats the folder as
* cloud-origin and nobody is asked to pick between two identical copies.
*/
async adoptIdenticalDelivery(item, local, folder) {
await this.currentRepository().write(item.name, {
name: item.name,
revision: item.revision ?? 1,
manifest_sha256: item.manifest_sha256 ?? this.localManifest(local.files),
files: local.files.map((file) => ({ path: file.path, sha256: file.sha256, size: file.size, data: file.data })),
}, { folder });
}
/** Fetch, verify and install the cloud copy, backing the local one up first. */
async autoTakeCloud(item, local, state, stats, client, folder) {
if (item.script_changed === true) {
this.conflict(stats, item.name, 'script_review_required');
return 'conflict';
}
const bundle = await client.skillBundle(item.name);
if (!bundle.ok) {
this.conflict(stats, item.name, `bundle_failed: ${describeError(bundle.error)}`);
return 'conflict';
}
if (linkedSkillManifest(bundle.data.files) !== bundle.data.manifest_sha256) {
this.conflict(stats, item.name, 'manifest_mismatch');
return 'conflict';
}
if (bundle.data.script_changed === true) {
this.conflict(stats, item.name, 'script_review_required');
return 'conflict';
}
const uploaded = state.uploaded[item.name];
const localFolder = folder ?? uploaded?.folder ?? local?.name ?? item.name;
if (local !== undefined)
await this.currentRepository().snapshot(localFolder);
await this.currentRepository().write(item.name, bundle.data, { folder: localFolder, cleanupFiles: uploaded?.files?.map((file) => file.path) });
this.markDelivered(state, item.name, bundle.data.manifest_sha256, localFolder);
delete state.removed[item.name];
stats.updated.push(item.name);
return 'resolved';
}
/** Publish the local copy as the next cloud revision. */
async autoUploadLocal(skill, folder, cloud, state, stats, client) {
const updated = await client.updateSkill(skill.name, {
description: skill.description,
files: this.toUploadFiles(skill.files),
expected_revision: cloud.revision ?? 0,
operation_id: `dsh-skill-${randomUUID()}`,
});
if (!updated.ok) {
const reason = updated.error.code === 'revision_conflict' ? 'cloud_newer' : `upload_failed: ${describeError(updated.error)}`;
this.conflict(stats, skill.name, reason);
return 'conflict';
}
const revision = updated.data.skill?.revision ?? updated.data.revision ?? (cloud.revision ?? 0) + 1;
await this.currentRepository().write(skill.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, skill.name, { folder, revision, manifest: skill.manifest,
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })), syncedAt: new Date().toISOString() });
delete state.removed[skill.name];
stats.updated.push(skill.name);
return 'resolved';
}
/** Resolve a name collision between a cloud skill and a local folder. */
async autoResolveCollision(item, local, state, stats, client) {
if (!local.files.some((file) => file.path === 'SKILL.md'))
return 'unresolved';
if (item.manifest_sha256 !== undefined && this.localManifest(local.files) === item.manifest_sha256) {
await this.adoptIdenticalDelivery(item, local, local.name);
this.markDelivered(state, item.name, item.manifest_sha256, local.name);
stats.skipped += 1;
return 'resolved';
}
return this.resolveDiverged(item, local, state, stats, client);
}
/** Resolve a locally-modified cloud delivery. */
async autoResolveLocalDrift(item, local, state, stats, client) {
if (item.manifest_sha256 !== undefined && local.files.length > 0 && this.localManifest(local.files) === item.manifest_sha256) {
await this.adoptIdenticalDelivery(item, local, local.name);
this.markDelivered(state, item.name, item.manifest_sha256, local.name);
stats.skipped += 1;
return 'resolved';
}
return this.resolveDiverged(item, local, state, stats, client);
}
/** The sides differ: the clearly newer one wins, ambiguity stays human. */
async resolveDiverged(item, local, state, stats, client) {
const cloudAt = this.cloudUpdatedAt(item);
const localAt = newestMtime(local.files);
if (cloudAt === undefined || localAt === 0 || cloudAt === localAt)
return 'unresolved';
if (cloudAt > localAt)
return this.autoTakeCloud(item, local, state, stats, client, local.name);
const skill = await this.readLocalSkill(local, item.name);
if (skill === undefined)
return 'unresolved';
if (typeof skill === 'string') {
this.conflict(stats, item.name, skill);
return 'conflict';
}
return this.autoUploadLocal(skill, item.name, item, state, stats, client);
}
dropConflict(name) {
this.current = { ...this.current, conflicts: this.current.conflicts.filter((conflict) => conflict.name !== name) };
}
/**
* Resolve every current conflict with one action (`keep_local` or
* `take_cloud`). Partial failures are collected instead of aborting the
* whole batch, so the UI can show "N done, M failed" in one shot.
*/
async resolveConflicts(actionInput, conflictIdsInput) {
const action = actionInput === 'keep_local' || actionInput === 'take_cloud' ? actionInput : '';
if (action === '')
throw new Error('invalid_action');
return this.runExclusive(() => this.resolveConflictsLocked(action, conflictIdsInput));
}
async resolveConflictsLocked(action, conflictIdsInput) {
if (this.running)
throw new Error('sync_running');
const run = this.captureRun();
const scopeKey = this.scopeKey(run.scope);
const details = await this.conflictDetails(run);
const requested = Array.isArray(conflictIdsInput) ? new Set(conflictIdsInput.filter((value) => typeof value === 'string')) : undefined;
const selected = details.filter((detail) => (detail.scopeKey === scopeKey || detail.scopeKey === '') && (requested === undefined || requested.has(detail.conflictId)));
const names = [...new Set(selected.map((detail) => detail.name))];
const idByName = new Map(selected.map((detail) => [detail.name, detail.conflictId]));
const resolved = [];
const failed = [];
for (const name of names) {
try {
await this.resolveConflictLocked(name, action, run, idByName.get(name));
resolved.push(name);
}
catch (error) {
failed.push({ name, error: error instanceof Error ? error.message : String(error) });
}
}
return { action, resolved, failed };
}
async conflictDetails(run) {
const conflicts = this.current.conflicts;
if (conflicts.length === 0)
return [];
const active = run ?? this.captureRun();
const repo = active.repo;
const state = await this.loadState(active.scope);
let cloudItems = [];
try {
const listing = await active.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 localFolder = state.uploaded[conflict.name]?.folder ?? state.delivered[conflict.name]?.folder ?? conflict.name;
const local = await repo.read(localFolder);
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);
const localVersion = local === undefined ? 'none' : sha256Hex(local.files.map((file) => file.path + '\0' + file.sha256).sort().join('\n'));
const cloudVersion = cloudItem === undefined ? 'none' : String(cloudItem.revision ?? '') + ':' + String(cloudItem.manifest_sha256 ?? '');
const scopeKey = conflict.scopeKey ?? this.scopeKey(active.scope);
const conflictId = sha256Hex([scopeKey, conflict.name, conflict.reason, localVersion, cloudVersion].join('|'));
out.push({
conflictId,
scopeKey,
localVersion,
cloudVersion,
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, conflictIdInput) {
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');
return this.runExclusive(() => { const run = this.captureRun(); return this.resolveConflictLocked(name, action, run, typeof conflictIdInput === 'string' ? conflictIdInput : undefined); });
}
async resolveConflictLocked(name, action, run, expectedConflictId) {
if (this.running)
throw new Error('sync_running');
const active = run ?? this.captureRun();
const scope = active.scope;
const repo = active.repo;
const client = active.client;
this.runRepository = repo;
try {
const conflict = this.current.conflicts.find((item) => item.name === name);
if (conflict?.scopeKey !== undefined && conflict.scopeKey !== this.scopeKey(scope))
throw new Error('stale_conflict');
if (expectedConflictId === undefined)
throw new Error('confirmation_required');
const details = await this.conflictDetails(active);
const confirmed = details.find((detail) => detail.name === name);
if (confirmed === undefined || confirmed.conflictId !== expectedConflictId)
throw new Error('stale_conflict');
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(scope);
const localFolder = state.uploaded[name]?.folder ?? state.delivered[name]?.folder ?? name;
const localNow = await repo.read(localFolder);
const localVersionNow = localNow === undefined ? 'none' : sha256Hex(localNow.files.map((file) => file.path + '\0' + file.sha256).sort().join('\n'));
if (localVersionNow !== confirmed.localVersion)
throw new Error('stale_conflict');
if ((cloud?.revision ?? undefined) !== (confirmed.cloud?.revision ?? undefined) || (cloud?.manifest_sha256 ?? undefined) !== (confirmed.cloud?.manifest ?? undefined))
throw new Error('stale_conflict');
if (action === 'manual') {
return {
name,
action,
applied: false,
note: '已返回两侧信息,未改动任何文件;手工编辑后在下次同步前保存即可。',
...(cloud?.revision === undefined ? {} : { revision: cloud.revision }),
};
}
if (action === 'keep_local') {
const local = localNow;
if (local === undefined)
throw new Error('no_local_copy');
const skill = await this.readLocalSkill(local, localFolder);
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 (confirmed.cloud === null) {
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,
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })), 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: confirmed.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 ?? (confirmed.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, folder: localFolder });
this.markUploaded(state, name, { folder: localFolder, revision, manifest: skill.manifest,
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })), syncedAt: new Date().toISOString() });
delete state.removed[name];
await this.saveState(state);
this.dropConflict(name);
return { name, action, applied: true, revision, note: '已用本地版本覆盖云端(revision 已更新)。' };
}
if (confirmed.cloud === null)
throw new Error('no_cloud_copy');
const bundle = await client.skillBundle(name);
if (!bundle.ok)
throw new Error(`bundle_failed: ${describeError(bundle.error)}`);
if (bundle.data.name !== name || bundle.data.revision !== confirmed.cloud.revision || bundle.data.manifest_sha256 !== confirmed.cloud.manifest)
throw new Error('stale_conflict');
if (linkedSkillManifest(bundle.data.files) !== bundle.data.manifest_sha256) {
throw new Error('manifest_mismatch');
}
const local = localNow;
const backup = local !== undefined ? (await repo.snapshot(localFolder)) ?? '' : '';
await repo.write(name, bundle.data, { folder: localFolder });
this.markDelivered(state, name, bundle.data.manifest_sha256, localFolder);
delete state.removed[name];
await this.saveState(state);
this.dropConflict(name);
return {
name,
action,
applied: true,
revision: bundle.data.revision,
...(backup === '' ? {} : { backup }),
note: '已采用云端版本覆盖本地(本地已备份)。',
};
}
finally {
this.runRepository = undefined;
}
}
}