neurastream 0.2.64 → 0.2.66

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.
@@ -6,6 +6,8 @@ import { accessSync, appendFileSync, chmodSync, constants, existsSync, mkdirSync
6
6
  import os from "node:os";
7
7
  import path from "node:path";
8
8
  import type { Config } from "../config.ts";
9
+ import type { ClaimStore } from "../claims.ts";
10
+ import { strftime } from "../clock.ts";
9
11
 
10
12
  // --- landing detection (plan 20261031_0911 P4/P5): lives here, not queue-close.ts, because
11
13
  // queueProblems' landed lock needs it and lib must not import the closer that imports lib ---
@@ -927,7 +929,7 @@ const STOP = new Set(
927
929
  );
928
930
  function keyWords(text: string): string[] {
929
931
  const words = text.toLowerCase().match(/[a-z0-9][a-z0-9_.-]{3,}/g) ?? [];
930
- return [...new Set(words.map(w => w.replace(/[._-]+$/, "")).filter(w => w.length >= 4 && !STOP.has(w)))].sort();
932
+ return [...new Set(words.map(w => w.replace(/[._-]+$/, "")).filter(w => w.length >= 4 && !STOP.has(w)))].toSorted();
931
933
  }
932
934
  export function planWords(text: string): string[] {
933
935
  const title = text.match(/^# (.+)$/m)?.[1] ?? "";
@@ -1142,6 +1144,12 @@ export function queueProblems(index = INDEX, blockersDir = BLOCKERS_DIR, reviewA
1142
1144
  return probs;
1143
1145
  }
1144
1146
 
1147
+ /** Queue ranks of the open queue plans an open plan waits on (I-20261025-208); empty when it is free to start. */
1148
+ export function openWaits(p: Plan, plans: Plan[], rank: Map<string, number>): number[] {
1149
+ if (p.status !== "open") return [];
1150
+ return p.waitsOn.map(f => rank.get(f)).filter((at): at is number => at !== undefined && plans[at - 1]!.status === "open");
1151
+ }
1152
+
1145
1153
  // P4 (plan 20261027_0915): from this day on, a Progress entry claiming a phase done/complete/
1146
1154
  // "nothing left"/"finished" must quote that phase's verify command (or the Done check) and its
1147
1155
  // result, or queue-check fails the plan; entries without a date or dated before it are grandfathered.
@@ -1203,17 +1211,24 @@ export function holdWarnings(plans: Plan[]): string[] {
1203
1211
  // and passes `cap = Infinity`.
1204
1212
  export const SUMMARY_CAP = 10;
1205
1213
 
1206
- export function queueSummary(index = INDEX, reviewAgents: string[] = [], stale: ReadonlySet<string> = new Set(), cap: number = SUMMARY_CAP): string {
1214
+ export function queueSummary(index = INDEX, reviewAgents: string[] = [], staleOrClaims: ReadonlySet<string> | ClaimStore | null = null, cap: number = SUMMARY_CAP): string {
1207
1215
  // Index order IS priority (20261025_0215_index_priority): the list is flat and ranked,
1208
1216
  // rank 1 = the index's top line; repos only surface through each plan's own path.
1209
1217
  const plans = activePlans(index);
1210
1218
  const rank = new Map(plans.map((p, i) => [p.file, i + 1] as const));
1211
1219
  const repos = [...new Set(plans.map(p => p.repo))];
1212
1220
  const lines = [`Queue (${index}): ${plans.length ? `${plans.length} plan(s) in ${repos.length} repo(s)` : "empty, no open work"}`];
1221
+ let claimStore: ClaimStore | null = null;
1222
+ let stale: ReadonlySet<string> = new Set<string>();
1223
+ if (staleOrClaims != null && typeof (staleOrClaims as ClaimStore).holder === 'function') {
1224
+ claimStore = staleOrClaims as ClaimStore;
1225
+ } else {
1226
+ stale = staleOrClaims as ReadonlySet<string> ?? new Set<string>();
1227
+ }
1213
1228
  plans.slice(0, cap).forEach((p, i) => {
1214
1229
  const status = awaitingMerge(p) ? "complete, awaiting merge" : (p.status ?? "INVALID");
1215
1230
  const ask = (p.waitingLine ?? "").slice(0, 80);
1216
- const hold = p.waiting ? (stale.has(p.file) ? `[STALE?] ${ask}` : `WAITING on owner: ${ask}`) : "";
1231
+ const hold = p.waiting ? (stale?.has(p.file) ? `[STALE?] ${ask}` : `WAITING on owner: ${ask}`) : "";
1217
1232
  // I-20261025-208: an open plan waiting on an open plan of the queue shows the target's rank.
1218
1233
  const waits: string[] = [];
1219
1234
  if (p.status === "open")
@@ -1223,7 +1238,11 @@ export function queueSummary(index = INDEX, reviewAgents: string[] = [], stale:
1223
1238
  waits.push(`waits on #${at}`);
1224
1239
  }
1225
1240
  const done = p.phases.total ? `${p.phases.done}/${p.phases.total} done` : "";
1226
- const flags = [status, done, hold, ...waits, p.priorityId ?? ""].filter(Boolean).join(", ");
1241
+ // P4 multi-main (20261027_1300): with the claim store handed in (guards' inject and
1242
+ // queue-check pass it), every plan shows `held by <id> since HH:MM` or `free`.
1243
+ const holder = claimStore?.holder(p.file) ?? null;
1244
+ const claimFlag = claimStore ? (holder ? `held by ${holder.main} since ${strftime(holder.since, "%H:%M")}` : "free") : "";
1245
+ const flags = [status, done, hold, ...waits, claimFlag, p.priorityId ?? ""].filter(Boolean).join(", ");
1227
1246
  const goal = items(sections(p.text).get("goal") ?? "")[0]?.slice(0, 100) ?? "";
1228
1247
  lines.push(` ${i + 1}. ${p.file} [${flags}] ${goal}`);
1229
1248
  });
@@ -1,8 +1,10 @@
1
1
  import type { Config } from "./config.ts";
2
+ import { fileClaimStore } from "./claims.ts";
3
+ import { nowSec } from "./clock.ts";
2
4
  import { applyQueueEnv } from "./queue/env.ts";
3
5
  import { activePlans, allowedAgents, holdWarnings, queueProblems, queueSummary, reviewAgentsProblem } from "./queue/lib.ts";
4
6
  import { mrSweep } from "./mr-sweep.ts";
5
- import { recheckHolds, staleFiles, staleHoldLines } from "./waiting-check.ts";
7
+ import { recheckHolds, staleHoldLines } from "./waiting-check.ts";
6
8
 
7
9
  // One index (20261024_1400_one_index): the main index lists plan files directly, so there are no
8
10
  // repo INDEX.md files to git-check and no work_roots scan; the queue problems carry the
@@ -13,9 +15,10 @@ export function queueCheck(args: string[], cfg: Config): number {
13
15
  for (const p of activePlans()) if (p.priorityId && !p.waiting && p.status === "open") console.log(p.priorityId);
14
16
  return 0;
15
17
  }
18
+ const claims = fileClaimStore(cfg.paths.queue_state, nowSec, cfg.queue.claim_ttl_min);
16
19
  const plans = activePlans();
17
20
  const holds = recheckHolds(cfg, plans);
18
- console.log(queueSummary(undefined, cfg.review.agents, staleFiles(holds), Infinity));
21
+ console.log(queueSummary(undefined, cfg.review.agents, claims, Infinity));
19
22
  for (const line of staleHoldLines(holds, plans)) console.log(line);
20
23
  // main-start prints the sweep itself and passes this so the child bin does not print it twice.
21
24
  let fail = queueProblems(undefined, undefined, cfg.review.agents).length > 0;
@@ -2,7 +2,10 @@ import { spawnSync } from "node:child_process";
2
2
  import { appendFileSync, existsSync, fstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
+ import { fileClaimStore } from "./claims.ts";
6
+ import { nowSec } from "./clock.ts";
5
7
  import type { Config } from "./config.ts";
8
+ import { mainId } from "./guards.ts";
6
9
  import { applyQueueEnv } from "./queue/env.ts";
7
10
  import { activePlans, cancelledFile, cancelledLine, closeLog, finishedEntry, finishedPath, gitOut as git, INDEX, landed, prependFinished, sha, STATE_DIR, writeIndex } from "./queue/lib.ts";
8
11
  import { fixedIncident } from "./incidents.ts";
@@ -316,6 +319,9 @@ export function queueClose(args: string[], cfg: Config): number {
316
319
  }
317
320
  if (recorded.length) console.log(`queue-close: recorded fixed for ${recorded.join(", ")}`);
318
321
  }
322
+ // Multi-main P3: closing the plan frees this Main's claim; another Main's claim stays
323
+ // (release is keyed by the holder).
324
+ fileClaimStore(cfg.paths.queue_state, nowSec, cfg.queue.claim_ttl_min).release(file, mainId());
319
325
  console.log("queue-close: CLOSED");
320
326
  return 0;
321
327
  }
@@ -5,8 +5,8 @@
5
5
  // the jobs and the note mtime, and performs the switch. No harness names here.
6
6
 
7
7
  import { join } from "node:path";
8
+ import { mainStateDir } from "./guards.ts";
8
9
  import { strftime } from "./clock.ts";
9
- import { stateDirPath } from "./queue/lib.ts";
10
10
  import type { OwnerAnswer, OwnerMessage } from "./incidents.ts";
11
11
 
12
12
  export type RolloverState = "below" | "need-note" | "wait-jobs" | "ready";
@@ -167,11 +167,11 @@ export function noteRequest(path: string, reason = ""): string {
167
167
  }
168
168
 
169
169
  /** Where Main writes the handoff note for one session. */
170
- export function notePath(sessionId: string, stateDir = stateDirPath()): string {
170
+ export function notePath(sessionId: string, stateDir = mainStateDir()): string {
171
171
  return join(stateDir, "rollover", `${sessionId}.md`);
172
172
  }
173
173
 
174
174
  /** The launcher's relaunch request file: written by the harness just before it exits under `neurastream main`. */
175
- export function relaunchPath(stateDir = stateDirPath()): string {
175
+ export function relaunchPath(stateDir = mainStateDir()): string {
176
176
  return join(stateDir, "rollover", "relaunch.json");
177
177
  }
@@ -0,0 +1,120 @@
1
+ // `neurastream setup` detection (plan 20261028_2356 P3): reads the machine and returns one typed
2
+ // object. Pure over injected seams (HOME as the fs root, a PATH lookup, the Tailscale seam, os
3
+ // facts): no prompts, no writes. realSeams wires the node fs/os, the given PATH and realTailscale.
4
+ // Core names no harness: the caller passes the harness binaries (the adapter registry lives in
5
+ // src/adapters, which core may not import).
6
+
7
+ import { existsSync, readdirSync, statfsSync, statSync } from "node:fs";
8
+ import { availableParallelism, homedir, totalmem } from "node:os";
9
+ import { join } from "node:path";
10
+ import { configFile, loadConfig, type Config } from "./config.ts";
11
+ import { PROXY_BIN } from "./secret-redact.ts";
12
+ import { realTailscale, type Tailscale, type TailscaleState } from "./tailscale.ts";
13
+
14
+ export interface HarnessBin {
15
+ name: string;
16
+ /** The binary name looked up on PATH. */
17
+ bin: string;
18
+ }
19
+
20
+ export interface OsFacts {
21
+ cores: number;
22
+ ramMb: number;
23
+ /** Free space on the filesystem holding HOME, in GB (1e9 bytes, as the machine guard counts). */
24
+ diskFreeGb: number;
25
+ }
26
+
27
+ export interface SetupSeams {
28
+ /** HOME: the fs root the config and the work roots resolve against. */
29
+ home: string;
30
+ onPath(bin: string): boolean;
31
+ harnesses: HarnessBin[];
32
+ tailscale: Tailscale;
33
+ os: OsFacts;
34
+ }
35
+
36
+ export interface MachineProposal {
37
+ load_over_cores: number;
38
+ avail_min_mb: number;
39
+ disk_min_gb: number;
40
+ }
41
+
42
+ export interface SetupFacts {
43
+ /** Absolute paths of HOME's direct non-dot children that hold a git repo one level down, sorted. */
44
+ workRoots: string[];
45
+ /** Names of the harnesses whose binary is on PATH. */
46
+ harnesses: string[];
47
+ tailscale: { state: TailscaleState; logins: string[] | null };
48
+ secretgate: boolean;
49
+ machine: OsFacts;
50
+ /** The values setup would write: the config.yml values on a re-run, else computed from the machine. */
51
+ proposed: MachineProposal;
52
+ /** The loaded config when config.yml exists; null on a first run. */
53
+ current: Config | null;
54
+ }
55
+
56
+ function hasRepoBelow(dir: string): boolean {
57
+ try {
58
+ return readdirSync(dir, { withFileTypes: true }).some(c => c.isDirectory() && existsSync(join(dir, c.name, ".git")));
59
+ } catch {
60
+ return false;
61
+ }
62
+ }
63
+
64
+ function workRoots(home: string): string[] {
65
+ return readdirSync(home, { withFileTypes: true })
66
+ .filter(d => d.isDirectory() && !d.name.startsWith("."))
67
+ .map(d => join(home, d.name))
68
+ .filter(hasRepoBelow)
69
+ .toSorted();
70
+ }
71
+
72
+ export function detect(seams: SetupSeams): SetupFacts {
73
+ // env {} so a live QUEUE_* override never leaks into what setup proposes.
74
+ const cfg = loadConfig({ home: seams.home, env: {} });
75
+ const current = existsSync(configFile(seams.home)) ? cfg : null;
76
+ const os = seams.os;
77
+ // Without a config.yml, loadConfig returns the shipped template, so its machine values are the defaults.
78
+ const proposed: MachineProposal = current
79
+ ? { load_over_cores: cfg.machine.load_over_cores, avail_min_mb: cfg.machine.avail_min_mb, disk_min_gb: cfg.machine.disk_min_gb }
80
+ : {
81
+ load_over_cores: cfg.machine.load_over_cores,
82
+ avail_min_mb: Math.max(1024, Math.round(os.ramMb * 0.1)),
83
+ disk_min_gb: Math.max(1, Math.min(cfg.machine.disk_min_gb, Math.floor(os.diskFreeGb * 0.1))),
84
+ };
85
+ return {
86
+ workRoots: workRoots(seams.home),
87
+ harnesses: seams.harnesses.filter(h => seams.onPath(h.bin)).map(h => h.name),
88
+ tailscale: { state: seams.tailscale.state(), logins: seams.tailscale.logins() },
89
+ secretgate: seams.onPath(PROXY_BIN),
90
+ machine: os,
91
+ proposed,
92
+ current,
93
+ };
94
+ }
95
+
96
+ function binOnPath(bin: string, env: NodeJS.ProcessEnv): boolean {
97
+ for (const dir of (env.PATH ?? "").split(":")) {
98
+ if (dir === "") continue;
99
+ try {
100
+ if (statSync(join(dir, bin)).isFile()) return true;
101
+ } catch {}
102
+ }
103
+ return false;
104
+ }
105
+
106
+ /** The production seams: node fs/os, the given PATH, realTailscale. */
107
+ export function realSeams(harnesses: HarnessBin[], home: string = homedir(), env: NodeJS.ProcessEnv = process.env): SetupSeams {
108
+ const st = statfsSync(home);
109
+ return {
110
+ home,
111
+ onPath: bin => binOnPath(bin, env),
112
+ harnesses,
113
+ tailscale: realTailscale,
114
+ os: {
115
+ cores: availableParallelism(),
116
+ ramMb: totalmem() / 1024 / 1024,
117
+ diskFreeGb: (Number(st.bavail) * Number(st.bsize)) / 1e9,
118
+ },
119
+ };
120
+ }
@@ -4,6 +4,8 @@
4
4
 
5
5
  import { spawnSync } from "node:child_process";
6
6
 
7
+ export type TailscaleState = "missing" | "stopped" | "running";
8
+
7
9
  export interface Tailscale {
8
10
  /** This machine's tailnet IPv4 address (first line of `tailscale ip -4`), or null when tailscale fails or answers nothing. */
9
11
  ip4(): string | null;
@@ -13,6 +15,8 @@ export interface Tailscale {
13
15
  whois(peer: string): string | null;
14
16
  /** Every `User[*].LoginName` of `tailscale status --json`, or null when tailscale fails or the answer is unreadable — callers then skip their login check with a printed warning, never refuse on a tailscale failure. */
15
17
  logins(): string[] | null;
18
+ /** `missing` when the binary does not exist; `stopped` when it is installed but `tailscale status --json` fails, answers unreadably, or its BackendState is not "Running"; else `running`. */
19
+ state(): TailscaleState;
16
20
  }
17
21
 
18
22
  function firstStdoutLine(args: string[]): string | null {
@@ -33,6 +37,16 @@ export function parseWhoisLogin(stdout: string): string | null {
33
37
  }
34
38
  }
35
39
 
40
+ /** `running` only when `BackendState` of `tailscale status --json` is "Running"; unreadable JSON or any other state is `stopped`. */
41
+ export function parseBackendState(stdout: string): "running" | "stopped" {
42
+ try {
43
+ const parsed = JSON.parse(stdout) as { BackendState?: unknown };
44
+ return parsed.BackendState === "Running" ? "running" : "stopped";
45
+ } catch {
46
+ return "stopped";
47
+ }
48
+ }
49
+
36
50
  export const realTailscale: Tailscale = {
37
51
  ip4() {
38
52
  return firstStdoutLine(["ip", "-4"]);
@@ -70,4 +84,10 @@ export const realTailscale: Tailscale = {
70
84
  return null;
71
85
  }
72
86
  },
87
+ state() {
88
+ const r = spawnSync("tailscale", ["status", "--json"], { encoding: "utf8", timeout: 8000 });
89
+ if (r.error) return (r.error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "stopped";
90
+ if (r.status !== 0) return "stopped";
91
+ return parseBackendState(r.stdout ?? "");
92
+ },
73
93
  };
@@ -381,6 +381,12 @@ export interface OwnRun {
381
381
  * it, so it replaces the final-text check below.
382
382
  */
383
383
  claimedNone?: boolean;
384
+ /**
385
+ * Read paths named in the run's brief text (cfg.brief.path_prefixes), extracted the
386
+ * brief-lint way. A read whose target globMatches one is skipped as a D7 finding: the
387
+ * owner deliberately pointed the sub at that path in the brief.
388
+ */
389
+ allowed?: string[];
384
390
  }
385
391
 
386
392
  export interface UnreportedFinding {
@@ -469,6 +475,9 @@ export function unreportedFindings(events: TraceEvent[], rules: ActionsRules, ow
469
475
  const t = expandHome(raw, rules.home);
470
476
  const repo = ownedRepoOf(t, rules.owned_repos);
471
477
  if (repo === null || segKey(repo) === ownKey) continue;
478
+ // P10c: a read whose path matches a path the run's brief text names is not an
479
+ // unreported finding — the owner deliberately pointed the sub at it.
480
+ if (own.allowed?.some((p) => globMatch(p, t, rules.home))) continue;
472
481
  const id = `${repo}:${t}`;
473
482
  if (seen.has(id)) continue;
474
483
  seen.add(id);
@@ -5,12 +5,13 @@
5
5
  // ones), so tests record argv and never run systemctl or the tailscale binary.
6
6
 
7
7
  import { spawnSync } from "node:child_process";
8
- import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
9
- import { homedir, tmpdir } from "node:os";
8
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
9
+ import { homedir } from "node:os";
10
10
  import { dirname, join } from "node:path";
11
11
  import { fileURLToPath } from "node:url";
12
12
  import { ConfigError, configFile, loadConfig } from "./config.ts";
13
13
  import { realTailscale, type Tailscale } from "./tailscale.ts";
14
+ import { checkEdited, setConfigKeys } from "./config-edit.ts";
14
15
 
15
16
  const HERE = dirname(fileURLToPath(import.meta.url));
16
17
  export const UI_UNIT_TEMPLATE = join(HERE, "../../templates/systemd/neurastream-ui.service");
@@ -28,6 +29,29 @@ export const systemRunner: Runner = args => {
28
29
  return { status: r.status, stderr: r.stderr ?? "" };
29
30
  };
30
31
 
32
+ export interface Terminal {
33
+ /** Prints the question on the terminal and returns the answer line. */
34
+ ask(question: string): string;
35
+ /** Opens a URL in the default browser. */
36
+ open(url: string): void;
37
+ }
38
+
39
+ // Production terminal. sh reads the answer from the inherited terminal, so uiOn stays synchronous.
40
+ export const systemTerminal: Terminal = {
41
+ ask(question) {
42
+ const r = spawnSync("sh", ["-c", 'printf "%s" "$1" >&2; read -r answer; printf "%s" "$answer"', "sh", question], { encoding: "utf8", stdio: ["inherit", "pipe", "inherit"] });
43
+ return r.stdout ?? "";
44
+ },
45
+ open(url) {
46
+ spawnSync(process.platform === "darwin" ? "open" : "xdg-open", [url], { stdio: "ignore" });
47
+ },
48
+ };
49
+
50
+ const TAILSCALE_DOWNLOAD = "https://tailscale.com/download";
51
+ const TAILSCALE_MISSING = "The phone page needs Tailscale (free, private network for your devices). Install it: Linux `curl -fsSL https://tailscale.com/install.sh | sh` (asks for your password), macOS: the App Store app, others: https://tailscale.com/download. Then run `neurastream ui on` again.";
52
+ const TAILSCALE_STOPPED = "Tailscale is installed but not connected. Run `sudo tailscale up` (Linux) or open the Tailscale app (macOS), then run this again.";
53
+ export { TAILSCALE_MISSING, TAILSCALE_STOPPED };
54
+
31
55
  export interface UiSetupOptions {
32
56
  /** HOME the config file and the user unit resolve against. Default: the real home. */
33
57
  home?: string;
@@ -43,64 +67,8 @@ export interface UiOnOptions extends UiSetupOptions {
43
67
  login: string;
44
68
  /** The --port N of the command line; null leaves the config's ui.port in place. */
45
69
  port?: number | null;
46
- }
47
-
48
- // Line-based edit of the top-level `ui:` block: replaces only the enabled/owner_login/port
49
- // lines inside it, keeps every other line of the file byte-for-byte (comments, order, other
50
- // sections), and appends a fresh block when the config has none. Never re-serialises YAML.
51
- function editUiBlock(text: string | null, values: { enabled: boolean; owner_login: string | null; port: number | null }): string {
52
- const fresh = ["ui:", ` enabled: ${values.enabled}`];
53
- if (values.owner_login !== null) fresh.push(` owner_login: ${values.owner_login}`);
54
- if (values.port !== null) fresh.push(` port: ${values.port}`);
55
- if (text === null) return `${fresh.join("\n")}\n`;
56
- const lines = text.split("\n");
57
- let start = -1;
58
- for (let i = 0; i < lines.length; i++) {
59
- if (/^ui\s*:(\s*(?:#.*)?)?$/.test(lines[i] ?? "")) {
60
- start = i;
61
- break;
62
- }
63
- }
64
- if (start === -1) {
65
- const base = text === "" || text.endsWith("\n") ? text : `${text}\n`;
66
- return `${base}${fresh.join("\n")}\n`;
67
- }
68
- let end = start + 1;
69
- while (end < lines.length && (lines[end] === "" || /^[ \t]/.test(lines[end]!))) end++;
70
- const setKey = (key: string, value: string): void => {
71
- const re = new RegExp(`^([ \\t]+)${key}\\s*:.*$`);
72
- for (let i = start + 1; i < end; i++) {
73
- const line = lines[i]!;
74
- if (re.test(line)) {
75
- lines[i] = line.replace(re, `$1${key}: ${value}`);
76
- return;
77
- }
78
- }
79
- // The block has no such key: insert after its last non-blank line, at two-space indent.
80
- let at = start + 1;
81
- for (let i = start + 1; i < end; i++) if (lines[i]!.trim() !== "") at = i + 1;
82
- lines.splice(at, 0, ` ${key}: ${value}`);
83
- };
84
- setKey("enabled", String(values.enabled));
85
- if (values.owner_login !== null) setKey("owner_login", values.owner_login);
86
- if (values.port !== null) setKey("port", String(values.port));
87
- return lines.join("\n");
88
- }
89
-
90
- // Validates the edited text through loadConfig before anything is written: if it would not
91
- // load, nothing is written and the caller reports the error (the real file stays untouched).
92
- function checkEdited(edited: string, home: string, what: string, error: (line: string) => void): boolean {
93
- const check = join(tmpdir(), `neurastream-ui-${what}-check-${process.pid}.yml`);
94
- try {
95
- writeFileSync(check, edited);
96
- loadConfig({ file: check, home });
97
- return true;
98
- } catch (err) {
99
- error(err instanceof ConfigError ? err.message : String(err));
100
- return false;
101
- } finally {
102
- rmSync(check, { force: true });
103
- }
70
+ /** Terminal seam for the missing-tailscale question. Absent: no question, only the message. src/cli/ui.ts passes the real one on a TTY. */
71
+ terminal?: Terminal;
104
72
  }
105
73
 
106
74
  export function uiOn(opts: UiOnOptions): number {
@@ -109,6 +77,18 @@ export function uiOn(opts: UiOnOptions): number {
109
77
  const tailscale = opts.tailscale ?? realTailscale;
110
78
  const print = opts.print ?? console.log;
111
79
  const error = opts.error ?? console.error;
80
+ // Tailscale comes first (plan 20261028_2356 P2): nothing is read, written or run unless it is up.
81
+ const state = tailscale.state();
82
+ if (state === "missing") {
83
+ error(`neurastream ui: ${TAILSCALE_MISSING}`);
84
+ const terminal = opts.terminal;
85
+ if (terminal && terminal.ask("Open the Tailscale download page now? [y/N] ").trim().toLowerCase() === "y") terminal.open(TAILSCALE_DOWNLOAD);
86
+ return 1;
87
+ }
88
+ if (state === "stopped") {
89
+ error(`neurastream ui: ${TAILSCALE_STOPPED}`);
90
+ return 1;
91
+ }
112
92
  const file = configFile(home);
113
93
  let cfg;
114
94
  try {
@@ -125,8 +105,16 @@ export function uiOn(opts: UiOnOptions): number {
125
105
  return 1;
126
106
  }
127
107
  const original = existsSync(file) ? readFileSync(file, "utf8") : null;
128
- const edited = editUiBlock(original, { enabled: true, owner_login: opts.login, port: opts.port ?? null });
129
- if (!checkEdited(edited, home, "on", error)) return 1;
108
+ const values: Record<string, string> = { "ui.enabled": "true", "ui.owner_login": opts.login };
109
+ if (typeof opts.port === "number") values["ui.port"] = String(opts.port);
110
+ let edited: string;
111
+ try {
112
+ edited = setConfigKeys(original, values);
113
+ } catch (err) {
114
+ error(err instanceof ConfigError ? err.message : String(err));
115
+ return 1;
116
+ }
117
+ if (!checkEdited(edited, home, error)) return 1;
130
118
  const unitPath = join(home, ".config", "systemd", "user", "neurastream-ui.service");
131
119
  mkdirSync(dirname(unitPath), { recursive: true });
132
120
  copyFileSync(UI_UNIT_TEMPLATE, unitPath);
@@ -165,8 +153,8 @@ export function uiOff(opts: UiSetupOptions): number {
165
153
  }
166
154
  const file = configFile(home);
167
155
  if (existsSync(file)) {
168
- const edited = editUiBlock(readFileSync(file, "utf8"), { enabled: false, owner_login: null, port: null });
169
- if (!checkEdited(edited, home, "off", error)) return 1;
156
+ const edited = setConfigKeys(readFileSync(file, "utf8"), { "ui.enabled": "false" });
157
+ if (!checkEdited(edited, home, error)) return 1;
170
158
  writeFileSync(file, edited);
171
159
  }
172
160
  return 0;