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
11 changes: 11 additions & 0 deletions pm-stack/aggregator/scripts/collect-fleet-feed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -1244,9 +1245,19 @@ async function main(): Promise<void> {
answers = [];
}

// #8766: Drew's decisions-page resolutions (answers + defers), from
// the aggregator's decision-set store. Fail-soft like `answers`.
let decisionResolutions: NonNullable<FleetFeed["decisionResolutions"]> = [];
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()) },
Expand Down
121 changes: 121 additions & 0 deletions pm-stack/aggregator/scripts/raise-decision-set.ts
Original file line number Diff line number Diff line change
@@ -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 <path-to-json>
//
// The intake bearer <redacted> 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 <path-to-json>";

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<string>();
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<void> {
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();
16 changes: 16 additions & 0 deletions pm-stack/aggregator/src/alerts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 ----------------------------------------------------------------

Expand Down Expand Up @@ -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";
Expand Down
6 changes: 6 additions & 0 deletions pm-stack/aggregator/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -186,6 +188,10 @@ export function loadConfig(env: Record<string, string | undefined> = 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"),
Expand Down
Loading
Loading