dsh-brain/verify-skill-sync-round2.mjs

69 lines
7.4 KiB
JavaScript

import http from 'node:http'
import { createHash } from 'node:crypto'
import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, existsSync, utimesSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const home = mkdtempSync(join(tmpdir(), 'skill-round2-'))
process.env.DSH_HOME = home
const results = []
const check = (name, ok, detail='') => { results.push({name,ok}); console.log((ok?'PASS ':'FAIL ')+name+(detail?' :: '+detail:'')) }
const sha=(b)=>createHash('sha256').update(b).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 storeFiles=(files)=>files.map(f=>{const b=Buffer.from(f.content??'', 'utf8'); return {path:f.path,sha256:sha(b),size:b.length,encoding:'utf8',data:b.toString('base64')}})
const center=new Map(); const requests=[]
const server=http.createServer((req,res)=>{
const url=new URL(req.url,'http://x'); const path=url.pathname.replace(/^\/api\/longmemory/,''); requests.push(req.method+' '+path)
const send=(status,body)=>{res.writeHead(status,{'content-type':'application/json'});res.end(JSON.stringify(body))}
const readBody=()=>new Promise(resolve=>{let raw='';req.on('data',c=>raw+=c);req.on('end',()=>resolve(raw?JSON.parse(raw):{}))})
void (async()=>{
if(req.method==='GET'&&path==='/skills'){const items=[...center.values()].map(s=>({name:s.name,description:s.description||'',execution_mode:'prompt-only',enabled:true,revision:s.revision,manifest_sha256:linked(s.files),files:s.files.length,script_changed:false,created_at:s.created_at||1,updated_at:s.updated_at||1}));return send(200,{items,total:items.length,trash_total:0,limits:{files:100}})}
const bm=/^\/skills\/([a-z0-9-]+)\/bundle$/.exec(path); if(req.method==='GET'&&bm){const s=center.get(bm[1]); if(!s)return send(404,{error:'skill_not_found',message:'missing'}); return send(200,{name:s.name,revision:s.revision,manifest_sha256:linked(s.files),script_changed:false,files:s.files.map(f=>({path:f.path,sha256:f.sha256,size:f.size,encoding:'utf8',data:f.data}))})}
if(req.method==='POST'&&path==='/skills'){const body=await readBody(); if(center.has(body.name))return send(409,{error:'skill_exists',message:'exists'}); const s={name:body.name,description:body.description||'',revision:1,files:storeFiles(body.files||[]),created_at:Date.now(),updated_at:Date.now()}; center.set(s.name,s); return send(201,{skill:{name:s.name,description:s.description,execution_mode:'prompt-only',enabled:true,revision:1,manifest_sha256:linked(s.files),files:s.files.length},revision:1,manifest_sha256:linked(s.files)})}
const sm=/^\/skills\/([a-z0-9-]+)$/.exec(path); if(req.method==='PATCH'&&sm){const body=await readBody(); const s=center.get(sm[1]); if(!s)return send(404,{error:'skill_not_found',message:'missing'}); if(body.expected_revision!==s.revision)return send(409,{error:'revision_conflict',message:'conflict'}); if(body.files)s.files=storeFiles(body.files); s.revision++; s.updated_at=Date.now(); return send(200,{skill:{name:s.name,description:s.description,revision:s.revision,manifest_sha256:linked(s.files),files:s.files.length},revision:s.revision,manifest_sha256:linked(s.files)})}
send(404,{error:'unknown',path})
})()
})
await new Promise(r=>server.listen(0,'127.0.0.1',r))
const base='http://127.0.0.1:'+server.address().port+'/api/longmemory'
const {CloudClient}=await import('./lib/api.js'); const {SkillSync}=await import('./lib/skill-sync.js'); const {SkillAdmin}=await import('./lib/skill-admin.js'); const {AdminSkillRepository}=await import('./lib/skills/repository.js')
const root=join(home,'skills'); mkdirSync(root,{recursive:true})
let scope={endpoint:base,accountToken:'token-a',root}
const client=new CloudClient({baseUrl:()=>base,['tok'+'en']:()=> 'x',timeoutMs:()=>3000})
const admin=new SkillAdmin({skillsRoot:()=>root,holdingDir:()=>join(home,'skills-disabled'),gate:()=>engine,log:()=>{}})
const repo=new AdminSkillRepository({admin,skillsRoot:()=>root,holdingDir:()=>join(home,'skills-disabled')})
const engine=new SkillSync({client:()=>client,settings:()=>({enabled:true,skillsSyncEnabled:true}),repository:()=>repo,log:()=>{},scope:()=>scope})
function writeSkill(name,content,mtime=Date.now()){mkdirSync(join(root,name),{recursive:true});writeFileSync(join(root,name,'SKILL.md'),content);utimesSync(join(root,name,'SKILL.md'),new Date(mtime),new Date(mtime))}
writeSkill('remote-update','# local v1',1)
mkdirSync(join(root,'remote-update','references'),{recursive:true})
writeFileSync(join(root,'remote-update','references','old.md'),'old synced file')
let stats=await engine.syncOnce()
check('local skill uploaded', stats.uploaded.includes('remote-update') && center.get('remote-update')?.revision===1, JSON.stringify(stats))
const cloud=center.get('remote-update'); cloud.revision=2; cloud.files=storeFiles([{path:'SKILL.md',content:'# cloud v2'}]); cloud.updated_at=Date.now()+100000
stats=await engine.syncOnce()
check('uploaded skill takes remote update', readFileSync(join(root,'remote-update','SKILL.md'),'utf8').includes('cloud v2'), JSON.stringify(stats))
check('remote update writes delivery receipt', existsSync(join(root,'remote-update','.manifest.json')))
check('uploaded skill removes files deleted on the cloud', !existsSync(join(root,'remote-update','references','old.md')))
writeSkill('delete-me','# delete me',1)
await engine.syncOnce(); check('delete fixture uploaded',center.has('delete-me'))
rmSync(join(root,'delete-me'),{recursive:true,force:true})
stats=await engine.syncOnce(); check('deleted local stays gone first pass',!existsSync(join(root,'delete-me')))
await engine.syncOnce(); check('deleted local stays gone on a second pass',!existsSync(join(root,'delete-me')))
const cloudDel=center.get('delete-me'); cloudDel.revision=2; cloudDel.files=storeFiles([{path:'SKILL.md',content:'# changed cloud'}])
stats=await engine.syncOnce(); check('cloud update does not resurrect deleted local',!existsSync(join(root,'delete-me')),JSON.stringify(stats))
writeSkill('account-a','# account a',1)
requests.length=0; await engine.syncOnce(); check('account A uploads its local skill',center.has('account-a') && requests.some(r=>r==='POST /skills'), requests.join('|'))
center.delete('account-a'); requests.length=0; scope={endpoint:'https://other.test/api/longmemory',accountToken:'token-b',root}
stats=await engine.syncOnce()
check('account B never uploads account A content',!requests.includes('POST /skills') && !stats.uploaded.includes('account-a'), JSON.stringify({requests,stats}))
writeSkill('different-folder','---\nname: logical-name\n---\n# logical',1)
await engine.syncOnce()
check('different local folder uploads logical cloud name', center.has('logical-name'))
const logicalCloud=center.get('logical-name'); logicalCloud.revision=2; logicalCloud.files=storeFiles([{path:'SKILL.md',content:'---\nname: logical-name\n---\n# logical cloud'}]); logicalCloud.updated_at=Date.now()+100000
await engine.syncOnce()
check('different local folder does not create a second copy', existsSync(join(root,'different-folder','SKILL.md')) && !existsSync(join(root,'logical-name')))
const state=JSON.parse(readFileSync(join(home,'dsh-brain-skills.json'),'utf8'))
check('scope A record remains isolated in sidecar',Object.keys(state.scopes||{}).length>=2, JSON.stringify(Object.keys(state.scopes||{})))
console.log('\n'+(results.every(r=>r.ok)?'ALL '+results.length+' CHECKS PASSED':results.filter(r=>!r.ok).length+' FAILED'))
server.close(); process.exit(results.every(r=>r.ok)?0:1)