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.
@@ -0,0 +1,111 @@
1
+ // The one config.yml editor. setConfigKeys edits dotted keys line by line and keeps every other
2
+ // line byte-for-byte (comments, order, other sections): it never re-serialises YAML.
3
+ // checkEdited proves an edited file still loads before anything is written.
4
+
5
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { join } from "node:path";
8
+ import { ConfigError, loadConfig } from "./config.ts";
9
+
10
+ const leading = (line: string): number => line.length - line.trimStart().length;
11
+ const isBlank = (line: string): boolean => line.trim() === "";
12
+
13
+ // Leaf dotted paths: a mapping recurses; a scalar, a list or null is a leaf.
14
+ export function leafKeys(node: unknown, prefix: string[] = []): string[] {
15
+ if (node === null || typeof node !== "object" || Array.isArray(node)) return [prefix.join(".")];
16
+ return Object.entries(node).flatMap(([k, v]) => leafKeys(v, [...prefix, k]));
17
+ }
18
+
19
+ export function valueAt(cfg: unknown, key: string): unknown {
20
+ let node = cfg;
21
+ for (const seg of key.split(".")) node = (node as Record<string, unknown>)[seg];
22
+ return node;
23
+ }
24
+
25
+ // A value as YAML text for setConfigKeys: lists in flow style on one line ([a, b]); scalars as JSON, which is valid YAML.
26
+ export function yamlValue(value: unknown): string {
27
+ return Array.isArray(value) ? `[${value.map((x) => JSON.stringify(x)).join(", ")}]` : JSON.stringify(value);
28
+ }
29
+
30
+ // First line at or after `from` that is not part of a block whose keys sit at column `col`.
31
+ // A block is the following lines that are blank or indented deeper than the key.
32
+ function blockEnd(lines: string[], from: number, col: number): number {
33
+ let j = from;
34
+ while (j < lines.length && (isBlank(lines[j]!) || leading(lines[j]!) > col)) j++;
35
+ return j;
36
+ }
37
+
38
+ // Just past the last non-blank line in [from, end): where a new line joins that block.
39
+ function afterLast(lines: string[], from: number, end: number): number {
40
+ let at = from;
41
+ for (let i = from; i < end; i++) if (!isBlank(lines[i]!)) at = i + 1;
42
+ return at;
43
+ }
44
+
45
+ // Sets one path segment list inside the block of `parent` (-1 = the whole file). `indent` is the
46
+ // column its keys sit at. Recurses one level per segment, so a.b.c only matches inside a's and b's blocks.
47
+ function setPath(lines: string[], segs: string[], value: string, parent: number, indent: string): void {
48
+ const [seg, ...deeper] = segs as [string, ...string[]];
49
+ const lo = parent < 0 ? 0 : parent + 1;
50
+ const hi = parent < 0 ? lines.length : blockEnd(lines, lo, leading(lines[parent]!));
51
+ const re = new RegExp("^" + indent + seg.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "(\\s*):(.*)$");
52
+ let k = -1;
53
+ for (let i = lo; i < hi; i++) {
54
+ if (re.test(lines[i]!)) {
55
+ k = i;
56
+ break;
57
+ }
58
+ }
59
+ if (deeper.length === 0) {
60
+ if (k < 0) {
61
+ lines.splice(afterLast(lines, lo, hi), 0, `${indent}${seg}: ${value}`);
62
+ return;
63
+ }
64
+ // Replace the leaf and any child lines under it; keep its trailing comment.
65
+ const rest = re.exec(lines[k]!)![2]!;
66
+ const comment = rest.match(/\s+#.*$/)?.[0] ?? "";
67
+ const cut = afterLast(lines, k + 1, blockEnd(lines, k + 1, indent.length));
68
+ lines.splice(k, cut - k, `${indent}${seg}: ${value}${comment}`);
69
+ return;
70
+ }
71
+ if (k < 0) {
72
+ k = afterLast(lines, lo, hi);
73
+ lines.splice(k, 0, `${indent}${seg}:`);
74
+ }
75
+ const end = blockEnd(lines, k + 1, indent.length);
76
+ const child = lines.slice(k + 1, end).find((l) => !isBlank(l));
77
+ const childIndent = child === undefined ? `${indent} ` : /^[ \t]*/.exec(child)![0];
78
+ setPath(lines, deeper, value, k, childIndent);
79
+ }
80
+
81
+ // `values` maps each dotted key to its already-formatted YAML value text (`true`, `7788`,
82
+ // `["a", "b"]`, `"quoted"`). A value with a line break is refused: it would write extra keys.
83
+ export function setConfigKeys(text: string | null, values: Record<string, string>): string {
84
+ for (const [key, value] of Object.entries(values)) {
85
+ if (/[\n\r]/.test(value)) throw new ConfigError(`config ${key}: a value cannot contain a line break`);
86
+ }
87
+ // "".split("\n") is [""], so an empty file still ends with a newline after the first insert.
88
+ let base = text ?? "";
89
+ if (base !== "" && !base.endsWith("\n")) base += "\n";
90
+ const lines = base.split("\n");
91
+ for (const [key, value] of Object.entries(values)) setPath(lines, key.split("."), value, -1, "");
92
+ return lines.join("\n");
93
+ }
94
+
95
+ // Proves an edited config still loads through loadConfig before anything is written. The copy goes
96
+ // to a fresh mkdtemp dir (mode 0700, unpredictable name, so no planted symlink can redirect it);
97
+ // the dir is removed in finally. Returns false after reporting the error when the file does not load.
98
+ export function checkEdited(edited: string, home: string, error: (line: string) => void): boolean {
99
+ const dir = mkdtempSync(join(tmpdir(), "neurastream-check-"));
100
+ try {
101
+ const file = join(dir, "config.yml");
102
+ writeFileSync(file, edited, { mode: 0o600 });
103
+ loadConfig({ file, home });
104
+ return true;
105
+ } catch (err) {
106
+ error(err instanceof ConfigError ? err.message : String(err));
107
+ return false;
108
+ } finally {
109
+ rmSync(dir, { recursive: true, force: true });
110
+ }
111
+ }
@@ -107,6 +107,8 @@ export interface Config {
107
107
  auto_close_min: number;
108
108
  repo_index: string;
109
109
  cancelled_rel: string;
110
+ /** Minutes without a heartbeat before a Main's plan claim frees (multi-main claims, src/core/claims.ts). */
111
+ claim_ttl_min: number;
110
112
  /** How long a hold's `still true if` result is reused (src/core/waiting-check.ts). */
111
113
  waiting_check_ttl_sec: number;
112
114
  /** One hold check may run this long; a timeout is "unknown", never "stale". */
@@ -584,6 +586,7 @@ function check(cfg: Config): void {
584
586
  if (!(cfg.guards.rate_limit.slack_s >= 0)) throw new ConfigError("guards.rate_limit.slack_s must be >= 0");
585
587
  if (!(cfg.rollover.exit_grace_s > 0)) throw new ConfigError("rollover.exit_grace_s must be > 0");
586
588
  if (!(cfg.metrics.report_days >= 1)) throw new ConfigError("metrics.report_days must be >= 1");
589
+ if (!(cfg.queue.claim_ttl_min >= 1)) throw new ConfigError("queue.claim_ttl_min must be >= 1");
587
590
  if (!(cfg.ui.port >= 1 && cfg.ui.port <= 65535)) throw new ConfigError("ui.port must be between 1 and 65535");
588
591
  if (!Number.isInteger(cfg.pages.port) || cfg.pages.port < 1 || cfg.pages.port > 65535) throw new ConfigError("pages.port must be an integer between 1 and 65535");
589
592
  if (typeof cfg.pages.dir !== "string" || cfg.pages.dir.length === 0) throw new ConfigError("pages.dir must be a non-empty path");
@@ -22,7 +22,7 @@
22
22
  // the stop is refused; an incident with a plan no longer blocks
23
23
 
24
24
  import { execFileSync } from "node:child_process";
25
- import { appendFileSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
25
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
26
26
  import { homedir } from "node:os";
27
27
  import path from "node:path";
28
28
  import type { Decision, InjectEvent, PlanEditEvent, SpawnEvent, StopEvent, ToolEvent } from "./adapter.ts";
@@ -35,11 +35,11 @@ import { UNANSWERED_PREFIX } from "./rollover.ts";
35
35
  import { notifyProtectedPaths, notifySecretReadHit } from "./notify.ts";
36
36
  import { defaultRunner, listOpenMrs, mentioned, type CommandRunner, type OpenMr } from "./mr-sweep.ts";
37
37
  import { unlandedRows } from "./wip-check.ts";
38
- import { recheckHolds, staleFiles } from "./waiting-check.ts";
39
38
  import * as q from "./queue/lib.ts";
40
39
  import type { Plan } from "./queue/lib.ts";
41
40
 
42
- import { nowSec } from "./clock.ts";
41
+ import { fileClaimStore, type Claim, type ClaimStore } from "./claims.ts";
42
+ import { nowSec, strftime } from "./clock.ts";
43
43
  import { outUntil, pinModel, providerOfModel, readOut } from "./provider-state.ts";
44
44
  import { lint } from "./brief-lint.ts";
45
45
  const ALLOW: Decision = { allow: true, reason: "" };
@@ -66,10 +66,10 @@ function isPlanName(raw: string): boolean {
66
66
  }
67
67
  const PLAN_WRITE_TOOLS: Record<string, true> = { edit: true, write: true, ast_edit: true };
68
68
 
69
- /** Guard-log line, `<ISO UTC> <line>`; a failed append is swallowed. */
69
+ /** Guard-log line, `<ISO UTC> [<main id>] <line>`; a failed append is swallowed. */
70
70
  export function log(file: string, line: string): void {
71
71
  try {
72
- appendFileSync(file, `${new Date().toISOString()} ${line}\n`);
72
+ appendFileSync(file, `${new Date().toISOString()} [${mainId()}] ${line}\n`);
73
73
  } catch {}
74
74
  }
75
75
 
@@ -91,8 +91,39 @@ interface EditWindow {
91
91
  mainCallsStart?: number;
92
92
  }
93
93
 
94
+ // --- this Main's identity (plan 20261027_1300_multi_main P2) ---
95
+
96
+ /** What `neurastream main --name` accepts and what `NEURASTREAM_MAIN_ID` may hold. */
97
+ export const MAIN_ID_RE = /^[a-z0-9-]{1,24}$/;
98
+
99
+ /** This Main's id: the launcher sets `NEURASTREAM_MAIN_ID` (default `main`); a bogus value falls back to `main`. */
100
+ export function mainId(): string {
101
+ const id = process.env.NEURASTREAM_MAIN_ID ?? "main";
102
+ return MAIN_ID_RE.test(id) ? id : "main";
103
+ }
104
+
105
+ /** One-time move of the pre-multi-main top-level state into `mains/main/` (renameSync, idempotent). */
106
+ function moveLegacyState(stateDir: string, dir: string): void {
107
+ if (existsSync(dir)) return;
108
+ mkdirSync(dir, { recursive: true });
109
+ for (const name of ["edit-window.json", "rollover"]) {
110
+ try {
111
+ renameSync(path.join(stateDir, name), path.join(dir, name));
112
+ } catch {}
113
+ }
114
+ }
115
+
116
+ /** This Main's own state dir, `<queue_state>/mains/<id>/`: edit window, rollover notes, running lock. */
117
+ export function mainStateDir(cfg?: Config): string {
118
+ const stateDir = cfg ? cfg.paths.queue_state : q.stateDirPath();
119
+ const id = mainId();
120
+ const dir = path.join(stateDir, "mains", id);
121
+ if (id === "main") moveLegacyState(stateDir, dir);
122
+ return dir;
123
+ }
124
+
94
125
  function windowFile(): string {
95
- return path.join(q.STATE_DIR, "edit-window.json");
126
+ return path.join(mainStateDir(), "edit-window.json");
96
127
  }
97
128
 
98
129
  export function readWindow(): EditWindow {
@@ -106,7 +137,7 @@ export function readWindow(): EditWindow {
106
137
 
107
138
  export function writeWindow(w: EditWindow): void {
108
139
  try {
109
- mkdirSync(q.STATE_DIR, { recursive: true });
140
+ mkdirSync(path.dirname(windowFile()), { recursive: true });
110
141
  writeFileSync(windowFile(), JSON.stringify(w, null, 1));
111
142
  } catch (err) {
112
143
  log(`${q.STATE_DIR}/../main-guard.log`, `cannot write ${windowFile()}: ${err}`);
@@ -1117,6 +1148,22 @@ function startsOwnerUi(input: Record<string, unknown>): boolean {
1117
1148
  });
1118
1149
  }
1119
1150
 
1151
+ // True when a command segment runs `claim release <plan> --force` (plan 20261027_1300 P4): it
1152
+ // frees another Main's claim, the owner's terminal move, refused for every agent. Segment
1153
+ // splitting and launcher skipping match startsOwnerUi, so `sh -c "neurastream claim release x
1154
+ // --force"` and `sudo neurastream claim release x --force` are seen too.
1155
+ function forceClaimRelease(input: Record<string, unknown>): boolean {
1156
+ const text = Object.values(input).filter((v): v is string => typeof v === "string").join("\n");
1157
+ return text.split(/&&|\|\||;|\||\n|\$\(|`/).some(seg => {
1158
+ const words = seg.trim().split(/\s+/).filter(Boolean).map(w => w.replace(/^["'(]+|["')]+$/g, ""));
1159
+ let i = 0;
1160
+ while (i < words.length && (LAUNCHERS[words[i] ?? ""] === true || /^\w+=/.test(words[i] ?? "") || /(^|\/)main\.ts$/.test(words[i] ?? ""))) i++;
1161
+ const seq = words.slice(i).map(bin);
1162
+ if (seq[0] === "neurastream") seq.shift();
1163
+ return seq[0] === "claim" && seq.includes("release") && seq.includes("--force");
1164
+ });
1165
+ }
1166
+
1120
1167
  // True when a command segment lands work on a remote (plan 20261025_1940 P2): `git push`,
1121
1168
  // `glab mr merge`, `gh pr merge`. Segment splitting and launcher skipping match startsOwnerUi,
1122
1169
  // so `sh -c "git push"`, `sudo git push` and chained pushes are seen too.
@@ -1321,6 +1368,13 @@ function taskLaunch(input: Record<string, unknown>, cfg: Config, runningJobs: st
1321
1368
  log(cfg.paths.guard_log, `BLOCK spawn: ${why}`);
1322
1369
  return why;
1323
1370
  }
1371
+ const inc = incidentSpawnProblem("spawn", JSON.stringify(input), files, cfg);
1372
+ if (inc) return inc;
1373
+ const held = claimGate(files, cfg);
1374
+ if (held) {
1375
+ log(cfg.paths.guard_log, `BLOCK spawn: ${held}`);
1376
+ return held;
1377
+ }
1324
1378
  recordSpawns(files, staffing);
1325
1379
  recordBudgets(budgets);
1326
1380
  return null;
@@ -1350,6 +1404,13 @@ function bypassLaunch(command: string, cfg: Config, spawner: Spawner): string |
1350
1404
  }
1351
1405
  const inc = incidentSpawnProblem("bypass launch", command, named, cfg);
1352
1406
  if (inc) return inc;
1407
+ // I-20261031-280: a bypass launch takes the claims like every other spawn, as its last
1408
+ // refusal before the record.
1409
+ const held = claimGate(named, cfg);
1410
+ if (held) {
1411
+ log(cfg.paths.guard_log, `BLOCK bypass launch: ${held}`);
1412
+ return held;
1413
+ }
1353
1414
  if (named.length) recordSpawns(named);
1354
1415
  }
1355
1416
  return null;
@@ -1455,6 +1516,12 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
1455
1516
  "plan-guard: starting the owner page (neurastream ui, or systemctl --user start/restart/enable of neurastream-ui) is the owner's move, not an agent's.",
1456
1517
  );
1457
1518
  }
1519
+ // claim release --force frees another Main's claim (plan 20261027_1300 P4): the owner's
1520
+ // terminal move, refused for every agent like the ui-start, plan-guard style.
1521
+ if (cfg.guards.shell_tools.includes(e.tool) && forceClaimRelease(input)) {
1522
+ log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} claim-force: ${String(input.command ?? "")}`);
1523
+ return deny("plan-guard: claim release --force frees another Main's claim; that is the owner's move, in a terminal.");
1524
+ }
1458
1525
  // The caller may know paths the text search cannot see (structured edits); union, never shrink.
1459
1526
  const paths: string[] = [];
1460
1527
  for (const p of [...(e.paths ?? []), ...q.touchedPaths(e.tool, input, e.cwd)]) if (!paths.includes(p)) paths.push(p);
@@ -1484,7 +1551,7 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
1484
1551
  }
1485
1552
  // Main writes its own rollover note unattended (the note turn has nobody to ask). Only a Write
1486
1553
  // of a .md directly in <state>/rollover/ is exempt; shell writes, subagents and relaunch.json stay refused.
1487
- const rolloverDir = path.join(q.stateDirPath(), "rollover");
1554
+ const rolloverDir = path.join(mainStateDir(cfg), "rollover");
1488
1555
  const openWrites =
1489
1556
  e.agent === "main" && e.tool === "write"
1490
1557
  ? writes.filter(p => !(path.extname(p) === ".md" && path.dirname(path.resolve(p)) === rolloverDir))
@@ -1631,6 +1698,42 @@ export function planReadNote(tool: string, input: Record<string, unknown>, cwd:
1631
1698
  return `plan-guard: before you edit this plan, re-read: ${stale.join(", ")}`;
1632
1699
  }
1633
1700
 
1701
+ /**
1702
+ * P3 (plan 20261027_1300): the claim store behind the spawn and Main edit gates. Claims live under
1703
+ * `<queue_state>/claims/`; the free-after TTL is queue.claim_ttl_min (never the store's default).
1704
+ */
1705
+ function claims(cfg: Config): ClaimStore {
1706
+ return fileClaimStore(cfg.paths.queue_state, nowSec, cfg.queue.claim_ttl_min);
1707
+ }
1708
+
1709
+ /** The held refusal (plan 20261027_1300 P3): "plan X is held by Main B since HH:MM" (HH:MM local). */
1710
+ function heldProblem(file: string, held: Claim): string {
1711
+ return `plan ${file} is held by Main ${held.main} since ${strftime(held.since, "%H:%M")}`;
1712
+ }
1713
+
1714
+ /**
1715
+ * The spawn claim gate (plan 20261027_1300 P3): a spawn on a plan claims it for this Main first;
1716
+ * another Main's live claim refuses the launch — a sub's launch too, once its Main no longer
1717
+ * holds the claim. Returns the refusal, or null.
1718
+ */
1719
+ function claimGate(files: string[], cfg: Config): string | null {
1720
+ const store = claims(cfg);
1721
+ const mine = mainId();
1722
+ const fresh: string[] = [];
1723
+ for (const f of files) {
1724
+ const heldBefore = store.holder(f)?.main === mine;
1725
+ const c = store.claim(f, mine);
1726
+ if ("heldBy" in c) {
1727
+ // A refusal leaves the store as it found it (P3 review finding 2): claims this call
1728
+ // newly created are released again; a claim this Main already held before the call stays.
1729
+ for (const g of fresh) store.release(g, mine);
1730
+ return heldProblem(f, c.heldBy);
1731
+ }
1732
+ if (!heldBefore) fresh.push(f);
1733
+ }
1734
+ return null;
1735
+ }
1736
+
1634
1737
  /**
1635
1738
  * spawn: the allow-list, task-only and open-plan gates for one implementer launch. Covers both
1636
1739
  * original paths (the extension spawn event and a `task` tool call); the brief names the plan.
@@ -1673,6 +1776,11 @@ export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = d
1673
1776
  }
1674
1777
  return deny(`main-guard: ${verdict}`);
1675
1778
  }
1779
+ const held = claimGate(named, cfg);
1780
+ if (held) {
1781
+ log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${held}`);
1782
+ return deny(`main-guard: ${held}`);
1783
+ }
1676
1784
  // The owner's pick order and live provider state (plan 20261025_1700 P3), before the spawn records.
1677
1785
  const staffing: Record<string, string[]> = {};
1678
1786
  for (const f of named) staffing[f] = [e.agent];
@@ -1715,7 +1823,7 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
1715
1823
  recordOwnerMessage(e.inject, cfg);
1716
1824
  let summary: string;
1717
1825
  try {
1718
- summary = q.queueSummary(undefined, cfg.review.agents, staleFiles(recheckHolds(cfg, q.activePlans())));
1826
+ summary = q.queueSummary(undefined, cfg.review.agents, claims(cfg));
1719
1827
  } catch (err) {
1720
1828
  summary = `Queue unreadable (${q.INDEX}): ${err}`;
1721
1829
  }
@@ -1843,6 +1951,17 @@ function codeReviewProblem(file: string, after: string, ids: string[]): string |
1843
1951
  // Main's plan text outside "## Progress" must rest on files Main read itself (planReadProblems).
1844
1952
  // An empty `before` means the plan file did not exist yet; a refusal then deletes it.
1845
1953
  function checkMainPlan(e: PlanEditEvent, cfg: Config): PlanEditDecision {
1954
+ // P3 (plan 20261027_1300): another Main's live claim on this plan refuses the edit, restored
1955
+ // like any refused plan edit. No claim — or this Main's own — edits freely.
1956
+ const holder = claims(cfg).holder(e.path);
1957
+ if (holder && holder.main !== mainId()) {
1958
+ log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (held by Main ${holder.main})`);
1959
+ return {
1960
+ allow: false,
1961
+ reason: `plan-guard: ${heldProblem(e.path, holder)}; the file was restored.`,
1962
+ restore: { path: e.path, text: e.before || null },
1963
+ };
1964
+ }
1846
1965
  // A PLAN REVIEW or CODE REVIEW line (P6) is a review spawn's verdict (P4k): Main writes none, so its edit is restored.
1847
1966
  if (newProgressEntries(e.before, e.after).some(b => REVIEW_LINE.test(b))) {
1848
1967
  log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (Main wrote a review line)`);
@@ -6,6 +6,7 @@
6
6
  import { dirname } from "node:path";
7
7
  import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
8
8
  import { configFile, type Config } from "./config.ts";
9
+ import { mainId } from "./guards.ts";
9
10
  import { strftime } from "./clock.ts";
10
11
  import { recentOwnerMessages, type MessageRow } from "./owner-ui.ts";
11
12
  import { stateDirPath } from "./queue/lib.ts";
@@ -213,7 +214,7 @@ const enqueuePost = <T>(operation: () => Promise<T>): Promise<T> => {
213
214
  export function postReply(text: string, cfg: Config): Promise<NotifyPostResult[]> {
214
215
  return enqueuePost(async () => {
215
216
  const providers = notifyProviders(cfg);
216
- const body = cfg.notify.prefix ? `${cfg.notify.prefix} ${text}` : text;
217
+ const body = cfg.notify.prefix ? `${cfg.notify.prefix} [${mainId()}] ${text}` : `[${mainId()}] ${text}`;
217
218
  if (body.trim() === "") return providers.map(p => ({ provider: p.name, posted: false, chunks: 0, error: "empty reply; nothing posted" }));
218
219
  // The chat is where a secret does its damage (plan 20261025_2204): a reply can carry a value
219
220
  // the owner pasted or one the redactor's tool_result pass never saw, so the post is scrubbed
@@ -13,12 +13,14 @@ import os from "node:os";
13
13
  import { basename, resolve } from "node:path";
14
14
  import type { RunSource } from "./adapter.ts";
15
15
  import { chatTier, currentTier, type Tier } from "./autonomy.ts";
16
+ import { fileClaimStore } from "./claims.ts";
16
17
  import type { Config } from "./config.ts";
17
18
  import { nowSec, strftime } from "./clock.ts";
18
19
  import { cpuCount } from "./host.ts";
19
20
  import { dismissIncident, isFindingKind, openIncidents } from "./incidents.ts";
20
21
  import { byText, knowledgeManifest, readKnowledgeTopicFile, urlField, urlValue, type KnowledgeEntry } from "./knowledge.ts";
21
- import { log } from "./guards.ts";
22
+ import { isBusy } from "./file-lock.ts";
23
+ import { log, MAIN_ID_RE } from "./guards.ts";
22
24
  import { publishedPages } from "./pages-expiry.ts";
23
25
  import { readMetricEvents } from "./metrics.ts";
24
26
  import { activePlans, chatUnlock, dependencyOrderProblems, expandHome, gitTop, stateDirPath, unlockPath, writeIndex, type Plan } from "./queue/lib.ts";
@@ -156,6 +158,8 @@ export interface QueueRow {
156
158
  waiting: boolean;
157
159
  /** `Summary:` header, else the first Goal bullet with a leading Owner/INCIDENT prefix cut off. */
158
160
  summary: string | null;
161
+ /** The Main id holding this plan's claim, else null (P5 multi-main). */
162
+ holder: string | null;
159
163
  /** Chip text: waits you, waits on a plan, not started, phase K of N, or all N done. */
160
164
  state: string;
161
165
  }
@@ -256,15 +260,20 @@ function queueState(p: Plan, plans: Plan[]): string {
256
260
 
257
261
  export function queueRows(cfg: Config): QueueRow[] {
258
262
  const plans = activePlans(cfg.paths.queue_index).filter(p => p.status === "open");
259
- return plans.map(p => ({
260
- repo: basename(p.repo),
261
- file: p.file,
262
- title: p.title,
263
- status: p.status ?? "?",
264
- waiting: p.waiting,
265
- summary: p.summary ?? (goalSummary(p.goal[0] ?? "") || null),
266
- state: queueState(p, plans),
267
- }));
263
+ const claims = fileClaimStore(cfg.paths.queue_state, nowSec, cfg.queue.claim_ttl_min);
264
+ return plans.map(p => {
265
+ const holder = claims.holder(p.file)?.main ?? null;
266
+ return {
267
+ repo: basename(p.repo),
268
+ file: p.file,
269
+ title: p.title,
270
+ status: p.status ?? "?",
271
+ waiting: p.waiting,
272
+ summary: p.summary ?? (goalSummary(p.goal[0] ?? "") || null),
273
+ state: queueState(p, plans),
274
+ holder,
275
+ };
276
+ });
268
277
  }
269
278
 
270
279
  export function ciRows(cfg: Config): CiRow[] {
@@ -382,6 +391,29 @@ function ownerMessagesDir(): string {
382
391
  return `${stateDirPath()}/owner-messages`;
383
392
  }
384
393
 
394
+ /** 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. */
395
+ export function runningMains(cfg: Config): string[] {
396
+ let dirs: string[];
397
+ try {
398
+ dirs = readdirSync(`${cfg.paths.queue_state}/mains`);
399
+ } catch {
400
+ return [];
401
+ }
402
+ return dirs
403
+ .filter(d => MAIN_ID_RE.test(d) && isBusy(`${cfg.paths.queue_state}/mains/${d}/running.lock`))
404
+ .toSorted();
405
+ }
406
+
407
+ /** Resolves where a message goes (P5 multi-main): an `@<id> ` prefix or the picker's `to` field names one running Main; empty is every Main. A stale target is refused before anything is stored. */
408
+ export function ownerMessageTarget(text: string, cfg: Config, formTo = ""): { to: string } | { refuse: string } {
409
+ const at = /^@([a-z0-9-]{1,24})(?:\s|$)/.exec(text);
410
+ const target = (at ? at[1] : formTo) ?? "";
411
+ if (!target || !MAIN_ID_RE.test(target)) return { to: "" };
412
+ const running = runningMains(cfg);
413
+ if (running.includes(target)) return { to: target };
414
+ return { refuse: `Main ${target} is not running; running: ${running.length ? running.join(", ") : "none"}` };
415
+ }
416
+
385
417
  export interface MessageRow {
386
418
  id: string;
387
419
  ts: number;
@@ -466,9 +498,10 @@ export function recentOwnerMessages(now: number): MessageRow[] {
466
498
  // ---- rendering (consumes the rows above, never the readers directly) ----
467
499
 
468
500
  /** The "Tell Main" card: one textarea, image picks, a Send button — no chat thread. Under it, "Sent today": this view's messages newer than the keep window, newest first, thumbnails served from /message-image. */
469
- function messageCard(messages: MessageRow[] | null): string {
501
+ function messageCard(messages: MessageRow[] | null, running: string[]): string {
470
502
  const form = `<form class="msgform" method="post" action="/message" enctype="multipart/form-data">
471
503
  <textarea name="text" maxlength="${MESSAGE_MAX}" rows="3" placeholder="What Main should know — a fix, a link, a photo"></textarea>
504
+ <select name="to"><option value="">All</option>${running.map(id => `<option value="${esc(id)}">Main ${esc(id)}</option>`).join("")}</select>
472
505
  <input type="file" name="images" accept="image/*" multiple>
473
506
  <button class="btn pri" type="submit">Send</button>
474
507
  </form>`;
@@ -553,7 +586,7 @@ function queueHtml(rows: QueueRow[], tab: string): string {
553
586
  <span class="qhandle" title="Drag to reorder" aria-label="Drag ${esc(r.title)}">≡</span>
554
587
  <span class="qrank">${i + 1}</span>
555
588
  <span class="qtitle">${esc(r.title)}${r.summary ? `<span class="qsum">${esc(r.summary)}</span>` : ""}</span>
556
- <span class="chip ${r.state.startsWith("waits") ? "c-wait" : "c-ready"}">${esc(r.state)}</span>
589
+ ${r.holder ? `<span class="chip c-held">Main ${esc(r.holder)}</span>` : ""}<span class="chip ${r.state.startsWith("waits") ? "c-wait" : "c-ready"}">${esc(r.state)}</span>
557
590
  <span class="qbtns"><button type="button" class="qmove" data-move="top">↑ top</button><button type="button" class="qmove" data-move="up">↑</button><button type="button" class="qmove" data-move="down">↓</button></span>
558
591
  </li>`,
559
592
  )
@@ -1255,7 +1288,7 @@ export function renderPage(cfg: Config, data: PageData, params: URLSearchParams,
1255
1288
  const machine = data.machine === null ? na("Machine") : machineHtml(cfg, data.machine);
1256
1289
  const body =
1257
1290
  tab === "now"
1258
- ? `${messageCard(data.messages)}
1291
+ ? `${messageCard(data.messages, runningMains(cfg))}
1259
1292
  <h1>Today</h1>
1260
1293
  <p class="sub">What your agents did in the last 24 hours.</p>
1261
1294
  <div class="card">
@@ -1385,6 +1418,7 @@ details.bg ul{margin:4px 0 8px;padding-left:20px;color:var(--mut);font-size:13px
1385
1418
  .c-wait{background:color-mix(in srgb,var(--warn) 18%,transparent);color:var(--warn)}
1386
1419
  .c-run{background:color-mix(in srgb,var(--teal) 18%,transparent);color:var(--teal)}
1387
1420
  .c-ready{background:color-mix(in srgb,var(--mut) 15%,transparent);color:var(--mut)}
1421
+ .c-held{background:color-mix(in srgb,var(--acc) 15%,transparent);color:var(--acc)}
1388
1422
  .chip.bad{color:var(--red)}
1389
1423
  .qbtns{display:flex;gap:4px;flex-wrap:wrap;margin-left:auto}
1390
1424
  .qbtns button{min-height:32px;padding:2px 10px;font-size:12px;border-radius:999px;border:1px solid var(--bd);background:var(--card);color:var(--mut)}
@@ -1520,13 +1554,13 @@ function handleIncident(cfg: Config, fields: Record<string, string>, login: stri
1520
1554
  if (wantsJson) return jsonSent("incident-closed", receiptText("incident-closed", new URLSearchParams()));
1521
1555
  return redirect(sentTo(fields.tab ?? "", "sent=incident-closed"));
1522
1556
  }
1523
- storeOwnerMessage(`${id}: it's a bug — plan it`, login, []);
1557
+ storeOwnerMessage(`${id}: it's a bug — plan it`, login, [], "");
1524
1558
  if (wantsJson) return jsonSent("incident-bug", receiptText("incident-bug", new URLSearchParams()));
1525
1559
  return redirect(sentTo(fields.tab ?? "", "sent=incident-bug"));
1526
1560
  }
1527
1561
 
1528
1562
  /** Stores an owner message (text and images) under a new id and inboxes it for Main (P13/P14). */
1529
- function storeOwnerMessage(text: string, login: string, images: { bytes: Uint8Array; kind: string }[]): void {
1563
+ function storeOwnerMessage(text: string, login: string, images: { bytes: Uint8Array; kind: string }[], to: string): void {
1530
1564
  const ts = nowSec();
1531
1565
  // The dir name starts with a whole-second ts: the sweep and the image route both parse it.
1532
1566
  const id = `${Math.floor(ts)}-${randomUUID().slice(0, 6)}`;
@@ -1538,21 +1572,23 @@ function storeOwnerMessage(text: string, login: string, images: { bytes: Uint8Ar
1538
1572
  writeFileSync(`${dir}/${name}`, images[i]!.bytes);
1539
1573
  names.push(name);
1540
1574
  }
1541
- writeFileSync(`${dir}/message.json`, `${JSON.stringify({ ts, text, login, images: names })}\n`);
1575
+ writeFileSync(`${dir}/message.json`, `${JSON.stringify({ ts, text, login, to, images: names })}\n`);
1542
1576
  mkdirSync(stateDirPath(), { recursive: true });
1543
1577
  // The text stays out of owner-inbox.jsonl; Main reads message.json through the id (P14).
1544
- appendFileSync(inboxPath(), `${JSON.stringify({ ts, kind: "message", id, login })}\n`);
1578
+ appendFileSync(inboxPath(), `${JSON.stringify({ ts, kind: "message", id, login, to })}\n`);
1545
1579
  }
1546
1580
 
1547
1581
  // ---- POST /message (plan P13): the owner's one-way note plus images, inboxed by id ----
1548
1582
 
1549
- async function handleMessage(req: Request, login: string, wantsJson: boolean): Promise<Response> {
1583
+ async function handleMessage(req: Request, cfg: Config, login: string, wantsJson: boolean): Promise<Response> {
1550
1584
  sweepOwnerMessages(nowSec());
1551
1585
  const form = await req.formData();
1552
1586
  let text = "";
1587
+ let toField = "";
1553
1588
  const files: File[] = [];
1554
1589
  for (const [key, value] of form.entries()) {
1555
1590
  if (key === "text" && typeof value === "string") text = value.trim();
1591
+ else if (key === "to" && typeof value === "string") toField = value;
1556
1592
  // A form sent with no file chosen still carries one empty, nameless file part (Bun parses it as a nameless Blob).
1557
1593
  else if (key === "images" && (value as unknown) instanceof Blob) {
1558
1594
  const part = value as unknown as File;
@@ -1571,7 +1607,10 @@ async function handleMessage(req: Request, login: string, wantsJson: boolean): P
1571
1607
  if (!kind) return fail("attachments must be PNG, JPEG, GIF or WEBP images — the type is read from the file itself");
1572
1608
  images.push({ bytes: data, kind });
1573
1609
  }
1574
- storeOwnerMessage(text, login, images);
1610
+ // P5: an `@<id>` prefix or the picker's to field names one Main; a stale name is refused before anything is stored.
1611
+ const pick = ownerMessageTarget(text, cfg, toField);
1612
+ if ("refuse" in pick) return fail(pick.refuse);
1613
+ storeOwnerMessage(text, login, images, pick.to);
1575
1614
  if (wantsJson) return jsonSent("message", receiptText("message", new URLSearchParams()));
1576
1615
  return redirect("/?sent=message");
1577
1616
  }
@@ -1816,7 +1855,7 @@ res = pageRes(cfg, source, url.searchParams, resultsBuild, pagesHost);
1816
1855
  // The page's script asks for JSON on every POST (P11b); a no-JS form post gets today's 303s.
1817
1856
  const wantsJson = (req.headers.get("accept") ?? "").includes("application/json");
1818
1857
  if (url.pathname === "/message") {
1819
- res = await handleMessage(req, login, wantsJson);
1858
+ res = await handleMessage(req, cfg, login, wantsJson);
1820
1859
  code = res.status;
1821
1860
  } else if (url.pathname === "/incident") {
1822
1861
  res = handleIncident(cfg, await fieldsOf(req), login, wantsJson);
@@ -11,6 +11,7 @@ import { checkDiagram } from "./diagram-check.ts";
11
11
  import { gitRaw } from "./proc.ts";
12
12
  import { recordPublish } from "./pages-expiry.ts";
13
13
  import { realTailscale, type Tailscale } from "./tailscale.ts";
14
+ import { checkEdited, setConfigKeys } from "./config-edit.ts";
14
15
  const HERE = dirname(fileURLToPath(import.meta.url));
15
16
  export const PAGES_UNIT_TEMPLATE = join(HERE, "../../templates/systemd/neurastream-pages.service");
16
17
  const DATA_MARK = "/* === DATA === */";
@@ -19,30 +20,13 @@ export interface RunnerResult { status: number | null; stderr: string; stdout?:
19
20
  export type Runner = (args: string[]) => RunnerResult;
20
21
  export const systemRunner: Runner = args => { const r = spawnSync("systemctl", args, { encoding:"utf8" }); return { status:r.status, stderr:r.stderr ?? "", stdout:r.stdout ?? "" }; };
21
22
  export interface Setup { home?: string; runner?: Runner; tailscale?: Tailscale }
22
- function editBlock(text: string | null, values: { enabled: boolean; port: number; dir: string }): string {
23
- const fresh = ["pages:", ` enabled: ${values.enabled}`, ` port: ${values.port}`, ` dir: "${values.dir.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`];
24
- if (text === null) return `${fresh.join("\n")}\n`;
25
- const lines = text.split("\n");
26
- let start = -1;
27
- for (let i = 0; i < lines.length; i++) if (/^pages\s*:(\s*(?:#.*)?)?$/.test(lines[i] ?? "")) { start = i; break; }
28
- if (start < 0) return `${text === "" || text.endsWith("\n") ? text : `${text}\n`}${fresh.join("\n")}\n`;
29
- let end = start + 1;
30
- while (end < lines.length && (lines[end] === "" || /^[ \t]/.test(lines[end]!))) end++;
31
- const setKey = (key: string, value: string): void => {
32
- const re = new RegExp(`^([ \\t]+)${key}\\s*:.*$`);
33
- for (let i = start + 1; i < end; i++) if (re.test(lines[i]!)) { lines[i] = lines[i]!.replace(re, `$1${key}: ${value}`); return; }
34
- let at = start + 1;
35
- for (let i = start + 1; i < end; i++) if (lines[i]!.trim() !== "") at = i + 1;
36
- lines.splice(at, 0, ` ${key}: ${value}`); end++;
37
- };
38
- setKey("enabled", String(values.enabled)); setKey("port", String(values.port)); setKey("dir", `"${values.dir.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`);
39
- return lines.join("\n");
40
- }
41
23
  export function pagesOn(opts: Setup & { port?: number; dir?: string }): number {
42
24
  const home = opts.home ?? homedir(), runner = opts.runner ?? systemRunner, ts = opts.tailscale ?? realTailscale;
43
25
  const file = configFile(home), old = existsSync(file) ? readFileSync(file,"utf8") : null; const cfg = loadConfig({ home });
44
26
  const port = opts.port ?? cfg.pages.port, dir = opts.dir ?? cfg.pages.dir;
45
- const edited = editBlock(old, { enabled:true, port, dir }); mkdirSync(dirname(file), { recursive:true }); writeFileSync(file, edited);
27
+ const edited = setConfigKeys(old, { "pages.enabled": "true", "pages.port": String(port), "pages.dir": JSON.stringify(dir) });
28
+ if (!checkEdited(edited, home, msg => console.error(msg))) return 1;
29
+ mkdirSync(dirname(file), { recursive:true }); writeFileSync(file, edited);
46
30
  mkdirSync(dir, { recursive:true });
47
31
  mkdirSync(join(home,".config/systemd/user"),{recursive:true}); copyFileSync(PAGES_UNIT_TEMPLATE, join(home,".config/systemd/user/neurastream-pages.service"));
48
32
  for (const args of [["--user","daemon-reload"],["--user","enable","--now","neurastream-pages"]]) { const r=runner(args); if(r.status!==0){console.error(r.stderr);return 1;} }
@@ -50,7 +34,8 @@ export function pagesOn(opts: Setup & { port?: number; dir?: string }): number {
50
34
  }
51
35
  export function pagesOff(opts: Setup = {}): number {
52
36
  const home=opts.home ?? homedir(), runner=opts.runner ?? systemRunner, file=configFile(home), old=existsSync(file)?readFileSync(file,"utf8"):null;
53
- const cfg=loadConfig({home}); writeFileSync(file,editBlock(old,{enabled:false,port:cfg.pages.port,dir:cfg.pages.dir}));
37
+ const cfg=loadConfig({home}); const edited=setConfigKeys(old,{"pages.enabled":"false","pages.port":String(cfg.pages.port),"pages.dir":JSON.stringify(cfg.pages.dir)});
38
+ if(!checkEdited(edited,home,msg=>console.error(msg))) return 1; writeFileSync(file,edited);
54
39
  const r=runner(["--user","stop","neurastream-pages"]); if(r.status!==0){console.error(r.stderr);return 1;} return 0;
55
40
  }
56
41
  /**