diff --git a/pm-stack/aggregator/src/decisions.ts b/pm-stack/aggregator/src/decisions.ts index 356159f7a5..953997fb86 100644 --- a/pm-stack/aggregator/src/decisions.ts +++ b/pm-stack/aggregator/src/decisions.ts @@ -18,6 +18,13 @@ // - deferred: Drew sent it back to the orchestrator, with a lean: // "none" (plain defer), "skeptical" (leaning no), "approve" // (leaning yes). +// - request-info: Drew asked for more information before deciding, +// with an optional note saying what is missing. The question leaves +// his page like a defer, but it is NOT a ruling: downstream (the +// dropped-thread catcher) marks the ledger question +// awaiting-enrichment and never closes the item for it; once the +// orchestrator gathers the information, the question is re-raised +// in a later set carrying it as `infoProvided`. // The set's per-set token (minted once, at raise) is the authority for // the decisions page (/decisions/?t=) and the submit / // defer endpoints — possession of the set push is the authority, the @@ -40,14 +47,22 @@ export interface DecisionOption { } export interface DecisionResolution { - kind: "answered" | "deferred"; - /** Answered only: the chosen option's id and its label at record time. */ + kind: "answered" | "deferred" | "request-info"; + /** Answered: the chosen option's id and label at record time. + * Deferred: Drew's tentative pick, recorded as guidance for the + * orchestrator — the defer is still the resolution kind. */ optionId?: string; optionLabel?: string; /** Answered only: Drew's own words, when he wrote any. */ freeText?: string; /** Deferred only: the lean Drew recorded with the defer. */ lean?: DeferLean; + /** Request-info only: what Drew said is missing (optional). */ + note?: string; + /** Any kind: a remark Drew attached to the resolution — on a defer it + * is the free text he wrote on the question; it rides back to the + * ledger with the resolution, it is not part of the ruling itself. */ + comment?: string; at: string; via: string; } @@ -57,6 +72,10 @@ export interface DecisionQuestion { qid: string; question: string; context?: string; + /** Information the orchestrator gathered after Drew requested more + * info on this question in an earlier set (the re-raise payload); + * rendered on the page as a marked "information you requested" block. */ + infoProvided?: string; options: DecisionOption[]; resolution?: DecisionResolution; } @@ -84,6 +103,7 @@ export interface DecisionSet { export interface DecisionQuestionInput { question: string; context?: string; + infoProvided?: string; options: DecisionOption[]; } @@ -108,11 +128,15 @@ export interface DecisionResolutionRecord { qid: string; /** 1-based index of the question within its ledger item. */ questionIndex: number; - kind: "answered" | "deferred"; + kind: "answered" | "deferred" | "request-info"; optionId?: string; optionLabel?: string; freeText?: string; lean?: DeferLean; + /** Request-info only: what Drew said is missing (optional). */ + note?: string; + /** Any kind: Drew's remark attached to the resolution. */ + comment?: string; at: string; via: string; } @@ -185,6 +209,9 @@ export function validateDecisionSet( if (q.context !== undefined && typeof q.context !== "string") { return { ok: false, error: `decisionSet item ${ledgerId} question context must be a string` }; } + if (q.infoProvided !== undefined && typeof q.infoProvided !== "string") { + return { ok: false, error: `decisionSet item ${ledgerId} question infoProvided must be a string` }; + } // Options may be empty: a free-text-only question is legitimate // (the ledger carries questions with no recorded options). if (!Array.isArray(q.options) || q.options.length > 8) { @@ -211,6 +238,7 @@ export function validateDecisionSet( questions.push({ question, ...(typeof q.context === "string" && q.context.trim() ? { context: q.context } : {}), + ...(typeof q.infoProvided === "string" && q.infoProvided.trim() ? { infoProvided: q.infoProvided } : {}), options, }); } @@ -292,6 +320,7 @@ export async function raiseDecisionSet( qid: `${item.ledgerId}#${i + 1}`, question: q.question, ...(q.context !== undefined ? { context: q.context } : {}), + ...(q.infoProvided !== undefined ? { infoProvided: q.infoProvided } : {}), options: q.options, })), })), @@ -310,10 +339,14 @@ export async function getDecisionSet(file: string, setId: string): Promise o.id === sub.optionId) : undefined; + if (sub.optionId !== undefined && !guide) { + outcomes.push({ qid: sub.qid, applied: false, reason: "bad-option" }); + continue; + } + const comment = typeof sub.comment === "string" ? sub.comment.trim() : ""; + q.resolution = { + kind: "deferred", + lean: sub.lean, + ...(guide ? { optionId: guide.id, optionLabel: guide.label } : {}), + ...(comment ? { comment } : {}), + at: now, + via, + }; + outcomes.push({ qid: sub.qid, applied: true }); + continue; + } + if (sub.kind === "request-info") { + // Not a ruling: the note is optional, an empty request still + // sends the question back for enrichment. + const note = typeof sub.note === "string" ? sub.note.trim() : ""; + const comment = typeof sub.comment === "string" ? sub.comment.trim() : ""; + q.resolution = { + kind: "request-info", + ...(note ? { note } : {}), + ...(comment ? { comment } : {}), + at: now, + via, + }; outcomes.push({ qid: sub.qid, applied: true }); continue; } @@ -376,10 +439,12 @@ export async function recordResolutions( outcomes.push({ qid: sub.qid, applied: false, reason: "empty-answer" }); continue; } + const comment = typeof sub.comment === "string" ? sub.comment.trim() : ""; q.resolution = { kind: "answered", ...(option ? { optionId: option.id, optionLabel: option.label } : {}), ...(freeText ? { freeText } : {}), + ...(comment ? { comment } : {}), at: now, via, }; @@ -401,6 +466,7 @@ export async function deferOpenQuestions( scope: { allRemaining: true } | { ledgerIds: string[] }, lean: DeferLean, via = "decisions-page", + comment?: string, ): Promise<{ set: DecisionSet; deferredCount: number } | null> { return serializeDecisions(file, async () => { const sets = await readDecisionSets(file); @@ -408,12 +474,13 @@ export async function deferOpenQuestions( if (!set) return null; const wanted = "allRemaining" in scope ? null : new Set(scope.ledgerIds); const now = new Date().toISOString(); + const trimmedComment = typeof comment === "string" ? comment.trim() : ""; let deferredCount = 0; for (const item of set.items) { if (wanted && !wanted.has(item.ledgerId)) continue; for (const q of item.questions) { if (q.resolution) continue; - q.resolution = { kind: "deferred", lean, at: now, via }; + q.resolution = { kind: "deferred", lean, ...(trimmedComment ? { comment: trimmedComment } : {}), at: now, via }; deferredCount++; } } @@ -422,12 +489,78 @@ export async function deferOpenQuestions( }); } +/** + * The bulk send-back with filled answers winning (#8766): record the + * submissions the page gathered from filled-in fields FIRST — an answer + * Drew typed but had not submitted is recorded as a ruling, never + * converted into a deferral or lost — then defer every still-open + * question in scope with the bulk lean (and the bulk comment, when one + * was written). A per-question defer inside the submissions keeps its + * own lean and comment; the bulk lean/comment apply only to the + * questions the bulk action itself defers. + */ +export async function deferWithSubmissions( + file: string, + setId: string, + submissions: DecisionSubmission[], + scope: { allRemaining: true } | { ledgerIds: string[] }, + lean: DeferLean, + comment?: string, + via = "decisions-page", +): Promise<{ set: DecisionSet; outcomes: SubmissionOutcome[]; deferredCount: number } | null> { + let outcomes: SubmissionOutcome[] = []; + if (submissions.length > 0) { + const applied = await recordResolutions(file, setId, submissions, via); + if (!applied) return null; + outcomes = applied.outcomes; + } + const deferred = await deferOpenQuestions(file, setId, scope, lean, via, comment); + if (!deferred) return null; + return { set: deferred.set, outcomes, deferredCount: deferred.deferredCount }; +} + +/** + * Request more information on every still-open question in scope (the + * page's checked-items request-info action): either the checked items, + * or all remaining questions in the set. Each open question records a + * request-info resolution carrying the shared note. Already-resolved + * questions are untouched. Returns the count requested. + */ +export async function requestInfoOpenQuestions( + file: string, + setId: string, + scope: { allRemaining: true } | { ledgerIds: string[] }, + note?: string, + via = "decisions-page", +): Promise<{ set: DecisionSet; requestedCount: number } | null> { + return serializeDecisions(file, async () => { + const sets = await readDecisionSets(file); + const set = sets.find((s) => s.setId === setId); + if (!set) return null; + const wanted = "allRemaining" in scope ? null : new Set(scope.ledgerIds); + const now = new Date().toISOString(); + const trimmed = typeof note === "string" ? note.trim() : ""; + let requestedCount = 0; + for (const item of set.items) { + if (wanted && !wanted.has(item.ledgerId)) continue; + for (const q of item.questions) { + if (q.resolution) continue; + q.resolution = { kind: "request-info", ...(trimmed ? { note: trimmed } : {}), at: now, via }; + requestedCount++; + } + } + if (requestedCount > 0) await writeDecisionSets(file, sets); + return { set, requestedCount }; + }); +} + export interface DecisionSetProgress { items: number; questions: number; openQuestions: number; answered: number; deferred: number; + infoRequested: number; /** Items with at least one open question. */ openItems: number; } @@ -437,6 +570,7 @@ export function decisionSetProgress(set: DecisionSet): DecisionSetProgress { let openQuestions = 0; let answered = 0; let deferred = 0; + let infoRequested = 0; let openItems = 0; for (const item of set.items) { let itemOpen = 0; @@ -446,11 +580,12 @@ export function decisionSetProgress(set: DecisionSet): DecisionSetProgress { openQuestions++; itemOpen++; } else if (q.resolution.kind === "answered") answered++; - else deferred++; + else if (q.resolution.kind === "deferred") deferred++; + else infoRequested++; } if (itemOpen > 0) openItems++; } - return { items: set.items.length, questions, openQuestions, answered, deferred, openItems }; + return { items: set.items.length, questions, openQuestions, answered, deferred, infoRequested, openItems }; } export function isDecisionSetFullyResolved(set: DecisionSet): boolean { @@ -502,6 +637,8 @@ export async function listDecisionResolutions(file: string): Promise 256) { + return { ok: false, error: "submissions must be an array of 1-256 entries" }; + } + const submissions: DecisionSubmission[] = []; + for (const entry of raw) { + if (!entry || typeof entry !== "object" || Array.isArray(entry)) { + return { ok: false, error: "submissions entries must be objects" }; + } + const s = entry as Record; + const ledgerId = typeof s.ledgerId === "string" ? s.ledgerId : ""; + const qid = typeof s.qid === "string" ? s.qid : ""; + const kind = s.kind; + if (!ledgerId || !qid || (kind !== "answered" && kind !== "deferred" && kind !== "request-info")) { + return { ok: false, error: "submissions entries require ledgerId, qid and kind answered|deferred|request-info" }; + } + if (kind === "deferred" && !isDeferLean(s.lean)) { + return { ok: false, error: "deferred submissions require a lean of none|skeptical|approve" }; + } + submissions.push({ + ledgerId, + qid, + kind, + ...(typeof s.optionId === "string" ? { optionId: s.optionId } : {}), + ...(typeof s.freeText === "string" ? { freeText: s.freeText } : {}), + ...(isDeferLean(s.lean) ? { lean: s.lean } : {}), + ...(typeof s.note === "string" ? { note: s.note } : {}), + ...(typeof s.comment === "string" ? { comment: s.comment } : {}), + }); + } + return { ok: true, value: submissions }; +} + const DECISIONS_PAGE_STYLE = `${ANSWER_PAGE_STYLE}`; @@ -711,8 +753,10 @@ function renderDecisionsPage(set: DecisionSet): string { const r = q.resolution!; const what = r.kind === "deferred" - ? `deferred to the orchestrator${r.lean && r.lean !== "none" ? ` (lean: ${esc(r.lean)})` : ""}` - : `answered${r.optionLabel ? `: ${esc(r.optionLabel)}` : r.freeText ? `: ${esc(r.freeText)}` : ""}`; + ? `deferred to the orchestrator${r.lean && r.lean !== "none" ? ` (lean: ${esc(r.lean)})` : ""}${r.optionLabel ? ` — your tentative pick: ${esc(r.optionLabel)}` : ""}${r.comment ? ` — comment: ${esc(r.comment)}` : ""}` + : r.kind === "request-info" + ? `more information requested${r.note ? ` — you said: ${esc(r.note)}` : ""}` + : `answered${r.optionLabel ? `: ${esc(r.optionLabel)}` : r.freeText ? `: ${esc(r.freeText)}` : ""}`; return `
✓ ${esc(q.question)} — ${what}
`; }) .join(""); @@ -726,20 +770,23 @@ function renderDecisionsPage(set: DecisionSet): string { .join(""); return `

