Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 30 additions & 4 deletions pm-stack/aggregator/scripts/submit-decision-set.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
// credential it is.
//
// Usage:
// bun run scripts/submit-decision-set.ts --payload <path-to-json>
// bun run scripts/submit-decision-set.ts --payload <path-to-json> [--refresh]
//
// The intake bearer token is resolved BY NAME from Bitwarden Secrets
// Manager (`pm-aggregator.alerts-intake-token`, via src/secrets.ts)
Expand All @@ -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";
Expand All @@ -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)}`);
}
}
Expand Down Expand Up @@ -96,26 +112,36 @@ async function main(): Promise<void> {
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) {
const text = await res.text().catch(() => "");
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();
155 changes: 115 additions & 40 deletions pm-stack/aggregator/src/decisions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -606,6 +606,66 @@ async function writeDecisionSets(file: string, sets: DecisionSet[]): Promise<voi
await writeDecisionsData(file, { sets, drafts });
}

/** Map validated input items to stored items (#9354 refresh shares
* this exact mapping with raise): qid is `<ledgerId>#<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<string, DecisionQuestion>,
): 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(
Expand All @@ -624,53 +684,68 @@ 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);
return set;
});
}

/**
* 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<DecisionSet> {
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<string, DecisionQuestion>();
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<DecisionSet | null> {
const sets = await readDecisionSets(file);
return sets.find((s) => s.setId === setId) ?? null;
Expand Down
5 changes: 4 additions & 1 deletion pm-stack/aggregator/src/pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading
Loading