neurastream 0.2.52 → 0.2.54

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.52",
3
+ "version": "0.2.54",
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",
@@ -0,0 +1,19 @@
1
+ // The owner page's Results build, run as its own process by spawnResultsBuild (src/core/owner-ui.ts):
2
+ // it parses months of sessions (over a minute, GBs of memory), which froze the page when the server
3
+ // did it itself (I-20261030-121). Writes the numbers to resultsCachePath(); the page only reads them.
4
+
5
+ import { renameSync, writeFileSync } from "node:fs";
6
+ import { getAdapter } from "../adapters/index.ts";
7
+ import { nowSec } from "../core/clock.ts";
8
+ import { loadConfig } from "../core/config.ts";
9
+ import { computeResults, resultsCachePath } from "../core/owner-ui.ts";
10
+ import { applyQueueEnv } from "../core/queue/env.ts";
11
+
12
+ const cfg = loadConfig();
13
+ applyQueueEnv(cfg);
14
+ const at = nowSec();
15
+ const data = computeResults(cfg, getAdapter(cfg).runSource(cfg), at);
16
+ const path = resultsCachePath();
17
+ // Write then rename: the page never reads a half-written file.
18
+ writeFileSync(`${path}.tmp`, JSON.stringify({ at, data }));
19
+ renameSync(`${path}.tmp`, path);
@@ -82,6 +82,8 @@ interface EditWindow {
82
82
  windowStart: number;
83
83
  /** Main tool calls since the last owner prompt or terminal hand-back (main_call_exempt_tools never count). */
84
84
  mainCalls: number;
85
+ /** When the first of those calls was counted; the count expires MAIN_CALLS_RESET_SEC later. */
86
+ mainCallsStart?: number;
85
87
  }
86
88
 
