neurastream 0.3.18 → 0.3.20

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.
@@ -24,7 +24,7 @@ import { isBusy } from "./file-lock.ts";
24
24
  import { log, MAIN_ID_RE } from "./guards.ts";
25
25
  import { publishedPages } from "./pages-expiry.ts";
26
26
  import { readMetricEvents } from "./metrics.ts";
27
- import { activePlans, chatUnlock, dependencyOrderProblems, expandHome, gitTop, stateDirPath, unlockPath, writeIndex, type Plan } from "./queue/lib.ts";
27
+ import { activePlans, chatUnlock, dependencyOrderProblems, expandHome, gitTop, writeIndex, type Plan, type QueuePaths } from "./queue/lib.ts";
28
28
  import { featuresReport, gatherTags, loadPlans, releasesReport, type FeaturesReport, type ReleaseRow, type ReleaseSideStats, type ReleasesReport } from "./results.ts";
29
29
  import type { Tailscale } from "./tailscale.ts";
30
30
  import { recheckHolds, staleFiles, type HoldRunner } from "./waiting-check.ts";
@@ -70,8 +70,8 @@ export interface OwnerUiOptions {
70
70
  export type Auth = { ok: true; login: string } | { ok: false; why: string };
71
71
 
72
72
  /** The inbox the page appends answers to and the adapter delivers from: under the queue state dir. */
73
- export function inboxPath(): string {
74
- return `${stateDirPath()}/owner-inbox.jsonl`;
73
+ export function inboxPath(paths: Pick<QueuePaths, "queue_state">): string {
74
+ return `${paths.queue_state}/owner-inbox.jsonl`;
75
75
  }
76
76
 
77
77
  export function isLoopback(peer: string): boolean {
@@ -127,10 +127,10 @@ export interface QuestionRow {
127
127
  }
128
128
 
129
129
  /** The newest inbox record that carries an answer for this plan, if any. A missing or torn inbox is simply "no answer". */
130
- function lastAnswerFor(plan: string): { answer: string; at: number } | null {
130
+ function lastAnswerFor(plan: string, paths: Pick<QueuePaths, "queue_state">): { answer: string; at: number } | null {
131
131
  let lines: string[];
132
132
  try {
133
- lines = readFileSync(inboxPath(), "utf8").split("\n");
133
+ lines = readFileSync(inboxPath(paths), "utf8").split("\n");
134
134
  } catch {
135
135
  return null;
136
136
  }
@@ -199,7 +199,7 @@ export interface MachineRow {
199
199
 
200
200
  export function questionRows(cfg: Config, run?: HoldRunner): QuestionRow[] {
201
201
  const now = Date.now();
202
- const plans = activePlans(cfg.paths.queue_index);
202
+ const plans = activePlans(cfg.paths);
203
203
  const stale = staleFiles(recheckHolds(cfg, plans, run));
204
204
  return plans
205
205
  .filter(p => p.waiting && p.status === "open" && p.waitingLine && !stale.has(p.file))
@@ -219,7 +219,7 @@ export function questionRows(cfg: Config, run?: HoldRunner): QuestionRow[] {
219
219
  unblocks: plans.filter(o => o.status === "open" && o.file !== p.file && o.waitsOn.includes(p.file)).map(o => o.title),
220
220
  goal: p.goal,
221
221
  waitingMin,
222
- answered: lastAnswerFor(p.file),
222
+ answered: lastAnswerFor(p.file, cfg.paths),
223
223
  };
224
224
  });
225
225
  }
@@ -262,7 +262,7 @@ function queueState(p: Plan, plans: Plan[]): string {
262
262
  }
263
263
 
264
264
  export function queueRows(cfg: Config, views?: Map<string, TeamView | Unreachable>): QueueRow[] {
265
- const plans = activePlans(cfg.paths.queue_index).filter(p => p.status === "open");
265
+ const plans = activePlans(cfg.paths).filter(p => p.status === "open");
266
266
  const claims = summaryHolder(cfg, {}, views);
267
267
  return plans.map(p => {
268
268
  const holder = claims.holder(p.file);
@@ -446,14 +446,14 @@ export function nowStats(cfg: Config, source: RunSource, now: number): NowStats
446
446
  const byModel = [...models.entries()].map(([model, v]) => ({ model, spend: v.spend, runs: v.runs })).sort((a, b) => b.spend - a.spend);
447
447
  // The tile counts the open plans the queue card renders; a holder read here would ask every
448
448
  // team server a second time on a page that already read one view per team (P4).
449
- return { spend24, mainSpend, agentSpend, runs24, running, died, spendByHour, runsByHour, byModel, openPlans: activePlans(cfg.paths.queue_index).filter(p => p.status === "open").length };
449
+ return { spend24, mainSpend, agentSpend, runs24, running, died, spendByHour, runsByHour, byModel, openPlans: activePlans(cfg.paths).filter(p => p.status === "open").length };
450
450
  }
451
451
 
452
452
  // ---- owner messages (plan P13): a one-way note plus images, kept for 12 h ----
453
453
 
454
454
  /** Where the page stores owner messages: under the queue state dir, one dir per message. */
455
- function ownerMessagesDir(): string {
456
- return `${stateDirPath()}/owner-messages`;
455
+ function ownerMessagesDir(paths: Pick<QueuePaths, "queue_state">): string {
456
+ return `${paths.queue_state}/owner-messages`;
457
457
  }
458
458
 
459
459
  /** Main ids with a live running.lock in their main state dir (P5 multi-main): the page's picker list and the @-routing target set. */
@@ -521,25 +521,27 @@ const IMAGE_EXT: Record<string, string> = { png: "png", jpeg: "jpg", gif: "gif",
521
521
  const IMAGE_MIME: Record<string, string> = { png: "image/png", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp" };
522
522
 
523
523
  /** Removes every message dir older than the keep window; runs on every GET / and every POST /message. */
524
- export function sweepOwnerMessages(now: number): void {
524
+ export function sweepOwnerMessages(now: number, paths: Pick<QueuePaths, "queue_state">): void {
525
+ const dir = ownerMessagesDir(paths);
525
526
  let names: string[];
526
527
  try {
527
- names = readdirSync(ownerMessagesDir());
528
+ names = readdirSync(dir);
528
529
  } catch {
529
530
  return;
530
531
  }
531
532
  for (const name of names) {
532
533
  const ts = Number(name.slice(0, name.indexOf("-")));
533
534
  if (Number.isFinite(ts) && now - ts <= OWNER_MESSAGE_KEEP_SEC) continue;
534
- rmSync(`${ownerMessagesDir()}/${name}`, { recursive: true, force: true });
535
+ rmSync(`${dir}/${name}`, { recursive: true, force: true });
535
536
  }
536
537
  }
537
538
 
538
539
  /** The messages newer than the keep window for the "Sent today" list, newest first. A torn dir is skipped, not fatal. */
539
- export function recentOwnerMessages(now: number): MessageRow[] {
540
+ export function recentOwnerMessages(now: number, paths: Pick<QueuePaths, "queue_state">): MessageRow[] {
541
+ const dir = ownerMessagesDir(paths);
540
542
  let names: string[] = [];
541
543
  try {
542
- names = readdirSync(ownerMessagesDir());
544
+ names = readdirSync(dir);
543
545
  } catch {
544
546
  return [];
545
547
  }
@@ -548,7 +550,7 @@ export function recentOwnerMessages(now: number): MessageRow[] {
548
550
  const dirTs = Number(id.slice(0, id.indexOf("-")));
549
551
  if (!Number.isFinite(dirTs) || now - dirTs >= OWNER_MESSAGE_KEEP_SEC) continue;
550
552
  try {
551
- const meta = JSON.parse(readFileSync(`${ownerMessagesDir()}/${id}/message.json`, "utf8")) as Record<string, unknown>;
553
+ const meta = JSON.parse(readFileSync(`${dir}/${id}/message.json`, "utf8")) as Record<string, unknown>;
552
554
  rows.push({
553
555
  id,
554
556
  ts: Number(meta.ts) || dirTs,
@@ -910,7 +912,7 @@ function publishedRows(cfg: Config, host: string): PublishedPageRow[] {
910
912
 
911
913
  function lockMinutesLeft(cfg: Config): number | null {
912
914
  try {
913
- const end = statSync(unlockPath()).mtimeMs + cfg.guards.unlock_minutes * 60_000;
915
+ const end = statSync(cfg.paths.unlock).mtimeMs + cfg.guards.unlock_minutes * 60_000;
914
916
  const left = Math.round((end - Date.now()) / 60_000);
915
917
  return left > 0 ? left : null;
916
918
  } catch {
@@ -934,8 +936,8 @@ export function buildPageData(cfg: Config, source: RunSource, tab: string, build
934
936
  pages: safe(() => publishedRows(cfg, pagesHost)),
935
937
  stats: safe(() => nowStats(cfg, source, nowSec())),
936
938
  teams: views === null ? null : safe(() => teamSections(cfg, views)),
937
- results: tab === "results" ? safe(() => resultsView(nowSec(), build)) : undefined,
938
- messages: safe(() => recentOwnerMessages(nowSec())),
939
+ results: tab === "results" ? safe(() => resultsView(nowSec(), build, cfg.paths)) : undefined,
940
+ messages: safe(() => recentOwnerMessages(nowSec(), cfg.paths)),
939
941
  lockMinutesLeft: lockMinutesLeft(cfg),
940
942
  };
941
943
  }
@@ -1131,8 +1133,8 @@ const RESULTS_MAX_AGE_SEC = 3600;
1131
1133
  /** A build that failed or got killed is retried no sooner than this. */
1132
1134
  const RESULTS_RETRY_SEC = 600;
1133
1135
 
1134
- export function resultsCachePath(): string {
1135
- return `${stateDirPath()}/results-cache.json`;
1136
+ export function resultsCachePath(paths: Pick<QueuePaths, "queue_state">): string {
1137
+ return `${paths.queue_state}/results-cache.json`;
1136
1138
  }
1137
1139
 
1138
1140
  /**
@@ -1166,10 +1168,10 @@ let buildRunning = false;
1166
1168
  let lastBuildStart = 0;
1167
1169
 
1168
1170
  /** Reads the saved numbers and, when they are missing or stale, starts one build in the background. */
1169
- function resultsView(now: number, build: ResultsBuild): ResultsView {
1171
+ function resultsView(now: number, build: ResultsBuild, paths: Pick<QueuePaths, "queue_state">): ResultsView {
1170
1172
  let saved: { at: number; data: ResultsData } | null = null;
1171
1173
  try {
1172
- saved = JSON.parse(readFileSync(resultsCachePath(), "utf8"));
1174
+ saved = JSON.parse(readFileSync(resultsCachePath(paths), "utf8"));
1173
1175
  } catch {
1174
1176
  // No build has finished yet.
1175
1177
  }
@@ -1687,12 +1689,12 @@ const lastAnswerByPlan = new Map<string, { answer: string; ts: number }>();
1687
1689
  const DOUBLE_PRESS_SEC = 10;
1688
1690
 
1689
1691
  /** Appends the answer to the owner inbox unless this plan got the same trimmed answer in the last 10 s (P8c). */
1690
- function appendAnswer(plan: string, question: string, answer: string, login: string): void {
1692
+ function appendAnswer(plan: string, question: string, answer: string, login: string, paths: Pick<QueuePaths, "queue_state">): void {
1691
1693
  const now = nowSec();
1692
1694
  const last = lastAnswerByPlan.get(plan);
1693
1695
  if (last !== undefined && last.answer === answer && now - last.ts < DOUBLE_PRESS_SEC) return;
1694
- mkdirSync(stateDirPath(), { recursive: true });
1695
- appendFileSync(inboxPath(), `${JSON.stringify({ ts: now, plan, question, answer, login })}\n`);
1696
+ mkdirSync(paths.queue_state, { recursive: true });
1697
+ appendFileSync(inboxPath(paths), `${JSON.stringify({ ts: now, plan, question, answer, login })}\n`);
1696
1698
  lastAnswerByPlan.set(plan, { answer, ts: now });
1697
1699
  }
1698
1700
 
@@ -1704,15 +1706,15 @@ function handleAnswer(cfg: Config, source: RunSource, fields: Record<string, str
1704
1706
  // P4: a team plan is answered on its server, never in this machine's inbox; the branch sits
1705
1707
  // before the INDEX lookup, which knows only this machine's own plans.
1706
1708
  if ((fields.team ?? "").trim()) return handleTeamAnswer(cfg, fields, planFile, answer, wantsJson);
1707
- const plan = activePlans(cfg.paths.queue_index).find(p => p.file === planFile);
1709
+ const plan = activePlans(cfg.paths).find(p => p.file === planFile);
1708
1710
  if (!plan) return wantsJson ? jsonFail("plan is not open and waiting", 409) : textRes("plan is not open and waiting", 409);
1709
1711
  if (plan.status !== "open" || !plan.waiting || !plan.waitingLine) {
1710
1712
  // Stale answer (P8b): Main cleared the question before the answer arrived; pass it on anyway.
1711
- appendAnswer(planFile, "(already cleared)", answer, login);
1713
+ appendAnswer(planFile, "(already cleared)", answer, login, cfg.paths);
1712
1714
  if (wantsJson) return jsonSent("stale", receiptText("stale", new URLSearchParams()));
1713
1715
  return pageRes(cfg, source, new URLSearchParams({ sent: "stale" }), undefined, pagesHost);
1714
1716
  }
1715
- appendAnswer(planFile, plan.waitingLine, answer, login);
1717
+ appendAnswer(planFile, plan.waitingLine, answer, login, cfg.paths);
1716
1718
  if (wantsJson) return jsonSent("answer", receiptText("answer", new URLSearchParams()));
1717
1719
  return redirect(sentTo(fields.tab ?? "", "sent=answer"));
1718
1720
  }
@@ -1764,17 +1766,17 @@ function handleIncident(cfg: Config, fields: Record<string, string>, login: stri
1764
1766
  if (wantsJson) return jsonSent("incident-closed", receiptText("incident-closed", new URLSearchParams()));
1765
1767
  return redirect(sentTo(fields.tab ?? "", "sent=incident-closed"));
1766
1768
  }
1767
- storeOwnerMessage(`${id}: it's a bug — plan it`, login, [], "");
1769
+ storeOwnerMessage(`${id}: it's a bug — plan it`, login, [], "", cfg.paths);
1768
1770
  if (wantsJson) return jsonSent("incident-bug", receiptText("incident-bug", new URLSearchParams()));
1769
1771
  return redirect(sentTo(fields.tab ?? "", "sent=incident-bug"));
1770
1772
  }
1771
1773
 
1772
1774
  /** Stores an owner message (text and images) under a new id and inboxes it for Main (P13/P14). */
1773
- function storeOwnerMessage(text: string, login: string, images: { bytes: Uint8Array; kind: string }[], to: string): void {
1775
+ function storeOwnerMessage(text: string, login: string, images: { bytes: Uint8Array; kind: string }[], to: string, paths: Pick<QueuePaths, "queue_state">): void {
1774
1776
  const ts = nowSec();
1775
1777
  // The dir name starts with a whole-second ts: the sweep and the image route both parse it.
1776
1778
  const id = `${Math.floor(ts)}-${randomUUID().slice(0, 6)}`;
1777
- const dir = `${ownerMessagesDir()}/${id}`;
1779
+ const dir = `${ownerMessagesDir(paths)}/${id}`;
1778
1780
  mkdirSync(dir, { recursive: true });
1779
1781
  const names: string[] = [];
1780
1782
  for (let i = 0; i < images.length; i++) {
@@ -1783,15 +1785,15 @@ function storeOwnerMessage(text: string, login: string, images: { bytes: Uint8Ar
1783
1785
  names.push(name);
1784
1786
  }
1785
1787
  writeFileSync(`${dir}/message.json`, `${JSON.stringify({ ts, text, login, to, images: names })}\n`);
1786
- mkdirSync(stateDirPath(), { recursive: true });
1788
+ mkdirSync(paths.queue_state, { recursive: true });
1787
1789
  // The text stays out of owner-inbox.jsonl; Main reads message.json through the id (P14).
1788
- appendFileSync(inboxPath(), `${JSON.stringify({ ts, kind: "message", id, login, to })}\n`);
1790
+ appendFileSync(inboxPath(paths), `${JSON.stringify({ ts, kind: "message", id, login, to })}\n`);
1789
1791
  }
1790
1792
 
1791
1793
  // ---- POST /message (plan P13): the owner's one-way note plus images, inboxed by id ----
1792
1794
 
1793
1795
  async function handleMessage(req: Request, cfg: Config, login: string, wantsJson: boolean): Promise<Response> {
1794
- sweepOwnerMessages(nowSec());
1796
+ sweepOwnerMessages(nowSec(), cfg.paths);
1795
1797
  const form = await req.formData();
1796
1798
  let text = "";
1797
1799
  let toField = "";
@@ -1820,24 +1822,25 @@ async function handleMessage(req: Request, cfg: Config, login: string, wantsJson
1820
1822
  // P5: an `@<id>` prefix or the picker's to field names one Main; a stale name is refused before anything is stored.
1821
1823
  const pick = ownerMessageTarget(text, cfg, toField);
1822
1824
  if ("refuse" in pick) return fail(pick.refuse);
1823
- storeOwnerMessage(text, login, images, pick.to);
1825
+ storeOwnerMessage(text, login, images, pick.to, cfg.paths);
1824
1826
  if (wantsJson) return jsonSent("message", receiptText("message", new URLSearchParams()));
1825
1827
  return redirect("/?sent=message");
1826
1828
  }
1827
1829
 
1828
1830
  /** Serves one stored message image. Both path pieces are shape-checked and the name must be in message.json — raw input never reaches a path join. */
1829
- function handleMessageImage(id: string, file: string): Response {
1831
+ function handleMessageImage(id: string, file: string, paths: Pick<QueuePaths, "queue_state">): Response {
1830
1832
  if (!/^[0-9]+-[0-9a-f]{6}$/.test(id) || !/^[0-9]+\.(png|jpg|gif|webp)$/.test(file)) return textRes("not found", 404);
1833
+ const dir = ownerMessagesDir(paths);
1831
1834
  let meta: Record<string, unknown>;
1832
1835
  try {
1833
- meta = JSON.parse(readFileSync(`${ownerMessagesDir()}/${id}/message.json`, "utf8")) as Record<string, unknown>;
1836
+ meta = JSON.parse(readFileSync(`${dir}/${id}/message.json`, "utf8")) as Record<string, unknown>;
1834
1837
  } catch {
1835
1838
  return textRes("not found", 404);
1836
1839
  }
1837
1840
  const names = Array.isArray(meta.images) ? meta.images.filter((n): n is string => typeof n === "string") : [];
1838
1841
  if (!names.includes(file)) return textRes("not found", 404);
1839
1842
  try {
1840
- return new Response(readFileSync(`${ownerMessagesDir()}/${id}/${file}`), {
1843
+ return new Response(readFileSync(`${dir}/${id}/${file}`), {
1841
1844
  headers: { "content-type": IMAGE_MIME[file.slice(file.lastIndexOf(".") + 1)] ?? "application/octet-stream" },
1842
1845
  });
1843
1846
  } catch {
@@ -1850,9 +1853,9 @@ function handleUnlock(cfg: Config, fields: Record<string, string>, login: string
1850
1853
  if (minutes !== "" && !/^\d+$/.test(minutes)) return wantsJson ? jsonFail("minutes must be a number", 400) : textRes("minutes must be a number", 400);
1851
1854
  const result = chatUnlock(minutes === "" ? "unlock" : `unlock ${minutes}`, cfg, `ui:${login}`, "ui");
1852
1855
  if (!result.applied) return wantsJson ? jsonFail("Refused — chat unlock is off", 400) : redirect(sentTo(fields.tab ?? "", "sent=unlock-off"));
1853
- mkdirSync(stateDirPath(), { recursive: true });
1856
+ mkdirSync(cfg.paths.queue_state, { recursive: true });
1854
1857
  appendFileSync(
1855
- inboxPath(),
1858
+ inboxPath(cfg.paths),
1856
1859
  `${JSON.stringify({ ts: nowSec(), kind: "unlock", minutes: result.minutes, until: result.until, login })}\n`,
1857
1860
  );
1858
1861
  if (wantsJson) return jsonSent("unlock", receiptText("unlock", new URLSearchParams({ minutes: String(result.minutes) })));
@@ -1862,8 +1865,8 @@ function handleUnlock(cfg: Config, fields: Record<string, string>, login: string
1862
1865
  function handleLock(cfg: Config, fields: Record<string, string>, login: string, wantsJson: boolean): Response {
1863
1866
  const result = chatUnlock("lock", cfg, `ui:${login}`, "ui");
1864
1867
  if (!result.applied) return wantsJson ? jsonFail("Refused — chat unlock is off", 400) : redirect(sentTo(fields.tab ?? "", "sent=unlock-off"));
1865
- mkdirSync(stateDirPath(), { recursive: true });
1866
- appendFileSync(inboxPath(), `${JSON.stringify({ ts: nowSec(), kind: "lock", login })}\n`);
1868
+ mkdirSync(cfg.paths.queue_state, { recursive: true });
1869
+ appendFileSync(inboxPath(cfg.paths), `${JSON.stringify({ ts: nowSec(), kind: "lock", login })}\n`);
1867
1870
  if (wantsJson) return jsonSent("lock", receiptText("lock", new URLSearchParams()));
1868
1871
  return redirect(sentTo(fields.tab ?? "", "sent=lock"));
1869
1872
  }
@@ -1878,8 +1881,8 @@ function handleTier(cfg: Config, fields: Record<string, string>, login: string,
1878
1881
  if (!(TIERS as readonly string[]).includes(name)) return wantsJson ? jsonFail("tier must be strict, opinionated or full", 400) : textRes("tier must be strict, opinionated or full", 400);
1879
1882
  const result = chatTier(`tier ${name}`, cfg, `ui:${login}`, "ui");
1880
1883
  if (!result.applied) return wantsJson ? jsonFail("Refused — chat unlock is off", 400) : redirect(sentTo(fields.tab ?? "", "sent=unlock-off"));
1881
- mkdirSync(stateDirPath(), { recursive: true });
1882
- appendFileSync(inboxPath(), `${JSON.stringify({ ts: nowSec(), kind: "tier", tier: result.tier, login })}\n`);
1884
+ mkdirSync(cfg.paths.queue_state, { recursive: true });
1885
+ appendFileSync(inboxPath(cfg.paths), `${JSON.stringify({ ts: nowSec(), kind: "tier", tier: result.tier, login })}\n`);
1883
1886
  if (wantsJson) return jsonSent("tier");
1884
1887
  return redirect(sentTo(fields.tab ?? "", `sent=tier&tier=${result.tier}`));
1885
1888
  }
@@ -1960,7 +1963,7 @@ function handleReorder(cfg: Config, fields: Record<string, string>, login: strin
1960
1963
  const fail = (error: string, status: number): Response =>
1961
1964
  wantsJson ? Response.json({ ok: false, error }, { status }) : textRes(error, status);
1962
1965
  // One source of truth for the reorderable set: the open plans, the same list queueRows renders.
1963
- const openPlans = activePlans(index).filter(p => p.status === "open");
1966
+ const openPlans = activePlans(cfg.paths).filter(p => p.status === "open");
1964
1967
  const openPaths = openPlans.map(p => p.file);
1965
1968
  const openPlan: Record<string, Plan> = Object.fromEntries(openPlans.map(p => [p.file, p]));
1966
1969
  if (!moved || !order.length) return fail("order and moved are required", 400);
@@ -1986,8 +1989,8 @@ function handleReorder(cfg: Config, fields: Record<string, string>, login: strin
1986
1989
  // The queue library owns every index write (plan 20261031_0911 P2): a reorder is the same plan
1987
1990
  // set, so no removal reason, and the write lands temp+rename and leaves the file 0444.
1988
1991
  writeIndex(newText.trimEnd().split("\n"), undefined, index);
1989
- mkdirSync(stateDirPath(), { recursive: true });
1990
- appendFileSync(inboxPath(), `${JSON.stringify({ ts: nowSec(), kind: "reorder", plan: moved, from: from + 1, to: to + 1, login })}\n`);
1992
+ mkdirSync(cfg.paths.queue_state, { recursive: true });
1993
+ appendFileSync(inboxPath(cfg.paths), `${JSON.stringify({ ts: nowSec(), kind: "reorder", plan: moved, from: from + 1, to: to + 1, login })}\n`);
1991
1994
  if (wantsJson) return Response.json({ ok: true, to: to + 1 });
1992
1995
  return redirect(sentTo(fields.tab ?? "", `sent=reorder&to=${to + 1}`));
1993
1996
  }
@@ -2056,7 +2059,7 @@ export function startOwnerUi(opts: OwnerUiOptions): OwnerUiServer {
2056
2059
  res = textRes("forbidden: origin is not this page", 403);
2057
2060
  code = 403;
2058
2061
  } else if (req.method === "GET" && url.pathname === "/") {
2059
- sweepOwnerMessages(nowSec());
2062
+ sweepOwnerMessages(nowSec(), cfg.paths);
2060
2063
  res = pageRes(cfg, source, url.searchParams, resultsBuild, pagesHost);
2061
2064
  code = 200;
2062
2065
  } else if (req.method === "GET" && url.pathname.startsWith("/knowledge/")) {
@@ -2070,7 +2073,7 @@ res = pageRes(cfg, source, url.searchParams, resultsBuild, pagesHost);
2070
2073
  code = res.status;
2071
2074
  } else if (req.method === "GET" && url.pathname.startsWith("/message-image/")) {
2072
2075
  const mim = /^\/message-image\/([^/]+)\/([^/]+)$/.exec(url.pathname);
2073
- res = mim ? handleMessageImage(mim[1]!, mim[2]!) : textRes("not found", 404);
2076
+ res = mim ? handleMessageImage(mim[1]!, mim[2]!, cfg.paths) : textRes("not found", 404);
2074
2077
  code = res.status;
2075
2078
  } else if (req.method === "POST") {
2076
2079
  // The page's script asks for JSON on every POST (P11b); a no-JS form post gets today's 303s.
package/src/core/pages.ts CHANGED
@@ -5,7 +5,6 @@ import { isLoopback, isTailnet, inboxPath, type UiHttpServer } from "./owner-ui.
5
5
  import { nowSec } from "./clock.ts";
6
6
  import { appendPageNotes, openNoteIds } from "./page-notes.ts";
7
7
  import { approvePlanFile, readPagePlan } from "./plan-approval.ts";
8
- import { stateDirPath } from "./queue/lib.ts";
9
8
  import type { RunSource } from "./adapter.ts";
10
9
  import type { Tailscale } from "./tailscale.ts";
11
10
 
@@ -44,11 +43,11 @@ export function startPagesServer(opts: PagesOptions): PagesServer {
44
43
  const plan = record.plan;
45
44
  if (!existsSync(plan)) return plain("not found: the plan file is gone", 404);
46
45
  try {
47
- const approved = approvePlanFile(plan, page);
46
+ const approved = approvePlanFile(plan, page, opts.cfg.paths);
48
47
  // P5 (plan 20261031_0917): the tap must reach Main at once — one owner-inbox row, the same
49
48
  // direct append the message POST uses; never a page note, which would 409 the next tap.
50
- mkdirSync(stateDirPath(), { recursive: true });
51
- appendFileSync(inboxPath(), `${JSON.stringify({ ts: nowSec(), kind: "approval", page, plan, login })}\n`);
49
+ mkdirSync(opts.cfg.paths.queue_state, { recursive: true });
50
+ appendFileSync(inboxPath(opts.cfg.paths), `${JSON.stringify({ ts: nowSec(), kind: "approval", page, plan, login })}\n`);
52
51
  return Response.json({ approved });
53
52
  } catch (e) {
54
53
  return plain(`not approved: ${e instanceof Error ? e.message : String(e)}`, 500);
@@ -83,44 +83,44 @@ export interface PlanApproval {
83
83
  page: string;
84
84
  }
85
85
 
86
- function planApprovalsFile(): string {
87
- return join(q.STATE_DIR, "plan-approvals.json");
86
+ function planApprovalsFile(paths: Pick<q.QueuePaths, "queue_state">): string {
87
+ return join(paths.queue_state, "plan-approvals.json");
88
88
  }
89
89
 
90
- function readPlanApprovals(): Record<string, PlanApproval> {
90
+ function readPlanApprovals(paths: Pick<q.QueuePaths, "queue_state">): Record<string, PlanApproval> {
91
91
  try {
92
- const parsed = JSON.parse(readFileSync(planApprovalsFile(), "utf8"));
92
+ const parsed = JSON.parse(readFileSync(planApprovalsFile(paths), "utf8"));
93
93
  if (parsed?.approvals && typeof parsed.approvals === "object") return parsed.approvals as Record<string, PlanApproval>;
94
94
  } catch {
95
95
  }
96
96
  return {};
97
97
  }
98
98
 
99
- function writePlanApprovals(approvals: Record<string, PlanApproval>): boolean {
99
+ function writePlanApprovals(approvals: Record<string, PlanApproval>, paths: Pick<q.QueuePaths, "queue_state">): boolean {
100
100
  try {
101
- mkdirSync(q.STATE_DIR, { recursive: true });
102
- writeFileSync(planApprovalsFile(), JSON.stringify({ approvals }, null, 1));
101
+ mkdirSync(paths.queue_state, { recursive: true });
102
+ writeFileSync(planApprovalsFile(paths), JSON.stringify({ approvals }, null, 1));
103
103
  return true;
104
104
  } catch {
105
105
  return false;
106
106
  }
107
107
  }
108
108
 
109
- function readPlanApproval(file: string): PlanApproval | null {
110
- return readPlanApprovals()[file] ?? null;
109
+ function readPlanApproval(file: string, paths: Pick<q.QueuePaths, "queue_state">): PlanApproval | null {
110
+ return readPlanApprovals(paths)[file] ?? null;
111
111
  }
112
112
 
113
113
  /** Record one approval. Throws when the queue state cannot be written, so nobody reports "approved" for a record that is not there. */
114
- function recordApproval(file: string, approval: PlanApproval): void {
115
- const approvals = readPlanApprovals();
114
+ function recordApproval(file: string, approval: PlanApproval, paths: Pick<q.QueuePaths, "queue_state">): void {
115
+ const approvals = readPlanApprovals(paths);
116
116
  approvals[file] = approval;
117
- if (!writePlanApprovals(approvals)) throw new Error(`cannot write ${planApprovalsFile()}`);
117
+ if (!writePlanApprovals(approvals, paths)) throw new Error(`cannot write ${planApprovalsFile(paths)}`);
118
118
  }
119
119
 
120
120
  /** The owner's click on a plan page: record a hash of the plan text in the queue state and return the page it approved. The plan file itself is never edited. */
121
- export function approvePlanFile(file: string, page: string, now = new Date()): string {
121
+ export function approvePlanFile(file: string, page: string, paths: Pick<q.QueuePaths, "queue_state">, now = new Date()): string {
122
122
  const text = readFileSync(file, "utf8");
123
- recordApproval(file, { hash: reviewHash(text), at: now.getTime(), via: "page", page });
123
+ recordApproval(file, { hash: reviewHash(text), at: now.getTime(), via: "page", page }, paths);
124
124
  return `approved ${page}`;
125
125
  }
126
126
 
@@ -139,12 +139,12 @@ export function chatApprove(text: string, cfg: Config, source: string): ChatAppr
139
139
  const m = APPROVE_CMD.exec(text.trim());
140
140
  if (!m) return { applied: false };
141
141
  const stamp = m[1];
142
- const matches = q.activePlans().filter(p => p.status === "open" && basename(p.file).startsWith(`${stamp}_`));
142
+ const matches = q.activePlans(cfg.paths).filter(p => p.status === "open" && basename(p.file).startsWith(`${stamp}_`));
143
143
  const [plan, second] = matches;
144
144
  if (!plan) return { applied: false, problem: `no open plan ${stamp}` };
145
145
  if (second) return { applied: false, problem: `${matches.length} open plans match ${stamp}; nothing approved` };
146
146
  try {
147
- recordApproval(plan.file, { hash: reviewHash(plan.text), at: Date.now(), via: "chat", page: pageOfPlan(cfg.pages.dir, plan.file) ?? "" });
147
+ recordApproval(plan.file, { hash: reviewHash(plan.text), at: Date.now(), via: "chat", page: pageOfPlan(cfg.pages.dir, plan.file) ?? "" }, cfg.paths);
148
148
  } catch (e) {
149
149
  return { applied: false, problem: `plan ${stamp} not approved: ${e instanceof Error ? e.message : String(e)}` };
150
150
  }
@@ -155,7 +155,7 @@ export function chatApprove(text: string, cfg: Config, source: string): ChatAppr
155
155
  }
156
156
 
157
157
  /** Why a spawn may not run on this plan, or null. Approval off (`since === ""`) approves everything, page or not (plan 20261031_1207 P5: the reviewer agent replaced the hard gate). Otherwise a plan with a page in Base needs a record with its current hash, and a plan stamped at or after `since` needs a page too (plan 20261029_1455 P3): with no page it is refused until the page is published. A file with no stamp counts as stamped after `since`. */
158
- export function approvalProblem(text: string, file: string, pagesDir: string, since: string): string | null {
158
+ export function approvalProblem(text: string, file: string, pagesDir: string, since: string, paths: Pick<q.QueuePaths, "queue_state">): string | null {
159
159
  if (since === "") return null;
160
160
  const page = pageOfPlan(pagesDir, file);
161
161
  const stamp = /^\d{8}_\d{4}/.exec(basename(file))?.[0] ?? null;
@@ -164,7 +164,7 @@ export function approvalProblem(text: string, file: string, pagesDir: string, si
164
164
  if (!gated) return null; // predates the convention
165
165
  return `plan ${file} has no page: publish its page with neurastream pages publish <page.html> --plan ${file}`;
166
166
  }
167
- const rec = readPlanApproval(file);
167
+ const rec = readPlanApproval(file, paths);
168
168
  if (rec !== null && rec.hash === reviewHash(text)) return null;
169
169
  const hint = stamp !== null ? `, or types: approve ${stamp}` : "";
170
170
  return `plan ${file} has no approval record. The owner approves it from ${page} in Base${hint}.`;