// Offline unit test for DidPeer.commitOps — the race-free CAR extraction. Build a REAL #commit frame
// (RepoManager.applyWrite -> commitFrame), decode it (firehose.decodeFrame), and assert commitOps
// yields normalized ops with the changed record decoded FROM THE FRAME'S OWN CAR. Run:
// node test/commitops.test.mjs
import { mkdtempSync, rmSync } from 'node:fs'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { RepoStore } from 'atproto-store/lib/repo-store.js'
import { RepoManager } from 'atproto-store/lib/repo-manager.js'
import { commitFrame, decodeFrame } from 'atproto-store/lib/firehose.js'
import { DidPeer } from '../lib/did-peer.js'
const assert = (c, m) => { if (!c) { console.error('FAIL:', m); process.exit(1) } console.log(' ok -', m) }
const DID = 'did:plc:commitops'
const PRIV = new Uint8Array(32).fill(9)
const iso = '2026-07-01T00:00:00.000Z'
const dir = mkdtempSync(join(tmpdir(), 'commitops-'))
const store = await new RepoStore(dir).ready()
let micros = 1_700_000_000_000_000n
const mgr = new RepoManager(store, { did: DID, privateKey: PRIV, clock: () => (micros += 1_000_000n) })
await mgr.init()
// CREATE -> the record must be recoverable from the frame CAR alone (no repo/store access)
const wc = await mgr.applyWrite({ action: 'create', collection: 'app.bsky.feed.post', rkey: '3zzz', record: { $type: 'app.bsky.feed.post', text: 'from-car', createdAt: iso } })
const dc = decodeFrame(await commitFrame(wc, { seq: 1, time: iso }))
assert(dc && dc.t === '#commit', 'create frame decodes as #commit')
const opsC = await DidPeer.commitOps(dc.body)
assert(opsC.length === 1, 'commitOps returns 1 op for a single create')
assert(opsC[0].action === 'create' && opsC[0].collection === 'app.bsky.feed.post' && opsC[0].rkey === '3zzz', 'op action/collection/rkey parsed from path')
assert(opsC[0].record && opsC[0].record.text === 'from-car', 'RECORD decoded from the frame CAR (race-free)')
// DELETE -> a delete op carries no record
const wd = await mgr.applyWrite({ action: 'delete', collection: 'app.bsky.feed.post', rkey: '3zzz' })
const dd = decodeFrame(await commitFrame(wd, { seq: 2, time: iso }))
const opsD = await DidPeer.commitOps(dd.body)
assert(opsD.length === 1 && opsD[0].action === 'delete' && opsD[0].rkey === '3zzz', 'commitOps yields a delete op')
assert(opsD[0].record === undefined, 'delete op carries no record')
console.log('\nCOMMITOPS OK: record extracted from the #commit CAR; create/delete normalized')
await store.close()
rmSync(dir, { recursive: true, force: true })