import test from "node:test"; import assert from "node:assert/strict"; import { mkdtemp, readFile, rm, writeFile, mkdir } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { LOG_FORMAT, isHitKey, logFile, markHit, readLog, tally } from "./log.mjs"; const S = "FAKE-TEST-VALUE"; test("a missing log is empty; marks round-trip; unread clears", async () => { const root = await mkdtemp(path.join(os.tmpdir(), "umtool-rlog-")); try { assert.deepEqual(await readLog(root, S), { marks: {} }); await markHit(root, S, "chan/vid1", "read", { query: "fired", scope: { source: "local:/x" }, now: new Date("2026-10-14T00:00:00Z") }); await markHit(root, S, "chan/vid2", "skipped"); const r = await readLog(root, S); assert.deepEqual(Object.keys(r.marks), ["chan/vid1", "chan/vid2"]); assert.equal(r.marks["chan/vid1"].state, "read"); assert.equal(r.marks["chan/vid1"].at, "2026-10-14T00:00:00.000Z"); assert.equal(r.query, "fired"); assert.deepEqual(r.scope, { source: "local:/x" }); await markHit(root, S, "chan/vid2", "unread"); assert.deepEqual(Object.keys((await readLog(root, S)).marks), ["chan/vid1"]); const doc = JSON.parse(await readFile(logFile(root, S), "utf8")); assert.equal(doc.format, LOG_FORMAT); assert.equal(doc.session, S); assert.equal(doc.query, "fired", "the query survives a later mark without one"); assert.ok(logFile(root, S).includes(`${path.sep}.umtool${path.sep}research${path.sep}sessions${path.sep}`)); } finally { await rm(root, { recursive: true, force: true }); } }); test("writes are serialised: a burst of marks all land", async () => { const root = await mkdtemp(path.join(os.tmpdir(), "umtool-rlog-")); try { await Promise.all(Array.from({ length: 20 }, (_, i) => markHit(root, S, `c/v${i}`, i % 2 ? "read" : "skipped"))); const r = await readLog(root, S); assert.equal(Object.keys(r.marks).length, 20); assert.deepEqual(tally(r.marks, [...Object.keys(r.marks), "c/other"]), { read: 10, skipped: 10, unread: 1, total: 21 }); } finally { await rm(root, { recursive: true, force: true }); } }); test("an unreadable log is never overwritten; bad input is refused", async () => { const root = await mkdtemp(path.join(os.tmpdir(), "umtool-rlog-")); try { await mkdir(path.dirname(logFile(root, S)), { recursive: true }); await writeFile(logFile(root, S), "{not json"); assert.match((await readLog(root, S)).error, /not JSON/); await assert.rejects(markHit(root, S, "c/v", "read"), (e) => e.status === 409); assert.equal(await readFile(logFile(root, S), "utf8"), "{not json"); await assert.rejects(markHit(root, "../../x", "c/v", "read"), (e) => e.status === 400); await assert.rejects(markHit(root, S, "../v", "read"), (e) => e.status === 400); await assert.rejects(markHit(root, S, "c/v", "done"), (e) => e.status === 400); assert.ok(isHitKey("the-quartering/vxe1ae")); assert.ok(!isHitKey("c/..")); assert.ok(!isHitKey("c/v/w")); } finally { await rm(root, { recursive: true, force: true }); } });