173 lines
12 KiB
JavaScript
173 lines
12 KiB
JavaScript
// Conflict confirmation must bind the preview scope and cloud revision.
|
|
import { mkdirSync, mkdtempSync, readFileSync, writeFileSync, existsSync } from 'node:fs'
|
|
import { tmpdir } from 'node:os'
|
|
import { join } from 'node:path'
|
|
import { createHash } from 'node:crypto'
|
|
const home = mkdtempSync(join(tmpdir(), 'skill-conflict-r5-'))
|
|
process.env.DSH_HOME = home
|
|
const results = []
|
|
function check(name, ok, detail = '') { results.push({ name, ok }); console.log((ok ? 'PASS ' : 'FAIL ') + name + (detail ? ' :: ' + detail : '')) }
|
|
const { SkillSync } = await import('./lib/skill-sync.js')
|
|
let scope = { endpoint: 'https://stub-a', accountToken: 'token-a', root: '/tmp/skills' }
|
|
let revision = 1; let manifest = 'manifest-a'
|
|
const repo = { read: async (name) => ({ name, area: 'root', files: [{ path: 'SKILL.md', sha256: 'abc', size: 3, data: 'eA==' }], delivery: undefined }) }
|
|
const client = { listSkills: async () => ({ ok: true, data: { items: [{ name: 'alpha', revision, manifest_sha256: manifest }] } }) }
|
|
const engine = new SkillSync({ client: () => client, settings: () => ({ enabled: true, skillsSyncEnabled: true }), repository: () => repo, log: () => {}, scope: () => scope })
|
|
engine.current.conflicts = [{ name: 'alpha', reason: 'diverged', scopeKey: undefined }]
|
|
const preview = await engine.conflictDetails()
|
|
check('conflict preview exposes a stable conflict id and versions', typeof preview[0]?.conflictId === 'string' && preview[0].localVersion.length > 0 && preview[0].cloudVersion.includes('1'))
|
|
const manual = await engine.resolveConflict('alpha', 'manual', preview[0].conflictId)
|
|
check('valid preview confirmation reaches manual action', manual.applied === false && manual.action === 'manual')
|
|
revision = 2; manifest = 'manifest-b'
|
|
let stale = ''
|
|
try { await engine.resolveConflict('alpha', 'manual', preview[0].conflictId) } catch (error) { stale = String(error) }
|
|
check('changed cloud revision rejects stale confirmation', stale.includes('stale_conflict'), stale)
|
|
const preview2 = await engine.conflictDetails()
|
|
check('a refreshed preview gets a different conflict id', preview2[0].conflictId !== preview[0].conflictId)
|
|
scope = { endpoint: 'https://stub-b', accountToken: 'token-b', root: '/tmp/skills' }
|
|
let scopeStale = ''
|
|
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)
|
|
|
|
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)
|
|
console.log('')
|
|
console.log(failed.length ? 'FAILED ' + failed.length + '/' + results.length + ': ' + failed.map((result) => result.name).join(', ') : 'ALL ' + results.length + ' CHECKS PASSED')
|
|
process.exit(failed.length ? 1 : 0)
|