diff --git a/pm-stack/aggregator/scripts/submit-decision-set.ts b/pm-stack/aggregator/scripts/submit-decision-set.ts index ccadbfd94b..9b02e601c0 100644 --- a/pm-stack/aggregator/scripts/submit-decision-set.ts +++ b/pm-stack/aggregator/scripts/submit-decision-set.ts @@ -18,7 +18,7 @@ // credential it is. // // Usage: -// bun run scripts/submit-decision-set.ts --payload +// bun run scripts/submit-decision-set.ts --payload [--refresh] // // The intake bearer token is resolved BY NAME from Bitwarden Secrets // Manager (`pm-aggregator.alerts-intake-token`, via src/secrets.ts) @@ -29,6 +29,17 @@ // Re-submitting the same setId is idempotent server-side: the existing // set (and its token and resolutions) is returned unchanged with // "created": false, and no second push is sent. +// +// --refresh (#9354) is the exception, for STANDING ledger-mirror sets +// only (e.g. the standing open-questions set): it sends +// `refresh: true` in the envelope, and the server replaces the set's +// title/items from the payload while preserving its token, createdAt +// and original source, carrying resolutions (and, for unchanged +// question wording, version history) over by qid. The response then +// carries "refreshed": true (passed through on stdout here), sends no +// push, and logs no set.created event. Do not use it for ordinary +// sets: for them a re-post is deliberately a duplicate, not an edit. +// Refreshing a setId that does not exist yet is a normal create. import { readFile } from "node:fs/promises"; import { resolveBwsSecret } from "../src/secrets.ts"; import { validateDecisionSet, withGeneratedSetId } from "../src/decisions.ts"; @@ -54,6 +65,11 @@ function rejectUnknownArgs(): void { i++; // skip the value; arg() validates it continue; } + if (token === "--refresh") { + if (seen.has(token)) usageError("duplicate --refresh"); + seen.add(token); + continue; + } usageError(`unknown argument ${JSON.stringify(token)}`); } } @@ -96,11 +112,12 @@ async function main(): Promise { console.error("submit-decision-set: intake token unavailable (bws secret pm-aggregator.alerts-intake-token)"); process.exit(1); } + const refresh = process.argv.includes("--refresh"); const base = (process.env.ALERTS_INTAKE_URL ?? "http://127.0.0.1:4870").replace(/\/+$/, ""); const res = await fetch(`${base}/api/decision-sets`, { method: "POST", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, - body: JSON.stringify({ decisionSet: v.value, source: "decisions-ledger" }), + body: JSON.stringify({ decisionSet: v.value, source: "decisions-ledger", ...(refresh ? { refresh: true } : {}) }), signal: AbortSignal.timeout(30_000), }); if (!res.ok) { @@ -108,14 +125,23 @@ async function main(): Promise { console.error(`submit-decision-set: submit API returned HTTP ${res.status}: ${text.slice(0, 300)}`); process.exit(1); } - const out = (await res.json().catch(() => null)) as { setId?: string; pageUrl?: string; created?: boolean } | null; + const out = (await res.json().catch(() => null)) as + | { setId?: string; pageUrl?: string; created?: boolean; refreshed?: boolean } + | null; if (!out?.setId || !out?.pageUrl) { console.error("submit-decision-set: submit API response carried no setId/pageUrl"); process.exit(1); } // The one place the token page URL is printed: the authenticated // submitter's own stdout, as the API contract promises. - console.log(JSON.stringify({ setId: out.setId, pageUrl: out.pageUrl, created: out.created ?? false })); + console.log( + JSON.stringify({ + setId: out.setId, + pageUrl: out.pageUrl, + created: out.created ?? false, + ...(out.refreshed !== undefined ? { refreshed: out.refreshed } : {}), + }), + ); } await main(); diff --git a/pm-stack/aggregator/src/decisions.ts b/pm-stack/aggregator/src/decisions.ts index 277dd4c0ae..af72e9b169 100644 --- a/pm-stack/aggregator/src/decisions.ts +++ b/pm-stack/aggregator/src/decisions.ts @@ -606,6 +606,66 @@ async function writeDecisionSets(file: string, sets: DecisionSet[]): Promise#<1-based index>`, + * and every question starts its version history at v1 (or keeps the + * history the raiser supplied). When `existingByQid` is given (the + * refresh path), a question carries its prior resolution over by qid, + * and — when its wording is identical to the prior question with the + * same qid — its prior versions/currentVersion too. */ +function mapDecisionItems( + input: DecisionSetInput, + stamp: string, + existingByQid?: Map, +): DecisionItem[] { + return input.items.map((item) => ({ + ledgerId: item.ledgerId, + title: item.title, + group: item.group ?? "Decisions", + ...(item.order !== undefined ? { order: item.order } : {}), + links: item.links, + questions: item.questions.map((q, i) => { + const qid = `${item.ledgerId}#${i + 1}`; + const prior = existingByQid?.get(qid); + const carryVersions = + prior && prior.question === q.question && prior.versions && prior.versions.length ? prior : undefined; + // Versioning backfill (#9335): every raised question starts + // its version history at v1 (or keeps the history the raiser + // supplied); the current pointer is the newest version. + const versions: DecisionQuestionVersion[] = carryVersions + ? (carryVersions.versions as DecisionQuestionVersion[]) + : q.versions && q.versions.length + ? q.versions + : [ + { + version: 1, + question: q.question, + ...(q.context !== undefined ? { context: q.context } : {}), + ...(q.description !== undefined ? { description: q.description } : {}), + editedAt: stamp, + note: "initial version", + }, + ]; + return { + qid, + question: q.question, + ...(q.context !== undefined ? { context: q.context } : {}), + ...(q.description !== undefined ? { description: q.description } : {}), + ...(q.infoProvided !== undefined ? { infoProvided: q.infoProvided } : {}), + ...(q.mode !== undefined ? { mode: q.mode } : {}), + ...(q.tags !== undefined ? { tags: q.tags } : {}), + ...(q.recommendedOptionIds !== undefined ? { recommendedOptionIds: q.recommendedOptionIds } : {}), + ...(q.order !== undefined ? { order: q.order } : {}), + ...(q.group !== undefined ? { group: q.group } : {}), + options: q.options, + versions, + currentVersion: carryVersions?.currentVersion ?? Math.max(...versions.map((v) => v.version)), + ...(prior?.resolution ? { resolution: prior.resolution } : {}), + }; + }), + })); +} + /** 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( @@ -624,46 +684,7 @@ export async function raiseDecisionSet( token: randomUUID(), createdAt, source, - items: input.items.map((item) => ({ - ledgerId: item.ledgerId, - title: item.title, - group: item.group ?? "Decisions", - ...(item.order !== undefined ? { order: item.order } : {}), - links: item.links, - questions: item.questions.map((q, i) => { - // Versioning backfill (#9335): every raised question starts - // its version history at v1 (or keeps the history the raiser - // supplied); the current pointer is the newest version. - const versions: DecisionQuestionVersion[] = - q.versions && q.versions.length - ? q.versions - : [ - { - version: 1, - question: q.question, - ...(q.context !== undefined ? { context: q.context } : {}), - ...(q.description !== undefined ? { description: q.description } : {}), - editedAt: createdAt, - note: "initial version", - }, - ]; - return { - qid: `${item.ledgerId}#${i + 1}`, - question: q.question, - ...(q.context !== undefined ? { context: q.context } : {}), - ...(q.description !== undefined ? { description: q.description } : {}), - ...(q.infoProvided !== undefined ? { infoProvided: q.infoProvided } : {}), - ...(q.mode !== undefined ? { mode: q.mode } : {}), - ...(q.tags !== undefined ? { tags: q.tags } : {}), - ...(q.recommendedOptionIds !== undefined ? { recommendedOptionIds: q.recommendedOptionIds } : {}), - ...(q.order !== undefined ? { order: q.order } : {}), - ...(q.group !== undefined ? { group: q.group } : {}), - options: q.options, - versions, - currentVersion: Math.max(...versions.map((v) => v.version)), - }; - }), - })), + items: mapDecisionItems(input, createdAt), }; sets.push(set); await writeDecisionSets(file, sets); @@ -671,6 +692,60 @@ export async function raiseDecisionSet( }); } +/** + * Refresh a standing decision set (#9354): the explicit opt-in edit + * path for ledger-mirror sets (e.g. the standing open-questions set), + * where raiseDecisionSet's create-only rule would freeze the contents + * forever. An existing set keeps its setId, token, createdAt and + * original source; its title and items are replaced from the input + * (mapped exactly as raise maps them). A question's resolution + * carries over when the refreshed payload still carries its qid, and + * its versions/currentVersion carry over too when the question text + * is identical. Questions absent from the new payload are dropped + * (with any resolution they carried). With no existing setId this + * behaves exactly like raiseDecisionSet. + */ +export async function refreshDecisionSet( + file: string, + input: DecisionSetInput, + source = "decisions-ledger", +): Promise { + return serializeDecisions(file, async () => { + const sets = await readDecisionSets(file); + const idx = sets.findIndex((s) => s.setId === input.setId); + if (idx < 0) { + const createdAt = new Date().toISOString(); + const set: DecisionSet = { + setId: input.setId, + title: input.title, + token: randomUUID(), + createdAt, + source, + items: mapDecisionItems(input, createdAt), + }; + sets.push(set); + await writeDecisionSets(file, sets); + return set; + } + const existing = sets[idx] as DecisionSet; + const existingByQid = new Map(); + for (const item of existing.items) { + for (const q of item.questions) existingByQid.set(q.qid, q); + } + const refreshed: DecisionSet = { + setId: existing.setId, + title: input.title, + token: existing.token, + createdAt: existing.createdAt, + source: existing.source, + items: mapDecisionItems(input, new Date().toISOString(), existingByQid), + }; + sets[idx] = refreshed; + await writeDecisionSets(file, sets); + return refreshed; + }); +} + export async function getDecisionSet(file: string, setId: string): Promise { const sets = await readDecisionSets(file); return sets.find((s) => s.setId === setId) ?? null; diff --git a/pm-stack/aggregator/src/pages.ts b/pm-stack/aggregator/src/pages.ts index 47007e73ed..3519a10767 100644 --- a/pm-stack/aggregator/src/pages.ts +++ b/pm-stack/aggregator/src/pages.ts @@ -99,7 +99,10 @@ export const PAGES: PageDef[] = [ blurb: "Every raised decision set (#8867): new today, this week, or all — with open-question counts. Each row opens the set's own page.", group: "overview", - nav: "dropdown", + // Promoted to primary in #9354 (Drew 2026-11-13): at dropdown + // tier the index was invisible in practice — no visible nav + // anchor on any page Drew uses. + nav: "primary", }, { id: "board", diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index 6b920fbe30..89eec4c006 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -131,6 +131,7 @@ import { blockedSummary, depthLayout, hasGraphEdges } from "./graph.ts"; import { EPIC_GRAPH_DEFAULT_CAP, epicGraph, epicSelector } from "./epic-graph.ts"; import { type AuthorIdentity } from "./registry.ts"; import type { SearchResult } from "./search-view.ts"; +import type { DecisionSetSummary } from "./decisions.ts"; import { dnsAnchor } from "./search-view.ts"; export function esc(s: unknown): string { @@ -3141,6 +3142,54 @@ const BULK_SCRIPT = ``; +/** + * The live "Questions" section (#9354): the open decision sets from + * the decision-set store, newest first, each linking to its own + * token page via `pageUrlFor`. Pure HTML from already-computed + * summaries — no I/O here, so tests render it directly. + * summaries === null means the store could not be read: the section + * says "unavailable" rather than rendering a confident zero (the + * needsDrewCensusHtml pattern). summaries === undefined means the + * caller predates the section and it is omitted entirely. + * Fully-resolved sets are excluded here as well as by callers, so + * the counts can never include a settled set. + */ +const QUESTIONS_STAMP = new Intl.DateTimeFormat("en-US", { + timeZone: "America/Chicago", + year: "numeric", + month: "short", + day: "numeric", + hour: "numeric", + minute: "2-digit", + timeZoneName: "short", +}); + +export function questionsSectionHtml( + summaries: DecisionSetSummary[] | null | undefined, + pageUrlFor: (summary: DecisionSetSummary) => string, +): string { + if (summaries === undefined) return ""; + const allSetsLink = `

