neurastream 0.2.86 → 0.3.2

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,311 @@
1
+ // `neurastream team share|unshare <plan>` (plan 20261027_1305 P1) and `team sync` (P3). share
2
+ // writes `Queue: team` when the repo's origin matches a teams: glob and pushes that one plan;
3
+ // unshare removes that line, keeps the file and deletes the plan's sync-record entries. The
4
+ // holder check goes through the chooser (claimStoreFor): a local-only read would unshare a plan
5
+ // another member holds on the server. planShare is the gate that refuses to send a plan without
6
+ // the marker; sync runs only when called — no hook and no heartbeat tick runs it.
7
+ // `team join <url> --name <name> --repo <glob>...` and `team leave <name>` (P6) add and remove one
8
+ // teams: entry in the config. join asks the server for its view first and writes nothing when the
9
+ // server does not answer this login (down, or not a member).
10
+ // `team pause <name>` and `team resume <name>` (P6b1): pause stops this login's claims on the team, and also gives up this Main's own claims there (see pauseTeam). resume only lifts the stop.
11
+
12
+ import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
13
+ import { homedir } from "node:os";
14
+ import path from "node:path";
15
+ import { heldByOther, type ClaimStore } from "../core/claims.ts";
16
+ import { nowSec, strftime } from "../core/clock.ts";
17
+ import { ConfigError, configFile, loadConfig, type Config } from "../core/config.ts";
18
+ import { setConfigKeys } from "../core/config-edit.ts";
19
+ import { mainId } from "../core/guards.ts";
20
+ import { defaultRunner, type CommandRunner } from "../core/mr-sweep.ts";
21
+ import { headerField, planRepo } from "../core/queue/lib.ts";
22
+ import { deleteRecordEntries, claimStoreFor, postTeamPause, pushTeamPlan, recordPath, releaseTeamClaim, sameGoalCheck, syncTeam, teamViews, type TeamEntry } from "../core/team-client.ts";
23
+ import { TEAM_NAME_HINT, TEAM_NAME_RE, repoTeam, teamConfigError } from "../core/team-labels.ts";
24
+
25
+ const USAGE = [
26
+ "usage: neurastream team share <plan> [--distinct \"<reason>\"]",
27
+ " neurastream team unshare <plan>",
28
+ " neurastream team sync [--team <name>]",
29
+ " neurastream team join <url> --name <name> --repo <glob>...",
30
+ " neurastream team leave <name>",
31
+ " neurastream team pause <name>",
32
+ " neurastream team resume <name>",
33
+ ].join("\n");
34
+
35
+ /** Header text with `Queue:` set to team, or removed (absent means personal). The first `##` section is kept. */
36
+ function withQueue(text: string, value: "team" | null): string {
37
+ const at = text.search(/^## /m);
38
+ const head = at < 0 ? text : text.slice(0, at);
39
+ const tail = at < 0 ? "" : text.slice(at);
40
+ const kept = head.split("\n").filter(line => !/^Queue:\s*\S/.test(line));
41
+ let body = kept.join("\n").replace(/\s*$/, "");
42
+ if (value === "team") body = body === "" ? "Queue: team" : `${body}\nQueue: team`;
43
+ if (tail) return `${body}\n\n${tail}`;
44
+ return body === "" ? "" : `${body}\n`;
45
+ }
46
+
47
+ export function runTeam(args: string[], opts: { cfg?: Config; run?: CommandRunner; store?: ClaimStore; home?: string; send?: ViewSend } = {}): number {
48
+ const sub = args[0];
49
+ if (sub === "join" || sub === "leave") return runJoinLeave(args, opts);
50
+ if (sub === "pause" || sub === "resume") return runPause(args, opts);
51
+ if (sub === "sync") {
52
+ let cfg: Config;
53
+ try {
54
+ cfg = opts.cfg ?? loadConfig();
55
+ } catch (err) {
56
+ console.error(err instanceof ConfigError ? err.message : String(err));
57
+ return 1;
58
+ }
59
+ const run = opts.run ?? defaultRunner;
60
+ const name = args.includes("--team") ? args[args.indexOf("--team") + 1] : undefined;
61
+ const teams = name ? (cfg.teams ?? []).filter(t => t.name === name) : cfg.teams ?? [];
62
+ if (name && !teams.length) {
63
+ console.error(`team sync: no teams: entry named ${name}`);
64
+ return 1;
65
+ }
66
+ for (const team of teams) syncTeam(team, cfg, run);
67
+ return 0;
68
+ }
69
+ const planArg = args[1];
70
+ const distinctAt = args.indexOf("--distinct");
71
+ const distinct = distinctAt === -1 ? undefined : args[distinctAt + 1];
72
+ const shaped = distinctAt === -1 ? args.length === 2 : sub === "share" && distinctAt === 2 && args.length === 4;
73
+ if ((sub !== "share" && sub !== "unshare") || !planArg || !shaped) {
74
+ console.error(USAGE);
75
+ return 2;
76
+ }
77
+ if (distinct !== undefined && (distinct.trim() === "" || distinct.length > 200)) {
78
+ console.error("team share: --distinct needs a reason of 1 to 200 characters");
79
+ return 2;
80
+ }
81
+ let cfg = opts.cfg;
82
+ if (!cfg) {
83
+ try {
84
+ cfg = loadConfig();
85
+ } catch (err) {
86
+ console.error(err instanceof ConfigError ? err.message : String(err));
87
+ return 1;
88
+ }
89
+ }
90
+ const file = path.resolve(planArg);
91
+ let text: string;
92
+ try {
93
+ if (!statSync(file).isFile()) throw new Error("not a file");
94
+ text = readFileSync(file, "utf8");
95
+ } catch {
96
+ console.error(`team ${sub}: ${file} is not a plan file`);
97
+ return 1;
98
+ }
99
+ const run = opts.run ?? defaultRunner;
100
+ if (sub === "share") {
101
+ const team = repoTeam(planRepo(file), cfg, run);
102
+ if (!team) {
103
+ console.error(`team share: ${file} is personal (its origin matches no team); a plan whose repo has no team label is not shared`);
104
+ return 1;
105
+ }
106
+ if (headerField(text, "Queue") === "team") {
107
+ console.log(`team share: ${file} already Queue: team for ${team}`);
108
+ return 0;
109
+ }
110
+ const entry = (cfg.teams ?? []).find(t => t.name === team) as TeamEntry | undefined;
111
+ // P6b2 rule a: a plan with the same goal as a plan or MR already in the team is refused unless --distinct gives a reason.
112
+ if (entry && distinct === undefined) {
113
+ const check = sameGoalCheck(entry, cfg, file, text, run, { send: opts.send });
114
+ if ("refused" in check) {
115
+ console.error(`team share: ${file} refused: ${check.refused}; pass --distinct "<reason>" to share anyway`);
116
+ return 1;
117
+ }
118
+ if (check.overlaps.length) {
119
+ console.error(`team share: ${file} has the same goal as:`);
120
+ for (const o of check.overlaps) console.error(` ${o.item} (overlap ${o.score.toFixed(2)})`);
121
+ console.error(`team share: refused; pass --distinct "<reason>" if this plan's goal is distinct`);
122
+ return 1;
123
+ }
124
+ }
125
+ writeFileSync(file, withQueue(text, "team"));
126
+ console.log(`team share: ${file} marked Queue: team for ${team}`);
127
+ // P3: share uploads the plan — one plan's push, guarded like every push.
128
+ if (entry) pushTeamPlan(entry, cfg, file, undefined, run, distinct);
129
+ return 0;
130
+ }
131
+ if (headerField(text, "Queue") !== "team") {
132
+ console.log(`team unshare: ${file} is already personal`);
133
+ return 0;
134
+ }
135
+ const store = opts.store ?? claimStoreFor(file, cfg);
136
+ const held = store.holder(file);
137
+ const me = mainId();
138
+ if (held !== null && "unreachable" in held) {
139
+ console.error(`team unshare: team server ${held.unreachable} unreachable`);
140
+ return 1;
141
+ }
142
+ if (held && heldByOther(held, me)) {
143
+ console.error(`team unshare: ${file} is held by Main ${held.main}; unshare only while you hold the claim, or the plan is unclaimed`);
144
+ return 1;
145
+ }
146
+ writeFileSync(file, withQueue(text, null));
147
+ // The record entries go too: the chooser's record rule must not keep routing a plan whose
148
+ // header says personal (that rule would fail open the other way).
149
+ deleteRecordEntries(cfg, file, run);
150
+ console.log(`team unshare: ${file} is personal again (local copy kept)`);
151
+ return 0;
152
+ }
153
+
154
+ /** The text with `line` as the last line of its `## Progress` section, or in a new section at the end when the plan has none. */
155
+ function withProgress(text: string, line: string): string {
156
+ const lines = text.replace(/\s*$/, "").split("\n");
157
+ const head = lines.findIndex(l => /^## Progress\s*$/.test(l));
158
+ if (head < 0) return `${lines.join("\n")}\n\n## Progress\n${line}\n`;
159
+ let end = lines.findIndex((l, i) => i > head && l.startsWith("## "));
160
+ if (end < 0) end = lines.length;
161
+ let last = end - 1;
162
+ while (last > head && lines[last]?.trim() === "") last--;
163
+ lines.splice(last + 1, 0, line);
164
+ return `${lines.join("\n")}\n`;
165
+ }
166
+
167
+ /** `team pause <name>` stops this login's claims on the team; it then gives up this Main's own claims there: each plan with a local copy the sync record names gets a Progress line, is pushed, and its claim is released by id. `team resume` only lifts the stop. */
168
+ export function pauseTeam(team: TeamEntry, cfg: Config, paused: boolean, opts: { run?: CommandRunner; send?: ViewSend } = {}): number {
169
+ const sent = postTeamPause(team, paused, { send: opts.send });
170
+ if (!sent.ok) {
171
+ console.error(`team ${paused ? "pause" : "resume"}: ${sent.error}`);
172
+ return 1;
173
+ }
174
+ if (!paused) {
175
+ console.log(`team resume: ${team.name} open to this member again`);
176
+ return 0;
177
+ }
178
+ const view = teamViews({ ...cfg, teams: [team] }, { send: opts.send }).get(team.name);
179
+ if (!view || "unreachable" in view) {
180
+ console.error(`team pause: ${team.name} is paused on the server, but its claims could not be read; none were released`);
181
+ return 1;
182
+ }
183
+ const me = mainId();
184
+ const run = opts.run ?? defaultRunner;
185
+ for (const claim of view.claims.filter(c => c.mine && c.main === me)) {
186
+ const file = recordPath(cfg, team, claim.plan);
187
+ if (file && existsSync(file)) {
188
+ const stamp = strftime(nowSec(), "%Y-%m-%d %H:%M");
189
+ const next = withProgress(readFileSync(file, "utf8"), `- ${stamp} ${me}: team ${team.name} paused by this member; claim released.`);
190
+ const tmp = `${file}.${process.pid}.tmp`;
191
+ writeFileSync(tmp, next);
192
+ renameSync(tmp, file);
193
+ pushTeamPlan(team, cfg, file, next, run);
194
+ }
195
+ releaseTeamClaim(team, claim.plan, me, { send: opts.send });
196
+ console.log(`team pause: released ${claim.plan} (${team.name})`);
197
+ }
198
+ console.log(`team pause: ${team.name} paused for this member`);
199
+ return 0;
200
+ }
201
+
202
+ /** `team pause|resume <name>`: looks up the named teams: entry, then runs pauseTeam. */
203
+ function runPause(args: string[], opts: { cfg?: Config; run?: CommandRunner; send?: ViewSend }): number {
204
+ const sub = args[0];
205
+ const name = args[1];
206
+ if (!name || args.length !== 2) {
207
+ console.error(USAGE);
208
+ return 2;
209
+ }
210
+ let cfg: Config;
211
+ try {
212
+ cfg = opts.cfg ?? loadConfig();
213
+ } catch (err) {
214
+ console.error(err instanceof ConfigError ? err.message : String(err));
215
+ return 1;
216
+ }
217
+ const team = (cfg.teams ?? []).find(t => t.name === name) as TeamEntry | undefined;
218
+ if (!team) {
219
+ console.error(`team ${sub}: no teams: entry named ${name}`);
220
+ return 1;
221
+ }
222
+ return pauseTeam(team, cfg, sub === "pause", opts);
223
+ }
224
+
225
+ // Writes the teams: list into the config file and keeps every other key as it is.
226
+ function writeTeamsKey(home: string, teams: TeamEntry[]): void {
227
+ const file = configFile(home);
228
+ mkdirSync(path.dirname(file), { recursive: true });
229
+ const text = existsSync(file) ? readFileSync(file, "utf8") : null;
230
+ writeFileSync(file, setConfigKeys(text, { teams: JSON.stringify(teams) }));
231
+ }
232
+
233
+ // `team join` adds one teams: entry; `team leave` removes it. join asks the server for its view
234
+ // before it writes: an unreachable server, or one that refuses this login, writes nothing. The repo
235
+ // globs are the admin's and come from the command line. leave leaves this machine's plan files alone.
236
+ // The probe's transport: the team-client seam, so tests stub the server's answer.
237
+ type ViewSend = NonNullable<Parameters<typeof teamViews>[1]>["send"];
238
+ function runJoinLeave(args: string[], opts: { cfg?: Config; home?: string; send?: ViewSend }): number {
239
+ const sub = args[0];
240
+ const rest = args.slice(1);
241
+ const home = opts.home ?? homedir();
242
+ let cfg = opts.cfg;
243
+ if (!cfg) {
244
+ try {
245
+ cfg = loadConfig({ home });
246
+ } catch (err) {
247
+ console.error(err instanceof ConfigError ? err.message : String(err));
248
+ return 1;
249
+ }
250
+ }
251
+ const teams = cfg.teams ?? [];
252
+ if (sub === "leave") {
253
+ const name = rest[0];
254
+ if (!name || rest.length !== 1) {
255
+ console.error(USAGE);
256
+ return 2;
257
+ }
258
+ if (!teams.some(t => t.name === name)) {
259
+ console.error(`team leave: no teams: entry named ${name}`);
260
+ return 1;
261
+ }
262
+ writeTeamsKey(home, teams.filter(t => t.name !== name));
263
+ console.log(`team leave: ${name} removed from teams:`);
264
+ return 0;
265
+ }
266
+ const url = rest[0];
267
+ let name: string | undefined;
268
+ const repos: string[] = [];
269
+ for (let i = 1; i < rest.length; i++) {
270
+ if (rest[i] === "--name") name = rest[++i];
271
+ else if (rest[i] === "--repo") repos.push(rest[++i] ?? "");
272
+ else {
273
+ console.error(USAGE);
274
+ return 2;
275
+ }
276
+ }
277
+ if (!url || name === undefined || repos.length === 0) {
278
+ console.error(USAGE);
279
+ return 2;
280
+ }
281
+ if (!TEAM_NAME_RE.test(name)) {
282
+ console.error(`team join: ${TEAM_NAME_HINT}`);
283
+ return 2;
284
+ }
285
+ let scheme = "";
286
+ try {
287
+ scheme = new URL(url).protocol;
288
+ } catch {}
289
+ if (scheme !== "http:" && scheme !== "https:") {
290
+ console.error("team join: server must be an http or https URL");
291
+ return 2;
292
+ }
293
+ if (teams.some(t => t.name === name)) {
294
+ console.error(`team join: a teams: entry named ${name} already exists`);
295
+ return 1;
296
+ }
297
+ const candidate: TeamEntry = { name, server: url.replace(/\/+$/, ""), repos };
298
+ const err = teamConfigError([candidate]);
299
+ if (err) {
300
+ console.error(`team join: ${err}`);
301
+ return 1;
302
+ }
303
+ const view = teamViews({ ...cfg, teams: [candidate] }, { send: opts.send }).get(name);
304
+ if (!view || "unreachable" in view) {
305
+ console.error(`team join: ${candidate.server} did not return the team view for this login — it is down, or this login is not a member; nothing was written`);
306
+ return 1;
307
+ }
308
+ writeTeamsKey(home, [...teams, candidate]);
309
+ console.log(`team join: ${name} added to teams: (${candidate.server})`);
310
+ return 0;
311
+ }
@@ -0,0 +1,235 @@
1
+ // `neurastream workspace`: serve the owner's phone page on the tailnet address only. Refuses to
2
+ // start when the config has the page off or no owner login; the core startOwnerUi enforces the
3
+ // same two refusals. Runs until killed (systemd user unit
4
+ // templates/systemd/neurastream-workspace.service). `workspace on --login <email> [--port N]` /
5
+ // `workspace off` set up and undo that whole setup in one command (the core lives in
6
+ // src/core/ui-setup.ts); plain `neurastream workspace` keeps serving as today. The command was
7
+ // `neurastream ui` before the workspace rename — no alias: the old name is an unknown command.
8
+ // Teams: `workspace on --team <name> --admin <login> --repo <glob>...` sets up one team's queue
9
+ // server (its own unit, `workspace --team <name>` serves it); `workspace members` edits a team's
10
+ // member list; `workspace off --team <name>` undoes that one team. The team server is the same
11
+ // queue the teams use: see src/core/team-server.ts.
12
+
13
+ import { homedir } from "node:os";
14
+ import { getAdapter } from "../adapters/index.ts";
15
+ import { ConfigError, loadConfig, type Config } from "../core/config.ts";
16
+ import { beat, errorLine } from "../core/heartbeat.ts";
17
+ import { startOwnerUi, type OwnerUiOptions, type OwnerUiServer } from "../core/owner-ui.ts";
18
+ import { applyQueueEnv } from "../core/queue/env.ts";
19
+ import { realTailscale, type Tailscale, untilIp4Changes } from "../core/tailscale.ts";
20
+ import { TEAM_NAME_HINT, TEAM_NAME_RE } from "../core/team-labels.ts";
21
+ import { addTeamMember, listTeamMembers, removeTeamMember, startTeamServer, type TeamServer, type TeamServerConfig, type TeamServerOptions } from "../core/team-server.ts";
22
+ import { PERSONAL, readTeamServerFile, systemTerminal, teamDbPath, uiOff, uiOn, type Runner, type Scope, type TeamServerFile } from "../core/ui-setup.ts";
23
+
24
+ export interface WorkspaceDeps {
25
+ /** The merged config. Default: loadConfig(). */
26
+ cfg?: Config;
27
+ /** Starts the page. Default: startOwnerUi. */
28
+ start?: (opts: OwnerUiOptions) => OwnerUiServer;
29
+ /** Command runner for `workspace on`/`workspace off` (default: spawnSync of systemctl --user). */
30
+ runner?: Runner;
31
+ /** Tailscale seam for `workspace on` and the serve path (default: realTailscale). */
32
+ tailscale?: Tailscale;
33
+ /** HOME the `workspace on`/`workspace off` config and unit paths resolve against (default: homedir()). */
34
+ home?: string;
35
+ /** How often the serve path checks for a new tailnet address (default: IP4_POLL_MS). */
36
+ ipPollMs?: number;
37
+ /** Starts the team queue server for `workspace --team <name>`. Default: startTeamServer. */
38
+ startTeam?: (opts: TeamServerOptions) => TeamServer;
39
+ }
40
+
41
+ const WORKSPACE_USAGE = "usage: neurastream workspace [on --login <tailscale login> [--port N] | on --team <name> --admin <tailscale login> --repo <glob>... [--port N] | off [--team <name>] | --team <name> | members add|remove <login> --team <name> | members list --team <name>]";
42
+
43
+ // `workspace on|off` argument handling. Personal: `on --login` (required: exit 1 without it).
44
+ // Team: `on --team <name> --admin <login> --repo <glob>...`. Flags that do not fit either form are
45
+ // a usage error (exit 2); the core (src/core/ui-setup.ts) decides the rest.
46
+ function runWorkspaceSetup(args: string[], deps: WorkspaceDeps): number {
47
+ const on = args[0] === "on";
48
+ const allowed = on ? ["--login", "--team", "--admin", "--repo", "--port"] : ["--team"];
49
+ let login: string | undefined;
50
+ let team: string | undefined;
51
+ let admin: string | undefined;
52
+ const repos: string[] = [];
53
+ let port: number | null = null;
54
+ for (let i = 1; i < args.length; i++) {
55
+ const flag = args[i]!;
56
+ if (!allowed.includes(flag)) {
57
+ console.error(WORKSPACE_USAGE);
58
+ return 2;
59
+ }
60
+ const value = args[i + 1];
61
+ i++;
62
+ if (flag === "--login") login = value;
63
+ else if (flag === "--team") team = value ?? "";
64
+ else if (flag === "--admin") admin = value;
65
+ else if (flag === "--repo") repos.push(value ?? "");
66
+ else {
67
+ const n = Number(value);
68
+ if (!Number.isInteger(n) || n <= 0 || n > 65535) {
69
+ console.error(`neurastream workspace on: --port needs a port number (1..65535), got "${value ?? ""}"`);
70
+ return 2;
71
+ }
72
+ port = n;
73
+ }
74
+ }
75
+ if (team !== undefined && !TEAM_NAME_RE.test(team)) {
76
+ console.error(`neurastream workspace: ${TEAM_NAME_HINT}`);
77
+ return 2;
78
+ }
79
+ // Personal forms take --login only; team forms take --admin and --repo only.
80
+ if (team === undefined ? admin !== undefined || repos.length > 0 : login !== undefined) {
81
+ console.error(WORKSPACE_USAGE);
82
+ return 2;
83
+ }
84
+ const scope: Scope = team === undefined ? PERSONAL : { kind: "team", name: team };
85
+ const setup = { home: deps.home, runner: deps.runner, tailscale: deps.tailscale, scope };
86
+ if (!on) return uiOff(setup);
87
+ if (team === undefined && !login) {
88
+ console.error("neurastream workspace on: --login <tailscale login> is required — e.g. neurastream workspace on --login me@example.com");
89
+ return 1;
90
+ }
91
+ // A question only on a terminal: scripted runs get the message and exit 1, no prompt.
92
+ const terminal = process.stdin.isTTY && process.stdout.isTTY ? systemTerminal : undefined;
93
+ return uiOn({ ...setup, login, admin, repos, port, terminal });
94
+ }
95
+
96
+ export async function runWorkspace(args: string[] = [], deps: WorkspaceDeps = {}): Promise<number> {
97
+ if (args[0] === "on" || args[0] === "off") return runWorkspaceSetup(args, deps);
98
+ if (args[0] === "members") return runMembers(args.slice(1), deps);
99
+ if (args[0] === "--team" && args.length === 2) return serveTeam(args[1]!, deps);
100
+ if (args.length) {
101
+ console.error(WORKSPACE_USAGE);
102
+ return 2;
103
+ }
104
+ let cfg = deps.cfg;
105
+ if (!cfg) {
106
+ try {
107
+ cfg = loadConfig();
108
+ } catch (err) {
109
+ console.error(err instanceof ConfigError ? err.message : String(err));
110
+ return 1;
111
+ }
112
+ }
113
+ applyQueueEnv(cfg);
114
+ if (!cfg.workspace.enabled) {
115
+ console.error("neurastream workspace: workspace.enabled is false — set it in the config first");
116
+ return 1;
117
+ }
118
+ if (!cfg.workspace.owner_login) {
119
+ console.error("neurastream workspace: workspace.owner_login is empty — set the tailscale login that may open the page");
120
+ return 1;
121
+ }
122
+ const tailscale = deps.tailscale ?? realTailscale;
123
+ let server: OwnerUiServer;
124
+ try {
125
+ server = (deps.start ?? startOwnerUi)({ cfg, tailscale, source: getAdapter(cfg).runSource(cfg) });
126
+ } catch (e) {
127
+ beat(cfg, "workspace", { ok: false, detail: errorLine(e) });
128
+ throw e;
129
+ }
130
+ beat(cfg, "workspace", { ok: true });
131
+ // Resolves 1 when the tailnet address moves: src/cli/main.ts exits with it, which would end the
132
+ // server, and systemd restarts it on the new address. Otherwise serving runs until systemd or a signal stops it.
133
+ return untilIp4Changes(tailscale, server.hostname, deps.ipPollMs);
134
+ }
135
+
136
+ type TeamState = { file: TeamServerFile; cfg: Config; config: TeamServerConfig; dbPath: string };
137
+
138
+ // Reads a team's settings file and the config (the queue database path comes from the config).
139
+ // Returns the failure as a message for the user, or the pieces a team command needs.
140
+ function readTeam(name: string, deps: WorkspaceDeps): TeamState | string {
141
+ const home = deps.home ?? homedir();
142
+ let file: TeamServerFile | null;
143
+ try {
144
+ file = readTeamServerFile(home, name);
145
+ } catch (err) {
146
+ return `neurastream workspace: ${(err as Error).message}`;
147
+ }
148
+ if (!file) return `neurastream workspace: no team "${name}" on this machine — run neurastream workspace on --team ${name} --admin <tailscale login> --repo <glob> first`;
149
+ let cfg = deps.cfg;
150
+ if (!cfg) {
151
+ try {
152
+ cfg = loadConfig({ home });
153
+ } catch (err) {
154
+ return `neurastream workspace: ${err instanceof ConfigError ? err.message : String(err)}`;
155
+ }
156
+ }
157
+ const config = { team: file.team, admin: file.admin, leader: file.leader, repos: file.repos, members: file.members };
158
+ return { file, cfg, config, dbPath: teamDbPath(cfg, name) };
159
+ }
160
+
161
+ // `workspace --team <name>`: the team's unit runs this. It serves the team queue on the tailnet
162
+ // address until the address changes or the unit stops. It writes no heartbeat: beat() feeds the
163
+ // personal page's health line, and a team server has no line of its own yet.
164
+ async function serveTeam(name: string, deps: WorkspaceDeps): Promise<number> {
165
+ if (!TEAM_NAME_RE.test(name)) {
166
+ console.error(`neurastream workspace: ${TEAM_NAME_HINT}`);
167
+ return 2;
168
+ }
169
+ const state = readTeam(name, deps);
170
+ if (typeof state === "string") {
171
+ console.error(state);
172
+ return 1;
173
+ }
174
+ applyQueueEnv(state.cfg);
175
+ const tailscale = deps.tailscale ?? realTailscale;
176
+ let server: TeamServer;
177
+ try {
178
+ server = (deps.startTeam ?? startTeamServer)({
179
+ tailscale,
180
+ config: state.config,
181
+ dbPath: state.dbPath,
182
+ port: state.file.port,
183
+ claimTtlMin: state.cfg.queue.claim_ttl_min,
184
+ });
185
+ } catch (err) {
186
+ console.error(`neurastream workspace: ${(err as Error).message}`);
187
+ return 1;
188
+ }
189
+ return untilIp4Changes(tailscale, server.hostname, deps.ipPollMs);
190
+ }
191
+
192
+ // `workspace members add|remove <login> --team <name>` and `workspace members list --team <name>`:
193
+ // the admin's changes go straight to the team's queue database, the same as the team server's own
194
+ // member routes. Both refuse until the team has started once.
195
+ function runMembers(args: string[], deps: WorkspaceDeps): number {
196
+ const sub = args[0];
197
+ const at = args.indexOf("--team");
198
+ const name = at >= 1 ? args[at + 1] : undefined;
199
+ const positional = args.filter((_, i) => i !== 0 && i !== at && i !== at + 1);
200
+ const wantsLogin = sub === "add" || sub === "remove";
201
+ if (name === undefined || !(sub === "list" || wantsLogin) || positional.length !== (sub === "list" ? 0 : 1)) {
202
+ console.error(WORKSPACE_USAGE);
203
+ return 2;
204
+ }
205
+ if (!TEAM_NAME_RE.test(name)) {
206
+ console.error(`neurastream workspace: ${TEAM_NAME_HINT}`);
207
+ return 2;
208
+ }
209
+ const state = readTeam(name, deps);
210
+ if (typeof state === "string") {
211
+ console.error(state);
212
+ return 1;
213
+ }
214
+ if (sub === "list") {
215
+ for (const login of listTeamMembers(state.dbPath)) console.log(login);
216
+ return 0;
217
+ }
218
+ const login = positional[0]!;
219
+ if (sub === "add") {
220
+ const r = addTeamMember(state.dbPath, state.config, login);
221
+ if (!r.ok) {
222
+ console.error(`neurastream workspace members: ${r.error}`);
223
+ return 1;
224
+ }
225
+ console.log(r.added ? `added ${login} to team ${name}` : `${login} is already a member of team ${name}`);
226
+ return 0;
227
+ }
228
+ const r = removeTeamMember(state.dbPath, state.config, login);
229
+ if (!r.ok) {
230
+ console.error(`neurastream workspace members: ${r.error}`);
231
+ return 1;
232
+ }
233
+ console.log(`removed ${login} from team ${name}; freed ${r.claimsFreed} claim(s)`);
234
+ return 0;
235
+ }
@@ -22,6 +22,8 @@ export interface Claim {
22
22
  since: number;
23
23
  /** Unix seconds of the last heartbeat or claim. */
24
24
  beat: number;
25
+ /** True when the claim is this login's own; set only by the team server's wire claims. Absent on file claims, which are this machine's own. */
26
+ mine?: boolean;
25
27
  }
26
28
 
27
29
  /** The plan answer when another Main holds a live claim. */
@@ -29,13 +31,33 @@ export interface Held {
29
31
  heldBy: Claim;
30
32
  }
31
33
 
32
- export interface ClaimStore {
33
- claim(plan: string, main: string): Claim | Held;
34
+ /** A team server that did not answer (timeout, refused connection, 5xx, unparseable answer). A value, never null: null keeps meaning "free". */
35
+ export interface Unreachable {
36
+ unreachable: string;
37
+ }
38
+
39
+ export interface ClaimStore<U = Unreachable> {
40
+ claim(plan: string, main: string): Claim | Held | U;
34
41
  /** 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;
42
+ holder(plan: string): Claim | U | null;
36
43
  heartbeat(plan: string, main: string): boolean;
37
44
  release(plan: string, main: string): void;
38
- list(): Claim[];
45
+ list(): Claim[] | U;
46
+ }
47
+
48
+ /** Whether a claim's last beat is `ttlMin` minutes old, so the plan is free for takeover. The file store and the team server share this rule. */
49
+ export function claimExpired(c: { beat: number }, now: number, ttlMin: number): boolean {
50
+ return now - c.beat >= ttlMin * 60;
51
+ }
52
+
53
+ /**
54
+ * True when this holder is not simply this Main's own claim: a team server that did not
55
+ * answer, another member's row (flagged `mine: false` by the server), another Main's id, or
56
+ * another Main on this login. File claims have no `mine`, so personal plans compare on `main`
57
+ * exactly as before.
58
+ */
59
+ export function heldByOther(h: Claim | Unreachable | null, me: string): boolean {
60
+ return !!h && ("unreachable" in h || h.main !== me || h.mine === false);
39
61
  }
40
62
 
41
63
  // Claim files are only ever written by temp+rename under the lock, so an unreadable one
@@ -63,7 +85,7 @@ function writeClaim(path: string, claim: Claim): void {
63
85
  * is free for takeover. The clock is injected in unix seconds (src/core/clock.ts convention) so
64
86
  * tests never use real time.
65
87
  */
66
- export function fileClaimStore(stateDir: string, clock: () => number, ttlMin: number): ClaimStore {
88
+ export function fileClaimStore(stateDir: string, clock: () => number, ttlMin: number): ClaimStore<never> {
67
89
  const dir = join(stateDir, "claims");
68
90
  const lockPath = join(dir, ".lock");
69
91
 
@@ -81,10 +103,6 @@ export function fileClaimStore(stateDir: string, clock: () => number, ttlMin: nu
81
103
  return join(dir, `${createHash("sha256").update(plan).digest("hex")}.json`);
82
104
  }
83
105
 
84
- function expired(c: Claim, now: number): boolean {
85
- return now - c.beat >= ttlMin * 60;
86
- }
87
-
88
106
  return {
89
107
  claim(plan, main) {
90
108
  return run(() => {
@@ -97,7 +115,7 @@ export function fileClaimStore(stateDir: string, clock: () => number, ttlMin: nu
97
115
  writeClaim(path, next);
98
116
  return next;
99
117
  }
100
- if (cur && !expired(cur, now)) return { heldBy: cur };
118
+ if (cur && !claimExpired(cur, now, ttlMin)) return { heldBy: cur };
101
119
  const fresh: Claim = { plan, main, host: hostname(), pid: process.pid, since: now, beat: now };
102
120
  writeClaim(path, fresh);
103
121
  return fresh;
@@ -115,7 +133,7 @@ export function fileClaimStore(stateDir: string, clock: () => number, ttlMin: nu
115
133
  holder(plan) {
116
134
  return run(() => {
117
135
  const cur = readClaim(fileFor(plan));
118
- return cur && !expired(cur, clock()) ? cur : null;
136
+ return cur && !claimExpired(cur, clock(), ttlMin) ? cur : null;
119
137
  });
120
138
  },
121
139
  release(plan, main) {