neurastream 0.3.20 → 0.3.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/package.json +1 -1
  2. package/src/adapters/index.ts +3 -2
  3. package/src/adapters/omp/adapter.ts +2 -1
  4. package/src/adapters/omp/auto-close.ts +64 -0
  5. package/src/adapters/omp/chat-commands.ts +161 -0
  6. package/src/adapters/omp/inbox.ts +221 -0
  7. package/src/adapters/omp/index.ts +115 -1039
  8. package/src/adapters/omp/launch.ts +31 -3
  9. package/src/adapters/omp/rate-limit-controller.ts +196 -0
  10. package/src/adapters/omp/rollover-controller.ts +334 -0
  11. package/src/adapters/omp/types.ts +143 -0
  12. package/src/cli/commands.ts +33 -2
  13. package/src/cli/dispatch.ts +37 -16
  14. package/src/cli/recall.ts +3 -2
  15. package/src/cli/results-build.ts +1 -1
  16. package/src/cli/workspace.ts +13 -2
  17. package/src/core/adapter.ts +16 -0
  18. package/src/core/blockers.ts +326 -30
  19. package/src/core/file-lock.ts +71 -12
  20. package/src/core/guards/plan-edit.ts +338 -0
  21. package/src/core/guards/planner.ts +70 -0
  22. package/src/core/guards/review.ts +391 -0
  23. package/src/core/guards/spawn.ts +699 -0
  24. package/src/core/guards/state.ts +581 -0
  25. package/src/core/guards/stop.ts +235 -0
  26. package/src/core/guards/tool.ts +541 -0
  27. package/src/core/guards.ts +12 -2658
  28. package/src/core/incidents.ts +125 -91
  29. package/src/core/machine-guard.ts +23 -5
  30. package/src/core/main-start.ts +10 -8
  31. package/src/core/owner-topics.ts +2 -13
  32. package/src/core/owner-ui/auth.ts +164 -0
  33. package/src/core/owner-ui/data.ts +437 -0
  34. package/src/core/owner-ui/handlers.ts +250 -0
  35. package/src/core/owner-ui/messages.ts +209 -0
  36. package/src/core/owner-ui/render.ts +714 -0
  37. package/src/core/owner-ui/results.ts +266 -0
  38. package/src/core/owner-ui/server.ts +142 -0
  39. package/src/core/owner-ui.ts +11 -2121
  40. package/src/core/page-notes.ts +25 -0
  41. package/src/core/pages.ts +452 -77
  42. package/src/core/plan-approval.ts +12 -14
  43. package/src/core/queue/lib.ts +88 -39
  44. package/src/core/queue-cancel.ts +21 -17
  45. package/src/core/queue-close.ts +48 -23
  46. package/src/core/secret-redact.ts +65 -14
  47. package/src/core/tailscale.ts +79 -3
  48. package/src/core/team-client.ts +13 -2
  49. package/src/core/uninstall.ts +2 -0
