neurastream 0.2.55 → 0.2.57

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.
package/README.md CHANGED
@@ -135,13 +135,13 @@ One setting decides how much Main does without asking: `autonomy.tier` in the co
135
135
 
136
136
  With `ui.enabled: true` and `ui.owner_login` set (`neurastream config`, `docs/config.md`), `neurastream ui` serves one page bound to this machine's tailnet address only (port `ui.port`, default 7787; `templates/systemd/neurastream-ui.service` runs it as a user unit). A sticky top bar holds the "ns" logo, five pill tabs — Now, Queue, Agents, Spend, Base (see "Base tab" below), each a server-rendered view (`/?tab=…`, an unknown value falls back to Now) — and the lock pill ("🔒 Off" / "🔓 12 min") that opens the guard unlock ("Unlock 15 min", "Unlock 30 min", "Lock now"; when `guards.chat_unlock` is off it says so in plain words with the exact config line). Now is the home tab: a Today tile card over the last 24 h (needs-you count in warn color, list-price spend with a sparkline and the Main/agents split, agent runs with running/died counts and a sparkline, open plans), then one card per open `WAITING on owner:` plan that says why it needs him — the plan's `#` title, then Do (what to do), Stuck until then (what stays blocked, including plans this answer unblocks), and Why you (why Main cannot do it), with the goal folded into a Background block. A question ask gets "Yes"/"No"/"Reply…"; a task ask gets "Done". The answer shows as a one-time receipt ("Sent to Main · 08:12"); once the owner inbox already holds an answer for a plan, the card says so ("You answered ‘yes' · 14:19 — Main is on it") with a small change-answer link. The queue is one flat ranked list in `INDEX.md` order. Each card shows the plan title, a two-line summary from the plan's `Summary:` header (one or two plain sentences under Branch; if that line is missing, the first Goal bullet with a leading Owner or INCIDENT prefix cut off), and a status chip — waits you, waits on another plan, not started, phase K of N, or all N done. Drag a card by its ≡ handle, or tap "↑ top"/"↑"/"↓"; the drop rewrites `INDEX.md`, Main gets the move as a message and the page confirms "Moved to #2". Now shows the first 8 rows with a "Show all N ›" link to the Queue tab. The Agents tab lists working-now rows (a run that died before its first reply shows the model from the spawning agent's `model:` frontmatter, never "?"), the agent-score table, open incidents, recent merges/CI and machine health; the Spend tab pairs the spend tile with per-model spend over 24 h. The Now tab also has a "Tell Main" message box for a text note and up to four images; Main receives the text and pictures, and the page keeps a "Sent today" list for 12 hours before removing those messages and their image files. Light and dark follow the OS; there are no external assets and no build step — one server-rendered HTML string, inline CSS and one small inline script under a per-response CSP nonce (`bun scripts/ui-preview.ts <out.html> [--tab <name>]` renders a preview without a server). No chat, no plan editing, no shell.
137
137
 
138
- A request is served only when the peer is a tailnet address that is neither loopback nor this machine's own tailnet IP, `tailscale whois` names the `ui.owner_login` login — and the Host header is this machine: the tailnet address or the MagicDNS name, with the served port. The Host check runs on every request before whois, and a POST's Origin must match it, so a DNS-rebinding page (foreign Host, matching Origin, owner's phone) gets a 403 like everyone else. Every request logs one `UI <method> <path> login=<l> → <code>` line to the guard log.
138
+ A request is served only when the peer is a tailnet address that is neither loopback nor this machine's own tailnet IP, `tailscale whois` names the `ui.owner_login` login — and the Host header is this machine: the tailnet address or the MagicDNS name, with the served port. The Host check runs on every request before whois, and a POST's Origin must match it, so a DNS-rebinding page (foreign Host, matching Origin, owner's phone) gets a 403 like everyone else. `ui.allow_this_machine: true` skips only the two this-machine refusals — loopback and the machine's own tailnet IP are then served as the owner, GET and POST — with the risk in one line: any local process can then press the buttons. Every request logs one `UI <method> <path> login=<l> → <code>` line to the guard log.
139
139
 
140
140
  An answer appends one record to `<queue_state>/owner-inbox.jsonl` (plan, question, answer, login); unlock/lock go through the core unlock and log `UNLOCK ui source=ui:<login> minutes=N`. Main's session delivers each record once as a user message — at turn end and on a 15 s poll while idle — and marks the consumed rows in `<queue_state>/owner-inbox.cursor`; subagent sessions never deliver. Both files sit under the queue state dir, so guards refuse agent writes to them: an agent cannot forge an owner answer. Guards also refuse agent commands that start the page (`neurastream ui`, or `systemctl --user start/restart/enable` of `neurastream-ui`): starting it is the owner's move.
141
141
 
142
142
  ## Static pages (`neurastream pages`)
143
143
 
144
- `neurastream pages on [--port N] [--dir D]` installs the systemd user unit and serves regular files in the configured pages directory on the tailnet; `pages publish <file> [name] [--force] [--keep]` publishes an artifact and prints its MagicDNS URL, then `expires YYYY-MM-DD` or `kept`. A page without `--keep` is deleted `pages.keep_days` days after publishing (default 15). `pages list` prints each file as `<name> expires YYYY-MM-DD` or `<name> kept`, and `pages off` stops the service. Publish, list, and serve remove expired files first; serve repeats that sweep every hour. Requests are limited to the configured owner's tailnet login or loopback; hidden files, symlinks and paths outside the directory are not served. A published HTML page carries the notes panel `pages publish` injects: `neurastream notes check <page>` exits 1 while any note on it has no answer in `<queue_state>/page-notes/<page>.answers.json`, and `pages publish` refuses that page until the file answers every id; `pages publish <html> <name> --plan <plan.md>` marks the page as a plan's diagram: it then carries an Approve bar that records `Approved: <date> (<page>)` in the plan (disabled, and refused with 409, while a note on the page has no answer), and `neurastream diagram check <html> <plan.md>` requires that page to show every phase of the plan and every file or command its phase lines name, with 2+ kids behind every drilldown — `pages publish --plan` runs it, and Approve stays disabled (the server answers 409) until it passes. main-guard refuses a spawn on a plan that has such a page and no approval line — a chat "go" is recorded as the same line, and `Approval: self — owner: "<his words>"` covers a plan he hands to Main. the publish that goes through prints each answer beside its note, archives the closed notes and never reuses an id.
144
+ `neurastream pages on [--port N] [--dir D]` installs the systemd user unit and serves regular files in the configured pages directory on the tailnet; `pages publish <file> [name] [--force] [--keep]` publishes an artifact and prints its MagicDNS URL, then `expires YYYY-MM-DD` or `kept`. A page without `--keep` is deleted `pages.keep_days` days after publishing (default 15). `pages list` prints each file as `<name> expires YYYY-MM-DD` or `<name> kept`, and `pages off` stops the service. Publish, list, and serve remove expired files first; serve repeats that sweep every hour. Requests are limited to the configured owner's tailnet login or loopback; hidden files, symlinks and paths outside the directory are not served. A published HTML page carries the notes panel `pages publish` injects: `neurastream notes check <page>` exits 1 while any note on it has no answer in `<queue_state>/page-notes/<page>.answers.json`, and `pages publish` refuses that page until the file answers every id; `pages publish <html> <name> --plan <plan.md>` marks the page as a plan's diagram: it then carries an Approve bar that records the plan's text hash in `<queue_state>/plan-approvals.json` and never edits the plan (disabled, and refused with 409, while a note on the page has no answer), and `neurastream diagram check <html> <plan.md>` requires that page to show every phase of the plan and every file or command its phase lines name, with 2+ kids behind every drilldown — `pages publish --plan` runs it, and Approve stays disabled (the server answers 409) until it passes. main-guard refuses a spawn on a plan that has such a page and no approval record whose hash matches the plan's current text. The publish that goes through prints each answer beside its note, archives the closed notes and never reuses an id.
145
145
 
146
146
  ## Base tab (`/?tab=knowledge`)
147
147
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.55",
3
+ "version": "0.2.57",
4
4
  "description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -58,6 +58,7 @@
58
58
  },
59
59
  "scripts": {
60
60
  "typecheck": "tsc --noEmit",
61
+ "lint": "oxlint --deny-warnings --ignore-pattern 'tests/fixtures/**' src tests bin",
61
62
  "test": "bun test"
62
63
  },
63
64
  "omp": {
@@ -67,6 +68,7 @@
67
68
  },
68
69
  "devDependencies": {
69
70
  "@types/bun": "^1.3.14",
71
+ "oxlint": "1.90.0",
70
72
  "typescript": "^5.9.3"
71
73
  }
72
74
  }
