refactor(skills): split the skill/cloud-sync seam behind SkillRepository and SkillSyncGate

The skill bundle now owns the directory format helpers (skills/shared.ts), the local skill file store (skills/repository.ts) and publishes the SkillRepository/SkillSyncGate contracts; the sync engine keeps the cloud protocol, sidecar state and conflict policy, touching the disk only through the repository. Format helpers stay re-exported from skill-sync.ts so existing import sites keep working.
This commit is contained in:
newbie 2026-11-23 12:48:41 +08:00
parent e1035358ab
commit 19eb15b231
27 changed files with 989 additions and 1321 deletions

View File

@ -17,7 +17,7 @@ import { readFile, readdir, stat } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join, resolve, sep } from 'node:path';
import { dshHome, migrateLegacyFile } from "./store.js";
import { parseSkillFrontmatter } from "./skill-sync.js";
import { parseSkillFrontmatter } from "./skills/shared.js";
import { SkillAdmin } from "./skill-admin.js";
/** Manual workspace additions live in the plugin's own metadata file. */
export function manualWorkspacesPath() {
@ -108,14 +108,10 @@ export class ClientRegistry {
throw new Error('unknown_workspace');
const skillsRoot = resolve(workspace.path, '.dsh', 'skills');
const holdingDir = join(dshHome(), 'skills-workspace-disabled', workspace.id);
const stateName = `${workspace.id.replace(/[^A-Za-z0-9_-]/g, '_')}.json`;
const statePath = join(dshHome(), `dsh-brain-workspace-${stateName}`);
migrateLegacyFile(statePath, join(dshHome(), `cloud-memory-workspace-${stateName}`));
const admin = new SkillAdmin({
skillsRoot: () => skillsRoot,
holdingDir: () => holdingDir,
syncStatePath: () => statePath,
syncRunning: () => false,
gate: () => ({ isRunning: () => false, provenance: async () => null }),
log: () => { },
});
return { admin, workspace };

View File

@ -12,10 +12,11 @@
import { CloudClient } from "./api.js";
import { Reporter } from "./reporter.js";
import { createLegacyRoutes, createRoutes } from "./routes.js";
import { join } from 'node:path';
import { join, resolve } from 'node:path';
import { SettingsStore, dshHome } from "./store.js";
import { SkillSync, skillsStatePath } from "./skill-sync.js";
import { SkillSync } from "./skill-sync.js";
import { SkillAdmin, skillsHoldingDir } from "./skill-admin.js";
import { AdminSkillRepository } from "./skills/repository.js";
import { SkillGroupManager, detectSources } from "./skill-groups.js";
import { ClaudePluginMarketplaceProvider, MarketService } from "./market.js";
import { SkillUpdater } from "./skill-update.js";
@ -58,21 +59,35 @@ export function apply(ctx, config) {
summaryToken: () => store.summaryToken(),
log: (message) => logger.warn(message),
});
// The skill bundle owns its folders; the composition root only wires the
// shared root path and the parking area. The sync engine touches folders
// exclusively through AdminSkillRepository below.
const skillsRootDir = () => {
const dir = settings().skillsDir;
return dir !== '' ? resolve(dir) : join(dshHome(), 'skills');
};
// Built before the sync engine: the gate closure below dereferences
// skillSync lazily, so the TDZ order here is safe.
const skillAdmin = new SkillAdmin({
skillsRoot: skillsRootDir,
holdingDir: () => skillsHoldingDir(),
gate: () => skillSync,
log: (message) => logger.info(message),
});
// The skill bundle's public repository: the only door the cloud-sync
// engine has into skill folders.
const skillRepository = new AdminSkillRepository({
admin: skillAdmin,
skillsRoot: skillsRootDir,
holdingDir: () => skillsHoldingDir(),
});
const skillSync = new SkillSync({
client: () => client,
settings: () => ({
enabled: settings().enabled,
skillsSyncEnabled: settings().skillsSyncEnabled,
skillsDir: settings().skillsDir,
}),
log: (message) => logger.info(message),
holdingDir: () => skillsHoldingDir(),
});
const skillAdmin = new SkillAdmin({
skillsRoot: () => skillSync.skillsRoot(),
holdingDir: () => skillsHoldingDir(),
syncStatePath: () => skillsStatePath(),
syncRunning: () => skillSync.stats().running,
repository: () => skillRepository,
log: (message) => logger.info(message),
});
// The tree's sources are detected per call so a directory created while the
@ -96,9 +111,9 @@ export function apply(ctx, config) {
]);
const updater = new SkillUpdater({
admin: skillAdmin,
skillsRoot: () => skillSync.skillsRoot(),
skillsRoot: skillsRootDir,
holdingDir: () => skillsHoldingDir(),
syncRunning: () => skillSync.stats().running,
gate: () => skillSync,
log: (message) => logger.info(message),
});
// Cross-software / workspace inventory. Read-only for every client except DSH.

View File

