// scope-rooms.mjs — SAFE, read-only room enumeration + on-disk map.
// Boots keet-daemon against a (backup) storage, lists every room with its
// title + roomId, computes sha256(roomId) (the state-bases-v3 dir name), and
// reports whether a StateBase corestore exists on disk + its size. Does NOT
// open any StateBase (no quarantine risk). Identifies which room is which.
//
// bare tools/scope-rooms.mjs --storage <keet-cli-root>
import { startDaemon } from '../index.js'
import crypto from 'hypercore-crypto'
import fs from 'bare-fs'
import path from 'bare-path'
const args = Bare.argv.slice(2)
const i = args.indexOf('--storage')
const storage = i >= 0 ? args[i + 1] : null
if (!storage) { console.log('usage: bare tools/scope-rooms.mjs --storage <keet-cli-root>'); Bare.exit(1) }
setTimeout(() => { console.error('TIMEOUT (90s)'); Bare.exit(2) }, 90000)
const d = await startDaemon({ storage, socketPath: '/tmp/keet-scope.sock', pidFile: '/tmp/keet-scope.pid', debug: false })
await d.core.backendAPI.ready()
const rooms = await d.router._rooms()
const sbRoot = path.join(d.router._storage, 'state-bases-v3')
const onDisk = new Set(fs.existsSync(sbRoot) ? fs.readdirSync(sbRoot) : [])
console.log('storage :', d.router._storage)
console.log('rooms (keet) :', rooms.length)
console.log('sb dirs disk :', [...onDisk].map(x => x.slice(0, 12)).join(', '))
console.log('================ room → on-disk state-base ================')
const matched = new Set()
for (const r of rooms) {
const hex = crypto.hash(Buffer.from(String(r.roomId), 'utf-8')).toString('hex')
const has = onDisk.has(hex)
if (has) matched.add(hex)
let size = ''
if (has) {
try {
let bytes = 0
const walk = (p) => { for (const e of fs.readdirSync(p)) { const fp = path.join(p, e); const st = fs.statSync(fp); if (st.isDirectory()) walk(fp); else bytes += st.size } }
walk(path.join(sbRoot, hex)); size = (bytes / 1048576).toFixed(1) + 'M'
} catch {}
}
console.log(' %s type=%d sb=%s %s "%s"', hex.slice(0, 12), r.roomType, has ? 'YES' : 'no ', size.padStart(7), r.title)
}
const orphan = [...onDisk].filter(h => !matched.has(h))
if (orphan.length) console.log('---- on-disk state-bases with NO matching keet room (orphans) ----\n ' + orphan.map(x => x.slice(0, 12)).join('\n '))
Bare.exit(0)