@@ -21,6 +21,7 @@ import { basename, dirname, extname, join, resolve } from "node:path";
21
21
  import type { Decision } from "../../core/adapter.ts";
22
22
  import { AGENTS_TEMPLATE, renderBlock } from "../../core/agents-md.ts";
23
23
  import { chatGo, chatTier, type Tier } from "../../core/autonomy.ts";
24
+ import { chatApprove } from "../../core/plan-approval.ts";
24
25
  import { burdenRule, repoRules, rulesChanged } from "../../core/repo-rules.ts";
25
26
  import { configFile, loadConfig, reloadingConfig, type Config } from "../../core/config.ts";
26
27
  import { checkWrite, deferSteer, type WriteCheckConfig } from "../../core/write-check.ts";
@@ -565,6 +566,8 @@ export function deliverOwnerInbox(pi: ExtensionHost, cfg: Config): void {
565
566
  adapterLog(cfg, `owner inbox: delivered ${delivered} answer(s) (cursor ${cursor} → ${next})`);
566
567
  }
567
568
 
569
+ /** The most recently registered createOmpAdapter cleanup, for the exported reset(). */
570
+ let activeAdapterReset: (() => void) | null = null;
568
571
  /** Register the guard handlers on one extension host. `initial` is injectable for tests; `freshConfig` re-reads the config per guarded call. */
569
572
  export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig: () => Config = () => initial): void {
570
573
  // Guarded handlers take `cfg = freshConfig()` first, so an edited config.yml reaches the next call (P4e).
@@ -832,7 +835,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
832
835
 
833
836
  // The spawn event carries no brief, so the plan gate runs at the task tool call (original
834
837
  // behaviour); here only the allow-list and the task-only rule apply, with the original texts.
835
- pi.on("before_subagent_spawn", (event, ctx) => {
838
+ pi.on("before_subagent_spawn", (event, _ctx) => {
836
839
  cfg = freshConfig();
837
840
  const agent = asString(asRecord(event).agent);
838
841
  const kind = asString(asRecord(event).invocationKind);
@@ -1200,6 +1203,17 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1200
1203
  }
1201
1204
  };
1202
1205
 
1206
+ // Clear the rollover episode state so a later createOmpAdapter setup in the same
1207
+ // process starts clean: a stale armGraceTimer would otherwise fire with this
1208
+ // closure's cfg and recreate torn-down dirs (P3c).
1209
+ const clearRolloverState = (): void => {
1210
+ clearGrace?.();
1211
+ relaunched = false;
1212
+ flight = null;
1213
+ };
1214
+ // Clear the previous adapter's armed grace timer before this one overwrites the pointer (P3c).
1215
+ activeAdapterReset?.();
1216
+ activeAdapterReset = clearRolloverState;
1203
1217
  // The launcher restarts omp: the request file carries the note and the editor draft, and omp
1204
1218
  // shuts down only after the file is written. A failed write keeps the session running.
1205
1219
  // Returns whether the request was written.
@@ -1448,6 +1462,15 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1448
1462
  notifyGo(ctx, g);
1449
1463
  return { handled: true };
1450
1464
  }
1465
+ const a = chatApprove(text, cfg, "interactive");
1466
+ if (a.applied) {
1467
+ asRolloverCtx(ctx)?.notify(`approved ${basename(a.plan)}`);
1468
+ return { handled: true };
1469
+ }
1470
+ if (a.problem !== undefined) {
1471
+ asRolloverCtx(ctx)?.notify(a.problem);
1472
+ return { handled: true };
1473
+ }
1451
1474
  const r = q.chatUnlock(asString(e.text), cfg, "interactive");
1452
1475
  if (!r.applied) return undefined;
1453
1476
  notifyUnlock(ctx, r);
@@ -1555,6 +1578,15 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1555
1578
  });
1556
1579
  }
1557
1580
 
1581
+ /** Clear the active adapter's rollover state. Tests call this in afterAll so a stale
1582
+ * grace-period timer does not fire into a later test file's sandbox paths (P3c). */
1583
+ export function reset(): void {
1584
+ if (activeAdapterReset) {
1585
+ activeAdapterReset();
1586
+ activeAdapterReset = null;
1587
+ }
1588
+ }
1589
+
1558
1590
  /** package.json omp.extensions entry. */
