fix(skill-sync): bind conflict resolution to the confirmed preview snapshot
This commit is contained in:
parent
467aea49be
commit
cae5c08a80
|
|
@ -18,7 +18,7 @@ section 15); the local layer remains usable without an account, token or network
|
||||||
| `node verify-skill-sync-round2.mjs` | ALL 13 CHECKS PASSED |
|
| `node verify-skill-sync-round2.mjs` | ALL 13 CHECKS PASSED |
|
||||||
| `node verify-sync-resolve.mjs` | 23/23 passed |
|
| `node verify-sync-resolve.mjs` | 23/23 passed |
|
||||||
| `node verify-skill-sync-scope-round3.mjs` | ALL 2 CHECKS PASSED |
|
| `node verify-skill-sync-scope-round3.mjs` | ALL 2 CHECKS PASSED |
|
||||||
| `node verify-skill-sync-conflict-round5.mjs` | ALL 5 CHECKS PASSED |
|
| `node verify-skill-sync-conflict-round5.mjs` | ALL 19 CHECKS PASSED |
|
||||||
| `node verify-local-memory-round4.mjs` | ALL 12 CHECKS PASSED |
|
| `node verify-local-memory-round4.mjs` | ALL 12 CHECKS PASSED |
|
||||||
| `node verify-local-memory-round5.mjs` | ALL 6 CHECKS PASSED |
|
| `node verify-local-memory-round5.mjs` | ALL 6 CHECKS PASSED |
|
||||||
| `node verify-local-memory-round6.mjs` | ALL 8 CHECKS PASSED |
|
| `node verify-local-memory-round6.mjs` | ALL 8 CHECKS PASSED |
|
||||||
|
|
|
||||||
|
|
@ -78,6 +78,8 @@ export class SkillSync {
|
||||||
/** Jobs accepted into the queue but not settled yet; makes busy() honest. */
|
/** Jobs accepted into the queue but not settled yet; makes busy() honest. */
|
||||||
pendingWrites = 0;
|
pendingWrites = 0;
|
||||||
stateCache;
|
stateCache;
|
||||||
|
/** Latest previews by conflict id: the exact snapshot the user confirmed. */
|
||||||
|
previews = new Map();
|
||||||
runRepository;
|
runRepository;
|
||||||
runScopeKey;
|
runScopeKey;
|
||||||
current = {
|
current = {
|
||||||
|
|
@ -883,15 +885,23 @@ export class SkillSync {
|
||||||
async resolveConflictsLocked(action, conflictIdsInput) {
|
async resolveConflictsLocked(action, conflictIdsInput) {
|
||||||
if (this.running)
|
if (this.running)
|
||||||
throw new Error('sync_running');
|
throw new Error('sync_running');
|
||||||
|
if (!Array.isArray(conflictIdsInput) || conflictIdsInput.length === 0 || conflictIdsInput.some((value) => typeof value !== 'string' || value.trim() === '')) {
|
||||||
|
throw new Error('confirmation_required');
|
||||||
|
}
|
||||||
const run = this.captureRun();
|
const run = this.captureRun();
|
||||||
const scopeKey = this.scopeKey(run.scope);
|
const scopeKey = this.scopeKey(run.scope);
|
||||||
const details = await this.conflictDetails(run);
|
const details = await this.conflictDetails(run);
|
||||||
const requested = Array.isArray(conflictIdsInput) ? new Set(conflictIdsInput.filter((value) => typeof value === 'string')) : undefined;
|
const requested = new Set(conflictIdsInput);
|
||||||
const selected = details.filter((detail) => (detail.scopeKey === scopeKey || detail.scopeKey === '') && (requested === undefined || requested.has(detail.conflictId)));
|
const currentIds = new Set(details.filter((detail) => detail.scopeKey === scopeKey || detail.scopeKey === '').map((detail) => detail.conflictId));
|
||||||
|
const selected = details.filter((detail) => (detail.scopeKey === scopeKey || detail.scopeKey === '') && requested.has(detail.conflictId));
|
||||||
const names = [...new Set(selected.map((detail) => detail.name))];
|
const names = [...new Set(selected.map((detail) => detail.name))];
|
||||||
const idByName = new Map(selected.map((detail) => [detail.name, detail.conflictId]));
|
const idByName = new Map(selected.map((detail) => [detail.name, detail.conflictId]));
|
||||||
const resolved = [];
|
const resolved = [];
|
||||||
const failed = [];
|
const failed = [];
|
||||||
|
for (const id of requested) {
|
||||||
|
if (!currentIds.has(id))
|
||||||
|
failed.push({ name: this.previews.get(id)?.name ?? 'unknown', error: 'stale_conflict' });
|
||||||
|
}
|
||||||
for (const name of names) {
|
for (const name of names) {
|
||||||
try {
|
try {
|
||||||
await this.resolveConflictLocked(name, action, run, idByName.get(name));
|
await this.resolveConflictLocked(name, action, run, idByName.get(name));
|
||||||
|
|
@ -935,7 +945,13 @@ export class SkillSync {
|
||||||
const localVersion = local === undefined ? 'none' : sha256Hex(local.files.map((file) => file.path + '\0' + file.sha256).sort().join('\n'));
|
const localVersion = local === undefined ? 'none' : sha256Hex(local.files.map((file) => file.path + '\0' + file.sha256).sort().join('\n'));
|
||||||
const cloudVersion = cloudItem === undefined ? 'none' : String(cloudItem.revision ?? '') + ':' + String(cloudItem.manifest_sha256 ?? '');
|
const cloudVersion = cloudItem === undefined ? 'none' : String(cloudItem.revision ?? '') + ':' + String(cloudItem.manifest_sha256 ?? '');
|
||||||
const scopeKey = conflict.scopeKey ?? this.scopeKey(active.scope);
|
const scopeKey = conflict.scopeKey ?? this.scopeKey(active.scope);
|
||||||
const conflictId = sha256Hex([scopeKey, conflict.name, conflict.reason, localVersion, cloudVersion].join('|'));
|
const conflictId = sha256Hex([scopeKey, conflict.name, localFolder, conflict.reason, localVersion, cloudVersion].join('|'));
|
||||||
|
this.previews.set(conflictId, { name: conflict.name, scopeKey, folder: localFolder });
|
||||||
|
if (this.previews.size > 1000) {
|
||||||
|
const oldest = this.previews.keys().next().value;
|
||||||
|
if (oldest !== undefined)
|
||||||
|
this.previews.delete(oldest);
|
||||||
|
}
|
||||||
out.push({
|
out.push({
|
||||||
conflictId,
|
conflictId,
|
||||||
scopeKey,
|
scopeKey,
|
||||||
|
|
@ -984,15 +1000,16 @@ export class SkillSync {
|
||||||
if (expectedConflictId === undefined)
|
if (expectedConflictId === undefined)
|
||||||
throw new Error('confirmation_required');
|
throw new Error('confirmation_required');
|
||||||
const details = await this.conflictDetails(active);
|
const details = await this.conflictDetails(active);
|
||||||
const confirmed = details.find((detail) => detail.name === name);
|
const confirmed = details.find((detail) => detail.name === name && detail.conflictId === expectedConflictId);
|
||||||
if (confirmed === undefined || confirmed.conflictId !== expectedConflictId)
|
if (confirmed === undefined)
|
||||||
throw new Error('stale_conflict');
|
throw new Error('stale_conflict');
|
||||||
|
const preview = this.previews.get(expectedConflictId);
|
||||||
const listing = await client.listSkills();
|
const listing = await client.listSkills();
|
||||||
if (!listing.ok)
|
if (!listing.ok)
|
||||||
throw new Error(`skill listing failed: ${describeError(listing.error)}`);
|
throw new Error(`skill listing failed: ${describeError(listing.error)}`);
|
||||||
const cloud = (listing.data.items ?? []).find((item) => item.name === name);
|
const cloud = (listing.data.items ?? []).find((item) => item.name === name);
|
||||||
const state = await this.loadState(scope);
|
const state = await this.loadState(scope);
|
||||||
const localFolder = state.uploaded[name]?.folder ?? state.delivered[name]?.folder ?? name;
|
const localFolder = preview?.folder ?? state.uploaded[name]?.folder ?? state.delivered[name]?.folder ?? name;
|
||||||
const localNow = await repo.read(localFolder);
|
const localNow = await repo.read(localFolder);
|
||||||
const localVersionNow = localNow === undefined ? 'none' : sha256Hex(localNow.files.map((file) => file.path + '\0' + file.sha256).sort().join('\n'));
|
const localVersionNow = localNow === undefined ? 'none' : sha256Hex(localNow.files.map((file) => file.path + '\0' + file.sha256).sort().join('\n'));
|
||||||
if (localVersionNow !== confirmed.localVersion)
|
if (localVersionNow !== confirmed.localVersion)
|
||||||
|
|
@ -1036,8 +1053,8 @@ export class SkillSync {
|
||||||
revision,
|
revision,
|
||||||
manifest_sha256: skill.manifest,
|
manifest_sha256: skill.manifest,
|
||||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256, size: file.size, data: file.data })),
|
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256, size: file.size, data: file.data })),
|
||||||
}, { delivery: false });
|
}, { delivery: false, folder: localFolder });
|
||||||
this.markUploaded(state, name, { folder: name, revision, manifest: skill.manifest,
|
this.markUploaded(state, name, { folder: localFolder, revision, manifest: skill.manifest,
|
||||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })), syncedAt: new Date().toISOString() });
|
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })), syncedAt: new Date().toISOString() });
|
||||||
delete state.removed[name];
|
delete state.removed[name];
|
||||||
await this.saveState(state);
|
await this.saveState(state);
|
||||||
|
|
|
||||||
|
|
@ -204,6 +204,8 @@ export class SkillSync implements SkillSyncGate {
|
||||||
/** Jobs accepted into the queue but not settled yet; makes busy() honest. */
|
/** Jobs accepted into the queue but not settled yet; makes busy() honest. */
|
||||||
private pendingWrites = 0
|
private pendingWrites = 0
|
||||||
private stateCache: { mtimeMs: number; scopeKey: string; state: SyncState } | undefined
|
private stateCache: { mtimeMs: number; scopeKey: string; state: SyncState } | undefined
|
||||||
|
/** Latest previews by conflict id: the exact snapshot the user confirmed. */
|
||||||
|
private previews = new Map<string, { name: string; scopeKey: string; folder: string }>()
|
||||||
private runRepository: SkillRepository | undefined
|
private runRepository: SkillRepository | undefined
|
||||||
private runScopeKey: string | undefined
|
private runScopeKey: string | undefined
|
||||||
private current: SkillSyncStats = {
|
private current: SkillSyncStats = {
|
||||||
|
|
@ -1031,15 +1033,22 @@ export class SkillSync implements SkillSyncGate {
|
||||||
|
|
||||||
private async resolveConflictsLocked(action: 'keep_local' | 'take_cloud', conflictIdsInput?: unknown): Promise<SyncResolveBatchResult> {
|
private async resolveConflictsLocked(action: 'keep_local' | 'take_cloud', conflictIdsInput?: unknown): Promise<SyncResolveBatchResult> {
|
||||||
if (this.running) throw new Error('sync_running')
|
if (this.running) throw new Error('sync_running')
|
||||||
|
if (!Array.isArray(conflictIdsInput) || conflictIdsInput.length === 0 || conflictIdsInput.some((value) => typeof value !== 'string' || value.trim() === '')) {
|
||||||
|
throw new Error('confirmation_required')
|
||||||
|
}
|
||||||
const run = this.captureRun()
|
const run = this.captureRun()
|
||||||
const scopeKey = this.scopeKey(run.scope)
|
const scopeKey = this.scopeKey(run.scope)
|
||||||
const details = await this.conflictDetails(run)
|
const details = await this.conflictDetails(run)
|
||||||
const requested = Array.isArray(conflictIdsInput) ? new Set(conflictIdsInput.filter((value): value is string => typeof value === 'string')) : undefined
|
const requested = new Set(conflictIdsInput as string[])
|
||||||
const selected = details.filter((detail) => (detail.scopeKey === scopeKey || detail.scopeKey === '') && (requested === undefined || requested.has(detail.conflictId)))
|
const currentIds = new Set(details.filter((detail) => detail.scopeKey === scopeKey || detail.scopeKey === '').map((detail) => detail.conflictId))
|
||||||
|
const selected = details.filter((detail) => (detail.scopeKey === scopeKey || detail.scopeKey === '') && requested.has(detail.conflictId))
|
||||||
const names = [...new Set(selected.map((detail) => detail.name))]
|
const names = [...new Set(selected.map((detail) => detail.name))]
|
||||||
const idByName = new Map(selected.map((detail) => [detail.name, detail.conflictId]))
|
const idByName = new Map(selected.map((detail) => [detail.name, detail.conflictId]))
|
||||||
const resolved: string[] = []
|
const resolved: string[] = []
|
||||||
const failed: { name: string; error: string }[] = []
|
const failed: { name: string; error: string }[] = []
|
||||||
|
for (const id of requested) {
|
||||||
|
if (!currentIds.has(id)) failed.push({ name: this.previews.get(id)?.name ?? 'unknown', error: 'stale_conflict' })
|
||||||
|
}
|
||||||
for (const name of names) {
|
for (const name of names) {
|
||||||
try {
|
try {
|
||||||
await this.resolveConflictLocked(name, action, run, idByName.get(name))
|
await this.resolveConflictLocked(name, action, run, idByName.get(name))
|
||||||
|
|
@ -1080,7 +1089,12 @@ export class SkillSync implements SkillSyncGate {
|
||||||
const localVersion = local === undefined ? 'none' : sha256Hex(local.files.map((file) => file.path + '\0' + file.sha256).sort().join('\n'))
|
const localVersion = local === undefined ? 'none' : sha256Hex(local.files.map((file) => file.path + '\0' + file.sha256).sort().join('\n'))
|
||||||
const cloudVersion = cloudItem === undefined ? 'none' : String(cloudItem.revision ?? '') + ':' + String(cloudItem.manifest_sha256 ?? '')
|
const cloudVersion = cloudItem === undefined ? 'none' : String(cloudItem.revision ?? '') + ':' + String(cloudItem.manifest_sha256 ?? '')
|
||||||
const scopeKey = conflict.scopeKey ?? this.scopeKey(active.scope)
|
const scopeKey = conflict.scopeKey ?? this.scopeKey(active.scope)
|
||||||
const conflictId = sha256Hex([scopeKey, conflict.name, conflict.reason, localVersion, cloudVersion].join('|'))
|
const conflictId = sha256Hex([scopeKey, conflict.name, localFolder, conflict.reason, localVersion, cloudVersion].join('|'))
|
||||||
|
this.previews.set(conflictId, { name: conflict.name, scopeKey, folder: localFolder })
|
||||||
|
if (this.previews.size > 1000) {
|
||||||
|
const oldest = this.previews.keys().next().value
|
||||||
|
if (oldest !== undefined) this.previews.delete(oldest)
|
||||||
|
}
|
||||||
out.push({
|
out.push({
|
||||||
conflictId,
|
conflictId,
|
||||||
scopeKey,
|
scopeKey,
|
||||||
|
|
@ -1126,13 +1140,14 @@ export class SkillSync implements SkillSyncGate {
|
||||||
if (conflict?.scopeKey !== undefined && conflict.scopeKey !== this.scopeKey(scope)) throw new Error('stale_conflict')
|
if (conflict?.scopeKey !== undefined && conflict.scopeKey !== this.scopeKey(scope)) throw new Error('stale_conflict')
|
||||||
if (expectedConflictId === undefined) throw new Error('confirmation_required')
|
if (expectedConflictId === undefined) throw new Error('confirmation_required')
|
||||||
const details = await this.conflictDetails(active)
|
const details = await this.conflictDetails(active)
|
||||||
const confirmed = details.find((detail) => detail.name === name)
|
const confirmed = details.find((detail) => detail.name === name && detail.conflictId === expectedConflictId)
|
||||||
if (confirmed === undefined || confirmed.conflictId !== expectedConflictId) throw new Error('stale_conflict')
|
if (confirmed === undefined) throw new Error('stale_conflict')
|
||||||
|
const preview = this.previews.get(expectedConflictId)
|
||||||
const listing = await client.listSkills()
|
const listing = await client.listSkills()
|
||||||
if (!listing.ok) throw new Error(`skill listing failed: ${describeError(listing.error)}`)
|
if (!listing.ok) throw new Error(`skill listing failed: ${describeError(listing.error)}`)
|
||||||
const cloud = (listing.data.items ?? []).find((item) => item.name === name)
|
const cloud = (listing.data.items ?? []).find((item) => item.name === name)
|
||||||
const state = await this.loadState(scope)
|
const state = await this.loadState(scope)
|
||||||
const localFolder = state.uploaded[name]?.folder ?? state.delivered[name]?.folder ?? name
|
const localFolder = preview?.folder ?? state.uploaded[name]?.folder ?? state.delivered[name]?.folder ?? name
|
||||||
const localNow = await repo.read(localFolder)
|
const localNow = await repo.read(localFolder)
|
||||||
const localVersionNow = localNow === undefined ? 'none' : sha256Hex(localNow.files.map((file) => file.path + '\0' + file.sha256).sort().join('\n'))
|
const localVersionNow = localNow === undefined ? 'none' : sha256Hex(localNow.files.map((file) => file.path + '\0' + file.sha256).sort().join('\n'))
|
||||||
if (localVersionNow !== confirmed.localVersion) throw new Error('stale_conflict')
|
if (localVersionNow !== confirmed.localVersion) throw new Error('stale_conflict')
|
||||||
|
|
@ -1172,8 +1187,8 @@ export class SkillSync implements SkillSyncGate {
|
||||||
revision,
|
revision,
|
||||||
manifest_sha256: skill.manifest,
|
manifest_sha256: skill.manifest,
|
||||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256, size: file.size, data: file.data })),
|
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256, size: file.size, data: file.data })),
|
||||||
}, { delivery: false })
|
}, { delivery: false, folder: localFolder })
|
||||||
this.markUploaded(state, name, { folder: name, revision, manifest: skill.manifest,
|
this.markUploaded(state, name, { folder: localFolder, revision, manifest: skill.manifest,
|
||||||
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })), syncedAt: new Date().toISOString() })
|
files: skill.files.map((file) => ({ path: file.path, sha256: file.sha256 })), syncedAt: new Date().toISOString() })
|
||||||
delete state.removed[name]
|
delete state.removed[name]
|
||||||
await this.saveState(state)
|
await this.saveState(state)
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,8 @@
|
||||||
// Conflict confirmation must bind the preview scope and cloud revision.
|
// Conflict confirmation must bind the preview scope and cloud revision.
|
||||||
import { mkdtempSync } from 'node:fs'
|
import { mkdirSync, mkdtempSync, readFileSync, writeFileSync, existsSync } from 'node:fs'
|
||||||
import { tmpdir } from 'node:os'
|
import { tmpdir } from 'node:os'
|
||||||
import { join } from 'node:path'
|
import { join } from 'node:path'
|
||||||
|
import { createHash } from 'node:crypto'
|
||||||
const home = mkdtempSync(join(tmpdir(), 'skill-conflict-r5-'))
|
const home = mkdtempSync(join(tmpdir(), 'skill-conflict-r5-'))
|
||||||
process.env.DSH_HOME = home
|
process.env.DSH_HOME = home
|
||||||
const results = []
|
const results = []
|
||||||
|
|
@ -27,6 +28,144 @@ scope = { endpoint: 'https://stub-b', accountToken: 'token-b', root: '/tmp/skill
|
||||||
let scopeStale = ''
|
let scopeStale = ''
|
||||||
try { await engine.resolveConflict('alpha', 'manual', preview2[0].conflictId) } catch (error) { scopeStale = String(error) }
|
try { await engine.resolveConflict('alpha', 'manual', preview2[0].conflictId) } catch (error) { scopeStale = String(error) }
|
||||||
check('scope change rejects confirmation from the old scope', scopeStale.includes('stale_conflict'), scopeStale)
|
check('scope change rejects confirmation from the old scope', scopeStale.includes('stale_conflict'), scopeStale)
|
||||||
|
|
||||||
|
const sha = (value) => createHash('sha256').update(value).digest('hex')
|
||||||
|
const linked = (files) => sha(Buffer.from('cloud-memory-skill-v1\n' + files.map((f) => f.path + '\0' + f.sha256).sort().join('\n') + '\n', 'utf8'))
|
||||||
|
const cloudFiles = (name, text) => {
|
||||||
|
const bytes = Buffer.from(text, 'utf8')
|
||||||
|
const file = { path: 'SKILL.md', sha256: sha(bytes), size: bytes.length, data: bytes.toString('base64') }
|
||||||
|
return { file, manifest: linked([{ path: file.path, sha256: file.sha256 }]) }
|
||||||
|
}
|
||||||
|
const writeLocal = (root, folder, text) => {
|
||||||
|
mkdirSync(join(root, folder), { recursive: true })
|
||||||
|
writeFileSync(join(root, folder, 'SKILL.md'), text)
|
||||||
|
writeFileSync(join(root, folder, '.manifest.json'), JSON.stringify({ name: folder, revision: 1, manifest_sha256: 'old', files: [{ path: 'SKILL.md', sha256: 'deadbeef' }] }))
|
||||||
|
}
|
||||||
|
const readState = (home) => { const p = join(home, 'dsh-brain-skills.json'); return existsSync(p) ? JSON.parse(readFileSync(p, 'utf8')) : {} }
|
||||||
|
|
||||||
|
const { SkillAdmin } = await import('./lib/skill-admin.js')
|
||||||
|
const { AdminSkillRepository } = await import('./lib/skills/repository.js')
|
||||||
|
|
||||||
|
async function makeFixture(kind, names) {
|
||||||
|
const home = mkdtempSync(join(tmpdir(), 'skill-accept-' + kind + '-'))
|
||||||
|
process.env.DSH_HOME = home
|
||||||
|
const root = join(home, 'skills'); mkdirSync(root, { recursive: true })
|
||||||
|
const holding = join(home, 'skills-disabled')
|
||||||
|
const items = []
|
||||||
|
const bundles = new Map()
|
||||||
|
for (const spec of names) {
|
||||||
|
writeLocal(root, spec.name, spec.local)
|
||||||
|
const { file, manifest } = cloudFiles(spec.name, spec.cloud)
|
||||||
|
items.push({ name: spec.name, enabled: true, revision: spec.revision, manifest_sha256: manifest, files: 1, bytes: Buffer.byteLength(spec.cloud) })
|
||||||
|
bundles.set(spec.name, { name: spec.name, revision: spec.revision, manifest_sha256: manifest, files: [file] })
|
||||||
|
}
|
||||||
|
const calls = { update: [], create: [], bundle: [] }
|
||||||
|
let listHook = null
|
||||||
|
const client = {
|
||||||
|
listSkills: async () => {
|
||||||
|
if (listHook !== null) { const out = listHook(items); if (out !== undefined) return out }
|
||||||
|
return { ok: true, data: { items } }
|
||||||
|
},
|
||||||
|
skillBundle: async (name) => {
|
||||||
|
calls.bundle.push(name)
|
||||||
|
const bundle = bundles.get(name)
|
||||||
|
return bundle === undefined ? { ok: false, error: { status: 404, code: 'not_found', message: 'missing' } } : { ok: true, data: bundle }
|
||||||
|
},
|
||||||
|
createSkill: async (_name, body) => { calls.create.push(body); return { ok: true, data: { skill: { revision: 1 } } } },
|
||||||
|
updateSkill: async (name, body) => {
|
||||||
|
calls.update.push({ name, expected: body.expected_revision, files: body.files })
|
||||||
|
return { ok: true, data: { skill: { revision: (body.expected_revision ?? 0) + 1 } } }
|
||||||
|
},
|
||||||
|
}
|
||||||
|
let sync
|
||||||
|
const admin = new SkillAdmin({ skillsRoot: () => root, holdingDir: () => holding, gate: () => sync, log: () => {} })
|
||||||
|
const repo = new AdminSkillRepository({ admin, skillsRoot: () => root, holdingDir: () => holding })
|
||||||
|
sync = new SkillSync({ client: () => client, settings: () => ({ enabled: true, skillsSyncEnabled: true }), repository: () => repo, log: () => {} })
|
||||||
|
const stats = await sync.syncOnce()
|
||||||
|
if (stats.conflicts.length !== names.length) console.log('FIXTURE WARN ' + kind + ' conflicts=' + JSON.stringify(stats.conflicts))
|
||||||
|
return { home, root, sync, client, calls, items, bundles, setListHook: (fn) => { listHook = fn } }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Case 1: valid confirmations execute keep_local and take_cloud for real.
|
||||||
|
{
|
||||||
|
const f = await makeFixture('valid', [
|
||||||
|
{ name: 'keep-one', local: '# keep-one local\n', cloud: '# keep-one cloud\n', revision: 3 },
|
||||||
|
{ name: 'take-one', local: '# take-one local\n', cloud: '# take-one cloud\n', revision: 7 },
|
||||||
|
])
|
||||||
|
const details = await f.sync.conflictDetails()
|
||||||
|
const keep = await f.sync.resolveConflict('keep-one', 'keep_local', details.find((d) => d.name === 'keep-one').conflictId)
|
||||||
|
check('valid keep_local applies with the previewed expected revision', keep.applied === true && f.calls.update.some((c) => c.name === 'keep-one' && c.expected === 3), JSON.stringify(keep))
|
||||||
|
const keepState = readState(f.home)
|
||||||
|
check('valid keep_local writes disk and upload receipt', readFileSync(join(f.root, 'keep-one', 'SKILL.md'), 'utf8').includes('keep-one local') && keepState.uploaded?.['keep-one']?.revision === 4, JSON.stringify(keepState.uploaded?.['keep-one']))
|
||||||
|
const take = await f.sync.resolveConflict('take-one', 'take_cloud', details.find((d) => d.name === 'take-one').conflictId)
|
||||||
|
check('valid take_cloud applies and backs up', take.applied === true && typeof take.backup === 'string' && existsSync(take.backup), JSON.stringify(take))
|
||||||
|
check('valid take_cloud writes cloud bytes and delivery receipt', readFileSync(join(f.root, 'take-one', 'SKILL.md'), 'utf8').includes('take-one cloud') && readState(f.home).delivered?.['take-one']?.manifest === f.bundles.get('take-one').manifest_sha256)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Case 2: remote changes after the confirmation re-check, before action listing.
|
||||||
|
{
|
||||||
|
const f = await makeFixture('remote-change', [{ name: 'race-one', local: '# race-one local\n', cloud: '# race-one cloud\n', revision: 1 }])
|
||||||
|
const details = await f.sync.conflictDetails()
|
||||||
|
let afterPreview = 0
|
||||||
|
f.setListHook((items) => {
|
||||||
|
afterPreview += 1
|
||||||
|
if (afterPreview === 1) return { ok: true, data: { items } }
|
||||||
|
return { ok: true, data: { items: items.map((item) => ({ ...item, revision: 2, manifest_sha256: 'changed-manifest' })) } }
|
||||||
|
})
|
||||||
|
let error = ''
|
||||||
|
try { await f.sync.resolveConflict('race-one', 'keep_local', details[0].conflictId) } catch (e) { error = e.message }
|
||||||
|
check('remote change after confirmation is rejected', error === 'stale_conflict', error)
|
||||||
|
check('remote change sends no write at the new revision', f.calls.update.length === 0 && existsSync(join(f.root, 'race-one', 'SKILL.md')))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Case 3: a complete bundle with different revision/manifest must be rejected.
|
||||||
|
{
|
||||||
|
const f = await makeFixture('bundle-change', [{ name: 'bundle-one', local: '# bundle-one local\n', cloud: '# bundle-one cloud\n', revision: 1 }])
|
||||||
|
const details = await f.sync.conflictDetails()
|
||||||
|
const good = f.bundles.get('bundle-one')
|
||||||
|
const other = cloudFiles('bundle-one', '# other cloud\n')
|
||||||
|
f.bundles.set('bundle-one', { name: 'bundle-one', revision: 2, manifest_sha256: other.manifest, files: [other.file] })
|
||||||
|
let error = ''
|
||||||
|
try { await f.sync.resolveConflict('bundle-one', 'take_cloud', details[0].conflictId) } catch (e) { error = e.message }
|
||||||
|
check('bundle with a different revision is rejected', error === 'stale_conflict', error)
|
||||||
|
check('rejected bundle leaves local file and receipt untouched', readFileSync(join(f.root, 'bundle-one', 'SKILL.md'), 'utf8').includes('bundle-one local') && readState(f.home).delivered?.['bundle-one'] === undefined)
|
||||||
|
f.bundles.set('bundle-one', good)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Case 4: local files change after the user preview.
|
||||||
|
{
|
||||||
|
const f = await makeFixture('local-change', [{ name: 'local-one', local: '# local-one before\n', cloud: '# local-one cloud\n', revision: 1 }])
|
||||||
|
const details = await f.sync.conflictDetails()
|
||||||
|
writeFileSync(join(f.root, 'local-one', 'SKILL.md'), '# local-one edited\n')
|
||||||
|
let error = ''
|
||||||
|
try { await f.sync.resolveConflict('local-one', 'keep_local', details[0].conflictId) } catch (e) { error = e.message }
|
||||||
|
check('local change after preview is rejected', error === 'stale_conflict', error)
|
||||||
|
check('local change is never uploaded', f.calls.update.length === 0 && readFileSync(join(f.root, 'local-one', 'SKILL.md'), 'utf8').includes('edited'))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Case 5: batch with one valid and one stale confirmation.
|
||||||
|
{
|
||||||
|
const f = await makeFixture('batch', [
|
||||||
|
{ name: 'batch-good', local: '# batch-good local\n', cloud: '# batch-good cloud\n', revision: 2 },
|
||||||
|
{ name: 'batch-stale', local: '# batch-stale local\n', cloud: '# batch-stale cloud\n', revision: 2 },
|
||||||
|
])
|
||||||
|
const details = await f.sync.conflictDetails()
|
||||||
|
const ids = details.map((d) => d.conflictId)
|
||||||
|
// Move only the stale skill's remote revision after the preview.
|
||||||
|
const staleItem = f.items.find((item) => item.name === 'batch-stale')
|
||||||
|
staleItem.revision = 9
|
||||||
|
staleItem.manifest_sha256 = 'new-manifest'
|
||||||
|
const batch = await f.sync.resolveConflicts('keep_local', ids)
|
||||||
|
const goodWrite = f.calls.update.some((c) => c.name === 'batch-good' && c.expected === 2)
|
||||||
|
const staleWrite = f.calls.update.some((c) => c.name === 'batch-stale')
|
||||||
|
check('batch applies the valid confirmation only', batch.resolved.includes('batch-good') && goodWrite && !staleWrite, JSON.stringify(batch))
|
||||||
|
check('batch reports the stale confirmation as expired', batch.failed.some((item) => item.name === 'batch-stale' && item.error === 'stale_conflict'), JSON.stringify(batch.failed))
|
||||||
|
check('batch stale skill stays untouched', readFileSync(join(f.root, 'batch-stale', 'SKILL.md'), 'utf8').includes('batch-stale local') && readState(f.home).uploaded?.['batch-stale'] === undefined)
|
||||||
|
let missing = ''
|
||||||
|
try { await f.sync.resolveConflicts('keep_local') } catch (error) { missing = error.message }
|
||||||
|
check('batch without explicit confirmations is refused', missing === 'confirmation_required', missing)
|
||||||
|
}
|
||||||
|
|
||||||
const failed = results.filter((result) => !result.ok)
|
const failed = results.filter((result) => !result.ok)
|
||||||
console.log('')
|
console.log('')
|
||||||
console.log(failed.length ? 'FAILED ' + failed.length + '/' + results.length + ': ' + failed.map((result) => result.name).join(', ') : 'ALL ' + results.length + ' CHECKS PASSED')
|
console.log(failed.length ? 'FAILED ' + failed.length + '/' + results.length + ': ' + failed.map((result) => result.name).join(', ') : 'ALL ' + results.length + ' CHECKS PASSED')
|
||||||
|
|
|
||||||
|
|
@ -154,7 +154,8 @@ const sync2 = new SkillSync({
|
||||||
})
|
})
|
||||||
const stats2 = await sync2.syncOnce()
|
const stats2 = await sync2.syncOnce()
|
||||||
check('second pass reports two drift conflicts', stats2.conflicts.length === 2, JSON.stringify(stats2.conflicts))
|
check('second pass reports two drift conflicts', stats2.conflicts.length === 2, JSON.stringify(stats2.conflicts))
|
||||||
const batchTake = await sync2.resolveConflicts('take_cloud')
|
const batchTakeIds = (await sync2.conflictDetails()).map((detail) => detail.conflictId)
|
||||||
|
const batchTake = await sync2.resolveConflicts('take_cloud', batchTakeIds)
|
||||||
check('batch take_cloud resolves every conflict',
|
check('batch take_cloud resolves every conflict',
|
||||||
batchTake.resolved.length === 2 && batchTake.failed.length === 0, JSON.stringify(batchTake))
|
batchTake.resolved.length === 2 && batchTake.failed.length === 0, JSON.stringify(batchTake))
|
||||||
const remaining2 = await sync2.conflictDetails()
|
const remaining2 = await sync2.conflictDetails()
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue