diff --git a/pm-stack/aggregator/scripts/collect-fleet-feed.ts b/pm-stack/aggregator/scripts/collect-fleet-feed.ts index 6cda75e8ae..896edc8280 100644 --- a/pm-stack/aggregator/scripts/collect-fleet-feed.ts +++ b/pm-stack/aggregator/scripts/collect-fleet-feed.ts @@ -110,6 +110,7 @@ import { import { computeCheckoutDrift } from "../src/checkout-drift.ts"; import { assembleCollectorFeed } from "../src/feed-contract.ts"; import { defaultNeedsDrewFile, listAnswers } from "../src/needs-drew.ts"; +import { defaultDecisionsFile, listDecisionResolutions } from "../src/decisions.ts"; import type { AaBatchSummary, AaFeedSection, @@ -1244,9 +1245,19 @@ async function main(): Promise { answers = []; } + // #8766: Drew's decisions-page resolutions (answers + defers), from + // the aggregator's decision-set store. Fail-soft like `answers`. + let decisionResolutions: NonNullable = []; + try { + decisionResolutions = await listDecisionResolutions(defaultDecisionsFile()); + } catch { + decisionResolutions = []; + } + const feed: FleetFeed = assembleCollectorFeed({ generatedAt: now.toISOString(), answers, + decisionResolutions, checkout, meta: { sections: sectionStatuses }, quota: { pools, burn: burnSegments, choices: computeChoices(pools, now.getTime()) }, diff --git a/pm-stack/aggregator/scripts/raise-decision-set.ts b/pm-stack/aggregator/scripts/raise-decision-set.ts new file mode 100644 index 0000000000..1acbb092d6 --- /dev/null +++ b/pm-stack/aggregator/scripts/raise-decision-set.ts @@ -0,0 +1,121 @@ +#!/usr/bin/env bun +// Raise a decision SET on the aggregator (#8766): the producer half of +// the decisions page. Reads a payload JSON file holding the +// `decisionSet` extension shape ({ setId, title, items: [...] }) — +// built from the Muse-side decisions ledger by whoever is presenting +// a batch — validates it locally against the same validator the server +// runs, then posts it to the alert throat (POST /api/alerts) with the +// decisionSet extension. The aggregator stores the set, and the alert +// engine sends Drew ONE push for the whole set whose tap opens the +// decisions page. +// +// Usage: +// bun run scripts/raise-decision-set.ts --payload +// +// The intake bearer is resolved BY NAME from Bitwarden Secrets +// Manager (`pm-aggregator.alerts-intake-token`, via src/secrets.ts) and +// is only ever sent to the aggregator as the Authorization header. The +// server's response carries the token-carrying page URL; this script +// deliberately does NOT print it (Drew reaches the page from the push; +// the URL is re-derivable from the store by anyone with laptop access). +// It prints only the set id and item/question counts. +// +// Env: ALERTS_INTAKE_URL (default http://127.0.0.1:4870). +// +// Re-raising the same setId is idempotent server-side: the existing +// set (and its token and resolutions) is returned unchanged. +import { readFile } from "node:fs/promises"; +import { resolveBwsSecret } from "../src/secrets.ts"; +import { validateDecisionSet } from "../src/decisions.ts"; + +const USAGE = "usage: raise-decision-set.ts --payload "; + +function usageError(message: string): never { + console.error(`raise-decision-set: ${message}`); + console.error(USAGE); + process.exit(2); +} + +// Unknown or duplicated arguments are usage errors, never silently +// ignored — same discipline as scripts/post-alert.ts (#7289). +function rejectUnknownArgs(): void { + const args = process.argv.slice(2); + const seen = new Set(); + for (let i = 0; i < args.length; i++) { + const token = args[i] as string; + if (token === "--payload") { + if (seen.has(token)) usageError("duplicate --payload"); + seen.add(token); + i++; // skip the value; arg() validates it + continue; + } + usageError(`unknown argument ${JSON.stringify(token)}`); + } +} +rejectUnknownArgs(); + +function arg(name: string): string | undefined { + const i = process.argv.indexOf(`--${name}`); + if (i < 0) return undefined; + const value = process.argv[i + 1]; + if (value === undefined || value === "" || value.startsWith("--")) { + usageError(`--${name} requires a value that is not a flag`); + } + return value; +} + +async function main(): Promise { + const payloadPath = arg("payload"); + if (!payloadPath) { + console.error(USAGE); + process.exit(2); + } + let raw: unknown; + try { + raw = JSON.parse(await readFile(payloadPath, "utf8")); + } catch (err) { + console.error(`raise-decision-set: cannot read/parse payload: ${err instanceof Error ? err.message : err}`); + process.exit(1); + } + const v = validateDecisionSet(raw); + if (!v.ok) { + console.error(`raise-decision-set: payload invalid: ${v.error}`); + process.exit(1); + } + const set = v.value; + const questionCount = set.items.reduce((n, i) => n + i.questions.length, 0); + const token = await resolveBwsSecret("pm-aggregator.alerts-intake-token"); + if (!token) { + console.error("raise-decision-set: intake token unavailable (bws secret pm-aggregator.alerts-intake-token)"); + process.exit(1); + } + const base = (process.env.ALERTS_INTAKE_URL ?? "http://127.0.0.1:4870").replace(/\/+$/, ""); + const res = await fetch(`${base}/api/alerts`, { + method: "POST", + headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, + body: JSON.stringify({ + source: "decisions-ledger", + key: `decision-set:${set.setId}`, + severity: "info", + title: set.title, + body: `${set.items.length} items, ${questionCount} questions — raised for the decisions page.`, + decisionSet: set, + }), + signal: AbortSignal.timeout(30_000), + }); + if (!res.ok) { + const text = await res.text().catch(() => ""); + console.error(`raise-decision-set: intake returned HTTP ${res.status}: ${text.slice(0, 300)}`); + process.exit(1); + } + const out = (await res.json().catch(() => null)) as { decisionSet?: { setId?: string } } | null; + if (!out?.decisionSet?.setId) { + console.error("raise-decision-set: intake response carried no decisionSet (extension not applied)"); + process.exit(1); + } + console.log( + `raised decision set ${out.decisionSet.setId}: ${set.items.length} items, ${questionCount} questions (page URL withheld — it rides the push)`, + ); +} + +await main(); diff --git a/pm-stack/aggregator/src/alerts.ts b/pm-stack/aggregator/src/alerts.ts index d6acdd8f5e..37f3fc93f1 100644 --- a/pm-stack/aggregator/src/alerts.ts +++ b/pm-stack/aggregator/src/alerts.ts @@ -35,6 +35,7 @@ import { } from "./notifications.ts"; import { JsonlNotificationHistory, type NotificationHistoryStore } from "./notification-history.ts"; import { getNeedsDrew } from "./needs-drew.ts"; +import { getDecisionSet } from "./decisions.ts"; // --- Shapes ---------------------------------------------------------------- @@ -1048,6 +1049,21 @@ async function runDashboardNotificationTick( ); } } + // #8766: a decision-set candidate pushes with the set page as + // its URL — the per-set token rides the URL; the page itself is + // the answer surface, so no `answer` payload is attached. + if (candidate.decisionSet) { + try { + const set = await getDecisionSet(cfg.decisionsFile, candidate.decisionSet.setId); + if (set) { + payload.url = `${cfg.publicOrigin}/decisions/${encodeURIComponent(set.setId)}?t=${set.token}`; + } + } catch (err) { + console.error( + `alerts engine: decision-set payload lookup failed (${err instanceof Error ? err.message : "error"})`, + ); + } + } const target: PushTarget = { endpoint: sub.endpoint, p256dh: sub.p256dh, auth: sub.auth }; const result = await push(target, payload); const outcome = result.ok ? "sent" : result.gone ? "gone" : "error"; diff --git a/pm-stack/aggregator/src/config.ts b/pm-stack/aggregator/src/config.ts index c264061763..32b450569e 100644 --- a/pm-stack/aggregator/src/config.ts +++ b/pm-stack/aggregator/src/config.ts @@ -63,6 +63,8 @@ export interface Config { notificationsFile: string; /** Needs-Drew question store (#8568): fleet workers blocked on Drew. */ needsDrewFile: string; + /** Decision-set store (#8766): batched decisions-page sets. */ + decisionsFile: string; /** Stack-health state written by the sentinel intake extension (#8568). */ stackHealthFile: string; /** Versioned item-history JSONL (#3981) the forecast contract @@ -186,6 +188,10 @@ export function loadConfig(env: Record = process.env env.PM_AGG_NEEDS_DREW_FILE, join(homedir(), ".local", "state", "pm-aggregator", "needs-drew.json"), ), + decisionsFile: s( + env.PM_AGG_DECISIONS_FILE, + join(homedir(), ".local", "state", "pm-aggregator", "decisions.json"), + ), stackHealthFile: s( env.PM_AGG_STACK_HEALTH_FILE, join(homedir(), ".local", "state", "pm-aggregator", "stack-health.json"), diff --git a/pm-stack/aggregator/src/decisions.ts b/pm-stack/aggregator/src/decisions.ts new file mode 100644 index 0000000000..356159f7a5 --- /dev/null +++ b/pm-stack/aggregator/src/decisions.ts @@ -0,0 +1,512 @@ +// Decision SETS (#8766, extending the #8568 notifications Phase 1 +// machinery): Drew answers batches of pending decisions on one page +// instead of one push per question. A set mirrors a group of items from +// the Muse-side decisions ledger (pending-questions.json) — the ledger +// stays the one source of truth; this file-backed store is the +// aggregator's presentation/working copy, exactly like the needs-drew +// question store in needs-drew.ts. Resolutions recorded here are +// published into fleet-feed.json's top-level `decisionResolutions` +// array by scripts/collect-fleet-feed.ts, and the dropped-thread +// catcher applies them to the ledger per question. +// +// Model: a set has items (one per ledger item); an item has questions +// (the ledger item's questions, in order). A question's `qid` is +// `#<1-based index>` so a resolution maps back to the ledger +// question by index. Each question resolves at most once (first +// resolution wins, mirroring recordAnswer in needs-drew.ts): +// - answered: Drew picked an option and/or wrote free text. +// - deferred: Drew sent it back to the orchestrator, with a lean: +// "none" (plain defer), "skeptical" (leaning no), "approve" +// (leaning yes). +// 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 +// same trust model as the #8568 per-question answer token. +import { randomUUID } from "node:crypto"; +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; + +export type DeferLean = "none" | "skeptical" | "approve"; +export const DEFER_LEANS: readonly DeferLean[] = ["none", "skeptical", "approve"]; + +export function isDeferLean(value: unknown): value is DeferLean { + return typeof value === "string" && (DEFER_LEANS as readonly string[]).includes(value); +} + +export interface DecisionOption { + id: string; + label: string; +} + +export interface DecisionResolution { + kind: "answered" | "deferred"; + /** Answered only: the chosen option's id and its label at record time. */ + 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; + at: string; + via: string; +} + +export interface DecisionQuestion { + /** `#<1-based index>` — stable across the set's life. */ + qid: string; + question: string; + context?: string; + options: DecisionOption[]; + resolution?: DecisionResolution; +} + +export interface DecisionItem { + /** The decisions-ledger item id this mirrors. */ + ledgerId: string; + title: string; + /** Page grouping (e.g. "Goals census", "Issue rulings"). */ + group: string; + links: string[]; + questions: DecisionQuestion[]; +} + +export interface DecisionSet { + setId: string; + title: string; + /** Per-set page authority; minted at raise, never rotated. */ + token: string; + createdAt: string; + source: string; + items: DecisionItem[]; +} + +export interface DecisionQuestionInput { + question: string; + context?: string; + options: DecisionOption[]; +} + +export interface DecisionItemInput { + ledgerId: string; + title: string; + group?: string; + links: string[]; + questions: DecisionQuestionInput[]; +} + +export interface DecisionSetInput { + setId: string; + title: string; + items: DecisionItemInput[]; +} + +/** One resolution as published to the fleet feed for the catcher. */ +export interface DecisionResolutionRecord { + setId: string; + ledgerId: string; + qid: string; + /** 1-based index of the question within its ledger item. */ + questionIndex: number; + kind: "answered" | "deferred"; + optionId?: string; + optionLabel?: string; + freeText?: string; + lean?: DeferLean; + at: string; + via: string; +} + +export const DECISIONS_OPEN_MAX_AGE_MS = 7 * 24 * 60 * 60_000; + +/** Default decision-set store path (mirrors src/config.ts decisionsFile). */ +export function defaultDecisionsFile(env: Record = process.env): string { + const v = env.PM_AGG_DECISIONS_FILE?.trim(); + return v ? v : join(homedir(), ".local", "state", "pm-aggregator", "decisions.json"); +} + +const SET_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/; + +function isHttpUrl(s: string): boolean { + return /^https?:\/\//.test(s); +} + +/** Validate the intake `decisionSet` extension object (#8766 wire contract). */ +export function validateDecisionSet( + value: unknown, +): { ok: true; value: DecisionSetInput } | { ok: false; error: string } { + if (!value || typeof value !== "object" || Array.isArray(value)) { + return { ok: false, error: "decisionSet must be an object" }; + } + const b = value as Record; + const setId = typeof b.setId === "string" ? b.setId.trim() : ""; + if (!SET_ID_RE.test(setId)) return { ok: false, error: "decisionSet.setId required (slug, <= 80 chars)" }; + const title = typeof b.title === "string" ? b.title.trim() : ""; + if (!title) return { ok: false, error: "decisionSet.title required" }; + if (!Array.isArray(b.items) || b.items.length < 1 || b.items.length > 64) { + return { ok: false, error: "decisionSet.items must be an array of 1-64 entries" }; + } + const seenLedgerIds = new Set(); + const items: DecisionItemInput[] = []; + for (const rawItem of b.items) { + if (!rawItem || typeof rawItem !== "object" || Array.isArray(rawItem)) { + return { ok: false, error: "decisionSet.items entries must be objects" }; + } + const it = rawItem as Record; + const ledgerId = typeof it.ledgerId === "string" ? it.ledgerId.trim() : ""; + if (!ledgerId) return { ok: false, error: "decisionSet.items entries require ledgerId" }; + if (seenLedgerIds.has(ledgerId)) { + return { ok: false, error: `decisionSet.items duplicates ledgerId ${ledgerId}` }; + } + seenLedgerIds.add(ledgerId); + const itemTitle = typeof it.title === "string" ? it.title.trim() : ""; + if (!itemTitle) return { ok: false, error: `decisionSet item ${ledgerId} requires title` }; + if (it.group !== undefined && typeof it.group !== "string") { + return { ok: false, error: `decisionSet item ${ledgerId} group must be a string` }; + } + let links: string[] = []; + if (it.links !== undefined) { + if (!Array.isArray(it.links) || it.links.some((l) => typeof l !== "string" || !isHttpUrl(l))) { + return { ok: false, error: `decisionSet item ${ledgerId} links must be an array of http(s) URLs` }; + } + links = [...(it.links as string[])]; + } + if (!Array.isArray(it.questions) || it.questions.length < 1 || it.questions.length > 16) { + return { ok: false, error: `decisionSet item ${ledgerId} questions must be an array of 1-16 entries` }; + } + const questions: DecisionQuestionInput[] = []; + for (const rawQ of it.questions) { + if (!rawQ || typeof rawQ !== "object" || Array.isArray(rawQ)) { + return { ok: false, error: `decisionSet item ${ledgerId} questions entries must be objects` }; + } + const q = rawQ as Record; + const question = typeof q.question === "string" ? q.question.trim() : ""; + if (!question) return { ok: false, error: `decisionSet item ${ledgerId} has a question with no text` }; + if (q.context !== undefined && typeof q.context !== "string") { + return { ok: false, error: `decisionSet item ${ledgerId} question context 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) { + return { ok: false, error: `decisionSet item ${ledgerId} question options must be an array of 0-8 entries` }; + } + const options: DecisionOption[] = []; + const seenOptionIds = new Set(); + for (const rawO of q.options) { + if (!rawO || typeof rawO !== "object" || Array.isArray(rawO)) { + return { ok: false, error: `decisionSet item ${ledgerId} question options entries must be objects` }; + } + const o = rawO as Record; + const id = typeof o.id === "string" ? o.id.trim() : ""; + const label = typeof o.label === "string" ? o.label.trim() : ""; + if (!id || !label) { + return { ok: false, error: `decisionSet item ${ledgerId} question options entries require id and label` }; + } + if (seenOptionIds.has(id)) { + return { ok: false, error: `decisionSet item ${ledgerId} question duplicates option id ${id}` }; + } + seenOptionIds.add(id); + options.push({ id, label }); + } + questions.push({ + question, + ...(typeof q.context === "string" && q.context.trim() ? { context: q.context } : {}), + options, + }); + } + items.push({ + ledgerId, + title: itemTitle, + ...(typeof it.group === "string" && it.group.trim() ? { group: it.group.trim() } : {}), + links, + questions, + }); + } + return { ok: true, value: { setId, title, items } }; +} + +interface DecisionsFileShape { + version: 1; + sets: DecisionSet[]; +} + +async function readDecisionSets(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), + ); + } + return []; + } catch { + return []; // absent/corrupt store reads as empty; a raise rewrites it + } +} + +let decisionsWriteSeq = 0; +const decisionsChains = new Map>(); + +function serializeDecisions(file: string, fn: () => Promise): Promise { + const prev = decisionsChains.get(file) ?? Promise.resolve(); + const run = prev.then(fn, fn); + decisionsChains.set( + file, + run.catch(() => {}), + ); + return run; +} + +async function writeDecisionSets(file: string, sets: DecisionSet[]): 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)); + await rename(tmp, file); +} + +/** 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( + file: string, + input: DecisionSetInput, + source = "decisions-ledger", +): Promise { + return serializeDecisions(file, async () => { + const sets = await readDecisionSets(file); + const existing = sets.find((s) => s.setId === input.setId); + if (existing) return existing; + const set: DecisionSet = { + setId: input.setId, + title: input.title, + token: randomUUID(), + createdAt: new Date().toISOString(), + source, + items: input.items.map((item) => ({ + ledgerId: item.ledgerId, + title: item.title, + group: item.group ?? "Decisions", + links: item.links, + questions: item.questions.map((q, i) => ({ + qid: `${item.ledgerId}#${i + 1}`, + question: q.question, + ...(q.context !== undefined ? { context: q.context } : {}), + options: q.options, + })), + })), + }; + sets.push(set); + await writeDecisionSets(file, sets); + return set; + }); +} + +export async function getDecisionSet(file: string, setId: string): Promise { + const sets = await readDecisionSets(file); + return sets.find((s) => s.setId === setId) ?? null; +} + +export interface DecisionSubmission { + ledgerId: string; + qid: string; + kind: "answered" | "deferred"; + optionId?: string; + freeText?: string; + lean?: DeferLean; +} + +export interface SubmissionOutcome { + qid: string; + applied: boolean; + reason?: string; +} + +function findQuestion(set: DecisionSet, ledgerId: string, qid: string): DecisionQuestion | null { + const item = set.items.find((i) => i.ledgerId === ledgerId); + if (!item) return null; + return item.questions.find((q) => q.qid === qid) ?? null; +} + +/** + * Record a batch of per-question resolutions (one item's submit, or the + * page's submit-all). First resolution wins per question; each + * submission is judged independently and its outcome reported, so one + * stale or malformed entry never fails the batch. + */ +export async function recordResolutions( + file: string, + setId: string, + submissions: DecisionSubmission[], + via = "decisions-page", +): Promise<{ set: DecisionSet; outcomes: SubmissionOutcome[] } | null> { + return serializeDecisions(file, async () => { + const sets = await readDecisionSets(file); + const set = sets.find((s) => s.setId === setId); + if (!set) return null; + const outcomes: SubmissionOutcome[] = []; + const now = new Date().toISOString(); + for (const sub of submissions) { + const q = findQuestion(set, sub.ledgerId, sub.qid); + if (!q) { + outcomes.push({ qid: sub.qid, applied: false, reason: "unknown-question" }); + continue; + } + if (q.resolution) { + outcomes.push({ qid: sub.qid, applied: false, reason: "already-resolved" }); + continue; + } + if (sub.kind === "deferred") { + if (!isDeferLean(sub.lean)) { + outcomes.push({ qid: sub.qid, applied: false, reason: "bad-lean" }); + continue; + } + q.resolution = { kind: "deferred", lean: sub.lean, at: now, via }; + outcomes.push({ qid: sub.qid, applied: true }); + continue; + } + // kind === "answered" + const option = sub.optionId !== undefined ? q.options.find((o) => o.id === sub.optionId) : undefined; + if (sub.optionId !== undefined && !option) { + outcomes.push({ qid: sub.qid, applied: false, reason: "bad-option" }); + continue; + } + const freeText = typeof sub.freeText === "string" ? sub.freeText.trim() : ""; + if (!option && !freeText) { + outcomes.push({ qid: sub.qid, applied: false, reason: "empty-answer" }); + continue; + } + q.resolution = { + kind: "answered", + ...(option ? { optionId: option.id, optionLabel: option.label } : {}), + ...(freeText ? { freeText } : {}), + at: now, + via, + }; + outcomes.push({ qid: sub.qid, applied: true }); + } + if (outcomes.some((o) => o.applied)) await writeDecisionSets(file, sets); + return { set, outcomes }; + }); +} + +/** + * Defer every still-open question in scope (the page's bulk send-back): + * either the checked items, or all remaining questions in the set. + * Already-resolved questions are untouched. Returns the count deferred. + */ +export async function deferOpenQuestions( + file: string, + setId: string, + scope: { allRemaining: true } | { ledgerIds: string[] }, + lean: DeferLean, + via = "decisions-page", +): Promise<{ set: DecisionSet; deferredCount: 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(); + 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 }; + deferredCount++; + } + } + if (deferredCount > 0) await writeDecisionSets(file, sets); + return { set, deferredCount }; + }); +} + +export interface DecisionSetProgress { + items: number; + questions: number; + openQuestions: number; + answered: number; + deferred: number; + /** Items with at least one open question. */ + openItems: number; +} + +export function decisionSetProgress(set: DecisionSet): DecisionSetProgress { + let questions = 0; + let openQuestions = 0; + let answered = 0; + let deferred = 0; + let openItems = 0; + for (const item of set.items) { + let itemOpen = 0; + for (const q of item.questions) { + questions++; + if (!q.resolution) { + openQuestions++; + itemOpen++; + } else if (q.resolution.kind === "answered") answered++; + else deferred++; + } + if (itemOpen > 0) openItems++; + } + return { items: set.items.length, questions, openQuestions, answered, deferred, openItems }; +} + +export function isDecisionSetFullyResolved(set: DecisionSet): boolean { + return decisionSetProgress(set).openQuestions === 0; +} + +/** The page/submit-response view of what is still open, per item. */ +export function decisionSetOpenState(set: DecisionSet): { + setId: string; + remainingOpenQuestions: number; + items: Array<{ ledgerId: string; openQids: string[]; fullyResolved: boolean }>; +} { + const progress = decisionSetProgress(set); + return { + setId: set.setId, + remainingOpenQuestions: progress.openQuestions, + items: set.items.map((item) => { + const openQids = item.questions.filter((q) => !q.resolution).map((q) => q.qid); + return { ledgerId: item.ledgerId, openQids, fullyResolved: openQids.length === 0 }; + }), + }; +} + +/** Open sets (at least one unresolved question, younger than 7 days), oldest first. */ +export async function listOpenDecisionSets(file: string, now = Date.now()): Promise { + const sets = await readDecisionSets(file); + return sets + .filter((s) => !isDecisionSetFullyResolved(s) && now - Date.parse(s.createdAt) < DECISIONS_OPEN_MAX_AGE_MS) + .sort((a, b) => a.createdAt.localeCompare(b.createdAt)); +} + +/** Every recorded resolution across all sets, in raise order (the feed's + * `decisionResolutions` source for the dropped-thread catcher). */ +export async function listDecisionResolutions(file: string): Promise { + const sets = await readDecisionSets(file); + const out: DecisionResolutionRecord[] = []; + for (const set of sets) { + for (const item of set.items) { + item.questions.forEach((q, i) => { + if (!q.resolution) return; + const r = q.resolution; + out.push({ + setId: set.setId, + ledgerId: item.ledgerId, + qid: q.qid, + questionIndex: i + 1, + kind: r.kind, + ...(r.optionId !== undefined ? { optionId: r.optionId } : {}), + ...(r.optionLabel !== undefined ? { optionLabel: r.optionLabel } : {}), + ...(r.freeText !== undefined ? { freeText: r.freeText } : {}), + ...(r.lean !== undefined ? { lean: r.lean } : {}), + at: r.at, + via: r.via, + }); + }); + } + } + return out; +} diff --git a/pm-stack/aggregator/src/feed.ts b/pm-stack/aggregator/src/feed.ts index 4e098fd68f..98c7b662ec 100644 --- a/pm-stack/aggregator/src/feed.ts +++ b/pm-stack/aggregator/src/feed.ts @@ -146,6 +146,11 @@ export interface FleetFeed { * collector from the aggregator's needs-drew store; the fleet lane * consumes this to resume blocked workers. Absent in older feeds. */ answers?: FleetFeedAnswer[]; + /** #8766: Drew's per-question resolutions from the decisions page + * (answers AND defer-to-orchestrator records), read by the collector + * from the aggregator's decision-set store; the dropped-thread + * catcher applies them to the decisions ledger. Absent in older feeds. */ + decisionResolutions?: FleetFeedDecisionResolution[]; } export interface FleetFeedAnswer { @@ -156,6 +161,22 @@ export interface FleetFeedAnswer { via: string; } +export interface FleetFeedDecisionResolution { + setId: string; + ledgerId: string; + qid: string; + /** 1-based index of the question within its ledger item. */ + questionIndex: number; + kind: "answered" | "deferred"; + optionId?: string; + optionLabel?: string; + freeText?: string; + /** Deferred only: the lean recorded with the defer. */ + lean?: "none" | "skeptical" | "approve"; + at: string; + via: string; +} + export type FeedSectionStatus = "ok" | "error" | "skipped"; export interface FeedSectionCollectionStatus { diff --git a/pm-stack/aggregator/src/notifications.ts b/pm-stack/aggregator/src/notifications.ts index afc45f3f99..046bd45550 100644 --- a/pm-stack/aggregator/src/notifications.ts +++ b/pm-stack/aggregator/src/notifications.ts @@ -28,6 +28,7 @@ import type { HealthView } from "./health.ts"; import type { QuotaView, TierItem, TieredEntry } from "./model.ts"; import type { NotificationSendRow } from "./alerts.ts"; import type { NeedsDrewQuestion } from "./needs-drew.ts"; +import { decisionSetProgress, type DecisionSet } from "./decisions.ts"; import { SENTINEL_SERVICE_IDS, type StackHealthRecord } from "./stack-health.ts"; export const NOTIFICATION_CLASS_DEFAULTS: Record = { @@ -155,6 +156,10 @@ export interface NotificationCandidate { /** #8568: a raised needs-Drew question rides its candidate so the * push payload can carry tappable answer actions. */ needsDrew?: { ledgerId: string; question: string; options: Array<{ id: string; label: string }> }; + /** #8766: a decision set rides its candidate so the push payload can + * point at the token-carrying decisions page (no tappable answers — + * the page is the answer surface). */ + decisionSet?: { setId: string }; } export interface NotificationHistoryEntry { @@ -190,6 +195,8 @@ export interface NotificationSnapshot { drewActivity?: Array<{ objectRef: string; at: string }>; /** #8568: open needs-Drew questions (unanswered, < 7 days old). */ needsDrewRaised?: NeedsDrewQuestion[]; + /** #8766: open decision sets (at least one unresolved question). */ + decisionSets?: DecisionSet[]; /** #8568: sentinel services currently down. */ stackHealthDown?: StackHealthRecord[]; /** #8568: full sentinel state map (up AND down) — decides when the @@ -489,6 +496,28 @@ export function buildNotificationCandidates(snapshot: NotificationSnapshot, now ); } + // #8766: open decision sets — ONE push per set, never one per item + // or question. The fingerprint is the set's raise time alone, so + // resolutions landing later do not re-push; a fully resolved set + // stops candidating (listOpenDecisionSets already filtered it out). + for (const set of snapshot.decisionSets ?? []) { + const progress = decisionSetProgress(set); + candidates.push( + candidate({ + class: "needs-drew", + objectRef: `decision-set:${set.setId}`, + title: `${progress.openItems} decision${progress.openItems === 1 ? "" : "s"} waiting for you`, + body: `${set.title} — ${progress.openQuestions} question${progress.openQuestions === 1 ? "" : "s"} open. Tap to open the decisions page.`, + url: `/decisions/${encodeURIComponent(set.setId)}`, + observedAt: set.createdAt, + breakthrough: true, + actedRefs: [`decision-set:${set.setId}`], + state: { raisedAt: set.createdAt }, + decisionSet: { setId: set.setId }, + }), + ); + } + // #8568: sentinel-reported down services. for (const svc of snapshot.stackHealthDown ?? []) { candidates.push( diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 014abbbff1..3a0d4bd9f5 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -65,6 +65,20 @@ import { type NeedsDrewCensus, type NeedsDrewQuestion, } from "./needs-drew.ts"; +import { + decisionSetOpenState, + decisionSetProgress, + deferOpenQuestions, + getDecisionSet, + isDeferLean, + listOpenDecisionSets, + raiseDecisionSet, + recordResolutions, + validateDecisionSet, + type DecisionItem, + type DecisionSet, + type DecisionSubmission, +} from "./decisions.ts"; import { listStackHealthDown, readStackHealthStates, setStackHealth, validateStackHealth } from "./stack-health.ts"; import { buildHealth, @@ -650,6 +664,209 @@ function renderAnswerForbidden(): string { `; } +// --- Decision sets (#8766) ------------------------------------------------- + +/** The token-carrying decisions-page URL for a raised set. */ +function decisionsPageUrl(set: DecisionSet): string { + return `${cfg.publicOrigin}/decisions/${encodeURIComponent(set.setId)}?t=${set.token}`; +} + +const DECISIONS_PAGE_STYLE = `${ANSWER_PAGE_STYLE}`; + +/** Render GET /decisions/. The caller has already verified the + * token; the 403 shape renders nothing about the set. Only open + * questions are interactive; resolved ones show as a compact recorded + * line, and an item whose questions are all resolved is not rendered + * at all — it has gone away, per the spec. */ +function renderDecisionsPage(set: DecisionSet): string { + const progress = decisionSetProgress(set); + const groups: string[] = []; + for (const item of set.items) if (!groups.includes(item.group)) groups.push(item.group); + const itemCard = (item: DecisionItem): string => { + const open = item.questions.filter((q) => !q.resolution); + if (open.length === 0) return ""; + const links = item.links + .filter((l) => /^https?:\/\//.test(l)) + .map((l) => `${esc(l)}`) + .join(""); + const resolvedLines = item.questions + .filter((q) => q.resolution) + .map((q) => { + 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)}` : ""}`; + return `
✓ ${esc(q.question)} — ${what}
`; + }) + .join(""); + const questionBlocks = open + .map((q) => { + const radios = q.options + .map( + (o) => + ``, + ) + .join(""); + return `
+

${esc(q.question)}

+${q.context ? `

${esc(q.context)}

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

${esc(item.title)}

+${links ? `` : ""} +${resolvedLines} +${questionBlocks} + +
`; + }; + const body = groups + .map((g) => { + const cards = set.items + .filter((i) => i.group === g) + .map(itemCard) + .join(""); + return cards ? `
${esc(g)}
${cards}` : ""; + }) + .join(""); + const caughtUp = progress.openQuestions === 0; + 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.

+${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:

+ + + +
+

+ +
`; +} + +function renderDecisionsForbidden(): string { + return ` +Not available — PM Stack${ANSWER_PAGE_STYLE} +

Decisions link not available

+

This decisions link is unknown or its token does not match. Nothing about the set is shown without the correct link.

+
`; +} + + /** The PWA manifest (#3315 slice a, landed with #3676): start_url is * the attention view per the design; icons incl. maskable + iOS. */ const PWA_MANIFEST = { @@ -2501,8 +2718,8 @@ async function handler(req: Request): Promise { if (!parsed.ok) return json({ error: parsed.error }, 400); const { incident, created } = await store.postIncident(parsed.value); const status = created ? 201 : 200; - // #8568 producer extensions: exactly one of needsDrew / - // stackHealth may ride an incident post. The incident insert + // #8568/#8766 producer extensions: exactly one of needsDrew / + // stackHealth / decisionSet may ride an incident post. The incident insert // above is unchanged; a VALIDATION failure of an extension is a // 400 (the poster's bug should be loud at the poster), while a // store failure is logged and never fails the incident post. @@ -2512,8 +2729,9 @@ async function handler(req: Request): Promise { : {}; const hasNeedsDrew = ext.needsDrew !== undefined; const hasStackHealth = ext.stackHealth !== undefined; - if (hasNeedsDrew && hasStackHealth) { - return json({ error: "needsDrew and stackHealth are mutually exclusive" }, 400); + const hasDecisionSet = ext.decisionSet !== undefined; + if ([hasNeedsDrew, hasStackHealth, hasDecisionSet].filter(Boolean).length > 1) { + return json({ error: "needsDrew, stackHealth and decisionSet extensions are mutually exclusive" }, 400); } if (hasNeedsDrew) { const v = validateNeedsDrew(ext.needsDrew); @@ -2548,6 +2766,23 @@ async function handler(req: Request): Promise { } return json({ incident, created }, status); } + if (hasDecisionSet) { + const v = validateDecisionSet(ext.decisionSet); + if (!v.ok) return json({ error: v.error }, 400); + try { + const set = await raiseDecisionSet(cfg.decisionsFile, v.value, parsed.value.source); + requestAlertTick(); + return json( + { incident, created, decisionSet: { setId: set.setId, pageUrl: decisionsPageUrl(set) } }, + status, + ); + } catch (err) { + console.error( + `alerts intake: decisionSet raise failed (${err instanceof Error ? err.message : "error"})`, + ); + return json({ incident, created }, status); + } + } return json({ incident, created }, status); } catch (err) { return json({ error: `invalid incident: ${err instanceof Error ? err.message : err}` }, 400); @@ -2607,6 +2842,97 @@ async function handler(req: Request): Promise { if (!item || !token || token !== item.token) return html(renderAnswerForbidden(), 403); return html(renderAnswerPage(item)); } + // --- Decision sets (#8766) ------------------------------------------- + const decisionsPageMatch = /^\/decisions\/([^/]+)$/.exec(path); + if (req.method === "GET" && decisionsPageMatch) { + const setId = decodePathSegment(decisionsPageMatch[1]); + const token = url.searchParams.get("t") ?? ""; + const set = setId === null ? null : await getDecisionSet(cfg.decisionsFile, setId).catch(() => null); + // Unknown set or token mismatch: 403, and the set is never rendered + // — the per-set token is the only authority here. + if (!set || !token || token !== set.token) return html(renderDecisionsForbidden(), 403); + return html(renderDecisionsPage(set)); + } + const decisionsSubmitMatch = /^\/api\/decisions\/([^/]+)\/submit$/.exec(path); + if (req.method === "POST" && decisionsSubmitMatch) { + const setId = decodePathSegment(decisionsSubmitMatch[1]); + if (setId === null) return json({ error: "bad setId" }, 400); + let body: { token?: unknown; submissions?: unknown }; + try { + body = (await readJsonBody(req)) as typeof body; + } catch { + return json({ error: "invalid submit 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); + } + 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); + if (!result) return json({ error: "unknown set" }, 404); + return json({ outcomes: result.outcomes, ...decisionSetOpenState(result.set) }); + } + const decisionsDeferMatch = /^\/api\/decisions\/([^/]+)\/defer$/.exec(path); + 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 }; + try { + body = (await readJsonBody(req)) as typeof body; + } catch { + return json({ error: "invalid defer 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); + } + if (!isDeferLean(body.lean)) { + return json({ error: "lean must be none|skeptical|approve" }, 400); + } + 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 deferOpenQuestions( + cfg.decisionsFile, + setId, + all ? { allRemaining: true as const } : { ledgerIds }, + body.lean, + ); + if (!result) return json({ error: "unknown set" }, 404); + return json({ deferredCount: result.deferredCount, ...decisionSetOpenState(result.set) }); + } const alertActionMatch = /^\/api\/alerts\/([\w-]+)\/(ack|close)$/.exec(path); if (req.method === "POST" && alertActionMatch) { const id = alertActionMatch[1]; @@ -2921,7 +3247,7 @@ if (source.ingestSnapshots) { // The alert throat's engine (#3676): the ~60s delivery/escalation // tick (live mode only, fail-soft — see src/alerts.ts). startAlertEngine(cfg, async (): Promise => { - const [attention, quota, health, actions, comments, needsDrewRaised, stackHealthDown, stackHealthStates] = + const [attention, quota, health, actions, comments, needsDrewRaised, decisionSets, stackHealthDown, stackHealthStates] = await Promise.all([ attentionContext(), source.quota().catch(() => emptyQuotaView()), @@ -2929,6 +3255,7 @@ startAlertEngine(cfg, async (): Promise => { actionsStore.all().catch(() => []), commentsStore.all().catch(() => []), listOpenNeedsDrew(cfg.needsDrewFile).catch(() => []), + listOpenDecisionSets(cfg.decisionsFile).catch(() => []), listStackHealthDown(cfg.stackHealthFile).catch(() => []), readStackHealthStates(cfg.stackHealthFile).catch(() => ({})), ]); @@ -2943,6 +3270,7 @@ startAlertEngine(cfg, async (): Promise => { drewActivity, soleDoorPoolIds: deriveSoleDoorPoolIds(quota), needsDrewRaised, + decisionSets, stackHealthDown, stackHealthStates, }; diff --git a/pm-stack/aggregator/test/decisions.test.ts b/pm-stack/aggregator/test/decisions.test.ts new file mode 100644 index 0000000000..e98e4f5f1c --- /dev/null +++ b/pm-stack/aggregator/test/decisions.test.ts @@ -0,0 +1,184 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + decisionSetOpenState, + decisionSetProgress, + deferOpenQuestions, + getDecisionSet, + isDecisionSetFullyResolved, + listDecisionResolutions, + listOpenDecisionSets, + raiseDecisionSet, + recordResolutions, + validateDecisionSet, + type DecisionSetInput, +} from "../src/decisions.ts"; + +let dir: string; +let file: string; + +beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), "decisions-test-")); + file = join(dir, "decisions.json"); +}); + +afterEach(async () => { + await rm(dir, { recursive: true, force: true }); +}); + +function sampleInput(setId = "set-test-1"): DecisionSetInput { + return { + setId, + title: "Test set", + items: [ + { + ledgerId: "item-a", + title: "Item A", + group: "Group 1", + links: ["https://github.com/developing-today/code/issues/1"], + questions: [ + { + question: "A Q1?", + context: "context a1", + options: [ + { id: "opt-1", label: "Yes" }, + { id: "opt-2", label: "No" }, + ], + }, + { question: "A Q2 (free text only)?", options: [] }, + ], + }, + { + ledgerId: "item-b", + title: "Item B", + links: [], + questions: [{ question: "B Q1?", options: [{ id: "opt-1", label: "Go" }] }], + }, + ], + }; +} + +describe("validateDecisionSet (#8766)", () => { + test("accepts a well-formed set, including a zero-option question", () => { + const v = validateDecisionSet(sampleInput()); + expect(v.ok).toBe(true); + }); + + test("rejects duplicate ledgerIds and duplicate option ids", () => { + const dup = sampleInput(); + dup.items.push({ ...dup.items[0]! }); + expect(validateDecisionSet(dup).ok).toBe(false); + const dupOpt = sampleInput(); + dupOpt.items[0]!.questions[0]!.options.push({ id: "opt-1", label: "Again" }); + expect(validateDecisionSet(dupOpt).ok).toBe(false); + }); + + test("rejects a bad setId and an item with no questions", () => { + expect(validateDecisionSet({ ...sampleInput(), setId: "has space" }).ok).toBe(false); + const noQ = sampleInput(); + noQ.items[0]!.questions = []; + expect(validateDecisionSet(noQ).ok).toBe(false); + }); + + test("rejects non-http links", () => { + const bad = sampleInput(); + bad.items[0]!.links = ["javascript:alert(1)"]; + expect(validateDecisionSet(bad).ok).toBe(false); + }); +}); + +describe("decision set store (#8766)", () => { + test("raise assigns qids by 1-based index and a token; re-raise is idempotent", async () => { + const set = await raiseDecisionSet(file, sampleInput()); + expect(set.token.length).toBeGreaterThan(10); + expect(set.items[0]!.questions.map((q) => q.qid)).toEqual(["item-a#1", "item-a#2"]); + expect(set.items[0]!.group).toBe("Group 1"); + expect(set.items[1]!.group).toBe("Decisions"); + const again = await raiseDecisionSet(file, { ...sampleInput(), title: "Changed title" }); + expect(again.token).toBe(set.token); + expect(again.title).toBe("Test set"); + }); + + test("partial submit: a subset of an item's questions resolves, the rest stay open", async () => { + await raiseDecisionSet(file, sampleInput()); + const res = await recordResolutions(file, "set-test-1", [ + { ledgerId: "item-a", qid: "item-a#1", kind: "answered", optionId: "opt-2" }, + ]); + expect(res?.outcomes).toEqual([{ qid: "item-a#1", applied: true }]); + const state = decisionSetOpenState(res!.set); + expect(state.remainingOpenQuestions).toBe(2); + expect(state.items.find((i) => i.ledgerId === "item-a")?.openQids).toEqual(["item-a#2"]); + expect(state.items.find((i) => i.ledgerId === "item-a")?.fullyResolved).toBe(false); + const progress = decisionSetProgress(res!.set); + expect(progress.answered).toBe(1); + expect(isDecisionSetFullyResolved(res!.set)).toBe(false); + }); + + test("first resolution wins; bad option and empty answer are skipped per-submission", async () => { + await raiseDecisionSet(file, sampleInput()); + const res = await recordResolutions(file, "set-test-1", [ + { ledgerId: "item-a", qid: "item-a#1", kind: "answered", optionId: "nope" }, + { ledgerId: "item-a", qid: "item-a#2", kind: "answered" }, + { ledgerId: "item-b", qid: "item-b#1", kind: "answered", optionId: "opt-1" }, + { ledgerId: "item-b", qid: "item-b#1", kind: "deferred", lean: "approve" }, + { ledgerId: "ghost", qid: "ghost#1", kind: "answered", optionId: "opt-1" }, + ]); + expect(res?.outcomes).toEqual([ + { qid: "item-a#1", applied: false, reason: "bad-option" }, + { qid: "item-a#2", applied: false, reason: "empty-answer" }, + { qid: "item-b#1", applied: true }, + { qid: "item-b#1", applied: false, reason: "already-resolved" }, + { qid: "ghost#1", applied: false, reason: "unknown-question" }, + ]); + }); + + test("defer records the lean; free-text-only questions answer with text", async () => { + await raiseDecisionSet(file, sampleInput()); + const res = await recordResolutions(file, "set-test-1", [ + { ledgerId: "item-a", qid: "item-a#1", kind: "deferred", lean: "skeptical" }, + { ledgerId: "item-a", qid: "item-a#2", kind: "answered", freeText: "Rockbot was the 2024 prototype" }, + ]); + expect(res?.outcomes.every((o) => o.applied)).toBe(true); + const records = await listDecisionResolutions(file); + expect(records).toHaveLength(2); + expect(records[0]).toMatchObject({ ledgerId: "item-a", questionIndex: 1, kind: "deferred", lean: "skeptical" }); + expect(records[1]).toMatchObject({ + ledgerId: "item-a", + questionIndex: 2, + kind: "answered", + freeText: "Rockbot was the 2024 prototype", + }); + }); + + test("bulk defer: checked items only, then all remaining; resolved questions untouched", async () => { + await raiseDecisionSet(file, sampleInput()); + await recordResolutions(file, "set-test-1", [ + { ledgerId: "item-a", qid: "item-a#1", kind: "answered", optionId: "opt-1" }, + ]); + const checked = await deferOpenQuestions(file, "set-test-1", { ledgerIds: ["item-b"] }, "none"); + expect(checked?.deferredCount).toBe(1); + // item-a#2 is still open: it was not in the checked scope. + expect(decisionSetOpenState(checked!.set).remainingOpenQuestions).toBe(1); + const rest = await deferOpenQuestions(file, "set-test-1", { allRemaining: true }, "approve"); + expect(rest?.deferredCount).toBe(1); + expect(isDecisionSetFullyResolved(rest!.set)).toBe(true); + const records = await listDecisionResolutions(file); + // The answered question kept its answer (not overwritten by defers). + expect(records.find((r) => r.qid === "item-a#1")?.kind).toBe("answered"); + expect(records.find((r) => r.qid === "item-a#2")?.lean).toBe("approve"); + }); + + test("listOpenDecisionSets drops fully resolved and 7-day-old sets", async () => { + await raiseDecisionSet(file, sampleInput("set-open")); + await raiseDecisionSet(file, sampleInput("set-done")); + await deferOpenQuestions(file, "set-done", { allRemaining: true }, "none"); + const open = await listOpenDecisionSets(file); + expect(open.map((s) => s.setId)).toEqual(["set-open"]); + const future = await listOpenDecisionSets(file, Date.now() + 8 * 24 * 60 * 60_000); + expect(future).toEqual([]); + expect(await getDecisionSet(file, "set-open")).not.toBeNull(); + expect(await getDecisionSet(file, "nope")).toBeNull(); + }); +});