1559
1591
  export default function ompExtension(pi: ExtensionHost): void {
1560
1592
  // The one switch (MAIN_ENV): plain `omp` runs nothing of neurastream — no hook, no command,
package/src/cli/pages.ts CHANGED
@@ -5,7 +5,7 @@ import { loadConfig } from "../core/config.ts";
5
5
  import { readExpiry, sweepPages } from "../core/pages-expiry.ts";
6
6
  import { startPagesServer } from "../core/pages.ts";
7
7
  import { pageNotesGate } from "../core/page-notes.ts";
8
- import { pagesOff, pagesOn, publishPage, type Runner } from "../core/pages-setup.ts";
8
+ import { pagesOff, pagesOn, publishPage, repoForPublish, type Runner } from "../core/pages-setup.ts";
9
9
  import { realTailscale, type Tailscale } from "../core/tailscale.ts";
10
10
 
11
11
  export interface PagesDeps { home?: string; runner?: Runner; tailscale?: Tailscale; clock?: () => Date }
@@ -25,24 +25,26 @@ export async function runPages(args: string[] = [], deps: PagesDeps = {}): Promi
25
25
  return new Promise<number>(() => {});
26
26
  }
27
27
  if (args[0] === "publish" && args[1]) {
28
- let force = false, keep = false, plan: string | undefined;
28
+ let force = false, keep = false, plan: string | undefined, repo: string | undefined;
29
29
  const rest: string[] = [];
30
30
  for (let i = 1; i < args.length; i++) {
31
31
  const arg = args[i]!;
32
32
  if (arg === "--force") force = true;
33
33
  else if (arg === "--keep") keep = true;
34
34
  else if (arg === "--plan") plan = args[++i] ?? "";
35
+ else if (arg === "--repo") repo = args[++i] ?? "";
35
36
  else rest.push(arg);
36
37
  }
37
38
  if (plan === "") { console.error("pages publish: --plan needs the plan file"); return 2; }
39
+ if (repo === "") { console.error("pages publish: --repo needs the repo name"); return 2; }
38
40
  // file first, then the optional name; flags may sit anywhere (2026-10-27: `--force <file>` used
39
- // to be read as file "--force" because only args.slice(2) was scanned)
41
+ // to be read as file "--force" because only args.slice(2) was scanned for flags)
40
42
  const file = rest[0];
41
43
  const name = rest[1];
42
44
  if (!file || rest.length > 2) return 2;
43
45
  const now = clock();
44
46
  sweepPages(cfg.pages.dir, cfg.pages.keep_days, now);
45
- const n = publishPage(file, name, force, cfg.pages.dir, { keep, keepDays: cfg.pages.keep_days, now, notes: pageNotesGate(cfg), plan });
47
+ const n = publishPage(file, name, force, cfg.pages.dir, { keep, keepDays: cfg.pages.keep_days, now, notes: pageNotesGate(cfg), plan, repo: repoForPublish(file, repo) });
46
48
  const host = (deps.tailscale ?? realTailscale).dnsName() ?? "tailnet";
47
49
  console.log(`http://${host}:${cfg.pages.port}/${encodeURIComponent(n)}`);
48
50
  const expires = readExpiry(cfg.pages.dir)[n]?.expires;
@@ -54,11 +56,13 @@ export async function runPages(args: string[] = [], deps: PagesDeps = {}): Promi
54
56
  const map = readExpiry(cfg.pages.dir);
55
57
  for (const f of readdirSync(cfg.pages.dir, { withFileTypes: true }).filter(e => e.isFile() && !e.name.startsWith("."))) {
56
58
  const expires = map[f.name]?.expires;
57
- console.log(`${f.name} ${expires ? `expires ${expires.slice(0, 10)}` : "kept"}`);
59
+ // A page published before the repo tag (plan 20261029_1436 P1) has no repo in its meta: "-"
60
+ // marks that, so the columns stay countable.
61
+ console.log(`${f.name} ${map[f.name]?.repo ?? "-"} ${expires ? `expires ${expires.slice(0, 10)}` : "kept"}`);
58
62
  }
59
63
  return 0;
60
64
  }
61
65
  } catch (e) { console.error(e instanceof Error ? e.message : String(e)); return 1; }
62
- console.error("usage: neurastream pages on [--port N] [--dir D] | off | serve | publish <file> [<name>] [--force] [--keep] | list");
66
+ console.error("usage: neurastream pages on [--port N] [--dir D] | off | serve | publish <file> [<name>] [--force] [--keep] [--repo <name>] | list");
63
67
  return 2;
64
68
  }
@@ -1,7 +1,7 @@
1
1
  import { existsSync, readFileSync, statSync } from "node:fs";
2
2
  import { basename, dirname } from "node:path";
3
3
  import type { Config } from "./config.ts";
4
- import { briefBudget, briefNamesPending } from "./guards.ts";
4
+ import { briefBudget, briefNamesPending, MAIN_PLAN_FILE } from "./guards.ts";
5
5
  import { exitText, helpDoc, printText } from "./help.ts";
6
6
  import { readIndex, sections } from "./queue/lib.ts";
7
7
 