${esc(q.question)}

+${q.infoProvided ? `

Information you requested

${esc(q.infoProvided)}

` : ""} ${q.context ? `

${esc(q.context)}

` : ""} ${radios} - + + +
`; }) .join(""); return `
- +

${esc(item.title)}

${links ? `` : ""} ${resolvedLines} @@ -760,19 +807,22 @@ ${questionBlocks} return ` Decisions — PM Stack${DECISIONS_PAGE_STYLE}

${esc(set.title)}

-

${progress.openQuestions} question${progress.openQuestions === 1 ? "" : "s"} open across ${progress.openItems} item${progress.openItems === 1 ? "" : "s"} · ${progress.answered} answered · ${progress.deferred} deferred so far. Fill in what you want — you can submit a partially-filled item; what you filled in is recorded and the rest stays here.

+

${progress.openQuestions} question${progress.openQuestions === 1 ? "" : "s"} open across ${progress.openItems} item${progress.openItems === 1 ? "" : "s"} · ${progress.answered} answered · ${progress.deferred} deferred · ${progress.infoRequested} sent back for more information so far. Fill in what you want — you can submit a partially-filled item; what you filled in is recorded and the rest stays here.

${caughtUp ? `

All caught up — every question in this set has been answered or sent back. Nothing left on this page.

