pi-straw-boss 0.74.0 → 0.75.0

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.
@@ -4429,6 +4429,7 @@ function trainFromToken(token) {
4429
4429
  return isName(project) && isCode(code) ? { project, code } : void 0;
4430
4430
  }
4431
4431
  var trainLabel = (code) => `train ${shortCode(code)}`;
4432
+ var isRoleLabel = (label2) => label2 === TOWER_LABEL || label2 === HEAD_LABEL || /^train \d{4}[a-z]{1,2}$/.test(label2);
4432
4433
  function trainFromRequest(request2) {
4433
4434
  const find = (key2) => new RegExp(`(?:^|[{,])[ \\t>*-]*["']?${key2}["']?[ \\t]*[:=][ \\t]*["']?([^\\s"',}]+)`, "im").exec(request2)?.[1];
4434
4435
  const [project, code] = [find("project"), find("code")];
@@ -6654,6 +6655,7 @@ export {
6654
6655
  trainToken,
6655
6656
  trainFromToken,
6656
6657
  trainLabel,
6658
+ isRoleLabel,
6657
6659
  trainFromRequest,
6658
6660
  appFromRequest,
6659
6661
  readMaxTrains,
@@ -86,7 +86,7 @@ import {
86
86
  writeBoard,
87
87
  writeJson,
88
88
  writerAlive
89
- } from "./chunk-ZHT3FG4Q.mjs";
89
+ } from "./chunk-4OLRDO5C.mjs";
90
90
 
91
91
  // src/server/cli.ts
92
92
  import { existsSync as existsSync2, realpathSync as realpathSync2 } from "node:fs";
@@ -101,6 +101,7 @@ import {
101
101
  isName,
102
102
  isObject,
103
103
  isOrphan,
104
+ isRoleLabel,
104
105
  isSessionRole,
105
106
  isStandin,
106
107
  isSub,
@@ -206,7 +207,7 @@ import {
206
207
  writeStartError,
207
208
  writerAlive,
208
209
  yardPath
209
- } from "./chunk-ZHT3FG4Q.mjs";
210
+ } from "./chunk-4OLRDO5C.mjs";
210
211
 
211
212
  // src/server/main.ts
212
213
  import { homedir as homedir14 } from "node:os";
@@ -3098,7 +3099,12 @@ async function popBase(d, name2) {
3098
3099
  }
3099
3100
  }