87
89
  function windowFile(): string {
@@ -92,7 +94,7 @@ export function readWindow(): EditWindow {
92
94
  try {
93
95
  const w = JSON.parse(readFileSync(windowFile(), "utf8")) as Partial<EditWindow>;
94
96
  if (Array.isArray(w.used) && typeof w.windowStart === "number")
95
- return { used: w.used, windowStart: w.windowStart, mainCalls: typeof w.mainCalls === "number" ? w.mainCalls : 0 };
97
+ return { used: w.used, windowStart: w.windowStart, mainCalls: typeof w.mainCalls === "number" ? w.mainCalls : 0, mainCallsStart: typeof w.mainCallsStart === "number" ? w.mainCallsStart : 0 };
96
98
  } catch {}
97
99
  return { used: [], windowStart: 0, mainCalls: 0 };
98
100
  }
@@ -1168,12 +1170,23 @@ function mainCallApplies(e: ToolEvent, cfg: Config): boolean {
1168
1170
  return cfg.guards.main_max_calls > 0 && currentTier(cfg) !== "full" && !cfg.guards.main_call_exempt_tools.includes(e.tool);
1169
1171
  }
1170
1172
 
1173
+ /**
1174
+ * A count older than this starts over, even with no owner message or hand-back: a blocked stop is
1175
+ * a continuation, not a hand-back, so without it a capped Main with no owner awake stays refused
1176
+ * all night.
1177
+ */
1178
+ const MAIN_CALLS_RESET_SEC = 15 * 60;
1179
+
1180
+ function mainCallsExpired(w: EditWindow): boolean {
1181
+ return w.mainCalls > 0 && nowSec() - (w.mainCallsStart ?? 0) >= MAIN_CALLS_RESET_SEC;
1182
+ }
1183
+
1171
1184
  /** Refusal once this turn has spent main_max_calls, or null. */
1172
1185
  function mainCallStop(e: ToolEvent, cfg: Config): string | null {
1173
1186
  if (!mainCallApplies(e, cfg)) return null;
1174
1187
  const w = readWindow();
1175
- if (w.mainCalls >= cfg.guards.main_max_calls)
1176
- return `main-guard: call ${w.mainCalls}/${cfg.guards.main_max_calls} since the owner's last message or your last hand-back (guards.main_max_calls). End your turn with the answer, or spawn an implementer.`;
1188
+ if (w.mainCalls >= cfg.guards.main_max_calls && !mainCallsExpired(w))
1189
+ return `main-guard: call ${w.mainCalls}/${cfg.guards.main_max_calls} since the owner's last message or your last hand-back (guards.main_max_calls); the count starts over ${Math.ceil((MAIN_CALLS_RESET_SEC - (nowSec() - (w.mainCallsStart ?? 0))) / 60)} min from now. End your turn with the answer, or spawn an implementer.`;
1177
1190
  return null;
1178
1191
  }
1179
1192
 
@@ -1181,6 +1194,10 @@ function mainCallStop(e: ToolEvent, cfg: Config): string | null {
1181
1194
  function mainCallWarn(e: ToolEvent, cfg: Config): string {
1182
1195
  if (!mainCallApplies(e, cfg)) return "";
1183
1196
  const w = readWindow();
1197
+ if (w.mainCalls === 0 || mainCallsExpired(w)) {
1198
+ w.mainCalls = 0;
1199
+ w.mainCallsStart = nowSec();
1200
+ }
1184
1201
  w.mainCalls += 1;
1185
1202
  writeWindow(w);
1186
1203
  if (w.mainCalls >= cfg.guards.main_warn_calls)
@@ -58,6 +58,8 @@ export interface OwnerUiOptions {
58
58
  port?: number;
59
59
  /** The peer address of a request. Default: the socket address. Tests inject fixture peers. */
60
60
  peerOf?: (req: Request, server: UiHttpServer) => string;
61
+ /** Starts a background Results build. Default: spawnResultsBuild. Tests inject a recorder. */
62
+ resultsBuild?: ResultsBuild;
61
63
  }
62
64
 
63
65
  export type Auth = { ok: true; login: string } | { ok: false; why: string };
@@ -748,8 +750,8 @@ export interface PageData {
748
750
  knowledge: KnowledgeEntry[] | null;
749
751
  /** The 24 h tile numbers; null when the run source is unreadable. */
750
752
  stats: NowStats | null;
751
- /** The Results tab's ledger and release windows; null when unreadable, absent in hand-built PageData. */
752
- results?: ResultsData | null;
753
+ /** 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. */
754
+ results?: ResultsView | null;
753
755
  /** The owner's messages newer than the keep window, newest first; null when unreadable. */
754
756
  messages: MessageRow[] | null;
755
757
  /** Minutes left in the guard unlock; null = locked. */
@@ -775,7 +777,7 @@ function lockMinutesLeft(cfg: Config): number | null {
775
777
  }
776
778
  }
777
779
 
778
- export function buildPageData(cfg: Config, source: RunSource): PageData {
780
+ export function buildPageData(cfg: Config, source: RunSource, tab: string, build: ResultsBuild = spawnResultsBuild): PageData {
779
781
  return {
780
782
  questions: safe(() => questionRows(cfg)),
781
783
  agents: safe(() => agentRows(cfg, source)),
@@ -786,7 +788,7 @@ export function buildPageData(cfg: Config, source: RunSource): PageData {
786
788
  machine: safe(() => machineRow(cfg)),
787
789
  knowledge: safe(() => knowledgeManifest(cfg)),
788
790
  stats: safe(() => nowStats(cfg, source, nowSec())),
789
- results: safe(() => resultsData(cfg, source)),
791
+ results: tab === "results" ? safe(() => resultsView(nowSec(), build)) : undefined,
790
792
  messages: safe(() => recentOwnerMessages(nowSec())),
791
793
  lockMinutesLeft: lockMinutesLeft(cfg),
792
794
  };
@@ -959,17 +961,28 @@ export interface ResultsData {
959
961
  releases: ReleasesReport;
960
962
  }
961
963
 
962
- let resultsCache: { at: number; data: ResultsData } | null = null;
964
+ /** The tab as the page sees it: the last saved numbers (if any), when they were saved, and whether a build runs now. */
965
+ export interface ResultsView {
966
+ data: ResultsData | null;
967
+ at: number | null;
968
+ building: boolean;
969
+ }
970
+
971
+ /** Saved numbers older than this start a fresh background build. */
972
+ const RESULTS_MAX_AGE_SEC = 3600;
973
+ /** A build that failed or got killed is retried no sooner than this. */
974
+ const RESULTS_RETRY_SEC = 600;
975
+
976
+ export function resultsCachePath(): string {
977
+ return `${stateDirPath()}/results-cache.json`;
978
+ }
963
979
 
964
980
  /**
965
- * The tab's data from the P2/P3 functions, computed once per build (the chart and the table read
966
- * the same object, like the Spend tile and its table). Cached for a minute: a release's before
967
- * window reaches back past the features window, so one build can parse months of sessions while
968
- * the page refetches every ${REFRESH_SEC} s.
981
+ * The tab's numbers from the P2/P3 functions. A release's before window reaches back months, so
982
+ * one build parses GBs of sessions for over a minute: it runs only in the separate process
983
+ * src/cli/results-build.ts, never in the server, which it froze (I-20261030-121).
969
984
  */
970
- function resultsData(cfg: Config, source: RunSource): ResultsData {
971
- const now = nowSec();
972
- if (resultsCache && now - resultsCache.at < 60) return resultsCache.data;
985
+ export function computeResults(cfg: Config, source: RunSource, now: number): ResultsData {
973
986
  const days = 7;
974
987
  const selfRepo = gitTop(import.meta.dir)?.repo ?? null;
975
988
  const tags = gatherTags(selfRepo);
@@ -977,12 +990,39 @@ function resultsData(cfg: Config, source: RunSource): ResultsData {
977
990
  const oldest = Math.min(now, ...tags.map(t => t.ts), ...events.filter(e => e.type === "ci").map(e => Number(e.ts)));
978
991
  const runs = source.listRuns(oldest - days * 86400);
979
992
  const plans = loadPlans(cfg);
980
- const data: ResultsData = {
993
+ return {
981
994
  features: featuresReport(runs, plans, selfRepo, now - cfg.metrics.report_days * 86400, now),
982
995
  releases: releasesReport(runs, plans, selfRepo, days, now, tags, events),
983
996
  };
984
- resultsCache = { at: now, data };
985
- return data;
997
+ }
998
+
999
+ /** Starts one background build; calls `done` when it exits, whatever the outcome. */
1000
+ export type ResultsBuild = (done: () => void) => void;
1001
+
1002
+ export const spawnResultsBuild: ResultsBuild = done => {
1003
+ const proc = Bun.spawn(["nice", "-n", "19", process.execPath, `${import.meta.dir}/../cli/results-build.ts`], { stdout: "ignore", stderr: "inherit" });
1004
+ void proc.exited.then(done, done);
1005
+ };
1006
+
1007
+ let buildRunning = false;
1008
+ let lastBuildStart = 0;
1009
+
1010
+ /** Reads the saved numbers and, when they are missing or stale, starts one build in the background. */
1011
+ function resultsView(now: number, build: ResultsBuild): ResultsView {
1012
+ let saved: { at: number; data: ResultsData } | null = null;
1013
+ try {
1014
+ saved = JSON.parse(readFileSync(resultsCachePath(), "utf8"));
1015
+ } catch {
1016
+ // No build has finished yet.
1017
+ }
1018
+ if ((!saved || now - saved.at >= RESULTS_MAX_AGE_SEC) && !buildRunning && now - lastBuildStart >= RESULTS_RETRY_SEC) {
1019
+ buildRunning = true;
1020
+ lastBuildStart = now;
1021
+ build(() => {
1022
+ buildRunning = false;
1023
+ });
1024
+ }
1025
+ return { data: saved?.data ?? null, at: saved?.at ?? null, building: buildRunning };
986
1026
  }
987
1027
 
988
1028
  /** One y axis choice: where the number sits on a release side and which way is better. */
@@ -1143,8 +1183,12 @@ function resultsTable(releases: ReleasesReport, all: YMetric[]): string {
1143
1183
 
1144
1184
  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.";
1145
1185
 
1146
- function resultsTabHtml(d: ResultsData | null | undefined, params: URLSearchParams): string {
1147
- if (!d) return `<h1>Results</h1>${na("Results")}`;
1186
+ function resultsTabHtml(view: ResultsView | null | undefined, params: URLSearchParams): string {
1187
+ const d = view?.data;
1188
+ if (!d) {
1189
+ 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>`;
1190
+ return `<h1>Results</h1>${na("Results")}`;
1191
+ }
1148
1192
  if (!d.releases.rows.length) {
1149
1193
  const empty = d.features.rows.length ? "No releases recorded yet" : "No finished features yet";
1150
1194
  return `<h1>Results</h1><div class="card"><p class="empty">${empty}</p></div><p class="sub">${RESULTS_CAVEAT}</p>`;
@@ -1154,7 +1198,7 @@ function resultsTabHtml(d: ResultsData | null | undefined, params: URLSearchPara
1154
1198
  // An unknown y falls back to $/feature.
1155
1199
  const y = all.find(m => m.key === params.get("y")) ?? all[0]!;
1156
1200
  return `<h1>Results</h1>
1157
- <p class="sub">What features cost and whether releases made it better or worse.</p>
1201
+ <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>
1158
1202
  <div class="card">
1159
1203
  ${resultsControls(all, y, x)}
1160
1204
  ${resultsChart(d.releases, y, x)}
@@ -1390,9 +1434,9 @@ function sentTo(tab: string, sent: string): string {
1390
1434
  }
1391
1435
 
1392
1436
  /** The normal page (the GET layout) as a POST reply; the stale-answer reply is this with sent=stale. */
1393
- function pageRes(cfg: Config, source: RunSource, params: URLSearchParams): Response {
1437
+ function pageRes(cfg: Config, source: RunSource, params: URLSearchParams, build: ResultsBuild = spawnResultsBuild): Response {
1394
1438
  const nonce = randomUUID().replaceAll("-", "");
1395
- return new Response(renderPage(cfg, buildPageData(cfg, source), params, nonce), {
1439
+ return new Response(renderPage(cfg, buildPageData(cfg, source, params.get("tab") ?? "", build), params, nonce), {
1396
1440
  status: 200,
1397
1441
  headers: {
1398
1442
  "content-type": "text/html; charset=utf-8",
@@ -1677,6 +1721,7 @@ function handleReorder(cfg: Config, fields: Record<string, string>, login: strin
1677
1721
  /** Starts the page. Refuses to start when ui.enabled is false or ui.owner_login is empty, and on the default hostname when tailscale does not answer. */
1678
1722
  export function startOwnerUi(opts: OwnerUiOptions): OwnerUiServer {
1679
1723
  const { cfg, tailscale, source } = opts;
1724
+ const resultsBuild = opts.resultsBuild ?? spawnResultsBuild;
1680
1725
  // The double-press guard (P8c) is per-server memory: a fresh server starts empty, which also
1681
1726
  // keeps the tests (one server per test) hermetic.
1682
1727
  lastAnswerByPlan.clear();
@@ -1725,7 +1770,7 @@ export function startOwnerUi(opts: OwnerUiOptions): OwnerUiServer {
1725
1770
  code = 403;
1726
1771
  } else if (req.method === "GET" && url.pathname === "/") {
1727
1772
  sweepOwnerMessages(nowSec());
1728
- res = pageRes(cfg, source, url.searchParams);
1773
+ res = pageRes(cfg, source, url.searchParams, resultsBuild);
1729
1774
  code = 200;
1730
1775
  } else if (req.method === "GET" && url.pathname.startsWith("/knowledge/")) {
1731
1776
  // The Knowledge tab's frame: the topic's own file bytes, GET only, no write path.