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.
- package/README.md +31 -0
- package/package.json +1 -1
- package/src/adapters/index.ts +7 -0
- package/src/adapters/omp/adapter.ts +1 -0
- package/src/adapters/omp/doctor.ts +4 -2
- package/src/adapters/omp/index.ts +84 -16
- package/src/adapters/omp/launch.ts +105 -52
- package/src/cli/claim.ts +79 -0
- package/src/cli/commands.ts +4 -0
- package/src/cli/config-set.ts +56 -0
- package/src/cli/dispatch.ts +12 -0
- package/src/cli/init.ts +6 -4
- package/src/cli/setup.ts +327 -0
- package/src/cli/ui.ts +4 -2
- package/src/core/brief-lint.ts +13 -6
- package/src/core/claims.ts +140 -0
- package/src/core/config-edit.ts +111 -0
- package/src/core/config.ts +3 -0
- package/src/core/guards.ts +128 -9
- package/src/core/notify.ts +2 -1
- package/src/core/owner-ui.ts +59 -20
- package/src/core/pages-setup.ts +6 -21
- package/src/core/queue/lib.ts +23 -4
- package/src/core/queue-check.ts +5 -2
- package/src/core/queue-close.ts +6 -0
- package/src/core/rollover.ts +3 -3
- package/src/core/setup-detect.ts +120 -0
- package/src/core/tailscale.ts +20 -0
- package/src/core/trace-actions.ts +9 -0
- package/src/core/ui-setup.ts +52 -64
- package/templates/config.yml +127 -126
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// `neurastream config set|get|list <key> [value]` (plan 20261028_2356 P1b): the non-interactive door
|
|
2
|
+
// to the generic config editor (src/core/config-edit.ts). Keys are the leaf paths of
|
|
3
|
+
// templates/config.yml, so a typo is refused and never written. A set writes through the same
|
|
4
|
+
// line-based editor and is refused, with the file untouched, when the result would not load.
|
|
5
|
+
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { dirname } from "node:path";
|
|
9
|
+
import { checkEdited, leafKeys, setConfigKeys, valueAt, yamlValue } from "../core/config-edit.ts";
|
|
10
|
+
import { TEMPLATE_PATH, configFile, loadConfig } from "../core/config.ts";
|
|
11
|
+
|
|
12
|
+
const VALID_KEYS = leafKeys(Bun.YAML.parse(readFileSync(TEMPLATE_PATH, "utf8")));
|
|
13
|
+
|
|
14
|
+
export function runConfigKeys(args: string[], home: string = homedir()): number {
|
|
15
|
+
const [verb, key, raw] = args;
|
|
16
|
+
try {
|
|
17
|
+
if (verb === "list") {
|
|
18
|
+
const cfg = loadConfig({ home });
|
|
19
|
+
for (const k of VALID_KEYS) {
|
|
20
|
+
const v = valueAt(cfg, k);
|
|
21
|
+
console.log(`${k} = ${Array.isArray(v) ? JSON.stringify(v) : String(v)}`);
|
|
22
|
+
}
|
|
23
|
+
return 0;
|
|
24
|
+
}
|
|
25
|
+
if (key === undefined || !VALID_KEYS.includes(key)) {
|
|
26
|
+
console.error(`neurastream config ${verb ?? ""}: unknown key ${key ?? "(none)"}; valid keys: ${VALID_KEYS.join(", ")}`);
|
|
27
|
+
return 1;
|
|
28
|
+
}
|
|
29
|
+
if (verb === "get") {
|
|
30
|
+
const v = valueAt(loadConfig({ home }), key);
|
|
31
|
+
console.log(Array.isArray(v) ? JSON.stringify(v) : String(v));
|
|
32
|
+
return 0;
|
|
33
|
+
}
|
|
34
|
+
if (verb !== "set") {
|
|
35
|
+
console.error("usage: neurastream config set|get|list [key] [value]");
|
|
36
|
+
return 1;
|
|
37
|
+
}
|
|
38
|
+
const parsed: unknown = raw === undefined ? null : Bun.YAML.parse(raw);
|
|
39
|
+
if (parsed === null || parsed === undefined || (typeof parsed === "object" && !Array.isArray(parsed))) {
|
|
40
|
+
console.error(`neurastream config set ${key}: give a scalar or a list (e.g. 7788, true, '["a", "b"]')`);
|
|
41
|
+
return 1;
|
|
42
|
+
}
|
|
43
|
+
// Lists in flow style on one line ([a, b]); scalars as JSON, which is valid YAML.
|
|
44
|
+
const text = yamlValue(parsed);
|
|
45
|
+
const file = configFile(home);
|
|
46
|
+
const original = existsSync(file) ? readFileSync(file, "utf8") : null;
|
|
47
|
+
const edited = setConfigKeys(original, { [key]: text });
|
|
48
|
+
if (!checkEdited(edited, home, (line) => console.error(line))) return 1;
|
|
49
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
50
|
+
writeFileSync(file, edited);
|
|
51
|
+
return 0;
|
|
52
|
+
} catch (err) {
|
|
53
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
54
|
+
return 1;
|
|
55
|
+
}
|
|
56
|
+
}
|
package/src/cli/dispatch.ts
CHANGED
|
@@ -15,11 +15,13 @@ import { applyQueueEnv } from "../core/queue/env.ts";
|
|
|
15
15
|
import { getAdapter } from "../adapters/index.ts";
|
|
16
16
|
import { GUARD_USAGE, runGuard } from "./guard.ts";
|
|
17
17
|
import { runInit } from "./init.ts";
|
|
18
|
+
import { realSetupDeps, runSetup } from "./setup.ts";
|
|
18
19
|
import { PORTED, runMain, runPorted } from "./commands.ts";
|
|
19
20
|
import { runMetrics } from "./metrics.ts";
|
|
20
21
|
import { runIncident } from "./incident.ts";
|
|
21
22
|
import { runTraces } from "./traces.ts";
|
|
22
23
|
import { runUi } from "./ui.ts";
|
|
24
|
+
import { runConfigKeys } from "./config-set.ts";
|
|
23
25
|
import { runDiagram } from "./diagram.ts";
|
|
24
26
|
import { runNotes } from "./notes.ts";
|
|
25
27
|
import { runPages } from "./pages.ts";
|
|
@@ -63,6 +65,9 @@ export function helpText(): string {
|
|
|
63
65
|
" create config, index, notes, blockers, queue template, state dirs",
|
|
64
66
|
" (--agent-dir: keep an existing index/notes/blockers dir)",
|
|
65
67
|
" (--allow a,b: subagents allowed to spawn; on a terminal init asks instead)",
|
|
68
|
+
" neurastream setup [--yes]",
|
|
69
|
+
" guided first run: detect this machine, ask in groups, install, doctor",
|
|
70
|
+
" (--yes: take the detected settings without asking)",
|
|
66
71
|
" neurastream adapter install omp",
|
|
67
72
|
" link the omp extension under this HOME",
|
|
68
73
|
" neurastream uninstall [--purge] [--yes]",
|
|
@@ -74,12 +79,17 @@ export function helpText(): string {
|
|
|
74
79
|
" neurastream redact filter stdin through the secret redactor: stdout gets the text,",
|
|
75
80
|
" stderr the hit summary (types and counts only)",
|
|
76
81
|
" neurastream queue migrate fold the old repo INDEX.md files into the one main index",
|
|
82
|
+
" neurastream claim next|list|release <plan> [--force]",
|
|
83
|
+
" claim the highest free plan for this Main, list the holders,",
|
|
84
|
+
" free this Main's claim; --force frees another Main's claim —",
|
|
85
|
+
" the owner's move in a terminal (the guard refuses agents)",
|
|
77
86
|
" neurastream queue add <plan.md> [--rank N]",
|
|
78
87
|
" add a plan to the index (append, or insert at 1-based rank N)",
|
|
79
88
|
" neurastream queue move <plan.md> <rank>",
|
|
80
89
|
" move a listed plan to rank N; the index file itself is 0444,",
|
|
81
90
|
" these two commands are the only agent writes to it",
|
|
82
91
|
" neurastream config [--json] print the merged config (defaults + file + env)",
|
|
92
|
+
" neurastream config set|get|list <key> [value] read or write one key (ui.port, paths.work_roots, ...)",
|
|
83
93
|
" neurastream guard <event> --json",
|
|
84
94
|
` (${GUARD_USAGE.slice(GUARD_USAGE.indexOf("(") + 1, -1)})`,
|
|
85
95
|
" neurastream main [args] run omp under the launcher (automatic session rollover)",
|
|
@@ -133,6 +143,8 @@ export async function run(cmd: string, args: string[]): Promise<number> {
|
|
|
133
143
|
if (cmd === "notes") return runNotes(args);
|
|
134
144
|
if (cmd === "diagram") return runDiagram(args);
|
|
135
145
|
if (cmd === "adapter") return getAdapter().install(args);
|
|
146
|
+
if (cmd === "setup") return runSetup(args, realSetupDeps(async () => runNotify(["test"])));
|
|
147
|
+
if (cmd === "config" && ["set", "get", "list"].includes(args[0] ?? "")) return runConfigKeys(args);
|
|
136
148
|
if (cmd === "config") {
|
|
137
149
|
try {
|
|
138
150
|
const cfg = loadConfig();
|
package/src/cli/init.ts
CHANGED
|
@@ -71,9 +71,11 @@ function configText(home: string, invoked: string, agentDir?: string): string {
|
|
|
71
71
|
text = text.replace(AGENT_DIR_KEYS, (_m, key: string) => `${key}${yamlQuote(agent).slice(0, -1)}`);
|
|
72
72
|
}
|
|
73
73
|
const protectedPaths = [...installedBins(home, invoked), `${agent}/notes/`, `${agent}/blockers/`, `${agent}/queue/`];
|
|
74
|
-
const
|
|
75
|
-
|
|
76
|
-
|
|
74
|
+
const items = protectedPaths.map(p => ` - ${yamlQuote(p)}`);
|
|
75
|
+
const placeholder = /^ protected: \[\].*$/m;
|
|
76
|
+
if (!placeholder.test(text)) throw new Error("templates/config.yml has no protected placeholder");
|
|
77
|
+
// The header stays a bare ` protected:`: install, uninstall and the guards read it in that form.
|
|
78
|
+
return text.replace(placeholder, [" protected:", ...items].join("\n"));
|
|
77
79
|
}
|
|
78
80
|
|
|
79
81
|
function putFile(dest: string, body: string, mode: number, created: string[], unchanged: string[]): void {
|
|
@@ -162,7 +164,7 @@ export function printInit(result: InitResult): void {
|
|
|
162
164
|
}
|
|
163
165
|
|
|
164
166
|
/** One line from stdin, read synchronously; a terminal hands over a line at a time. */
|
|
165
|
-
function askLine(prompt: string): string {
|
|
167
|
+
export function askLine(prompt: string): string {
|
|
166
168
|
process.stdout.write(prompt);
|
|
167
169
|
const buf = Buffer.alloc(4096);
|
|
168
170
|
const n = readSync(0, buf, 0, buf.length, null);
|
package/src/cli/setup.ts
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
// `neurastream setup [--yes]` (plan 20261028_2356 P4): the guided first run. It shows what this
|
|
2
|
+
// machine has (src/core/setup-detect.ts), lays out the home (initHome), asks in groups, writes each
|
|
3
|
+
// group's answers through the one config editor (src/core/config-edit.ts), then runs the adapter
|
|
4
|
+
// install and doctor. Every answer is proven to load before it is kept; --yes takes the proposals
|
|
5
|
+
// without asking. SetupDeps carries the terminal, the seams, and the install/doctor runs, so tests
|
|
6
|
+
// drive the whole flow without a real terminal, systemctl or Tailscale.
|
|
7
|
+
|
|
8
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { homedir } from "node:os";
|
|
10
|
+
import { getAdapter, harnessBins } from "../adapters/index.ts";
|
|
11
|
+
import { TEMPLATE_PATH, configFile } from "../core/config.ts";
|
|
12
|
+
import { checkEdited, leafKeys, setConfigKeys, valueAt, yamlValue } from "../core/config-edit.ts";
|
|
13
|
+
import { pagesDoctor } from "../core/pages-doctor.ts";
|
|
14
|
+
import { detect, realSeams, type SetupFacts, type SetupSeams } from "../core/setup-detect.ts";
|
|
15
|
+
import { invalidSlugs } from "../core/subagents.ts";
|
|
16
|
+
import { TAILSCALE_MISSING, TAILSCALE_STOPPED } from "../core/ui-setup.ts";
|
|
17
|
+
import { askLine, initHome } from "./init.ts";
|
|
18
|
+
|
|
19
|
+
export interface SetupDeps {
|
|
20
|
+
home: string;
|
|
21
|
+
env: NodeJS.ProcessEnv;
|
|
22
|
+
invoked: string;
|
|
23
|
+
terminal: boolean;
|
|
24
|
+
ask: (question: string) => string;
|
|
25
|
+
seams: SetupSeams;
|
|
26
|
+
install: () => number;
|
|
27
|
+
doctor: () => number;
|
|
28
|
+
say: (line: string) => void;
|
|
29
|
+
// `neurastream notify test`, injected by dispatch (setup.ts does not import dispatch.ts).
|
|
30
|
+
notifyTest: () => Promise<number>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The production deps: the real home, terminal, PATH, Tailscale, adapter install and doctor. */
|
|
34
|
+
export function realSetupDeps(notifyTest: () => Promise<number>): SetupDeps {
|
|
35
|
+
const home = homedir();
|
|
36
|
+
return {
|
|
37
|
+
home,
|
|
38
|
+
env: process.env,
|
|
39
|
+
invoked: process.argv[1] ?? "",
|
|
40
|
+
terminal: process.stdin.isTTY === true,
|
|
41
|
+
ask: askLine,
|
|
42
|
+
seams: realSeams(harnessBins(), home, process.env),
|
|
43
|
+
install: () => getAdapter().install(["install", getAdapter().name]),
|
|
44
|
+
doctor: () => {
|
|
45
|
+
for (const warning of pagesDoctor(home)) console.warn(`warning: ${warning}`);
|
|
46
|
+
return getAdapter().doctor();
|
|
47
|
+
},
|
|
48
|
+
say: (line) => console.log(line),
|
|
49
|
+
notifyTest,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Trailing `# comment` of each leaf key, by dotted path. The indentation stack gives a key's path
|
|
54
|
+
// from its parents' keys, so a nested key never takes a neighbour's comment.
|
|
55
|
+
export function templateComments(text: string): Record<string, string> {
|
|
56
|
+
const out: Record<string, string> = {};
|
|
57
|
+
const stack: { indent: number; key: string }[] = [];
|
|
58
|
+
for (const line of text.split("\n")) {
|
|
59
|
+
const m = /^( *)([A-Za-z_][\w-]*):(.*)$/.exec(line);
|
|
60
|
+
if (!m) continue;
|
|
61
|
+
const indent = m[1]!.length;
|
|
62
|
+
while (stack.length > 0 && stack[stack.length - 1]!.indent >= indent) stack.pop();
|
|
63
|
+
stack.push({ indent, key: m[2]! });
|
|
64
|
+
const comment = /#\s*(.*)$/.exec(m[3]!)?.[1]?.trim() ?? "";
|
|
65
|
+
if (comment !== "") out[stack.map((s) => s.key).join(".")] = comment;
|
|
66
|
+
}
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const TEMPLATE_TEXT = readFileSync(TEMPLATE_PATH, "utf8");
|
|
71
|
+
const TEMPLATE = Bun.YAML.parse(TEMPLATE_TEXT);
|
|
72
|
+
const COMMENTS = templateComments(TEMPLATE_TEXT);
|
|
73
|
+
const VALID_KEYS = leafKeys(TEMPLATE);
|
|
74
|
+
const TIERS = ["strict", "opinionated", "full"];
|
|
75
|
+
|
|
76
|
+
// The asked groups, in order. Keys outside them form the advanced walk.
|
|
77
|
+
const GROUPS: { name: string; keys: string[] }[] = [
|
|
78
|
+
{ name: "Paths", keys: ["paths.work_roots"] },
|
|
79
|
+
{ name: "Harness", keys: ["harness"] },
|
|
80
|
+
{ name: "Autonomy", keys: ["autonomy.tier", "autonomy.strict_edit_limit", "autonomy.go_minutes", "autonomy.go_phrase"] },
|
|
81
|
+
{ name: "Phone page", keys: ["ui.enabled", "ui.owner_login"] },
|
|
82
|
+
{ name: "Static pages", keys: ["pages.enabled", "pages.port", "pages.dir"] },
|
|
83
|
+
{ name: "Notify", keys: ["notify.discord_webhook_file", "notify.slack_webhook_file"] },
|
|
84
|
+
{ name: "Secrets", keys: ["secrets.redact", "secrets.known_value_files", "secrets.proxy"] },
|
|
85
|
+
{ name: "Machine", keys: ["machine.load_over_cores", "machine.avail_min_mb", "machine.disk_min_gb"] },
|
|
86
|
+
{ name: "Session rollover", keys: ["rollover.enabled", "rollover.max_session_mb", "rollover.exit_grace_s"] },
|
|
87
|
+
];
|
|
88
|
+
|
|
89
|
+
type Kind = "bool" | "num" | "list" | "str";
|
|
90
|
+
interface Change {
|
|
91
|
+
key: string;
|
|
92
|
+
old: unknown;
|
|
93
|
+
next: unknown;
|
|
94
|
+
}
|
|
95
|
+
interface Ctx {
|
|
96
|
+
deps: SetupDeps;
|
|
97
|
+
facts: SetupFacts;
|
|
98
|
+
fresh: boolean;
|
|
99
|
+
file: string;
|
|
100
|
+
text: string;
|
|
101
|
+
changed: Change[];
|
|
102
|
+
// none: ask every key. group: accept proposals until this group ends (s). all: accept every proposal (q, --yes).
|
|
103
|
+
auto: "none" | "group" | "all";
|
|
104
|
+
// set when the Notify group was asked and a webhook file is set; runSetup then offers the test.
|
|
105
|
+
testOffer: boolean;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export async function runSetup(args: string[], deps: SetupDeps): Promise<number> {
|
|
109
|
+
const yes = args.includes("--yes");
|
|
110
|
+
if (!yes && !deps.terminal) {
|
|
111
|
+
deps.say("neurastream setup needs a terminal or --yes");
|
|
112
|
+
return 2;
|
|
113
|
+
}
|
|
114
|
+
const facts = detect(deps.seams);
|
|
115
|
+
printFacts(deps, facts);
|
|
116
|
+
const ctx: Ctx = {
|
|
117
|
+
deps,
|
|
118
|
+
facts,
|
|
119
|
+
fresh: facts.current === null,
|
|
120
|
+
file: configFile(deps.home),
|
|
121
|
+
text: "",
|
|
122
|
+
changed: [],
|
|
123
|
+
auto: yes ? "all" : "none",
|
|
124
|
+
testOffer: false,
|
|
125
|
+
};
|
|
126
|
+
const allow = yes ? [] : askSubagents(deps);
|
|
127
|
+
const made = initHome(deps.home, { invoked: deps.invoked, env: deps.env, allow: allow.length > 0 ? allow : undefined });
|
|
128
|
+
deps.say(`layout: created ${made.created.length}, kept ${made.unchanged.length}`);
|
|
129
|
+
ctx.text = readFileSync(ctx.file, "utf8");
|
|
130
|
+
for (const group of GROUPS) {
|
|
131
|
+
if (runGroup(ctx, group.name, group.keys) !== 0) return 1;
|
|
132
|
+
}
|
|
133
|
+
if (ctx.auto === "none") {
|
|
134
|
+
const advanced = VALID_KEYS.filter((k) => !GROUPS.some((g) => g.keys.includes(k)));
|
|
135
|
+
const open = deps.ask(`Show the ${advanced.length} advanced settings? [y/N]: `).trim();
|
|
136
|
+
if (/^y(es)?$/i.test(open) && runGroup(ctx, "Advanced", advanced) !== 0) return 1;
|
|
137
|
+
}
|
|
138
|
+
if (ctx.testOffer) await offerTest(ctx);
|
|
139
|
+
const installed = deps.install();
|
|
140
|
+
if (installed !== 0) {
|
|
141
|
+
deps.say("adapter install failed");
|
|
142
|
+
return installed;
|
|
143
|
+
}
|
|
144
|
+
const doctor = deps.doctor();
|
|
145
|
+
printChanges(deps, ctx.changed);
|
|
146
|
+
if (doctor === 0) deps.say("Next: neurastream main");
|
|
147
|
+
return doctor;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function printFacts(deps: SetupDeps, facts: SetupFacts): void {
|
|
151
|
+
deps.say("Detected on this machine:");
|
|
152
|
+
deps.say(` work roots: ${facts.workRoots.join(", ") || "none"}`);
|
|
153
|
+
deps.say(` harnesses on PATH: ${facts.harnesses.join(", ") || "none"}`);
|
|
154
|
+
deps.say(` tailscale: ${facts.tailscale.state}`);
|
|
155
|
+
deps.say(` secretgate: ${facts.secretgate ? "on PATH" : "not on PATH"}`);
|
|
156
|
+
deps.say(` machine: ${facts.machine.cores} cores, ${facts.machine.ramMb} MB RAM, ${facts.machine.diskFreeGb} GB free disk`);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function askSubagents(deps: SetupDeps): string[] {
|
|
160
|
+
for (;;) {
|
|
161
|
+
const names = deps.ask("Subagents allowed to spawn (comma-separated names, empty = none): ")
|
|
162
|
+
.split(",")
|
|
163
|
+
.map((s) => s.trim())
|
|
164
|
+
.filter((s) => s !== "");
|
|
165
|
+
const bad = invalidSlugs(names);
|
|
166
|
+
if (bad.length === 0) return names;
|
|
167
|
+
deps.say(` not a valid name: ${bad.join(", ")}`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function printChanges(deps: SetupDeps, changed: Change[]): void {
|
|
172
|
+
if (changed.length === 0) {
|
|
173
|
+
deps.say("No settings changed.");
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
deps.say("Changed:");
|
|
177
|
+
for (const c of changed) deps.say(` ${c.key}: ${JSON.stringify(c.old)} → ${JSON.stringify(c.next)}`);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// Asks one group, then writes the changed keys once through the editor. Returns non-zero only
|
|
181
|
+
// when the edited file would not load (nothing is written then). A Notify group the owner was
|
|
182
|
+
// asked, with a webhook file set, sets ctx.testOffer so runSetup offers the test.
|
|
183
|
+
function runGroup(ctx: Ctx, name: string, keys: string[]): number {
|
|
184
|
+
ctx.deps.say(`\n${name}`);
|
|
185
|
+
const now = Bun.YAML.parse(ctx.text);
|
|
186
|
+
const picks: Record<string, unknown> = {};
|
|
187
|
+
const asking = ctx.auto === "none";
|
|
188
|
+
for (const key of keys) {
|
|
189
|
+
if (key === "ui.owner_login" && picks["ui.enabled"] !== true) continue;
|
|
190
|
+
const proposed = proposal(ctx, key, valueAt(now, key));
|
|
191
|
+
let value = askKey(ctx, key, kindOf(key), proposed);
|
|
192
|
+
if (key === "ui.enabled" && value === true && !phoneReady(ctx)) value = false;
|
|
193
|
+
picks[key] = value;
|
|
194
|
+
}
|
|
195
|
+
if (asking && Object.keys(picks).some((key) => key.startsWith("notify.") && picks[key] !== "")) {
|
|
196
|
+
ctx.testOffer = true;
|
|
197
|
+
}
|
|
198
|
+
if (ctx.auto === "group") ctx.auto = "none";
|
|
199
|
+
const changes: Record<string, string> = {};
|
|
200
|
+
for (const key of Object.keys(picks)) {
|
|
201
|
+
const old = valueAt(now, key);
|
|
202
|
+
if (JSON.stringify(old) === JSON.stringify(picks[key])) continue;
|
|
203
|
+
changes[key] = yamlValue(picks[key]);
|
|
204
|
+
ctx.changed.push({ key, old, next: picks[key] });
|
|
205
|
+
}
|
|
206
|
+
if (Object.keys(changes).length === 0) return 0;
|
|
207
|
+
const edited = setConfigKeys(ctx.text, changes);
|
|
208
|
+
if (!checkEdited(edited, ctx.deps.home, (line) => ctx.deps.say(line))) return 1;
|
|
209
|
+
writeFileSync(ctx.file, edited);
|
|
210
|
+
ctx.text = edited;
|
|
211
|
+
return 0;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// The notify test offer. A yes runs `neurastream notify test` through the injected seam. A failed
|
|
215
|
+
// test is printed by that command and setup goes on: the webhook is the owner's to fix.
|
|
216
|
+
async function offerTest(ctx: Ctx): Promise<void> {
|
|
217
|
+
const answer = ctx.deps.ask("send a test message now? [y/N]: ").trim();
|
|
218
|
+
if (/^y(es)?$/i.test(answer)) await ctx.deps.notifyTest();
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// The value offered for Enter. A fresh home offers what this machine has; a re-run offers the
|
|
222
|
+
// current config, so a setting the owner already chose never moves on its own.
|
|
223
|
+
function proposal(ctx: Ctx, key: string, current: unknown): unknown {
|
|
224
|
+
if (!ctx.fresh) return current;
|
|
225
|
+
const fromFacts: Record<string, unknown> = {
|
|
226
|
+
"paths.work_roots": ctx.facts.workRoots,
|
|
227
|
+
harness: ctx.facts.harnesses[0],
|
|
228
|
+
"machine.load_over_cores": ctx.facts.proposed.load_over_cores,
|
|
229
|
+
"machine.avail_min_mb": ctx.facts.proposed.avail_min_mb,
|
|
230
|
+
"machine.disk_min_gb": ctx.facts.proposed.disk_min_gb,
|
|
231
|
+
};
|
|
232
|
+
return fromFacts[key] ?? current;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function kindOf(key: string): Kind {
|
|
236
|
+
const t = valueAt(TEMPLATE, key);
|
|
237
|
+
if (typeof t === "boolean") return "bool";
|
|
238
|
+
if (typeof t === "number") return "num";
|
|
239
|
+
if (Array.isArray(t)) return "list";
|
|
240
|
+
return "str";
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function askKey(ctx: Ctx, key: string, kind: Kind, proposed: unknown): unknown {
|
|
244
|
+
if (ctx.auto !== "none") return proposed;
|
|
245
|
+
const comment = COMMENTS[key] ?? "";
|
|
246
|
+
for (;;) {
|
|
247
|
+
const raw = ctx.deps
|
|
248
|
+
.ask(`${key}: ${comment} [${yamlValue(proposed)}] (Enter keeps; s keeps the rest of this group; q keeps the rest): `)
|
|
249
|
+
.trim();
|
|
250
|
+
if (raw === "") return proposed;
|
|
251
|
+
if (raw === "s" || raw === "q") {
|
|
252
|
+
ctx.auto = raw === "s" ? "group" : "all";
|
|
253
|
+
return proposed;
|
|
254
|
+
}
|
|
255
|
+
const parsed = parseAnswer(kind, raw);
|
|
256
|
+
if ("error" in parsed) {
|
|
257
|
+
ctx.deps.say(` ${parsed.error}`);
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
const problem = validate(ctx, key, parsed.value);
|
|
261
|
+
if (problem !== null) {
|
|
262
|
+
ctx.deps.say(` ${problem}`);
|
|
263
|
+
continue;
|
|
264
|
+
}
|
|
265
|
+
return parsed.value;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function parseAnswer(kind: Kind, raw: string): { value: unknown } | { error: string } {
|
|
270
|
+
if (kind === "bool") {
|
|
271
|
+
if (/^(true|yes|y|on)$/i.test(raw)) return { value: true };
|
|
272
|
+
if (/^(false|no|n|off)$/i.test(raw)) return { value: false };
|
|
273
|
+
return { error: "answer yes or no" };
|
|
274
|
+
}
|
|
275
|
+
if (kind === "num") {
|
|
276
|
+
const n = Number(raw);
|
|
277
|
+
return Number.isFinite(n) ? { value: n } : { error: "answer a number" };
|
|
278
|
+
}
|
|
279
|
+
if (kind === "list") {
|
|
280
|
+
if (!raw.startsWith("[")) return { value: raw.split(",").map((s) => s.trim()).filter((s) => s !== "") };
|
|
281
|
+
try {
|
|
282
|
+
const list: unknown = Bun.YAML.parse(raw);
|
|
283
|
+
if (Array.isArray(list) && list.every((x) => typeof x === "string")) return { value: list };
|
|
284
|
+
} catch {
|
|
285
|
+
// not YAML: reported below
|
|
286
|
+
}
|
|
287
|
+
return { error: "answer a list of strings, e.g. [\"a\", \"b\"] or a, b" };
|
|
288
|
+
}
|
|
289
|
+
return { value: raw };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// Why an answer is refused, or null. The file must load with the answer in place (checkEdited),
|
|
293
|
+
// and the named keys must hold values the setup understands.
|
|
294
|
+
function validate(ctx: Ctx, key: string, value: unknown): string | null {
|
|
295
|
+
const problem = rule(ctx, key, value);
|
|
296
|
+
if (problem !== null) return problem;
|
|
297
|
+
const messages: string[] = [];
|
|
298
|
+
const candidate = setConfigKeys(ctx.text, { [key]: yamlValue(value) });
|
|
299
|
+
return checkEdited(candidate, ctx.deps.home, (line) => messages.push(line)) ? null : messages.join("\n");
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function rule(ctx: Ctx, key: string, value: unknown): string | null {
|
|
303
|
+
if (key === "autonomy.tier" && !TIERS.includes(String(value))) return `autonomy.tier must be ${TIERS.join(", ")}`;
|
|
304
|
+
if (key === "harness" && !ctx.deps.seams.harnesses.some((h) => h.name === value)) {
|
|
305
|
+
return `harness must be one of: ${ctx.deps.seams.harnesses.map((h) => h.name).join(", ")}`;
|
|
306
|
+
}
|
|
307
|
+
if (key === "secrets.proxy" && value === "secretgate" && !ctx.facts.secretgate) return "secretgate is not on PATH";
|
|
308
|
+
if (key === "secrets.proxy" && value !== "none" && value !== "secretgate") return "secrets.proxy must be none or secretgate";
|
|
309
|
+
return null;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// The phone page needs a running tailnet. Without one the page stays off and the setup says why.
|
|
313
|
+
function phoneReady(ctx: Ctx): boolean {
|
|
314
|
+
const tailscale = ctx.deps.seams.tailscale;
|
|
315
|
+
const state = tailscale.state();
|
|
316
|
+
if (state === "missing") {
|
|
317
|
+
ctx.deps.say(TAILSCALE_MISSING);
|
|
318
|
+
return false;
|
|
319
|
+
}
|
|
320
|
+
if (state === "stopped") {
|
|
321
|
+
ctx.deps.say(TAILSCALE_STOPPED);
|
|
322
|
+
return false;
|
|
323
|
+
}
|
|
324
|
+
const logins = tailscale.logins() ?? [];
|
|
325
|
+
if (logins.length > 0) ctx.deps.say(` logins on this tailnet: ${logins.join(", ")}`);
|
|
326
|
+
return true;
|
|
327
|
+
}
|
package/src/cli/ui.ts
CHANGED
|
@@ -10,7 +10,7 @@ import { beat, errorLine } from "../core/heartbeat.ts";
|
|
|
10
10
|
import { startOwnerUi, type OwnerUiOptions, type OwnerUiServer } from "../core/owner-ui.ts";
|
|
11
11
|
import { applyQueueEnv } from "../core/queue/env.ts";
|
|
12
12
|
import { realTailscale, type Tailscale } from "../core/tailscale.ts";
|
|
13
|
-
import { uiOff, uiOn, type Runner } from "../core/ui-setup.ts";
|
|
13
|
+
import { systemTerminal, uiOff, uiOn, type Runner } from "../core/ui-setup.ts";
|
|
14
14
|
|
|
15
15
|
export interface UiDeps {
|
|
16
16
|
/** The merged config. Default: loadConfig(). */
|
|
@@ -56,7 +56,9 @@ function runUiSetup(args: string[], deps: UiDeps): number {
|
|
|
56
56
|
console.error("neurastream ui on: --login <tailscale login> is required — e.g. neurastream ui on --login me@example.com");
|
|
57
57
|
return 1;
|
|
58
58
|
}
|
|
59
|
-
|
|
59
|
+
// A question only on a terminal: scripted runs get the message and exit 1, no prompt.
|
|
60
|
+
const terminal = process.stdin.isTTY && process.stdout.isTTY ? systemTerminal : undefined;
|
|
61
|
+
return uiOn({ login, port, terminal, ...setup });
|
|
60
62
|
}
|
|
61
63
|
return uiOff(setup);
|
|
62
64
|
}
|
package/src/core/brief-lint.ts
CHANGED
|
@@ -36,6 +36,18 @@ function escapeReg(s: string): string {
|
|
|
36
36
|
|
|
37
37
|
/** A scanned path without its trailing sentence punctuation (the path loop's cleaning). */
|
|
38
38
|
const clean = (raw: string): string => raw.replace(/[.,)]+$/, "");
|
|
39
|
+
/** Extract the paths a brief text names via cfg.brief.path_prefixes (the brief-lint way),
|
|
40
|
+
* reused by the D7 detector so a read the run's brief deliberately points at is not flagged.
|
|
41
|
+
*/
|
|
42
|
+
export function briefPaths(text: string, cfg: Config): string[] {
|
|
43
|
+
const paths = new Set<string>();
|
|
44
|
+
const scan = liveText(text);
|
|
45
|
+
for (const prefix of cfg.brief.path_prefixes) {
|
|
46
|
+
const re = new RegExp(`(${escapeReg(prefix)}[\\w./\\-]+)`, "g");
|
|
47
|
+
for (const hit of scan.matchAll(re)) paths.add(hit[1]!);
|
|
48
|
+
}
|
|
49
|
+
return [...paths].toSorted();
|
|
50
|
+
}
|
|
39
51
|
|
|
40
52
|
/** The same rules on a file on disk; the guard's spawn verdict lints the named plan files (plan 20261031_1207 P4). */
|
|
41
53
|
export function lint(path: string, cfg: Config): { errs: string[]; warns: string[] } {
|
|
@@ -73,12 +85,7 @@ export function lintText(text: string, cfg: Config): { errs: string[]; warns: st
|
|
|
73
85
|
}
|
|
74
86
|
|
|
75
87
|
|
|
76
|
-
const paths =
|
|
77
|
-
const scan = liveText(text);
|
|
78
|
-
for (const prefix of cfg.brief.path_prefixes) {
|
|
79
|
-
const re = new RegExp(`(${escapeReg(prefix)}[\\w./\\-]+)`, "g");
|
|
80
|
-
for (const hit of scan.matchAll(re)) paths.add(hit[1]!);
|
|
81
|
-
}
|
|
88
|
+
const paths = briefPaths(text, cfg);
|
|
82
89
|
for (const raw of [...paths].toSorted()) {
|
|
83
90
|
const p = clean(raw);
|
|
84
91
|
if (p.endsWith("-") || p.endsWith("_")) continue;
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// The claim store behind "several Mains, one queue, never the same plan twice"
|
|
2
|
+
// (plan 20261027_1300 P1): one JSON file per plan under <queue_state>/claims/, named by the
|
|
3
|
+
// sha256 of the plan path. Every read-modify-write runs while holding the store's flock
|
|
4
|
+
// (src/core/file-lock.ts) and releases it in finally, so racing processes serialize; the
|
|
5
|
+
// kernel frees the lock when a holder dies. Claim files are written to a temp file in the
|
|
6
|
+
// same directory and renameSync over the target, so a reader never sees a half-written claim.
|
|
7
|
+
import { createHash } from "node:crypto";
|
|
8
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { hostname } from "node:os";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { lock } from "./file-lock.ts";
|
|
12
|
+
|
|
13
|
+
/** A plan one Main is working on. */
|
|
14
|
+
export interface Claim {
|
|
15
|
+
/** The plan path the claim is for. */
|
|
16
|
+
plan: string;
|
|
17
|
+
/** The Main id holding it. */
|
|
18
|
+
main: string;
|
|
19
|
+
host: string;
|
|
20
|
+
pid: number;
|
|
21
|
+
/** Unix seconds when the claim was taken (unchanged by heartbeats and re-claims). */
|
|
22
|
+
since: number;
|
|
23
|
+
/** Unix seconds of the last heartbeat or claim. */
|
|
24
|
+
beat: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The plan answer when another Main holds a live claim. */
|
|
28
|
+
export interface Held {
|
|
29
|
+
heldBy: Claim;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface ClaimStore {
|
|
33
|
+
claim(plan: string, main: string): Claim | Held;
|
|
34
|
+
/** The live claim for a plan, or null when it is free (absent, unreadable or expired). Read-only: no claim is taken. */
|
|
35
|
+
holder(plan: string): Claim | null;
|
|
36
|
+
heartbeat(plan: string, main: string): boolean;
|
|
37
|
+
release(plan: string, main: string): void;
|
|
38
|
+
list(): Claim[];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Claim files are only ever written by temp+rename under the lock, so an unreadable one
|
|
42
|
+
// means outside tampering; treating it as absent lets the next claim replace it.
|
|
43
|
+
function readClaim(path: string): Claim | null {
|
|
44
|
+
if (!existsSync(path)) return null;
|
|
45
|
+
try {
|
|
46
|
+
const c = JSON.parse(readFileSync(path, "utf8")) as Claim;
|
|
47
|
+
if (typeof c.main !== "string" || typeof c.beat !== "number" || typeof c.since !== "number") return null;
|
|
48
|
+
return c;
|
|
49
|
+
} catch {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function writeClaim(path: string, claim: Claim): void {
|
|
55
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
56
|
+
writeFileSync(tmp, JSON.stringify(claim));
|
|
57
|
+
renameSync(tmp, path);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The local file claim store. `ttlMin` is `queue.claim_ttl_min` — required, every caller passes
|
|
62
|
+
* the configured value (P1 review I-20261031-189): a claim whose `beat` is that many minutes old
|
|
63
|
+
* is free for takeover. The clock is injected in unix seconds (src/core/clock.ts convention) so
|
|
64
|
+
* tests never use real time.
|
|
65
|
+
*/
|
|
66
|
+
export function fileClaimStore(stateDir: string, clock: () => number, ttlMin: number): ClaimStore {
|
|
67
|
+
const dir = join(stateDir, "claims");
|
|
68
|
+
const lockPath = join(dir, ".lock");
|
|
69
|
+
|
|
70
|
+
function run<T>(fn: () => T): T {
|
|
71
|
+
mkdirSync(dir, { recursive: true });
|
|
72
|
+
const held = lock(lockPath);
|
|
73
|
+
try {
|
|
74
|
+
return fn();
|
|
75
|
+
} finally {
|
|
76
|
+
held.release();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function fileFor(plan: string): string {
|
|
81
|
+
return join(dir, `${createHash("sha256").update(plan).digest("hex")}.json`);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function expired(c: Claim, now: number): boolean {
|
|
85
|
+
return now - c.beat >= ttlMin * 60;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return {
|
|
89
|
+
claim(plan, main) {
|
|
90
|
+
return run(() => {
|
|
91
|
+
const path = fileFor(plan);
|
|
92
|
+
const now = clock();
|
|
93
|
+
const cur = readClaim(path);
|
|
94
|
+
if (cur && cur.main === main) {
|
|
95
|
+
// The same main again: idempotent — `since` unchanged, `beat` refreshed.
|
|
96
|
+
const next = { ...cur, beat: now };
|
|
97
|
+
writeClaim(path, next);
|
|
98
|
+
return next;
|
|
99
|
+
}
|
|
100
|
+
if (cur && !expired(cur, now)) return { heldBy: cur };
|
|
101
|
+
const fresh: Claim = { plan, main, host: hostname(), pid: process.pid, since: now, beat: now };
|
|
102
|
+
writeClaim(path, fresh);
|
|
103
|
+
return fresh;
|
|
104
|
+
});
|
|
105
|
+
},
|
|
106
|
+
heartbeat(plan, main) {
|
|
107
|
+
return run(() => {
|
|
108
|
+
const path = fileFor(plan);
|
|
109
|
+
const cur = readClaim(path);
|
|
110
|
+
if (!cur || cur.main !== main) return false;
|
|
111
|
+
writeClaim(path, { ...cur, beat: clock() });
|
|
112
|
+
return true;
|
|
113
|
+
});
|
|
114
|
+
},
|
|
115
|
+
holder(plan) {
|
|
116
|
+
return run(() => {
|
|
117
|
+
const cur = readClaim(fileFor(plan));
|
|
118
|
+
return cur && !expired(cur, clock()) ? cur : null;
|
|
119
|
+
});
|
|
120
|
+
},
|
|
121
|
+
release(plan, main) {
|
|
122
|
+
run(() => {
|
|
123
|
+
const path = fileFor(plan);
|
|
124
|
+
const cur = readClaim(path);
|
|
125
|
+
if (cur && cur.main === main) rmSync(path);
|
|
126
|
+
});
|
|
127
|
+
},
|
|
128
|
+
list() {
|
|
129
|
+
return run(() => {
|
|
130
|
+
// A crashed writer leaves <claim>.<pid>.tmp behind; the next list sweeps it (the lock
|
|
131
|
+
// guarantees no live writer is mid-rename).
|
|
132
|
+
for (const f of readdirSync(dir)) if (f.endsWith(".tmp")) rmSync(join(dir, f), { force: true });
|
|
133
|
+
return readdirSync(dir)
|
|
134
|
+
.filter(f => f.endsWith(".json"))
|
|
135
|
+
.map(f => readClaim(join(dir, f)))
|
|
136
|
+
.filter((c): c is Claim => c !== null);
|
|
137
|
+
});
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
}
|