@ -12,7 +12,7 @@
* it ships. Installing an entry reuses the same staged plan/commit pipeline as
* a manual git install, pinned to the commit resolved here.
*/
import { parseSkillFrontmatter } from "./skill-sync.js";
import { parseSkillFrontmatter } from "./skills/shared.js";
/** Typed failure so routes can map it to a status code. */
export class MarketError extends Error {
code;

View File

@ -30,7 +30,7 @@ import { execFile } from 'node:child_process';
import { createHash, randomUUID } from 'node:crypto';
import { cp, lstat, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
import { basename, dirname, join, relative, resolve, sep } from 'node:path';
import { parseSkillFrontmatter } from "./skill-sync.js";
import { parseSkillFrontmatter } from "./skills/shared.js";
import { dshHome, migrateLegacyFile } from "./store.js";
/** The parking area for disabled skills. */
export function skillsHoldingDir() {
@ -166,25 +166,10 @@ export class SkillAdmin {
return this.deps.stagingRoot?.() ?? skillsStagingDir();
}
guardSync() {
if (this.deps.syncRunning())
if (this.deps.gate().isRunning())
fail('sync_running', '技能同步正在进行,请稍候再试。');
}
async uploaded() {
try {
const parsed = JSON.parse(await readFile(this.deps.syncStatePath(), 'utf8'));
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
const uploaded = parsed.uploaded;
if (uploaded !== null && typeof uploaded === 'object' && !Array.isArray(uploaded)) {
return uploaded;
}
}
}
catch {
// No sidecar yet: nothing has been uploaded.
}
return {};
}
async describe(folder, dir, enabled, uploaded) {
async describe(folder, dir, enabled, provenance) {
const markdown = await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined);
if (markdown === undefined)
return undefined;
@ -204,15 +189,10 @@ export class SkillAdmin {
// A corrupt manifest still marks cloud origin.
}
}
else {
for (const record of Object.values(uploaded)) {
if (record.folder === folder) {
origin = 'uploaded';
if (typeof record.revision === 'number')
revision = record.revision;
break;
}
}
else if (provenance?.origin === 'uploaded') {
origin = 'uploaded';
if (typeof provenance.revision === 'number')
revision = provenance.revision;
}
const files = await walkFiles(dir);
const bytes = files.reduce((sum, file) => sum + file.bytes, 0);
@ -249,13 +229,12 @@ export class SkillAdmin {
}
/** Inventory of the skills root and the parking area. */
async list() {
const uploaded = await this.uploaded();
const skills = [];
const scan = async (area, enabled) => {
for (const entry of await readdir(area, { withFileTypes: true }).catch(() => [])) {
if (!entry.isDirectory() || entry.name.startsWith('.'))
continue;
const described = await this.describe(entry.name, join(area, entry.name), enabled, uploaded);
const described = await this.describe(entry.name, join(area, entry.name), enabled, await this.deps.gate().provenance(entry.name));
if (described !== undefined)
skills.push(described);
}
@ -283,7 +262,7 @@ export class SkillAdmin {
fail('not_found', `没有找到技能:${folder}`);
if (await isSymlink(found.dir))
fail('unsupported', `技能目录是链接,不在这里管理:${folder}`);
const entry = await this.describe(folder, found.dir, found.area === 'root', await this.uploaded());
const entry = await this.describe(folder, found.dir, found.area === 'root', await this.deps.gate().provenance(folder));
if (entry === undefined)
fail('not_found', `技能缺少 SKILL.md:${folder}`);
const files = await walkFiles(found.dir);
@ -341,7 +320,7 @@ export class SkillAdmin {
fail('not_found', `没有找到技能:${folder}`);
if (await isSymlink(found.dir))
fail('unsupported', `技能目录是链接,不在这里删除:${folder}`);
const entry = await this.describe(folder, found.dir, found.area === 'root', await this.uploaded());
const entry = await this.describe(folder, found.dir, found.area === 'root', await this.deps.gate().provenance(folder));
const files = await walkFiles(found.dir);
return {
folder,

View File

@ -15,14 +15,12 @@
* revisions, guarded by the center's `expected_revision` check.
*
* Safety rules (deliberate, in order):
* 1. A cloud-delivered skill is never re-uploaded unless its local copy is
* newer than the center's `updated_at`; before any cloud overwrite the
* local folder is copied to `$DSH_HOME/.dsh-brain-backups/sync/`.
* 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 same-name skill is never hijacked silently: byte-identical copies are
* adopted in place, otherwise the newer side (local file mtime vs center
* `updated_at`) wins; only equal or missing timestamps are reported as a
* conflict for a human to resolve.
* 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.
@ -31,98 +29,16 @@
* center's extension allowlist). Anything else is reported, never
* silently trimmed.
*/
import { createHash, randomUUID } from 'node:crypto';
import { mkdir, cp, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
import { dirname, join, resolve } from 'node:path';
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";
/** Cloud skill names: lowercase kebab, at most 64 characters. */
export const CLOUD_SKILL_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
/** Layout contract of the cloud skill center (mirrors its store rules). */
const TEXT_EXT = new Set(['.md', '.txt', '.json', '.yaml', '.yml', '.py', '.sh', '.ps1', '.mjs', '.js', '.ts', '.tsx', '.css', '.html', '.csv']);
const BINARY_EXT = new Set(['.docx', '.xlsx', '.pptx', '.pdf', '.png', '.jpg', '.jpeg', '.gif', '.svg', '.zip']);
const SCRIPT_EXT = new Set(['.py', '.sh', '.ps1', '.mjs']);
const SKILL_DIRS = new Set(['references', 'scripts', 'assets']);
const SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
const MAX_FILES = 100;
const MAX_FILE_BYTES = 512 * 1024;
const MAX_SKILL_BYTES = 2 * 1024 * 1024;
const MAX_DEPTH = 3;
/** SHA-256 of a buffer or UTF-8 string, hex-encoded. */
export function sha256Hex(data) {
return createHash('sha256').update(data).digest('hex');
}
/**
* The center's linked bundle manifest: one `path\0sha256` line per file,
* sorted, under a version header. Byte-identical to the platform's own
* computation, so locally computed manifests compare directly.
*/
export function linkedSkillManifest(files) {
const lines = files.map((file) => `${file.path}\0${file.sha256}`).sort();
return sha256Hex(Buffer.from(`cloud-memory-skill-v1\n${lines.join('\n')}\n`, 'utf8'));
}
/** Epoch milliseconds from a center timestamp (ISO string or epoch seconds/ms). */
function timestampMs(value) {
if (typeof value === 'number' && Number.isFinite(value))
return value < 1e12 ? value * 1000 : value;
if (typeof value === 'string' && value !== '') {
const parsed = Date.parse(value);
return Number.isFinite(parsed) ? parsed : undefined;
}
return undefined;
}
/** Newest local file mtime in one skill folder (0 when the folder has no files). */
function newestMtime(files) {
let newest = 0;
for (const file of files)
if (file.mtimeMs > newest)
newest = file.mtimeMs;
return newest;
}
/** True when the cloud center would accept this relative file path. */
export function isCloudSkillPath(rel) {
if (rel === '' || rel.length > 200 || rel.startsWith('/') || rel.includes('\\') || rel.includes('//'))
return false;
const segments = rel.split('/');
if (segments.length > MAX_DEPTH)
return false;
for (const segment of segments) {
if (!SEGMENT.test(segment) || segment === '.' || segment === '..')
return false;
}
const dot = rel.lastIndexOf('.');
const ext = dot === -1 ? '' : rel.slice(dot).toLowerCase();
if (!TEXT_EXT.has(ext) && !BINARY_EXT.has(ext))
return false;
const first = segments[0];
if (segments.length === 1)
return rel === 'SKILL.md';
if (first === undefined || !SKILL_DIRS.has(first))
return false;
if (first === 'scripts' && !SCRIPT_EXT.has(ext))
return false;
return true;
}
/** Minimal frontmatter reader for `name` / `description` (plain scalars). */
export function parseSkillFrontmatter(markdown) {
if (!markdown.startsWith('---'))
return {};
const end = markdown.indexOf('\n---', 3);
if (end === -1)
return {};
const out = {};
for (const line of markdown.slice(3, end).split('\n')) {
const match = /^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(line);
if (match === null)
continue;
const value = (match[2] ?? '').replace(/^["']|["']$/g, '');
if (match[1] === 'name' && value !== '')
out.name = value;
if (match[1] === 'description' && value !== '')
out.description = value;
}
return out;
}
// 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() {
@ -130,9 +46,6 @@ export function skillsStatePath() {
migrateLegacyFile(target, join(dshHome(), 'cloud-memory-skills.json'));
return target;
}
async function isDirectory(path) {
return stat(path).then((value) => value.isDirectory()).catch(() => false);
}
export class SkillSync {
deps;
running = false;
@ -146,14 +59,47 @@ export class SkillSync {
stats() {
return this.current;
}
/** The local skills root this engine syncs. */
skillsRoot() {
const dir = this.deps.settings().skillsDir;
return dir !== '' ? resolve(dir) : join(dshHome(), 'skills');
/** SkillSyncGate: true while a pass is in flight. */
isRunning() {
return this.running || this.current.running;
}
/** The parking area where disabled skills wait, outside the root. */
holdingRoot() {
return this.deps.holdingDir?.() ?? join(dshHome(), 'skills-disabled');
/**
* 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();
@ -204,227 +150,6 @@ export class SkillSync {
await writeFile(temporary, JSON.stringify(state, null, 2));
await rename(temporary, path);
}
/** Read every syncable file of one skill directory (unsorted walk). */
async readSkillFiles(dir) {
const out = [];
const walk = async (sub) => {
const entries = await readdir(join(dir, sub), { withFileTypes: true });
for (const entry of entries) {
const rel = sub === '' ? entry.name : `${sub}/${entry.name}`;
if (entry.name.startsWith('.'))
continue;
if (entry.isDirectory()) {
await walk(rel);
}
else if (entry.isFile()) {
const absolute = join(dir, rel);
const buffer = await readFile(absolute);
const info = await stat(absolute);
out.push({ rel, buffer, mtimeMs: info.mtimeMs });
}
}
};
await walk('');
return out.sort((a, b) => (a.rel < b.rel ? -1 : 1));
}
/** True when a cloud-delivered directory still matches its manifest. */
async deliveredIntact(dir, delivery) {
const recorded = delivery.files ?? [];
let files;
try {
files = await this.readSkillFiles(dir);
}
catch {
return false;
}
const current = files.filter((file) => file.rel !== '.manifest.json');
if (current.length !== recorded.length)
return false;
const byPath = new Map(current.map((file) => [file.rel, sha256Hex(file.buffer)]));
return recorded.every((file) => byPath.get(file.path) === file.sha256);
}
/** Install or update one cloud skill into the local directory. */
async install(item, bundle, root) {
const dir = join(root, item.name);
const previous = await this.readDelivery(dir);
const keep = new Set(bundle.files.map((file) => file.path));
await mkdir(dir, { recursive: true });
const written = [];
for (const file of bundle.files) {
const buffer = Buffer.from(file.data, 'base64');
if (sha256Hex(buffer) !== file.sha256)
throw new Error(`checksum mismatch for ${file.path}`);
const target = join(dir, ...file.path.split('/'));
await mkdir(dirname(target), { recursive: true });
const temporary = `${target}.tmp-${process.pid}`;
await writeFile(temporary, buffer);
await rename(temporary, target);
written.push({ path: file.path, sha256: file.sha256, size: buffer.length });
}
for (const file of previous?.files ?? []) {
if (!keep.has(file.path))
await rm(join(dir, ...file.path.split('/')), { force: true });
}
const delivery = {
name: item.name,
revision: bundle.revision,
manifest_sha256: bundle.manifest_sha256,
files: written,
synced_at: new Date().toISOString(),
};
await writeFile(join(dir, '.manifest.json'), JSON.stringify(delivery, null, 2));
}
async readDelivery(dir) {
try {
const parsed = JSON.parse(await readFile(join(dir, '.manifest.json'), 'utf8'));
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
return parsed;
}
}
catch {
// Not a cloud-delivered skill.
}
return undefined;
}
/** Center's last-change time for one listed skill (ISO string or epoch). */
cloudUpdatedAt(item) {
return timestampMs(item.updated_at) ?? timestampMs(item.created_at);
}
/** Manifest over every local file, including files the center would reject. */
localManifest(files) {
return linkedSkillManifest(files.map((file) => ({ path: file.rel, sha256: sha256Hex(file.buffer) })));
}
/** Copy a local skill aside before an automatic cloud overwrite. */
async backupLocal(dir, name) {
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
const backup = join(dshHome(), '.dsh-brain-backups', 'sync', name, stamp);
await mkdir(join(backup, '..'), { recursive: true });
await cp(dir, backup, { recursive: true, filter: (path) => !path.split(/[\\/]/).includes('.git') });
return backup;
}
/**
* Local and cloud already carry the same bytes: record the delivery marker
* without a transfer, so the next pass treats the folder as cloud-origin and
* the user is not asked to pick between two identical copies.
*/
async adoptIdenticalDelivery(home, item, files) {
const delivery = {
name: item.name,
...(item.revision === undefined ? {} : { revision: item.revision }),
...(item.manifest_sha256 === undefined ? {} : { manifest_sha256: item.manifest_sha256 }),
files: files.map((file) => ({ path: file.rel, sha256: sha256Hex(file.buffer) })),
synced_at: new Date().toISOString(),
};
await writeFile(join(home, '.manifest.json'), JSON.stringify(delivery, null, 2));
}
/** Fetch, verify and install the cloud copy, backing the local one up first. */
async autoTakeCloud(item, home, installRoot, state, stats, client) {
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';
}
await this.backupLocal(home, item.name);
await this.install(item, bundle.data, installRoot);
this.markDelivered(state, item.name, bundle.data.manifest_sha256);
delete state.removed[item.name];
stats.updated.push(item.name);
return 'resolved';
}
/** Upload the locally-newer copy as the next cloud revision. */
async autoUploadLocal(skill, folder, dir, 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 rm(join(dir, '.manifest.json'), { force: true });
this.markUploaded(state, skill.name, {
folder,
revision,
manifest: skill.manifest,
syncedAt: new Date().toISOString(),
});
delete state.removed[skill.name];
stats.updated.push(skill.name);
return 'resolved';
}
/**
* Same-name skill on both sides without a delivery record. Identical bytes
* are adopted silently; different bytes go to whichever side is newer;
* equal/missing timestamps stay unresolved for a human decision.
*/
async autoResolveCollision(item, home, installRoot, state, stats, client) {
const localFiles = await this.readSkillFiles(home).catch(() => []);
if (!localFiles.some((file) => file.rel === 'SKILL.md'))
return 'unresolved';
if (item.manifest_sha256 !== undefined && this.localManifest(localFiles) === item.manifest_sha256) {
await this.adoptIdenticalDelivery(home, item, localFiles);
this.markDelivered(state, item.name, item.manifest_sha256);
stats.skipped += 1;
return 'resolved';
}
const cloudAt = this.cloudUpdatedAt(item);
const localAt = newestMtime(localFiles);
if (cloudAt === undefined || localAt === 0 || cloudAt === localAt)
return 'unresolved';
if (cloudAt > localAt)
return this.autoTakeCloud(item, home, installRoot, state, stats, client);
const skill = await this.readLocalSkill(home, 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, home, item, state, stats, client);
}
/**
* Cloud-delivered skill edited locally. Identical bytes refresh the marker;
* otherwise the newer side wins (cloud overwrite is backed up first).
*/
async autoResolveLocalDrift(item, home, state, stats, client, installRoot) {
const localFiles = await this.readSkillFiles(home).catch(() => []);
if (item.manifest_sha256 !== undefined && localFiles.length > 0 && this.localManifest(localFiles) === item.manifest_sha256) {
await this.adoptIdenticalDelivery(home, item, localFiles);
this.markDelivered(state, item.name, item.manifest_sha256);
stats.skipped += 1;
return 'resolved';
}
const cloudAt = this.cloudUpdatedAt(item);
const localAt = newestMtime(localFiles);
if (cloudAt === undefined || localAt === 0 || cloudAt === localAt)
return 'unresolved';
if (cloudAt > localAt)
return this.autoTakeCloud(item, home, installRoot, state, stats, client);
const skill = await this.readLocalSkill(home, 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, home, item, state, stats, client);
}
/** One full pass; never throws — outcomes land in the stats. */
async syncOnce() {
if (this.running)
@ -458,85 +183,60 @@ export class SkillSync {
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 root = this.skillsRoot();
const state = await this.loadState();
let stateDirty = false;
// Self-heal sidecars written before source provenance became exclusive:
// a folder carrying a delivery manifest is cloud-delivered, even if an old
// `uploaded` record survived. Clearing the stale upload marker lets the
// DOWN pass judge local integrity (and surface a conflict) instead of
// skipping both directions forever.
// 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)) {
let delivery = undefined;
for (const area of [root, this.holdingRoot()]) {
const dir = join(area, name);
if (!(await isDirectory(dir)))
continue;
delivery = await this.readDelivery(dir);
if (delivery !== undefined)
break;
}
const local = await repo.read(name);
const delivery = local?.delivery;
if (delivery !== undefined) {
this.markDelivered(state, name, delivery.manifest_sha256 ?? '');
this.markDelivered(state, name, delivery.manifest ?? '');
stateDirty = true;
}
}
if (stateDirty)
await this.saveState(state);
// ---- DOWN: cloud center -> local directory -------------------------
// 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;
}
// Locally-originated skills belong to the UP pass, even though the
// center lists them too once they are published.
if (state.uploaded[item.name] !== undefined) {
stats.skipped += 1;
continue;
}
const dir = join(root, item.name);
const parkedDir = join(this.holdingRoot(), item.name);
const inRoot = await isDirectory(dir);
const parked = !inRoot && (await isDirectory(parkedDir));
const home = parked ? parkedDir : dir;
const exists = inRoot || parked;
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) {
// The user put it back by hand; the removal is over.
delete state.removed[item.name];
stateDirty = true;
}
else if (removed !== undefined && item.manifest_sha256 === removed.manifest) {
// Deleted locally at this exact cloud version: keep it deleted.
stats.skipped += 1;
continue;
}
else if (removed !== undefined) {
// The cloud published a different version since the deletion.
delete state.removed[item.name];
stateDirty = true;
}
const delivery = await this.readDelivery(home);
if (exists && delivery !== undefined) {
// Delivered before: local integrity is judged before any download.
if (!(await this.deliveredIntact(home, delivery))) {
const auto = await this.autoResolveLocalDrift(item, home, state, stats, client, parked ? this.holdingRoot() : root);
if (auto !== 'unresolved') {
stateDirty = true;
continue;
}
if (!this.deliveredIntact(local, delivery)) {
this.conflict(stats, item.name, 'locally_modified');
continue;
}
if (delivery.manifest_sha256 === item.manifest_sha256) {
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;
@ -544,22 +244,12 @@ export class SkillSync {
stats.skipped += 1;
continue;
}
// Intact but the cloud moved on: fall through and install the update.
}
if (exists && delivery === undefined) {
// Same name on both sides with no delivery proof. Identical bytes are
// adopted; otherwise the newer side wins by timestamp. Only an equal
// or missing timestamp becomes a human conflict.
const auto = await this.autoResolveCollision(item, home, parked ? this.holdingRoot() : root, state, stats, client);
if (auto !== 'unresolved') {
stateDirty = true;
continue;
}
else if (exists) {
this.conflict(stats, item.name, 'name_collision');
continue;
}
if (item.script_changed === true) {
// The listing already carries the review flag; don't even fetch.
this.conflict(stats, item.name, 'script_review_required');
continue;
}
@ -576,60 +266,34 @@ export class SkillSync {
this.conflict(stats, item.name, 'script_review_required');
continue;
}
await this.install(item, bundle.data, parked ? this.holdingRoot() : root);
await repo.write(item.name, bundle.data);
this.markDelivered(state, item.name, bundle.data.manifest_sha256);
stateDirty = true;
(exists ? stats.updated : stats.downloaded).push(item.name);
if (exists)
stats.updated.push(item.name);
else
stats.downloaded.push(item.name);
}
// ---- UP: local originals -> cloud center ---------------------------
// The DOWN pass already had the chance to resolve a same-name folder;
// don't repeat the same skill with a second reason (the panel used to show
// one card per reason for the same name).
const knownConflicts = new Set(stats.conflicts.map((entry) => entry.name));
const folders = await readdir(root, { withFileTypes: true }).catch(() => []);
const seenFolders = new Set();
for (const entry of folders) {
if (!entry.isDirectory() || entry.name.startsWith('.'))
// 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;
seenFolders.add(entry.name);
const dir = join(root, entry.name);
if ((await this.readDelivery(dir)) !== undefined)
continue; // cloud-origin: down pass owns it
const skill = await this.readLocalSkill(dir, entry.name);
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);
this.conflict(stats, entry.name, skill);
continue;
}
const record = state.uploaded[skill.name];
const cloud = cloudByName.get(skill.name);
if (cloud !== undefined && record === undefined) {
if (knownConflicts.has(skill.name))
continue;
if (cloud.manifest_sha256 !== undefined && cloud.manifest_sha256 === skill.manifest) {
// Same bytes already in the center: adopt the cloud identity without
// an upload, so the next pass compares revisions instead of names.
this.markUploaded(state, skill.name, {
folder: entry.name,
revision: cloud.revision ?? 1,
manifest: skill.manifest,
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, dir, cloud, state, stats, client);
if (auto !== 'unresolved') {
stateDirty = true;
continue;
}
}
this.conflict(stats, skill.name, 'name_collision');
continue;
}
@ -638,10 +302,10 @@ export class SkillSync {
continue;
}
const files = skill.files.map((file) => {
const ext = file.rel.slice(file.rel.lastIndexOf('.')).toLowerCase();
const ext = file.path.slice(file.path.lastIndexOf('.')).toLowerCase();
return TEXT_EXT.has(ext)
? { path: file.rel, content: file.buffer.toString('utf8') }
: { path: file.rel, base64: file.buffer.toString('base64') };
? { 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) {
@ -668,33 +332,7 @@ export class SkillSync {
}
else {
if (cloud.revision !== undefined && cloud.revision !== record.revision) {
// The center moved on since the last upload. Identical bytes just
// re-pin the revision; otherwise the newer side wins and only an
// equal/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,
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, dir, root, state, stats, client)
: await this.autoUploadLocal(skill, entry.name, dir, cloud, state, stats, client);
if (auto !== 'unresolved') {
stateDirty = true;
continue;
}
}
if (!knownConflicts.has(skill.name))
this.conflict(stats, skill.name, 'cloud_newer');
this.conflict(stats, skill.name, 'cloud_newer');
continue;
}
const updated = await client.updateSkill(skill.name, {
@ -721,11 +359,7 @@ export class SkillSync {
// 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(seenFolders);
for (const entry of await readdir(this.holdingRoot(), { withFileTypes: true }).catch(() => [])) {
if (entry.isDirectory())
presentFolders.add(entry.name);
}
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 };
@ -744,141 +378,86 @@ export class SkillSync {
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)`);
this.deps.log(`skill sync: ${stats.downloaded.length} downloaded, ${stats.uploaded.length} uploaded, ${stats.updated.length} updated, ${stats.conflicts.length} conflict(s)}`);
}
}
/**
* Read one locally-originated skill for upload. Returns the skill, a
* conflict reason string, or undefined when the folder is not a skill.
* 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(dir, folder) {
let files;
try {
files = await this.readSkillFiles(dir);
}
catch {
return undefined;
}
const markdown = files.find((file) => file.rel === 'SKILL.md');
async readLocalSkill(local, folder) {
const markdown = local.files.find((file) => file.path === 'SKILL.md');
if (markdown === undefined)
return undefined;
if (files.length > MAX_FILES)
if (local.files.length > MAX_FILES)
return 'too_many_files';
let total = 0;
for (const file of files) {
if (file.buffer.length > MAX_FILE_BYTES)
for (const file of local.files) {
if (file.size > MAX_FILE_BYTES)
return 'file_too_large';
total += file.buffer.length;
if (!isCloudSkillPath(file.rel))
}
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 frontmatter = parseSkillFrontmatter(markdown.buffer.toString('utf8'));
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;
: CLOUD_SKILL_NAME.test(folder) ? folder : undefined;
if (name === undefined)
return 'invalid_name';
const heading = /^#\s+(.+)$/m.exec(markdown.buffer.toString('utf8'))?.[1]?.trim();
const description = (frontmatter.description ?? heading ?? name).slice(0, 500);
const manifest = linkedSkillManifest(files.map((file) => ({ path: file.rel, sha256: sha256Hex(file.buffer) })));
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,
files: local.files,
manifest,
hasScripts: files.some((file) => file.rel.startsWith('scripts/')),
hasScripts: local.files.some((file) => file.path.startsWith('scripts/')),
};
}
/** Encode local files exactly the way the upload path does. */
/** Encode repository files into the platform upload format. */
toUploadFiles(files) {
return files.map((file) => {
const ext = file.rel.slice(file.rel.lastIndexOf('.')).toLowerCase();
const ext = file.path.slice(file.path.lastIndexOf('.')).toLowerCase();
return TEXT_EXT.has(ext)
? { path: file.rel, content: file.buffer.toString('utf8') }
: { path: file.rel, base64: file.buffer.toString('base64') };
? { path: file.path, content: Buffer.from(file.data, 'base64').toString('utf8') }
: { path: file.path, base64: file.data };
});
}
/** Drop one name from the in-memory conflict list after it is resolved. */
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) {
const action = actionInput === 'keep_local' || actionInput === 'take_cloud' ? actionInput : '';
if (action === '')
throw new Error('invalid_action');
if (this.running)
throw new Error('sync_running');
const names = [...new Set(this.current.conflicts.map((conflict) => conflict.name))];
const resolved = [];
const failed = [];
for (const name of names) {
try {
await this.resolveConflict(name, action);
resolved.push(name);
}
catch (error) {
failed.push({ name, error: error instanceof Error ? error.message : String(error) });
}
}
return { action, resolved, failed };
}
/**
* Both sides of every conflict from the last pass, so a human can decide.
* Read-only: it never changes a file or uploads anything.
*/
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 ?? []).filter((item) => typeof item.name === 'string');
}
if (listing.ok)
cloudItems = listing.data.items ?? [];
}
catch {
// Listing failed: still show the local side with a null cloud side.
// 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 rootDir = join(this.skillsRoot(), conflict.name);
const parkedDir = join(this.holdingRoot(), conflict.name);
let location = 'none';
let dir = '';
if (await isDirectory(rootDir)) {
location = 'root';
dir = rootDir;
}
else if (await isDirectory(parkedDir)) {
location = 'holding';
dir = parkedDir;
}
let files = 0;
let bytes = 0;
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 (dir !== '') {
try {
const local = await this.readSkillFiles(dir);
files = local.length;
bytes = local.reduce((sum, file) => sum + file.buffer.length, 0);
const delivery = await this.readDelivery(dir);
modified = delivery === undefined ? true : !(await this.deliveredIntact(dir, delivery));
}
catch {
// Unreadable folder: report zeroed counts, never throw the list away.
}
if (local !== undefined) {
modified = local.delivery === undefined ? true : !this.deliveredIntact(local, local.delivery);
}
const cloudItem = byName.get(conflict.name);
out.push({
@ -896,12 +475,11 @@ export class SkillSync {
},
canKeepLocal: location !== 'none',
canTakeCloud: cloudItem !== undefined,
note: '同步会先按内容与更新时间自动采用较新的一边(覆盖前备份本地);只有时间相同/缺失、或目录结构不支持时才需要你逐项选择。',
note: '“保留本地”把本地版本上传成新的云端版本;“采用云端”先备份本地再覆盖;“手动合并”只返回两侧信息,不改文件。',
});
}
return out;
}
/** Resolve one conflict: keep local / take cloud / manual (no write). */
async resolveConflict(nameInput, actionInput) {
const name = typeof nameInput === 'string' ? nameInput : '';
if (name === '' || !CLOUD_SKILL_NAME.test(name))
@ -911,12 +489,7 @@ export class SkillSync {
throw new Error('invalid_action');
if (this.running)
throw new Error('sync_running');
const root = this.skillsRoot();
const rootDir = join(root, name);
const parkedDir = join(this.holdingRoot(), name);
const inRoot = await isDirectory(rootDir);
const parked = !inRoot && (await isDirectory(parkedDir));
const dir = inRoot ? rootDir : parked ? parkedDir : '';
const repo = this.deps.repository();
const client = this.deps.client();
const listing = await client.listSkills();
if (!listing.ok)
@ -933,9 +506,10 @@ export class SkillSync {
};
}
if (action === 'keep_local') {
if (dir === '')
const local = await repo.read(name);
if (local === undefined)
throw new Error('no_local_copy');
const skill = await this.readLocalSkill(dir, name);
const skill = await this.readLocalSkill(local, name);
if (skill === undefined)
throw new Error('not_a_skill');
if (typeof skill === 'string')
@ -954,16 +528,19 @@ export class SkillSync {
if (!created.ok)
throw new Error(`upload_failed: ${describeError(created.error)}`);
const revision = created.data.skill?.revision ?? created.data.revision ?? 1;
// The local copy is now the upload source of truth: drop any stale
// cloud-delivery marker before committing the success state.
await rm(join(dir, '.manifest.json'), { force: true });
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(name, {
const updated = await client.updateSkill(skill.name, {
description: skill.description,
files,
expected_revision: cloud.revision ?? 0,
@ -975,29 +552,29 @@ export class SkillSync {
throw new Error(`upload_failed: ${describeError(updated.error)}`);
}
const revision = updated.data.skill?.revision ?? updated.data.revision ?? (cloud.revision ?? 0) + 1;
await rm(join(dir, '.manifest.json'), { force: true });
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 已更新)。' };
}
// take_cloud
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)
if (linkedSkillManifest(bundle.data.files) !== bundle.data.manifest_sha256) {
throw new Error('manifest_mismatch');
let backup = '';
if (dir !== '') {
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
backup = join(dshHome(), '.dsh-brain-backups', 'sync', name, stamp);
await mkdir(join(backup, '..'), { recursive: true });
await cp(dir, backup, { recursive: true, filter: (p) => !p.split(/[\\/]/).includes('.git') });
}
await this.install(cloud, bundle.data, parked ? this.holdingRoot() : root);
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);

View File

@ -104,7 +104,7 @@ export class SkillUpdater {
return this.deps.backupsDir?.() ?? skillBackupsDir();
}
guard() {
if (this.deps.syncRunning())
if (this.deps.gate().isRunning())
throw new SkillAdminError('sync_running', '技能同步正在进行,请稍候再试。');
}
async find(folder) {

12
lib/skills/contracts.js Normal file
View File

@ -0,0 +1,12 @@
// Skill bundle member — the seam between skill management and cloud sync.
// The skill bundle owns the local skill folders and their receipts; the
// cloud-sync engine (src/skill-sync.ts) reads and writes them only through
// SkillRepository, and asks SkillSyncGate what it needs to know about the
// sync pass. Nothing on the sync side touches a skill directory directly.
//
// Reserved convention: the `.manifest.json` file inside a skill folder is the
// cloud delivery receipt. repository.read() reports it as `delivery`, never
// as one of `files`; repository.write() writes it by default and clears it
// with { delivery: false }. Dot-prefixed files are private to the skill side
// and never take part in a sync.
export {};

157
lib/skills/repository.js Normal file
View File

@ -0,0 +1,157 @@
// 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) });
}
};
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'),
}));
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;
}
}

73
lib/skills/shared.js Normal file
View File

@ -0,0 +1,73 @@
// Skill bundle member — the shared on-disk skill format helpers.
// Both sides of the seam speak this vocabulary: the repository and admin
// validate folder layouts with it, and the sync engine reuses the same
// constants when it prepares uploads. Moved verbatim from skill-sync.ts.
import { createHash } from 'node:crypto';
export const CLOUD_SKILL_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
/** Layout contract of the cloud skill center (mirrors its store rules). */
export const TEXT_EXT = new Set(['.md', '.txt', '.json', '.yaml', '.yml', '.py', '.sh', '.ps1', '.mjs', '.js', '.ts', '.tsx', '.css', '.html', '.csv']);
export const BINARY_EXT = new Set(['.docx', '.xlsx', '.pptx', '.pdf', '.png', '.jpg', '.jpeg', '.gif', '.svg', '.zip']);
export const SCRIPT_EXT = new Set(['.py', '.sh', '.ps1', '.mjs']);
const SKILL_DIRS = new Set(['references', 'scripts', 'assets']);
const SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
export const MAX_FILES = 100;
export const MAX_FILE_BYTES = 512 * 1024;
export const MAX_SKILL_BYTES = 2 * 1024 * 1024;
export const MAX_DEPTH = 3;
/** SHA-256 of a buffer or UTF-8 string, hex-encoded. */
export function sha256Hex(data) {
return createHash('sha256').update(data).digest('hex');
}
/**
* The center's linked bundle manifest: one `path\0sha256` line per file,
* sorted, under a version header. Byte-identical to the platform's own
* computation, so locally computed manifests compare directly.
*/
export function linkedSkillManifest(files) {
const lines = files.map((file) => `${file.path}\0${file.sha256}`).sort();
return sha256Hex(Buffer.from(`cloud-memory-skill-v1\n${lines.join('\n')}\n`, 'utf8'));
}
/** True when the cloud center would accept this relative file path. */
export function isCloudSkillPath(rel) {
if (rel === '' || rel.length > 200 || rel.startsWith('/') || rel.includes('\\') || rel.includes('//'))
return false;
const segments = rel.split('/');
if (segments.length > MAX_DEPTH)
return false;
for (const segment of segments) {
if (!SEGMENT.test(segment) || segment === '.' || segment === '..')
return false;
}
const dot = rel.lastIndexOf('.');
const ext = dot === -1 ? '' : rel.slice(dot).toLowerCase();
if (!TEXT_EXT.has(ext) && !BINARY_EXT.has(ext))
return false;
const first = segments[0];
if (segments.length === 1)
return rel === 'SKILL.md';
if (first === undefined || !SKILL_DIRS.has(first))
return false;
if (first === 'scripts' && !SCRIPT_EXT.has(ext))
return false;
return true;
}
/** Minimal frontmatter reader for `name` / `description` (plain scalars). */
export function parseSkillFrontmatter(markdown) {
if (!markdown.startsWith('---'))
return {};
const end = markdown.indexOf('\n---', 3);
if (end === -1)
return {};
const out = {};
for (const line of markdown.slice(3, end).split('\n')) {
const match = /^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(line);
if (match === null)
continue;
const value = (match[2] ?? '').replace(/^["']|["']$/g, '');
if (match[1] === 'name' && value !== '')
out.name = value;
if (match[1] === 'description' && value !== '')
out.description = value;
}
return out;
}

View File

@ -17,7 +17,7 @@ import { readFile, readdir, stat } from 'node:fs/promises'
import { homedir } from 'node:os'
import { join, resolve, sep } from 'node:path'
import { dshHome, migrateLegacyFile } from './store.ts'
import { parseSkillFrontmatter } from './skill-sync.ts'
import { parseSkillFrontmatter } from './skills/shared.ts'
import { SkillAdmin } from './skill-admin.ts'
export type SoftwareId = 'dsh' | 'agents' | 'codex' | 'workbuddy' | 'claude' | 'opencode'
@ -178,14 +178,10 @@ export class ClientRegistry {
if (workspace === undefined) throw new Error('unknown_workspace')
const skillsRoot = resolve(workspace.path, '.dsh', 'skills')
const holdingDir = join(dshHome(), 'skills-workspace-disabled', workspace.id)
const stateName = `${workspace.id.replace(/[^A-Za-z0-9_-]/g, '_')}.json`
const statePath = join(dshHome(), `dsh-brain-workspace-${stateName}`)
migrateLegacyFile(statePath, join(dshHome(), `cloud-memory-workspace-${stateName}`))
const admin = new SkillAdmin({
skillsRoot: () => skillsRoot,
holdingDir: () => holdingDir,
syncStatePath: () => statePath,
syncRunning: () => false,
gate: () => ({ isRunning: () => false, provenance: async () => null }),
log: () => {},
})
return { admin, workspace }

View File

@ -13,10 +13,11 @@ import { CloudClient } from './api.ts'
import type { CloudMemoryContext, SessionEventLike, SessionLike } from './context-types.ts'
import { Reporter } from './reporter.ts'
import { createLegacyRoutes, createRoutes } from './routes.ts'
import { join } from 'node:path'
import { join, resolve } from 'node:path'
import { SettingsStore, dshHome } from './store.ts'
import { SkillSync , skillsStatePath } from './skill-sync.ts'
import { SkillSync } from './skill-sync.ts'
import { SkillAdmin, skillsHoldingDir } from './skill-admin.ts'
import { AdminSkillRepository } from './skills/repository.ts'
import { SkillGroupManager, detectSources } from './skill-groups.ts'
import { ClaudePluginMarketplaceProvider, MarketService } from './market.ts'
import { SkillUpdater } from './skill-update.ts'
@ -69,22 +70,38 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
log: (message) => logger.warn(message),
})
const skillSync = new SkillSync({
// The skill bundle owns its folders; the composition root only wires the
// shared root path and the parking area. The sync engine touches folders
// exclusively through AdminSkillRepository below.
const skillsRootDir = (): string => {
const dir = settings().skillsDir
return dir !== '' ? resolve(dir) : join(dshHome(), 'skills')
}
// Built before the sync engine: the gate closure below dereferences
// skillSync lazily, so the TDZ order here is safe.
const skillAdmin = new SkillAdmin({
skillsRoot: skillsRootDir,
holdingDir: () => skillsHoldingDir(),
gate: () => skillSync,
log: (message) => logger.info(message),
})
// The skill bundle's public repository: the only door the cloud-sync
// engine has into skill folders.
const skillRepository = new AdminSkillRepository({
admin: skillAdmin,
skillsRoot: skillsRootDir,
holdingDir: () => skillsHoldingDir(),
})
const skillSync: SkillSync = new SkillSync({
client: () => client,
settings: () => ({
enabled: settings().enabled,
skillsSyncEnabled: settings().skillsSyncEnabled,
skillsDir: settings().skillsDir,
}),
log: (message) => logger.info(message),
holdingDir: () => skillsHoldingDir(),
})
const skillAdmin = new SkillAdmin({
skillsRoot: () => skillSync.skillsRoot(),
holdingDir: () => skillsHoldingDir(),
syncStatePath: () => skillsStatePath(),
syncRunning: () => skillSync.stats().running,
repository: () => skillRepository,
log: (message) => logger.info(message),
})
@ -111,9 +128,9 @@ export function apply(ctx: CloudMemoryContext, config: unknown): void {
const updater = new SkillUpdater({
admin: skillAdmin,
skillsRoot: () => skillSync.skillsRoot(),
skillsRoot: skillsRootDir,
holdingDir: () => skillsHoldingDir(),
syncRunning: () => skillSync.stats().running,
gate: () => skillSync,
log: (message) => logger.info(message),
})

View File

@ -12,7 +12,7 @@
* it ships. Installing an entry reuses the same staged plan/commit pipeline as
* a manual git install, pinned to the commit resolved here.
*/
import { parseSkillFrontmatter } from './skill-sync.ts'
import { parseSkillFrontmatter } from './skills/shared.ts'
/** One provider as the card lists it (no credentials, no local paths). */
export interface MarketProviderInfo {

View File

@ -30,7 +30,8 @@ import { execFile } from 'node:child_process'
import { createHash, randomUUID } from 'node:crypto'
import { cp, lstat, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'
import { basename, dirname, join, relative, resolve, sep } from 'node:path'
import { parseSkillFrontmatter } from './skill-sync.ts'
import { parseSkillFrontmatter } from './skills/shared.ts'
import type { SkillProvenance, SkillSyncGate } from './skills/contracts.ts'
import { dshHome, migrateLegacyFile } from './store.ts'
/** The parking area for disabled skills. */
@ -254,8 +255,7 @@ export interface SkillEntry {
export interface SkillAdminDeps {
skillsRoot: () => string
holdingDir: () => string
syncStatePath: () => string
syncRunning: () => boolean
gate: () => SkillSyncGate
log: (message: string) => void
/** Where plan metadata is persisted; defaults to `$DSH_HOME/.dsh-brain-plans.json`. */
plansPath?: () => string
@ -278,29 +278,14 @@ export class SkillAdmin {
}
private guardSync(): void {
if (this.deps.syncRunning()) fail('sync_running', '技能同步正在进行,请稍候再试。')
}
private async uploaded(): Promise<Record<string, { folder?: string; revision?: number }>> {
try {
const parsed: unknown = JSON.parse(await readFile(this.deps.syncStatePath(), 'utf8'))
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
const uploaded = (parsed as { uploaded?: unknown }).uploaded
if (uploaded !== null && typeof uploaded === 'object' && !Array.isArray(uploaded)) {
return uploaded as Record<string, { folder?: string; revision?: number }>
}
}
} catch {
// No sidecar yet: nothing has been uploaded.
}
return {}
if (this.deps.gate().isRunning()) fail('sync_running', '技能同步正在进行,请稍候再试。')
}
private async describe(
folder: string,
dir: string,
enabled: boolean,
uploaded: Record<string, { folder?: string; revision?: number }>,
provenance: SkillProvenance | null,
): Promise<SkillEntry | undefined> {
const markdown = await readFile(join(dir, 'SKILL.md'), 'utf8').catch(() => undefined)
if (markdown === undefined) return undefined
@ -317,14 +302,9 @@ export class SkillAdmin {
} catch {
// A corrupt manifest still marks cloud origin.
}
} else {
for (const record of Object.values(uploaded)) {
if (record.folder === folder) {
origin = 'uploaded'
if (typeof record.revision === 'number') revision = record.revision
break
}
}
} else if (provenance?.origin === 'uploaded') {
origin = 'uploaded'
if (typeof provenance.revision === 'number') revision = provenance.revision
}
const files = await walkFiles(dir)
const bytes = files.reduce((sum, file) => sum + file.bytes, 0)
@ -362,12 +342,11 @@ export class SkillAdmin {
/** Inventory of the skills root and the parking area. */
async list(): Promise<{ skills: SkillEntry[]; root: string; holding: string; staging: string }> {
const uploaded = await this.uploaded()
const skills: SkillEntry[] = []
const scan = async (area: string, enabled: boolean): Promise<void> => {
for (const entry of await readdir(area, { withFileTypes: true }).catch(() => [])) {
if (!entry.isDirectory() || entry.name.startsWith('.')) continue
const described = await this.describe(entry.name, join(area, entry.name), enabled, uploaded)
const described = await this.describe(entry.name, join(area, entry.name), enabled, await this.deps.gate().provenance(entry.name))
if (described !== undefined) skills.push(described)
}
}
@ -399,7 +378,7 @@ export class SkillAdmin {
const found = await this.locate(folder)
if (found === undefined) fail('not_found', `没有找到技能:${folder}`)
if (await isSymlink(found.dir)) fail('unsupported', `技能目录是链接,不在这里管理:${folder}`)
const entry = await this.describe(folder, found.dir, found.area === 'root', await this.uploaded())
const entry = await this.describe(folder, found.dir, found.area === 'root', await this.deps.gate().provenance(folder))
if (entry === undefined) fail('not_found', `技能缺少 SKILL.md:${folder}`)
const files = await walkFiles(found.dir)
const raw = await readFile(join(found.dir, 'SKILL.md'), 'utf8').catch(() => '')
@ -463,7 +442,7 @@ export class SkillAdmin {
const found = await this.locate(folder)
if (found === undefined) fail('not_found', `没有找到技能:${folder}`)
if (await isSymlink(found.dir)) fail('unsupported', `技能目录是链接,不在这里删除:${folder}`)
const entry = await this.describe(folder, found.dir, found.area === 'root', await this.uploaded())
const entry = await this.describe(folder, found.dir, found.area === 'root', await this.deps.gate().provenance(folder))
const files = await walkFiles(found.dir)
return {
folder,

File diff suppressed because it is too large Load Diff

View File

@ -23,6 +23,7 @@ import { tmpdir } from 'node:os'
import type { SkillAdmin, SkillSourceRecord } from './skill-admin.ts'
import { readSkillSourceRecord, SkillAdminError } from './skill-admin.ts'
import { dshHome } from './store.ts'
import type { SkillSyncGate } from './skills/contracts.ts'
/** Where pre-update backups are kept (one folder per skill, one dir per run). */
export function skillBackupsDir(): string {
@ -136,7 +137,7 @@ export interface SkillUpdaterDeps {
skillsRoot: () => string
holdingDir: () => string
backupsDir?: () => string
syncRunning: () => boolean
gate: () => SkillSyncGate
log: (message: string) => void
}
@ -151,7 +152,7 @@ export class SkillUpdater {
}
private guard(): void {
if (this.deps.syncRunning()) throw new SkillAdminError('sync_running', '技能同步正在进行,请稍候再试。')
if (this.deps.gate().isRunning()) throw new SkillAdminError('sync_running', '技能同步正在进行,请稍候再试。')
}
private async find(folder: string): Promise<{ dir: string; source: SkillSourceRecord }> {

75
src/skills/contracts.ts Normal file
View File

@ -0,0 +1,75 @@
// Skill bundle member — the seam between skill management and cloud sync.
// The skill bundle owns the local skill folders and their receipts; the
// cloud-sync engine (src/skill-sync.ts) reads and writes them only through
// SkillRepository, and asks SkillSyncGate what it needs to know about the
// sync pass. Nothing on the sync side touches a skill directory directly.
//
// Reserved convention: the `.manifest.json` file inside a skill folder is the
// cloud delivery receipt. repository.read() reports it as `delivery`, never
// as one of `files`; repository.write() writes it by default and clears it
// with { delivery: false }. Dot-prefixed files are private to the skill side
// and never take part in a sync.
import type { SkillBundle } from '../api.ts'
/** What the sync engine can tell the skill side about one name. */
export interface SkillProvenance {
name: string
origin: 'uploaded' | 'cloud-delivered'
revision?: number
manifest?: string
syncedAt?: string
}
export interface SkillSyncGate {
isRunning(): boolean
provenance(name: string): Promise<SkillProvenance | null>
}
/** One managed folder — including folders that are not valid skills yet,
* because cloud download needs to detect name collisions against them. */
export interface SkillRepositoryEntry {
name: string
area: 'root' | 'holding'
enabled: boolean
}
export interface SkillRepositoryFile {
path: string
sha256: string
size: number
/** File bytes, base64-encoded. */
data: string
}
/** Parsed `.manifest.json` delivery receipt. */
export interface SkillRepositoryDelivery {
name?: string
revision?: number
manifest?: string
files?: { path: string; sha256: string }[]
syncedAt?: string
}
/** A local skill folder as the sync engine sees it. */
export interface SkillLocalBundle {
name: string
area: 'root' | 'holding'
files: SkillRepositoryFile[]
delivery?: SkillRepositoryDelivery
}
export interface SkillRepositoryWriteOptions {
/** Write the cloud delivery receipt (default true); false clears it. */
delivery?: boolean
}
export interface SkillRepository {
list(): Promise<SkillRepositoryEntry[]>
read(name: string): Promise<SkillLocalBundle | undefined>
write(name: string, bundle: SkillBundle, options?: SkillRepositoryWriteOptions): Promise<void>
park(name: string): Promise<void>
unpark(name: string): Promise<void>
/** Copy the folder to a timestamped backup; the backup path, or undefined when absent. */
snapshot(name: string): Promise<string | undefined>
}

165
src/skills/repository.ts Normal file
View File

@ -0,0 +1,165 @@
// 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.ts'
import type { SkillAdmin } from '../skill-admin.ts'
import type { SkillBundle } from '../api.ts'
import type { SkillLocalBundle, SkillRepository, SkillRepositoryDelivery, SkillRepositoryEntry } from './contracts.ts'
import { sha256Hex } from './shared.ts'
export interface AdminSkillRepositoryDeps {
/** Folder moves and locate() come from the admin; it already owns park/unpark. */
admin: SkillAdmin
skillsRoot: () => string
holdingDir: () => string
}
const RECEIPT = '.manifest.json'
async function isDirectory(path: string): Promise<boolean> {
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: string): Promise<{ rel: string; bytes: Buffer }[]> {
const files: { rel: string; bytes: Buffer }[] = []
const walk = async (current: string, depth: number): Promise<void> => {
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) })
}
}
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: string): Promise<SkillRepositoryDelivery | undefined> {
try {
const raw: unknown = JSON.parse(await readFile(join(dir, RECEIPT), 'utf8'))
if (typeof raw !== 'object' || raw === null) return undefined
const record = raw as Record<string, unknown>
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): file is { path: string; sha256: string } => typeof file === 'object' && file !== null && typeof (file as { path?: unknown }).path === 'string' && typeof (file as { sha256?: unknown }).sha256 === 'string')
: undefined
const delivery: SkillRepositoryDelivery = { 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 implements SkillRepository {
private readonly deps: AdminSkillRepositoryDeps
constructor(deps: AdminSkillRepositoryDeps) {
this.deps = deps
}
async list(): Promise<SkillRepositoryEntry[]> {
const entries: SkillRepositoryEntry[] = []
// 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: string): Promise<SkillLocalBundle | undefined> {
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'),
}))
return { name, area, files, delivery: await readDeliveryReceipt(found.dir) }
}
async write(name: string, bundle: SkillBundle, options?: { delivery?: boolean }): Promise<void> {
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: { path: string; sha256: string; size: number }[] = []
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: string): Promise<void> {
await this.deps.admin.setEnabled(name, false)
}
async unpark(name: string): Promise<void> {
await this.deps.admin.setEnabled(name, true)
}
async snapshot(name: string): Promise<string | undefined> {
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
}
}

68
src/skills/shared.ts Normal file
View File

@ -0,0 +1,68 @@
// Skill bundle member — the shared on-disk skill format helpers.
// Both sides of the seam speak this vocabulary: the repository and admin
// validate folder layouts with it, and the sync engine reuses the same
// constants when it prepares uploads. Moved verbatim from skill-sync.ts.
import { createHash } from 'node:crypto'
export const CLOUD_SKILL_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/
/** Layout contract of the cloud skill center (mirrors its store rules). */
export const TEXT_EXT = new Set(['.md', '.txt', '.json', '.yaml', '.yml', '.py', '.sh', '.ps1', '.mjs', '.js', '.ts', '.tsx', '.css', '.html', '.csv'])
export const BINARY_EXT = new Set(['.docx', '.xlsx', '.pptx', '.pdf', '.png', '.jpg', '.jpeg', '.gif', '.svg', '.zip'])
export const SCRIPT_EXT = new Set(['.py', '.sh', '.ps1', '.mjs'])
const SKILL_DIRS = new Set(['references', 'scripts', 'assets'])
const SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/
export const MAX_FILES = 100
export const MAX_FILE_BYTES = 512 * 1024
export const MAX_SKILL_BYTES = 2 * 1024 * 1024
export const MAX_DEPTH = 3
/** SHA-256 of a buffer or UTF-8 string, hex-encoded. */
export function sha256Hex(data: Buffer | string): string {
return createHash('sha256').update(data).digest('hex')
}
/**
* The center's linked bundle manifest: one `path\0sha256` line per file,
* sorted, under a version header. Byte-identical to the platform's own
* computation, so locally computed manifests compare directly.
*/
export function linkedSkillManifest(files: readonly { path: string; sha256: string }[]): string {
const lines = files.map((file) => `${file.path}\0${file.sha256}`).sort()
return sha256Hex(Buffer.from(`cloud-memory-skill-v1\n${lines.join('\n')}\n`, 'utf8'))
}
/** True when the cloud center would accept this relative file path. */
export function isCloudSkillPath(rel: string): boolean {
if (rel === '' || rel.length > 200 || rel.startsWith('/') || rel.includes('\\') || rel.includes('//')) return false
const segments = rel.split('/')
if (segments.length > MAX_DEPTH) return false
for (const segment of segments) {
if (!SEGMENT.test(segment) || segment === '.' || segment === '..') return false
}
const dot = rel.lastIndexOf('.')
const ext = dot === -1 ? '' : rel.slice(dot).toLowerCase()
if (!TEXT_EXT.has(ext) && !BINARY_EXT.has(ext)) return false
const first = segments[0]
if (segments.length === 1) return rel === 'SKILL.md'
if (first === undefined || !SKILL_DIRS.has(first)) return false
if (first === 'scripts' && !SCRIPT_EXT.has(ext)) return false
return true
}
/** Minimal frontmatter reader for `name` / `description` (plain scalars). */
export function parseSkillFrontmatter(markdown: string): { name?: string; description?: string } {
if (!markdown.startsWith('---')) return {}
const end = markdown.indexOf('\n---', 3)
if (end === -1) return {}
const out: { name?: string; description?: string } = {}
for (const line of markdown.slice(3, end).split('\n')) {
const match = /^\s*(name|description)\s*:\s*(.+?)\s*$/.exec(line)
if (match === null) continue
const value = (match[2] ?? '').replace(/^["']|["']$/g, '')
if (match[1] === 'name' && value !== '') out.name = value
if (match[1] === 'description' && value !== '') out.description = value
}
return out
}

View File

@ -57,8 +57,7 @@ const reporter = new Reporter({
const admin = new SkillAdmin({
skillsRoot: () => root,
holdingDir: () => holding,
syncStatePath: () => join(process.env.DSH_HOME, 'dsh-brain-skills.json'),
syncRunning: () => false,
gate: () => ({ isRunning: () => false, provenance: async () => null }),
log: () => {},
})
const routes = createRoutes({

View File

@ -28,8 +28,8 @@ mkdirSync(join(root, 'alpha'), { recursive: true })
writeFileSync(join(root, 'alpha', 'SKILL.md'), '# alpha\n')
let running = true
const admin = new SkillAdmin({ skillsRoot: () => root, holdingDir: () => holding, syncStatePath: () => join(process.env.DSH_HOME, 'dsh-brain-skills.json'), syncRunning: () => running, log: () => {} })
const updater = new SkillUpdater({ admin, skillsRoot: () => root, holdingDir: () => holding, syncRunning: () => running, log: () => {} })
const admin = new SkillAdmin({ skillsRoot: () => root, holdingDir: () => holding, gate: () => ({ isRunning: () => running, provenance: async () => null }), log: () => {} })
const updater = new SkillUpdater({ admin, skillsRoot: () => root, holdingDir: () => holding, gate: () => ({ isRunning: () => running, provenance: async () => null }), log: () => {} })
async function expectCode(fn, code) {
try { await fn(); return false } catch (error) { return error.code === code || error.message === code }

View File

@ -92,7 +92,7 @@ const reporter = new Reporter({
client: () => ({ reportTurn: async () => ({ ok: true, status: 200, data: {} }), submitSummary: async () => ({ ok: true, status: 200, data: {} }) }),
settings: () => ({ enabled: true, clientId: 'test' }), activityToken: () => '', summary: () => ({ enabled: false, maxChars: 1 }), summaryToken: () => '', log: () => {},
})
const admin = new SkillAdmin({ skillsRoot: () => root, holdingDir: () => holding, syncStatePath: () => join(process.env.DSH_HOME, 'dsh-brain-skills.json'), syncRunning: () => false, log: () => {} })
const admin = new SkillAdmin({ skillsRoot: () => root, holdingDir: () => holding, gate: () => ({ isRunning: () => false, provenance: async () => null }), log: () => {} })
const entry = { id: 'alpha', providerId: 'fake', name: 'alpha', description: 'fake alpha', skills: ['alpha'], skillPaths: ['./skills/alpha'], sourceRepo: 'local/repo', sourceUrl: 'file://x' }
const fakeProvider = {
info: () => ({ id: 'fake', label: 'Fake', description: 'local', source: 'local/repo', homepage: 'https://example' }),

View File

@ -50,8 +50,13 @@ const holding = skillsHoldingDir()
const admin = new SkillAdmin({
skillsRoot: () => root,
holdingDir: () => holding,
syncStatePath: () => join(process.env.DSH_HOME, 'cloud-memory-skills.json'),
syncRunning: () => false,
// Gate stub mirroring the sidecar above: plain-local was uploaded at revision 3.
gate: () => ({
isRunning: () => false,
provenance: async (name) => name === 'plain-local'
? { name, origin: 'uploaded', revision: 3, manifest: 'x', syncedAt: 'now' }
: null,
}),
log: () => {},
})
@ -138,13 +143,15 @@ const server = http.createServer((req, res) => {
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
const { CloudClient } = await import('./lib/api.js')
const { SkillSync } = await import('./lib/skill-sync.js')
const { AdminSkillRepository } = await import('./lib/skills/repository.js')
const tk = () => 'test-token'
const client = new CloudClient({ baseUrl: () => `http://127.0.0.1:${server.address().port}/api/longmemory`, ['tok' + 'en']: tk, timeoutMs: () => 3000 })
const skillRepo = new AdminSkillRepository({ admin, skillsRoot: () => root, holdingDir: () => holding })
const engine = new SkillSync({
client: () => client,
settings: () => ({ enabled: true, skillsSyncEnabled: true, skillsDir: '' }),
settings: () => ({ enabled: true, skillsSyncEnabled: true }),
repository: () => skillRepo,
log: () => {},
holdingDir: () => holding,
})
await admin.setEnabled('cloudy', false)
let stats = await engine.syncOnce()

View File

@ -54,8 +54,7 @@ const { createRoutes } = await import('./lib/routes.js')
const admin = new SkillAdmin({
skillsRoot: () => root,
holdingDir: () => holding,
syncStatePath: () => join(process.env.DSH_HOME, 'dsh-brain-skills.json'),
syncRunning: () => false,
gate: () => ({ isRunning: () => false, provenance: async () => null }),
log: () => {},
})
const sources = () => [

View File

@ -38,8 +38,7 @@ const { createRoutes } = await import('./lib/routes.js')
const admin = new SkillAdmin({
skillsRoot: () => root,
holdingDir: () => holding,
syncStatePath: () => join(process.env.DSH_HOME, 'dsh-brain-skills.json'),
syncRunning: () => false,
gate: () => ({ isRunning: () => false, provenance: async () => null }),
log: () => {},
})

View File

@ -30,8 +30,8 @@ execFileSync('git', ['-C', repoDir, '-c', 'user.name=t', '-c', 'user.email=t@t',
const c1 = execFileSync('git', ['-C', repoDir, 'rev-parse', 'HEAD']).toString().trim()
const repoUrl = 'file://' + repoDir.replace(/\\/g, '/')
const admin = new SkillAdmin({ skillsRoot: () => root, holdingDir: () => holding, syncStatePath: () => join(process.env.DSH_HOME, 'cloud-memory-skills.json'), syncRunning: () => false, log: () => {} })
const updater = new SkillUpdater({ admin, skillsRoot: () => root, holdingDir: () => holding, syncRunning: () => false, log: () => {} })
const admin = new SkillAdmin({ skillsRoot: () => root, holdingDir: () => holding, gate: () => ({ isRunning: () => false, provenance: async () => null }), log: () => {} })
const updater = new SkillUpdater({ admin, skillsRoot: () => root, holdingDir: () => holding, gate: () => ({ isRunning: () => false, provenance: async () => null }), log: () => {} })
// Install alpha from the repo.
const plan = await admin.prepareInstall(repoUrl)

View File

@ -112,12 +112,19 @@ const { CloudClient } = await import('./lib/api.js')
const { SkillSync } = await import('./lib/skill-sync.js')
const tk = () => 'test-token'
const client = new CloudClient({ baseUrl: () => base, ['tok' + 'en']: tk, timeoutMs: () => 3000 })
const root = join(process.env.DSH_HOME, 'skills')
const holding = join(process.env.DSH_HOME, 'skills-disabled')
const { SkillAdmin } = await import('./lib/skill-admin.js')
const { AdminSkillRepository } = await import('./lib/skills/repository.js')
// The composition root's wiring, in miniature: admin + repository + engine.
const admin = new SkillAdmin({ skillsRoot: () => root, holdingDir: () => holding, gate: () => engine, log: () => {} })
const repo = new AdminSkillRepository({ admin, skillsRoot: () => root, holdingDir: () => holding })
const engine = new SkillSync({
client: () => client,
settings: () => ({ enabled: true, skillsSyncEnabled: true, skillsDir: '' }),
settings: () => ({ enabled: true, skillsSyncEnabled: true }),
repository: () => repo,
log: () => {},
})
const root = join(process.env.DSH_HOME, 'skills')
const skillDir = (name) => join(root, name)
const writeLocal = (name, files, mtime = Date.now()) => {
for (const [rel, content] of Object.entries(files)) {

View File

@ -55,9 +55,15 @@ const client = {
},
}
const { SkillAdmin } = await import('./lib/skill-admin.js')
const { AdminSkillRepository } = await import('./lib/skills/repository.js')
const holding = join(process.env.DSH_HOME, 'skills-disabled')
const admin = new SkillAdmin({ skillsRoot: () => root, holdingDir: () => holding, gate: () => sync, log: () => {} })
const repo = new AdminSkillRepository({ admin, skillsRoot: () => root, holdingDir: () => holding })
const sync = new SkillSync({
client: () => client,
settings: () => ({ enabled: true, skillsSyncEnabled: true, skillsDir: '' }),
settings: () => ({ enabled: true, skillsSyncEnabled: true }),
repository: () => repo,
log: () => {},
})
const stats = await sync.syncOnce()