@@ -0,0 +1,266 @@
1
+ // Results tab (plan 20261025_2148 P4): $ per finished feature, releases before vs after, cache read, and SVG/table rendering.
2
+
3
+ import { readFileSync } from "node:fs";
4
+ import { basename } from "node:path";
5
+ import type { RunSource } from "../adapter.ts";
6
+ import { nowSec, strftime } from "../clock.ts";
7
+ import type { Config } from "../config.ts";
8
+ import { readMetricEvents } from "../metrics.ts";
9
+ import { gitTop, type QueuePaths } from "../queue/lib.ts";
10
+ import { featuresReport, gatherTags, loadPlans, releasesReport, type FeaturesReport, type ReleaseRow, type ReleaseSideStats, type ReleasesReport } from "../results.ts";
11
+ import { esc, na } from "./auth.ts";
12
+
13
+ export interface ResultsData {
14
+ /** The ledger over the last `metrics.report_days` days — only the empty state reads it. */
15
+ features: FeaturesReport;
16
+ /** Per release, the N-day before/after windows: the chart's series and the table's rows. */
17
+ releases: ReleasesReport;
18
+ }
19
+
20
+ /** The tab as the page sees it: the last saved numbers (if any), when they were saved, and whether a build runs now. */
21
+ export interface ResultsView {
22
+ data: ResultsData | null;
23
+ at: number | null;
24
+ building: boolean;
25
+ }
26
+
27
+ /** Saved numbers older than this start a fresh background build. */
28
+ const RESULTS_MAX_AGE_SEC = 3600;
29
+ /** A build that failed or got killed is retried no sooner than this. */
30
+ const RESULTS_RETRY_SEC = 600;
31
+
32
+ export function resultsCachePath(paths: Pick<QueuePaths, "queue_state">): string {
33
+ return `${paths.queue_state}/results-cache.json`;
34
+ }
35
+
36
+ /**
37
+ * The tab's numbers from the P2/P3 functions. A release's before window reaches back months, so
38
+ * one build parses GBs of sessions for over a minute: it runs only in the separate process
39
+ * src/cli/results-build.ts, never in the server, which it froze (I-20261030-121).
40
+ */
41
+ export function computeResults(cfg: Config, source: RunSource, now: number): ResultsData {
42
+ const days = 7;
43
+ const selfRepo = gitTop(import.meta.dir)?.repo ?? null;
44
+ const tags = gatherTags(selfRepo);
45
+ const events = readMetricEvents(cfg);
46
+ const oldest = Math.min(now, ...tags.map(t => t.ts), ...events.filter(e => e.type === "ci").map(e => Number(e.ts)));
47
+ const runs = source.listRuns(oldest - days * 86400);
48
+ const plans = loadPlans(cfg);
49
+ return {
50
+ features: featuresReport(runs, plans, selfRepo, now - cfg.metrics.report_days * 86400, now),
51
+ releases: releasesReport(runs, plans, selfRepo, days, now, tags, events),
52
+ };
53
+ }
54
+
55
+ /** Starts one background build; calls `done` when it exits, whatever the outcome. */
56
+ export type ResultsBuild = (done: () => void) => void;
57
+
58
+ export const noopResultsBuild: ResultsBuild = done => {
59
+ done();
60
+ };
61
+
62
+ let buildRunning = false;
63
+ let lastBuildStart = 0;
64
+
65
+ /** Reads the saved numbers and, when they are missing or stale, starts one build in the background. */
66
+ export function resultsView(now: number, build: ResultsBuild, paths: Pick<QueuePaths, "queue_state">): ResultsView {
67
+ let saved: { at: number; data: ResultsData } | null = null;
68
+ try {
69
+ saved = JSON.parse(readFileSync(resultsCachePath(paths), "utf8"));
70
+ } catch {
71
+ // No build has finished yet.
72
+ }
73
+ if ((!saved || now - saved.at >= RESULTS_MAX_AGE_SEC) && !buildRunning && now - lastBuildStart >= RESULTS_RETRY_SEC) {
74
+ buildRunning = true;
75
+ lastBuildStart = now;
76
+ build(() => {
77
+ buildRunning = false;
78
+ });
79
+ }
80
+ return { data: saved?.data ?? null, at: saved?.at ?? null, building: buildRunning };
81
+ }
82
+
83
+ /** One y axis choice: where the number sits on a release side and which way is better. */
84
+ interface YMetric {
85
+ key: string;
86
+ label: string;
87
+ axis: string;
88
+ /** null = no known direction (product numbers): the table's arrow carries no color. */
89
+ better: "lower" | "higher" | null;
90
+ fmt(v: number): string;
91
+ get(side: ReleaseSideStats): number | null;
92
+ }
93
+
94
+ const LEDGER_METRICS: YMetric[] = [
95
+ { key: "usd", label: "$/feat", axis: "$ per feature", better: "lower", fmt: v => `$${v.toFixed(2)}`, get: s => s.perFeature },
96
+ { key: "perday", label: "/day", axis: "features per day", better: "higher", fmt: v => v.toFixed(2), get: s => s.featuresPerDay },
97
+ { key: "calls", label: "calls", axis: "main calls per feature", better: "lower", fmt: v => v.toFixed(1), get: s => s.callsPerFeature },
98
+ { key: "tok", label: "tok", axis: "tokens per call", better: "lower", fmt: v => v.toFixed(0), get: s => s.tokensPerCall },
99
+ { key: "fix", label: "fix", axis: "fix plans per feature", better: "lower", fmt: v => v.toFixed(2), get: s => s.fixPlansPerFeature },
100
+ ];
101
+
102
+ /** One metric per recorded product number, keyed `p:<name>` (repo-qualified when names clash). */
103
+ function productMetrics(releases: ReleasesReport): YMetric[] {
104
+ const pairs = new Map<string, { repo: string; name: string }>();
105
+ for (const row of releases.rows) for (const p of [...row.before.products, ...row.after.products]) pairs.set(`${p.repo}|${p.name}`, p);
106
+ const clashes: Record<string, number> = {};
107
+ for (const { name } of pairs.values()) clashes[name] = (clashes[name] ?? 0) + 1;
108
+ return [...pairs.values()]
109
+ .sort((a, b) => (a.name + a.repo).localeCompare(b.name + b.repo))
110
+ .map(({ repo, name }) => {
111
+ const clash = (clashes[name] ?? 0) > 1;
112
+ return {
113
+ key: clash ? `p:${basename(repo)}:${name}` : `p:${name}`,
114
+ label: clash ? `${basename(repo)}/${name}` : name,
115
+ axis: `${name} (product number)`,
116
+ better: null,
117
+ fmt: (v: number) => String(Math.round(v * 100) / 100),
118
+ get: (s: ReleaseSideStats): number | null => s.products.find(p => p.repo === repo && p.name === name)?.value ?? null,
119
+ };
120
+ });
121
+ }
122
+
123
+ const RESULT_KINDS = ["product", "neurastream"] as const;
124
+ const KIND_COLOR: Record<(typeof RESULT_KINDS)[number], string> = { product: "var(--acc)", neurastream: "var(--teal)" };
125
+ const CHART_W = 390;
126
+ const CHART_H = 200;
127
+ const CHART_L = 48;
128
+ const CHART_R = 8;
129
+ const CHART_T = 10;
130
+ const CHART_B = 20;
131
+
132
+ interface ChartPoint {
133
+ px: number;
134
+ py: number;
135
+ label: string;
136
+ value: number;
137
+ }
138
+ interface ChartSeries {
139
+ label: string;
140
+ color: string;
141
+ points: ChartPoint[];
142
+ }
143
+
144
+ /** The tab's controls: plain links, so the page's existing fetch/pushState swap handles them with no new script. */
145
+ function resultsControls(all: YMetric[], y: YMetric, x: "time" | "feature"): string {
146
+ const yLinks = all
147
+ .map(m => `<a href="/?tab=results&amp;y=${m.key}&amp;x=${x}"${m.key === y.key ? ` class="on"` : ""}>${esc(m.label)}</a>`)
148
+ .join("");
149
+ const xLinks = (["time", "feature"] as const)
150
+ .map(v => `<a href="/?tab=results&amp;y=${y.key}&amp;x=${v}"${v === x ? ` class="on"` : ""}>${v === "time" ? "time" : "feature"}</a>`)
151
+ .join("");
152
+ return `<div class="rlinks"><span>y</span>${yLinks}</div><div class="rlinks"><span>x</span>${xLinks}</div>`;
153
+ }
154
+
155
+ /**
156
+ * Hand-written inline SVG under the page's CSP: one polyline per series (product vs neurastream
157
+ * for a ledger metric, one per product number), points carrying <title> tooltips, releases as
158
+ * dashed verticals on the time axis, theme colors via the page's CSS variables.
159
+ */
160
+ function resultsChart(releases: ReleasesReport, y: YMetric, x: "time" | "feature"): string {
161
+ const rows = releases.rows;
162
+ const mid = CHART_L + (CHART_W - CHART_L - CHART_R) / 2;
163
+ const t0 = rows[0]!.ts;
164
+ const t1 = rows[rows.length - 1]!.ts;
165
+ const pxOf = (i: number, ts: number): number =>
166
+ x === "feature" ? (rows.length < 2 ? mid : CHART_L + (i / (rows.length - 1)) * (CHART_W - CHART_L - CHART_R))
167
+ : t1 === t0 ? mid : CHART_L + ((ts - t0) / (t1 - t0)) * (CHART_W - CHART_L - CHART_R);
168
+ const tip = (row: ReleaseRow, v: number): string => `${row.name} · ${y.fmt(v)} · ${strftime(row.ts, "%m-%d %H:%M")}`;
169
+ const point = (row: ReleaseRow, i: number, v: number): ChartPoint => ({ px: pxOf(i, row.ts), py: 0, label: tip(row, v), value: v });
170
+ const series: ChartSeries[] = LEDGER_METRICS.includes(y)
171
+ ? RESULT_KINDS.map(kind => ({
172
+ label: kind,
173
+ color: KIND_COLOR[kind],
174
+ points: rows.flatMap((row, i) => {
175
+ if (row.kind !== kind) return [];
176
+ const v = y.get(row.after);
177
+ return v === null ? [] : [point(row, i, v)];
178
+ }),
179
+ }))
180
+ : [
181
+ {
182
+ label: y.label,
183
+ color: "var(--warn)",
184
+ points: rows.flatMap((row, i) => {
185
+ const v = y.get(row.after);
186
+ return v === null ? [] : [point(row, i, v)];
187
+ }),
188
+ },
189
+ ];
190
+ const yMax = Math.max(...series.flatMap(s => s.points.map(p => p.value)), 1e-9);
191
+ const pyOf = (v: number): number => CHART_T + (1 - v / yMax) * (CHART_H - CHART_T - CHART_B);
192
+ const parts: string[] = [];
193
+ for (const v of [0, yMax / 2, yMax]) {
194
+ parts.push(`<line x1="${CHART_L}" x2="${CHART_W - CHART_R}" y1="${pyOf(v).toFixed(1)}" y2="${pyOf(v).toFixed(1)}" stroke="var(--bd)"/>`);
195
+ parts.push(`<text x="${CHART_L - 5}" y="${(pyOf(v) + 3).toFixed(1)}" text-anchor="end" font-size="10" fill="var(--mut)">${esc(y.fmt(v))}</text>`);
196
+ }
197
+ if (x === "time") {
198
+ for (const row of rows) {
199
+ const px = pxOf(0, row.ts).toFixed(1);
200
+ parts.push(
201
+ `<line x1="${px}" x2="${px}" y1="${CHART_T}" y2="${CHART_H - CHART_B}" stroke="var(--bd)" stroke-dasharray="3 3"><title>${esc(`${row.name} · ${strftime(row.ts, "%m-%d %H:%M")}`)}</title></line>`,
202
+ );
203
+ }
204
+ parts.push(`<text x="${CHART_L}" y="${CHART_H - 6}" font-size="10" fill="var(--mut)">${esc(strftime(t0, "%m-%d"))}</text>`);
205
+ parts.push(`<text x="${CHART_W - CHART_R}" y="${CHART_H - 6}" text-anchor="end" font-size="10" fill="var(--mut)">${esc(strftime(t1, "%m-%d"))}</text>`);
206
+ }
207
+ for (const s of series) {
208
+ if (s.points.length > 1) {
209
+ const pts = s.points.map(p => `${p.px.toFixed(1)},${pyOf(p.value).toFixed(1)}`).join(" ");
210
+ parts.push(`<polyline points="${pts}" fill="none" stroke="${s.color}" stroke-width="2"/>`);
211
+ }
212
+ for (const p of s.points) {
213
+ parts.push(`<circle cx="${p.px.toFixed(1)}" cy="${pyOf(p.value).toFixed(1)}" r="3" fill="${s.color}"><title>${esc(p.label)}</title></circle>`);
214
+ }
215
+ }
216
+ const legend = series.map(s => `<span style="color:${s.color}">— ${esc(s.label)}</span>`).join("");
217
+ return `<p class="rlegend">${legend}</p><svg class="rchart" role="img" aria-label="${esc(`${y.axis} by ${x === "time" ? "day" : "release"}`)}" viewBox="0 0 ${CHART_W} ${CHART_H}">${parts.join("")}</svg>`;
218
+ }
219
+
220
+ /** One row per release, the `metrics releases` table: before→after cells with ▲/▼, green when the change is for the better. */
221
+ function resultsTable(releases: ReleasesReport, all: YMetric[]): string {
222
+ const cell = (row: ReleaseRow, m: YMetric): string => {
223
+ const before = m.get(row.before);
224
+ const after = m.get(row.after);
225
+ if (before === null || after === null) return `<td class="mutcell">–</td>`;
226
+ const arrow = after > before ? "▲" : after < before ? "▼" : "·";
227
+ const cls = m.better !== null && after !== before ? ((m.better === "lower") === (after < before) ? ` class="good"` : ` class="badv"`) : "";
228
+ return `<td>${esc(m.fmt(before))}→${esc(m.fmt(after))}<span${cls}>${arrow}</span></td>`;
229
+ };
230
+ const head = `<tr><th>release</th>${all.map(m => `<th>${esc(m.label)}</th>`).join("")}</tr>`;
231
+ const body = releases.rows
232
+ .map(row =>
233
+ `<tr><td>${esc(row.name)} <span class="note">${strftime(row.ts, "%m-%d")}</span>${row.measuring ? ` <span class="chip c-ready">measuring</span>` : ""}</td>${all.map(m => cell(row, m)).join("")}</tr>`,
234
+ )
235
+ .join("");
236
+ return `<div class="tscroll"><table><thead>${head}</thead><tbody>${body}</tbody></table></div>`;
237
+ }
238
+
239
+ const RESULTS_CAVEAT = "Fixes inside the same plan are not split out; plans that do not cite an earlier stem are not linked. Product numbers carry no better/worse color.";
240
+
241
+ export function resultsTabHtml(view: ResultsView | null | undefined, params: URLSearchParams): string {
242
+ const d = view?.data;
243
+ if (!d) {
244
+ if (view?.building) return `<h1>Results</h1><div class="card"><p class="empty">Working out the numbers from your past sessions — the first time takes a few minutes. This page refreshes by itself.</p></div>`;
245
+ return `<h1>Results</h1>${na("Results")}`;
246
+ }
247
+ if (!d.releases.rows.length) {
248
+ const empty = d.features.rows.length ? "No releases recorded yet" : "No finished features yet";
249
+ return `<h1>Results</h1><div class="card"><p class="empty">${empty}</p></div><p class="sub">${RESULTS_CAVEAT}</p>`;
250
+ }
251
+ const x = params.get("x") === "feature" ? "feature" : "time";
252
+ const all = [...LEDGER_METRICS, ...productMetrics(d.releases)];
253
+ // An unknown y falls back to $/feature.
254
+ const y = all.find(m => m.key === params.get("y")) ?? all[0]!;
255
+ return `<h1>Results</h1>
256
+ <p class="sub">What features cost and whether releases made it better or worse. Updated ${Math.max(0, Math.round((nowSec() - (view.at ?? nowSec())) / 60))} min ago${view.building ? " · updating now" : ""}.</p>
257
+ <div class="card">
258
+ ${resultsControls(all, y, x)}
259
+ ${resultsChart(d.releases, y, x)}
260
+ </div>
261
+ <h2>Releases <small>${d.releases.days} days before → after</small></h2>
262
+ <div class="card">
263
+ ${resultsTable(d.releases, all)}
264
+ </div>
265
+ <p class="sub">${RESULTS_CAVEAT}</p>`;
266
+ }
@@ -0,0 +1,142 @@
1
+ // Owner UI HTTP server: binds tailnet address, enforces Host/auth/Origin guards, and dispatches GET/POST routes.
2
+
3
+ import type { RunSource } from "../adapter.ts";
4
+ import { nowSec } from "../clock.ts";
5
+ import type { Config } from "../config.ts";
6
+ import { log } from "../guards.ts";
7
+ import { readKnowledgeTopicFile, urlField } from "../knowledge.ts";
8
+ import type { Tailscale } from "../tailscale.ts";
9
+ import { authenticate, fieldsOf, hostAllowlist, originIsHost, textRes, type UiHttpServer } from "./auth.ts";
10
+ import { clearAnswerDedupe, handleAnswer, handleIncident, handleLock, handleReorder, handleTier, handleUnlock } from "./handlers.ts";
11
+ import { handleMessage, handleMessageImage, sweepOwnerMessages } from "./messages.ts";
12
+ import { pageRes } from "./render.ts";
13
+ import { noopResultsBuild, type ResultsBuild } from "./results.ts";
14
+
15
+ export interface OwnerUiServer {
16
+ stop(): void;
17
+ hostname: string;
18
+ port: number;
19
+ }
20
+
21
+ export interface OwnerUiOptions {
22
+ cfg: Config;
23
+ tailscale: Tailscale;
24
+ source: RunSource;
25
+ /** Bind address. Default: the tailnet address from `tailscale ip -4`. Tests bind 127.0.0.1. */
26
+ hostname?: string;
27
+ /** Bind port. Default: workspace.port; 0 picks a free port (tests). */
28
+ port?: number;
29
+ /** The peer address of a request. Default: the socket address. Tests inject fixture peers. */
30
+ peerOf?: (req: Request, server: UiHttpServer) => string;
31
+ /** Starts a background Results build. Default: no-op (CLI passes `spawnResultsBuild`). Tests inject a recorder. */
32
+ resultsBuild?: ResultsBuild;
33
+ }
34
+
35
+ /** Starts the page. Refuses to start when workspace.enabled is false or workspace.owner_login is empty, and on the default hostname when tailscale does not answer. */
36
+ export function startOwnerUi(opts: OwnerUiOptions): OwnerUiServer {
37
+ const { cfg, tailscale, source } = opts;
38
+ const resultsBuild = opts.resultsBuild ?? noopResultsBuild;
39
+ // The Base tab links to the pages server by its MagicDNS name, the same URL `pages publish` prints.
40
+ const pagesHost = tailscale.dnsName() ?? "tailnet";
41
+ // The double-press guard (P8c) is per-server memory: a fresh server starts empty, which also
42
+ // keeps the tests (one server per test) hermetic.
43
+ clearAnswerDedupe();
44
+ if (!cfg.workspace.enabled) throw new Error("owner ui: workspace.enabled is false — set it in the config first");
45
+ if (!cfg.workspace.owner_login) throw new Error("owner ui: workspace.owner_login is empty — set the tailscale login that may open the page");
46
+ const hostname = opts.hostname ?? tailscale.ip4();
47
+ if (!hostname) throw new Error("owner ui: tailscale ip -4 did not answer — is tailscale up?");
48
+ const peerOf = opts.peerOf ?? ((req: Request, server: UiHttpServer) => server.requestIP(req)?.address ?? "");
49
+ const hostAllowed = hostAllowlist(tailscale);
50
+ const server = Bun.serve({
51
+ hostname,
52
+ port: opts.port ?? cfg.workspace.port,
53
+ fetch: async (req, srv) => {
54
+ const url = new URL(req.url);
55
+ let code = 500;
56
+ let login: string | null = null;
57
+ let res: Response;
58
+ try {
59
+ const hostHeader = req.headers.get("host") ?? "";
60
+ if (!hostAllowed(hostHeader, srv.port)) {
61
+ res = textRes("forbidden: host is not this page", 403);
62
+ code = 403;
63
+ } else {
64
+ const auth = authenticate(cfg, tailscale, peerOf(req, srv));
65
+ if (!auth.ok) {
66
+ res = textRes("forbidden: this page serves only the owner", 403);
67
+ code = 403;
68
+ } else {
69
+ login = auth.login;
70
+ if (req.method === "POST" && !originIsHost(req.headers.get("origin"), hostHeader)) {
71
+ res = textRes("forbidden: origin is not this page", 403);
72
+ code = 403;
73
+ } else if (req.method === "GET" && url.pathname === "/") {
74
+ sweepOwnerMessages(nowSec(), cfg.paths);
75
+ res = pageRes(cfg, source, url.searchParams, resultsBuild, pagesHost);
76
+ code = 200;
77
+ } else if (req.method === "GET" && url.pathname.startsWith("/knowledge/")) {
78
+ // The Knowledge tab's frame: the topic's own file bytes, GET only, no write path.
79
+ const topicPath = /^\/knowledge\/([^/]+)\/([^/]+)$/.exec(url.pathname);
80
+ const bytes =
81
+ topicPath === null
82
+ ? null
83
+ : readKnowledgeTopicFile(cfg, urlField(topicPath[1]!), urlField(topicPath[2]!));
84
+ res =
85
+ bytes === null
86
+ ? textRes("not found", 404)
87
+ : new Response(bytes, {
88
+ headers: {
89
+ "content-type": "text/html; charset=utf-8",
90
+ "content-security-policy": "sandbox allow-scripts",
91
+ "x-content-type-options": "nosniff",
92
+ },
93
+ });
94
+ code = res.status;
95
+ } else if (req.method === "GET" && url.pathname.startsWith("/message-image/")) {
96
+ const mim = /^\/message-image\/([^/]+)\/([^/]+)$/.exec(url.pathname);
97
+ res = mim ? handleMessageImage(mim[1]!, mim[2]!, cfg.paths) : textRes("not found", 404);
98
+ code = res.status;
99
+ } else if (req.method === "POST") {
100
+ // The page's script asks for JSON on every POST (P11b); a no-JS form post gets today's 303s.
101
+ const wantsJson = (req.headers.get("accept") ?? "").includes("application/json");
102
+ if (url.pathname === "/message") {
103
+ res = await handleMessage(req, cfg, login, wantsJson);
104
+ code = res.status;
105
+ } else if (url.pathname === "/incident") {
106
+ res = handleIncident(cfg, await fieldsOf(req), login, wantsJson);
107
+ code = res.status;
108
+ } else if (url.pathname === "/answer") {
109
+ res = handleAnswer(cfg, source, await fieldsOf(req), login, wantsJson, pagesHost);
110
+ code = res.status;
111
+ } else if (url.pathname === "/unlock") {
112
+ res = handleUnlock(cfg, await fieldsOf(req), login, wantsJson);
113
+ code = res.status;
114
+ } else if (url.pathname === "/lock") {
115
+ res = handleLock(cfg, await fieldsOf(req), login, wantsJson);
116
+ code = res.status;
117
+ } else if (url.pathname === "/tier") {
118
+ res = handleTier(cfg, await fieldsOf(req), login, wantsJson);
119
+ code = res.status;
120
+ } else if (url.pathname === "/reorder") {
121
+ res = handleReorder(cfg, await fieldsOf(req), login, wantsJson);
122
+ code = res.status;
123
+ } else {
124
+ res = textRes("not found", 404);
125
+ code = 404;
126
+ }
127
+ } else {
128
+ res = textRes("not found", 404);
129
+ code = 404;
130
+ }
131
+ }
132
+ }
133
+ } catch {
134
+ res = textRes("internal error", 500);
135
+ code = 500;
136
+ }
137
+ log(cfg.paths.guard_log, `UI ${req.method} ${url.pathname} login=${login ?? "-"} → ${code}`);
138
+ return res;
139
+ },
140
+ });
141
+ return { stop: () => server.stop(true), hostname, port: Number(server.port) };
142
+ }