3100
3101
  async function open2(d, name2, file2) {
3101
- const { run: run3 } = d, st = readStash(d.stateDir, name2, file2), all = st.tabs.flatMap((t) => t.panes);
3102
+ const { run: run3 } = d, st = readStash(d.stateDir, name2, file2), refused3 = [];
3103
+ for (const tab of st.tabs) {
3104
+ const alone = tab.label === TOWER_LABEL && tab.panes.filter((p) => p.kind !== "shell").length === 1;
3105
+ tab.panes = tab.panes.map((p) => p.kind !== "tower" || alone ? p : (refused3.push(p.name ?? p.session ?? "a session"), { ...p, kind: "member" }));
3106
+ }
3107
+ const all = st.tabs.flatMap((t) => t.panes);
3102
3108
  const envOf = (kind) => [...roleEnv(kind), ...d.agentDir ? [`PI_CODING_AGENT_DIR=${d.agentDir}`] : []];
3103
3109
  const gone = [.../* @__PURE__ */ new Set([...all.filter((p) => p.session && !existsSync3(p.session)).map((p) => p.session), ...all.map((p) => p.cwd).filter((c) => !statSync5(c, { throwIfNoEntry: false })?.isDirectory())])];
3104
3110
  if (gone.length) throw new Error(`Nothing was opened: ${gone.join(", ")} no longer exist${gone.length > 1 ? "" : "s"}`);
@@ -3119,7 +3125,7 @@ async function open2(d, name2, file2) {
3119
3125
  const starts = tab.panes.map((p, j) => ({ p, pane: ids[j] })).filter(({ p }) => p.kind !== "shell").sort((a, b) => RANK[a.p.kind] - RANK[b.p.kind]);
3120
3126
  for (const { p, pane } of starts) await resume(d, ws, pane, p), sessions++;
3121
3127
  }
3122
- return { workspace: ws, label: st.label, sessions };
3128
+ return { workspace: ws, label: st.label, sessions, ...refused3.length ? { warning: `Straw Boss: the stash names ${refused3.join(", ")} a tower, but not alone in a tower tab, so it came back as a member: a file alone gives no role` } : {} };
3123
3129
  } catch (error) {
3124
3130
  await run3(["workspace", "close", ws]).catch(() => {
3125
3131
  });
@@ -18767,6 +18773,7 @@ function opener(env) {
18767
18773
  train = found2;
18768
18774
  label = trainLabel(found2.code);
18769
18775
  }
18776
+ if (!train && label !== void 0 && isRoleLabel(label.trim())) throw new OpenLimitError("label is the label of a tower's or a train's tab, which only Straw Boss gives; choose another");
18770
18777
  if (role === INTEGRATOR) {
18771
18778
  if (peer) throw new OpenLimitError("An integrator is opened on a car slip a session of this computer sent, not for a teammate's device");
18772
18779
  if (env.integrationOff?.()) throw new OpenLimitError("No integrator is opened: integration is off on this computer");
@@ -23419,7 +23426,7 @@ function createTowers(o) {
23419
23426
  const pane = ps.find((p) => p.pane_id === record2.pane && p.workspace_id === record2.workspace), workspace = all.find((w) => w.workspace_id === record2.workspace);
23420
23427
  if (!pane || !workspace || isSub(workspace) || record2.tab !== pane.tab_id) continue;
23421
23428
  const glyph = (await tabs(run3, workspace.workspace_id)).some((t) => t.tab_id === pane.tab_id && t.label === TOWER_LABEL);
23422
- if (!glyph && !(typeof record2.file === "string" && pane.agent_session?.value === record2.file)) continue;
23429
+ if (!glyph && !(pane.tokens?.sb_role === "tower" && typeof record2.file === "string" && pane.agent_session?.value === record2.file)) continue;
23423
23430
  if (!services.has(workspace.workspace_id) && !readService(slot, workspace.workspace_id)) {
23424
23431
  const made = { workspace: workspace.workspace_id, label: workspace.label, id: towerId(slot, workspace.workspace_id), name: towerName(slot, workspace.label), pane: pane.pane_id, tab: pane.tab_id, created: new Date(now()).toISOString(), seq: 0 };
23425
23432
  if (!glyph) await run3(["tab", "rename", pane.tab_id, TOWER_LABEL]).catch(() => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-straw-boss",
3
- "version": "0.74.0",
3
+ "version": "0.75.0",
4
4
  "description": "Straw Boss coordination for pi in Herdr: sessions join a tab's net by choice, the first joiner is its main agent, a workspace tower opens on demand with a live monitoring dashboard, and boss_broadcast reaches the rest",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/membership.ts CHANGED
@@ -99,6 +99,10 @@ export function createMembership({ pi, cfg, s, me, tell }: Kit, { presence, elec
99
99
  if (s.joined) return;
100
100
  await s.recheck?.(); // a session whose sub workspace check failed (or is still running) asks Herdr again, or shares the ask in flight, before it is refused
101
101
  if (s.barred) throw new Error(s.barred);
102
+ if (s.isTower) throw fatal("This session is the tower of its workspace, not a member of a tab's net"); // the check may have just proven a restored tower (session.ts `towerProof`), and a caller that waited for it joins nothing
103
+ // A session with a sign of a train (trainguard.ts `signsOfTrain`) whose start has not settled the role yet (Herdr did not list its pane or tab) joins nothing early: /boss or a subagent call
104
+ // would publish it as a member, and a promotion would make a train's pane its tab's main. The start's own join comes after it has settled (session.ts `proceed`).
105
+ if (s.trainSign && !s.trainSettled) throw new Error("This session's train role is not settled yet: Herdr has not answered for its pane and tab; it is asked again");
102
106
  s.at = await place(run);
103
107
  connect(true);
104
108
  await connected();
package/src/opener.ts CHANGED
@@ -9,7 +9,7 @@ import { assertSettingsSafe, SettingsRefused } from "./trust/settings.ts";
9
9
  import { inside } from "./link/routing.ts";
10
10
  import { checkoutProject, noTrainRefusal, openRefusal, repoRoot } from "./train/appsconfig.ts";
11
11
  import { slipsInText } from "./train/cars.ts";
12
- import { appFromRequest, readMaxTrains, TRAIN, type TrainId, trainFromRequest, trainFromToken, trainLabel, trainToken } from "./trainrole.ts";
12
+ import { appFromRequest, isRoleLabel, readMaxTrains, TRAIN, type TrainId, trainFromRequest, trainFromToken, trainLabel, trainToken } from "./trainrole.ts";
13
13
  import { waitPastTrust } from "./trust/wait.ts";
14
14
 
15
15
  // The one thing a tower does besides routing: when no session owns a request, it opens a main for it (docs/how-it-works.md, "Opening a main").
@@ -129,6 +129,8 @@ export function opener(env: OpenerEnv) {
129
129
  train = found;
130
130
  label = trainLabel(found.code);
131
131
  }
132
+ // The label becomes the new tab's, and a tab labelled as a tower's or a train's is what proves that role after a restore (roles.ts): a main's tab is never given one (a train's is its code's, above).
133
+ if (!train && label !== undefined && isRoleLabel(label.trim())) throw new OpenLimitError("label is the label of a tower's or a train's tab, which only Straw Boss gives; choose another");
132
134
  // An integrator is opened on a car slip a session of this computer sent, for the project of the workspace's checkout (read below); its tab and session carry the project's name, which makes the new pi an integrator from its first turn (mainduty.ts).
133
135
  if (role === INTEGRATOR) {
134
136
  if (peer) throw new OpenLimitError("An integrator is opened on a car slip a session of this computer sent, not for a teammate's device");
package/src/roles.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
+ import { TOWER_LABEL } from "./herdr.ts";
4
5
  import type { Kit } from "./state.ts";
5
- import { TRAIN, type TrainId, trainFromToken, trainToken } from "./trainrole.ts";
6
+ import { TRAIN, type TrainId, trainFromToken, trainLabel, trainToken } from "./trainrole.ts";
6
7
 
7
8
  // What a Herdr restore cannot keep. After `herdr server stop` and a new server, Herdr resumes each pi pane into its session file, but a role lives in
8
9
  // things the restore drops: STRAW_BOSS_ROLE in the pane's environment, the pane and workspace tokens, and, for a session without a conversation yet, the
@@ -16,11 +17,15 @@ import { TRAIN, type TrainId, trainFromToken, trainToken } from "./trainrole.ts"
16
17
  // main, whose record would race the new one at a restore). And a main takes the role back only in a pane whose terminal is not the one it recorded: Herdr starts
17
18
  // a new terminal for a pane it restores, while a `/resume` in the same shell after a /quit finds the old one, and that is no restore. (A tower needs no such
18
19
  // check: it closes its pane when it quits, and its record is dropped then.)
20
+ // A record is a claim, never a proof: the session's own shell can write this folder (and its session file), so a record that says `tower` or `train` gives the
21
+ // role back only in the tab Herdr labels as that role's (the tower glyph, a train's `train <MMDDx>`), which a restore keeps and no file holds. The caller reads the
22
+ // label from Herdr (`Here.tabLabel`). A main has no such tab (its label is its own free name), so its record stands on the checks above
23
+ // (docs/specs/2026-11-07-train-workers.md §29).
19
24
 
20
25
  const KEEP_MS = 90 * 24 * 3600_000;
21
26
  export interface RoleRecord { role: "tower" | "main" | "train"; pane: string; tab: string; workspace: string; terminal?: string; file?: string; openedBy?: string; /** A train's project and code (docs/specs/2026-11-07-train-workers.md §3.3). */ train?: TrainId; at: number }
22
- /** Where a session runs now: the pane, tab, and workspace of the record must all be these. */
23
- export interface Here { paneId?: string; tabId?: string; workspaceId?: string; terminalId?: string }
27
+ /** Where a session runs now: the pane, tab, and workspace of the record must all be these. `tabLabel` is the label Herdr lists for the tab now, the proof of a tower's or a train's tab; left out, neither role is given back. */
28
+ export interface Here { paneId?: string; tabId?: string; workspaceId?: string; terminalId?: string; tabLabel?: string }
24
29
 
25
30
  const keyOf = (file: string) => createHash("sha256").update(file).digest("hex").slice(0, 32);
26
31
 
@@ -65,15 +70,20 @@ export function createRoles({ cfg, s, guiDir, tell }: Kit) {
65
70
  /**
66
71
  * The role this session recorded for the pane, tab, and workspace it is in now; undefined when it recorded none there, or when `here` lacks one of the
67
72
  * three. A main also needs proof of a restart (a terminal other than the one it recorded) and the newest main record of its tab: a tab has one main.
73
+ * A tower and a train need the tab Herdr labels as theirs (`here.tabLabel`): the record alone gives neither role.
68
74
  */
69
75
  held(here: Here): RoleRecord["role"] | undefined {
70
76
  const record = within(here);
71
- if (record?.role === "tower") return "tower";
77
+ if (record?.role === "tower") return here.tabLabel === TOWER_LABEL ? "tower" : undefined;
72
78
  if (!record || !record.terminal || !here.terminalId || record.terminal === here.terminalId) return undefined;
73
- // A train takes its role back on the same proof as a main (a new terminal for the same pane, tab, and workspace); a tab has no "newest train" to check, since no one else is crowned beside it.
74
- if (record.role === TRAIN) return TRAIN;
79
+ // A train takes its role back on the same proof as a main (a new terminal for the same pane, tab, and workspace), in the tab that carries its code; a tab has no "newest train" to check, since no one else is crowned beside it.
80
+ if (record.role === TRAIN) return record.train && here.tabLabel === trainLabel(record.train.code) ? TRAIN : undefined;
75
81
  return mainOf(record.tab, record.workspace)?.at === record.at ? "main" : undefined;
76
82
  },
83
+ /** The role the record names for the pane, tab, and workspace the session is in, proven or not: what tells the start to ask Herdr for the tab's label, and what a refusal names. */
84
+ claimed(here: Here): RoleRecord["role"] | undefined {
85
+ return within(here)?.role;
86
+ },
77
87
  /** Whether the record is a main's from this very terminal: a pi started in the shell that outlived the session, which no restore brought. */
78
88
  sameShell(here: Here): boolean {
79
89
  const record = within(here);
@@ -787,11 +787,12 @@ export function createTowers(o: TowersOptions): Towers {
787
787
  if (record?.role !== "tower" || typeof record.pane !== "string" || typeof record.workspace !== "string") continue;
788
788
  const pane = ps.find((p) => p.pane_id === record!.pane && p.workspace_id === record!.workspace), workspace = all.find((w) => w.workspace_id === record!.workspace);
789
789
  // A pane that is not in this Herdr belongs to another one (or to a tab that is gone): the record is left for the server that finds it. Herdr ids are short counters that repeat
790
- // across Herdr servers and `roles/` is shared by them all, so the id alone proves nothing: the pane must also be in the recorded tab, and that tab a tower tab or the pane
791
- // run the record's own session file.
790
+ // across Herdr servers and `roles/` is shared by them all, so the id alone proves nothing: the pane must also be in the recorded tab, and that tab a tower tab, or the pane
791
+ // run the record's own session file as a live tower (its `sb_role=tower` mark). The record and the session file are files the session's own shell can write, so they alone
792
+ // never make a seat: the glyph and the mark are Herdr's (docs/specs/2026-11-07-train-workers.md §29).
792
793
  if (!pane || !workspace || isSub(workspace) || record.tab !== pane.tab_id) continue;
793
794
  const glyph = (await tabs(run, workspace.workspace_id)).some((t) => t.tab_id === pane.tab_id && t.label === TOWER_LABEL);
794
- if (!glyph && !(typeof (record as { file?: unknown }).file === "string" && pane.agent_session?.value === (record as { file?: string }).file)) continue;
795
+ if (!glyph && !(pane.tokens?.sb_role === "tower" && typeof (record as { file?: unknown }).file === "string" && pane.agent_session?.value === (record as { file?: string }).file)) continue;
795
796
  if (!services.has(workspace.workspace_id) && !readService(slot, workspace.workspace_id)) {
796
797
  const made: ServiceRecord = { workspace: workspace.workspace_id, label: workspace.label, id: towerId(slot, workspace.workspace_id), name: towerName(slot, workspace.label), pane: pane.pane_id, tab: pane.tab_id, created: new Date(now()).toISOString(), seq: 0 };
797
798
  // A tab that is the tower's by its session file, not by the glyph, gets the glyph: it is what proves the seat after a Herdr restart (typegate.ts `seatGate`).
package/src/session.ts CHANGED
@@ -5,7 +5,7 @@ import type { Briefing } from "./briefing.ts";
5
5
  import type { Control } from "./closemain.ts";
6
6
  import type { Digest } from "./digest.ts";
7
7
  import type { Guard } from "./guard.ts";
8
- import { isHead, isSub, type Place, panes, place, report, waitFor, workspaces } from "./herdr.ts";
8
+ import { isHead, isSub, type Place, panes, place, report, tabs, TOWER_LABEL, waitFor, workspaces } from "./herdr.ts";
9
9
  import type { createHost } from "./host.ts";
10
10
  import type { IntegrationWatch } from "./integration.ts";
11
11
  import { CONNECT_MS, type Membership } from "./membership.ts";
@@ -19,7 +19,7 @@ import type { Presence } from "./presence.ts";
19
19
  import type { Reach } from "./reach.ts";
20
20
  import type { Roles } from "./roles.ts";
21
21
  import { ENTRY, type Kit } from "./state.ts";
22
- import { isSessionRole, TRAIN, TRAIN_EVENT, trainFromToken, trainToken } from "./trainrole.ts";
22
+ import { isSessionRole, TRAIN, TRAIN_EVENT, trainFromToken, trainLabel, trainToken } from "./trainrole.ts";
23
23
 
24
24
  /** The custom message that asks the launcher to resume the subagents a Herdr restore brought back plain. */
25
25
  const RESUME = "straw-boss-resume";
@@ -48,13 +48,29 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
48
48
  // A session in a sub workspace (a linked git worktree) acts like a subagent: it never joins. Only a definitive answer bars it for good;
49
49
  // a Herdr that could not answer (it is slow under load) leaves the session unplaced, and the check is asked again (`begin`).
50
50
  let placed: Place | undefined; // where Herdr says this session runs, as the sub workspace check found it
51
- type Verdict = { bar?: { text: string; level: "info" } } | { failed: string };
51
+ type Verdict = { bar?: { text: string; level: "info" } } | { failed: string } | { tower: true };
52
52
  type Once = (what: string, text: string, level: "info" | "warning" | "error") => void;
53
53
  /** `tell`, each `what` once per start: a check that is asked again does not repeat its warning. */
54
54
  const onceOf = (): Once => {
55
55
  const seen = new Set<string>();
56
56
  return (what, text, level) => void (seen.has(what) || (seen.add(what), tell(text, level)));
57
57
  };
58
+ /** The label Herdr lists for the tab now: the proof of a tower's or a train's tab (roles.ts). A list that fails throws, and proves nothing. */
59
+ const labelOf = async (here: Place) => (await tabs(run, here.workspaceId)).find((t) => t.tab_id === here.tabId)?.label;
60
+ const shown = (label: string | undefined) => (label === undefined ? "no tab" : JSON.stringify(Array.from(label).slice(0, 40).join("")));
61
+ // Whether the tower role this session claims is proven. Its saved entry and its role record are files its own shell can write, so they only claim; the proof is Herdr's:
62
+ // the pane sits in a tab labelled with the tower glyph, which a restore keeps and no file holds (docs/specs/2026-11-07-train-workers.md §29), and no other pane of that tab runs an
63
+ // agent: the label proves the tab, not the pane, and a tower that starts beside a live one yields by closing the tab (RP131-F001). No proof is a member, told once.
64
+ const towerProof = async (here: Place, once: Once): Promise<boolean> => {
65
+ const entry = Boolean(s.saved.tower);
66
+ if (!entry && roles.claimed(here) !== "tower") return false;
67
+ const label = await labelOf(here);
68
+ const inTab = (entry && label === TOWER_LABEL) || roles.held({ ...here, tabLabel: label }) === "tower";
69
+ const shared = inTab && (await panes(run, here.workspaceId)).some((p) => p.tab_id === here.tabId && p.pane_id !== here.paneId && (p.agent || p.tokens?.sb_role));
70
+ if (inTab && !shared) return true;
71
+ once("tower-claim", `Straw Boss: this session's ${entry ? "saved entry" : "role record"} says it was a tower, but ${shared ? "its pane shares the tower tab with another agent's pane" : `Herdr lists its pane in ${shown(label)}, not in a tower tab`}, so it starts as a member: a file alone gives no role`, "warning");
72
+ return false;
73
+ };
58
74
  const barReason = async (once: Once): Promise<Verdict> => {
59
75
  try {
60
76
  const here = (placed = await place(run)), { workspaceId } = here;
@@ -62,7 +78,8 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
62
78
  const all = await workspaces(run);
63
79
  const sub = all.find((w) => w.workspace_id === workspaceId);
64
80
  if (sub && isHead(sub)) return { bar: { text: "This is the head tower's workspace, so a session typed here cannot join the net; the head tower is its own", level: "info" } };
65
- return sub && isSub(sub) ? { bar: { text: `${sub.label} is a sub workspace, so this session cannot join the net; the main agent of its parent workspace represents it`, level: "info" } } : {};
81
+ if (sub && isSub(sub)) return { bar: { text: `${sub.label} is a sub workspace, so this session cannot join the net; the main agent of its parent workspace represents it`, level: "info" } };
82
+ return (await towerProof(here, once)) ? { tower: true } : {};
66
83
  } catch (error) {
67
84
  return { failed: (error as Error).message };
68
85
  }
@@ -98,9 +115,8 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
98
115
  s.duty = isCoordinatorDuty(s.saved.duty) ? s.saved.duty : undefined; // the migration's guard is this live value (docs/specs/2026-11-09-agent-kinds.md §2)
99
116
  s.branch = () => ctx.sessionManager.getBranch();
100
117
  s.file = ctx.sessionManager.getSessionFile();
101
- // A Herdr restore resumes the pane into this session file without STRAW_BOSS_ROLE and, when pi had not yet written the file, without its entries: the record decides (roles.ts).
102
- // The pane, tab, and workspace must all be the recorded ones; a tower needs no more, since it closes its pane when it quits (roles.ts).
103
- s.isTower ||= Boolean(s.saved.tower) || roles.held({ paneId: env.HERDR_PANE_ID, tabId: env.HERDR_TAB_ID, workspaceId: env.HERDR_WORKSPACE_ID }) === "tower";
118
+ // A tower here is one by its process: started with STRAW_BOSS_ROLE=tower (state.ts), or a tower already in an earlier start of this process. A Herdr restore resumes the pane into this session
119
+ // file without the variable: the saved entry or the role record then claims the role, and the claim is proven against Herdr with the workspace check below (`towerProof`), never taken from the file.
104
120
  const log = ctx.sessionManager;
105
121
  stopWatching();
106
122
  nudges = orphans({ run, file: () => log.getSessionFile(), entries: () => log.getEntries(), sessions: host.sessions, send: reach.send, type: ENTRY, remember: (key) => pi.appendEntry(ENTRY, { nudged: key }), me, tell });
@@ -108,13 +124,13 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
108
124
  restores = restored({ run, sleep: cfg.sleep, file: () => log.getSessionFile(), entries: () => log.getEntries(), active: () => !s.isTower, launcher: () => (me() ? { id: me(), name: who() } : undefined), sessions: host.sessions, send: reach.send, type: ENTRY, remember: (data) => pi.appendEntry(ENTRY, data), resume: (text, details) => pi.sendMessage({ customType: RESUME, content: text, display: true, details }, { triggerTurn: true, deliverAs: "steer" }), tell });
109
125
  nudgeTimer = setInterval(() => void Promise.allSettled([nudges?.poll(), restores?.poll()]), cfg.nudgeMs).unref();
110
126
  // Starting runs in the background: pi awaits session_start handlers in turn, and pi-intercom connects in its own, after this one.
111
- if (s.isTower) {
127
+ const asTower = () => {
112
128
  s.trainSettled = true; // a tower is no train
113
129
  s.barred = s.recheck = undefined; // what an earlier start of this process left (a member's unplaced check) is not a tower's: it dispatches no subagents, and a bar would let its call through
114
- unwatch = cfg.watch(presence.restore);
130
+ unwatch ??= cfg.watch(presence.restore);
115
131
  startTower().catch((error: Error) => tell(`Straw Boss: ${error.message}`, "error"));
116
- return;
117
- }
132
+ };
133
+ if (s.isTower) return asTower();
118
134
  // Asking Herdr whether this is a sub workspace waits in the background too: on a loaded machine a Herdr call takes seconds, and pi-intercom
119
135
  // connects only after this handler returns. Until the answer comes the session counts as barred: a join waits for the answer first (`s.recheck`, membership.ts), and a promotion needs the join, so nothing joins or promotes early.
120
136
  s.barred = CHECKING;
@@ -138,14 +154,24 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
138
154
  const mine = opensAsTrain ? (await panes(run, placed.workspaceId).catch((error) => { throw Object.assign(error as Error, { joining: true }); })).find((p) => p.pane_id === placed!.paneId) : undefined;
139
155
  const token = trainFromToken(mine?.tokens?.sb_train);
140
156
  const saved = trainFromToken(s.saved.train && trainToken(s.saved.train));
141
- if (mine?.tokens?.sb_open_main === "1" && token) {
142
- [s.isTrain, s.train, s.openedBy, trainHow] = [true, token, mine.tokens.sb_opened_by, "claim"];
143
- } else if (event.reason !== "startup" && saved && s.saved.openedPane === placed.paneId) {
144
- [s.isTrain, s.train, s.openedBy, trainHow] = [true, saved, s.saved.openedBy ?? undefined, "reload"];
145
- } else if (roles.held(placed) === TRAIN) {
157
+ if (mine?.tokens?.sb_open_main === "1" && token) return void ([s.isTrain, s.train, s.openedBy, trainHow] = [true, token, mine.tokens.sb_opened_by, "claim"]);
158
+ // The saved entry and the role record are files the session's own shell can write: they name the train it claims to be, and Herdr proves it, by the tab that carries the train's code
159
+ // (`train <MMDDx>`, set by the open and kept by a restore; docs/specs/2026-11-07-train-workers.md §29). A tab list that fails is no answer, as the pane list above.
160
+ const entry = event.reason !== "startup" && saved && s.saved.openedPane === placed.paneId ? saved : undefined;
161
+ // The label carries the short code only. At a /reload the pane still carries the train's own `sb_train` (presence.ts keeps it over the gap), which says the project and the year:
162
+ // an entry that names another train is not taken (RP131-F003). After a restore, or another start in this process, the token is gone and only the label is left.
163
+ const kept = entry && event.reason === "reload" ? (mine ?? (await panes(run, placed.workspaceId).catch((error) => { throw Object.assign(error as Error, { joining: true }); })).find((p) => p.pane_id === placed!.paneId))?.tokens?.sb_train : undefined;
164
+ const other = entry && event.reason === "reload" && kept !== trainToken(entry);
165
+ const named = entry ?? (roles.claimed(placed) === TRAIN ? roles.trainOf(placed) : undefined);
166
+ if (!named) return;
167
+ const label = await labelOf(placed).catch((error) => { throw Object.assign(error as Error, { joining: true }); });
168
+ if (entry && !other && label === trainLabel(entry.code)) {
169
+ [s.isTrain, s.train, s.openedBy, trainHow] = [true, entry, s.saved.openedBy ?? undefined, "reload"];
170
+ } else if (roles.held({ ...placed, tabLabel: label }) === TRAIN) {
146
171
  const record = roles.trainOf(placed);
147
172
  if (record) [s.isTrain, s.train, s.openedBy, trainHow] = [true, record, roles.openerOf(placed), "restore"];
148
- }
173
+ } else if (label !== trainLabel(named.code)) once("train-claim", `Straw Boss: this session's ${entry ? "saved entry" : "role record"} names ${trainLabel(named.code)}, but Herdr lists its pane in ${shown(label)}, not in that train's tab, so it is no train: a file alone gives no role`, "warning");
174
+ else if (other) once("train-claim", `Straw Boss: this session's saved entry names ${trainToken(entry!)}, but its pane carries ${kept ?? "no train's mark"}, so it is no train: a file alone gives no role`, "warning");
149
175
  };
150
176
  const proceed = async () => {
151
177
  if (!s.stopped && !unwatch) unwatch = cfg.watch(presence.restore); // a shutdown that came while Herdr was asked about the workspace has stopped nothing yet
@@ -224,6 +250,8 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
224
250
  return false;
225
251
  }
226
252
  clearTimeout(retryTimer);
253
+ // The claim is proven: the tower starts now, as one started with the variable does at once. It never joins (membership.ts refuses a tower's join).
254
+ if ("tower" in verdict) return ((s.isTower = true), asTower(), false);
227
255
  s.recheck = undefined;
228
256
  s.barred = verdict.bar?.text;
229
257
  if (verdict.bar) return (tell(verdict.bar.text, verdict.bar.level), (s.trainSettled = true), false); // a session that never joins is no train
package/src/stash.ts CHANGED
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { existsSync, linkSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
4
  import type { Reply } from "./control.ts";
5
- import { createTab, type HerdrRun, isHead, isStandin, isSub, type Pane, panes, parentOf, report, result, type Session, type Sleep, startPi, tabs, workspaces } from "./herdr.ts";
5
+ import { createTab, type HerdrRun, isHead, isStandin, isSub, type Pane, panes, parentOf, report, result, type Session, type Sleep, startPi, tabs, TOWER_LABEL, workspaces } from "./herdr.ts";
6
6
  import { isSessionRole } from "./trainrole.ts";
7
7
  import { assertSettingsSafe } from "./trust/settings.ts";
8
8
  import { waitPastTrust } from "./trust/wait.ts";
@@ -250,7 +250,7 @@ async function resume({ run, sleep, live, trustDir }: PopDeps, ws: string, paneI
250
250
  * Opens the stash `name` in a new workspace; on any failure the new workspace closes and the manifest goes back, so popping again starts over.
251
251
  * The manifest is claimed first by moving it into stash/.popping/ (one rename, which only one session wins), so two pops never run one session file twice.
252
252
  */
253
- export async function popBase(d: PopDeps, name: string): Promise<{ workspace: string; label: string; sessions: number }> {
253
+ export async function popBase(d: PopDeps, name: string): Promise<{ workspace: string; label: string; sessions: number; warning?: string }> {
254
254
  if (!nameOk(name)) throw new Error(`"${name}" is not a stash name`);
255
255
  const claimed = join(dirOf(d.stateDir), ".popping", `${name}.json`);
256
256
  mkdirSync(dirname(claimed), { recursive: true, mode: 0o700 });
@@ -273,7 +273,14 @@ export async function popBase(d: PopDeps, name: string): Promise<{ workspace: st
273
273
  }
274
274
  }
275
275
  async function open(d: PopDeps, name: string, file: string) {
276
- const { run } = d, st = readStash(d.stateDir, name, file), all = st.tabs.flatMap((t) => t.panes);
276
+ const { run } = d, st = readStash(d.stateDir, name, file), refused: string[] = [];
277
+ // The manifest is a file a session's shell can write, so the tower it names is a claim, as a role record's is (docs/specs/2026-11-07-train-workers.md §29): a pop starts a tower
278
+ // only where the stash made one, alone in a tab labelled with the tower glyph. Anywhere else the pi comes back a member, told once.
279
+ for (const tab of st.tabs) {
280
+ const alone = tab.label === TOWER_LABEL && tab.panes.filter((p) => p.kind !== "shell").length === 1;
281
+ tab.panes = tab.panes.map((p) => (p.kind !== "tower" || alone ? p : (refused.push(p.name ?? p.session ?? "a session"), { ...p, kind: "member" })));
282
+ }
283
+ const all = st.tabs.flatMap((t) => t.panes);
277
284
  const envOf = (kind: StashPane["kind"]) => [...roleEnv(kind), ...(d.agentDir ? [`PI_CODING_AGENT_DIR=${d.agentDir}`] : [])];
278
285
  const gone = [...new Set([...all.filter((p) => p.session && !existsSync(p.session)).map((p) => p.session!), ...all.map((p) => p.cwd).filter((c) => !statSync(c, { throwIfNoEntry: false })?.isDirectory())])];
279
286
  if (gone.length) throw new Error(`Nothing was opened: ${gone.join(", ")} no longer exist${gone.length > 1 ? "" : "s"}`);
@@ -295,7 +302,7 @@ async function open(d: PopDeps, name: string, file: string) {
295
302
  const starts = tab.panes.map((p, j) => ({ p, pane: ids[j]! })).filter(({ p }) => p.kind !== "shell").sort((a, b) => RANK[a.p.kind] - RANK[b.p.kind]);
296
303
  for (const { p, pane } of starts) (await resume(d, ws, pane, p), sessions++);
297
304
  }
298
- return { workspace: ws, label: st.label, sessions };
305
+ return { workspace: ws, label: st.label, sessions, ...(refused.length ? { warning: `Straw Boss: the stash names ${refused.join(", ")} a tower, but not alone in a tower tab, so it came back as a member: a file alone gives no role` } : {}) };
299
306
  } catch (error) {
300
307
  await run(["workspace", "close", ws]).catch(() => {});
301
308
  throw error;
package/src/stashing.ts CHANGED
@@ -58,6 +58,7 @@ export function createStashing({ cfg, s, guiDir, tell, me }: Kit, { host }: { ho
58
58
  const live = async (id: string) => (await host.sessions()).some((x) => x.id === id);
59
59
  const r = await popBase({ run, sleep, stateDir: guiDir, live, agentDir: cfg.env.PI_CODING_AGENT_DIR, trustDir: trustDir(guiDir) }, name);
60
60
  tell(`Popped "${name}": ${r.sessions} sessions are back in ${r.label}`);
61
+ if (r.warning) tell(r.warning, "warning");
61
62
  },
62
63
  };
63
64
  }
package/src/tools.ts CHANGED
@@ -18,7 +18,7 @@ import type { Kit } from "./state.ts";
18
18
  import { snapshotOfBranch } from "./todo.ts";
19
19
  import { todosOf } from "./items.ts";
20
20
  import { integrationOff } from "./trainswitch.ts";
21
- import { ownsBoard, trainLabel } from "./trainrole.ts";
21
+ import { isRoleLabel, ownsBoard, trainLabel } from "./trainrole.ts";
22
22
  import { trustDir } from "./trust/files.ts";
23
23
 
24
24
  /** The tab label for a name, cut at 16 characters as pi-auto-tab-name cuts it, so that extension takes the label as its own and keeps it. */
@@ -138,6 +138,8 @@ export function createTools({ pi, cfg, s, guiDir, me, role }: Kit, { mainDuty, p
138
138
  const phrase = name.replace(/\s+/g, " ").trim();
139
139
  if (!phrase) throw new Error("The name is empty");
140
140
  if (Array.from(phrase).length > 40) throw new Error(`The name has ${Array.from(phrase).length} characters; keep it a short phrase (at most 16 fit the tab)`);
141
+ // A main's tab takes the name as its label, and a tab labelled as a tower's or a train's is what proves that role after a restore (roles.ts).
142
+ if (isRoleLabel(tabLabel(phrase))) throw new Error("That name is the label of a tower's or a train's tab, which only Straw Boss gives; choose another");
141
143
  const was = pi.getSessionName() || s.ownName || me().slice(0, 8);
142
144
  const before = s.duty;
143
145
  pi.setSessionName(phrase);
package/src/trainrole.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { type HerdrRun, panes } from "./herdr.ts";
3
+ import { HEAD_LABEL, type HerdrRun, panes, TOWER_LABEL } from "./herdr.ts";
4
4
  import { appsFile } from "./train/appsconfig.ts";
5
5
  import { isCode, isName, shortCode } from "./train/spec.ts";
6
6
 
@@ -35,6 +35,12 @@ export function trainFromToken(token: unknown): TrainId | undefined {
35
35
  /** The name of a train's tab and session, set by the open and never changed: `train 1106m`. */
36
36
  export const trainLabel = (code: string): string => `train ${shortCode(code)}`;
37
37
 
38
+ /**
39
+ * Whether a label is one only Straw Boss gives a tab: the tower's and the head tower's glyph, and a train's `train <MMDDx>`. Such a tab is what proves a tower or a train after a restore
40
+ * (roles.ts), so a session's `boss_rename` and a tower's `boss_open_main` never name a tab into one.
41
+ */
42
+ export const isRoleLabel = (label: string): boolean => label === TOWER_LABEL || label === HEAD_LABEL || /^train \d{4}[a-z]{1,2}$/.test(label);
43
+
38
44
  /** The first `project:` and `code:` of the manifest the tower passes verbatim as the open's request (§5.3): `key: value` lines or JSON members, the manifest's own header first. */
39
45
  export function trainFromRequest(request: string): TrainId | { refusal: string } {
40
46
  const find = (key: string) => new RegExp(`(?:^|[{,])[ \\t>*-]*["']?${key}["']?[ \\t]*[:=][ \\t]*["']?([^\\s"',}]+)`, "im").exec(request)?.[1];