-
+
+
-
+
-
+
diff --git a/pm-stack/console/public/sw.js b/pm-stack/console/public/sw.js
new file mode 100644
index 0000000000..cb7f646694
--- /dev/null
+++ b/pm-stack/console/public/sw.js
@@ -0,0 +1,40 @@
+// The app's service worker: it shows a notification when one is pushed,
+// and opens the right screen when it is tapped.
+self.addEventListener("install", () => self.skipWaiting());
+self.addEventListener("activate", (event) => event.waitUntil(self.clients.claim()));
+
+self.addEventListener("push", (event) => {
+ let data = {};
+ try {
+ data = event.data ? event.data.json() : {};
+ } catch {
+ data = {};
+ }
+ event.waitUntil(
+ self.registration.showNotification(data.title || "PM", {
+ body: data.body || "",
+ tag: data.tag || undefined,
+ renotify: Boolean(data.tag),
+ icon: "/icons/icon-192.png",
+ badge: "/icons/icon-192.png",
+ data: { url: data.url || "/console/" },
+ }),
+ );
+});
+
+self.addEventListener("notificationclick", (event) => {
+ event.notification.close();
+ const url = event.notification.data?.url || "/console/";
+ event.waitUntil(
+ (async () => {
+ const windows = await self.clients.matchAll({ type: "window", includeUncontrolled: true });
+ for (const client of windows) {
+ if (new URL(client.url).pathname.startsWith("/console")) {
+ await client.focus();
+ return client.navigate ? client.navigate(url) : undefined;
+ }
+ }
+ return self.clients.openWindow(url);
+ })(),
+ );
+});
diff --git a/pm-stack/console/scripts/demo.ts b/pm-stack/console/scripts/demo.ts
new file mode 100644
index 0000000000..9ceacbe78d
--- /dev/null
+++ b/pm-stack/console/scripts/demo.ts
@@ -0,0 +1,371 @@
+// Run the interface against canned state, to look at it without a fleet.
+//
+// bun run scripts/demo.ts [port] then open http://127.0.0.1:/console/
+//
+// The real server code answers; only the sources are canned, and every
+// action succeeds and is listed under "What you did".
+import { readConfig } from "../src/config.ts";
+import { Docs } from "../src/docs.ts";
+import { Ops } from "../src/ops.ts";
+import { Push } from "../src/push.ts";
+import { handle } from "../src/server.ts";
+
+const iso = (minutesAgo: number) => new Date(Date.now() - minutesAgo * 60_000).toISOString().slice(0, 19);
+const task = (id: number, title: string, extra: Record) => ({
+ id,
+ title,
+ priority: 30,
+ status: "queued",
+ attempts: 1,
+ claimed: "",
+ lease: "",
+ created: iso(300),
+ worker: null,
+ lane: null,
+ model: null,
+ kind: "small_fix",
+ issue: 9000 + id,
+ pr: null,
+ step: "",
+ goal: "The fix lands with a test that fails without it",
+ url: `https://github.com/developing-today/code/issues/${9000 + id}`,
+ ...extra,
+});
+const question = (set: string, n: number, extra: Record = {}) => ({
+ set,
+ setTitle: `Pending questions — ${set}`,
+ created: iso(60 * 24 * n),
+ ledger: `ledger-${set}-${n}`,
+ item: `PM-stack S${n} attachments (#1003${n}): where do attachments live`,
+ links: [`https://github.com/developing-today/code/issues/1003${n}`],
+ qid: `q${n}`,
+ q: `For S${n} attachments and multimedia, build new storage, or reuse a mechanism outside pm-stack that you name?`,
+ context: "Attachments today are pasted links. The dashboard has no storage of its own, and three pages want one.",
+ detail:
+ "Building new keeps the stack self-contained. Reusing means one fewer store to run, but ties the release to another project.",
+ multi: false,
+ recommended: ["opt-1"],
+ options: [
+ { id: "opt-1", label: "Build new attachment storage", tags: ["recommended", "simpler"] },
+ { id: "opt-2", label: "Reuse a mechanism outside pm-stack (name it in your answer)", tags: [] },
+ { id: "opt-3", label: "Build new now; migrate storage refs later", tags: ["reversible"] },
+ ],
+ ...extra,
+});
+
+const state = {
+ board: {
+ counts: { claimed: 3, queued: 4, blocked: 474, parked: 58 },
+ now: [
+ task(1, "Fix #9075: session state — session id in env and a resume path", {
+ status: "claimed",
+ claimed: iso(14),
+ worker: "repo-worker-code",
+ lane: "oc-code-02",
+ model: "workhorse",
+ attempts: 8,
+ step: "Write the failing test for resume after a crash, then wire the env var through the launcher.",
+ }),
+ task(2, "Implement mcpx Roc script support after the Python parity gate", {
+ status: "claimed",
+ claimed: iso(41),
+ worker: "repo-worker-code",
+ lane: "code-h",
+ priority: 20,
+ step: "Resume only when a compatible docs build is available.",
+ }),
+ task(3, "Fix #2723 phase 3: PendingHold post and void lifecycle", {
+ status: "claimed",
+ claimed: iso(3),
+ worker: "repo-worker-code",
+ lane: "code-j",
+ goal: "Posting and voiding a hold are covered by the ledger property tests",
+ }),
+ ],
+ next: [
+ task(4, "Owner prompt developing-today/code#12501: make the join-at-admission slice the top priority", {
+ priority: 10,
+ kind: "triage",
+ }),
+ task(5, "Triage developing-today/code#12416: link from the dashboard to the console", {
+ priority: 30,
+ kind: "triage",
+ }),
+ task(6, "Merge-watch developing-today/code#12240: recheck fix PR for issue #12230", {
+ priority: 30,
+ kind: "pr_shepherd",
+ }),
+ task(7, "Fix #11350: toolchain file drift between crates", { priority: 50 }),
+ ],
+ blockedWhy: [
+ { why: "waits on #9106 (open, all PRs merged)", n: 212 },
+ { why: "no reason recorded", n: 140 },
+ { why: '{"kind":"time","until":"2026-11-19T14:02:00Z"}', n: 4 },
+ ],
+ },
+ sessions: {
+ moving: [
+ {
+ id: "s1",
+ title: "F12.11 binary frames: fuzz the decoder",
+ agent: "build",
+ model: "gpt-5.2-codex",
+ where: "git/code-j",
+ last: iso(1),
+ tools: 2,
+ messages: 141,
+ },
+ {
+ id: "s2",
+ title: "Triage sweep: opencode",
+ agent: "triage",
+ model: "workhorse",
+ where: "git/opencode",
+ last: iso(6),
+ tools: 0,
+ messages: 37,
+ },
+ ],
+ waiting: [
+ {
+ id: "porkbun",
+ title: "Porkbun: log into the main account and enter the password in the staged modal",
+ ref: "gh:developing-today/code#902",
+ why: "",
+ },
+ ],
+ },
+ census: {
+ at: iso(1),
+ complete: true,
+ hands: [
+ {
+ ref: "developing-today/code#12417",
+ title: "Google sign-in for pm.security.cab: create the OAuth client",
+ url: "https://github.com/developing-today/code/issues/12417",
+ pr: false,
+ updated: iso(50),
+ kind: "interactive-login",
+ action:
+ "Create a Google OAuth web client with the redirect URI in the issue and save its ID and secret in Bitwarden.",
+ },
+ {
+ ref: "developing-today/code#1080",
+ title: "epic(cluster): hardware inventory and first-node selection",
+ url: "https://github.com/developing-today/code/issues/1080",
+ pr: false,
+ updated: iso(60 * 24 * 9),
+ kind: "physical",
+ action: "Power on one Threadripper host and make its BMC reachable to the worker.",
+ },
+ ],
+ reviews: [
+ {
+ ref: "developing-today/code#24",
+ title: "Dependency Dashboard",
+ url: "https://github.com/developing-today/code/issues/24",
+ pr: false,
+ updated: iso(60 * 30),
+ },
+ ],
+ other: [
+ {
+ ref: "developing-today/code#1086",
+ title: "epic(cluster): TALM and Talos bootstrap",
+ url: "https://github.com/developing-today/code/issues/1086",
+ pr: false,
+ updated: iso(60 * 24 * 20),
+ why: "",
+ },
+ ],
+ },
+ asks: [
+ {
+ issue: 12501,
+ url: "https://github.com/developing-today/code/issues/12501",
+ text: "Make the join-at-admission slice the top priority and tell me what is in its way.",
+ created: iso(30),
+ updated: iso(4),
+ status: "answered",
+ worker: null,
+ replies: [
+ {
+ you: false,
+ at: iso(4),
+ text: "Done. #12279 is ranked expedite and its task is first in the queue. In its way: #12230 (36 test files in no registry row) fails the lint the slice's PR will run. I queued that ahead of it.",
+ },
+ ],
+ },
+ {
+ issue: 12499,
+ url: "https://github.com/developing-today/code/issues/12499",
+ text: "What is blocked and why? One paragraph.",
+ created: iso(200),
+ updated: iso(180),
+ status: "done",
+ worker: null,
+ replies: [
+ {
+ you: false,
+ at: iso(180),
+ text: "474 tasks are blocked. 212 wait on #9106, which is open although every PR for it is merged; closing it frees them.",
+ },
+ ],
+ },
+ {
+ issue: 12502,
+ url: "https://github.com/developing-today/code/issues/12502",
+ text: "Add a dark and light theme switch to the app.",
+ created: iso(2),
+ updated: iso(2),
+ status: "queued",
+ worker: null,
+ replies: [],
+ },
+ ],
+ questionCount: { total: 6, sets: 2 },
+ questions: {
+ total: 6,
+ sets: 2,
+ open: [
+ question("2026-11-17", 7),
+ question("2026-11-17", 8, {
+ q: "Which checks must pass before a batch merges?",
+ multi: true,
+ recommended: ["opt-1", "opt-3"],
+ options: [
+ { id: "opt-1", label: "Unit tests of the crates the batch touches", tags: ["recommended"] },
+ { id: "opt-2", label: "The whole workspace", tags: ["safer"] },
+ { id: "opt-3", label: "The module reach check", tags: ["recommended"] },
+ ],
+ }),
+ question("2026-11-17", 9, { recommended: [], context: "", detail: "" }),
+ question("2026-11-16", 4),
+ question("2026-11-16", 5),
+ question("2026-11-16", 6),
+ ],
+ },
+ prs: [
+ {
+ number: 12240,
+ title: "ci(id): register the 36 unwired suites",
+ draft: false,
+ url: "https://github.com/developing-today/code/pull/12240",
+ created: iso(60 * 20),
+ author: "dezren39",
+ branch: "task/suite-registry",
+ },
+ {
+ number: 12241,
+ title: "feat(id): F12.11 binary frames, encoder",
+ draft: false,
+ url: "https://github.com/developing-today/code/pull/12241",
+ created: iso(60 * 19),
+ author: "dezren39",
+ branch: "task/f12-11-frames",
+ },
+ {
+ number: 12390,
+ title: "wip: talos bootstrap notes",
+ draft: true,
+ url: "https://github.com/developing-today/code/pull/12390",
+ created: iso(60 * 3),
+ author: "dezren39",
+ branch: "wip/talos",
+ },
+ ],
+ priorities: {
+ truncated: false,
+ issues: [
+ {
+ number: 4000,
+ title: "id: Phase 12 exit",
+ url: "https://github.com/developing-today/code/issues/4000",
+ updated: iso(90),
+ comments: 14,
+ labels: ["expedite"],
+ rank: "expedite",
+ order: 0,
+ },
+ {
+ number: 12279,
+ title: "id: join at admission (slice 3)",
+ url: "https://github.com/developing-today/code/issues/12279",
+ updated: iso(300),
+ comments: 2,
+ labels: ["now"],
+ rank: "now",
+ order: 2,
+ },
+ ],
+ },
+ agents: [
+ { name: "conductor", groups: ["opencode"], last_seen: iso(2), unread_commands: 0, unread_messages: 1 },
+ { name: "muse", groups: ["research"], last_seen: iso(400), unread_commands: 2, unread_messages: 0 },
+ ],
+ services: [
+ { unit: "pm-aggregator.service", load: "loaded", active: "active", sub: "running", description: "PM dashboard" },
+ {
+ unit: "opencode-go-seating-guard.service",
+ load: "loaded",
+ active: "failed",
+ sub: "failed",
+ description: "OpenCode Go seating guard",
+ },
+ {
+ unit: "queue-broker.service",
+ load: "loaded",
+ active: "active",
+ sub: "running",
+ description: "Repo queue broker",
+ },
+ ],
+ more: [
+ {
+ group: "Overview",
+ pages: [
+ {
+ title: "Overview",
+ route: "/?dashboard",
+ blurb: "The stack front door: needs-you, projects, quotas and health at a glance.",
+ },
+ { title: "Today", route: "/today", blurb: "What changed today." },
+ ],
+ },
+ { group: "Work", pages: [{ title: "Roadmap", route: "/roadmap", blurb: "Phases and what is in each." }] },
+ ],
+};
+
+const cfg = readConfig({ HOME: "/tmp", PM_CONSOLE_DASHBOARD_URL: "" });
+const docs = new Docs(
+ Object.fromEntries(Object.entries(state).map(([name, data]) => [name, { ttlMs: 3_600_000, load: async () => data }])),
+);
+const done = (result: unknown) => ({ run: async () => result, touch: [] as string[], audit: () => ({}) });
+const table = new Proxy({} as Record>, {
+ get: (_t, kind) =>
+ done(
+ kind === "ask.send"
+ ? { issue: 12503, queued: true }
+ : kind === "questions.accept"
+ ? { applied: 2, refused: [] }
+ : { ok: true },
+ ),
+ has: () => true,
+ getOwnPropertyDescriptor: () => ({ configurable: true, enumerable: true, value: done({}) }),
+});
+const port = Number(process.argv[2] ?? 4899);
+Bun.serve({
+ hostname: "127.0.0.1",
+ port,
+ fetch: (req) =>
+ handle(req, {
+ cfg,
+ ops: new Ops(cfg, async () => ({ code: 0, stdout: "[]", stderr: "" })),
+ docs,
+ push: new Push("/tmp/pm-console-demo-push.json", "mailto:you@example.com", async () => ({ status: 201 })),
+ actions: table,
+ identify: async () => ({ via: "demo", email: "you@example.com" }),
+ audit: async () => {},
+ }),
+});
+console.log(`demo: http://127.0.0.1:${port}/console/`);
diff --git a/pm-stack/console/scripts/expose.py b/pm-stack/console/scripts/expose.py
index 468b4e08ce..2c156d4179 100755
--- a/pm-stack/console/scripts/expose.py
+++ b/pm-stack/console/scripts/expose.py
@@ -50,10 +50,12 @@
CONSOLE = "http://localhost:4872"
UNIT = "pm-console.service"
# The sign-in cookie is not sent on another site's requests, and page
-# scripts cannot read it.
+# scripts cannot read it. A sign-in lasts a month, so signing in is a
+# rare event and not a daily one.
APP_SETTINGS = {
"same_site_cookie_attribute": "lax",
"http_only_cookie_attribute": True,
+ "session_duration": "720h",
}
PUBLIC_PATHS = ("/.well-known/assetlinks.json", "/manifest.webmanifest", "/icons")
GOOGLE_ID = "google.access-sso.client-id"
diff --git a/pm-stack/console/scripts/test_expose.py b/pm-stack/console/scripts/test_expose.py
index 5ebf315bf7..9b62a96d03 100755
--- a/pm-stack/console/scripts/test_expose.py
+++ b/pm-stack/console/scripts/test_expose.py
@@ -165,6 +165,7 @@ def test_the_gate_exists_before_the_route(self):
)
self.assertEqual(main["allowed_idps"], ["idp-onetimepin"])
self.assertEqual(main["same_site_cookie_attribute"], "lax")
+ self.assertEqual(main["session_duration"], "720h")
self.assertIs(main["http_only_cookie_attribute"], True)
for path in expose.PUBLIC_PATHS:
app = next(a for a in account.apps if a["domain"] == HOST + path)
diff --git a/pm-stack/console/src/actions.ts b/pm-stack/console/src/actions.ts
new file mode 100644
index 0000000000..da6007338a
--- /dev/null
+++ b/pm-stack/console/src/actions.ts
@@ -0,0 +1,116 @@
+// Everything the owner can do, as one list of named actions.
+//
+// One endpoint takes `{ kind, args }`. Each action names the sections it
+// changes, so the documents are read again before the answer goes back,
+// and what it leaves in the audit log, which never includes the text the
+// owner typed.
+import type { Docs } from "./docs.ts";
+import { OpError, type Ops } from "./ops.ts";
+import type { Push } from "./push.ts";
+import type { Work } from "./work.ts";
+
+type Args = Record;
+interface Action {
+ run: (args: Args) => Promise;
+ /** Sections to read again afterwards. */
+ touch: string[];
+ /** What the audit log keeps of the arguments. */
+ audit: (args: Args) => Args;
+}
+
+const ids =
+ (...keys: string[]) =>
+ (args: Args) =>
+ Object.fromEntries(keys.map((k) => [k, args[k]]));
+
+/** A refusal from the push module is the caller's mistake, not a failure of this service. */
+const asked = async (p: Promise): Promise =>
+ p.catch((error: Error) => {
+ throw error instanceof OpError ? error : new OpError(400, error.message);
+ });
+
+export function actions(ops: Ops, work: Work, push?: Push): Record {
+ const notify: Record = push
+ ? {
+ "push.on": { run: (a) => asked(push.subscribe(a.subscription, a.label)), touch: [], audit: () => ({}) },
+ "push.off": { run: (a) => asked(push.unsubscribe(a.endpoint)), touch: [], audit: () => ({}) },
+ "push.class": { run: (a) => asked(push.setClass(a.class, a.on)), touch: [], audit: ids("class", "on") },
+ "push.test": {
+ run: () =>
+ push.send("test", {
+ title: "PM",
+ body: "Notifications are on for this device.",
+ url: "/console/",
+ tag: "test",
+ }),
+ touch: [],
+ audit: () => ({}),
+ },
+ }
+ : {};
+ return {
+ ...notify,
+ "ask.send": { run: (a) => work.ask(a), touch: ["asks", "board"], audit: () => ({}) },
+ "ask.reply": { run: (a) => work.askReply(a), touch: ["asks", "board"], audit: ids("issue") },
+ "ask.close": { run: (a) => work.askClose(a), touch: ["asks"], audit: ids("issue") },
+ "question.answer": {
+ run: (a) => work.answer(a),
+ touch: ["questions", "questionCount"],
+ audit: ids("set", "ledger", "qid", "option", "options"),
+ },
+ "question.defer": {
+ run: (a) => work.defer(a),
+ touch: ["questions", "questionCount"],
+ audit: ids("set", "ledger", "qid", "lean"),
+ },
+ "questions.accept": {
+ run: (a) => work.acceptRecommended(a.set),
+ touch: ["questions", "questionCount"],
+ audit: ids("set"),
+ },
+ "hands.done": { run: (a) => work.handsDone(a), touch: [], audit: ids("ref") },
+ "need.comment": { run: (a) => work.needComment(a), touch: [], audit: ids("ref") },
+ "task.move": { run: (a) => work.moveTask(a), touch: ["board"], audit: ids("task", "to") },
+ "task.unblock": {
+ run: (a) => ops.queueAct("unblock", a.task, a.reason),
+ touch: ["board"],
+ audit: ids("task", "reason"),
+ },
+ "task.cancel": {
+ run: (a) => ops.queueAct("cancel", a.task, a.reason),
+ touch: ["board"],
+ audit: ids("task", "reason"),
+ },
+ "issue.rank": { run: (a) => ops.setRank(a.issue, a.rank), touch: ["priorities"], audit: ids("issue", "rank") },
+ "issue.comment": { run: (a) => ops.comment(a.issue, a.text), touch: [], audit: ids("issue") },
+ "pr.merge": { run: (a) => ops.mergePr(a.pr), touch: ["prs"], audit: ids("pr") },
+ "unit.act": {
+ run: (a) => ops.serviceAct(a.unit, a.action),
+ touch: ["services"],
+ audit: ids("unit", "action"),
+ },
+ "message.send": {
+ run: (a) => ops.send(a.to, a.text, a.command),
+ touch: [],
+ audit: (a) => ({ to: a.to, command: a.command === true }),
+ },
+ };
+}
+
+/** Run one named action and read again what it changed. */
+export async function perform(
+ table: Record,
+ docs: Docs,
+ kind: unknown,
+ args: unknown,
+): Promise {
+ const action = typeof kind === "string" && Object.hasOwn(table, kind) ? table[kind] : undefined;
+ if (!action) throw new OpError(400, "kind: not an action this console has");
+ if (args === null || typeof args !== "object" || Array.isArray(args))
+ throw new OpError(400, "args: expected an object");
+ const result = await action.run(args as Args);
+ // The census is the dashboard's and refreshes on its own clock; for the
+ // rest, the caller's next read should already show the change.
+ await docs.touch(action.touch);
+ return result;
+}
diff --git a/pm-stack/console/src/config.ts b/pm-stack/console/src/config.ts
index 274150780f..d32daa07b0 100644
--- a/pm-stack/console/src/config.ts
+++ b/pm-stack/console/src/config.ts
@@ -52,6 +52,13 @@ export interface Config {
/** The signed APK the console hands to the signed-in owner, if the
* file exists. */
androidApk: string;
+ /** The dashboard's decision-set store: the questions waiting on the
+ * owner, and the per-set tokens that authorise an answer. */
+ decisionsFile: string;
+ /** Label on an issue that is an instruction from the owner. */
+ promptLabel: string;
+ /** Repositories whose issues may be answered from "Needs me". */
+ needsRepos: string[];
}
export class ConfigError extends Error {}
@@ -211,5 +218,13 @@ export function readConfig(
androidPackage: env.PM_CONSOLE_ANDROID_PACKAGE ?? "today.developing.pmconsole",
androidFingerprints: fingerprints,
androidApk: env.PM_CONSOLE_ANDROID_APK ?? `${home}/.local/state/pm-console/android/pm-console.apk`,
+ decisionsFile: env.PM_CONSOLE_DECISIONS_FILE ?? `${home}/.local/state/pm-aggregator/decisions.json`,
+ promptLabel: env.PM_CONSOLE_PROMPT_LABEL ?? "owner/prompt",
+ needsRepos: list(env, "PM_CONSOLE_NEEDS_REPOS", [
+ "developing-today/code",
+ "developing-today/opencode",
+ "developing-today/openchamber",
+ "dezren39/nix",
+ ]),
};
}
diff --git a/pm-stack/console/src/docs.ts b/pm-stack/console/src/docs.ts
new file mode 100644
index 0000000000..56cb9cd2be
--- /dev/null
+++ b/pm-stack/console/src/docs.ts
@@ -0,0 +1,175 @@
+// The state the interface draws, kept ready.
+//
+// A page never waits on a live fan-out to GitHub, the queue store or the
+// dashboard: each source is a section that is refreshed in the
+// background and served from memory, with the time it was last read and
+// the error if the last read failed. Three documents are built from the
+// sections, sized for a phone on a poor link:
+//
+// core what is in progress, what is next, what needs the owner,
+// what he has asked for (small, polled)
+// questions every open question waiting on him (large, read on demand)
+// ops pull requests, ranked issues, agents, units, other pages
+//
+// The same documents can be stored and served somewhere else: nothing in
+// them depends on this process.
+import { createHash } from "node:crypto";
+
+export type DocName = "core" | "questions" | "ops";
+export const DOC_NAMES: DocName[] = ["core", "questions", "ops"];
+
+interface Section {
+ /** Refresh when older than this while someone is looking. */
+ ttlMs: number;
+ load: () => Promise;
+ at: number;
+ /** When it was last read successfully. */
+ goodAt: number;
+ ok: boolean;
+ error: string | null;
+ data: unknown;
+ loading: Promise | null;
+}
+
+export interface Act {
+ id: string;
+ kind: string;
+ at: string;
+ by: string;
+ status: "running" | "done" | "failed";
+ note: string;
+}
+
+/** Which sections each document is built from. */
+const DOCS: Record = {
+ core: ["board", "sessions", "census", "asks", "questionCount"],
+ questions: ["questions"],
+ ops: ["prs", "priorities", "agents", "services", "more"],
+};
+/** Stop refreshing when nobody has asked for this long. */
+const WATCH_MS = 10 * 60_000;
+const FIRST_LOAD_MS = 25_000;
+const ACTS_KEPT = 30;
+
+export class Docs {
+ private sections = new Map();
+ private asked = 0;
+ private acts: Act[] = [];
+ private timer: ReturnType | null = null;
+
+ constructor(
+ loaders: Record Promise }>,
+ private now: () => number = Date.now,
+ ) {
+ for (const [name, l] of Object.entries(loaders)) {
+ this.sections.set(name, { ...l, at: 0, goodAt: 0, ok: false, error: null, data: null, loading: null });
+ }
+ for (const names of Object.values(DOCS)) {
+ for (const name of names) {
+ if (!this.sections.has(name)) throw new Error(`no loader for section ${name}`);
+ }
+ }
+ }
+
+ /** Read one section again. Concurrent callers share the read. A failed
+ * read keeps the last good data and records why. */
+ refresh(name: string): Promise {
+ const s = this.sections.get(name);
+ if (!s) return Promise.resolve();
+ if (s.loading) return s.loading;
+ s.loading = (async () => {
+ try {
+ s.data = await s.load();
+ s.ok = true;
+ s.error = null;
+ s.goodAt = this.now();
+ } catch (error) {
+ s.ok = false;
+ s.error = (error as Error).message.slice(0, 300);
+ } finally {
+ s.at = this.now();
+ s.loading = null;
+ }
+ })();
+ return s.loading;
+ }
+
+ /** After an action: read the sections it changed, so the next document shows it. */
+ async touch(names: string[]): Promise {
+ await Promise.all(names.map((n) => this.refresh(n)));
+ }
+
+ private stale(s: Section): boolean {
+ return this.now() - s.at > s.ttlMs;
+ }
+
+ /** One pass of the background loop: refresh what is stale, if anyone is looking. */
+ tick(): void {
+ if (this.now() - this.asked > WATCH_MS) return;
+ for (const [name, s] of this.sections) {
+ if (this.stale(s)) void this.refresh(name);
+ }
+ }
+
+ start(everyMs = 5_000): void {
+ this.timer ??= setInterval(() => this.tick(), everyMs);
+ }
+
+ stop(): void {
+ if (this.timer) clearInterval(this.timer);
+ this.timer = null;
+ }
+
+ /** The last good copy of one section, or null if it has never been read. */
+ good(name: string): unknown {
+ const s = this.sections.get(name);
+ return s && s.goodAt > 0 ? s.data : null;
+ }
+
+ logAct(act: Act): void {
+ this.acts = [act, ...this.acts.filter((a) => a.id !== act.id)].slice(0, ACTS_KEPT);
+ }
+
+ /** The document, at once. Only a section that has never been read is
+ * waited for, and only so long. `asOf` is now when every section has
+ * been read within its own interval, and earlier by however far the
+ * most overdue section is behind: how stale the document really is. */
+ async doc(name: DocName): Promise<{ etag: string; body: string; asOf: number }> {
+ this.asked = this.now();
+ const names = DOCS[name];
+ const section = (n: string) => this.sections.get(n) as Section;
+ const never = names.filter((n) => section(n).at === 0);
+ if (never.length > 0) {
+ let timer: ReturnType | undefined;
+ await Promise.race([
+ Promise.all(never.map((n) => this.refresh(n))),
+ new Promise((resolve) => {
+ timer = setTimeout(resolve, FIRST_LOAD_MS);
+ }),
+ ]);
+ clearTimeout(timer);
+ }
+ const out: Record = { v: 1, doc: name };
+ const health: Record = {};
+ for (const n of names) {
+ const s = section(n);
+ if (this.stale(s)) void this.refresh(n);
+ out[n] = s.data;
+ health[n] = { ok: s.ok, error: s.error };
+ }
+ out.health = health;
+ if (name === "core") out.acts = this.acts;
+ // The tag covers the content and not the times it was read, so a
+ // document that has not changed costs the phone nothing. The read
+ // times travel beside it.
+ const etag = `"${createHash("sha1").update(JSON.stringify(out)).digest("base64url")}"`;
+ const now = this.now();
+ const overdue = names
+ .map((n) => section(n))
+ .filter((s) => s.goodAt > 0)
+ .map((s) => Math.max(0, now - s.goodAt - s.ttlMs));
+ const asOf = now - Math.max(0, ...overdue);
+ out.read = Object.fromEntries(names.map((n) => [n, section(n).at ? new Date(section(n).at).toISOString() : null]));
+ return { etag, body: JSON.stringify(out), asOf };
+ }
+}
diff --git a/pm-stack/console/src/notify.ts b/pm-stack/console/src/notify.ts
new file mode 100644
index 0000000000..0a42981d6b
--- /dev/null
+++ b/pm-stack/console/src/notify.ts
@@ -0,0 +1,163 @@
+// What is worth interrupting the owner for, and only once each.
+//
+// The state documents say how things stand; this compares them with what
+// he has already been told and sends the difference: the fleet answered
+// one of his prompts, something new needs his hands, new questions
+// arrived, a unit failed. The first pass only takes stock, so turning
+// notifications on never sets off a flood about things already there.
+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import { dirname } from "node:path";
+import type { Docs } from "./docs.ts";
+import type { Class, Push } from "./push.ts";
+
+export interface Seen {
+ primed: boolean;
+ /** issue number -> time of the last fleet reply already announced */
+ asks: Record;
+ hands: string[];
+ questions: number;
+ failed: string[];
+}
+export const NOTHING_SEEN: Seen = { primed: false, asks: {}, hands: [], questions: 0, failed: [] };
+
+export interface Message {
+ cls: Class;
+ title: string;
+ body: string;
+ url: string;
+ tag: string;
+}
+
+interface State {
+ asks?: { issue: number; replies: { you: boolean; at: string; text: string }[] }[] | null;
+ census?: { hands: { ref: string; title: string; action?: string }[] } | null;
+ sessions?: { waiting: { id: string; title: string }[] } | null;
+ questionCount?: { total: number } | null;
+ services?: { unit: string; active: string }[] | null;
+}
+
+const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
+
+/** The messages owed for `now`, and what will have been seen once they
+ * are sent. A section that could not be read (null) changes nothing. */
+export function changes(seen: Seen, now: State): { messages: Message[]; seen: Seen } {
+ const next: Seen = {
+ primed: true,
+ asks: { ...seen.asks },
+ hands: seen.hands,
+ questions: seen.questions,
+ failed: seen.failed,
+ };
+ const messages: Message[] = [];
+ for (const ask of now.asks ?? []) {
+ const last = ask.replies[ask.replies.length - 1];
+ if (!last || last.you || next.asks[ask.issue] === last.at) continue;
+ next.asks[ask.issue] = last.at;
+ messages.push({
+ cls: "replies",
+ title: `The fleet replied on #${ask.issue}`,
+ body: clip(last.text, 180),
+ url: "/console/#ask",
+ tag: `ask-${ask.issue}`,
+ });
+ }
+ if (now.census || now.sessions) {
+ const hands = [
+ ...(now.census?.hands ?? []).map((i) => ({ key: i.ref, text: i.action || i.title })),
+ ...(now.sessions?.waiting ?? []).map((w) => ({ key: `session:${w.id}`, text: w.title })),
+ ];
+ for (const item of hands) {
+ if (seen.hands.includes(item.key)) continue;
+ messages.push({
+ cls: "needs",
+ title: "Something needs you",
+ body: clip(item.text, 180),
+ url: "/console/#needs/hands",
+ tag: `hands-${item.key}`,
+ });
+ }
+ next.hands = hands.map((i) => i.key);
+ }
+ if (now.questionCount) {
+ const total = now.questionCount.total;
+ if (total > seen.questions) {
+ const more = total - seen.questions;
+ messages.push({
+ cls: "questions",
+ title: more === 1 ? "1 new question for you" : `${more} new questions for you`,
+ body: `${total} open in all.`,
+ url: "/console/#needs/questions",
+ tag: "questions",
+ });
+ }
+ next.questions = total;
+ }
+ if (now.services) {
+ const failed = now.services.filter((u) => u.active === "failed").map((u) => u.unit);
+ for (const unit of failed) {
+ if (seen.failed.includes(unit)) continue;
+ messages.push({
+ cls: "trouble",
+ title: "A unit failed",
+ body: unit,
+ url: "/console/#more/services",
+ tag: `unit-${unit}`,
+ });
+ }
+ next.failed = failed;
+ }
+ return { messages: seen.primed ? messages : [], seen: next };
+}
+
+/** Sections the notifier reads, whether or not anyone is looking. */
+const WATCHED = ["asks", "census", "sessions", "questionCount", "services"];
+
+export class Notifier {
+ private seen: Seen | null = null;
+ private timer: ReturnType | null = null;
+ private busy = false;
+
+ constructor(
+ private docs: Docs,
+ private push: Push,
+ private file: string,
+ ) {}
+
+ private async load(): Promise {
+ if (this.seen) return this.seen;
+ try {
+ this.seen = { ...NOTHING_SEEN, ...(JSON.parse(await readFile(this.file, "utf8")) as Seen) };
+ } catch {
+ this.seen = NOTHING_SEEN;
+ }
+ return this.seen;
+ }
+
+ /** One pass. Does nothing while no device is subscribed. */
+ async tick(): Promise {
+ if (this.busy) return 0;
+ this.busy = true;
+ try {
+ if ((await this.push.status()).devices === 0) return 0;
+ await this.docs.touch(WATCHED);
+ const now = Object.fromEntries(WATCHED.map((n) => [n, this.docs.good(n)])) as State;
+ const { messages, seen } = changes(await this.load(), now);
+ for (const m of messages) await this.push.send(m.cls, m);
+ this.seen = seen;
+ await mkdir(dirname(this.file), { recursive: true, mode: 0o700 });
+ const tmp = `${this.file}.tmp-${process.pid}`;
+ await writeFile(tmp, JSON.stringify(seen), { mode: 0o600 });
+ await rename(tmp, this.file);
+ return messages.length;
+ } finally {
+ this.busy = false;
+ }
+ }
+
+ start(everyMs = 60_000): void {
+ this.timer ??= setInterval(
+ () => void this.tick().catch((e) => console.error(`pm-console: notify: ${e.message}`)),
+ everyMs,
+ );
+ }
+}
diff --git a/pm-stack/console/src/ops.ts b/pm-stack/console/src/ops.ts
index 29a2a06607..59751a99cb 100644
--- a/pm-stack/console/src/ops.ts
+++ b/pm-stack/console/src/ops.ts
@@ -17,8 +17,11 @@ export interface RunResult {
export type Run = (argv: string[], opts?: { stdin?: string; timeoutMs?: number }) => Promise;
export type Fetch = (
url: string,
- init: { method: string; headers: Record; body: string },
+ init: { method: string; headers: Record; body?: string; signal?: AbortSignal },
) => Promise<{ ok: boolean; status: number; json(): Promise }>;
+export type Row = Record;
+/** Queue priorities, most urgent first (the queue's design scale). */
+export const PRIORITY_SCALE = [10, 20, 30, 40, 50, 70, 90] as const;
export class OpError extends Error {
constructor(
@@ -171,12 +174,12 @@ export class Ops {
private queueToken: string | null = null;
constructor(
- private cfg: Config,
- private run: Run = realRun,
- private fetchImpl: Fetch = fetch as unknown as Fetch,
+ readonly cfg: Config,
+ readonly run: Run = realRun,
+ readonly fetchImpl: Fetch = fetch as unknown as Fetch,
) {}
- private async must(argv: string[], opts?: { stdin?: string; timeoutMs?: number }): Promise {
+ async must(argv: string[], opts?: { stdin?: string; timeoutMs?: number }): Promise {
const r = await this.run(argv, opts);
if (r.code !== 0) {
const detail = (r.stderr || r.stdout).trim().split("\n").slice(-3).join(" ").slice(0, 400);
@@ -185,7 +188,7 @@ export class Ops {
return r.stdout;
}
- private async gh(args: string[], body?: unknown): Promise {
+ async gh(args: string[], body?: unknown): Promise {
const argv = [this.cfg.fleetBin, "gh", "api", ...args];
const out = await this.must(
body === undefined ? argv : [...argv, "--input", "-"],
@@ -196,19 +199,19 @@ export class Ops {
// ---- queue -----------------------------------------------------------
- private async sql(statement: string, args: (string | number)[]): Promise[]> {
- if (!/^\s*select\b/i.test(statement)) throw new Error("the console only reads the queue store");
+ /** One request to the queue store carrying `statements` in order. */
+ private async pipeline(statements: { sql: string; args: (string | number)[] }[]) {
const body = {
requests: [
- {
+ ...statements.map((st) => ({
type: "execute",
stmt: {
- sql: statement,
- args: args.map((a) =>
+ sql: st.sql,
+ args: st.args.map((a) =>
typeof a === "number" ? { type: "integer", value: String(a) } : { type: "text", value: a },
),
},
- },
+ })),
{ type: "close" },
],
};
@@ -229,17 +232,60 @@ export class Ops {
res = await ask();
}
if (!res.ok) throw new OpError(502, `queue store answered http ${res.status}`);
- const first = (
- (await res.json()) as {
- results?: {
- type?: string;
- response?: { result?: { cols: { name: string }[]; rows: { value?: string | number | null }[][] } };
- }[];
- }
- ).results?.[0];
- const result = first?.type === "ok" ? first.response?.result : undefined;
- if (!result) throw new OpError(502, "queue store refused the query");
- return result.rows.map((row) => Object.fromEntries(result.cols.map((c, i) => [c.name, row[i]?.value ?? null])));
+ const results =
+ (
+ (await res.json()) as {
+ results?: {
+ type?: string;
+ response?: {
+ result?: {
+ cols: { name: string }[];
+ rows: { value?: string | number | null }[][];
+ affected_row_count?: number;
+ };
+ };
+ }[];
+ }
+ ).results ?? [];
+ return statements.map((_, i) => {
+ const result = results[i]?.type === "ok" ? results[i].response?.result : undefined;
+ if (!result) throw new OpError(502, "queue store refused the query");
+ return result;
+ });
+ }
+
+ /** Several reads in one round trip. Reads only: anything else throws. */
+ async reads(statements: { sql: string; args: (string | number)[] }[]): Promise {
+ for (const st of statements) {
+ if (!/^\s*select\b/i.test(st.sql)) throw new Error("the console only reads the queue store");
+ }
+ return (await this.pipeline(statements)).map((result) =>
+ result.rows.map((row) => Object.fromEntries(result.cols.map((c, i) => [c.name, row[i]?.value ?? null]))),
+ );
+ }
+
+ async sql(statement: string, args: (string | number)[]): Promise {
+ return (await this.reads([{ sql: statement, args }]))[0];
+ }
+
+ /**
+ * Move a queued task along the priority scale. The one write this
+ * service makes to the queue store, because the queue has no verb for
+ * it: one column, on one row, and only while the task is still queued.
+ */
+ async setTaskPriority(task: unknown, priority: unknown) {
+ const t = id(task, "task");
+ if (!PRIORITY_SCALE.includes(priority as (typeof PRIORITY_SCALE)[number])) {
+ throw new OpError(400, `priority: one of ${PRIORITY_SCALE.join(", ")}`);
+ }
+ const [result] = await this.pipeline([
+ {
+ sql: "UPDATE tasks SET priority = ? WHERE id = ? AND queue = ? AND status = 'queued'",
+ args: [priority as number, t, this.cfg.queue],
+ },
+ ]);
+ if (!result.affected_row_count) throw new OpError(409, `task ${t} is not queued, so its place cannot change`);
+ return { task: t, priority };
}
async queueCounts(): Promise> {
@@ -352,6 +398,19 @@ export class Ops {
return { issue: n, url: made.html_url };
}
+ /** Hand one packet to the queue. `fleet queue enqueue` reads a packet
+ * file, not stdin, so the packet lives in a private file for the call. */
+ async enqueue(packet: unknown): Promise {
+ const dir = mkdtempSync(join(tmpdir(), "pm-console-"));
+ const file = join(dir, "packet.json");
+ try {
+ writeFileSync(file, JSON.stringify(packet), { mode: 0o600 });
+ return await this.run([this.cfg.fleetBin, "queue", "enqueue", file, "--queue", this.cfg.queue]);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+
/**
* File an idea as an issue and enqueue its triage task in the same
* pass (doc/agents/one-queue-claiming-work.md): an issue with no queue
@@ -376,16 +435,7 @@ export class Ops {
rank as Rank,
new Date().toISOString(),
);
- // `fleet queue enqueue` reads a packet file, not stdin.
- const dir = mkdtempSync(join(tmpdir(), "pm-console-"));
- const file = join(dir, "packet.json");
- let queued: RunResult;
- try {
- writeFileSync(file, JSON.stringify(packet), { mode: 0o600 });
- queued = await this.run([this.cfg.fleetBin, "queue", "enqueue", file, "--queue", this.cfg.queue]);
- } finally {
- rmSync(dir, { recursive: true, force: true });
- }
+ const queued = await this.enqueue(packet);
return {
issue: made.number,
url: made.html_url,
diff --git a/pm-stack/console/src/push.ts b/pm-stack/console/src/push.ts
new file mode 100644
index 0000000000..3686f318b8
--- /dev/null
+++ b/pm-stack/console/src/push.ts
@@ -0,0 +1,247 @@
+// Web Push, with nothing but the platform's own cryptography.
+//
+// A notification reaches the phone through the browser vendor's push
+// service. The message is encrypted for the one browser that subscribed
+// (RFC 8291, aes128gcm), and the request is signed with this server's
+// own key pair so the push service knows who is sending (RFC 8292,
+// VAPID). The key pair is made here on first use and kept in this
+// service's state directory; nobody ever handles it.
+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import { dirname } from "node:path";
+
+const enc = new TextEncoder();
+const b64u = (bytes: Uint8Array | ArrayBuffer) => Buffer.from(bytes as ArrayBuffer).toString("base64url");
+const unb64u = (text: string) => new Uint8Array(Buffer.from(text, "base64url"));
+const concat = (...parts: Uint8Array[]) => {
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
+ let at = 0;
+ for (const p of parts) {
+ out.set(p, at);
+ at += p.length;
+ }
+ return out;
+};
+
+/** Push services a subscription may name. This server posts to the
+ * endpoint a browser gives it, so the endpoint has to be one of these. */
+const PUSH_HOSTS = [
+ /^fcm\.googleapis\.com$/,
+ /^([a-z0-9-]+\.)*push\.services\.mozilla\.com$/,
+ /^([a-z0-9-]+\.)*notify\.windows\.com$/,
+ /^([a-z0-9-]+\.)*push\.apple\.com$/,
+];
+
+export interface Subscription {
+ endpoint: string;
+ keys: { p256dh: string; auth: string };
+ at?: string;
+ label?: string;
+}
+
+/** Notification classes the owner can switch off one by one. */
+export const CLASSES = ["replies", "needs", "questions", "trouble"] as const;
+export type Class = (typeof CLASSES)[number];
+
+interface PushFile {
+ vapid: { publicKey: string; privateJwk: JsonWebKey } | null;
+ subscriptions: Subscription[];
+ off: Class[];
+}
+
+export function validSubscription(value: unknown): Subscription | null {
+ const v = value as { endpoint?: unknown; keys?: { p256dh?: unknown; auth?: unknown } } | null;
+ if (!v || typeof v.endpoint !== "string" || typeof v.keys?.p256dh !== "string" || typeof v.keys?.auth !== "string") {
+ return null;
+ }
+ let url: URL;
+ try {
+ url = new URL(v.endpoint);
+ } catch {
+ return null;
+ }
+ if (url.protocol !== "https:" || url.username || url.password || !PUSH_HOSTS.some((h) => h.test(url.hostname))) {
+ return null;
+ }
+ // An uncompressed P-256 point is 65 bytes; the auth secret is 16.
+ if (unb64u(v.keys.p256dh).length !== 65 || unb64u(v.keys.auth).length !== 16) return null;
+ return { endpoint: url.href, keys: { p256dh: v.keys.p256dh, auth: v.keys.auth } };
+}
+
+async function hkdf(salt: Uint8Array, ikm: Uint8Array, info: Uint8Array, length: number): Promise {
+ const key = await crypto.subtle.importKey("raw", ikm, "HKDF", false, ["deriveBits"]);
+ return new Uint8Array(await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt, info }, key, length * 8));
+}
+
+/** Encrypt one message for one subscription (RFC 8291). */
+export async function encrypt(sub: Subscription, plaintext: Uint8Array): Promise {
+ const uaPublic = unb64u(sub.keys.p256dh);
+ const authSecret = unb64u(sub.keys.auth);
+ const local = (await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, [
+ "deriveBits",
+ ])) as CryptoKeyPair;
+ const localPublic = new Uint8Array(await crypto.subtle.exportKey("raw", local.publicKey));
+ const peer = await crypto.subtle.importKey("raw", uaPublic, { name: "ECDH", namedCurve: "P-256" }, false, []);
+ const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: "ECDH", public: peer }, local.privateKey, 256));
+ const ikm = await hkdf(authSecret, shared, concat(enc.encode("WebPush: info\0"), uaPublic, localPublic), 32);
+ const salt = crypto.getRandomValues(new Uint8Array(16));
+ const cek = await hkdf(salt, ikm, enc.encode("Content-Encoding: aes128gcm\0"), 16);
+ const nonce = await hkdf(salt, ikm, enc.encode("Content-Encoding: nonce\0"), 12);
+ const key = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]);
+ // One record: the message, then the delimiter that marks the last record.
+ const sealed = new Uint8Array(
+ await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce }, key, concat(plaintext, new Uint8Array([2]))),
+ );
+ const header = new Uint8Array(16 + 4 + 1 + localPublic.length);
+ header.set(salt, 0);
+ new DataView(header.buffer).setUint32(16, 4096);
+ header[20] = localPublic.length;
+ header.set(localPublic, 21);
+ return concat(header, sealed);
+}
+
+type Poster = (
+ url: string,
+ init: { method: string; headers: Record; body: Uint8Array; signal?: AbortSignal },
+) => Promise<{ status: number }>;
+
+export class Push {
+ private state: PushFile | null = null;
+ private signer: CryptoKey | null = null;
+
+ constructor(
+ private file: string,
+ private subject: string,
+ private post: Poster = (url, init) => fetch(url, init as RequestInit),
+ private now: () => number = Date.now,
+ ) {}
+
+ private async load(): Promise {
+ if (this.state) return this.state;
+ try {
+ this.state = JSON.parse(await readFile(this.file, "utf8")) as PushFile;
+ } catch {
+ this.state = { vapid: null, subscriptions: [], off: [] };
+ }
+ if (!this.state.vapid) {
+ const pair = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [
+ "sign",
+ "verify",
+ ])) as CryptoKeyPair;
+ this.state.vapid = {
+ publicKey: b64u(await crypto.subtle.exportKey("raw", pair.publicKey)),
+ privateJwk: await crypto.subtle.exportKey("jwk", pair.privateKey),
+ };
+ await this.save();
+ }
+ return this.state;
+ }
+
+ private async save(): Promise {
+ if (!this.state) return;
+ await mkdir(dirname(this.file), { recursive: true, mode: 0o700 });
+ const tmp = `${this.file}.tmp-${process.pid}`;
+ await writeFile(tmp, JSON.stringify(this.state), { mode: 0o600 });
+ await rename(tmp, this.file);
+ }
+
+ /** What the page needs to subscribe, and what is switched on. */
+ async status() {
+ const s = await this.load();
+ return {
+ key: s.vapid?.publicKey ?? "",
+ devices: s.subscriptions.length,
+ classes: Object.fromEntries(CLASSES.map((c) => [c, !s.off.includes(c)])),
+ };
+ }
+
+ async subscribe(value: unknown, label: unknown) {
+ const sub = validSubscription(value);
+ if (!sub) throw new Error("subscription: not a push subscription from a known push service");
+ const s = await this.load();
+ s.subscriptions = [
+ ...s.subscriptions.filter((x) => x.endpoint !== sub.endpoint),
+ { ...sub, at: new Date(this.now()).toISOString(), label: typeof label === "string" ? label.slice(0, 80) : "" },
+ ].slice(-20);
+ await this.save();
+ return { devices: s.subscriptions.length };
+ }
+
+ async unsubscribe(endpoint: unknown) {
+ const s = await this.load();
+ const before = s.subscriptions.length;
+ s.subscriptions = s.subscriptions.filter((x) => x.endpoint !== endpoint);
+ if (s.subscriptions.length !== before) await this.save();
+ return { devices: s.subscriptions.length };
+ }
+
+ async setClass(cls: unknown, on: unknown) {
+ if (!CLASSES.includes(cls as Class)) throw new Error(`class: one of ${CLASSES.join(", ")}`);
+ const s = await this.load();
+ s.off = s.off.filter((c) => c !== cls);
+ if (on !== true) s.off.push(cls as Class);
+ await this.save();
+ return (await this.status()).classes;
+ }
+
+ private async vapid(endpoint: string): Promise {
+ const s = await this.load();
+ const v = s.vapid as NonNullable;
+ this.signer ??= await crypto.subtle.importKey("jwk", v.privateJwk, { name: "ECDSA", namedCurve: "P-256" }, false, [
+ "sign",
+ ]);
+ const head = b64u(enc.encode(JSON.stringify({ typ: "JWT", alg: "ES256" })));
+ const body = b64u(
+ enc.encode(
+ JSON.stringify({
+ aud: new URL(endpoint).origin,
+ exp: Math.floor(this.now() / 1000) + 12 * 3600,
+ sub: this.subject,
+ }),
+ ),
+ );
+ const sig = await crypto.subtle.sign(
+ { name: "ECDSA", hash: "SHA-256" },
+ this.signer,
+ enc.encode(`${head}.${body}`),
+ );
+ return `vapid t=${head}.${body}.${b64u(sig)}, k=${v.publicKey}`;
+ }
+
+ /** Send one notification to every subscribed device, unless its class
+ * is switched off. A subscription the push service says is gone is
+ * forgotten. Returns how many devices took it. */
+ async send(cls: Class | "test", message: { title: string; body: string; url: string; tag?: string }) {
+ const s = await this.load();
+ if (cls !== "test" && s.off.includes(cls)) return { sent: 0, gone: 0, failed: 0 };
+ const payload = enc.encode(JSON.stringify({ ...message, class: cls }));
+ let sent = 0;
+ let failed = 0;
+ const gone: string[] = [];
+ for (const sub of s.subscriptions) {
+ try {
+ const res = await this.post(sub.endpoint, {
+ method: "POST",
+ headers: {
+ Authorization: await this.vapid(sub.endpoint),
+ "Content-Encoding": "aes128gcm",
+ "Content-Type": "application/octet-stream",
+ TTL: "86400",
+ Urgency: "high",
+ },
+ body: await encrypt(sub, payload),
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (res.status === 404 || res.status === 410) gone.push(sub.endpoint);
+ else if (res.status >= 200 && res.status < 300) sent++;
+ else failed++;
+ } catch {
+ failed++;
+ }
+ }
+ if (gone.length) {
+ s.subscriptions = s.subscriptions.filter((x) => !gone.includes(x.endpoint));
+ await this.save();
+ }
+ return { sent, gone: gone.length, failed };
+ }
+}
diff --git a/pm-stack/console/src/server.ts b/pm-stack/console/src/server.ts
index a6fef3e7a3..3270bd6651 100644
--- a/pm-stack/console/src/server.ts
+++ b/pm-stack/console/src/server.ts
@@ -10,9 +10,14 @@
import { mkdirSync, readFileSync } from "node:fs";
import { appendFile } from "node:fs/promises";
import { dirname, join } from "node:path";
+import { actions, perform } from "./actions.ts";
import { AuthError, type Identity, identify } from "./auth.ts";
import { type Config, readConfig } from "./config.ts";
+import { DOC_NAMES, type DocName, Docs } from "./docs.ts";
+import { Notifier } from "./notify.ts";
import { OpError, Ops } from "./ops.ts";
+import { Push } from "./push.ts";
+import { Work } from "./work.ts";
const BASE = "/console";
const PUBLIC_DIR = join(import.meta.dir, "..", "public");
@@ -20,7 +25,32 @@ const STATIC = new Map([
["app.js", "text/javascript; charset=utf-8"],
["app.css", "text/css; charset=utf-8"],
["icon.svg", "image/svg+xml"],
+ ["sw.js", "text/javascript; charset=utf-8"],
]);
+
+/** The install manifest of the app at this origin. The home-screen icon
+ * opens the app, and a long press offers its four primary screens. */
+const MANIFEST = {
+ name: "PM",
+ short_name: "PM",
+ description: "What the fleet is doing, what is next, what needs you, and a place to say what you want.",
+ start_url: "/console/",
+ scope: "/",
+ display: "standalone",
+ background_color: "#0b0f14",
+ theme_color: "#11161d",
+ icons: [
+ { src: "/icons/icon-192.png", sizes: "192x192", type: "image/png", purpose: "any" },
+ { src: "/icons/icon-512.png", sizes: "512x512", type: "image/png", purpose: "any" },
+ { src: "/icons/icon-maskable-512.png", sizes: "512x512", type: "image/png", purpose: "maskable" },
+ ],
+ shortcuts: [
+ { name: "Ask the fleet", short_name: "Ask", url: "/console/#ask" },
+ { name: "Needs me", short_name: "Needs me", url: "/console/#needs" },
+ { name: "In progress", short_name: "Now", url: "/console/#now" },
+ { name: "Queued next", short_name: "Next", url: "/console/#next" },
+ ],
+};
const APK_NAME = "pm-console.apk";
const SECURITY = {
"Content-Security-Policy":
@@ -30,8 +60,7 @@ const SECURITY = {
};
/** The dashboard's files that are public, matched against the parsed
* path in full. They say nothing about the fleet. */
-const PUBLIC_DASHBOARD =
- /^\/(manifest\.webmanifest|icons\/(icon-192|icon-512|icon-maskable-512|apple-touch-icon)\.png)$/;
+const PUBLIC_DASHBOARD = /^\/icons\/(icon-192|icon-512|icon-maskable-512|apple-touch-icon)\.png$/;
/** Headers that belong to one connection, not to the request or response. */
const HOP_BY_HOP = new Set([
"connection",
@@ -95,6 +124,27 @@ export interface Deps {
audit: (entry: Record) => Promise;
/** Reaches the dashboard. Injected so tests can stand in for it. */
upstream?: (url: string, init: RequestInit) => Promise;
+ /** The interface's state, kept ready, and the actions it can take. */
+ docs?: Docs;
+ actions?: ReturnType;
+ work?: Work;
+ push?: Push;
+}
+
+/** Text that shrinks well. The dashboard's fragments run to a megabyte
+ * each, and the link to a phone is the slow part. */
+const COMPRESSIBLE = /^(text\/|application\/(json|javascript|manifest\+json|xml)|image\/svg\+xml)/;
+const COMPRESS_FROM_BYTES = 1024;
+
+function wantsGzip(req: Request): boolean {
+ return /\bgzip\b/.test(req.headers.get("accept-encoding") ?? "");
+}
+
+function gzipped(req: Request, bytes: Uint8Array, headers: Headers): Response | null {
+ if (!wantsGzip(req) || bytes.byteLength < COMPRESS_FROM_BYTES) return null;
+ headers.set("content-encoding", "gzip");
+ headers.append("vary", "accept-encoding");
+ return new Response(Bun.gzipSync(bytes), { headers });
}
/** A write must come from this site. A browser sends Origin on every
@@ -155,6 +205,15 @@ async function toDashboard(req: Request, url: URL, deps: Deps, open: boolean): P
for (const [name, value] of res.headers) {
if (!HOP_BY_HOP.has(name) && name !== "content-length" && name !== "content-encoding") out.append(name, value);
}
+ // A page or a fragment is finite: read it and send it compressed. An
+ // event stream that stays open (anything but a fragment) is passed
+ // through as it comes, since compressing would hold its events back.
+ const type = res.headers.get("content-type") ?? "";
+ const finite = type.startsWith("text/event-stream") ? url.pathname.startsWith("/frag/") : COMPRESSIBLE.test(type);
+ if (req.method !== "HEAD" && res.status === 200 && finite && wantsGzip(req)) {
+ const bytes = new Uint8Array(await res.arrayBuffer());
+ return gzipped(req, bytes, out) ?? new Response(bytes, { status: res.status, headers: out });
+ }
return new Response(req.method === "HEAD" ? null : res.body, { status: res.status, headers: out });
}
@@ -179,6 +238,11 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul
// Public, unauthenticated: nothing here says anything about the fleet.
if (path === "/.well-known/assetlinks.json" && method === "GET") return json(assetLinks(deps.cfg));
if (path === `${BASE}/health` && method === "GET") return json({ ok: true });
+ if (path === "/manifest.webmanifest" && method === "GET") {
+ return new Response(JSON.stringify(MANIFEST), {
+ headers: { "Content-Type": "application/manifest+json; charset=utf-8", "Cache-Control": "no-cache", ...SECURITY },
+ });
+ }
const ours = path === BASE || path.startsWith(`${BASE}/`);
if (!ours) {
if (deps.cfg.dashboardUrl === null) return json({ error: "not found" }, 404);
@@ -195,6 +259,9 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul
}
if (!ours) {
if (crossSiteWrite(req)) return json({ error: "this request did not come from this site" }, 403);
+ // The front door is the app. The dashboard's own home stays one
+ // link away, under More, at /?dashboard.
+ if (method === "GET" && path === "/" && url.search === "") return Response.redirect(`${BASE}/`, 302);
return toDashboard(req, url, deps, false);
}
@@ -259,6 +326,22 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul
return json(await ops.prs());
}
}
+ if (seg.length === 2 && seg[0] === "doc" && deps.docs && DOC_NAMES.includes(seg[1] as DocName)) {
+ const doc = await deps.docs.doc(seg[1] as DocName);
+ const headers = new Headers({
+ "Content-Type": "application/json; charset=utf-8",
+ "Cache-Control": "no-cache",
+ ETag: doc.etag,
+ "X-As-Of": String(doc.asOf),
+ ...SECURITY,
+ });
+ if (req.headers.get("if-none-match") === doc.etag) return new Response(null, { status: 304, headers });
+ return gzipped(req, new TextEncoder().encode(doc.body), headers) ?? new Response(doc.body, { headers });
+ }
+ if (seg.length === 1 && seg[0] === "push" && deps.push) return json(await deps.push.status());
+ if (seg.length === 1 && seg[0] === "question" && deps.work) {
+ return json(await deps.work.question(query.get("set"), query.get("ledger"), query.get("qid")));
+ }
if (seg.length === 2 && seg[0] === "prs") return json(await ops.pr(seg[1]));
if (seg.length === 3 && seg[0] === "services" && seg[2] === "logs") {
return json(await ops.serviceLogs(seg[1], query.get("lines")));
@@ -315,6 +398,33 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul
}
};
+ if (seg.length === 1 && seg[0] === "act" && deps.docs && deps.actions) {
+ const { docs, actions: table } = deps;
+ const kind = typeof body.kind === "string" ? body.kind : "";
+ const args = body.args ?? {};
+ const kept =
+ Object.hasOwn(table, kind) && args !== null && typeof args === "object"
+ ? table[kind].audit(args as Record)
+ : {};
+ const entry = {
+ id: crypto.randomUUID(),
+ kind,
+ at: new Date().toISOString(),
+ by: who.email ?? who.certName ?? who.sub ?? who.via,
+ note: "",
+ };
+ return await act(kind || "unknown", kept, async () => {
+ docs.logAct({ ...entry, status: "running" });
+ try {
+ const result = await perform(table, docs, kind, args);
+ docs.logAct({ ...entry, status: "done" });
+ return result;
+ } catch (error) {
+ docs.logAct({ ...entry, status: "failed", note: (error as Error).message.slice(0, 200) });
+ throw error;
+ }
+ });
+ }
if (seg.length === 3 && seg[0] === "queue") {
return await act(`queue.${seg[2]}`, { task: seg[1], reason: body.reason }, () =>
ops.queueAct(seg[2], seg[1], body.reason),
@@ -350,13 +460,75 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul
}
}
+/** How often each source is read again while someone is looking. */
+export function loaders(
+ ops: Ops,
+ work: Work,
+ more: unknown,
+): Record Promise }> {
+ return {
+ board: { ttlMs: 10_000, load: () => work.board() },
+ sessions: { ttlMs: 20_000, load: () => work.sessions() },
+ census: { ttlMs: 60_000, load: () => work.census() },
+ asks: { ttlMs: 20_000, load: () => work.asks() },
+ questionCount: {
+ ttlMs: 15_000,
+ load: async () => {
+ const q = await work.questions();
+ return { total: q.total, sets: q.sets };
+ },
+ },
+ questions: { ttlMs: 15_000, load: () => work.questions() },
+ prs: { ttlMs: 45_000, load: () => ops.prs() },
+ priorities: { ttlMs: 120_000, load: () => ops.priorities() },
+ agents: { ttlMs: 30_000, load: () => ops.agents() },
+ services: { ttlMs: 20_000, load: () => ops.services() },
+ more: { ttlMs: 3_600_000, load: async () => more },
+ };
+}
+
+/** The dashboard's own pages, grouped as it groups them, for the list
+ * under More. Read from the dashboard's manifest beside this package;
+ * if that is not there, the list is simply empty. */
+export async function morePages(): Promise<
+ { group: string; pages: { title: string; route: string; blurb: string }[] }[]
+> {
+ try {
+ const manifest = (await import("../../aggregator/src/pages.ts")) as {
+ PAGE_GROUPS: { id: string; title: string }[];
+ PAGES: { title: string; route: string; blurb: string; group: string }[];
+ };
+ return manifest.PAGE_GROUPS.map((g) => ({
+ group: g.title,
+ pages: manifest.PAGES.filter((pg) => pg.group === g.id).map((pg) => ({
+ title: pg.title,
+ // The dashboard's home is at /, which is now the app's front door.
+ route: pg.route === "/" ? "/?dashboard" : pg.route,
+ blurb: pg.blurb,
+ })),
+ })).filter((g) => g.pages.length > 0);
+ } catch {
+ return [];
+ }
+}
+
if (import.meta.main) {
const cfg = readConfig();
const ops = new Ops(cfg);
mkdirSync(dirname(cfg.auditFile), { recursive: true, mode: 0o700 });
+ const work = new Work(ops);
+ const docs = new Docs(loaders(ops, work, await morePages()));
+ docs.start();
+ const state = dirname(cfg.auditFile);
+ const push = new Push(join(state, "push.json"), `mailto:${cfg.owners[0] ?? "owner@invalid.example"}`);
+ new Notifier(docs, push, join(state, "notified.json")).start();
const deps: Deps = {
cfg,
ops,
+ docs,
+ work,
+ push,
+ actions: actions(ops, work, push),
identify: (req, peer) => identify(req, cfg, { peer }),
audit: (entry) => appendFile(cfg.auditFile, `${JSON.stringify(entry)}\n`, { mode: 0o600 }),
};
diff --git a/pm-stack/console/src/work.ts b/pm-stack/console/src/work.ts
new file mode 100644
index 0000000000..a679676914
--- /dev/null
+++ b/pm-stack/console/src/work.ts
@@ -0,0 +1,597 @@
+// What the owner looks at first: the work in progress, what comes next,
+// what is waiting on him, and what he has asked for.
+//
+// Reads come from the queue store, the dashboard's own data and GitHub.
+// Every write is something the fleet already understands: an answer to a
+// decision set through the dashboard's own endpoint, an issue and a
+// queue task, a comment, a label.
+import { readFile } from "node:fs/promises";
+import { OpError, type Ops, PRIORITY_SCALE, type Row } from "./ops.ts";
+
+const P = "CASE WHEN json_valid(payload) THEN payload ELSE '{}' END";
+const G = "CASE WHEN json_valid(progress) THEN progress ELSE '{}' END";
+const TASK_COLS = `id, title, priority, status, attempts,
+ substr(coalesce(claimed_at,''),1,19) AS claimed, substr(coalesce(lease_until,''),1,19) AS lease,
+ substr(created_at,1,19) AS created, worker_id AS worker, lane_id AS lane, claim_model AS model,
+ json_extract(${P},'$.kind') AS kind, json_extract(${P},'$.issue.number') AS issue,
+ json_extract(${P},'$.pr.number') AS pr,
+ substr(coalesce(json_extract(${G},'$.next'), json_extract(${G},'$.last_checkpoint.progress'),
+ json_extract(${G},'$.last_checkpoint.stage'), ''),1,400) AS step,
+ substr(coalesce(json_extract(${P},'$.acceptance[0]'),''),1,300) AS goal`;
+
+const OWNER_PROMPT_MARK = "";
+const OWNER_REPLY_MARK = "";
+const ASK_NOTE =
+ "This is an instruction from the owner, in his own words, sent from the PM console. Work out what he wants and do it with the fleet's own verbs; if it is a question, answer it here. Say on this issue what you did, with links, and close it when nothing is left.";
+const SET_ID = /^[A-Za-z0-9._:-]{1,160}$/;
+const REF = /^([A-Za-z0-9._-]+\/[A-Za-z0-9._-]+)#([1-9][0-9]{0,8})$/;
+const LEANS = ["none", "skeptical", "approve"] as const;
+
+function clip(value: unknown, max: number): string {
+ const s = typeof value === "string" ? value : "";
+ return s.length > max ? `${s.slice(0, max - 1)}…` : s;
+}
+
+function words(value: unknown, name: string, max: number): string {
+ if (typeof value !== "string" || value.trim() === "") throw new OpError(400, `${name}: required`);
+ if (value.length > max) throw new OpError(400, `${name}: at most ${max} characters`);
+ return value.trim();
+}
+
+export interface DecisionOption {
+ id: string;
+ label: string;
+ tags?: string[];
+}
+interface DecisionQuestion {
+ qid: string;
+ question: string;
+ context?: string;
+ description?: string;
+ mode?: string;
+ order?: number;
+ recommendedOptionIds?: string[];
+ options: DecisionOption[];
+ resolution?: unknown;
+}
+interface DecisionItem {
+ ledgerId: string;
+ title: string;
+ order?: number;
+ group?: string;
+ links?: string[];
+ questions: DecisionQuestion[];
+}
+interface DecisionSet {
+ setId: string;
+ title: string;
+ token: string;
+ createdAt: string;
+ items: DecisionItem[];
+}
+export interface Submission {
+ ledgerId: string;
+ qid: string;
+ kind: "answered" | "deferred";
+ optionId?: string;
+ optionIds?: string[];
+ freeText?: string;
+ comment?: string;
+ lean?: (typeof LEANS)[number];
+}
+
+/** The task that carries out an owner prompt. Top band: the owner asked.
+ * It takes the issue's triage key, the one key the queue has for "someone
+ * must look at this issue", so an issue never has two tasks: a reply on a
+ * prompt whose task is still live joins it, and one whose task has
+ * finished gets a new one. */
+export function promptPacket(repo: string, queue: string, number: number, text: string, at: string) {
+ const url = `https://github.com/${repo}/issues/${number}`;
+ const first = text.split("\n")[0].trim();
+ return {
+ title: `Owner prompt ${repo}#${number}: ${first}`.slice(0, 180),
+ body: `Instruction from the owner, sent from the PM console: ${url}`,
+ priority: 10,
+ dedupe_key: `repo-health:v1:triage:${repo}:issue:${number}`,
+ payload: {
+ schema: "repo-task/v1",
+ kind: "triage",
+ repo,
+ queue,
+ issue: { number, url, title: `Owner: ${first}`.slice(0, 120), state_checked_at: at },
+ problem:
+ "The owner wrote this instruction in his own words from the PM console. It is not a report to classify: it is something he wants done, or a question he wants answered.",
+ evidence: [`Sent from the PM console at ${at}`, url],
+ acceptance: [
+ "What the owner asked for is done with the fleet's own verbs, or answered if it is a question",
+ "A comment on the issue says in plain words what was done, with links, or what could not be done and why",
+ "The issue is closed when nothing is left; work that outlasts this task is filed, enqueued and linked from the issue",
+ ],
+ tests: ["The issue carries the report comment and is closed, or carries the reason it is still open"],
+ scope: {
+ include: [`Carry out the owner's instruction on ${repo}#${number}`],
+ exclude: ["Secrets, credentials or purchases"],
+ },
+ risk: { level: "low", flags: ["owner-prompt"] },
+ priority_reason: "Owner prompt from the console: top band (10).",
+ timebox_minutes: 45,
+ max_attempts: 1000,
+ context_refs: [url],
+ dedupe: { checked_at: at, basis: "Created with its issue, or with the owner's reply, in the same pass." },
+ },
+ };
+}
+
+export class Work {
+ private labelReady = false;
+ private replies = new Map();
+
+ constructor(
+ private ops: Ops,
+ private read: (path: string) => Promise = (path) => readFile(path, "utf8"),
+ private clock: () => Date = () => new Date(),
+ ) {}
+
+ private get repo() {
+ return this.ops.cfg.repo;
+ }
+
+ private task = (r: Row) => ({
+ ...r,
+ url: r.issue ? `https://github.com/${this.repo}/issues/${r.issue}` : null,
+ });
+
+ /** In progress and next, in the order the queue will hand work out. */
+ async board() {
+ const q = this.ops.cfg.queue;
+ const [counts, now, next, why] = await this.ops.reads([
+ {
+ sql: "SELECT status, count(*) AS n FROM tasks WHERE queue = ? AND status IN ('queued','claimed','blocked','parked') GROUP BY status",
+ args: [q],
+ },
+ {
+ sql: `SELECT ${TASK_COLS} FROM tasks WHERE queue = ? AND status = 'claimed' ORDER BY claimed_at DESC, id DESC LIMIT 60`,
+ args: [q],
+ },
+ {
+ sql: `SELECT ${TASK_COLS} FROM tasks WHERE queue = ? AND status = 'queued' ORDER BY (priority IS NULL), priority ASC, created_at ASC, id ASC LIMIT 60`,
+ args: [q],
+ },
+ {
+ sql: `SELECT substr(coalesce(json_extract(${G},'$.reason'), json_extract(${G},'$.blocker'), ready_condition, blocked_deps, 'no reason recorded'),1,140) AS why, count(*) AS n FROM tasks WHERE queue = ? AND status = 'blocked' GROUP BY 1 ORDER BY n DESC LIMIT 6`,
+ args: [q],
+ },
+ ]);
+ return {
+ counts: Object.fromEntries(counts.map((r) => [String(r.status), Number(r.n)])),
+ now: now.map(this.task),
+ next: next.map(this.task),
+ blockedWhy: why,
+ };
+ }
+
+ private async dash(path: string, body?: unknown): Promise {
+ const base = this.ops.cfg.dashboardUrl;
+ if (base === null) throw new OpError(502, "no dashboard is configured");
+ const res = await this.ops.fetchImpl(`${base}${path}`, {
+ method: body === undefined ? "GET" : "POST",
+ headers: { accept: "application/json", ...(body === undefined ? {} : { "content-type": "application/json" }) },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ signal: AbortSignal.timeout(20_000),
+ });
+ const data = await res.json().catch(() => null);
+ if (!res.ok) {
+ const why = (data as { error?: string } | null)?.error ?? `http ${res.status}`;
+ throw new OpError(
+ res.status === 400 || res.status === 403 || res.status === 404 ? 400 : 502,
+ `dashboard: ${why}`,
+ );
+ }
+ return data;
+ }
+
+ /** Agent sessions that are moving, and what the dashboard's own tiers
+ * say is waiting on the owner. */
+ async sessions() {
+ const all = (await this.dash("/api/attention.json")) as Record[];
+ const moving = all
+ .filter((e) => e.tier === "in-motion")
+ .map((e) => ({
+ id: clip(e.sessionId, 80),
+ title: clip(e.title, 160),
+ agent: clip(e.agent, 60),
+ model: clip(e.model, 60),
+ where: clip(e.directory, 200).split("/").slice(-2).join("/"),
+ last: clip(e.lastActivityAt, 30),
+ tools: Number(e.activeToolCalls) || 0,
+ messages: Number(e.messageCount) || 0,
+ }))
+ .sort((a, b) => b.last.localeCompare(a.last));
+ const waiting = all
+ .filter((e) => e.tier === "needs-drew")
+ .map((e) => ({
+ id: clip(e.id, 120),
+ title: clip(e.title, 300),
+ ref: clip(e.ref, 120),
+ why: clip(e.drewReason, 300),
+ }));
+ return { moving, waiting };
+ }
+
+ /** Issues and pull requests labelled as waiting on the owner. */
+ async census() {
+ const data = (await this.dash("/api/needs-drew.json")) as {
+ fetchedAt?: string;
+ complete?: boolean;
+ items?: {
+ ref: string;
+ kind: string;
+ title: string;
+ url: string;
+ needsLabels: string[];
+ reason: string | null;
+ updatedAt: string;
+ hands?: { kind: string; action: string | null } | null;
+ }[];
+ };
+ const base = (i: NonNullable[number]) => ({
+ ref: i.ref,
+ title: clip(i.title, 200),
+ url: i.url,
+ pr: i.kind === "pr",
+ updated: clip(i.updatedAt, 19),
+ });
+ const items = data.items ?? [];
+ return {
+ at: data.fetchedAt ?? null,
+ complete: data.complete !== false,
+ // A hands item is one action only a person can do (FDR-0013).
+ hands: items
+ .filter((i) => i.hands?.kind)
+ .map((i) => ({ ...base(i), kind: i.hands?.kind, action: clip(i.hands?.action, 400) })),
+ reviews: items.filter((i) => !i.hands?.kind && i.needsLabels.includes("user/review")).map(base),
+ // Escalated with no stated action: the fleet's to decide, listed so nothing is hidden.
+ other: items
+ .filter((i) => !i.hands?.kind && !i.needsLabels.includes("user/review"))
+ .map((i) => ({ ...base(i), why: clip(i.reason, 300) })),
+ };
+ }
+
+ private async sets(): Promise {
+ let raw: { sets?: DecisionSet[] };
+ try {
+ raw = JSON.parse(await this.read(this.ops.cfg.decisionsFile));
+ } catch (error) {
+ throw new OpError(502, `the questions store could not be read: ${(error as Error).message.slice(0, 120)}`);
+ }
+ return Array.isArray(raw.sets) ? raw.sets : [];
+ }
+
+ /** Every open question, newest set first. The per-set tokens stay here. */
+ async questions() {
+ const sets = (await this.sets()).sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)));
+ const open = [];
+ const byOrder = (a: { order?: number }, b: { order?: number }) => (a.order ?? 0) - (b.order ?? 0);
+ for (const set of sets) {
+ for (const item of [...(set.items ?? [])].sort(byOrder)) {
+ for (const q of [...(item.questions ?? [])].sort(byOrder)) {
+ if (q.resolution) continue;
+ open.push({
+ set: set.setId,
+ setTitle: clip(set.title, 120),
+ created: clip(set.createdAt, 19),
+ ledger: item.ledgerId,
+ item: clip(item.title, 200),
+ links: (item.links ?? []).slice(0, 3),
+ qid: q.qid,
+ q: clip(q.question, 600),
+ // The list carries a line of background; the rest is read
+ // when a question is opened, so 360 questions fit a phone.
+ context: clip(q.context, 280),
+ more: (q.context ?? "").length > 280 || Boolean(q.description),
+ multi: q.mode === "multi",
+ recommended: q.recommendedOptionIds ?? [],
+ options: (q.options ?? []).map((o) => ({ id: o.id, label: clip(o.label, 240), tags: o.tags ?? [] })),
+ });
+ }
+ }
+ }
+ return { total: open.length, sets: new Set(open.map((q) => q.set)).size, open };
+ }
+
+ /** The full background of one question, read when it is opened. */
+ async question(setId: unknown, ledger: unknown, qid: unknown) {
+ const set = (await this.sets()).find((s) => s.setId === setId);
+ const q = set?.items?.find((i) => i.ledgerId === ledger)?.questions?.find((x) => x.qid === qid);
+ if (!q) throw new OpError(404, "that question is not in the store");
+ return { context: clip(q.context, 8000), detail: clip(q.description, 8000) };
+ }
+
+ /** Answer or hand back questions through the dashboard's own endpoint,
+ * so everything downstream of an answer happens as it always has. */
+ async submit(setId: unknown, submissions: Submission[]) {
+ if (typeof setId !== "string" || !SET_ID.test(setId)) throw new OpError(400, "set: not a decision set id");
+ if (submissions.length === 0) throw new OpError(400, "nothing to submit");
+ const set = (await this.sets()).find((s) => s.setId === setId);
+ if (!set) throw new OpError(404, "that decision set is not in the store");
+ const out = (await this.dash(`/api/decisions/${encodeURIComponent(setId)}/submit`, {
+ token: set.token,
+ submissions,
+ })) as { outcomes?: { qid: string; applied: boolean; reason?: string }[] };
+ const outcomes = out.outcomes ?? [];
+ return {
+ set: setId,
+ applied: outcomes.filter((o) => o.applied).length,
+ refused: outcomes.filter((o) => !o.applied).map((o) => ({ qid: o.qid, why: o.reason ?? "not applied" })),
+ };
+ }
+
+ async answer(args: Record) {
+ const sub: Submission = {
+ ledgerId: words(args.ledger, "ledger", 300),
+ qid: words(args.qid, "qid", 300),
+ kind: "answered",
+ };
+ if (typeof args.option === "string" && args.option !== "") sub.optionId = words(args.option, "option", 200);
+ if (Array.isArray(args.options) && args.options.length > 0) {
+ sub.optionIds = args.options.slice(0, 20).map((o) => words(o, "options", 200));
+ }
+ if (typeof args.text === "string" && args.text.trim() !== "") sub.freeText = words(args.text, "text", 4000);
+ if (typeof args.comment === "string" && args.comment.trim() !== "")
+ sub.comment = words(args.comment, "comment", 2000);
+ if (!sub.optionId && !sub.optionIds && !sub.freeText) throw new OpError(400, "choose an option or write an answer");
+ return this.submit(args.set, [sub]);
+ }
+
+ /** "Decide for me": hand the question back with a lean. */
+ async defer(args: Record) {
+ const lean = args.lean === undefined ? "approve" : args.lean;
+ if (!LEANS.includes(lean as (typeof LEANS)[number])) throw new OpError(400, `lean: one of ${LEANS.join(", ")}`);
+ return this.submit(args.set, [
+ {
+ ledgerId: words(args.ledger, "ledger", 300),
+ qid: words(args.qid, "qid", 300),
+ kind: "deferred",
+ lean: lean as (typeof LEANS)[number],
+ },
+ ]);
+ }
+
+ /** Take the recommended option on every open question of one set that has one. */
+ async acceptRecommended(setId: unknown) {
+ const set = (await this.sets()).find((s) => s.setId === setId);
+ if (!set) throw new OpError(404, "that decision set is not in the store");
+ const subs: Submission[] = [];
+ for (const item of set.items ?? []) {
+ for (const q of item.questions ?? []) {
+ const rec = q.recommendedOptionIds ?? [];
+ if (q.resolution || rec.length === 0) continue;
+ subs.push(
+ q.mode === "multi"
+ ? { ledgerId: item.ledgerId, qid: q.qid, kind: "answered", optionIds: rec }
+ : { ledgerId: item.ledgerId, qid: q.qid, kind: "answered", optionId: rec[0] },
+ );
+ }
+ }
+ if (subs.length === 0) throw new OpError(409, "no open question in that set has a recommendation");
+ return this.submit(setId, subs);
+ }
+
+ private ref(value: unknown): { repo: string; number: number } {
+ const m = typeof value === "string" ? REF.exec(value) : null;
+ if (!m || !this.ops.cfg.needsRepos.includes(m[1])) throw new OpError(400, "ref: not an item on the Needs me list");
+ return { repo: m[1], number: Number(m[2]) };
+ }
+
+ /** The owner did the one thing only he could: say so and take the item off his list. */
+ async handsDone(args: Record) {
+ const { repo, number } = this.ref(args.ref);
+ const note =
+ typeof args.note === "string" && args.note.trim() !== "" ? `\n\n${words(args.note, "note", 4000)}` : "";
+ await this.ops.gh(["-X", "POST", `repos/${repo}/issues/${number}/comments`], {
+ body: `Done by the owner, from the PM console. The step that needed a person is finished; carry on.${note}\n\n${OWNER_REPLY_MARK}`,
+ });
+ await this.ops.gh([
+ "-X",
+ "DELETE",
+ `repos/${repo}/issues/${number}/labels/${encodeURIComponent("user/escalated")}`,
+ ]);
+ return { ref: args.ref, done: true };
+ }
+
+ async needComment(args: Record) {
+ const { repo, number } = this.ref(args.ref);
+ const made = (await this.ops.gh(["-X", "POST", `repos/${repo}/issues/${number}/comments`], {
+ body: `${words(args.text, "text", 8000)}\n\n${OWNER_REPLY_MARK}`,
+ })) as { html_url: string };
+ return { ref: args.ref, url: made.html_url };
+ }
+
+ // ---- asks: what the owner has told the fleet to do, in his words ------
+
+ async asks() {
+ const label = this.ops.cfg.promptLabel;
+ const found = (await this.ops.gh([
+ "-X",
+ "GET",
+ "search/issues",
+ "-f",
+ `q=repo:${this.repo} is:issue label:"${label}" sort:updated-desc`,
+ "-f",
+ "per_page=20",
+ ])) as {
+ items: {
+ number: number;
+ title: string;
+ body: string | null;
+ html_url: string;
+ state: string;
+ created_at: string;
+ updated_at: string;
+ comments: number;
+ }[];
+ };
+ // The newest task for each prompt's issue, by the key the task was filed under.
+ const keys = found.items.map((i) => `repo-health:v1:triage:${this.repo}:issue:${i.number}`);
+ const tasks = keys.length
+ ? await this.ops.sql(
+ `SELECT dedupe_key, status, worker_id AS worker FROM tasks WHERE queue = ? AND dedupe_key IN (${keys.map(() => "?").join(",")}) ORDER BY id DESC LIMIT 200`,
+ [this.ops.cfg.queue, ...keys],
+ )
+ : [];
+ const taskOf = new Map();
+ for (const t of tasks) {
+ const n = Number(/:issue:(\d+)$/.exec(String(t.dedupe_key))?.[1]);
+ if (n && !taskOf.has(n)) taskOf.set(n, t);
+ }
+ const out = [];
+ for (const i of found.items) {
+ let thread = this.replies.get(i.number);
+ if (i.comments > 0 && thread?.updated !== i.updated_at) {
+ const comments = (await this.ops.gh([`repos/${this.repo}/issues/${i.number}/comments?per_page=100`])) as {
+ body: string | null;
+ created_at: string;
+ }[];
+ thread = {
+ updated: i.updated_at,
+ replies: comments.slice(-6).map((c) => ({
+ you: (c.body ?? "").includes(OWNER_REPLY_MARK),
+ at: c.created_at.slice(0, 19),
+ text: clip((c.body ?? "").replace(OWNER_REPLY_MARK, "").trim(), 1500),
+ })),
+ };
+ this.replies.set(i.number, thread);
+ }
+ const replies = i.comments > 0 ? (thread?.replies ?? []) : [];
+ const task = taskOf.get(i.number);
+ const answered = replies.length > 0 && !replies[replies.length - 1].you;
+ out.push({
+ issue: i.number,
+ url: i.html_url,
+ text: clip((i.body ?? "").split("\n---\n")[0].trim() || i.title, 2000),
+ created: i.created_at.slice(0, 19),
+ updated: i.updated_at.slice(0, 19),
+ // done: closed. working: an agent holds the task. answered: the last word is the fleet's.
+ status:
+ i.state === "closed"
+ ? "done"
+ : task?.status === "claimed"
+ ? "working"
+ : answered
+ ? "answered"
+ : task?.status === "queued"
+ ? "queued"
+ : "waiting",
+ worker: task?.status === "claimed" ? task.worker : null,
+ replies,
+ });
+ }
+ return out;
+ }
+
+ private async ensureLabel() {
+ if (this.labelReady) return;
+ const made = await this.ops.run(
+ [this.ops.cfg.fleetBin, "gh", "api", "-X", "POST", `repos/${this.repo}/labels`, "--input", "-"],
+ {
+ stdin: JSON.stringify({
+ name: this.ops.cfg.promptLabel,
+ color: "5319e7",
+ description: "An instruction from the owner, in his words (PM console)",
+ }),
+ },
+ );
+ // Exit 0: created. "already_exists": it was there. Anything else is a real failure.
+ if (made.code !== 0 && !/already_exists/.test(made.stdout + made.stderr)) {
+ throw new OpError(502, `could not prepare the ${this.ops.cfg.promptLabel} label`);
+ }
+ this.labelReady = true;
+ }
+
+ /** Turn the owner's words into an issue and a top-band task, in one pass. */
+ async ask(args: Record) {
+ const text = words(args.text, "text", 8000);
+ await this.ensureLabel();
+ const first = text.split("\n")[0].trim();
+ const made = (await this.ops.gh(["-X", "POST", `repos/${this.repo}/issues`], {
+ title: `Owner: ${first}`.slice(0, 120),
+ body: `${text}\n\n---\n${ASK_NOTE}\n${OWNER_PROMPT_MARK}`,
+ labels: [this.ops.cfg.promptLabel, "expedite"],
+ })) as { number: number; html_url: string };
+ const queued = await this.ops.enqueue(
+ promptPacket(this.repo, this.ops.cfg.queue, made.number, text, this.clock().toISOString()),
+ );
+ return {
+ issue: made.number,
+ url: made.html_url,
+ queued: queued.code === 0,
+ ...(queued.code === 0
+ ? {}
+ : { note: `filed, not queued: ${(queued.stderr || queued.stdout).trim().split("\n").pop()?.slice(0, 200)}` }),
+ };
+ }
+
+ /** The owner answers back on one of his prompts; the fleet is woken for it. */
+ async askReply(args: Record) {
+ const issue = Number(args.issue);
+ if (!Number.isSafeInteger(issue) || issue <= 0) throw new OpError(400, "issue: a positive whole number");
+ const text = words(args.text, "text", 8000);
+ const current = (await this.ops.gh([`repos/${this.repo}/issues/${issue}`])) as {
+ state: string;
+ labels: { name: string }[];
+ };
+ if (!current.labels.some((l) => l.name === this.ops.cfg.promptLabel)) {
+ throw new OpError(400, "that issue is not one of the owner's prompts");
+ }
+ await this.ops.gh(["-X", "POST", `repos/${this.repo}/issues/${issue}/comments`], {
+ body: `${text}\n\n${OWNER_REPLY_MARK}`,
+ });
+ if (current.state === "closed") {
+ await this.ops.gh(["-X", "PATCH", `repos/${this.repo}/issues/${issue}`], { state: "open" });
+ }
+ const queued = await this.ops.enqueue(
+ promptPacket(this.repo, this.ops.cfg.queue, issue, text, this.clock().toISOString()),
+ );
+ return { issue, queued: queued.code === 0 };
+ }
+
+ /** Nothing is left on a prompt: close it. */
+ async askClose(args: Record) {
+ const issue = Number(args.issue);
+ if (!Number.isSafeInteger(issue) || issue <= 0) throw new OpError(400, "issue: a positive whole number");
+ const current = (await this.ops.gh([`repos/${this.repo}/issues/${issue}`])) as { labels: { name: string }[] };
+ if (!current.labels.some((l) => l.name === this.ops.cfg.promptLabel)) {
+ throw new OpError(400, "that issue is not one of the owner's prompts");
+ }
+ await this.ops.gh(["-X", "PATCH", `repos/${this.repo}/issues/${issue}`], {
+ state: "closed",
+ state_reason: "completed",
+ });
+ return { issue, closed: true };
+ }
+
+ /** Move a queued task: to the top band, or one step sooner or later. */
+ async moveTask(args: Record) {
+ const task = Number(args.task);
+ if (!Number.isSafeInteger(task) || task <= 0) throw new OpError(400, "task: a positive whole number");
+ if (args.to === "first") return this.ops.setTaskPriority(task, PRIORITY_SCALE[0]);
+ if (args.to !== "sooner" && args.to !== "later") throw new OpError(400, "to: first, sooner or later");
+ const [row] = await this.ops.sql("SELECT priority FROM tasks WHERE id = ? AND queue = ? AND status = 'queued'", [
+ task,
+ this.ops.cfg.queue,
+ ]);
+ if (!row) throw new OpError(409, `task ${task} is not queued, so its place cannot change`);
+ const scale = PRIORITY_SCALE as readonly number[];
+ const current = Number(row.priority ?? 30);
+ // The nearest step on the scale in the direction asked.
+ const target =
+ args.to === "sooner" ? [...scale].reverse().find((p) => p < current) : scale.find((p) => p > current);
+ if (target === undefined) {
+ throw new OpError(
+ 409,
+ `task ${task} is already ${args.to === "sooner" ? "in the top band" : "in the last band"}`,
+ );
+ }
+ return this.ops.setTaskPriority(task, target);
+ }
+}
diff --git a/pm-stack/console/test/console.test.ts b/pm-stack/console/test/console.test.ts
index 82637ac9d0..ba2ed260b5 100644
--- a/pm-stack/console/test/console.test.ts
+++ b/pm-stack/console/test/console.test.ts
@@ -977,7 +977,6 @@ describe("HTTP surface", () => {
});
const PUBLIC = [
- "/manifest.webmanifest",
"/icons/icon-192.png",
"/icons/icon-512.png",
"/icons/icon-maskable-512.png",
@@ -1026,6 +1025,11 @@ describe("HTTP surface", () => {
expect(call.method).toBe("GET");
expect(call.headers).toEqual({ host: "pm.security.cab", "accept-encoding": "identity" });
}
+ expect((await handle(post("/icons/icon-192.png", {}), out)).status).toBe(401);
+ // The install manifest is the app's own: public, and it opens the app.
+ const manifest = await handle(get("/manifest.webmanifest"), out);
+ expect(manifest.headers.get("content-type")).toContain("application/manifest+json");
+ expect(await manifest.json()).toMatchObject({ start_url: "/console/", scope: "/", display: "standalone" });
expect((await handle(post("/manifest.webmanifest", {}), out)).status).toBe(401);
expect(out.sent.length).toBe(PUBLIC.length);
});
diff --git a/pm-stack/console/test/push.test.ts b/pm-stack/console/test/push.test.ts
new file mode 100644
index 0000000000..68943184ce
--- /dev/null
+++ b/pm-stack/console/test/push.test.ts
@@ -0,0 +1,337 @@
+// Notifications: the message a phone receives, and when one is owed.
+//
+// Oracles: the test plays the browser. It makes the subscription's key
+// pair itself and decrypts what the server sends with the receiving
+// half of RFC 8291, written here from the RFC and not shared with the
+// code under test; it verifies the VAPID signature with the server's
+// public key. "Owed" is decided by a table of before and after states.
+import { describe, expect, test } from "bun:test";
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { Docs } from "../src/docs.ts";
+import { changes, NOTHING_SEEN, Notifier, type Seen } from "../src/notify.ts";
+import { encrypt, Push, validSubscription } from "../src/push.ts";
+
+const b64u = (b: ArrayBuffer | Uint8Array) => Buffer.from(b as ArrayBuffer).toString("base64url");
+const raw = (s: string) => new Uint8Array(Buffer.from(s, "base64url"));
+
+async function browser(host = "fcm.googleapis.com") {
+ const pair = (await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, [
+ "deriveBits",
+ ])) as CryptoKeyPair;
+ const auth = crypto.getRandomValues(new Uint8Array(16));
+ const p256dh = new Uint8Array(await crypto.subtle.exportKey("raw", pair.publicKey));
+ const hkdf = async (salt: Uint8Array, ikm: Uint8Array, info: Uint8Array, n: number) =>
+ new Uint8Array(
+ await crypto.subtle.deriveBits(
+ { name: "HKDF", hash: "SHA-256", salt, info },
+ await crypto.subtle.importKey("raw", ikm, "HKDF", false, ["deriveBits"]),
+ n * 8,
+ ),
+ );
+ const cat = (...p: Uint8Array[]) => new Uint8Array(p.flatMap((x) => [...x]));
+ const t = new TextEncoder();
+ return {
+ subscription: { endpoint: `https://${host}/fcm/send/abc123`, keys: { p256dh: b64u(p256dh), auth: b64u(auth) } },
+ /** RFC 8291 section 3.4 and RFC 8188: what a user agent does with the body. */
+ async open(body: Uint8Array): Promise {
+ const salt = body.slice(0, 16);
+ const rs = new DataView(body.buffer, body.byteOffset).getUint32(16);
+ const idlen = body[20];
+ const sender = body.slice(21, 21 + idlen);
+ const sealed = body.slice(21 + idlen);
+ expect(rs).toBe(4096);
+ expect(idlen).toBe(65);
+ const shared = new Uint8Array(
+ await crypto.subtle.deriveBits(
+ {
+ name: "ECDH",
+ public: await crypto.subtle.importKey("raw", sender, { name: "ECDH", namedCurve: "P-256" }, false, []),
+ },
+ pair.privateKey,
+ 256,
+ ),
+ );
+ const ikm = await hkdf(auth, shared, cat(t.encode("WebPush: info\0"), p256dh, sender), 32);
+ const cek = await hkdf(salt, ikm, t.encode("Content-Encoding: aes128gcm\0"), 16);
+ const nonce = await hkdf(salt, ikm, t.encode("Content-Encoding: nonce\0"), 12);
+ const plain = new Uint8Array(
+ await crypto.subtle.decrypt(
+ { name: "AES-GCM", iv: nonce },
+ await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]),
+ sealed,
+ ),
+ );
+ expect(plain[plain.length - 1]).toBe(2); // the last-record delimiter
+ return new TextDecoder().decode(plain.slice(0, -1));
+ },
+ };
+}
+
+describe("the message a phone receives", () => {
+ test("only the subscribed browser can read it, and each one is sealed afresh", async () => {
+ const b = await browser();
+ const text = JSON.stringify({ title: "The fleet replied on #12501", body: "Done — and “quoted” ✓" });
+ const one = await encrypt(b.subscription, new TextEncoder().encode(text));
+ const two = await encrypt(b.subscription, new TextEncoder().encode(text));
+ expect(await b.open(one)).toBe(text);
+ expect(await b.open(two)).toBe(text);
+ expect(b64u(one)).not.toBe(b64u(two)); // a new salt and a new sender key every time
+ const other = await browser();
+ await expect(other.open(one)).rejects.toThrow(); // not readable by anyone else
+ const flipped = one.slice();
+ flipped[flipped.length - 3] ^= 1;
+ await expect(b.open(flipped)).rejects.toThrow(); // and not alterable on the way
+ });
+
+ test("a send is signed for the push service it goes to, and reaches every device", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "pm-push-"));
+ try {
+ const a = await browser();
+ const m = await browser("updates.push.services.mozilla.com");
+ const posts: { url: string; headers: Record; body: Uint8Array }[] = [];
+ const NOW = 1_800_000_000_000;
+ const push = new Push(
+ join(dir, "push.json"),
+ "mailto:owner@example.com",
+ async (url, init) => (posts.push({ url, headers: init.headers, body: init.body }), { status: 201 }),
+ () => NOW,
+ );
+ const status = await push.status();
+ expect(raw(status.key).length).toBe(65); // an uncompressed P-256 point, as the browser expects
+ expect(status.devices).toBe(0);
+ await push.subscribe(a.subscription, "phone");
+ await push.subscribe(a.subscription, "phone again"); // the same device is not counted twice
+ expect((await push.subscribe(m.subscription, "desktop")).devices).toBe(2);
+ expect(await push.send("replies", { title: "t", body: "b", url: "/console/#ask", tag: "x" })).toEqual({
+ sent: 2,
+ gone: 0,
+ failed: 0,
+ });
+ expect(posts.map((p) => p.url)).toEqual([a.subscription.endpoint, m.subscription.endpoint]);
+ expect(JSON.parse(await a.open(posts[0].body))).toEqual({
+ title: "t",
+ body: "b",
+ url: "/console/#ask",
+ tag: "x",
+ class: "replies",
+ });
+ expect(JSON.parse(await m.open(posts[1].body)).class).toBe("replies");
+ for (const p of posts) {
+ expect(p.headers["Content-Encoding"]).toBe("aes128gcm");
+ expect(Number(p.headers.TTL)).toBeGreaterThan(0);
+ const [, jwt, key] = /^vapid t=([^,]+), k=(.+)$/.exec(p.headers.Authorization) ?? [];
+ expect(key).toBe(status.key);
+ const [head, body, sig] = jwt.split(".");
+ expect(JSON.parse(Buffer.from(head, "base64url").toString())).toEqual({ typ: "JWT", alg: "ES256" });
+ const claims = JSON.parse(Buffer.from(body, "base64url").toString());
+ expect(claims.aud).toBe(new URL(p.url).origin); // signed for this push service and no other
+ expect(claims.sub).toBe("mailto:owner@example.com");
+ expect(claims.exp).toBe(NOW / 1000 + 12 * 3600); // within the 24 hours a push service allows
+ const pub = await crypto.subtle.importKey("raw", raw(key), { name: "ECDSA", namedCurve: "P-256" }, false, [
+ "verify",
+ ]);
+ expect(
+ await crypto.subtle.verify(
+ { name: "ECDSA", hash: "SHA-256" },
+ pub,
+ raw(sig),
+ new TextEncoder().encode(`${head}.${body}`),
+ ),
+ ).toBe(true);
+ }
+ // The key pair and the devices survive a restart; the file is private.
+ const again = new Push(join(dir, "push.json"), "mailto:owner@example.com", async () => ({ status: 201 }));
+ expect(await again.status()).toEqual(status.devices === 0 ? { ...status, devices: 2 } : status);
+ expect((await again.status()).key).toBe(status.key);
+ expect(JSON.parse(readFileSync(join(dir, "push.json"), "utf8")).vapid.privateJwk.d.length).toBeGreaterThan(20);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test("a device that is gone is forgotten, a class switched off sends nothing, a failure is counted", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "pm-push-"));
+ try {
+ const a = await browser();
+ const b = await browser("web.push.apple.com");
+ let answer = (url: string) => (url === a.subscription.endpoint ? 410 : 201);
+ let posts = 0;
+ const push = new Push(
+ join(dir, "push.json"),
+ "mailto:o@example.com",
+ async (url) => (posts++, { status: answer(url) }),
+ );
+ await push.subscribe(a.subscription, "");
+ await push.subscribe(b.subscription, "");
+ expect(await push.send("needs", { title: "t", body: "b", url: "/" })).toEqual({ sent: 1, gone: 1, failed: 0 });
+ expect((await push.status()).devices).toBe(1);
+ expect(await push.setClass("needs", false)).toEqual({
+ replies: true,
+ needs: false,
+ questions: true,
+ trouble: true,
+ });
+ posts = 0;
+ expect(await push.send("needs", { title: "t", body: "b", url: "/" })).toEqual({ sent: 0, gone: 0, failed: 0 });
+ expect(posts).toBe(0);
+ expect((await push.send("test", { title: "t", body: "b", url: "/" })).sent).toBe(1); // a test ignores the switches
+ await push.setClass("needs", true);
+ answer = () => 500;
+ expect(await push.send("needs", { title: "t", body: "b", url: "/" })).toEqual({ sent: 0, gone: 0, failed: 1 });
+ expect((await push.status()).devices).toBe(1); // a failure is not "gone"
+ await expect(push.setClass("everything", true)).rejects.toThrow(/class/);
+ expect((await push.unsubscribe(b.subscription.endpoint)).devices).toBe(0);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test("the server only posts to push services", async () => {
+ const good = (await browser()).subscription;
+ expect(validSubscription(good)).toEqual(good);
+ for (const endpoint of [
+ "http://fcm.googleapis.com/fcm/send/x", // not https
+ "https://127.0.0.1:4870/api/alerts", // this machine
+ "https://fcm.googleapis.com.evil.example/x",
+ "https://evil.example/fcm.googleapis.com",
+ "https://user:pw@fcm.googleapis.com/x",
+ "https://queue-broker.security.cab/enqueue",
+ "not a url",
+ ]) {
+ expect(validSubscription({ ...good, endpoint })).toBeNull();
+ }
+ expect(validSubscription({ ...good, keys: { ...good.keys, p256dh: "AAAA" } })).toBeNull();
+ expect(validSubscription({ ...good, keys: { ...good.keys, auth: "AAAA" } })).toBeNull();
+ expect(validSubscription({ endpoint: good.endpoint })).toBeNull();
+ expect(validSubscription(null)).toBeNull();
+ const dir = mkdtempSync(join(tmpdir(), "pm-push-"));
+ try {
+ await expect(
+ new Push(join(dir, "p.json"), "mailto:o@example.com").subscribe(
+ { ...good, endpoint: "https://127.0.0.1/x" },
+ "",
+ ),
+ ).rejects.toThrow(/push service/);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe("when a notification is owed", () => {
+ const reply = (at: string, you = false) => ({ you, at, text: "Done. #12279 is first in the queue." });
+ const state = (over: Record = {}) => ({
+ asks: [
+ { issue: 12501, replies: [reply("2026-11-22T06:00:00")] },
+ { issue: 12502, replies: [] },
+ ],
+ census: { hands: [{ ref: "o/r#1", title: "t1", action: "Power on the host." }] },
+ sessions: { waiting: [] },
+ questionCount: { total: 360 },
+ services: [
+ { unit: "a.service", active: "active" },
+ { unit: "b.service", active: "failed" },
+ ],
+ ...over,
+ });
+
+ test("turning notifications on takes stock and says nothing", () => {
+ const first = changes(NOTHING_SEEN, state());
+ expect(first.messages).toEqual([]);
+ expect(first.seen).toEqual({
+ primed: true,
+ asks: { "12501": "2026-11-22T06:00:00" },
+ hands: ["o/r#1"],
+ questions: 360,
+ failed: ["b.service"],
+ });
+ expect(changes(first.seen, state()).messages).toEqual([]); // and nothing is said twice
+ });
+
+ test("each new thing is announced once, with where to go", () => {
+ const seen: Seen = changes(NOTHING_SEEN, state()).seen;
+ const later = state({
+ asks: [
+ { issue: 12501, replies: [reply("2026-11-22T06:00:00"), reply("2026-11-22T07:00:00")] },
+ { issue: 12502, replies: [reply("2026-11-22T07:05:00", true)] },
+ ],
+ census: {
+ hands: [
+ { ref: "o/r#1", title: "t1", action: "Power on the host." },
+ { ref: "o/r#2", title: "Sign the form", action: "" },
+ ],
+ },
+ sessions: { waiting: [{ id: "porkbun", title: "Log into the main account" }] },
+ questionCount: { total: 363 },
+ services: [
+ { unit: "a.service", active: "failed" },
+ { unit: "b.service", active: "failed" },
+ ],
+ });
+ const out = changes(seen, later);
+ expect(out.messages.map((m) => [m.cls, m.title, m.body, m.url])).toEqual([
+ ["replies", "The fleet replied on #12501", "Done. #12279 is first in the queue.", "/console/#ask"],
+ ["needs", "Something needs you", "Sign the form", "/console/#needs/hands"],
+ ["needs", "Something needs you", "Log into the main account", "/console/#needs/hands"],
+ ["questions", "3 new questions for you", "363 open in all.", "/console/#needs/questions"],
+ ["trouble", "A unit failed", "a.service", "/console/#more/services"],
+ ]);
+ expect(changes(out.seen, later).messages).toEqual([]);
+ // His own reply is not news to him; fewer questions is not news either,
+ // but it lowers the mark, so the next new one is.
+ const fewer = changes(out.seen, { ...later, questionCount: { total: 300 } });
+ expect(fewer.messages).toEqual([]);
+ expect(changes(fewer.seen, { ...later, questionCount: { total: 301 } }).messages.map((m) => m.title)).toEqual([
+ "1 new question for you",
+ ]);
+ // Something that went away and came back needs him again.
+ const gone = changes(out.seen, { ...later, census: { hands: [] }, sessions: { waiting: [] } });
+ expect(changes(gone.seen, later).messages.filter((m) => m.cls === "needs").length).toBe(3);
+ });
+
+ test("a source that could not be read changes nothing", () => {
+ const seen = changes(NOTHING_SEEN, state()).seen;
+ const blind = changes(seen, { asks: null, census: null, sessions: null, questionCount: null, services: null });
+ expect(blind.messages).toEqual([]);
+ expect(blind.seen).toEqual(seen); // nothing is forgotten, so nothing is announced again when it reads once more
+ });
+
+ test("the notifier reads the sources itself, sends what is owed, and remembers across restarts", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "pm-notify-"));
+ try {
+ let now = state();
+ const still = { ttlMs: 1e12, load: async () => "x" };
+ const sections = { board: still, prs: still, priorities: still, agents: still, more: still, questions: still };
+ const live = (name: string) => ({ ttlMs: 1e12, load: async () => (now as Record)[name] });
+ const docs = new Docs({
+ ...sections,
+ asks: live("asks"),
+ census: live("census"),
+ sessions: live("sessions"),
+ questionCount: live("questionCount"),
+ services: live("services"),
+ });
+ const sent: string[] = [];
+ const b = await browser();
+ const push = new Push(
+ join(dir, "push.json"),
+ "mailto:o@example.com",
+ async (_u, init) => (sent.push(JSON.parse(await b.open(init.body)).title), { status: 201 }),
+ );
+ const notifier = new Notifier(docs, push, join(dir, "notified.json"));
+ expect(await notifier.tick()).toBe(0); // no device: nothing is read, nothing is sent
+ await push.subscribe(b.subscription, "phone");
+ expect(await notifier.tick()).toBe(0); // first pass: take stock
+ now = state({ questionCount: { total: 361 } });
+ expect(await notifier.tick()).toBe(1);
+ expect(sent).toEqual(["1 new question for you"]);
+ const restarted = new Notifier(docs, push, join(dir, "notified.json"));
+ expect(await restarted.tick()).toBe(0);
+ expect(sent.length).toBe(1);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/pm-stack/console/test/work.test.ts b/pm-stack/console/test/work.test.ts
new file mode 100644
index 0000000000..7ae3914020
--- /dev/null
+++ b/pm-stack/console/test/work.test.ts
@@ -0,0 +1,796 @@
+// The primary screens: what is in progress, what is next, what needs the
+// owner, and what he has asked for.
+//
+// Oracles: the queue store, the dashboard and the fleet's commands are
+// recorders, so every read and write is compared with what it should be
+// as an exact statement, request or argument vector. The questions store
+// is a file written by the test, so "open" and "recommended" are defined
+// here and not by the code under test.
+import { describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { gunzipSync } from "node:zlib";
+import { actions, perform } from "../src/actions.ts";
+import { readConfig } from "../src/config.ts";
+import { Docs } from "../src/docs.ts";
+import { type Fetch, OpError, Ops, type Run } from "../src/ops.ts";
+import { type Deps, handle, loaders } from "../src/server.ts";
+import { promptPacket, Work } from "../src/work.ts";
+
+const CFG = readConfig({ HOME: "/h" });
+const REPO = "developing-today/code";
+
+type Sql = { sql: string; args: (string | number)[] };
+/** A queue store and a dashboard in one fetch, both recording. */
+function world(opts: {
+ rows?: (st: Sql) => Record[] | { affected: number };
+ dash?: (path: string, body: unknown) => unknown | { status: number; error: string };
+ commands?: (argv: string[], stdin?: string) => string | { code: number; stderr: string };
+}) {
+ const sqls: Sql[][] = [];
+ const dashed: { path: string; body: unknown }[] = [];
+ const calls: { argv: string[]; stdin?: string; packet?: unknown }[] = [];
+ const fetchImpl: Fetch = async (url, init) => {
+ if (url.startsWith(CFG.queueDbUrl)) {
+ const requests = (
+ JSON.parse(init.body ?? "{}").requests as {
+ type: string;
+ stmt?: { sql: string; args: { value: string; type: string }[] };
+ }[]
+ ).filter((r) => r.type === "execute");
+ const batch = requests.map((r) => ({
+ sql: r.stmt?.sql ?? "",
+ args: (r.stmt?.args ?? []).map((a) => (a.type === "integer" ? Number(a.value) : a.value)),
+ }));
+ sqls.push(batch);
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ results: batch.map((st) => {
+ const out = opts.rows?.(st) ?? [];
+ if (!Array.isArray(out))
+ return { type: "ok", response: { result: { cols: [], rows: [], affected_row_count: out.affected } } };
+ const cols = Object.keys(out[0] ?? {}).map((name) => ({ name }));
+ return {
+ type: "ok",
+ response: { result: { cols, rows: out.map((r) => cols.map((c) => ({ value: r[c.name] }))) } },
+ };
+ }),
+ }),
+ };
+ }
+ const path = url.replace(CFG.dashboardUrl ?? "", "");
+ const body = init.body ? JSON.parse(init.body) : undefined;
+ dashed.push({ path, body });
+ const out = opts.dash?.(path, body) ?? {};
+ const failed = out !== null && typeof out === "object" && "status" in out && "error" in out;
+ return { ok: !failed, status: failed ? (out as { status: number }).status : 200, json: async () => out };
+ };
+ const run: Run = async (argv, o) => {
+ const entry: { argv: string[]; stdin?: string; packet?: unknown } = { argv, stdin: o?.stdin };
+ if (argv[1] === "queue" && argv[2] === "enqueue") entry.packet = JSON.parse(readFileSync(argv[3], "utf8"));
+ calls.push(entry);
+ if (argv[1] === "secrets") return { code: 0, stdout: "token\n", stderr: "" };
+ const a = opts.commands?.(argv, o?.stdin) ?? "{}";
+ return typeof a === "string" ? { code: 0, stdout: a, stderr: "" } : { code: a.code, stdout: "", stderr: a.stderr };
+ };
+ const ops = new Ops(CFG, run, fetchImpl);
+ return { ops, sqls, dashed, calls, gh: () => calls.filter((c) => c.argv[1] === "gh").map((c) => c.argv.slice(3)) };
+}
+
+const TOKEN = "set-token-never-leaves-the-host";
+function store(extra: Record = {}) {
+ const q = (qid: string, more: Record = {}) => ({
+ qid,
+ question: `Question ${qid}?`,
+ context: "c".repeat(900),
+ description: "d",
+ options: [
+ { id: "opt-1", label: "First", tags: ["recommended"] },
+ { id: "opt-2", label: "Second" },
+ ],
+ recommendedOptionIds: ["opt-1"],
+ ...more,
+ });
+ return JSON.stringify({
+ version: 1,
+ sets: [
+ {
+ setId: "old-set",
+ title: "Older",
+ token: `${TOKEN}-old`,
+ createdAt: "2026-11-10T00:00:00Z",
+ items: [{ ledgerId: "L0", title: "Old item", group: "g", links: [], questions: [q("a")] }],
+ },
+ {
+ setId: "new-set",
+ title: "Newer",
+ token: TOKEN,
+ createdAt: "2026-11-17T00:00:00Z",
+ items: [
+ {
+ ledgerId: "L1",
+ title: "Item one",
+ group: "g",
+ links: ["https://github.com/developing-today/code/issues/10036"],
+ questions: [
+ q("b", { order: 2 }),
+ q("c", { order: 1, mode: "multi", recommendedOptionIds: ["opt-1", "opt-2"] }),
+ q("answered", { resolution: { kind: "answered", at: "x", via: "y" } }),
+ q("norec", { order: 3, recommendedOptionIds: [] }),
+ ],
+ },
+ ],
+ },
+ ],
+ ...extra,
+ });
+}
+
+describe("what is in progress and what is next", () => {
+ test("one round trip, reads only, in the queue's own order", async () => {
+ const w = world({
+ rows: (st) =>
+ st.sql.includes("GROUP BY status")
+ ? [
+ { status: "claimed", n: 3 },
+ { status: "blocked", n: 474 },
+ ]
+ : st.sql.includes("'claimed'")
+ ? [{ id: 7, title: "t", issue: 9075, kind: "small_fix", step: "next thing" }]
+ : [],
+ });
+ const board = await new Work(w.ops).board();
+ expect(w.sqls.length).toBe(1);
+ expect(w.sqls[0].length).toBe(4);
+ for (const st of w.sqls[0]) {
+ expect(st.sql.trimStart().startsWith("SELECT")).toBe(true);
+ expect(st.args).toEqual(["repo-health-code-pilot"]);
+ }
+ // In progress: newest claim first. Next: the claim order the queue itself uses.
+ expect(w.sqls[0][1].sql).toContain("status = 'claimed' ORDER BY claimed_at DESC");
+ expect(w.sqls[0][2].sql).toContain(
+ "status = 'queued' ORDER BY (priority IS NULL), priority ASC, created_at ASC, id ASC",
+ );
+ // A row whose progress or payload is not JSON must not fail the whole read.
+ expect(w.sqls[0][1].sql).toContain("json_valid(progress)");
+ expect(w.sqls[0][1].sql).toContain("json_valid(payload)");
+ expect(board.counts).toEqual({ claimed: 3, blocked: 474 });
+ expect(board.now).toEqual([
+ {
+ id: 7,
+ title: "t",
+ issue: 9075,
+ kind: "small_fix",
+ step: "next thing",
+ url: `https://github.com/${REPO}/issues/9075`,
+ },
+ ]);
+ });
+
+ test("moving a queued task changes one column on one queued row, along the scale", async () => {
+ const run = async (to: string, current: number | null, affected = 1) => {
+ const w = world({
+ rows: (st) => (st.sql.startsWith("UPDATE") ? { affected } : current === null ? [] : [{ priority: current }]),
+ });
+ const out = await new Work(w.ops).moveTask({ task: 21016, to }).catch((e: OpError) => e.status);
+ return { out, writes: w.sqls.flat().filter((s) => !s.sql.startsWith("SELECT")) };
+ };
+ const update = (priority: number) => [
+ {
+ sql: "UPDATE tasks SET priority = ? WHERE id = ? AND queue = ? AND status = 'queued'",
+ args: [priority, 21016, "repo-health-code-pilot"],
+ },
+ ];
+ expect(await run("first", 30)).toEqual({ out: { task: 21016, priority: 10 }, writes: update(10) });
+ expect(await run("sooner", 30)).toEqual({ out: { task: 21016, priority: 20 }, writes: update(20) });
+ expect(await run("later", 30)).toEqual({ out: { task: 21016, priority: 40 }, writes: update(40) });
+ expect(await run("later", 50)).toEqual({ out: { task: 21016, priority: 70 }, writes: update(70) });
+ // Off-scale values in the store still move to the nearest step in the direction asked.
+ expect(await run("sooner", 25)).toEqual({ out: { task: 21016, priority: 20 }, writes: update(20) });
+ // Nothing further to move to, a task that is no longer queued, and a bad request: no write.
+ expect(await run("sooner", 10)).toEqual({ out: 409, writes: [] });
+ expect(await run("later", 90)).toEqual({ out: 409, writes: [] });
+ expect(await run("sooner", null)).toEqual({ out: 409, writes: [] });
+ expect((await run("first", 30, 0)).out).toBe(409);
+ expect(await run("sideways", 30)).toEqual({ out: 400, writes: [] });
+ const w = world({});
+ for (const [task, priority] of [
+ [1, 25],
+ [1, 0],
+ ["1; DROP", 10],
+ [-1, 10],
+ ] as const) {
+ await expect(w.ops.setTaskPriority(task, priority)).rejects.toThrow(OpError);
+ }
+ expect(w.sqls).toEqual([]);
+ await expect(w.ops.reads([{ sql: "UPDATE tasks SET status = 'done'", args: [] }])).rejects.toThrow(/only reads/);
+ });
+});
+
+describe("questions waiting on the owner", () => {
+ test("only open questions, newest set first, and the answer tokens stay on the host", async () => {
+ const w = world({});
+ const q = await new Work(w.ops, async () => store()).questions();
+ expect(q.total).toBe(4);
+ expect(q.sets).toBe(2);
+ expect(q.open.map((x) => [x.set, x.qid])).toEqual([
+ ["new-set", "c"],
+ ["new-set", "b"],
+ ["new-set", "norec"],
+ ["old-set", "a"],
+ ]);
+ expect(q.open[0]).toMatchObject({ multi: true, recommended: ["opt-1", "opt-2"], ledger: "L1", setTitle: "Newer" });
+ expect(q.open[0].context.length).toBe(280);
+ expect(q.open[0].more).toBe(true);
+ expect(JSON.stringify(q)).not.toContain(TOKEN);
+ // The rest of the background is read when the question is opened.
+ const work = new Work(w.ops, async () => store());
+ expect(await work.question("new-set", "L1", "b")).toEqual({ context: "c".repeat(900), detail: "d" });
+ await expect(work.question("new-set", "L1", "nope")).rejects.toThrow(/not in the store/);
+ await expect(work.question("__proto__", "L1", "b")).rejects.toThrow(/not in the store/);
+ await expect(new Work(w.ops, async () => "not json").questions()).rejects.toThrow(/questions store/);
+ expect((await new Work(w.ops, async () => "{}").questions()).total).toBe(0);
+ });
+
+ test("an answer goes through the dashboard's own endpoint with the set's token", async () => {
+ const w = world({ dash: () => ({ outcomes: [{ qid: "b", applied: true }] }) });
+ const work = new Work(w.ops, async () => store());
+ expect(
+ await work.answer({ set: "new-set", ledger: "L1", qid: "b", option: "opt-2", comment: " because " }),
+ ).toEqual({ set: "new-set", applied: 1, refused: [] });
+ expect(w.dashed).toEqual([
+ {
+ path: "/api/decisions/new-set/submit",
+ body: {
+ token: TOKEN,
+ submissions: [{ ledgerId: "L1", qid: "b", kind: "answered", optionId: "opt-2", comment: "because" }],
+ },
+ },
+ ]);
+ await work.answer({ set: "new-set", ledger: "L1", qid: "c", options: ["opt-1", "opt-2"] });
+ await work.answer({ set: "new-set", ledger: "L1", qid: "b", text: "my own answer" });
+ await work.defer({ set: "new-set", ledger: "L1", qid: "b" });
+ expect(w.dashed.slice(1).map((d) => (d.body as { submissions: unknown[] }).submissions[0])).toEqual([
+ { ledgerId: "L1", qid: "c", kind: "answered", optionIds: ["opt-1", "opt-2"] },
+ { ledgerId: "L1", qid: "b", kind: "answered", freeText: "my own answer" },
+ { ledgerId: "L1", qid: "b", kind: "deferred", lean: "approve" },
+ ]);
+ const before = w.dashed.length;
+ for (const args of [
+ { set: "new-set", ledger: "L1", qid: "b" }, // nothing chosen
+ { set: "../etc", ledger: "L1", qid: "b", option: "opt-1" },
+ { set: "missing-set", ledger: "L1", qid: "b", option: "opt-1" },
+ { set: "new-set", ledger: "", qid: "b", option: "opt-1" },
+ { set: "new-set", ledger: "L1", qid: "b", text: "x".repeat(4001) },
+ ]) {
+ await expect(work.answer(args)).rejects.toThrow(OpError);
+ }
+ await expect(work.defer({ set: "new-set", ledger: "L1", qid: "b", lean: "whatever" })).rejects.toThrow(/lean/);
+ expect(w.dashed.length).toBe(before);
+ // What the dashboard refuses is reported, not hidden.
+ const refusing = world({ dash: () => ({ outcomes: [{ qid: "b", applied: false, reason: "already answered" }] }) });
+ expect(
+ await new Work(refusing.ops, async () => store()).answer({
+ set: "new-set",
+ ledger: "L1",
+ qid: "b",
+ option: "opt-1",
+ }),
+ ).toEqual({ set: "new-set", applied: 0, refused: [{ qid: "b", why: "already answered" }] });
+ const down = world({ dash: () => ({ status: 403, error: "unknown set or bad token" }) });
+ await expect(
+ new Work(down.ops, async () => store()).answer({ set: "new-set", ledger: "L1", qid: "b", option: "opt-1" }),
+ ).rejects.toThrow(/bad token/);
+ });
+
+ test("accepting recommendations answers exactly the open questions that have one", async () => {
+ const w = world({
+ dash: (_p, body) => ({
+ outcomes: (body as { submissions: { qid: string }[] }).submissions.map((s) => ({ qid: s.qid, applied: true })),
+ }),
+ });
+ const work = new Work(w.ops, async () => store());
+ expect((await work.acceptRecommended("new-set")).applied).toBe(2);
+ expect((w.dashed[0].body as { submissions: unknown[] }).submissions).toEqual([
+ { ledgerId: "L1", qid: "b", kind: "answered", optionId: "opt-1" },
+ { ledgerId: "L1", qid: "c", kind: "answered", optionIds: ["opt-1", "opt-2"] },
+ ]);
+ await expect(work.acceptRecommended("nope")).rejects.toThrow(/not in the store/);
+ const none = JSON.parse(store());
+ none.sets[1].items[0].questions = none.sets[1].items[0].questions.filter((q: { qid: string }) => q.qid === "norec");
+ await expect(new Work(w.ops, async () => JSON.stringify(none)).acceptRecommended("new-set")).rejects.toThrow(
+ /no open question/,
+ );
+ });
+});
+
+describe("what needs the owner's hands", () => {
+ test("the census is split into what only he can do, reviews, and the rest", async () => {
+ const item = (n: number, labels: string[], hands?: unknown) => ({
+ ref: `${REPO}#${n}`,
+ kind: "issue",
+ title: `t${n}`,
+ url: `u${n}`,
+ needsLabels: labels,
+ reason: n === 3 ? "why" : null,
+ updatedAt: "2026-11-20T01:02:03Z",
+ hands,
+ });
+ const w = world({
+ dash: (path) =>
+ path === "/api/needs-drew.json"
+ ? {
+ fetchedAt: "x",
+ complete: true,
+ items: [
+ item(1, ["user/escalated"], { kind: "physical", action: "Power on the host." }),
+ item(2, ["user/review"]),
+ item(3, ["user/escalated"]),
+ item(4, ["user/escalated", "user/review"], { kind: "payment", action: null }),
+ ],
+ }
+ : [
+ {
+ tier: "in-motion",
+ sessionId: "s",
+ title: "moving",
+ agent: "build",
+ model: "m",
+ directory: "/home/user/git/code-j",
+ lastActivityAt: "2026-11-22T00:00:00Z",
+ activeToolCalls: 2,
+ messageCount: 9,
+ },
+ { tier: "needs-drew", id: "p", title: "log in", ref: "gh:x/y#1", drewReason: null },
+ { tier: "needs-orchestrator", title: "not his" },
+ ],
+ });
+ const work = new Work(w.ops);
+ const c = await work.census();
+ expect(c.hands.map((i) => [i.ref, i.kind, i.action])).toEqual([
+ [`${REPO}#1`, "physical", "Power on the host."],
+ [`${REPO}#4`, "payment", ""],
+ ]);
+ expect(c.reviews.map((i) => i.ref)).toEqual([`${REPO}#2`]);
+ expect(c.other.map((i) => [i.ref, i.why])).toEqual([[`${REPO}#3`, "why"]]);
+ const s = await work.sessions();
+ expect(s.moving).toEqual([
+ {
+ id: "s",
+ title: "moving",
+ agent: "build",
+ model: "m",
+ where: "git/code-j",
+ last: "2026-11-22T00:00:00Z",
+ tools: 2,
+ messages: 9,
+ },
+ ]);
+ expect(s.waiting).toEqual([{ id: "p", title: "log in", ref: "gh:x/y#1", why: "" }]);
+ });
+
+ test("done means a comment and the label gone, only for a repository on the list", async () => {
+ const w = world({});
+ const work = new Work(w.ops);
+ await work.handsDone({ ref: "dezren39/nix#12", note: " the BMC is on " });
+ expect(w.gh()).toEqual([
+ ["-X", "POST", "repos/dezren39/nix/issues/12/comments", "--input", "-"],
+ ["-X", "DELETE", "repos/dezren39/nix/issues/12/labels/user%2Fescalated"],
+ ]);
+ expect(JSON.parse(w.calls[0].stdin ?? "").body).toContain("the BMC is on");
+ await work.needComment({ ref: `${REPO}#5`, text: "go on" });
+ expect(w.gh()[2]).toEqual(["-X", "POST", `repos/${REPO}/issues/5/comments`, "--input", "-"]);
+ const before = w.calls.length;
+ for (const ref of ["someone/else#1", `${REPO}#0`, `${REPO}#1/labels`, `${REPO}`, "", 7, `../${REPO}#1`]) {
+ await expect(work.handsDone({ ref })).rejects.toThrow(OpError);
+ }
+ await expect(work.needComment({ ref: `${REPO}#5`, text: " " })).rejects.toThrow(OpError);
+ expect(w.calls.length).toBe(before);
+ });
+});
+
+describe("what the owner asks for in his own words", () => {
+ test("a prompt becomes a labelled issue and a top-band task in one pass", async () => {
+ const w = world({
+ commands: (argv) =>
+ argv.includes(`repos/${REPO}/issues`) ? JSON.stringify({ number: 12501, html_url: "https://x/12501" }) : "{}",
+ });
+ const work = new Work(w.ops, undefined, () => new Date("2026-11-22T06:00:00Z"));
+ expect(await work.ask({ text: "Make the join slice the top priority\nand tell me what is in its way." })).toEqual({
+ issue: 12501,
+ url: "https://x/12501",
+ queued: true,
+ });
+ expect(w.gh()).toEqual([
+ ["-X", "POST", `repos/${REPO}/labels`, "--input", "-"],
+ ["-X", "POST", `repos/${REPO}/issues`, "--input", "-"],
+ ]);
+ const issue = JSON.parse(w.calls[1].stdin ?? "");
+ expect(issue.title).toBe("Owner: Make the join slice the top priority");
+ expect(issue.labels).toEqual(["owner/prompt", "expedite"]);
+ expect(issue.body.startsWith("Make the join slice the top priority\nand tell me")).toBe(true);
+ expect(issue.body).toContain("");
+ const enqueue = w.calls[2];
+ expect(enqueue.argv.slice(0, 3)).toEqual(["fleet", "queue", "enqueue"]);
+ expect(enqueue.argv.slice(4)).toEqual(["--queue", "repo-health-code-pilot"]);
+ expect(enqueue.packet).toEqual(
+ promptPacket(
+ REPO,
+ "repo-health-code-pilot",
+ 12501,
+ "Make the join slice the top priority\nand tell me what is in its way.",
+ "2026-11-22T06:00:00.000Z",
+ ),
+ );
+ expect(enqueue.packet).toMatchObject({
+ priority: 10,
+ dedupe_key: `repo-health:v1:triage:${REPO}:issue:12501`,
+ payload: { schema: "repo-task/v1", kind: "triage", issue: { number: 12501 } },
+ });
+ // The label is prepared once per process, and "already there" is success.
+ await work.ask({ text: "second" });
+ expect(w.gh().filter((a) => a[2] === `repos/${REPO}/labels`).length).toBe(1);
+ const exists = world({
+ commands: (argv) =>
+ argv.includes(`repos/${REPO}/labels`)
+ ? { code: 1, stderr: 'gh: Validation Failed (HTTP 422) {"code":"already_exists"}' }
+ : JSON.stringify({ number: 1, html_url: "u" }),
+ });
+ expect((await new Work(exists.ops).ask({ text: "x" })).issue).toBe(1);
+ const denied = world({
+ commands: (argv) =>
+ argv.includes(`repos/${REPO}/labels`) ? { code: 1, stderr: "gh: Forbidden (HTTP 403)" } : "{}",
+ });
+ await expect(new Work(denied.ops).ask({ text: "x" })).rejects.toThrow(/label/);
+ expect(denied.gh().length).toBe(1); // no issue is filed if the label cannot be prepared
+ // The issue exists either way: a failed enqueue is said, not thrown.
+ const stuck = world({
+ commands: (argv) =>
+ argv[1] === "queue"
+ ? { code: 1, stderr: "repo-queue: broker unreachable" }
+ : JSON.stringify({ number: 2, html_url: "u" }),
+ });
+ expect(await new Work(stuck.ops).ask({ text: "x" })).toEqual({
+ issue: 2,
+ url: "u",
+ queued: false,
+ note: "filed, not queued: repo-queue: broker unreachable",
+ });
+ for (const text of ["", " ", 5, "x".repeat(8001)]) await expect(work.ask({ text })).rejects.toThrow(OpError);
+ });
+
+ test("a reply wakes the fleet again, and only on one of his prompts", async () => {
+ const issue = (state: string, labels: string[]) =>
+ JSON.stringify({ state, labels: labels.map((name) => ({ name })) });
+ const w = world({
+ commands: (argv) =>
+ argv.includes("--input") && argv[5].endsWith("/comments")
+ ? JSON.stringify({ id: 777 })
+ : argv[3] === `repos/${REPO}/issues/12501`
+ ? issue("closed", ["owner/prompt"])
+ : "{}",
+ });
+ const work = new Work(w.ops, undefined, () => new Date("2026-11-22T06:00:00Z"));
+ expect(await work.askReply({ issue: 12501, text: "also do the docs" })).toEqual({ issue: 12501, queued: true });
+ expect(w.gh()).toEqual([
+ [`repos/${REPO}/issues/12501`],
+ ["-X", "POST", `repos/${REPO}/issues/12501/comments`, "--input", "-"],
+ ["-X", "PATCH", `repos/${REPO}/issues/12501`, "--input", "-"], // it was closed: reopened
+ ]);
+ expect(JSON.parse(w.calls[1].stdin ?? "").body).toBe("also do the docs\n\n");
+ expect(w.calls[3].packet).toMatchObject({
+ priority: 10,
+ dedupe_key: `repo-health:v1:triage:${REPO}:issue:12501`,
+ });
+ const other = world({ commands: () => issue("open", ["bug"]) });
+ await expect(new Work(other.ops).askReply({ issue: 5, text: "x" })).rejects.toThrow(
+ /not one of the owner's prompts/,
+ );
+ await expect(new Work(other.ops).askClose({ issue: 5 })).rejects.toThrow(/not one of the owner's prompts/);
+ expect(other.calls.length).toBe(2);
+ await expect(work.askReply({ issue: "12501/comments", text: "x" })).rejects.toThrow(OpError);
+ });
+
+ test("each prompt shows where it stands", async () => {
+ const found = (n: number, state: string, comments: number) => ({
+ number: n,
+ title: `Owner: t${n}`,
+ body: `words ${n}\n\n---\nnote`,
+ html_url: `u${n}`,
+ state,
+ created_at: "2026-11-22T01:00:00Z",
+ updated_at: `2026-11-22T0${n}:00:00Z`,
+ comments,
+ });
+ let commentReads = 0;
+ const w = world({
+ commands: (argv) => {
+ if (argv.includes("search/issues"))
+ return JSON.stringify({
+ items: [
+ found(1, "closed", 1),
+ found(2, "open", 1),
+ found(3, "open", 0),
+ found(4, "open", 2),
+ found(5, "open", 0),
+ ],
+ });
+ commentReads++;
+ const n = Number(/issues\/(\d+)\/comments/.exec(argv[3])?.[1]);
+ return JSON.stringify(
+ n === 4
+ ? [
+ { body: "fleet says", created_at: "2026-11-22T02:00:00Z" },
+ { body: "and I say\n\n", created_at: "2026-11-22T03:00:00Z" },
+ ]
+ : [{ body: "fleet says", created_at: "2026-11-22T02:00:00Z" }],
+ );
+ },
+ rows: () => [
+ { dedupe_key: `repo-health:v1:triage:${REPO}:issue:3`, status: "claimed", worker: "w1" },
+ { dedupe_key: `repo-health:v1:triage:${REPO}:issue:4`, status: "queued", worker: null },
+ { dedupe_key: `repo-health:v1:triage:${REPO}:issue:4`, status: "done", worker: null },
+ ],
+ });
+ const work = new Work(w.ops);
+ const asks = await work.asks();
+ expect(asks.map((a) => [a.issue, a.status, a.worker, a.text, a.replies.map((r) => r.you)])).toEqual([
+ [1, "done", null, "words 1", [false]],
+ [2, "answered", null, "words 2", [false]],
+ [3, "working", "w1", "words 3", []],
+ [4, "queued", null, "words 4", [false, true]], // the last word is his: back in the queue
+ [5, "waiting", null, "words 5", []],
+ ]);
+ expect(asks[3].replies[1].text).toBe("and I say");
+ // Threads are read again only when the issue has changed.
+ await work.asks();
+ expect(commentReads).toBe(3);
+ });
+});
+
+describe("the state kept ready", () => {
+ const source = () => {
+ let n = 0;
+ let fail = false;
+ let gate: Promise | null = null;
+ return {
+ load: async () => {
+ n++;
+ await gate;
+ if (fail) throw new Error("source is down");
+ return { n };
+ },
+ reads: () => n,
+ break: (b: boolean) => {
+ fail = b;
+ },
+ hold: () => {
+ let open = () => {};
+ gate = new Promise((r) => {
+ open = r;
+ });
+ return () => {
+ gate = null;
+ open();
+ };
+ },
+ };
+ };
+ const all = (board: { ttlMs: number; load: () => Promise }) => {
+ const still = { ttlMs: 1e12, load: async () => "x" };
+ return {
+ board,
+ sessions: still,
+ census: still,
+ asks: still,
+ questionCount: still,
+ questions: still,
+ prs: still,
+ priorities: still,
+ agents: still,
+ services: still,
+ more: still,
+ };
+ };
+
+ test("a page never waits on a source that has been read before", async () => {
+ let now = 1_000_000;
+ const s = source();
+ const docs = new Docs(all({ ttlMs: 10_000, load: s.load }), () => now);
+ const first = JSON.parse((await docs.doc("core")).body);
+ expect(first.board).toEqual({ n: 1 }); // the first read is waited for
+ expect(first.health.board).toEqual({ ok: true, error: null });
+ now += 5_000;
+ await docs.doc("core");
+ expect(s.reads()).toBe(1); // fresh: not read again
+ now += 6_000;
+ const release = s.hold();
+ const stale = JSON.parse((await docs.doc("core")).body); // answers at once with what it has
+ expect(stale.board).toEqual({ n: 1 });
+ expect(s.reads()).toBe(2); // and a read is under way
+ await docs.doc("core");
+ expect(s.reads()).toBe(2); // one read at a time
+ release();
+ await docs.refresh("board");
+ expect(JSON.parse((await docs.doc("core")).body).board).toEqual({ n: 2 });
+ });
+
+ test("a failed read keeps the last good copy and says so", async () => {
+ let now = 1_000_000;
+ const s = source();
+ const docs = new Docs(all({ ttlMs: 10_000, load: s.load }), () => now);
+ const good = await docs.doc("core");
+ s.break(true);
+ now += 11_000;
+ await docs.refresh("board");
+ const after = await docs.doc("core");
+ const body = JSON.parse(after.body);
+ expect(body.board).toEqual({ n: 1 });
+ expect(body.health.board).toEqual({ ok: false, error: "source is down" });
+ expect(after.etag).not.toBe(good.etag);
+ expect(after.asOf).toBe(now - 1_000); // the board is a second past its interval
+ });
+
+ test("an unchanged document keeps its tag, and nothing is read when nobody is looking", async () => {
+ let now = 1_000_000;
+ let reads = 0;
+ const docs = new Docs(all({ ttlMs: 10_000, load: async () => (reads++, { same: true }) }), () => now);
+ const a = await docs.doc("core");
+ now += 11_000;
+ await docs.refresh("board");
+ const b = await docs.doc("core");
+ expect(b.etag).toBe(a.etag);
+ expect(b.asOf).toBeGreaterThan(a.asOf);
+ expect(reads).toBe(2);
+ now += 11_000;
+ docs.tick(); // someone looked 11 seconds ago: refresh
+ await docs.refresh("board");
+ expect(reads).toBe(3);
+ now += 11 * 60_000;
+ docs.tick(); // nobody has looked for eleven minutes: leave the sources alone
+ await docs.refresh("more");
+ expect(reads).toBe(3);
+ expect(() => new Docs({ board: { ttlMs: 1, load: async () => 1 } })).toThrow(/no loader/);
+ });
+});
+
+describe("the interface's endpoints", () => {
+ function deps(who: "owner" | 401 = "owner") {
+ const w = world({
+ rows: (st) => (st.sql.startsWith("UPDATE") ? { affected: 1 } : [{ priority: 30 }]),
+ dash: () => [],
+ });
+ const work = new Work(w.ops, async () => store());
+ const docs = new Docs(loaders(w.ops, work, [{ group: "Overview", pages: [] }]));
+ const audited: Record[] = [];
+ const d: Deps = {
+ cfg: CFG,
+ ops: w.ops,
+ docs,
+ actions: actions(w.ops, work),
+ identify: async () => {
+ if (who === "owner") return { via: "cloudflare-access", email: "drewrypope@gmail.com" };
+ throw new (await import("../src/auth.ts")).AuthError(401, "sign-in required");
+ },
+ audit: async (e) => {
+ audited.push(e);
+ },
+ };
+ return { d, w, audited, docs };
+ }
+ const get = (path: string, headers: Record = {}) =>
+ new Request(`https://pm.security.cab${path}`, { headers: { host: "pm.security.cab", ...headers } });
+ const post = (path: string, body: unknown) =>
+ new Request(`https://pm.security.cab${path}`, {
+ method: "POST",
+ body: JSON.stringify(body),
+ headers: {
+ host: "pm.security.cab",
+ "content-type": "application/json",
+ "x-pm-console": "1",
+ origin: "https://pm.security.cab",
+ },
+ });
+
+ test("a document comes with a tag, is not sent twice, and is compressed", async () => {
+ const { d } = deps();
+ const res = await handle(get("/console/api/doc/questions"), d);
+ expect(res.status).toBe(200);
+ const body = await res.json();
+ expect(body.questions.total).toBe(4);
+ expect(JSON.stringify(body)).not.toContain(TOKEN);
+ const etag = res.headers.get("etag") ?? "";
+ expect(etag.length).toBeGreaterThan(10);
+ expect(Number(res.headers.get("x-as-of"))).toBeGreaterThan(0);
+ const again = await handle(get("/console/api/doc/questions", { "if-none-match": etag }), d);
+ expect([again.status, await again.text()]).toEqual([304, ""]);
+ expect(Number(again.headers.get("x-as-of"))).toBeGreaterThan(0);
+ const packed = await handle(get("/console/api/doc/questions", { "accept-encoding": "gzip, br" }), d);
+ expect(packed.headers.get("content-encoding")).toBe("gzip");
+ const raw = new Uint8Array(await packed.arrayBuffer());
+ expect(JSON.parse(gunzipSync(raw).toString()).questions.total).toBe(4);
+ expect(raw.byteLength).toBeLessThan(JSON.stringify(body).length / 2);
+ expect((await handle(get("/console/api/doc/secrets"), d)).status).toBe(404);
+ expect((await handle(get("/console/api/doc/core"), deps(401).d)).status).toBe(401);
+ });
+
+ test("an action runs, is recorded without the owner's words, and shows in the state", async () => {
+ const { d, w, audited } = deps();
+ // What an action changes is read again before the answer goes back,
+ // so the next document already shows it.
+ const boardReads = () => w.sqls.filter((batch) => batch.length === 4).length;
+ await handle(get("/console/api/doc/core"), d);
+ const readsBefore = boardReads();
+ const res = await handle(post("/console/api/act", { kind: "task.move", args: { task: 21016, to: "first" } }), d);
+ expect(await res.json()).toEqual({ ok: true, result: { task: 21016, priority: 10 } });
+ expect(boardReads()).toBe(readsBefore + 1);
+ expect(w.sqls.flat().some((s) => s.sql.startsWith("UPDATE tasks SET priority"))).toBe(true);
+ await handle(
+ post("/console/api/act", { kind: "need.comment", args: { ref: `${REPO}#5`, text: "private words" } }),
+ d,
+ );
+ expect(audited.map((e) => [e.action, e.phase, e.args])).toEqual([
+ ["task.move", "start", { task: 21016, to: "first" }],
+ ["task.move", "done", { task: 21016, to: "first" }],
+ ["need.comment", "start", { ref: `${REPO}#5` }],
+ ["need.comment", "done", { ref: `${REPO}#5` }],
+ ]);
+ expect(JSON.stringify(audited)).not.toContain("private words");
+ const core = await (await handle(get("/console/api/doc/core"), d)).json();
+ expect(core.acts.map((a: { kind: string; status: string }) => [a.kind, a.status])).toEqual([
+ ["need.comment", "done"],
+ ["task.move", "done"],
+ ]);
+ // Unknown actions, inherited names and bad arguments run nothing.
+ const before = w.calls.length;
+ for (const body of [
+ { kind: "task.delete", args: {} },
+ { kind: "constructor", args: {} },
+ { kind: "toString", args: {} },
+ { args: {} },
+ { kind: "task.move", args: [] },
+ { kind: "task.move", args: { task: 1, to: "up" } },
+ ]) {
+ expect((await handle(post("/console/api/act", body), d)).status).toBe(400);
+ }
+ expect(w.calls.length).toBe(before);
+ const failed = (await (await handle(get("/console/api/doc/core"), d)).json()).acts[0];
+ expect([failed.kind, failed.status]).toEqual(["task.move", "failed"]);
+ await expect(perform(actions(w.ops, new Work(w.ops)), deps().docs, "__proto__", {})).rejects.toThrow(
+ /not an action/,
+ );
+ });
+
+ test("the front door is the app, the dashboard's pages are compressed on the way", async () => {
+ const { d } = deps();
+ const big = "
row
".repeat(2000);
+ const stream = "data: x\n\n".repeat(500);
+ d.upstream = async (url) =>
+ new Response(url.includes("/frag/") || url.endsWith("/freshness/stream") ? stream : big, {
+ headers: {
+ "content-type":
+ url.includes("/frag/") || url.endsWith("/stream") ? "text/event-stream" : "text/html; charset=utf-8",
+ },
+ });
+ const home = await handle(get("/"), d);
+ expect([home.status, home.headers.get("location")]).toEqual([302, "/console/"]);
+ expect((await handle(get("/"), deps(401).d)).status).toBe(401);
+ // The dashboard's own home is still there, one link away.
+ expect(await (await handle(get("/?dashboard"), d)).text()).toBe(big);
+ const gz = { "accept-encoding": "gzip" };
+ const page = await handle(get("/attention", gz), d);
+ expect(page.headers.get("content-encoding")).toBe("gzip");
+ expect(gunzipSync(new Uint8Array(await page.arrayBuffer())).toString()).toBe(big);
+ const frag = await handle(get("/frag/attention/queues", gz), d);
+ expect(frag.headers.get("content-encoding")).toBe("gzip");
+ expect(frag.headers.get("content-type")).toBe("text/event-stream");
+ expect(gunzipSync(new Uint8Array(await frag.arrayBuffer())).toString()).toBe(stream);
+ // A stream that stays open is passed through as it comes.
+ const live = await handle(get("/freshness/stream", gz), d);
+ expect(live.headers.get("content-encoding")).toBeNull();
+ expect(await live.text()).toBe(stream);
+ // A client that did not ask for gzip gets the bytes as they are.
+ expect(await (await handle(get("/attention"), d)).text()).toBe(big);
+ });
+});
diff --git a/pm-stack/systemd/pm-console-expose.service b/pm-stack/systemd/pm-console-expose.service
new file mode 100644
index 0000000000..a455c93d1d
--- /dev/null
+++ b/pm-stack/systemd/pm-console-expose.service
@@ -0,0 +1,12 @@
+[Unit]
+Description=PM console — keep the public address as declared (sign-in methods, policy, route) (pm-stack)
+Documentation=https://github.com/developing-today/code/tree/main/pm-stack/console
+After=network-online.target
+
+[Service]
+Type=oneshot
+# Changes only what is not already so. When the Google sign-in secrets
+# appear in the secret store, the next run turns Google sign-in on.
+ExecStart=/run/current-system/sw/bin/python3 %h/git/code/pm-stack/console/scripts/expose.py
+Environment=PATH=%h/.local/bin:/run/current-system/sw/bin:/etc/profiles/per-user/%u/bin:/usr/bin:/bin
+TimeoutStartSec=600
diff --git a/pm-stack/systemd/pm-console-expose.timer b/pm-stack/systemd/pm-console-expose.timer
new file mode 100644
index 0000000000..3d93f938fd
--- /dev/null
+++ b/pm-stack/systemd/pm-console-expose.timer
@@ -0,0 +1,10 @@
+[Unit]
+Description=PM console — re-check the public address every quarter hour (pm-stack)
+
+[Timer]
+OnBootSec=5min
+OnUnitActiveSec=15min
+RandomizedDelaySec=60
+
+[Install]
+WantedBy=timers.target
diff --git a/pm-stack/systemd/pm-console.service b/pm-stack/systemd/pm-console.service
index c62922d647..662a353f15 100644
--- a/pm-stack/systemd/pm-console.service
+++ b/pm-stack/systemd/pm-console.service
@@ -3,6 +3,9 @@ Description=PM console — queue, priorities, agents, services and pull requests
After=network-online.target
[Service]
+# The management plane has to answer while the fleet is compiling: under
+# contention this unit gets nine times the processor share of a default one.
+CPUWeight=900
Type=simple
WorkingDirectory=%h/git/code/pm-stack/console
ExecStart=/run/current-system/sw/bin/bun run src/server.ts