// Verifies one sync pass keeps the scope/client captured at its start. import http from 'node:http' import { mkdtempSync, mkdirSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' const root = mkdtempSync(join(tmpdir(), 'skill-scope-r3-')) process.env.DSH_HOME = join(root, 'home') const results = [] function check(name, ok, detail = '') { results.push({ name, ok }); console.log((ok ? 'PASS ' : 'FAIL ') + name + (detail ? ' :: ' + detail : '')) } const requests = { a: 0, b: 0 } function server(label) { return http.createServer((req, res) => { requests[label] += 1; const send = () => { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify({ items: [], total: 0, trash_total: 0, limits: { files: 100 } })) }; if (label === 'a') setTimeout(send, 100); else send() }) } const a = server('a'); const b = server('b') await new Promise((resolve) => a.listen(0, '127.0.0.1', resolve)); await new Promise((resolve) => b.listen(0, '127.0.0.1', resolve)) const baseA = 'http://127.0.0.1:' + a.address().port + '/api/longmemory'; const baseB = 'http://127.0.0.1:' + b.address().port + '/api/longmemory' const { CloudClient } = await import('./lib/api.js'); const { SkillSync } = await import('./lib/skill-sync.js'); const { AdminSkillRepository } = await import('./lib/skills/repository.js') const skillsRoot = join(root, 'skills'); mkdirSync(skillsRoot, { recursive: true }) const live = new CloudClient({ baseUrl: () => baseB, token: () => 'token-b', timeoutMs: () => 1000 }) let current = { endpoint: baseA, accountToken: 'token-a', root: skillsRoot } const repo = new AdminSkillRepository({ admin: { locate: async () => undefined, setEnabled: async () => {} }, skillsRoot: () => skillsRoot, holdingDir: () => join(root, 'holding') }) const engine = new SkillSync({ client: () => live, clientForScope: (scope) => new CloudClient({ baseUrl: () => scope.endpoint, token: () => scope.accountToken, timeoutMs: () => 1000 }), settings: () => ({ enabled: true, skillsSyncEnabled: true }), repository: () => repo, repositoryForScope: () => repo, log: () => {}, scope: () => current }) const pending = engine.syncOnce() await new Promise((resolve) => setTimeout(resolve, 20)) current = { endpoint: baseB, accountToken: 'token-b', root: skillsRoot } const stats = await pending check('sync uses the connection captured at pass start', requests.a === 1 && requests.b === 0, JSON.stringify(requests)) check('scope switch does not turn the pass into an error', stats.running === false && stats.lastError === undefined, JSON.stringify(stats)) a.close(); b.close() 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)