All decision sets

`; + const footer = `

Live from the decision-set store at page load.

`; + if (summaries === null) { + return `

Questions

Unavailable — the decision-set store could not be read, so open questions cannot be reported here.

${allSetsLink}${footer}
`; + } + const open = summaries + .filter((s) => s.openQuestions > 0) + .sort((a, b) => b.createdAt.localeCompare(a.createdAt)); + if (!open.length) { + return `

Questions

No open questions right now — the stack is clear.

${allSetsLink}${footer}
`; + } + const totalOpen = open.reduce((n, s) => n + s.openQuestions, 0); + const rows = open + .map((s) => { + const stamp = Number.isFinite(Date.parse(s.createdAt)) ? QUESTIONS_STAMP.format(new Date(s.createdAt)) : s.createdAt; + return `
${esc(s.title)}
${s.openQuestions} open question${s.openQuestions === 1 ? "" : "s"} · ${s.items} item${s.items === 1 ? "" : "s"} · ${s.questions} question${s.questions === 1 ? "" : "s"} · Raised ${esc(stamp)}
`; + }) + .join(""); + return `

Questions

${open.length} open set${open.length === 1 ? "" : "s"} · ${totalOpen} open question${totalOpen === 1 ? "" : "s"}

${rows}${allSetsLink}${footer}
`; +} + export function renderAttention( view: AttentionView, coverage: SourceCoverage[], @@ -3150,12 +3199,13 @@ export function renderAttention( act?: AttentionAct, briefs?: Map, census?: NeedsDrewCensus | null, + questionsHtml = "", ): string { const sections = attentionSections(view, coverage, counts, act, briefs, census); return layout( "Needs you", `