@@ -112,7 +112,7 @@ function lint(path: string, cfg: Config): { errs: string[]; warns: string[] } {
112
112
  if (/\bplans?\b/i.test(text)) {
113
113
  const indexed = readIndex(cfg.paths.queue_index);
114
114
  const noPlanLine = "no line names the plan's absolute path in its main checkout (paths.queue_index)";
115
- const planPaths = [...paths].map(clean).filter(p => /\/docs\/plans\/[\w.-]+\.md$/.test(p));
115
+ const planPaths = [...paths].map(clean).filter(p => MAIN_PLAN_FILE.test(p));
116
116
  const named = planPaths.filter(p => indexed.includes(p));
117
117
  if (indexed.length && !named.length) {
118
118
  const copy = planPaths[0];
@@ -164,16 +164,16 @@ export interface Config {
164
164
  go_phrase: string;
165
165
  };
166
166
  /** The owner's phone page (`neurastream ui`): binds the tailnet address only. */
167
- ui: { enabled: boolean; port: number; owner_login: string };
167
+ ui: { enabled: boolean; port: number; owner_login: string; allow_this_machine: boolean };
168
168
  /** Plan review gate (plan 20261028_1600): reuse lines and, from P2 on, the reviewer PASS lock. */
169
169
  review: {
170
- /** Plans stamped before this ISO date are exempt from the reuse-line and reviewer-PASS gates; "" = off. */
171
- since: string;
172
- /** Agents a review spawn may run under: the PASS exemption needs one of these plus the brief's `Plan review: <plan>` line. */
170
+ /** Agents a review spawn may run under: the PASS exemption needs one of these plus the brief's `Plan review: <plan>` line. An empty list turns both review gates off (P5c). */
173
171
  agents: string[];
174
172
  /** Minutes the spawn gate caches a repo's open-MR list in <queue_state>/mr-cache.json; 0 = no cache. */
175
173
  mr_cache_minutes: number;
176
174
  };
175
+ /** Plan approval hard gate (plan 20261029_1455 P3): a plan stamped at or after `since` needs a page and an approval record. "" = off. */
176
+ approval: { since: string };
177
177
  /** Static pages hosted over the tailnet. */
178
178
  pages: { enabled: boolean; port: number; dir: string; keep_days: number };
179
179
  /** Repo-local HTML explainers under docs/knowledge/ (owner page Knowledge tab). */
@@ -503,6 +503,8 @@ function check(cfg: Config): void {
503
503
  throw new ConfigError(`${at}.argv must be a non-empty list of strings containing "{file}"`);
504
504
  if (typeof l.pattern !== "string" || !l.pattern.includes("(?<rule>"))
505
505
  throw new ConfigError(`${at}.pattern must be a regex with a named group rule`);
506
+ if (l.only_with_config !== undefined && (!Array.isArray(l.only_with_config) || l.only_with_config.some((n) => typeof n !== "string" || n === "")))
507
+ throw new ConfigError(`${at}.only_with_config must be a list of file names`);
506
508
  regexes.push([`${at}.pattern`, l.pattern]);
507
509
  }
508
510
  for (const [key, src] of regexes) {
@@ -519,11 +521,12 @@ function check(cfg: Config): void {
519
521
  throw new ConfigError(`guards.plan_offer: not a valid regex: ${cfg.guards.plan_offer}`);
520
522
  }
521
523
  if (!(cfg.rollover.max_session_mb > 0)) throw new ConfigError("rollover.max_session_mb must be > 0");
522
- if (typeof cfg.review.since !== "string") throw new ConfigError("review.since must be an ISO date string (\"\" = off)");
523
524
  if (!Array.isArray(cfg.review.agents) || cfg.review.agents.some(a => typeof a !== "string" || !a.trim()))
524
525
  throw new ConfigError('review.agents must be a list of agent names allowed to run review spawns (default ["reviewer"])');
525
526
  if (!Number.isInteger(cfg.review.mr_cache_minutes) || cfg.review.mr_cache_minutes < 0)
526
527
  throw new ConfigError("review.mr_cache_minutes must be an integer >= 0 (minutes the spawn gate caches a repo's open-MR list; 0 = no cache)");
528
+ if (typeof cfg.approval.since !== "string" || (cfg.approval.since !== "" && !/^\d{8}_\d{4}$/.test(cfg.approval.since)))
529
+ throw new ConfigError('approval.since must be "" or a plan stamp YYYYMMDD_HHMM (plans stamped at or after it need a page and an approval record)');
527
530
  if (cfg.autonomy.tier !== "strict" && cfg.autonomy.tier !== "opinionated" && cfg.autonomy.tier !== "full")
528
531
  throw new ConfigError('autonomy.tier must be "strict", "opinionated" or "full"');
529
532
  if (!Number.isInteger(cfg.autonomy.strict_edit_limit) || cfg.autonomy.strict_edit_limit < 1)
@@ -26,7 +26,8 @@ import { appendFileSync, mkdirSync, readFileSync, statSync, writeFileSync } from
26
26
  import path from "node:path";
27
27
  import type { Decision, InjectEvent, PlanEditEvent, SpawnEvent, StopEvent, ToolEvent } from "./adapter.ts";
28
28
  import { currentTier, takeGo } from "./autonomy.ts";
29
- import { approvalProblem } from "./plan-approval.ts";
29
+ import { approvalProblem, MAIN_ONLY_LINE, reviewHash } from "./plan-approval.ts";
30
+ export { reviewHash };
30
31
  import type { Config } from "./config.ts";
31
32
  import { addIncident, openIncidents, ownerMessagesFile, ownerSaid, readOwnerMessages, type IncidentView, type OwnerMessage } from "./incidents.ts";
32
33
  import { notifyProtectedPaths, notifySecretReadHit } from "./notify.ts";
@@ -167,18 +168,6 @@ function writePlanReviews(reviews: Record<string, PlanReview>, cfg: Config): voi
167
168
  }
168
169
  }
169
170
 
170
- /** What a PASS covers: the plan text outside "## Progress" without the Main-only lines, so progress notes never expire a review. */
171
- export function reviewHash(text: string): string {
172
- return q.sha(
173
- q
174
- .outsideProgress(text)
175
- .split("\n")
176
- .filter(l => !MAIN_ONLY_LINE.test(l))
177
- .map(l => l.replace(/^(\s*[-*]\s+)\[[xX]\]/, "$1[ ]")) // a ticked phase box hashes as unticked: ticking never expires a PASS
178
- .join("\n"),
179
- );
180
- }
181
-
182
171
  /** The progress entry that records a review; only a subagent's edit can carry one. The verdict is the match, never a substring. */
183
172
  const REVIEW_LINE = /^- (?:\d{4}-\d{2}-\d{2} \d{2}:\d{2} [^\s:]+: )?PLAN REVIEW: (PASS|FAIL)\b/;
184
173
  /** Any entry that opens like a review line; one that REVIEW_LINE does not match is restored, not recorded. */
@@ -191,14 +180,14 @@ export type Spawner = "main" | "sub";
191
180
  * P2 (plan 20261028_1600): a spawn on a plan needs a recorded reviewer PASS whose hash still
192
181
  * matches the plan text — progress-only edits keep a PASS valid, any other change expires it,
193
182
  * a FAIL is denied with its first finding. A review spawn itself — an agent from review.agents
194
- * whose brief has the `Plan review: <plan>` line — is exempt when Main launches it, and so is any plan stamped
195
- * before `review.since` (P4c: same cutover as the reuse-line gate).
183
+ * whose brief has the `Plan review: <plan>` line — is exempt when Main launches it. P5 removed
184
+ * the cutover: every named plan is gated.
196
185
  */
197
186
  export function reviewPassProblem(named: string[], brief: string, agent: string, cfg: Config, spawner: Spawner): string | null {
187
+ if (!cfg.review.agents.length) return null; // P5c: an empty review.agents list turns both review gates off
198
188
  const reviews = readPlanReviews();
199
189
  for (const file of named) {
200
190
  if (isReviewSpawn(file, brief, agent, cfg, spawner)) continue;
201
- if (!q.reviewApplies(file, cfg.review.since)) continue;
202
191
  const rec = reviews[file];
203
192
  if (!rec) return `plan ${file} has no current reviewer PASS. Spawn a reviewer with templates/plan-review-brief.md.`;
204
193
  if (rec.verdict === "FAIL")
@@ -562,7 +551,7 @@ function unticked(p: Plan): string[] {
562
551
 
563
552
  // Plans an implementer brief may run on; returns [reason, null] or [null, plan files].
564
553
  export function planGate(text: string, label: string, cfg?: Config): [string | null, string[]] {
565
- const plans = q.activePlans(undefined, undefined, cfg?.review.since ?? "");
554
+ const plans = q.activePlans(undefined, undefined, cfg?.review.agents ?? []);
566
555
  const unclosed = plans.filter(p => (p.status === "complete" || p.status === "cancelled") && !q.awaitingMerge(p));
567
556
  if (unclosed.length)
568
557
  return [
@@ -597,7 +586,7 @@ export function planGate(text: string, label: string, cfg?: Config): [string | n
597
586
  [],
598
587
  ];
599
588
  if (cfg) {
600
- const approval = approvalProblem(p.text, p.file, cfg.pages.dir);
589
+ const approval = approvalProblem(p.text, p.file, cfg.pages.dir, cfg.approval.since);
601
590
  if (approval) return [approval, []];
602
591
  }
603
592
  const open = unticked(p);
@@ -638,9 +627,12 @@ function priorityIdle(p: Plan, plans: Plan[]): boolean {
638
627
  * Proof is either the higher plan's own `Waits on: <plan>` line for a plan still open in the index
639
628
  * (then it is not idle at all) or a `Priority skip: <path> — owner: "<words>"` line whose quoted
640
629
  * words (≥ 4, normalised) appear in one of `messages` (the owner's recorded words of the last
641
- * 24 h; `now` is the current unix seconds). In tier full (`cfg`) a `Priority skip: <path> —
642
- * Main: "<reason>"` line with ≥ 4 words is proof too; without `cfg` the refusal behaviour is the
643
- * pre-tier one. Any other skip line is refused.
630
+ * 24 h; `now` is the current unix seconds). A higher plan whose branch carries an open MR in the
631
+ * cached forge list (fresh within `review.mr_cache_minutes`; the one list the main-start sweep
632
+ * and pendingWorkProblem maintain — never queried here) is landing, not idle: no proof needed.
633
+ * A stale cache proves nothing, so the refusal stands (I-20261029-435). In tier full (`cfg`) a
634
+ * `Priority skip: <path> — Main: "<reason>"` line with ≥ 4 words is proof too; without `cfg` the
635
+ * refusal behaviour is the pre-tier one. Any other skip line is refused.
644
636
  * `staffed === undefined` means the caller had no running-job info (CLI spawn without it): never
645
637
  * refuse. Plans already named by this call never block it.
646
638
  */
@@ -657,9 +649,12 @@ export function priorityProblem(plans: Plan[], named: string[], staffed: string[
657
649
  if (plan && why) skipLines[plan] = why;
658
650
  }
659
651
  const skips: PrioritySkip[] = [];
652
+ const cache = readMrCache();
653
+ const fresh = cfg ? now - cache.at < cfg.review.mr_cache_minutes * 60 : false;
660
654
  for (let i = 0; i < higher.length; i++) {
661
655
  const p = higher[i]!;
662
656
  if (!priorityIdle(p, plans) || staffed.includes(p.file)) continue;
657
+ if (fresh && p.branch && (cache.repos[p.repo] ?? []).some(mr => mr.branch === p.branch)) continue;
663
658
  const why = skipLines[p.file];
664
659
  // Tier full (20261025_1940 P2): Main's own >= 4-word reason is proof enough; every other
665
660
  // tier refuses it exactly as before — only the owner's recorded words let a skip through.
@@ -1214,8 +1209,8 @@ export function resetMainCalls(): void {
1214
1209
  writeWindow(w);
1215
1210
  }
1216
1211
 
1217
- /** A live plan file (archived plans excluded); Main's plan-text checks run on these. */
1218
- export const MAIN_PLAN_FILE = /\/docs\/plans\/(?!archive\/)[^/]+\.md$/;
1212
+ /** A live plan file (archived plans excluded); Main's plan-text checks run on these. Subfolders like docs/plans/immediate/ hold live plans too. */
1213
+ export const MAIN_PLAN_FILE = /\/docs\/plans\/(?!archive\/)(?:[^/]+\/)*[^/]+\.md$/;
1219
1214
 
1220
1215
  /**
1221
1216
  * pre-tool: plan-guard checkCall for subs (protected files, budget, plan-edit rules, blockers)
@@ -1497,7 +1492,7 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
1497
1492
  recordOwnerMessage(e.inject, cfg);
1498
1493
  let summary: string;
1499
1494
  try {
1500
- summary = q.queueSummary(undefined, cfg.review.since);
1495
+ summary = q.queueSummary(undefined, cfg.review.agents);
1501
1496
  } catch (err) {
1502
1497
  summary = `Queue unreadable (${q.INDEX}): ${err}`;
1503
1498
  }
@@ -1521,9 +1516,6 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
1521
1516
  };
1522
1517
  }
1523
1518
 
1524
- // Lines only Main may write: the status, owner parking, plan waits, owner cancellation, cancelled-list clearance.
1525
- const MAIN_ONLY_LINE = /^\s*(?:[-*]\s+)?(Status:|WAITING on owner:|Waits on:|Cancelled by owner:|False positive:)/;
1526
-
1527
1519
  function mainOnlyLines(text: string): string {
1528
1520
  return text.split("\n").filter(l => MAIN_ONLY_LINE.test(l)).join("\n");
1529
1521
  }
@@ -1708,10 +1700,11 @@ function planFile(p: string, planPath: string, text: string): string {
1708
1700
  return path.join(root, home);
1709
1701
  }
1710
1702
 
1711
- /** The roots a plan-relative path resolves against: the plan's Worktree (when set), then its repo (dirname³ of the plan file). */
1703
+ /** The roots a plan-relative path resolves against: the plan's Worktree (when set), then its repo (the text before /docs/plans/, so a docs/plans/<subdir>/ plan still resolves repo-relative paths against <repo>). */
1712
1704
  function planRoots(planPath: string, text: string): string[] {
1713
1705
  const wt = /^Worktree:\s*(\S+)/m.exec(text)?.[1];
1714
- const repo = path.dirname(path.dirname(path.dirname(planPath)));
1706
+ const cut = planPath.indexOf("/docs/plans/");
1707
+ const repo = cut >= 0 ? planPath.slice(0, cut) : path.dirname(path.dirname(path.dirname(planPath)));
1715
1708
  return wt && wt !== "-" ? [wt, repo] : [repo];
1716
1709
  }
1717
1710
 
@@ -1803,12 +1796,12 @@ function readMainReads(): Record<string, string> {
1803
1796
  }
1804
1797
 
1805
1798
  // Plans still responsible for: open plans (parked "WAITING on owner" excluded) plus queue problems.
1806
- export function openQueue(reviewSince = ""): string[] {
1799
+ export function openQueue(reviewAgents: string[] = []): string[] {
1807
1800
  const open = q
1808
1801
  .activePlans()
1809
1802
  .filter(p => !p.waiting && !q.awaitingMerge(p))
1810
1803
  .map(p => p.file);
1811
- for (const prob of q.queueProblems(undefined, undefined, reviewSince)) open.push(`${prob.where}: ${prob.problem}`);
1804
+ for (const prob of q.queueProblems(undefined, undefined, reviewAgents)) open.push(`${prob.where}: ${prob.problem}`);
1812
1805
  const unique: string[] = [];
1813
1806
  for (const item of open) if (!unique.includes(item)) unique.push(item);
1814
1807
  return unique;
@@ -1845,7 +1838,7 @@ export function checkStop(e: StopEvent, cfg: Config): Decision {
1845
1838
  }
1846
1839
  let open: string[];
1847
1840
  try {
1848
- open = openQueue(cfg.review.since);
1841
+ open = openQueue(cfg.review.agents);
1849
1842
  } catch (err) {
1850
1843
  log(cfg.paths.guard_log, `BLOCK stop: cannot read queue: ${err}`);
1851
1844
  open = [`queue unreadable (${q.INDEX}): ${err}`];
@@ -49,7 +49,9 @@ export function urlField(s: string): string {
49
49
  return new TextDecoder().decode(new Uint8Array(bytes));
50
50
  }
51
51
 
52
- function repoKey(repoPath: string): string {
52
+ /** The one repo-name rule (Base tab and pages alike): the origin remote's basename without
53
+ * ".git", else the directory's basename. */
54
+ export function repoKey(repoPath: string): string {
53
55
  const remote = gitRaw(repoPath, ["remote", "get-url", "origin"]).stdout.trim();
54
56
  if (remote) {
55
57
  const base = basename(remote.replace(/\/$/, ""));
@@ -65,7 +67,7 @@ function parseTitle(html: string, fallback: string): string {
65
67
  return t || fallback;
66
68
  }
67
69
 
68
- function topicUpdated(repoPath: string, rel: string, abs: string, now: number): string {
70
+ function topicUpdated(repoPath: string, rel: string, abs: string, _now: number): string {
69
71
  const log = gitRaw(repoPath, ["log", "-1", "--format=%cI", "--", rel]).stdout.trim();
70
72
  if (log) return log;
71
73
  const mtime = statSync(abs).mtimeMs;
@@ -19,6 +19,7 @@ import { cpuCount } from "./host.ts";
19
19
  import { dismissIncident, isFindingKind, openIncidents } from "./incidents.ts";
20
20
  import { byText, knowledgeManifest, readKnowledgeTopicFile, urlField, urlValue, type KnowledgeEntry } from "./knowledge.ts";
21
21
  import { log } from "./guards.ts";
22
+ import { publishedPages } from "./pages-expiry.ts";
22
23
  import { readMetricEvents } from "./metrics.ts";
23
24
  import { activePlans, chatUnlock, dependencyOrderProblems, expandHome, gitTop, stateDirPath, unlockPath, type Plan } from "./queue/lib.ts";
24
25
  import { featuresReport, gatherTags, loadPlans, releasesReport, type FeaturesReport, type ReleaseRow, type ReleaseSideStats, type ReleasesReport } from "./results.ts";
@@ -79,9 +80,10 @@ export function isTailnet(peer: string): boolean {
79
80
  return TAILNET6.test(peer);
80
81
  }
81
82
 
82
- /** Serve only the owner's phone: a tailnet peer that is not this machine and not loopback, whose tailscale whois login equals ui.owner_login. Everything else is a 403. */
83
+ /** Serve only the owner's phone: a tailnet peer that is not this machine and not loopback, whose tailscale whois login equals ui.owner_login. Everything else is a 403. With `ui.allow_this_machine`, this machine itself (loopback and its own tailnet IP) is served as the owner too — any local process can then press the buttons. */
83
84
  export function authenticate(cfg: Config, tailscale: Tailscale, peer: string): Auth {
84
85
  if (!cfg.ui.owner_login) return { ok: false, why: "ui.owner_login is empty" };
86
+ if (cfg.ui.allow_this_machine && (isLoopback(peer) || peer === tailscale.ip4())) return { ok: true, login: cfg.ui.owner_login };
85
87
  if (isLoopback(peer)) return { ok: false, why: "loopback peer" };
86
88
  if (!isTailnet(peer)) return { ok: false, why: "peer is not a tailnet address" };
87
89
  if (peer === tailscale.ip4()) return { ok: false, why: "this machine's own tailnet address" };
@@ -738,6 +740,9 @@ function jsonFail(error: string, status: number): Response {
738
740
 
739
741
  // ---- page assembly: one unreadable source never takes the page down ----
740
742
 
743
+ /** One published page row for the Base tab: the pages-server link is built once, at data build. */
744
+ export interface PublishedPageRow { name: string; repo: string; published: string; url: string }
745
+
741
746
  export interface PageData {
742
747
  questions: QuestionRow[] | null;
743
748
  agents: AgentRow[] | null;
@@ -748,6 +753,8 @@ export interface PageData {
748
753
  machine: MachineRow | null;
749
754
  /** Repo-local HTML explainers from the knowledge manifest; null when unreadable. */
750
755
  knowledge: KnowledgeEntry[] | null;
756
+ /** Published pages (plan 20261029_1436 P2), newest first, with their pages-server URL; null when unreadable. */
757
+ pages: PublishedPageRow[] | null;
751
758
  /** The 24 h tile numbers; null when the run source is unreadable. */
752
759
  stats: NowStats | null;
753
760
  /** The Results tab's saved numbers and build state; absent on every other tab. The numbers come from a background process (computeResults), never from the request. */
@@ -767,6 +774,10 @@ function safe<T>(build: () => T): T | null {
767
774
  }
768
775
  }
769
776
 
777
+ function publishedRows(cfg: Config, host: string): PublishedPageRow[] {
778
+ return publishedPages(cfg.pages.dir, new Date()).map(p => ({ ...p, url: `http://${host}:${cfg.pages.port}/${urlValue(p.name)}` }));
779
+ }
780
+
770
781
  function lockMinutesLeft(cfg: Config): number | null {
771
782
  try {
772
783
  const end = statSync(unlockPath()).mtimeMs + cfg.guards.unlock_minutes * 60_000;
@@ -777,7 +788,7 @@ function lockMinutesLeft(cfg: Config): number | null {
777
788
  }
778
789
  }
779
790
 
780
- export function buildPageData(cfg: Config, source: RunSource, tab: string, build: ResultsBuild = spawnResultsBuild): PageData {
791
+ export function buildPageData(cfg: Config, source: RunSource, tab: string, build: ResultsBuild = spawnResultsBuild, pagesHost = "tailnet"): PageData {
781
792
  return {
782
793
  questions: safe(() => questionRows(cfg)),
783
794
  agents: safe(() => agentRows(cfg, source)),
@@ -787,6 +798,7 @@ export function buildPageData(cfg: Config, source: RunSource, tab: string, build
787
798
  scores: safe(() => scoresData(cfg)),
788
799
  machine: safe(() => machineRow(cfg)),
789
800
  knowledge: safe(() => knowledgeManifest(cfg)),
801
+ pages: safe(() => publishedRows(cfg, pagesHost)),
790
802
  stats: safe(() => nowStats(cfg, source, nowSec())),
791
803
  results: tab === "results" ? safe(() => resultsView(nowSec(), build)) : undefined,
792
804
  messages: safe(() => recentOwnerMessages(nowSec())),
@@ -918,34 +930,46 @@ bindPage();
918
930
  * read-only files at docs/knowledge/<topic>.html in a repo under the configured roots; the page
919
931
  * bytes come from /knowledge/<repo>/<topic> and there is no route that writes one.
920
932
  */
921
- function knowledgeHtml(entries: KnowledgeEntry[], repo: string, topic: string): string {
933
+ function knowledgeHtml(entries: KnowledgeEntry[], repo: string, topic: string, pages: PublishedPageRow[]): string {
922
934
  const repoHref = `/?tab=knowledge&repo=${urlValue(repo)}`;
923
935
  const crumb =
924
936
  repo === ""
925
937
  ? ""
926
938
  : `<p class="sub"><a href="/?tab=knowledge">knowledge-base</a> / ${topic === "" ? esc(repo) : `<a href="${repoHref}">${esc(repo)}</a>`}${topic === "" ? "" : ` / ${esc(topic)}`}</p>`;
927
- if (entries.length === 0) {
928
- return `<h1>Base</h1><div class="card"><p class="empty">No topics yet. Any repo under the configured roots counts: put a page in <span class="mono">docs/knowledge/</span> and it shows up here on the next reload.</p></div>`;
939
+ if (entries.length === 0 && pages.length === 0) {
940
+ return `<h1>Base</h1><div class="card"><p class="empty">Nothing here yet. Any repo under the configured roots counts: put a page in <span class="mono">docs/knowledge/</span> or publish one with <span class="mono">pages publish</span>, and it shows up here on the next reload.</p></div>`;
929
941
  }
930
942
  if (repo === "") {
931
- const repos = new Map<string, KnowledgeEntry[]>();
932
- for (const e of entries) repos.set(e.repo, [...(repos.get(e.repo) ?? []), e]);
943
+ // One card per repo NAME (plan 20261029_1436 P2): a repo's knowledge topics and its published
944
+ // pages share the card; a worktree's page was already tagged with the main checkout's name.
945
+ const repos = new Map<string, { topics: KnowledgeEntry[]; pages: PublishedPageRow[] }>();
946
+ const slot = (name: string) => {
947
+ const r = repos.get(name) ?? { topics: [], pages: [] };
948
+ repos.set(name, r);
949
+ return r;
950
+ };
951
+ for (const e of entries) slot(e.repo).topics.push(e);
952
+ for (const p of pages) slot(p.repo).pages.push(p);
933
953
  const rows = [...repos.entries()]
934
954
  .sort((a, b) => byText(a[0], b[0]))
935
- .map(([name, list]) => {
936
- const newest = list.map(e => e.updated).sort().at(-1)!.slice(0, 10);
937
- return `<div class="mrow"><a href="/?tab=knowledge&repo=${urlValue(name)}">${esc(name)}</a><span class="mono">${list.length} topic${list.length === 1 ? "" : "s"} · ${newest}</span></div>`;
955
+ .map(([name, r]) => {
956
+ const n = r.topics.length + r.pages.length;
957
+ const newest = [...r.topics.map(e => e.updated), ...r.pages.map(p => p.published)].sort().at(-1)!.slice(0, 10);
958
+ return `<div class="mrow"><a href="/?tab=knowledge&repo=${urlValue(name)}">${esc(name)}</a><span class="mono">${n} page${n === 1 ? "" : "s"} · ${newest}</span></div>`;
938
959
  })
939
960
  .join("");
940
- return `<h1>Base</h1><p class="sub">One card per repo with pages in <span class="mono">docs/knowledge/</span> — tap a repo for its topics.</p><div class="card">${rows}</div>`;
961
+ return `<h1>Base</h1><p class="sub">One card per repo: its <span class="mono">docs/knowledge/</span> pages and the pages Main published from it — tap a repo to open its list.</p><div class="card">${rows}</div>`;
941
962
  }
942
963
  const topics = entries.filter(e => e.repo === repo);
943
- if (topics.length === 0) return `${crumb}<div class="card"><p class="empty">No repo named "${esc(repo)}" has a page under the configured roots.</p></div>`;
964
+ const repoPages = pages.filter(p => p.repo === repo);
965
+ if (topics.length === 0 && repoPages.length === 0) return `${crumb}<div class="card"><p class="empty">No repo named "${esc(repo)}" has a page under the configured roots.</p></div>`;
944
966
  if (topic === "") {
945
- const rows = topics
967
+ const topicRows = topics
946
968
  .map(e => `<div class="mrow"><a href="${repoHref}&topic=${urlValue(e.topic)}">${esc(e.title)}</a><span class="mono">${e.updated.slice(0, 10)}</span></div>`)
947
969
  .join("");
948
- return `${crumb}<div class="card">${rows}</div>`;
970
+ // Published pages after the topics, newest first (publishedPages sorts them that way).
971
+ const pageRows = repoPages.map(p => `<div class="mrow"><a href="${p.url}">${esc(p.name)}</a><span class="mono">${p.published.slice(0, 10)}</span></div>`).join("");
972
+ return `${crumb}<div class="card">${topicRows}${pageRows}</div>`;
949
973
  }
950
974
  const hit = topics.find(e => e.topic === topic);
951
975
  if (hit === undefined) return `${crumb}<div class="card"><p class="empty">No topic "${esc(topic)}" in ${esc(repo)}.</p></div>`;
@@ -1268,9 +1292,9 @@ ${merges}
1268
1292
  ${machine}
1269
1293
  </div>`
1270
1294
  : tab === "knowledge"
1271
- ? `${data.knowledge === null ? na("Base") : knowledgeHtml(data.knowledge, params.get("repo") ?? "", params.get("topic") ?? "")}`
1295
+ ? `${data.knowledge === null ? na("Base") : knowledgeHtml(data.knowledge, params.get("repo") ?? "", params.get("topic") ?? "", data.pages ?? [])}`
1272
1296
  : tab === "spend"
1273
- ? `<h1>Spend</h1>
1297
+ ? `<h1>Spend</h1
1274
1298
  <p class="sub">List price over the last 24 hours.</p>
1275
1299
  <div class="card">
1276
1300
  ${spendTileHtml(data)}
@@ -1434,9 +1458,9 @@ function sentTo(tab: string, sent: string): string {
1434
1458
  }
1435
1459
 
1436
1460
  /** The normal page (the GET layout) as a POST reply; the stale-answer reply is this with sent=stale. */
1437
- function pageRes(cfg: Config, source: RunSource, params: URLSearchParams, build: ResultsBuild = spawnResultsBuild): Response {
1461
+ function pageRes(cfg: Config, source: RunSource, params: URLSearchParams, build: ResultsBuild = spawnResultsBuild, pagesHost = "tailnet"): Response {
1438
1462
  const nonce = randomUUID().replaceAll("-", "");
1439
- return new Response(renderPage(cfg, buildPageData(cfg, source, params.get("tab") ?? "", build), params, nonce), {
1463
+ return new Response(renderPage(cfg, buildPageData(cfg, source, params.get("tab") ?? "", build, pagesHost), params, nonce), {
1440
1464
  status: 200,
1441
1465
  headers: {
1442
1466
  "content-type": "text/html; charset=utf-8",
@@ -1459,7 +1483,7 @@ function appendAnswer(plan: string, question: string, answer: string, login: str
1459
1483
  lastAnswerByPlan.set(plan, { answer, ts: now });
1460
1484
  }
1461
1485
 
1462
- function handleAnswer(cfg: Config, source: RunSource, fields: Record<string, string>, login: string, wantsJson: boolean): Response {
1486
+ function handleAnswer(cfg: Config, source: RunSource, fields: Record<string, string>, login: string, wantsJson: boolean, pagesHost: string): Response {
1463
1487
  const planFile = (fields.plan ?? "").trim();
1464
1488
  const answer = (fields.answer_text ?? "").trim() || (fields.answer ?? "").trim();
1465
1489
  if (!planFile || !answer) return wantsJson ? jsonFail("plan and answer are required", 400) : textRes("plan and answer are required", 400);
@@ -1470,7 +1494,7 @@ function handleAnswer(cfg: Config, source: RunSource, fields: Record<string, str
1470
1494
  // Stale answer (P8b): Main cleared the question before the answer arrived; pass it on anyway.
1471
1495
  appendAnswer(planFile, "(already cleared)", answer, login);
1472
1496
  if (wantsJson) return jsonSent("stale", receiptText("stale", new URLSearchParams()));
1473
- return pageRes(cfg, source, new URLSearchParams({ sent: "stale" }));
1497
+ return pageRes(cfg, source, new URLSearchParams({ sent: "stale" }), undefined, pagesHost);
1474
1498
  }
1475
1499
  appendAnswer(planFile, plan.waitingLine, answer, login);
1476
1500
  if (wantsJson) return jsonSent("answer", receiptText("answer", new URLSearchParams()));
@@ -1722,6 +1746,8 @@ function handleReorder(cfg: Config, fields: Record<string, string>, login: strin
1722
1746
  export function startOwnerUi(opts: OwnerUiOptions): OwnerUiServer {
1723
1747
  const { cfg, tailscale, source } = opts;
1724
1748
  const resultsBuild = opts.resultsBuild ?? spawnResultsBuild;
1749
+ // The Base tab links to the pages server by its MagicDNS name, the same URL `pages publish` prints.
1750
+ const pagesHost = tailscale.dnsName() ?? "tailnet";
1725
1751
  // The double-press guard (P8c) is per-server memory: a fresh server starts empty, which also
1726
1752
  // keeps the tests (one server per test) hermetic.
1727
1753
  lastAnswerByPlan.clear();
@@ -1770,7 +1796,7 @@ export function startOwnerUi(opts: OwnerUiOptions): OwnerUiServer {
1770
1796
  code = 403;
1771
1797
  } else if (req.method === "GET" && url.pathname === "/") {
1772
1798
  sweepOwnerMessages(nowSec());
1773
- res = pageRes(cfg, source, url.searchParams, resultsBuild);
1799
+ res = pageRes(cfg, source, url.searchParams, resultsBuild, pagesHost);
1774
1800
  code = 200;
1775
1801
  } else if (req.method === "GET" && url.pathname.startsWith("/knowledge/")) {
1776
1802
  // The Knowledge tab's frame: the topic's own file bytes, GET only, no write path.
@@ -1795,7 +1821,7 @@ export function startOwnerUi(opts: OwnerUiOptions): OwnerUiServer {
1795
1821
  res = handleIncident(cfg, await fieldsOf(req), login, wantsJson);
1796
1822
  code = res.status;
1797
1823
  } else if (url.pathname === "/answer") {
1798
- res = handleAnswer(cfg, source, await fieldsOf(req), login, wantsJson);
1824
+ res = handleAnswer(cfg, source, await fieldsOf(req), login, wantsJson, pagesHost);
1799
1825
  code = res.status;
1800
1826
  } else if (url.pathname === "/unlock") {
1801
1827
  res = handleUnlock(cfg, await fieldsOf(req), login, wantsJson);