diff --git a/pm-stack/aggregator/src/decisions.ts b/pm-stack/aggregator/src/decisions.ts index b26f135630..ae1cf0083c 100644 --- a/pm-stack/aggregator/src/decisions.ts +++ b/pm-stack/aggregator/src/decisions.ts @@ -256,23 +256,66 @@ export function validateDecisionSet( interface DecisionsFileShape { version: 1; sets: DecisionSet[]; + /** Server-side drafts, keyed by setId. A separate top-level map so + * drafts can never be mistaken for resolutions; store files written + * before the drafts layer simply lack the key. */ + drafts?: Record; } -async function readDecisionSets(file: string): Promise { +interface DecisionsData { + sets: DecisionSet[]; + drafts: Record; +} + +function sanitizeSetDrafts(raw: unknown): DecisionSetDrafts | null { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; + const r = raw as Record; + const questions: Record = {}; + if (r.questions && typeof r.questions === "object" && !Array.isArray(r.questions)) { + for (const [qid, qRaw] of Object.entries(r.questions as Record)) { + const entry = sanitizeDraftEntry(qRaw); + if (entry) questions[qid] = entry; + } + } + return { + questions, + bulk: Array.isArray(r.bulk) ? r.bulk.filter((x): x is string => typeof x === "string") : [], + bulkLean: typeof r.bulkLean === "string" ? r.bulkLean : "", + bulkNote: typeof r.bulkNote === "string" ? r.bulkNote : "", + updatedAt: typeof r.updatedAt === "string" ? r.updatedAt : "", + }; +} + +async function readDecisionsData(file: string): Promise { try { const parsed: unknown = JSON.parse(await readFile(file, "utf8")); if (parsed && typeof parsed === "object" && Array.isArray((parsed as DecisionsFileShape).sets)) { - return (parsed as DecisionsFileShape).sets.filter( - (s): s is DecisionSet => - !!s && typeof s === "object" && typeof s.setId === "string" && typeof s.token === "string" && Array.isArray(s.items), - ); + const shape = parsed as DecisionsFileShape; + const drafts: Record = {}; + if (shape.drafts && typeof shape.drafts === "object") { + for (const [setId, raw] of Object.entries(shape.drafts)) { + const d = sanitizeSetDrafts(raw); + if (d) drafts[setId] = d; + } + } + return { + sets: shape.sets.filter( + (s): s is DecisionSet => + !!s && typeof s === "object" && typeof s.setId === "string" && typeof s.token === "string" && Array.isArray(s.items), + ), + drafts, + }; } - return []; + return { sets: [], drafts: {} }; } catch { - return []; // absent/corrupt store reads as empty; a raise rewrites it + return { sets: [], drafts: {} }; // absent/corrupt store reads as empty; a raise rewrites it } } +async function readDecisionSets(file: string): Promise { + return (await readDecisionsData(file)).sets; +} + let decisionsWriteSeq = 0; const decisionsChains = new Map>(); @@ -286,14 +329,41 @@ function serializeDecisions(file: string, fn: () => Promise): Promise { return run; } -async function writeDecisionSets(file: string, sets: DecisionSet[]): Promise { +async function writeDecisionsData(file: string, data: DecisionsData): Promise { await mkdir(dirname(file), { recursive: true }); const tmp = `${file}.tmp-${process.pid}-${++decisionsWriteSeq}`; - const data: DecisionsFileShape = { version: 1, sets }; - await writeFile(tmp, JSON.stringify(data, null, 2)); + const shape: DecisionsFileShape = { version: 1, sets: data.sets, drafts: data.drafts }; + await writeFile(tmp, JSON.stringify(shape, null, 2)); await rename(tmp, file); } +/** Delete stored drafts for questions that now carry a resolution. + * Returns how many were removed. */ +function pruneResolvedDrafts(set: DecisionSet, drafts: DecisionSetDrafts | undefined): number { + if (!drafts) return 0; + let removed = 0; + for (const item of set.items) { + for (const q of item.questions) { + if (q.resolution && drafts.questions[q.qid]) { + delete drafts.questions[q.qid]; + removed++; + } + } + } + return removed; +} + +/** The sets write shared by every existing writer (raise / record / + * defer / request-info): it preserves all sets' server drafts and + * prunes the drafts of any question the write just resolved, so a + * draft can never outlive its question on the server layer. Callers + * are inside serializeDecisions, so the re-read here is consistent. */ +async function writeDecisionSets(file: string, sets: DecisionSet[]): Promise { + const { drafts } = await readDecisionsData(file); + for (const set of sets) pruneResolvedDrafts(set, drafts[set.setId]); + await writeDecisionsData(file, { sets, drafts }); +} + /** Raise a decision set. Idempotent: an existing setId keeps its token * and its original contents (a re-post is a duplicate, not an edit). */ export async function raiseDecisionSet( @@ -336,6 +406,111 @@ export async function getDecisionSet(file: string, setId: string): Promise s.setId === setId) ?? null; } + +// --- Decision drafts (server layer, #8766 both-layers upgrade) -------- +// +// Drafts are Drew's in-progress form state, mirrored server-side so a +// draft survives the device or browser it was typed on. They live in +// the same store file as the sets, under a separate top-level `drafts` +// map, and are NOT resolutions: nothing here ever reaches +// listDecisionResolutions or the fleet feed. A question's draft is +// deleted the moment the question resolves (any kind), and an upsert +// for an already-resolved or unknown question is a no-op, so a stale +// client can never resurrect a settled question. Per question, the +// newest updatedAt wins — a slow tab's late push cannot clobber a +// newer draft of the same question. + +export interface DecisionQuestionDraft { + /** Selected option id (the page radio's value). */ + opt?: string; + /** The question's text box: the answer text, or the comment that + * rides with a defer — the page uses one field for both. */ + ft?: string; + /** Defer pick: a DeferLean value when the defer select is set. */ + lean?: string; + /** Request-info note text. */ + note?: string; + /** Client-stamped last-edit time (ISO); newest wins per question. */ + updatedAt: string; +} + +export interface DecisionSetDrafts { + questions: Record; + /** Ledger ids checked for a bulk action. */ + bulk: string[]; + bulkLean: string; + bulkNote: string; + /** Last write to any part of this set's drafts (ISO). */ + updatedAt: string; +} + +/** Wire shape for a draft upsert: per-question entries; `null` deletes. */ +export interface DecisionDraftUpsert { + questions: Record; + bulk?: string[]; + bulkLean?: string; + bulkNote?: string; +} + +const DRAFT_TEXT_MAX = 16384; + +function sanitizeDraftEntry(raw: unknown): DecisionQuestionDraft | null { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; + const r = raw as Record; + const entry: DecisionQuestionDraft = { updatedAt: "" }; + if (typeof r.opt === "string" && r.opt) entry.opt = r.opt.slice(0, 200); + if (typeof r.ft === "string" && r.ft) entry.ft = r.ft.slice(0, DRAFT_TEXT_MAX); + if (isDeferLean(r.lean)) entry.lean = r.lean; + if (typeof r.note === "string" && r.note) entry.note = r.note.slice(0, DRAFT_TEXT_MAX); + const at = typeof r.updatedAt === "string" ? Date.parse(r.updatedAt) : NaN; + entry.updatedAt = Number.isFinite(at) ? new Date(at).toISOString() : ""; + if (!entry.opt && !entry.ft && !entry.lean && !entry.note) return null; + return entry; +} + +/** Validate the POST /api/decisions//drafts payload body. */ +export function validateDecisionDraftUpsert( + value: unknown, +): { ok: true; value: DecisionDraftUpsert } | { ok: false; error: string } { + if (!value || typeof value !== "object" || Array.isArray(value)) { + return { ok: false, error: "drafts must be an object" }; + } + const b = value as Record; + if (!b.questions || typeof b.questions !== "object" || Array.isArray(b.questions)) { + return { ok: false, error: "drafts.questions must be an object keyed by qid" }; + } + const qEntries = Object.entries(b.questions as Record); + if (qEntries.length > 64) return { ok: false, error: "drafts.questions has too many entries (max 64)" }; + const questions: Record = {}; + for (const [qid, raw] of qEntries) { + if (raw === null) { + questions[qid] = null; + continue; + } + const entry = sanitizeDraftEntry(raw); + if (!entry) return { ok: false, error: `draft for ${qid} has no usable fields` }; + questions[qid] = entry; + } + const out: DecisionDraftUpsert = { questions }; + if (b.bulk !== undefined) { + if (!Array.isArray(b.bulk) || b.bulk.length > 64 || (b.bulk as unknown[]).some((x) => typeof x !== "string")) { + return { ok: false, error: "drafts.bulk must be an array of up to 64 strings" }; + } + out.bulk = [...(b.bulk as string[])]; + } + if (b.bulkLean !== undefined) { + if (typeof b.bulkLean !== "string" || (b.bulkLean !== "" && !isDeferLean(b.bulkLean))) { + return { ok: false, error: "drafts.bulkLean must be '' or a defer lean" }; + } + out.bulkLean = b.bulkLean; + } + if (b.bulkNote !== undefined) { + if (typeof b.bulkNote !== "string") return { ok: false, error: "drafts.bulkNote must be a string" }; + out.bulkNote = b.bulkNote.slice(0, DRAFT_TEXT_MAX); + } + return { ok: true, value: out }; +} + export interface DecisionSubmission { ledgerId: string; qid: string; @@ -648,6 +823,116 @@ export async function listDecisionResolutions(file: string): Promise { + const data = await readDecisionsData(file); + const set = data.sets.find((s) => s.setId === setId); + if (!set) return null; + const stored = data.drafts[setId]; + if (!stored) return emptySetDrafts(); + const out = emptySetDrafts(); + out.bulk = stored.bulk; + out.bulkLean = stored.bulkLean; + out.bulkNote = stored.bulkNote; + out.updatedAt = stored.updatedAt; + for (const item of set.items) { + for (const q of item.questions) { + if (q.resolution) continue; + const d = stored.questions[q.qid]; + if (d) out.questions[q.qid] = d; + } + } + return out; +} + +/** + * Upsert a set's server drafts from the page's debounced push. Each + * entry is judged independently: unknown qids are skipped, drafts for + * already-resolved questions are dropped (never resurrected), a null + * entry deletes, and a stale entry (older updatedAt than the stored + * draft) loses. The file is rewritten only when something changed, + * so a no-op push leaves the store byte-identical. + */ +export async function upsertDecisionDrafts( + file: string, + setId: string, + upsert: DecisionDraftUpsert, +): Promise<{ drafts: DecisionSetDrafts; applied: string[]; skipped: Array<{ qid: string; reason: string }> } | null> { + return serializeDecisions(file, async () => { + const data = await readDecisionsData(file); + const set = data.sets.find((s) => s.setId === setId); + if (!set) return null; + const stored: DecisionSetDrafts = data.drafts[setId] ?? emptySetDrafts(); + const applied: string[] = []; + const skipped: Array<{ qid: string; reason: string }> = []; + let changed = false; + for (const [qid, entry] of Object.entries(upsert.questions)) { + const cut = qid.lastIndexOf("#"); + const ledgerId = cut > 0 ? qid.slice(0, cut) : ""; + const q = ledgerId ? findQuestion(set, ledgerId, qid) : null; + if (!q) { + skipped.push({ qid, reason: "unknown-question" }); + continue; + } + if (q.resolution) { + if (stored.questions[qid]) { + delete stored.questions[qid]; + changed = true; + } + skipped.push({ qid, reason: "already-resolved" }); + continue; + } + if (entry === null) { + if (stored.questions[qid]) { + delete stored.questions[qid]; + changed = true; + applied.push(qid); + } + continue; + } + const existing = stored.questions[qid]; + if (existing && existing.updatedAt && entry.updatedAt && entry.updatedAt < existing.updatedAt) { + skipped.push({ qid, reason: "stale" }); + continue; + } + const stamped: DecisionQuestionDraft = { + ...entry, + updatedAt: entry.updatedAt || new Date().toISOString(), + }; + if (JSON.stringify(existing) !== JSON.stringify(stamped)) { + stored.questions[qid] = stamped; + changed = true; + } + applied.push(qid); + } + if (upsert.bulk !== undefined && JSON.stringify(upsert.bulk) !== JSON.stringify(stored.bulk)) { + stored.bulk = upsert.bulk; + changed = true; + } + if (upsert.bulkLean !== undefined && upsert.bulkLean !== stored.bulkLean) { + stored.bulkLean = upsert.bulkLean; + changed = true; + } + if (upsert.bulkNote !== undefined && upsert.bulkNote !== stored.bulkNote) { + stored.bulkNote = upsert.bulkNote; + changed = true; + } + if (changed) { + stored.updatedAt = new Date().toISOString(); + data.drafts[setId] = stored; + await writeDecisionsData(file, data); + } + return { drafts: stored, applied, skipped }; + }); +} + // --- Decisions-page draft persistence (#8777) --------------------------- // // The 2026-11-11 "front end crashed" incident: pm-aggregator was killed @@ -660,6 +945,17 @@ export async function listDecisionResolutions(file: string): Promise (idbData.updatedAt || 0))) { + winner = lsData; + var now = Date.now(); + Object.keys(winner.q).forEach(function (qid) { + if (!winner.q[qid].updatedAt) winner.q[qid].updatedAt = now; + }); + if (!winner.updatedAt) winner.updatedAt = now; + } + draftState = winner; + draftLocalPersist(); + try { localStorage.removeItem(DRAFT_KEY); } catch (e) {} + resolve(winner); + }; + rq.onerror = function () { resolve(lsData); }; + } catch (e) { resolve(lsData); } + }); +} +function draftCollect() { + var seen = {}; + document.querySelectorAll('.q').forEach(function (block) { + var entry = {}; + var picked = block.querySelector('input[type=radio]:checked'); + if (picked) entry.opt = picked.value; + var ft = block.querySelector('textarea.ft').value; + if (ft) entry.ft = ft; + var lean = block.querySelector('select.defer').value; + if (lean) entry.lean = lean; + var note = block.querySelector('textarea.infonote').value; + if (note) entry.note = note; + if (Object.keys(entry).length) { + var qid = block.getAttribute('data-qid'); + seen[qid] = true; + var prev = draftState.q[qid]; + if (!prev || prev.opt !== entry.opt || prev.ft !== entry.ft || prev.lean !== entry.lean || prev.note !== entry.note) { + entry.updatedAt = Date.now(); + } else { + entry.updatedAt = prev.updatedAt || Date.now(); + } + draftState.q[qid] = entry; + } + }); + // A question whose block left the DOM was recorded; a question whose + // fields were cleared is intentionally blank. Either way its draft + // is gone locally and tombstoned for the next server push. + Object.keys(draftState.q).forEach(function (qid) { + if (!seen[qid]) { delete draftState.q[qid]; draftGone[qid] = true; } + }); + draftState.bulk = []; + document.querySelectorAll('section.item').forEach(function (card) { + var box = card.querySelector('input.bulk'); + if (box && box.checked) draftState.bulk.push(card.getAttribute('data-ledger')); + }); + var bl = document.getElementById('bulkLean'); + draftState.bulkLean = bl ? bl.value : ''; + var bn = document.getElementById('bulkInfoNote'); + draftState.bulkNote = bn ? bn.value : ''; + draftState.updatedAt = Date.now(); +} +var draftPushTimer = null; +function draftPush() { + if (draftPushTimer) return; + draftPushTimer = setTimeout(function () { draftPushTimer = null; draftPushNow(false); }, 900); +} +function draftPushNow(keepalive) { + if (typeof TOKEN === 'undefined') return; + var questions = {}; + Object.keys(draftState.q).forEach(function (qid) { + var e = draftState.q[qid]; + var out = {}; + if (e.opt) out.opt = e.opt; + if (e.ft) out.ft = e.ft; + if (e.lean) out.lean = e.lean; + if (e.note) out.note = e.note; + out.updatedAt = new Date(e.updatedAt || Date.now()).toISOString(); + questions[qid] = out; + }); + Object.keys(draftGone).forEach(function (qid) { questions[qid] = null; }); + if (!Object.keys(questions).length && !draftState.bulk.length && !draftState.bulkLean && !draftState.bulkNote && !draftServerKnown) return; + var payload = { token: TOKEN, drafts: { questions: questions, bulk: draftState.bulk, bulkLean: draftState.bulkLean, bulkNote: draftState.bulkNote } }; try { - var d = { q: {}, bulk: [], bulkLean: '', bulkNote: '' }; - document.querySelectorAll('.q').forEach(function (block) { - var entry = {}; - var picked = block.querySelector('input[type=radio]:checked'); - if (picked) entry.opt = picked.value; - var ft = block.querySelector('textarea.ft').value; - if (ft) entry.ft = ft; - var lean = block.querySelector('select.defer').value; - if (lean) entry.lean = lean; - var note = block.querySelector('textarea.infonote').value; - if (note) entry.note = note; - if (Object.keys(entry).length) d.q[block.getAttribute('data-qid')] = entry; - }); - document.querySelectorAll('section.item').forEach(function (card) { - var box = card.querySelector('input.bulk'); - if (box && box.checked) d.bulk.push(card.getAttribute('data-ledger')); - }); - var bl = document.getElementById('bulkLean'); - if (bl) d.bulkLean = bl.value; - var bn = document.getElementById('bulkInfoNote'); - if (bn) d.bulkNote = bn.value; - if (!Object.keys(d.q).length && !d.bulk.length && !d.bulkNote && !d.bulkLean) { - localStorage.removeItem(DRAFT_KEY); - } else { - localStorage.setItem(DRAFT_KEY, JSON.stringify(d)); + fetch('/api/decisions/' + encodeURIComponent(DRAFT_SET_ID) + '/drafts', { + method: 'POST', headers: { 'content-type': 'application/json' }, + body: JSON.stringify(payload), keepalive: !!keepalive + }).then(function (r) { if (r && r.ok) { draftGone = {}; draftServerKnown = true; } }).catch(function () {}); + } catch (e) { /* drafts are best-effort */ } +} +function draftSave() { + draftCollect(); + draftLocalPersist(); + if (!draftIsEmpty() || Object.keys(draftGone).length || draftServerKnown) draftPush(); +} +function draftFetchServer() { + if (typeof TOKEN === 'undefined') return Promise.resolve(null); + return fetch('/api/decisions/' + encodeURIComponent(DRAFT_SET_ID) + '/drafts?t=' + encodeURIComponent(TOKEN)) + .then(function (r) { return r.ok ? r.json() : null; }) + .then(function (j) { + if (j && j.drafts) { draftServerKnown = true; return j.drafts; } + return null; + }) + .catch(function () { return null; }); +} +function draftMergeServer(sv) { + if (!sv || typeof sv !== 'object') return; + var sq = sv.questions || {}; + Object.keys(sq).forEach(function (qid) { + var s = sq[qid]; + if (!s) return; + var sAt = Date.parse(s.updatedAt) || 0; + var l = draftState.q[qid]; + var lAt = l ? (l.updatedAt || 0) : -1; + if (sAt > lAt) { + var e = {}; + if (s.opt) e.opt = s.opt; + if (s.ft) e.ft = s.ft; + if (s.lean) e.lean = s.lean; + if (s.note) e.note = s.note; + e.updatedAt = sAt || Date.now(); + draftState.q[qid] = e; + draftFromServer++; } - } catch (e) { /* storage unavailable: drafts are best-effort */ } + }); + var svAt = Date.parse(sv.updatedAt) || 0; + if (svAt > (draftState.updatedAt || 0)) { + draftState.bulk = Array.isArray(sv.bulk) ? sv.bulk : []; + draftState.bulkLean = typeof sv.bulkLean === 'string' ? sv.bulkLean : ''; + draftState.bulkNote = typeof sv.bulkNote === 'string' ? sv.bulkNote : ''; + } } function draftRestore() { - var d; - try { - var raw = localStorage.getItem(DRAFT_KEY); - if (!raw) return; - d = JSON.parse(raw); - } catch (e) { return; } - if (!d || typeof d !== 'object') return; + var d = draftState; var restored = 0; document.querySelectorAll('.q').forEach(function (block) { var entry = (d.q || {})[block.getAttribute('data-qid')]; @@ -741,12 +1213,26 @@ function draftRestore() { }); if (d.bulkLean) { var bl2 = document.getElementById('bulkLean'); if (bl2) bl2.value = d.bulkLean; } if (d.bulkNote) { var bn2 = document.getElementById('bulkInfoNote'); if (bn2) { bn2.value = d.bulkNote; restored++; } } - if (restored) status('Restored your in-progress work from before the interruption — nothing you typed was lost.'); + if (restored) { + status(draftFromServer + ? 'Restored your in-progress work — including drafts synced from the server (started on another device or browser). Nothing you typed was lost.' + : 'Restored your in-progress work from before the interruption — nothing you typed was lost.'); + } } document.addEventListener('input', draftSave); document.addEventListener('change', draftSave); new MutationObserver(draftSave).observe(document.querySelector('main'), { childList: true, subtree: true }); -draftRestore(); -draftSave(); +document.addEventListener('visibilitychange', function () { + if (document.visibilityState === 'hidden') draftPushNow(true); +}); +window.addEventListener('beforeunload', function () { draftPushNow(true); }); +draftDbOpen().then(function () { return draftLocalRead(); }).then(function (local) { + if (local) draftState = local; + return draftFetchServer(); +}).then(function (serverDrafts) { + draftMergeServer(serverDrafts); + draftRestore(); + draftSave(); +}).catch(function () { draftRestore(); draftSave(); }); `; } diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 7feeb33961..c7eb80a960 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -69,12 +69,15 @@ import { decisionSetOpenState, decisionSetProgress, deferWithSubmissions, + getDecisionDrafts, getDecisionSet, isDeferLean, listOpenDecisionSets, raiseDecisionSet, recordResolutions, requestInfoOpenQuestions, + upsertDecisionDrafts, + validateDecisionDraftUpsert, validateDecisionSet, type DecisionItem, type DecisionSet, @@ -3085,6 +3088,40 @@ async function handler(req: Request): Promise { if (!result) return json({ error: "unknown set" }, 404); return json({ requestedCount: result.requestedCount, ...decisionSetOpenState(result.set) }); } + + const decisionsDraftsMatch = /^\/api\/decisions\/([^/]+)\/drafts$/.exec(path); + if ((req.method === "GET" || req.method === "POST") && decisionsDraftsMatch) { + const setId = decodePathSegment(decisionsDraftsMatch[1]); + if (setId === null) return json({ error: "bad setId" }, 400); + const set = await getDecisionSet(cfg.decisionsFile, setId).catch(() => null); + if (req.method === "GET") { + const token = url.searchParams.get("t") ?? ""; + // Unknown set or token mismatch: 403, nothing about the set's + // drafts is shown without the correct link. + if (!set || !token || token !== set.token) { + return json({ error: "unknown set or bad token" }, 403); + } + const drafts = await getDecisionDrafts(cfg.decisionsFile, setId).catch(() => null); + return json({ + drafts: drafts ?? { questions: {}, bulk: [], bulkLean: "", bulkNote: "", updatedAt: "" }, + }); + } + let body: { token?: unknown; drafts?: unknown }; + try { + body = (await readJsonBody(req)) as typeof body; + } catch { + return json({ error: "invalid drafts body" }, 400); + } + // No bearer: the per-set token is the authority. + if (!set || typeof body.token !== "string" || body.token !== set.token) { + return json({ error: "unknown set or bad token" }, 403); + } + const parsedDrafts = validateDecisionDraftUpsert(body.drafts); + if (!parsedDrafts.ok) return json({ error: parsedDrafts.error }, 400); + const result = await upsertDecisionDrafts(cfg.decisionsFile, setId, parsedDrafts.value); + if (!result) return json({ error: "unknown set" }, 404); + return json({ drafts: result.drafts, applied: result.applied, skipped: result.skipped }); + } const alertActionMatch = /^\/api\/alerts\/([\w-]+)\/(ack|close)$/.exec(path); if (req.method === "POST" && alertActionMatch) { const id = alertActionMatch[1]; diff --git a/pm-stack/aggregator/test/decisions.test.ts b/pm-stack/aggregator/test/decisions.test.ts index d10a46de06..4dc48469fe 100644 --- a/pm-stack/aggregator/test/decisions.test.ts +++ b/pm-stack/aggregator/test/decisions.test.ts @@ -6,6 +6,9 @@ import { esc } from "../src/render.ts"; import { decisionSetOpenState, decisionSetProgress, + getDecisionDrafts, + upsertDecisionDrafts, + validateDecisionDraftUpsert, deferOpenQuestions, deferWithSubmissions, getDecisionSet, @@ -428,3 +431,127 @@ describe("decisions page crash hardening (#8777)", () => { expect(js).toContain("draftRestore()"); }); }); + +// --- Server-side drafts (#8766 both-layers upgrade) -------------------- +// Drafts mirror the page's in-progress form state server-side so work +// survives the device it was typed on. They are NOT resolutions: they +// never enter the feed the catcher consumes, and a question's draft +// dies the moment the question resolves, on every resolution path. +describe("decisions server drafts", () => { + test("upsert, read back, and clear-on-answer", async () => { + await raiseDecisionSet(file, sampleInput()); + const up = await upsertDecisionDrafts(file, "set-test-1", { + questions: { + "item-a#1": { opt: "opt-2", ft: "draft words", updatedAt: "2026-11-11T20:00:00.000Z" }, + "item-a#2": { note: "need the numbers", updatedAt: "2026-11-11T20:00:00.000Z" }, + }, + bulk: ["item-b"], + bulkLean: "skeptical", + bulkNote: "", + }); + expect(up?.applied.slice().sort()).toEqual(["item-a#1", "item-a#2"]); + const drafts = await getDecisionDrafts(file, "set-test-1"); + expect(drafts?.questions["item-a#1"]).toMatchObject({ opt: "opt-2", ft: "draft words" }); + expect(drafts?.questions["item-a#2"]).toMatchObject({ note: "need the numbers" }); + expect(drafts?.bulk).toEqual(["item-b"]); + expect(drafts?.bulkLean).toBe("skeptical"); + // Answering item-a#1 kills only its own draft. + await recordResolutions(file, "set-test-1", [ + { ledgerId: "item-a", qid: "item-a#1", kind: "answered", optionId: "opt-1" }, + ]); + const after = await getDecisionDrafts(file, "set-test-1"); + expect(after?.questions["item-a#1"]).toBeUndefined(); + expect(after?.questions["item-a#2"]).toMatchObject({ note: "need the numbers" }); + }); + + test("drafts never enter the resolutions feed", async () => { + await raiseDecisionSet(file, sampleInput()); + await upsertDecisionDrafts(file, "set-test-1", { + questions: { "item-a#1": { ft: "unsubmitted", updatedAt: "2026-11-11T20:00:00.000Z" } }, + }); + expect(await listDecisionResolutions(file)).toEqual([]); + await recordResolutions(file, "set-test-1", [ + { ledgerId: "item-a", qid: "item-a#1", kind: "deferred", lean: "none" }, + ]); + const feed = await listDecisionResolutions(file); + expect(feed).toHaveLength(1); + expect(feed[0]).toMatchObject({ qid: "item-a#1", kind: "deferred" }); + }); + + test("ghost qids are skipped and resolved questions never resurrect", async () => { + await raiseDecisionSet(file, sampleInput()); + const ghost = await upsertDecisionDrafts(file, "set-test-1", { + questions: { "nope#9": { ft: "boo", updatedAt: "2026-11-11T20:00:00.000Z" } }, + }); + expect(ghost?.applied).toEqual([]); + expect(ghost?.skipped).toEqual([{ qid: "nope#9", reason: "unknown-question" }]); + await recordResolutions(file, "set-test-1", [ + { ledgerId: "item-a", qid: "item-a#1", kind: "answered", freeText: "done" }, + ]); + const zombie = await upsertDecisionDrafts(file, "set-test-1", { + questions: { "item-a#1": { ft: "too late", updatedAt: "2026-11-11T21:00:00.000Z" } }, + }); + expect(zombie?.skipped).toEqual([{ qid: "item-a#1", reason: "already-resolved" }]); + expect((await getDecisionDrafts(file, "set-test-1"))?.questions["item-a#1"]).toBeUndefined(); + }); + + test("tombstones delete; defer and request-info clear drafts too", async () => { + await raiseDecisionSet(file, sampleInput()); + await upsertDecisionDrafts(file, "set-test-1", { + questions: { + "item-a#1": { ft: "x", updatedAt: "2026-11-11T20:00:00.000Z" }, + "item-a#2": { ft: "y", updatedAt: "2026-11-11T20:00:00.000Z" }, + "item-b#1": { ft: "z", updatedAt: "2026-11-11T20:00:00.000Z" }, + }, + }); + const del = await upsertDecisionDrafts(file, "set-test-1", { questions: { "item-a#1": null } }); + expect(del?.applied).toEqual(["item-a#1"]); + expect((await getDecisionDrafts(file, "set-test-1"))?.questions["item-a#1"]).toBeUndefined(); + await deferOpenQuestions(file, "set-test-1", { ledgerIds: ["item-a"] }, "approve"); + expect((await getDecisionDrafts(file, "set-test-1"))?.questions["item-a#2"]).toBeUndefined(); + await requestInfoOpenQuestions(file, "set-test-1", { ledgerIds: ["item-b"] }); + expect((await getDecisionDrafts(file, "set-test-1"))?.questions["item-b#1"]).toBeUndefined(); + }); + + test("newest updatedAt wins at the store; a stale push is skipped", async () => { + await raiseDecisionSet(file, sampleInput()); + await upsertDecisionDrafts(file, "set-test-1", { + questions: { "item-a#1": { ft: "newer", updatedAt: "2026-11-11T21:00:00.000Z" } }, + }); + const stale = await upsertDecisionDrafts(file, "set-test-1", { + questions: { "item-a#1": { ft: "older", updatedAt: "2026-11-11T20:00:00.000Z" } }, + }); + expect(stale?.skipped).toEqual([{ qid: "item-a#1", reason: "stale" }]); + expect((await getDecisionDrafts(file, "set-test-1"))?.questions["item-a#1"]?.ft).toBe("newer"); + }); + + test("an unknown set reads back null", async () => { + expect(await getDecisionDrafts(file, "no-such-set")).toBeNull(); + expect( + await upsertDecisionDrafts(file, "no-such-set", { questions: {} }), + ).toBeNull(); + }); + + test("validateDecisionDraftUpsert rejects malformed payloads", () => { + expect(validateDecisionDraftUpsert(null).ok).toBe(false); + expect(validateDecisionDraftUpsert({}).ok).toBe(false); + expect(validateDecisionDraftUpsert({ questions: { "item-a#1": { updatedAt: "x" } } }).ok).toBe(false); + expect(validateDecisionDraftUpsert({ questions: { "item-a#1": { lean: "bogus" } } }).ok).toBe(false); + expect(validateDecisionDraftUpsert({ questions: { "item-a#1": null } }).ok).toBe(true); + const okRes = validateDecisionDraftUpsert({ + questions: { "item-a#1": { ft: "hi", lean: "approve", updatedAt: "2026-11-11T20:00:00.000Z" } }, + bulk: ["item-a"], + }); + expect(okRes.ok).toBe(true); + }); + + test("draft script wires IndexedDB, the server drafts API and the merge", () => { + const js = decisionsDraftScript("set-a"); + expect(js).toContain("indexedDB.open"); + expect(js).toContain("/drafts"); + expect(js).toContain("visibilitychange"); + expect(js).toContain("draftMergeServer"); + expect(js).toContain("draftFetchServer"); + expect(() => new Function(js)).not.toThrow(); + }); +});