` : body}

Bulk actions

-

Send whole items back to the orchestrator instead of answering:

+

Defer checked items to the orchestrator instead of answering — they leave this page and become the orchestrator's job. Precedence per question: (1) the question's own defer setting wins, with its tentative pick and comment riding along as guidance; (2) a filled-in answer submits as an answer; (3) only a question nobody touched uses the default flavor picked here:

- - + + +

Or request more information for the checked items — they leave this page and come back in a later set once the information has been gathered:

+ +

`; } @@ -2868,34 +2994,9 @@ async function handler(req: Request): Promise { if (!set || typeof body.token !== "string" || body.token !== set.token) { return json({ error: "unknown set or bad token" }, 403); } - if (!Array.isArray(body.submissions) || body.submissions.length < 1 || body.submissions.length > 256) { - return json({ error: "submissions must be an array of 1-256 entries" }, 400); - } - const submissions: DecisionSubmission[] = []; - for (const raw of body.submissions) { - if (!raw || typeof raw !== "object" || Array.isArray(raw)) { - return json({ error: "submissions entries must be objects" }, 400); - } - const s = raw as Record; - const ledgerId = typeof s.ledgerId === "string" ? s.ledgerId : ""; - const qid = typeof s.qid === "string" ? s.qid : ""; - const kind = s.kind; - if (!ledgerId || !qid || (kind !== "answered" && kind !== "deferred")) { - return json({ error: "submissions entries require ledgerId, qid and kind answered|deferred" }, 400); - } - if (kind === "deferred" && !isDeferLean(s.lean)) { - return json({ error: "deferred submissions require a lean of none|skeptical|approve" }, 400); - } - submissions.push({ - ledgerId, - qid, - kind, - ...(typeof s.optionId === "string" ? { optionId: s.optionId } : {}), - ...(typeof s.freeText === "string" ? { freeText: s.freeText } : {}), - ...(isDeferLean(s.lean) ? { lean: s.lean } : {}), - }); - } - const result = await recordResolutions(cfg.decisionsFile, setId, submissions); + const parsedSubs = parseDecisionSubmissions(body.submissions); + if (!parsedSubs.ok) return json({ error: parsedSubs.error }, 400); + const result = await recordResolutions(cfg.decisionsFile, setId, parsedSubs.value); if (!result) return json({ error: "unknown set" }, 404); return json({ outcomes: result.outcomes, ...decisionSetOpenState(result.set) }); } @@ -2903,7 +3004,14 @@ async function handler(req: Request): Promise { if (req.method === "POST" && decisionsDeferMatch) { const setId = decodePathSegment(decisionsDeferMatch[1]); if (setId === null) return json({ error: "bad setId" }, 400); - let body: { token?: unknown; lean?: unknown; ledgerIds?: unknown; allRemaining?: unknown }; + let body: { + token?: unknown; + lean?: unknown; + ledgerIds?: unknown; + allRemaining?: unknown; + submissions?: unknown; + comment?: unknown; + }; try { body = (await readJsonBody(req)) as typeof body; } catch { @@ -2924,14 +3032,56 @@ async function handler(req: Request): Promise { if (!all && ledgerIds.length === 0) { return json({ error: "ledgerIds or allRemaining required" }, 400); } - const result = await deferOpenQuestions( + // Filled answers win over the bulk defer (#8766): submissions the + // page gathered from filled-in fields are recorded FIRST, and only + // the still-unanswered questions in scope are deferred. + let submissions: DecisionSubmission[] = []; + if (body.submissions !== undefined) { + const parsedSubs = parseDecisionSubmissions(body.submissions); + if (!parsedSubs.ok) return json({ error: parsedSubs.error }, 400); + submissions = parsedSubs.value; + } + const result = await deferWithSubmissions( cfg.decisionsFile, setId, + submissions, all ? { allRemaining: true as const } : { ledgerIds }, body.lean, + typeof body.comment === "string" ? body.comment : undefined, + ); + if (!result) return json({ error: "unknown set" }, 404); + return json({ outcomes: result.outcomes, deferredCount: result.deferredCount, ...decisionSetOpenState(result.set) }); + } + const decisionsReqInfoMatch = /^\/api\/decisions\/([^/]+)\/request-info$/.exec(path); + if (req.method === "POST" && decisionsReqInfoMatch) { + const setId = decodePathSegment(decisionsReqInfoMatch[1]); + if (setId === null) return json({ error: "bad setId" }, 400); + let body: { token?: unknown; note?: unknown; ledgerIds?: unknown; allRemaining?: unknown }; + try { + body = (await readJsonBody(req)) as typeof body; + } catch { + return json({ error: "invalid request-info body" }, 400); + } + // No bearer: the per-set token is the authority. + const set = await getDecisionSet(cfg.decisionsFile, setId).catch(() => null); + if (!set || typeof body.token !== "string" || body.token !== set.token) { + return json({ error: "unknown set or bad token" }, 403); + } + const all = body.allRemaining === true; + const ledgerIds = Array.isArray(body.ledgerIds) + ? body.ledgerIds.filter((x): x is string => typeof x === "string") + : []; + if (!all && ledgerIds.length === 0) { + return json({ error: "ledgerIds or allRemaining required" }, 400); + } + const result = await requestInfoOpenQuestions( + cfg.decisionsFile, + setId, + all ? { allRemaining: true as const } : { ledgerIds }, + typeof body.note === "string" ? body.note : undefined, ); if (!result) return json({ error: "unknown set" }, 404); - return json({ deferredCount: result.deferredCount, ...decisionSetOpenState(result.set) }); + return json({ requestedCount: result.requestedCount, ...decisionSetOpenState(result.set) }); } const alertActionMatch = /^\/api\/alerts\/([\w-]+)\/(ack|close)$/.exec(path); if (req.method === "POST" && alertActionMatch) { diff --git a/pm-stack/aggregator/test/decisions.test.ts b/pm-stack/aggregator/test/decisions.test.ts index e98e4f5f1c..859f8f904d 100644 --- a/pm-stack/aggregator/test/decisions.test.ts +++ b/pm-stack/aggregator/test/decisions.test.ts @@ -6,12 +6,14 @@ import { decisionSetOpenState, decisionSetProgress, deferOpenQuestions, + deferWithSubmissions, getDecisionSet, isDecisionSetFullyResolved, listDecisionResolutions, listOpenDecisionSets, raiseDecisionSet, recordResolutions, + requestInfoOpenQuestions, validateDecisionSet, type DecisionSetInput, } from "../src/decisions.ts"; @@ -182,3 +184,201 @@ describe("decision set store (#8766)", () => { expect(await getDecisionSet(file, "nope")).toBeNull(); }); }); + +describe("request-info, comments, filled-answers-win (#8766 follow-up)", () => { + test("request-info records the optional note, counts separately, and is not overwritten in-set", async () => { + await raiseDecisionSet(file, sampleInput()); + const res = await recordResolutions(file, "set-test-1", [ + { ledgerId: "item-a", qid: "item-a#1", kind: "request-info", note: "need the cost numbers" }, + { ledgerId: "item-a", qid: "item-a#2", kind: "request-info" }, + ]); + expect(res?.outcomes).toEqual([ + { qid: "item-a#1", applied: true }, + { qid: "item-a#2", applied: true }, + ]); + const progress = decisionSetProgress(res!.set); + expect(progress.infoRequested).toBe(2); + expect(progress.answered).toBe(0); + expect(progress.deferred).toBe(0); + expect(decisionSetOpenState(res!.set).items.find((i) => i.ledgerId === "item-a")?.openQids).toEqual([]); + const records = await listDecisionResolutions(file); + expect(records.find((r) => r.qid === "item-a#1")).toMatchObject({ kind: "request-info", note: "need the cost numbers" }); + expect(records.find((r) => r.qid === "item-a#2")?.note).toBeUndefined(); + // First resolution still wins inside one set: a later answer in the + // SAME set does not overwrite the request-info. + const again = await recordResolutions(file, "set-test-1", [ + { ledgerId: "item-a", qid: "item-a#1", kind: "answered", optionId: "opt-1" }, + ]); + expect(again?.outcomes).toEqual([{ qid: "item-a#1", applied: false, reason: "already-resolved" }]); + }); + + test("bulk request-info: checked items only, resolved questions untouched, shared note", async () => { + await raiseDecisionSet(file, sampleInput()); + await recordResolutions(file, "set-test-1", [ + { ledgerId: "item-a", qid: "item-a#1", kind: "answered", optionId: "opt-1" }, + ]); + const out = await requestInfoOpenQuestions(file, "set-test-1", { ledgerIds: ["item-a", "item-b"] }, "missing the timeline"); + expect(out?.requestedCount).toBe(2); // item-a#2 + item-b#1; item-a#1 already answered + const records = await listDecisionResolutions(file); + expect(records.find((r) => r.qid === "item-a#1")?.kind).toBe("answered"); + expect(records.find((r) => r.qid === "item-b#1")).toMatchObject({ kind: "request-info", note: "missing the timeline" }); + }); + + test("re-raise: an enriched question returns in a later set carrying infoProvided and can be answered there", async () => { + await raiseDecisionSet(file, sampleInput("set-first")); + await recordResolutions(file, "set-first", [ + { ledgerId: "item-a", qid: "item-a#1", kind: "request-info", note: "what did it cost?" }, + ]); + // The orchestrator gathers the information and raises a later set + // whose question carries it, visibly marked as the requested info. + const enriched = sampleInput("set-reraise"); + enriched.items[0]!.questions[0]!.infoProvided = "It cost $4,100 over March-May (export linked on the issue)."; + expect(validateDecisionSet(enriched).ok).toBe(true); + const set2 = await raiseDecisionSet(file, enriched); + expect(set2.items[0]!.questions[0]!.infoProvided).toContain("$4,100"); + const res = await recordResolutions(file, "set-reraise", [ + { ledgerId: "item-a", qid: "item-a#1", kind: "answered", optionId: "opt-2" }, + ]); + expect(res?.outcomes).toEqual([{ qid: "item-a#1", applied: true }]); + // Both resolutions for the same qid reach the feed, keyed by set. + const forQ = (await listDecisionResolutions(file)).filter((r) => r.qid === "item-a#1"); + expect(forQ.map((r) => `${r.setId}:${r.kind}`)).toEqual(["set-first:request-info", "set-reraise:answered"]); + // infoProvided validation: a non-string is rejected. + const bad = sampleInput("set-bad"); + (bad.items[0]!.questions[0] as { infoProvided?: unknown }).infoProvided = 42; + expect(validateDecisionSet(bad).ok).toBe(false); + }); + + test("filled answers win over bulk defer: typed answer recorded as a ruling, the rest deferred", async () => { + await raiseDecisionSet(file, sampleInput()); + const out = await deferWithSubmissions( + file, + "set-test-1", + [ + { ledgerId: "item-a", qid: "item-a#1", kind: "answered", optionId: "opt-2" }, + { ledgerId: "item-a", qid: "item-a#2", kind: "deferred", lean: "skeptical", comment: "not without the numbers" }, + ], + { allRemaining: true }, + "none", + "bulk note", + ); + expect(out?.outcomes).toEqual([ + { qid: "item-a#1", applied: true }, + { qid: "item-a#2", applied: true }, + ]); + expect(out?.deferredCount).toBe(1); // only item-b#1 was still unanswered + const records = await listDecisionResolutions(file); + const byQid = new Map(records.map((r) => [r.qid, r])); + // The filled-in answer is an answer resolution, never a deferral. + expect(byQid.get("item-a#1")).toMatchObject({ kind: "answered", optionId: "opt-2" }); + // The per-question defer kept its own lean and comment. + expect(byQid.get("item-a#2")).toMatchObject({ kind: "deferred", lean: "skeptical", comment: "not without the numbers" }); + // The bulk defer took the bulk lean and bulk comment. + expect(byQid.get("item-b#1")).toMatchObject({ kind: "deferred", lean: "none", comment: "bulk note" }); + expect(isDecisionSetFullyResolved(out!.set)).toBe(true); + }); + + test("comments ride on every kind: answer, defer, request-info", async () => { + await raiseDecisionSet(file, sampleInput()); + await recordResolutions(file, "set-test-1", [ + { ledgerId: "item-a", qid: "item-a#1", kind: "answered", optionId: "opt-1", comment: "but revisit in Q1" }, + { ledgerId: "item-a", qid: "item-a#2", kind: "deferred", lean: "approve", comment: "fine either way" }, + { ledgerId: "item-b", qid: "item-b#1", kind: "request-info", note: "need dates", comment: "and who owns it" }, + ]); + const records = await listDecisionResolutions(file); + expect(records.find((r) => r.qid === "item-a#1")?.comment).toBe("but revisit in Q1"); + expect(records.find((r) => r.qid === "item-a#2")?.comment).toBe("fine either way"); + expect(records.find((r) => r.qid === "item-b#1")).toMatchObject({ note: "need dates", comment: "and who owns it" }); + }); +}); + +describe("guided defer + mixed flavors (#8766 follow-up)", () => { + test("guided defer: option pick + comment ride along, kind stays deferred", async () => { + await raiseDecisionSet(file, sampleInput()); + const res = await recordResolutions(file, "set-test-1", [ + { + ledgerId: "item-a", + qid: "item-a#1", + kind: "deferred", + lean: "skeptical", + optionId: "opt-1", + comment: "leaning yes on the tech, no on the timing", + }, + { ledgerId: "item-a", qid: "item-a#2", kind: "deferred", lean: "none", optionId: "bogus" }, + ]); + expect(res?.outcomes).toEqual([ + { qid: "item-a#1", applied: true }, + { qid: "item-a#2", applied: false, reason: "bad-option" }, + ]); + const records = await listDecisionResolutions(file); + expect(records.find((r) => r.qid === "item-a#1")).toMatchObject({ + kind: "deferred", + lean: "skeptical", + optionId: "opt-1", + optionLabel: "Yes", + comment: "leaning yes on the tech, no on the timing", + }); + const progress = decisionSetProgress(res!.set); + expect(progress.deferred).toBe(1); + expect(progress.answered).toBe(0); + }); + + test("bulk send-all precedence: guided defer > filled answer > untouched (plain defer)", async () => { + await raiseDecisionSet(file, sampleInput()); + // One bulk action carrying: item-a#1 = option + comment + defer set + // (guided defer), item-a#2 = free-text answer only (an answer). + // item-b#1 is untouched and must defer plain with the bulk lean. + const out = await deferWithSubmissions( + file, + "set-test-1", + [ + { ledgerId: "item-a", qid: "item-a#1", kind: "deferred", lean: "approve", optionId: "opt-2", comment: "if we must" }, + { ledgerId: "item-a", qid: "item-a#2", kind: "answered", freeText: "Rockbot was the 2024 prototype" }, + ], + { allRemaining: true }, + "none", + ); + expect(out?.deferredCount).toBe(1); + const records = await listDecisionResolutions(file); + const byQid = new Map(records.map((r) => [r.qid, r])); + // Defer setting wins over the filled option: kind is deferred, and + // the option + comment ride as guidance. + expect(byQid.get("item-a#1")).toMatchObject({ + kind: "deferred", + lean: "approve", + optionId: "opt-2", + optionLabel: "No", + comment: "if we must", + }); + // The answer-only question in the same bulk action is an answer. + expect(byQid.get("item-a#2")).toMatchObject({ kind: "answered", freeText: "Rockbot was the 2024 prototype" }); + // The untouched question defers plain — no flavor stamped on it. + expect(byQid.get("item-b#1")).toMatchObject({ kind: "deferred", lean: "none" }); + expect(byQid.get("item-b#1")?.optionId).toBeUndefined(); + }); +}); + +describe("bulk default flavor (#8766 follow-up)", () => { + test("bulk dropdown is only a default: own flavor beats it, filled answer beats it, untouched takes it", async () => { + await raiseDecisionSet(file, sampleInput()); + // Bulk send-all with the bottom dropdown on "skeptical": + // item-a#1 has its OWN defer flavor (approve) + a tentative pick — + // level 1 wins. item-a#2 has only a filled answer — level 2 wins. + // item-b#1 is untouched — it takes the bulk default, level 3. + const out = await deferWithSubmissions( + file, + "set-test-1", + [ + { ledgerId: "item-a", qid: "item-a#1", kind: "deferred", lean: "approve", optionId: "opt-1", comment: "guidance" }, + { ledgerId: "item-a", qid: "item-a#2", kind: "answered", freeText: "the answer" }, + ], + { allRemaining: true }, + "skeptical", + ); + expect(out?.deferredCount).toBe(1); // only the untouched question is bulk-deferred + const byQid = new Map((await listDecisionResolutions(file)).map((r) => [r.qid, r])); + expect(byQid.get("item-a#1")).toMatchObject({ kind: "deferred", lean: "approve", optionId: "opt-1", comment: "guidance" }); + expect(byQid.get("item-a#2")).toMatchObject({ kind: "answered", freeText: "the answer" }); + expect(byQid.get("item-b#1")).toMatchObject({ kind: "deferred", lean: "skeptical" }); + }); +});