diff --git a/lib/cloudsync-routes.js b/lib/cloudsync-routes.js index 944e859..cd19a67 100644 --- a/lib/cloudsync-routes.js +++ b/lib/cloudsync-routes.js @@ -219,6 +219,7 @@ async function serveLogin(deps, req, res) { * `GET /dsh-brain/sync/status` latest stats + both sides of each conflict * `POST /dsh-brain/sync/run` trigger one pass now * `POST /dsh-brain/sync/resolve` { name, action: keep_local | take_cloud | manual } + * `POST /dsh-brain/sync/resolve-all` { action: keep_local | take_cloud } */ async function serveSync(deps, req, res) { const sync = deps.sync; @@ -258,6 +259,18 @@ async function serveSync(deps, req, res) { json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() }); return; } + if (suffix === '/resolve-all') { + if (req.method !== 'POST') { + fail(res, 405, 'method-not-allowed'); + return; + } + const body = await jsonBody(req, res); + if (body === undefined) + return; + const result = await sync.resolveConflicts(body.action); + json(res, 200, { ok: true, ...result, stats: sync.stats(), conflicts: await sync.conflictDetails() }); + return; + } fail(res, 404, 'unknown-sync-route'); } catch (error) { diff --git a/lib/skill-sync.js b/lib/skill-sync.js index 47cab2d..2cfe23d 100644 --- a/lib/skill-sync.js +++ b/lib/skill-sync.js @@ -15,12 +15,17 @@ * revisions, guarded by the center's `expected_revision` check. * * Safety rules (deliberate, in order): - * 1. A cloud-delivered skill is never re-uploaded. If its local files no - * longer match the delivery manifest, the skill is flagged as a - * conflict and left completely alone. + * 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; - * it is reported as a conflict for a human to resolve. + * 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. @@ -39,6 +44,25 @@ import { dshHome, migrateLegacyFile } from "./store.js"; // 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() { @@ -233,6 +257,11 @@ export class SkillSync { } 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; } @@ -246,6 +275,11 @@ export class SkillSync { } } 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; } @@ -275,7 +309,10 @@ export class SkillSync { stats.downloaded.push(item.name); } // UP: only local-origin folders ride. A delivery receipt means the - // cloud owns the name, so its local edits go through conflicts. + // 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; @@ -288,12 +325,37 @@ export class SkillSync { if (skill === undefined) continue; if (typeof skill === 'string') { - this.conflict(stats, entry.name, skill); + 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 (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, + 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; } @@ -301,12 +363,7 @@ export class SkillSync { stats.skipped += 1; continue; } - const files = skill.files.map((file) => { - const ext = file.path.slice(file.path.lastIndexOf('.')).toLowerCase(); - return TEXT_EXT.has(ext) - ? { path: file.path, content: Buffer.from(file.data, 'base64').toString('utf8') } - : { path: file.path, base64: file.data }; - }); + const files = this.toUploadFiles(skill.files); const operationId = `dsh-skill-${randomUUID()}`; if (record === undefined || cloud === undefined) { const created = await client.createSkill({ @@ -332,7 +389,33 @@ export class SkillSync { } else { if (cloud.revision !== undefined && cloud.revision !== record.revision) { - this.conflict(stats, skill.name, 'cloud_newer'); + // 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, + 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, { @@ -431,9 +514,146 @@ export class SkillSync { : { 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) { + await this.deps.repository().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 })), + }); + } + /** Fetch, verify and install the cloud copy, backing the local one up first. */ + async autoTakeCloud(item, local, 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'; + } + if (local !== undefined) + await this.deps.repository().snapshot(item.name); + await this.deps.repository().write(item.name, bundle.data); + this.markDelivered(state, item.name, bundle.data.manifest_sha256); + 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.deps.repository().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, 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); + this.markDelivered(state, item.name, item.manifest_sha256); + 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); + this.markDelivered(state, item.name, item.manifest_sha256); + 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); + 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) { + 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 }; + } async conflictDetails() { const conflicts = this.current.conflicts; if (conflicts.length === 0) diff --git a/lib/skills/repository.js b/lib/skills/repository.js index ead84ff..a8a0813 100644 --- a/lib/skills/repository.js +++ b/lib/skills/repository.js @@ -35,7 +35,11 @@ async function walkSkillFiles(dir) { } if (!entry.isFile()) continue; - files.push({ rel: full.slice(dir.length + 1).replace(/\\/g, '/'), bytes: await readFile(full) }); + files.push({ + rel: full.slice(dir.length + 1).replace(/\\/g, '/'), + bytes: await readFile(full), + mtimeMs: (await stat(full)).mtimeMs, + }); } }; await walk(dir, 0); @@ -95,6 +99,7 @@ export class AdminSkillRepository { sha256: sha256Hex(file.bytes), size: file.bytes.length, data: file.bytes.toString('base64'), + mtimeMs: file.mtimeMs, })); return { name, area, files, delivery: await readDeliveryReceipt(found.dir) }; } diff --git a/src/cloudsync-routes.ts b/src/cloudsync-routes.ts index 04a96f7..1a2fe2c 100644 --- a/src/cloudsync-routes.ts +++ b/src/cloudsync-routes.ts @@ -253,6 +253,7 @@ async function serveLogin(deps: CloudSyncRouteDeps, req: IncomingMessage, res: S * `GET /dsh-brain/sync/status` latest stats + both sides of each conflict * `POST /dsh-brain/sync/run` trigger one pass now * `POST /dsh-brain/sync/resolve` { name, action: keep_local | take_cloud | manual } + * `POST /dsh-brain/sync/resolve-all` { action: keep_local | take_cloud } */ async function serveSync(deps: CloudSyncRouteDeps, req: IncomingMessage, res: ServerResponse): Promise { @@ -283,6 +284,14 @@ async function serveSync(deps: CloudSyncRouteDeps, req: IncomingMessage, res: Se json(res, 200, { ok: true, ...result, conflicts: await sync.conflictDetails() }) return } + if (suffix === '/resolve-all') { + if (req.method !== 'POST') { fail(res, 405, 'method-not-allowed'); return } + const body = await jsonBody(req, res) + if (body === undefined) return + const result = await sync.resolveConflicts(body.action) + json(res, 200, { ok: true, ...result, stats: sync.stats(), conflicts: await sync.conflictDetails() }) + return + } fail(res, 404, 'unknown-sync-route') } catch (error) { const message = error instanceof Error ? error.message : String(error) diff --git a/src/skill-sync.ts b/src/skill-sync.ts index cfe9f37..57cc563 100644 --- a/src/skill-sync.ts +++ b/src/skill-sync.ts @@ -15,12 +15,17 @@ * revisions, guarded by the center's `expected_revision` check. * * Safety rules (deliberate, in order): - * 1. A cloud-delivered skill is never re-uploaded. If its local files no - * longer match the delivery manifest, the skill is flagged as a - * conflict and left completely alone. + * 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; - * it is reported as a conflict for a human to resolve. + * 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. @@ -47,6 +52,28 @@ export { isCloudSkillPath, parseSkillFrontmatter, } from './skills/shared.ts' +/** Parse an ISO string or epoch number into epoch milliseconds. */ +function timestampMs(value: string | number | undefined): number | undefined { + 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: readonly SkillRepositoryFile[]): number { + let newest = 0 + for (const file of files) { + if (file.mtimeMs > newest) newest = file.mtimeMs + } + return newest +} + +/** Outcome of one automatic conflict resolution inside a pass. */ +type AutoResolution = 'resolved' | 'conflict' | 'unresolved' + /** One sync conflict a human should look at; sync never forces these. */ export interface SkillSyncConflict { name: string @@ -294,6 +321,11 @@ export class SkillSync implements SkillSyncGate { } 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 } @@ -306,6 +338,11 @@ export class SkillSync implements SkillSyncGate { 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 } @@ -334,7 +371,10 @@ export class SkillSync implements SkillSyncGate { } // UP: only local-origin folders ride. A delivery receipt means the - // cloud owns the name, so its local edits go through conflicts. + // 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) @@ -343,22 +383,40 @@ export class SkillSync implements SkillSyncGate { const skill = await this.readLocalSkill(local, entry.name) if (skill === undefined) continue if (typeof skill === 'string') { - this.conflict(stats, entry.name, skill) + 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 (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, + 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 } if (record !== undefined && record.manifest === skill.manifest) { stats.skipped += 1; continue } - const files: SkillUploadFile[] = skill.files.map((file) => { - const ext = file.path.slice(file.path.lastIndexOf('.')).toLowerCase() - return TEXT_EXT.has(ext) - ? { path: file.path, content: Buffer.from(file.data, 'base64').toString('utf8') } - : { path: file.path, base64: file.data } - }) + const files: SkillUploadFile[] = this.toUploadFiles(skill.files) const operationId = `dsh-skill-${randomUUID()}` if (record === undefined || cloud === undefined) { const created = await client.createSkill({ @@ -383,7 +441,32 @@ export class SkillSync implements SkillSyncGate { stats.uploaded.push(skill.name) } else { if (cloud.revision !== undefined && cloud.revision !== record.revision) { - this.conflict(stats, skill.name, 'cloud_newer') + // 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, + 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, { @@ -479,10 +562,179 @@ export class SkillSync implements SkillSyncGate { }) } + /** The center's last-change time for one listed skill (ISO or epoch). */ + private cloudUpdatedAt(item: SkillSummary): number | undefined { + return timestampMs(item.updated_at) ?? timestampMs(item.created_at) + } + + /** Manifest over every local file, in the linked form. */ + private localManifest(files: readonly SkillRepositoryFile[]): string { + 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. + */ + private async adoptIdenticalDelivery(item: SkillSummary, local: SkillLocalBundle): Promise { + await this.deps.repository().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 })), + }) + } + + /** Fetch, verify and install the cloud copy, backing the local one up first. */ + private async autoTakeCloud( + item: SkillSummary, + local: SkillLocalBundle | undefined, + state: SyncState, + stats: SkillSyncStats, + client: CloudClient, + ): Promise { + 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' + } + if (local !== undefined) await this.deps.repository().snapshot(item.name) + await this.deps.repository().write(item.name, bundle.data) + this.markDelivered(state, item.name, bundle.data.manifest_sha256) + delete state.removed[item.name] + stats.updated.push(item.name) + return 'resolved' + } + + /** Publish the local copy as the next cloud revision. */ + private async autoUploadLocal( + skill: LocalSkill, + folder: string, + cloud: SkillSummary, + state: SyncState, + stats: SkillSyncStats, + client: CloudClient, + ): Promise { + 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.deps.repository().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, 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. */ + private async autoResolveCollision( + item: SkillSummary, + local: SkillLocalBundle, + state: SyncState, + stats: SkillSyncStats, + client: CloudClient, + ): Promise { + 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) + this.markDelivered(state, item.name, item.manifest_sha256) + stats.skipped += 1 + return 'resolved' + } + return this.resolveDiverged(item, local, state, stats, client) + } + + /** Resolve a locally-modified cloud delivery. */ + private async autoResolveLocalDrift( + item: SkillSummary, + local: SkillLocalBundle, + state: SyncState, + stats: SkillSyncStats, + client: CloudClient, + ): Promise { + if (item.manifest_sha256 !== undefined && local.files.length > 0 && this.localManifest(local.files) === item.manifest_sha256) { + await this.adoptIdenticalDelivery(item, local) + this.markDelivered(state, item.name, item.manifest_sha256) + stats.skipped += 1 + return 'resolved' + } + return this.resolveDiverged(item, local, state, stats, client) + } + + /** The sides differ: the clearly newer one wins, ambiguity stays human. */ + private async resolveDiverged( + item: SkillSummary, + local: SkillLocalBundle, + state: SyncState, + stats: SkillSyncStats, + client: CloudClient, + ): Promise { + 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) + 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) + } + private dropConflict(name: string): void { 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: unknown): Promise { + 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: string[] = [] + const failed: { name: string; error: string }[] = [] + 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 } + } + async conflictDetails(): Promise { const conflicts = this.current.conflicts if (conflicts.length === 0) return [] @@ -648,4 +900,11 @@ export interface SyncResolveResult { revision?: number backup?: string note: string +} + +/** Outcome of a batch resolution over every current conflict. */ +export interface SyncResolveBatchResult { + action: 'keep_local' | 'take_cloud' + resolved: string[] + failed: { name: string; error: string }[] } \ No newline at end of file diff --git a/src/skills/contracts.ts b/src/skills/contracts.ts index 518954f..12b9390 100644 --- a/src/skills/contracts.ts +++ b/src/skills/contracts.ts @@ -40,6 +40,8 @@ export interface SkillRepositoryFile { size: number /** File bytes, base64-encoded. */ data: string + /** Local modification time, for auto-resolve comparisons. */ + mtimeMs: number } /** Parsed `.manifest.json` delivery receipt. */ diff --git a/src/skills/repository.ts b/src/skills/repository.ts index 239fc62..c518d3f 100644 --- a/src/skills/repository.ts +++ b/src/skills/repository.ts @@ -28,8 +28,8 @@ async function isDirectory(path: string): Promise { } /** 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 }[] = [] +async function walkSkillFiles(dir: string): Promise<{ rel: string; bytes: Buffer; mtimeMs: number }[]> { + const files: { rel: string; bytes: Buffer; mtimeMs: number }[] = [] const walk = async (current: string, depth: number): Promise => { let entries try { @@ -45,7 +45,11 @@ async function walkSkillFiles(dir: string): Promise<{ rel: string; bytes: Buffer continue } if (!entry.isFile()) continue - files.push({ rel: full.slice(dir.length + 1).replace(/\\/g, '/'), bytes: await readFile(full) }) + files.push({ + rel: full.slice(dir.length + 1).replace(/\\/g, '/'), + bytes: await readFile(full), + mtimeMs: (await stat(full)).mtimeMs, + }) } } await walk(dir, 0) @@ -102,6 +106,7 @@ export class AdminSkillRepository implements SkillRepository { sha256: sha256Hex(file.bytes), size: file.bytes.length, data: file.bytes.toString('base64'), + mtimeMs: file.mtimeMs, })) return { name, area, files, delivery: await readDeliveryReceipt(found.dir) } } diff --git a/verify-sync-resolve.mjs b/verify-sync-resolve.mjs index 86deb6f..0375b2b 100644 --- a/verify-sync-resolve.mjs +++ b/verify-sync-resolve.mjs @@ -143,9 +143,13 @@ const client2 = { createSkill: async () => ({ ok: true, status: 200, data: { skill: { revision: 1 } } }), updateSkill: async () => ({ ok: true, status: 200, data: { skill: { revision: 3 } } }), } +const holding2 = join(secondHome, 'skills-disabled') +const admin2 = new SkillAdmin({ skillsRoot: () => root2, holdingDir: () => holding2, gate: () => sync2, log: () => {} }) +const repo2 = new AdminSkillRepository({ admin: admin2, skillsRoot: () => root2, holdingDir: () => holding2 }) const sync2 = new SkillSync({ client: () => client2, - settings: () => ({ enabled: true, skillsSyncEnabled: true, skillsDir: '' }), + settings: () => ({ enabled: true, skillsSyncEnabled: true }), + repository: () => repo2, log: () => {}, }) const stats2 = await sync2.syncOnce()