Needs you

The NEEDS USER queue is an intake the orchestrator works first — it resolves what it can and escalates only what genuinely requires the user, each escalated item with its reason. Everything else the fleet can work is the orchestrator's own queue. Finished runs and stale items expire out (2 h after a run finishes, 24 h at the latest). Machine-first: /api/attention.json · /api/coverage.json. Incident alerts (watchdog push + ack) live on Alerts.

-${sections.header}${sections.queues}${sections.sessions}`, +${sections.header}${sections.queues}${sections.sessions}${questionsHtml}`, provenance, "/attention", act?.identities ? ACTION_SCRIPT + COMMENT_SCRIPT + BULK_SCRIPT : "", @@ -3428,13 +3478,13 @@ export function attentionFragment(section: "header" | "queues" | "sessions", inn * immediately; the three heavy sections stream in as fragments. * Without JS, a meta refresh lands on the full server render. */ -export function renderAttentionShell(provenance: Provenance, detail?: ProvenanceDetail, refs?: string): string { +export function renderAttentionShell(provenance: Provenance, detail?: ProvenanceDetail, refs?: string, questionsHtml = ""): string { const refsQuery = refs ? `refs=${encodeURIComponent(refs)}` : ""; const skel = (label: string) => `
Loading ${label}…
`; const body = `

Needs you

Loading the Needs User and Needs Orchestrator queues…

${attentionFragment("header", skel("queue status"), refsQuery)} ${attentionFragment("queues", skel("the queues"), refsQuery)} -${attentionFragment("sessions", skel("sessions"), refsQuery)}`; +${attentionFragment("sessions", skel("sessions"), refsQuery)}${questionsHtml}`; return layout( "Needs you", body, @@ -3534,6 +3584,7 @@ export function renderTodayBody( quotaUnavailable = false, queue?: QueueView, queueStale = false, + questionsHtml = "", ): string { const walled = quota.pools.filter((p) => p.state === "walled"); const quotaActions = buildQuotaActions(quota, AA_PLAN_FACTS); @@ -3636,7 +3687,7 @@ export function renderTodayBody( return `${todayHealthStrip(health, quota, quotaUnavailable)}${provenanceLine}${alerts.join("")}

Top objectives

${objectives}

Project momentum

${momentum} -${nextUp}${actions}${coverageHtml(coverage)}`; +${nextUp}${questionsHtml}${actions}${coverageHtml(coverage)}`; } /** The today page (#1444): full server render. */ @@ -3651,10 +3702,11 @@ export function renderToday( quotaUnavailable = false, queue?: QueueView, queueStale = false, + questionsHtml = "", ): string { return layout( "Today", - `

Today

${renderTodayBody(today, attention, quota, coverage, health, quotaUnavailable, queue, queueStale)}`, + `

Today

${renderTodayBody(today, attention, quota, coverage, health, quotaUnavailable, queue, queueStale, questionsHtml)}`, provenance, "/today", "", @@ -3669,10 +3721,11 @@ export function renderTodayShell( health: HealthView | null, quota: QuotaView, quotaUnavailable = false, + questionsHtml = "", ): string { return layout( "Today", - `

Today

${todayHealthStrip(health, quota, quotaUnavailable)}
Loading today…
`, + `

Today

${todayHealthStrip(health, quota, quotaUnavailable)}
Loading today…
${questionsHtml}`, provenance, "/today", "", diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 9f017a9f69..137ac8f186 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -79,6 +79,7 @@ import { listDecisionSets, listOpenDecisionSets, raiseDecisionSet, + refreshDecisionSet, recordResolutions, requestInfoOpenQuestions, upsertDecisionDrafts, @@ -174,6 +175,7 @@ import { renderToday, renderTodayBody, renderTodayShell, + questionsSectionHtml, type CommentFormOpts, eventTableHtml, } from "./render.ts"; @@ -713,6 +715,31 @@ function decisionsPageUrl(set: DecisionSet): string { return `${cfg.publicOrigin}/decisions/${encodeURIComponent(set.setId)}?t=${set.token}`; } +/** + * The live Questions section for Today / Needs-you (#9354): reads the + * decision-set store at request time, keeps sets with open questions, + * newest first. A store read failure renders the honest unavailable + * section (questionsSectionHtml(null, ...)), never a confident zero. + * (listDecisionSets itself reads an absent/corrupt store as empty, + * following the store's existing contract.) + */ +async function questionsHtml(): Promise { + try { + const sets = await listDecisionSets(cfg.decisionsFile); + const byId = new Map(sets.map((s) => [s.setId, s])); + const summaries = sets + .map((s) => decisionSetSummary(s)) + .filter((s) => s.openQuestions > 0) + .sort((a, b) => b.createdAt.localeCompare(a.createdAt)); + return questionsSectionHtml(summaries, (s) => { + const set = byId.get(s.setId); + return set ? decisionsPageUrl(set) : `/decisions/${encodeURIComponent(s.setId)}`; + }); + } catch { + return questionsSectionHtml(null, () => "/decisions"); + } +} + /** Append decision-set events (#9335 v2): best-effort — an event-log * failure is logged and never fails the interaction it records. */ async function logDecisionEvents(inputs: DecisionEventInput[]): Promise { @@ -2388,14 +2415,24 @@ async function handler(req: Request): Promise { if (path === "/today") { if (url.searchParams.get("full") !== "1") { const signals = await todaySignals(); - return html(renderTodayShell(prov(), provDetail(), signals.health, signals.quota, signals.quotaUnavailable)); + // #9354: the Questions section lives in the SHELL, outside the + // #today-main fragment div (see the /frag/today note below). + return html( + renderTodayShell(prov(), provDetail(), signals.health, signals.quota, signals.quotaUnavailable, await questionsHtml()), + ); } const { today, view, coverage, quota, health, quotaUnavailable, queue, queueStale } = await todayContext(); return html( - renderToday(today, view, quota, coverage, prov(), provDetail(), health, quotaUnavailable, queue, queueStale), + renderToday(today, view, quota, coverage, prov(), provDetail(), health, quotaUnavailable, queue, queueStale, await questionsHtml()), ); } if (path === "/frag/today") { + // #9354: questionsHtml is deliberately NOT passed here — the + // /today shell already renders the Questions section outside the + // #today-main fragment div, so a fragment refresh carrying it too + // would show the section twice on the live page. The shell's copy + // is from page load, which its footer states. (?full=1 never uses + // the shell, so it passes questionsHtml via renderToday instead.) const { today, view, coverage, quota, health, quotaUnavailable, queue, queueStale } = await todayContext(); const wrapped = `
${renderTodayBody(today, view, quota, coverage, health, quotaUnavailable, queue, queueStale)}
`; return sseResponse(ssePatch("#today-main", wrapped)); @@ -2570,7 +2607,9 @@ async function handler(req: Request): Promise { .filter(Boolean) : []; if (url.searchParams.get("full") !== "1") { - return html(renderAttentionShell(prov(), provDetail(), refsParam ?? undefined)); + // #9354: Questions section in the shell, below the sessions + // fragment; the /frag/attention/* fragments do not carry it. + return html(renderAttentionShell(prov(), provDetail(), refsParam ?? undefined, await questionsHtml())); } const rendered = await attentionRender(); const view = refs.length ? filterAttentionViewByRefs(rendered.view, refs) : rendered.view; @@ -2584,6 +2623,7 @@ async function handler(req: Request): Promise { rendered.act, rendered.briefs, rendered.census, + await questionsHtml(), ), ); } @@ -3311,8 +3351,36 @@ async function handler(req: Request): Promise { const v = validateDecisionSet(candidate); if (!v.ok) return json({ error: v.error }, 400); const source = typeof ext.source === "string" && ext.source ? ext.source : "decisions-ledger"; + // #9354 refresh mode: a sibling `refresh: true` opts a standing + // (ledger-mirror) set into refreshDecisionSet — contents are + // replaced, token/createdAt/source and resolutions-by-qid are + // preserved. No push and no set.created event on a refresh: the + // set is not new, and a standing set refreshed hourly must not + // push hourly. Refresh of a not-yet-existing set is a normal + // create (201, created: true, push + set.created as usual). + const refresh = ext.refresh === true; const before = await getDecisionSet(cfg.decisionsFile, v.value.setId).catch(() => null); try { + if (refresh && before) { + const set = await refreshDecisionSet(cfg.decisionsFile, v.value, source); + // The event log accepts a set-level "edit" event without a + // questionRef (validateDecisionEventInput / the type enum + // include "edit"), so a refresh is recorded that way. + await logDecisionEvents([ + { + setId: set.setId, + type: "edit", + payload: { + via: "api/decision-sets", + refresh: true, + items: set.items.length, + questions: set.items.reduce((n, i) => n + i.questions.length, 0), + }, + }, + ]); + const pageUrl = decisionsPageUrl(set); + return json({ setId: set.setId, pageUrl, url: pageUrl, created: false, refreshed: true }, 200); + } const set = await raiseDecisionSet(cfg.decisionsFile, v.value, source); if (!before) { await logDecisionEvents([ diff --git a/pm-stack/aggregator/test/curation-1497.test.ts b/pm-stack/aggregator/test/curation-1497.test.ts index 1c9f55bc69..d6f034a67f 100644 --- a/pm-stack/aggregator/test/curation-1497.test.ts +++ b/pm-stack/aggregator/test/curation-1497.test.ts @@ -62,9 +62,10 @@ const DECISIONS: Record = { // it, and new pages do not take primary slots without one. digest: "dropdown", // Post-#1497 addition (#8867, 2026-11-12): the decision-sets index - // enters at dropdown tier — no curation ruling promotes it, and - // new pages do not take primary slots without one. - decisions: "dropdown", + // entered at dropdown tier; #9354 (Drew 2026-11-13, he could not + // find the question stack) promotes it to primary — a curation + // ruling recorded here like the others. + decisions: "primary", }; describe("the #1497 decision table is applied to the manifest", () => { diff --git a/pm-stack/aggregator/test/questions-9354.test.ts b/pm-stack/aggregator/test/questions-9354.test.ts new file mode 100644 index 0000000000..6a362406a2 --- /dev/null +++ b/pm-stack/aggregator/test/questions-9354.test.ts @@ -0,0 +1,194 @@ +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 { + decisionSetSummary, + getDecisionSet, + raiseDecisionSet, + recordResolutions, + refreshDecisionSet, + type DecisionSet, + type DecisionSetInput, +} from "../src/decisions.ts"; +import { questionsSectionHtml, navLinks } from "../src/render.ts"; +import { primaryGroupedPages } from "../src/pages.ts"; + +// #9354: the decision-set question stack surfaces inside Today / +// Needs-you and in the primary nav, and standing sets can be +// refreshed in place. Oracle for every test below: the decisions +// store itself (for refresh) and the rendered HTML string (for the +// section / nav) — no mocks of the code under test. + +let dir: string; +let file: string; + +beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), "questions-9354-test-")); + file = join(dir, "decisions.json"); +}); + +afterEach(async () => { + await rm(dir, { recursive: true, force: true }); +}); + +function input(setId = "standing-1", question = "Keep this?"): DecisionSetInput { + return { + setId, + title: "Standing set", + items: [ + { + ledgerId: "item-a", + title: "Item A", + links: [], + questions: [ + { question, options: [{ id: "yes", label: "Yes" }] }, + { question: "Second question?", options: [] }, + ], + }, + ], + }; +} + +describe("refreshDecisionSet (#9354)", () => { + test("creates when absent — oracle: the stored set is a fresh raise with a token and the input contents", async () => { + const set = await refreshDecisionSet(file, input(), "test-source"); + expect(set.setId).toBe("standing-1"); + expect(set.token.length).toBeGreaterThan(0); + expect(set.source).toBe("test-source"); + expect(set.items[0]?.questions.map((q) => q.qid)).toEqual(["item-a#1", "item-a#2"]); + const stored = await getDecisionSet(file, "standing-1"); + expect(stored?.title).toBe("Standing set"); + }); + + test("refresh preserves token + createdAt + source, replaces title/items, carries a resolution by qid, carries versions for identical wording, and drops absent questions — oracle: the stored set after refresh", async () => { + const created = await raiseDecisionSet(file, input(), "original-source"); + // Resolve the first question so the refresh must carry it by qid. + const applied = await recordResolutions(file, "standing-1", [ + { ledgerId: "item-a", qid: "item-a#1", kind: "answered", optionId: "yes" }, + ]); + expect(applied?.outcomes).toEqual([{ qid: "item-a#1", applied: true }]); + const before = await getDecisionSet(file, "standing-1"); + const beforeQ1 = before?.items[0]?.questions[0]; + + const next = input("standing-1", "Keep this?"); + next.title = "Standing set — refreshed"; + // Drop the second question entirely; keep the first with identical wording. + next.items[0]!.questions = [next.items[0]!.questions[0]!]; + const refreshed = await refreshDecisionSet(file, next, "other-source"); + + expect(refreshed.token).toBe(created.token); + expect(refreshed.createdAt).toBe(created.createdAt); + expect(refreshed.source).toBe("original-source"); + expect(refreshed.title).toBe("Standing set — refreshed"); + // Dropped question is gone. + expect(refreshed.items[0]?.questions.map((q) => q.qid)).toEqual(["item-a#1"]); + const q1 = refreshed.items[0]?.questions[0]; + // Resolution carried by qid. + expect(q1?.resolution?.kind).toBe("answered"); + expect(q1?.resolution?.optionId).toBe("yes"); + // Identical wording: versions + currentVersion carried. + expect(q1?.versions).toEqual(beforeQ1?.versions); + expect(q1?.currentVersion).toBe(beforeQ1?.currentVersion); + // Exactly one stored set with this id. + const stored = await getDecisionSet(file, "standing-1"); + expect(stored?.items[0]?.questions.length).toBe(1); + }); + + test("refresh with changed wording does not carry the old version history — oracle: the refreshed question starts its own v1 history with the new text", async () => { + await raiseDecisionSet(file, input()); + const changed = input("standing-1", "Completely different?"); + const refreshed = await refreshDecisionSet(file, changed); + const q1 = refreshed.items[0]?.questions[0]; + expect(q1?.question).toBe("Completely different?"); + expect(q1?.versions?.length).toBe(1); + expect(q1?.versions?.[0]?.question).toBe("Completely different?"); + expect(q1?.currentVersion).toBe(1); + }); +}); + +function summary(set: DecisionSet) { + return decisionSetSummary(set); +} + +function makeSet(setId: string, createdAt: string, open: number, settled: number): DecisionSet { + const questions = [ + ...Array.from({ length: open }, (_, i) => ({ + qid: `${setId}-item#${i + 1}`, + question: `Open ${i + 1}?`, + options: [], + })), + ...Array.from({ length: settled }, (_, i) => ({ + qid: `${setId}-item#${open + i + 1}`, + question: `Settled ${i + 1}?`, + options: [], + resolution: { kind: "answered" as const, at: createdAt, via: "test" }, + })), + ]; + return { + setId, + title: `Set ${setId}`, + token: `tok-${setId}`, + createdAt, + source: "test", + items: [{ ledgerId: `${setId}-item`, title: "Item", group: "G", links: [], questions }], + }; +} + +describe("questionsSectionHtml (#9354)", () => { + const urlFor = (s: { setId: string; token?: string }) => + `/decisions/${s.setId}?t=tok-${s.setId}`; + + test("open counts, token link for an open set, newest first — oracle: the rendered section HTML", () => { + const older = makeSet("set-old", "2026-11-10T12:00:00.000Z", 2, 1); + const newer = makeSet("set-new", "2026-11-12T12:00:00.000Z", 1, 0); + const html = questionsSectionHtml([summary(older), summary(newer)], (s) => urlFor(s)); + expect(html).toContain(" { + const settled = makeSet("set-done", "2026-11-12T12:00:00.000Z", 0, 2); + const open = makeSet("set-open", "2026-11-11T12:00:00.000Z", 1, 0); + const html = questionsSectionHtml([summary(settled), summary(open)], (s) => urlFor(s)); + expect(html).not.toContain("set-done"); + expect(html).toContain("1 open set"); + expect(html).toContain("1 open question"); + }); + + test("empty state when nothing is open — oracle: the clear-stack wording plus the index link, and no confident counts", () => { + const settled = makeSet("set-done", "2026-11-12T12:00:00.000Z", 0, 1); + for (const html of [questionsSectionHtml([], (s) => urlFor(s)), questionsSectionHtml([summary(settled)], (s) => urlFor(s))]) { + expect(html).toContain("No open questions right now — the stack is clear."); + expect(html).toContain('href="/decisions"'); + } + }); + + test("null is unavailable, never a zero — oracle: the section says Unavailable and does not claim the stack is clear", () => { + const html = questionsSectionHtml(null, (s) => urlFor(s)); + expect(html).toContain("Unavailable"); + expect(html).not.toContain("stack is clear"); + expect(html).not.toContain("0 open"); + }); +}); + +describe("decisions in the primary nav (#9354)", () => { + test("navLinks contains an anchor to /decisions — oracle: the rendered nav-bar HTML", () => { + // navLinks is the bar every page renders; /decisions must be an anchor there. + expect(navLinks("/")).toContain(' { + const flat = primaryGroupedPages().flatMap((g) => g.pages.map((p) => p.id)); + expect(flat).toContain("decisions"); + }); +});