pi-straw-boss 0.125.4 → 0.127.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.
@@ -3536,7 +3536,7 @@ function createHeadReach({ read: read4, deliver }) {
3536
3536
  import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3 } from "node:fs";
3537
3537
  import { dirname as dirname4, join as join12 } from "node:path";
3538
3538
  var KINDS2 = ["wait_raised", "wait_answered", "wait_closed", "wait_returned", "wait_parked", "link_wait_open", "link_wait_done", "thread_open", "thread_close", "call_tower", "wrap", "handover"];
3539
- var WHYS2 = { wait_closed: ["resolved", "dropped"], thread_close: ["done", "blocked", "abandoned"], call_tower: ["milestone", "shared", "blocked", "route", "fork"], wrap: ["wrapped", "auto-wrapped", "refused", "auto"] };
3539
+ var WHYS2 = { wait_closed: ["resolved", "dropped"], thread_close: ["done", "blocked", "abandoned"], call_tower: ["milestone", "shared", "blocked", "route", "fork"], wrap: ["wrapped", "auto-wrapped", "refused", "auto"], handover: ["rotate"] };
3540
3540
  var BYS = ["terminal", "gui", "phone", "box", "tower"];
3541
3541
  var ID = /^[A-Za-z0-9_.:#@+=|-]{1,160}$/;
3542
3542
  var ledgerId = (v) => typeof v === "string" && ID.test(v) ? v : null;
@@ -26822,6 +26822,7 @@ function deliveryOf(status) {
26822
26822
  var byOf2 = (via) => via === "gui" || via === "phone" || via === "box" ? via : "terminal";
26823
26823
  var doorOf = (via) => via === "prompt" || via === "run-pane" || via === "ask" ? via : "pi";
26824
26824
  var askRefused = (request, unattended) => (request.cmd === "boss-waits" && request.ask === true || request.cmd === "tower-memory" && request.via === "ask") && unattended() ? UNATTENDED : void 0;
26825
+ var raiserOf = (d, id2) => id2 && !id2.startsWith("link:") && d.successor ? d.successor(id2) : id2;
26825
26826
  var cardNotice = (plan2) => plan2.act === "done" || plan2.act === "choose" ? `${plan2.notice} ${ACT_ON_IT}` : plan2.notice;
26826
26827
  var quoted = (reason) => reason ? `: "${reason}"` : "";
26827
26828
  var trimStop = (text14) => text14.replace(/[.。]+$/u, "");
@@ -26922,7 +26923,7 @@ async function lateNotice(d, workspace, json3, via = "pi") {
26922
26923
  const key2 = `${workspace}
26923
26924
  ${String(json3.id)}`, hold = held.get(key2);
26924
26925
  if (via !== "ask") return { status: 409, body: { error: "refused", reason: "no notice is held for that session" } };
26925
- const raiser = updateMemory(d.slot, workspace, d.now(), () => void 0).memory.entries.find((e) => e.id === json3.id)?.card?.from?.id;
26926
+ const raiser = raiserOf(d, updateMemory(d.slot, workspace, d.now(), () => void 0).memory.entries.find((e) => e.id === json3.id)?.card?.from?.id);
26926
26927
  const mine = hold !== void 0 && raiser !== void 0 && json3.asker === raiser;
26927
26928
  if (json3.clear === true) return mine && (hold.cleared = true), { status: 200, body: { cleared: mine } };
26928
26929
  if (!hold || !mine || hold.cleared && json3.recover !== true || d.now() - hold.at > HELD_MS2) return !hold || d.now() - hold.at > HELD_MS2 ? held.delete(key2) : false, { status: 409, body: { error: "refused", reason: "no notice is held for that session" } };
@@ -26953,7 +26954,7 @@ async function pressRequest(d, workspace, json3, via = "pi") {
26953
26954
  } catch (cause) {
26954
26955
  return failure(cause);
26955
26956
  }
26956
- const raiser = plan2.card?.from?.id;
26957
+ const raiser = raiserOf(d, plan2.card?.from?.id);
26957
26958
  let status;
26958
26959
  if (raiser?.startsWith("link:") && d.linkPress) status = await d.linkPress(plan2.entry.id, plan2.act).catch(() => "failed");
26959
26960
  else if (plan2.notice && raiser) {
@@ -30786,6 +30787,26 @@ function noteTrains(open9, d) {
30786
30787
  };
30787
30788
  }
30788
30789
 
30790
+ // src/peertargets.ts
30791
+ import { basename as basename18 } from "node:path";
30792
+ var fileId = (file4) => basename18(file4, ".jsonl").split("_").pop();
30793
+ function successorOf(id2, handed, me) {
30794
+ for (let at = id2, seen = /* @__PURE__ */ new Set([id2]); ; ) {
30795
+ const next2 = handed.get(at);
30796
+ if (next2 === void 0 || next2 === me || seen.has(next2)) return at;
30797
+ seen.add(at = next2);
30798
+ }
30799
+ }
30800
+ var MARK2 = Buffer.from('"customType":"todo/v1"');
30801
+ var CHUNK3 = 1 << 20;
30802
+ var MAX2 = 64 << 20;
30803
+
30804
+ // src/rotationmarks.ts
30805
+ function rotations(stateDir) {
30806
+ return new Map(readRecords(stateDir).flatMap(({ record: record2 }) => record2.role === "main" && record2.handedOver?.rotated === true && typeof record2.handedOver.to === "string" ? [[fileId(record2.file), record2.handedOver.to]] : []));
30807
+ }
30808
+ var rotatedTo = (stateDir, id2) => successorOf(id2, rotations(stateDir), "");
30809
+
30789
30810
  // src/server/towers.ts
30790
30811
  var UNKNOWN = "(unknown)";
30791
30812
  var RUN_SEND_CAP_MS = 2e4;
@@ -32041,7 +32062,9 @@ ${d.message}`, at: new Date(now()).toISOString(), messageId: d.key });
32041
32062
  live: async (id2) => (await l.reach.read()).sessions.some((x) => x.id === id2),
32042
32063
  send: (to, text14, wait2) => l.reach.post(to, text14, "wait_card", "session", false, void 0, void 0, { wait: wait2 }),
32043
32064
  boss: (text14) => void runs2.boss(l.record.workspace, text14, "the boss (wait card)", { press: true }),
32044
- ...o.waits ? { linkPress: (card, act) => o.waits.pressed(workspace, card, act) } : {}
32065
+ ...o.waits ? { linkPress: (card, act) => o.waits.pressed(workspace, card, act) } : {},
32066
+ successor: (id2) => rotatedTo(slot.stateDir, id2)
32067
+ // a raiser that rotated in its own pane (docs/specs/2026-11-30-boss-rotate.md)
32045
32068
  }, workspace, json3, via);
32046
32069
  }
32047
32070
  return memoryRequest(slot, workspace, now(), json3, log);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-straw-boss",
3
- "version": "0.125.4",
3
+ "version": "0.127.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/election.ts CHANGED
@@ -3,25 +3,41 @@ import { trainInTab } from "./trainrole.ts";
3
3
 
4
4
  /** Who is the tab's main: the owner of the tab channel records it, and decides the claims members send. */
5
5
  export function createElection({ cfg, s, me, tell }: Kit) {
6
+ // Every election of this process runs on one path, one at a time (the claims membership relays, the guard's crown and clear): a decision never interleaves with another (rotate review round 2, F001).
7
+ let chain: Promise<unknown> = Promise.resolve();
8
+ const serial = <T>(fn: () => Promise<T> | T): Promise<T> => {
9
+ const next = chain.then(fn, fn);
10
+ chain = next.catch(() => undefined);
11
+ return next;
12
+ };
6
13
  // The owner records who is main. Promotion is first come, first served, and the main stays until it leaves: a later owner change never swaps it.
7
- const pin = (channel: Channel, main?: string) => {
14
+ const write = (channel: Channel, main?: string) => {
8
15
  if (channel.snapshot().owner?.sessionId !== me()) return;
9
16
  channel.commitState({ v: 1, ...(main ? { main } : {}), since: cfg.now() });
10
17
  if (channel === s.c) s.pinned = main;
11
18
  };
12
- // The owner decides a claim: a tab has one main, so a claim is dropped while a live main exists, unless the user forced it with /boss.
13
- const claim = async (channel: Channel, from: string, force: boolean) => {
19
+ // The owner decides a claim: a tab has one main, so a claim is dropped while a live main exists, unless the user forced it with /boss. A rotation's new session claims like anyone else: no claim replaces a
20
+ // live main (rotate review round 3). Every await comes first; the owner and the incumbent are read after the last one, and the compare and the write follow with no await between.
21
+ // `by: "guard"`: the guard's own crown, which a step-down for a rotation that landed during its awaits cancels (rotate review round 4, F010).
22
+ const claim = (channel: Channel, from: string, force: boolean, by?: "guard") => serial(async () => {
14
23
  try {
15
24
  if (channel.snapshot().owner?.sessionId !== me()) return;
16
25
  // A tab with a train has no main to crown, whoever asks (docs/specs/2026-11-07-train-workers.md §3.3); a pane list that cannot be had is no reason to drop it.
17
- if (channel === s.c && (s.isTrain || (await trainInTab(cfg.run, s.at.workspaceId, s.at.tabId).catch(() => undefined)))) return;
26
+ const train = channel === s.c && (s.isTrain || Boolean(await trainInTab(cfg.run, s.at.workspaceId, s.at.tabId).catch(() => undefined)));
27
+ const live = new Set((await channel.listSessions()).map((x) => x.id));
28
+ if (train || channel.snapshot().owner?.sessionId !== me() || (by === "guard" && s.rotating)) return;
18
29
  const current = (channel === s.c ? s.pinned : undefined) ?? (channel.snapshot().state?.payload as { main?: string } | undefined)?.main;
19
- if (!force && current && current !== from && (await channel.listSessions()).some((x) => x.id === current)) return;
20
- pin(channel, from);
30
+ if (!force && current && current !== from && live.has(current)) return;
31
+ write(channel, from);
21
32
  } catch (error) {
22
33
  tell(`Straw Boss: ${(error as Error).message}`, "warning");
23
34
  }
35
+ });
36
+ /** A main steps down before pi replaces its session (boss_rotate): the owner clears the record only while it still names `from`. No await, so it lands at once, between any claim's awaits and before its compare. */
37
+ const resign = (channel: Channel, from: string) => {
38
+ const current = (channel === s.c ? s.pinned : undefined) ?? (channel.snapshot().state?.payload as { main?: string } | undefined)?.main;
39
+ if (current === from) write(channel, undefined);
24
40
  };
25
- return { pin, claim };
41
+ return { pin: (channel: Channel, main?: string) => serial(() => write(channel, main)), claim, resign };
26
42
  }
27
43
  export type Election = ReturnType<typeof createElection>;
package/src/fork.ts CHANGED
@@ -76,6 +76,21 @@ export function advanceFork(dir: string, id: string, step: ForkStep, patch: Part
76
76
  return whole;
77
77
  });
78
78
  }
79
+ /**
80
+ * Fork `id` handed from main `from` to `to` (a handover or a rotation), under its lock: only while the record is there, not imported, and still names `from` as its source; it keeps the session the todos moved from.
81
+ * The record as written, or why it was left (rotate review F005).
82
+ */
83
+ export function handFork(dir: string, id: string, from: string, to: string): Fork | string {
84
+ return locked(dir, id, () => {
85
+ const now = readFork(dir, id);
86
+ if (!now) return "its record is gone";
87
+ if (now.step === "imported") return "its main imported it already";
88
+ if (now.source.id !== from) return `it is session ${now.source.id}'s now`;
89
+ const whole: Fork = { ...now, source: { ...now.source, id: to }, origin: now.origin ?? now.source.id };
90
+ put(dir, whole);
91
+ return whole;
92
+ });
93
+ }
79
94
  /** Removes a fork's record and handoff: a reserved fork whose move committed nothing, or an imported one a week on. */
80
95
  export function dropFork(dir: string, id: string): void {
81
96
  if (!safeSession(id)) return;
package/src/forkmain.ts CHANGED
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
3
  import { Type } from "typebox";
4
4
  import { checkText, clean } from "./board.ts";
5
- import { advanceFork, createFork, crossings, dropFork, type Fork, FORK_IDS, forkRepos, forksDir, handoffPath, type LiveFacts, liveRefusal, readFork, readForks, runningChildren, stepAt, uncovered } from "./fork.ts";
5
+ import { advanceFork, createFork, crossings, dropFork, type Fork, FORK_IDS, forkRepos, forksDir, handoffPath, type LiveFacts, liveRefusal, readFork, readForks, runningChildren, stepAt, uncovered, handFork } from "./fork.ts";
6
6
  import { panes } from "./herdr.ts";
7
7
  import { subagents } from "./netdata.ts";
8
8
  import { FORK_MESSAGE, forkMark, importRefusal, ledgerList } from "./forkimport.ts";
@@ -142,9 +142,9 @@ export function createForks(kit: Kit, d: ForkDeps) {
142
142
  return taken.length ? { message: { customType: FORK_MESSAGE, content: forkTakenReminder(taken), display: false } } : undefined;
143
143
  });
144
144
  return {
145
- /** Hands this main's forks that are still open to its successor (boss_handover; the boss, 2026-11-30: 「讓接班的 main 接管」): each record names the successor as its source, and keeps where the todos moved from. */
146
- async inherit(to: string, ctx?: unknown): Promise<string> {
147
- const list = ledgerList(s.branch())?.tasks ?? [], went: Fork[] = [], kept: string[] = [];
145
+ /** This main's forks that are still open, each made whole from its tombstones (a pickup's `restore`) for a successor to take; a fork that cannot be made whole stays, with the line that says why. */
146
+ async ready(ctx?: unknown): Promise<{ forks: Fork[]; kept: string[] }> {
147
+ const list = ledgerList(s.branch())?.tasks ?? [], forks: Fork[] = [], kept: string[] = [];
148
148
  for (const f of readForks(dir, cfg.now())) {
149
149
  if (f.source.id !== me() || f.step === "imported" || busy.has(f.id)) continue;
150
150
  const tombs = list.filter((t) => isObject(t.moved) && t.moved.to === f.id), named = `fork ${short(f.id)} (${f.ids.map((n) => `#${n}`).join(", ")})`;
@@ -154,16 +154,31 @@ export function createForks(kit: Kit, d: ForkDeps) {
154
154
  if (tombs.length && tombs.map((t) => t.id as number).sort((a, b) => a - b).join() !== f.ids.join()) throw new Error(`its tombstones here are ${tombs.map((t) => `#${String(t.id)}`).join(", ")}, not the fork's`);
155
155
  const refusal = tombs.length ? proofOf(f, f.id, f.ids, tombs) : undefined;
156
156
  if (refusal) throw new Error(refusal);
157
- const { fork } = await restore(ctx as Nested, f, f.ids, tombs);
158
- went.push(advanceFork(dir, f.id, fork.step, { source: { ...fork.source, id: to }, origin: fork.origin ?? fork.source.id }) ?? fork);
157
+ forks.push((await restore(ctx as Nested, f, f.ids, tombs)).fork);
159
158
  } catch (error) {
160
159
  kept.push(`${named} stayed with you: ${clean((error as Error).message, 200)}.`);
161
160
  }
162
161
  }
162
+ return { forks, kept };
163
+ },
164
+ /** Names `to` as the source of each fork `ready` made whole, each checked again under its lock (fork.ts `handFork`); `went` holds only the records rewritten (no pi call: a rotation's `setup` runs it after the old session's teardown). */
165
+ pass(forks: readonly Fork[], to: string): { went: Fork[]; kept: string[] } {
166
+ const went: Fork[] = [], kept: string[] = [];
167
+ for (const fork of forks) {
168
+ let out: Fork | string;
169
+ try { out = handFork(dir, fork.id, fork.source.id, to); } catch (error) { out = clean((error as Error).message, 200); }
170
+ if (typeof out === "string") kept.push(`fork ${short(fork.id)} was not handed on: ${out}.`);
171
+ else went.push(out);
172
+ }
173
+ return { went, kept };
174
+ },
175
+ /** Hands this main's forks that are still open to its successor (boss_handover; the boss, 2026-11-30: 「讓接班的 main 接管」): each record names the successor as its source, and keeps where the todos moved from. */
176
+ async inherit(to: string, ctx?: unknown): Promise<string> {
177
+ const made = await this.ready(ctx), { went, kept } = this.pass(made.forks, to);
163
178
  // The successor hears of them from this main at once; its own sb reminds it at each turn until each one's main is opened.
164
179
  const sent = went.length ? await d.post(to, forkTaken({ name: nameOf(), id: me() }, went), "handoff", "main", false).then((r) => r.status === "sent", () => false) : false;
165
180
  const names = went.map((f) => `fork ${short(f.id)} (${f.ids.map((n) => `#${n}`).join(", ")})`).join(", ");
166
- return [...(went.length ? [`${names} went to your successor, ${sent ? "which sb told how to pick them up" : "which sb could not tell now; its sb reminds it at each turn"}.`] : []), ...kept].join(" ");
181
+ return [...(went.length ? [`${names} went to your successor, ${sent ? "which sb told how to pick them up" : "which sb could not tell now; its sb reminds it at each turn"}.`] : []), ...made.kept, ...kept].join(" ");
167
182
  },
168
183
  addTool() {
169
184
  if (registered) return;
package/src/guard.ts CHANGED
@@ -62,10 +62,10 @@ export function createGuard({ cfg, s, me, guiDir }: Kit, { claim, pin, openTower
62
62
  if (towerLive(ws?.tokens?.tower)) {
63
63
  missing = undefined;
64
64
  // A tab with a train in it has no main to crown: the train is a worker of its own, and a pi that comes later stays a member (§3.3). A pane list that cannot be had is no reason to hold the crown back (restoring() reads it the same way).
65
- if (owner && !live(main) && !s.isTrain && !(await trainInTab(run, s.at.workspaceId, s.at.tabId).catch(() => undefined))) {
65
+ if (owner && !live(main) && !s.isTrain && !s.rotating && !(await trainInTab(run, s.at.workspaceId, s.at.tabId).catch(() => undefined))) {
66
66
  // Whoever joins a restored tab first would be crowned over the main the restore is bringing back.
67
67
  const waitUntil = await restoring();
68
- if (waitUntil === undefined) await claim(s.c, me(), false);
68
+ if (waitUntil === undefined) await claim(s.c, me(), false, "guard");
69
69
  else wake(waitUntil);
70
70
  }
71
71
  return;
package/src/index.ts CHANGED
@@ -56,6 +56,7 @@ import { registerRunTrust } from "./trust/runtrust.ts";
56
56
  import { registerThreadTools } from "./threadtools.ts";
57
57
  import { createWrapUp } from "./wrapup.ts";
58
58
  import { createRotationClose } from "./rotclose.ts";
59
+ import { createRotate } from "./rotate.ts";
59
60
  import { registerDoctor } from "./doctorlive.ts";
60
61
  import { createTopics } from "./topicmain.ts";
61
62
  import { registerTopicGate } from "./topicgate.ts";
@@ -128,7 +129,7 @@ export function createStrawBoss({ run: given, world: reading, api = herdrApi(),
128
129
  let trainGuard: TrainGuard | undefined;
129
130
  const addPeer = createPeerTool(kit, { post: reach.post, read: reach.read, openTower: reach.openTower, sync: () => membership.sync() }); // call_peer (callpeer.ts)
130
131
  const addTrainCar = trainCarTool(kit, () => trainGuard, cars, (text) => reach.callTower(text, undefined, false, "blocked"));
131
- const membership = createMembership(kit, { presence, election, guard, briefing, roles, openTower: reach.openTower, register: () => (netTools(), s.isTower || (watch.addTool(), ward.addTool(), pair.addTool(), wrap.addTool(), topics.addTool(), forks.addTool()), tools.addPromote(), tools.addDuty(), tools.addHandover(), addTrainCar(), addPeer()), onMain: link.look, control: () => control });
132
+ const membership = createMembership(kit, { presence, election, guard, briefing, roles, openTower: reach.openTower, register: () => (netTools(), s.isTower || (watch.addTool(), ward.addTool(), pair.addTool(), wrap.addTool(), topics.addTool(), forks.addTool()), tools.addPromote(), tools.addDuty(), tools.addHandover(), rotate.addTool(), addTrainCar(), addPeer()), onMain: link.look, control: () => control });
132
133
  // `look` (above) starts and upgrades the sb server (src/server/) and is the way to it; a session that is no part of that has none.
133
134
  const pair = createBossPair(kit, { ask: cfg.ask ?? look?.ask, remote: () => Boolean(link.remoteScope()) }); // boss_pair and board_read's review threads (bosspair.ts)
134
135
  const capFill = createCapFill(kit); // a main's capacity facts for the board, and its snoozes (capfill.ts)
@@ -140,6 +141,7 @@ export function createStrawBoss({ run: given, world: reading, api = herdrApi(),
140
141
  const control = createCloseMain(kit, { closeSelf, check: bridge.stashCheck, turn: bridge.turn });
141
142
  const wrap = createWrapUp(kit, { reach, boardFill, closeSelf, blockers: () => bridge.turn?.blockers(), duty: () => mainDuty.now(), remote: () => Boolean(link.remoteScope()), ask: cfg.ask ?? look?.ask, first: (c) => rot.look(c) }); // idle wrap-up and boss_wrap (wrapup.ts)
142
143
  const rot = createRotationClose(kit, { control, running: () => wrap.running(), reach, boardFill, closeSelf, remote: () => Boolean(link.remoteScope()) }); // an old main closes itself once its successor took over (rotclose.ts)
144
+ const rotate = createRotate(kit, { membership, probe: wrap.probe, remote: () => Boolean(link.remoteScope()), topics, forks }); // boss_rotate: a fresh session in this pane, by pi's own newSession (rotate.ts)
143
145
  const watch = createBossWatch(kit, { ask: cfg.ask ?? look?.ask, control, openTower: reach.openTower, remote: () => Boolean(link.remoteScope()), owned: (request) => ward.owned(request) });
144
146
  const ward = createWard(kit, { ask: cfg.ask ?? look?.ask, control, openTower: reach.openTower, remote: () => Boolean(link.remoteScope()) }); // sb_ward (wardtool.ts)
145
147
  registerSession(kit, { mainDuty, attended: () => link.attended(), integration: createIntegrationWatch(kit), runMode, briefing, roles, presence, membership, guard, host, reach, digest, control, startTower: createTower(kit, { membership, presence, tools: { ...tools, addNetTools: netTools }, control, digest, roles, reach }) });
package/src/link/hooks.ts CHANGED
@@ -105,7 +105,7 @@ export function createRemoteTurns({ pi, now, config, policy: policyDeps, home, a
105
105
  if (e.toolName === "link_request") return { block: true, reason: "a remote turn cannot ask for a link action, whatever its sender's level; a trust change (for example to dispatch) is asked from a local turn" };
106
106
  // A peer could otherwise restart this computer's server: no level, dispatch included, may.
107
107
  if (e.toolName === "boss_server") return { block: true, reason: "a remote turn cannot see or restart this computer's sb server, whatever its sender's level" };
108
- if (e.toolName === "boss_handover") return { block: true, reason: "a remote turn cannot open a successor of this main, whatever its sender's level" };
108
+ if (e.toolName === "boss_handover" || e.toolName === "boss_rotate") return { block: true, reason: "a remote turn cannot open a successor of this main or rotate its session, whatever its sender's level" };
109
109
  if (e.toolName === "boss_pair") return { block: true, reason: "a remote turn cannot open a review thread, whatever its sender's level" };
110
110
  if (e.toolName === "boss_wrap") return { block: true, reason: "a remote turn cannot wrap up this main, whatever its sender's level" };
111
111
  // As an ally run (server/runtools.ts): dead panes and their list are the local tower's, whatever the sender's level; a main is checked by the tool against its `sb_opened_by` (tools.ts).
package/src/membership.ts CHANGED
@@ -11,8 +11,10 @@ import { type Channel, ENTRY, type Kit, REGISTER } from "./state.ts";
11
11
  const NAMESPACE = /^[a-z0-9][a-z0-9._/-]{0,63}$/;
12
12
  export const CONNECT_MS = 15_000;
13
13
  const CLAIM_MS = 5000;
14
+ /** How long a rollback waits for the owner's ack of the step-down before it claims anyway (rotate review round 4, F008). */
15
+ export const RESIGN_ACK_MS = 3000;
14
16
  const fatal = (message: string) => Object.assign(new Error(message), { final: true }); // a join error that waiting cannot fix: session.ts does not retry it
15
- type Event = { type: string; fromSessionId?: string; owner?: { sessionId: string }; payload?: { type?: string; force?: boolean } };
17
+ type Event = { type: string; fromSessionId?: string; owner?: { sessionId: string }; payload?: { type?: string; force?: boolean; id?: unknown; for?: unknown } };
16
18
  /** What membership calls on the other modules; `register` adds the tools a joined session has. */
17
19
  interface Parts { presence: Presence; election: Election; guard: Guard; briefing: Briefing; roles: Roles; openTower: Reach["openTower"]; register(): void; onMain?(): void; control(): { register(): void } }
18
20
 
@@ -36,9 +38,16 @@ export function createMembership({ pi, cfg, s, me, tell }: Kit, { presence, elec
36
38
  // never promote); nothing else that channel says concerns the session's role.
37
39
  const onEvent = (channel: Channel, event: Event) => {
38
40
  if (event.type === "message" && event.payload?.type === "claim" && event.fromSessionId) {
39
- const [from, force] = [event.fromSessionId, Boolean(event.payload.force)];
41
+ const force = Boolean(event.payload.force), from = event.fromSessionId;
40
42
  s.queue = s.queue.then(() => election.claim(channel, from, force));
41
43
  }
44
+ // A main that steps down (boss_rotate): the broker names the sender, so only the main itself clears its record; the owner acks once it is cleared.
45
+ if (event.type === "message" && event.payload?.type === "resign" && event.fromSessionId && channel.snapshot().owner?.sessionId === me()) {
46
+ election.resign(channel, event.fromSessionId);
47
+ channel.publish({ type: "resigned", id: event.payload.id, for: event.fromSessionId }, { audience: "capable" });
48
+ }
49
+ // The owner's ack of this session's own step-down.
50
+ if (event.type === "message" && event.payload?.type === "resigned" && event.payload.for === me() && event.fromSessionId === channel.snapshot().owner?.sessionId && ack && event.payload.id === ack.id) ack.done(true);
42
51
  if (channel !== s.c) return;
43
52
  // Ownership moved away: what this session pinned as owner is no longer its to defend.
44
53
  if (event.type === "owner" && event.owner?.sessionId !== me()) s.pinned = undefined;
@@ -137,6 +146,37 @@ export function createMembership({ pi, cfg, s, me, tell }: Kit, { presence, elec
137
146
  }
138
147
  return { promoted: true, text: `You are now the main agent of tab ${s.info.tab}.` };
139
148
  };
140
- return { connect, connected, joinNet, promote, adoptOpener, /** Reads the tab's net again (its main, the labels); call_peer looks before it sends (callpeer.ts). */ sync };
149
+ /** The main steps down before pi replaces its session (boss_rotate): its record no longer names it, so the new session's ordinary claim is judged on a tab with no main. Sync: the owner's write, or one
150
+ * message to it, which the owner acks once the record is cleared. It may throw (a message that cannot be sent); `reclaim` undoes it either way. */
151
+ const resign = () => {
152
+ s.rotating = true; // its own guard does not crown it again meanwhile (guard.ts, election.ts)
153
+ let done: (acked: boolean) => void = () => {};
154
+ const settled = new Promise<boolean>((r) => (done = r)), id = `${me()}:${cfg.now()}:${Math.random().toString(36).slice(2)}`;
155
+ ack = { id, done, settled };
156
+ if (s.c.snapshot().owner?.sessionId === me()) return void (election.resign(s.c, me()), done(true));
157
+ s.c.publish({ type: "resign", id }, { audience: "owner" });
158
+ };
159
+ let ack: { id: string; done(acked: boolean): void; settled: Promise<boolean> } | undefined;
160
+ const revision = () => s.c.snapshot().state?.revision;
161
+ const recorded = () => (s.c.snapshot().state?.payload as { main?: string } | undefined)?.main;
162
+ /**
163
+ * A rotation that stopped before pi's teardown, after `resign` (rotate review round 4, F008): no snapshot from before the step-down is trusted. It waits for the owner's ack (or RESIGN_ACK_MS), reads the tab
164
+ * again, and makes an ordinary claim whose real result it reports. Without the ack the record may still name it from before the step-down, so it sends the claim anyway (it reaches the owner after the resign)
165
+ * and reads the result only after the record has changed and names someone.
166
+ */
167
+ const reclaim = async (): Promise<{ promoted: boolean; text: string }> => {
168
+ const acked = await Promise.race([ack?.settled ?? Promise.resolve(false), sleep(RESIGN_ACK_MS).then(() => false)]);
169
+ [ack, s.rotating] = [undefined, false];
170
+ await sync();
171
+ if (acked && !s.isMain) return promote(false);
172
+ const before = revision();
173
+ if (s.c.snapshot().owner?.sessionId === me()) await (s.queue = s.queue.then(() => election.claim(s.c, me(), false)));
174
+ else s.c.publish({ type: "claim", force: false }, { audience: "owner" });
175
+ const moved = await waitFor(sleep, () => revision() !== before && recorded() !== undefined, CLAIM_MS);
176
+ await sync();
177
+ if (s.isMain && moved) return { promoted: true, text: `You are the main agent of tab ${s.info.tab} again.` };
178
+ return { promoted: false, text: s.mainId && s.mainId !== me() ? `Tab ${s.info.tab} has another main agent, ${s.info.main}` : "The tab's owner did not confirm the claim within 5 s" };
179
+ };
180
+ return { connect, connected, joinNet, promote, resign, reclaim, adoptOpener, /** Reads the tab's net again (its main, the labels); call_peer looks before it sends (callpeer.ts). */ sync };
141
181
  }
142
182
  export type Membership = ReturnType<typeof createMembership>;
package/src/roles.ts CHANGED
@@ -30,7 +30,7 @@ import { TRAIN, type TrainId, trainFromToken, trainLabel, trainToken } from "./t
30
30
  export interface Ended { at: number; reason: "quit" | "new" | "resume" | "fork" | "signal" }
31
31
  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; /** A main's kind, for a restore before its first message, when pi has written no entry yet (docs/specs/2026-11-09-agent-kinds.md §6). */ duty?: MainKind; at: number; ended?: Ended; /** A main that opened its successor with boss_handover, once that successor took the handoff (RVR-F004): never raised as dead or revived, however it ends. */ handedOver?: HandedOver }
32
32
  /** The successor a main handed its work to: when, its session id, and the tab and pane it was opened in (the tower's refusal names the tab). */
33
- export interface HandedOver { at: number; to: string; tab?: string; pane?: string }
33
+ export interface HandedOver { at: number; to: string; tab?: string; pane?: string; /** A rotation in the same pane (boss_rotate, rotate.ts): a wait card's notice follows it (rotationmarks.ts). */ rotated?: true }
34
34
  /** 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. */
35
35
  export interface Here { paneId?: string; tabId?: string; workspaceId?: string; terminalId?: string; tabLabel?: string }
36
36
 
@@ -87,9 +87,10 @@ export function createRoles({ cfg, s, guiDir, tell }: Kit) {
87
87
  const dir = rolesDir(guiDir);
88
88
  const path = (file: string) => recordPath(guiDir, file);
89
89
  const load = (record: string, quiet = false): RoleRecord | undefined => loadRecord(record, quiet ? undefined : (why) => tell(`Straw Boss: could not read this session's role record: ${why}`, "warning"));
90
+ // A record marked rotated (boss_rotate) is lineage only, for its wait cards (rotationmarks.ts): its session gave the pane to the one it rotated to, so it holds, claims, and restores nothing (rotate review F004).
90
91
  const within = (here: Here): RoleRecord | undefined => {
91
92
  const record = s.file ? load(path(s.file)) : undefined;
92
- return record && here.paneId === record.pane && here.tabId === record.tab && here.workspaceId === record.workspace ? record : undefined;
93
+ return record && record.handedOver?.rotated !== true && here.paneId === record.pane && here.tabId === record.tab && here.workspaceId === record.workspace ? record : undefined;
93
94
  };
94
95
  /** The newest main record of a tab. A tab has one, but a demoted main's record from before the one-record rule may be left beside it. */
95
96
  const mainOf = (tab: string, workspace: string): RoleRecord | undefined => {
@@ -97,7 +98,7 @@ export function createRoles({ cfg, s, guiDir, tell }: Kit) {
97
98
  try {
98
99
  names = readdirSync(dir).filter((name) => name.endsWith(".json"));
99
100
  } catch { /* no records */ }
100
- const mains = names.flatMap((name) => load(join(dir, name), true) ?? []).filter((r) => r.role === "main" && r.tab === tab && r.workspace === workspace);
101
+ const mains = names.flatMap((name) => load(join(dir, name), true) ?? []).filter((r) => r.role === "main" && r.tab === tab && r.workspace === workspace && r.handedOver?.rotated !== true);
101
102
  return mains.sort((a, b) => b.at - a.at)[0];
102
103
  };
103
104
  const forget = () => {
@@ -169,8 +170,9 @@ export function createRoles({ cfg, s, guiDir, tell }: Kit) {
169
170
  for (const name of names) {
170
171
  try {
171
172
  const other = join(dir, name), record = load(other, true);
172
- // A tab has one main: the others' records, a demoted main's among them, would race this one at a restore.
173
- const rival = role === "main" && record?.role === "main" && record.tab === s.at.tabId && record.workspace === s.at.workspaceId;
173
+ // A tab has one main: the others' records, a demoted main's among them, would race this one at a restore. A main that rotated into this pane stays (boss_rotate): no restore takes a handed-over
174
+ // record back, it is older than this one, and its mark is what sends its wait cards on (rotationmarks.ts).
175
+ const rival = role === "main" && record?.role === "main" && record.tab === s.at.tabId && record.workspace === s.at.workspaceId && record.handedOver?.rotated !== true;
174
176
  if (rival) rmSync(other, { force: true });
175
177
  } catch { /* gone already, or unreadable: left for the next write */ }
176
178
  }
package/src/rotate.ts ADDED
@@ -0,0 +1,201 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { lstatSync } from "node:fs";
3
+ import { isAbsolute, join, resolve } from "node:path";
4
+ import { Type } from "typebox";
5
+ import { clean } from "./board.ts";
6
+ import type { MainKind } from "./duty.ts";
7
+ import type { Fork } from "./fork.ts";
8
+ import { forkTaken } from "./forktext.ts";
9
+ import { handoverSnapshot, writeHandoverTodos } from "./handovertodo.ts";
10
+ import { todosOf } from "./items.ts";
11
+ import { moveHolds } from "./link/holds.ts";
12
+ import { REARM_TEXT } from "./moments.ts";
13
+ import { FORK_OWED_ENTRY, owedOf } from "./owed.ts";
14
+ import { markHandedOver } from "./roles.ts";
15
+ import { ROTATE_MESSAGE } from "./rotatestart.ts";
16
+ import { noteLedger } from "./server/ledger.ts";
17
+ import { ENTRY, type Kit, type Rotation } from "./state.ts";
18
+ import { boundTickets, ticketsLine } from "./teamwork.ts";
19
+ import { snapshotOfBranch } from "./todo.ts";
20
+ import { type Topic, topicsDir, writeTopic } from "./topic.ts";
21
+
22
+ // boss_rotate (docs/specs/2026-11-30-boss-rotate.md): a main rotates its session in its own pane. The tool checks and schedules; it hands pi the line `/sb-rotate <token>`, which pi runs as an extension command
23
+ // (never a prompt, never the editor), and the command waits for the turn's end, checks again, and calls pi's own `ctx.newSession`. Its `setup` writes the new session's state; rotatestart.ts is the new session's side.
24
+
25
+ export const ROTATE_COMMAND = "sb-rotate";
26
+ export const BOSS_ROTATE_DESCRIPTION =
27
+ "Main only: rotate your session in this pane (a fresh pi session, as /new) keeping your name, kind, topic, forks, owed replies and tab. Call with reason alone before writing the handoff; then with its path. " +
28
+ "Runs when your turn ends; refused while a subagent, monitor, loop, watch or train step of yours runs.";
29
+ const parameters = () => Type.Object({
30
+ handoff: Type.Optional(Type.String({ description: "Existing handoff path (absolute or cwd-relative)." })),
31
+ reason: Type.String({ description: "One line of at most 200 characters." }),
32
+ });
33
+
34
+ export interface RotateDeps {
35
+ /** What still runs for this session (stillruns.ts): `gather` does the awaits (the watch list, Herdr's panes); `verdict` reads the dialogs, monitors and loops then, with no await; a read that failed counts. */
36
+ probe: { gather(): Promise<unknown>; verdict(facts: never): string[] };
37
+ /** A teammate's turn (link). */
38
+ remote(): boolean;
39
+ topics: { current(): Topic | undefined };
40
+ forks: { ready(ctx?: unknown): Promise<{ forks: Fork[]; kept: string[] }>; pass(forks: readonly Fork[], to: string): { went: Fork[]; kept: string[] } };
41
+ /** The main steps down at once, before newSession (membership.ts `resign`), and claims the tab again as any session does when the rotation stops before pi's teardown. */
42
+ membership: { resign(): void; reclaim(): Promise<{ promoted: boolean; text: string }> };
43
+ }
44
+ interface Scheduled { token: string; handoff: string; reason: string; forks: Fork[]; kept: string[] }
45
+ type Ctx = { hasPendingMessages?(): boolean; cwd?: string; ui?: { notify?(text: string, level?: string): void } };
46
+ type CommandCtx = Ctx & { waitForIdle?(): Promise<void>; newSession?(o: { parentSession?: string; setup?: (sm: SessionWriter) => Promise<void> }): Promise<{ cancelled: boolean }> };
47
+ /** What `setup` gets: pi's session manager of the new session, before anything of it is flushed. */
48
+ interface SessionWriter { getSessionId(): string; appendCustomEntry(customType: string, data: unknown): unknown; appendSessionInfo?(name: string): unknown }
49
+
50
+ /** The new session's first message: who rotated and why, the import, the handoff, and what sb carried or could not. Facts only; the session-rotation rule says the rest. */
51
+ export const rotationPrompt = (r: { name: string; from: string; reason: string; handoff: string; todosPath?: string; duty?: MainKind; forks: string; problems: string[] }) => [
52
+ `Straw Boss: this session took over from ${r.name} (session ${r.from}) in the same pane: it rotated itself with boss_rotate, and pi started this fresh session; its reason: ${r.reason}.`,
53
+ ...(r.todosPath ? [`First call todo with ${JSON.stringify({ action: "import", path: r.todosPath })} to restore its list with its ids, anchors and evidence. If the import is refused or the todo tool has no import action (older pi-todo-ledger), recreate the todos from the handoff text. Otherwise, do not recreate them.`] : []),
54
+ `Read the handoff file ${r.handoff} now and follow it as your session-rotation rule describes: take up the handoff todo and file it names, and recreate the monitors and loops it lists. sb carried over the replies it owed and reminds you of each.`,
55
+ ...(r.duty === "standing" ? [REARM_TEXT] : []),
56
+ `Your name, kind (${r.duty ?? "coordinator"}), topic and tab are the old session's. The old session is gone: there is no one to tell that you took over.`,
57
+ ...(r.forks ? [r.forks] : []),
58
+ ...(r.problems.length ? [`sb could not hand on: ${r.problems.join("; ")}. Tell the tower with call_tower if your work needs it.`] : []),
59
+ ].join("\n");
60
+
61
+ export function createRotate({ pi, cfg, s, me, role, guiDir }: Kit, d: RotateDeps) {
62
+ let scheduled: Scheduled | undefined, underWay = false, torn = false, registered = false;
63
+ const shown = new Set<string>(); // the tickets whose team_work reminder this session showed
64
+ pi.on("session_shutdown", () => void (torn = true));
65
+ const tickets = () => boundTickets(pi, handoverSnapshot(snapshotOfBranch(s.branch())).data?.tasks);
66
+ /** What a rotation would retire: what runs, a queued message, an open train step. Sync: `facts` are the probe's awaited reads, gathered before (rotate review round 2, F002). */
67
+ const blockers = (ctx: Ctx | undefined, facts: unknown) => {
68
+ const steps = (todosOf(snapshotOfBranch(s.branch())) ?? []).filter((t) => t.sb && (t.status === "pending" || t.status === "in_progress"));
69
+ return [
70
+ ...d.probe.verdict(facts as never),
71
+ ...(ctx?.hasPendingMessages?.() ? ["messages wait in your queue: read them first"] : []),
72
+ ...(steps.length ? [`open train step ${steps.map((t) => `#${t.id}`).join(", ")}: finish or return it first`] : []),
73
+ ];
74
+ };
75
+ const callerRefusal = (): string | undefined => {
76
+ if (s.remoteOrigin || d.remote()) return "A teammate's turn cannot rotate this main's session";
77
+ if (s.isTower || role() === "tower") return "A tower does not rotate: boss_rotate is a main's";
78
+ if (role() === "train") return "A train does not rotate: it ends with its milestone report";
79
+ if (role() !== "main") return "Only a tab's main rotates its session; a member has no role to pass on";
80
+ if (s.openedBy?.startsWith("link:")) return `A main opened for a teammate's device (${s.openedBy.slice(0, 40)}) does not rotate: its new session would run outside the device's revoke and signed stop`;
81
+ if (s.closing) return "Not rotated: this session is closing";
82
+ };
83
+ const regular = (path: string) => { try { return lstatSync(path).isFile(); } catch { return false; } };
84
+ /**
85
+ * Every refusal in one place (rotate review F002, round 2 F002): the probe's async reads come first, its only await; then every sync check is read after it: the dialogs, monitors, loops, subagents and watches
86
+ * the probe gathered or reads now, a queued message, the train steps, the caller, the handover state, the handoff file, and the tickets not yet shown. The tool runs it, and the command again right before
87
+ * newSession with no await between, so nothing that changed in between (a handover, a deleted handoff, a monitor started while the probe waited) is missed.
88
+ */
89
+ const refusal = async (ctx: Ctx | undefined, handoff: string): Promise<string | undefined> => {
90
+ const facts = await d.probe.gather();
91
+ const blocking = blockers(ctx, facts), caller = callerRefusal();
92
+ if (caller) return caller;
93
+ if (s.saved.successor?.main) return `Not rotated: this main handed over to session ${s.saved.successor.main} already, and its work is that session's`;
94
+ if (s.saved.handoverFrom) return `Not rotated: you took over from session ${s.saved.handoverFrom} and have not told it yet: tell it with call_peer (to: caller) first`;
95
+ if (!regular(handoff)) return `Not rotated: the handoff file ${handoff} does not exist (or is no regular file): write it first`;
96
+ if (blocking.length) return `Not rotated: ${blocking.join("; ")}. A rotation would retire it: wait for it, or stop it, then call boss_rotate again`;
97
+ const bound = tickets(), unseen = bound.filter((t) => !shown.has(t));
98
+ if (unseen.length) return (unseen.forEach((t) => shown.add(t)), `Not rotated: hand off the tickets first.${ticketsLine(bound)} Then call boss_rotate again with the same handoff.`);
99
+ };
100
+ /** The old session stays: its model hears why at once, in a message that starts a turn. `back`: its claim of the tab again, when it had stepped down; a session that took the tab meanwhile keeps it. */
101
+ const stay = (why: string, back?: { promoted: boolean; text: string }) => {
102
+ const role = !back || back.promoted ? "This session stays the tab's main and" : `This session stepped down for the rotation and could not take the tab back (${clean(back.text, 200)}); it`;
103
+ try { pi.sendMessage({ customType: ROTATE_MESSAGE, content: `sb: the rotation did not happen: ${why}. ${role} still owns everything it had (its topic, forks, owed replies, held devices and wait cards). Call boss_rotate again once that is settled.`, display: true }, { triggerTurn: true }); } catch { /* the session is gone already */ }
104
+ };
105
+ /** A rotation that stopped after the main stepped down (or tried to) and before pi's teardown: the main claims its tab again, after the owner acked the step-down, and is told what the claim got. */
106
+ const back = async (why: string) => {
107
+ stay(why, await d.membership.reclaim().catch((error) => ((s.rotating = false), { promoted: false, text: (error as Error).message })));
108
+ };
109
+
110
+ /** `setup` of pi's newSession: the old session is torn down, so only the plain data gathered before is used; every write is its own, and one that fails is named in the first message. */
111
+ function handOn(sm: SessionWriter, p: Scheduled & { todosPath?: string }, o: { from: string; file?: string; name: string; pane: string; tab: string; workspace: string; duty?: MainKind; openedBy?: string; topic?: Topic; owed: ReturnType<typeof owedOf>; now: number }) {
112
+ const to = sm.getSessionId(), problems: string[] = [];
113
+ const step = (what: string, write: () => unknown) => { try { write(); } catch (error) { problems.push(`${what} (${clean((error as Error).message, 160)})`); } };
114
+ if (o.topic) step("your topic", () => writeTopic(topicsDir(guiDir), { ...o.topic!, session: to }));
115
+ const forks = d.forks.pass(p.forks, to);
116
+ step("the devices you held", () => moveHolds(join(guiDir, "link"), o.now, o.from, to));
117
+ if (o.file) step("the old session's role record", () => markHandedOver(guiDir, o.file!, { at: o.now, to, tab: o.tab, pane: o.pane, rotated: true }));
118
+ noteLedger(guiDir, { kind: "handover", id: to, session: o.from, workspace: o.workspace, why: "rotate" }, o.now, () => {});
119
+ const forkText = [...(forks.went.length ? [forkTaken({ name: o.name, id: o.from }, forks.went)] : []), ...p.kept, ...forks.kept].join(" ");
120
+ const prompt = rotationPrompt({ name: o.name, from: o.from, reason: p.reason, handoff: p.handoff, ...(p.todosPath ? { todosPath: p.todosPath } : {}), ...(o.duty ? { duty: o.duty } : {}), forks: forkText, problems });
121
+ const rotation: Rotation = { from: o.from, name: o.name, ...(o.file ? { file: o.file } : {}), pane: o.pane, tab: o.tab, at: o.now, prompt };
122
+ try {
123
+ if (o.name) sm.appendSessionInfo?.(o.name);
124
+ sm.appendCustomEntry(ENTRY, { rotation, ...(o.duty ? { duty: o.duty, dutyFrom: null, dutyWhy: `rotated from session ${o.from}`, dutyAt: o.now } : {}), ...(o.openedBy ? { openedBy: o.openedBy, openedPane: o.pane } : {}) });
125
+ if (o.owed.length) sm.appendCustomEntry(FORK_OWED_ENTRY, { owes: o.owed.map(({ id, from, at, text, tower }) => ({ id, from, at, text, tower })) });
126
+ } catch (error) {
127
+ process.stderr.write(`straw-boss: the new session of ${o.from} did not take sb's entries: ${(error as Error).message}\n`);
128
+ }
129
+ }
130
+
131
+ /** The command's run: after the turn, checked again, then pi's own newSession. */
132
+ async function run(p: Scheduled, c: CommandCtx) {
133
+ if (typeof c.newSession !== "function" || typeof c.waitForIdle !== "function") return stay("this pi cannot replace its session from an extension command (ctx.newSession)");
134
+ await c.waitForIdle();
135
+ const no = await refusal(c, p.handoff); // after the last await: nothing below awaits before newSession
136
+ if (no) return stay(no.replace(/^Not rotated: /, ""));
137
+ // Plain data only from here: pi's teardown ends this session's pi, its context, and its intercom id before `setup` runs.
138
+ // The list is exported again now, at the turn's end (rotate review F003): what the turn changed after the call goes with it, and a write that fails leaves no file to import (handovertodo.ts).
139
+ let todosPath: string | undefined;
140
+ try { const t = writeHandoverTodos(p.handoff, snapshotOfBranch(s.branch())); todosPath = t.path ?? undefined; } catch { /* no file: the new session recreates the todos from the handoff */ }
141
+ const now = cfg.now(), from = me(), o = { from, ...(s.file ? { file: s.file } : {}), name: pi.getSessionName() || s.ownName || from.slice(0, 8), pane: s.at.paneId, tab: s.at.tabId, workspace: s.at.workspaceId, ...(s.duty ? { duty: s.duty } : {}), ...(s.openedBy ? { openedBy: s.openedBy } : {}), owed: owedOf(s.branch(), from, now), now };
142
+ const topic = d.topics.current();
143
+ // The main steps down now (rotate review round 3): the tab's record no longer names it, so the new session's ordinary claim finds no main even while the broker still lists this id. No claim
144
+ // ever replaces a live main; a member that claims in the gap keeps the tab, and the new session stays a member.
145
+ let asked = false;
146
+ try {
147
+ d.membership.resign(); // inside the try (rotate review round 4, F009): a throw here is a stop before the teardown, rolled back as one; nothing awaits between it and newSession
148
+ asked = true;
149
+ const out = await c.newSession({ ...(o.file ? { parentSession: o.file } : {}), setup: async (sm) => handOn(sm, { ...p, ...(todosPath ? { todosPath } : {}) }, { ...o, ...(topic ? { topic } : {}) }) });
150
+ if (out?.cancelled) await back("pi cancelled the new session (an extension's session_before_switch refused it)");
151
+ } catch (error) {
152
+ if (!torn) return back(`${asked ? "pi could not start the new session" : "this main could not step down"}: ${clean((error as Error).message, 200)}`);
153
+ process.stderr.write(`straw-boss: the rotation of session ${from} failed after pi ended it: ${(error as Error).message}\n`);
154
+ }
155
+ }
156
+
157
+ // Registered at the factory, as /boss is: pi looks a command up when it runs the line.
158
+ pi.registerCommand(ROTATE_COMMAND, {
159
+ description: "sb's own step of boss_rotate (typing it does nothing)",
160
+ handler: async (args, ctx) => {
161
+ const p = scheduled;
162
+ if (!p || args.trim() !== p.token) return void (ctx as Ctx).ui?.notify?.("sb: no rotation of this session is scheduled here; a main schedules one with boss_rotate.", "info");
163
+ [scheduled, underWay] = [undefined, true];
164
+ try { await run(p, ctx as CommandCtx); } finally { underWay = false; }
165
+ },
166
+ });
167
+ return {
168
+ /** boss_rotate, with the net tools of a joined session. */
169
+ addTool() {
170
+ if (registered) return;
171
+ registered = true;
172
+ pi.registerTool({
173
+ name: "boss_rotate", label: "boss_rotate", description: BOSS_ROTATE_DESCRIPTION, parameters: parameters(),
174
+ execute: async (_id, { handoff, reason }, _signal, _update, ctx) => {
175
+ const caller = callerRefusal();
176
+ if (caller) throw new Error(caller);
177
+ const why = reason.replace(/\s+/g, " ").trim(), bound = tickets();
178
+ if (!why || why.length > 200) throw new Error("reason is required: one line of 1 to 200 characters");
179
+ if (handoff === undefined) {
180
+ bound.forEach((t) => shown.add(t));
181
+ return { content: [{ type: "text" as const, text: `No rotation yet.${ticketsLine(bound)} Write the handoff (the goal, the anchor and its last result, the monitors and loops to recreate, the replies you owe, the user's last words), then call boss_rotate with its path and reason.` }], details: { prepared: true } };
182
+ }
183
+ const path = isAbsolute(handoff) ? handoff : resolve((ctx as Ctx)?.cwd ?? process.cwd(), handoff);
184
+ if (underWay) throw new Error("A rotation of this session is under way: wait for it");
185
+ const no = await refusal(ctx as Ctx, path);
186
+ if (no) throw new Error(no);
187
+ if (typeof pi.sendUserMessage !== "function") throw new Error("This pi cannot run a command for a tool (pi.sendUserMessage), which boss_rotate needs");
188
+ let todos: ReturnType<typeof writeHandoverTodos>;
189
+ try { todos = writeHandoverTodos(path, snapshotOfBranch(s.branch())); } catch (error) { todos = { written: false, path: null, count: 0, reason: String(error) }; }
190
+ const made = await d.forks.ready(ctx);
191
+ // A schedule that pi never ran (the line went nowhere) is replaced: the newest call is the one that counts.
192
+ const p: Scheduled = (scheduled = { token: randomUUID(), handoff: path, reason: why, forks: made.forks, kept: made.kept });
193
+ pi.sendUserMessage(`/${ROTATE_COMMAND} ${p.token}`, { expandPromptTemplates: true });
194
+ const what = todos.written ? `Wrote ${todos.count} tasks to ${todos.path}; sb writes the list again when the turn ends, and the first message says to import that.` : `No todos file written (0 tasks exported): ${todos.reason}.`;
195
+ return { content: [{ type: "text" as const, text: `sb rotates this session once this turn ends, so end your turn now and start nothing more (a monitor, loop, watch or subagent stops it): pi starts a fresh session in this pane under your name and kind, with your topic, forks and owed replies, and its first message names ${path}. ${what}${made.kept.length ? ` ${made.kept.join(" ")}` : ""}` }], details: { scheduled: true, todos } };
196
+ },
197
+ });
198
+ },
199
+ };
200
+ }
201
+ export type Rotate = ReturnType<typeof createRotate>;
@@ -0,0 +1,24 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { ENTRY, type Rotation, type State } from "./state.ts";
3
+
4
+ // The new session's side of a rotation (docs/specs/2026-11-30-boss-rotate.md): pi started it in its predecessor's pane (`ctx.newSession`), and sb's `setup` wrote the rotation entry into it before pi flushed
5
+ // anything to disk, so only this process wrote it. session.ts asks `rotationOf` at the start; a rotation claims the tab as any session does (its predecessor stepped down before pi's teardown; election.ts refuses it while any main lives) and then takes its first message, once.
6
+
7
+ export const ROTATE_MESSAGE = "straw-boss-rotate";
8
+ /** A rotation entry older than this proves nothing: the new session starts within seconds of its `setup`. */
9
+ const CLAIM_MS = 10 * 60_000;
10
+
11
+ /** The rotation this start continues: a `new` start whose branch carries the entry, naming the session file pi says came before and this pane and tab, written in the last ten minutes. */
12
+ export function rotationOf(saved: State["saved"], event: { reason?: string; previousSessionFile?: string }, here: { paneId?: string; tabId?: string } | undefined, now: number): Rotation | undefined {
13
+ const r = saved.rotation;
14
+ if (event.reason !== "new" || !r || typeof r !== "object" || typeof r.prompt !== "string" || typeof r.at !== "number") return undefined;
15
+ return r.file === event.previousSessionFile && r.pane === here?.paneId && r.tab === here?.tabId && Math.abs(now - r.at) < CLAIM_MS ? r : undefined;
16
+ }
17
+ /** Spends the claim (a /reload of this session is the same main, and asks nothing again) and sends the first message, which starts a turn; `refused` is why sb could not make it the tab's main. */
18
+ export function deliverRotation(pi: Pick<ExtensionAPI, "appendEntry" | "sendMessage">, s: Pick<State, "saved">, r: Rotation, refused?: string): void {
19
+ if (s.saved.rotation === null) return;
20
+ s.saved.rotation = null;
21
+ pi.appendEntry(ENTRY, { rotation: null });
22
+ const content = refused ? `${r.prompt}\nsb could not make this session the tab's main (${refused}): call boss_promote, then go on.` : r.prompt;
23
+ pi.sendMessage({ customType: ROTATE_MESSAGE, content, display: true }, { triggerTurn: true });
24
+ }
@@ -0,0 +1,18 @@
1
+ import { fileId, successorOf } from "./peertargets.ts";
2
+ import { readRecords } from "./roles.ts";
3
+
4
+ // The rotations of the role records (boss_rotate, docs/specs/2026-11-30-boss-rotate.md): a main that rotated in its own pane marks its record `handedOver` with `rotated: true`, naming the new session.
5
+ // A wait card it raised is the new session's: the sb server tells the session its raiser rotated to (waitpress.ts), and boss_wait_ask asks it the cards its predecessors raised. A plain handover is not followed. No pi imports.
6
+
7
+ /** Each main that rotated, by session id: the session it rotated to. */
8
+ export function rotations(stateDir: string): Map<string, string> {
9
+ return new Map(readRecords(stateDir).flatMap(({ record }) => (record.role === "main" && record.handedOver?.rotated === true && typeof record.handedOver.to === "string" ? [[fileId(record.file), record.handedOver.to] as const] : [])));
10
+ }
11
+ /** The session `id`'s work is in now, after one rotation after another; `id` itself when it never rotated. */
12
+ export const rotatedTo = (stateDir: string, id: string): string => successorOf(id, rotations(stateDir), "");
13
+ /** The sessions that rotated, one after another, into `id`. */
14
+ export function rotatedFrom(stateDir: string, id: string): string[] {
15
+ const back = new Map([...rotations(stateDir)].map(([from, to]) => [to, from] as const)), out: string[] = [];
16
+ for (let at = back.get(id); at !== undefined && at !== id && !out.includes(at); at = back.get(at)) out.push(at);
17
+ return out;
18
+ }
@@ -11,7 +11,7 @@ export type LedgerKind = (typeof KINDS)[number];
11
11
  /** Where a boss wait's answer came in: a terminal (pi's `/boss wait` or `/boss memory`, the tower prompt, a run's pane, the dialog of `boss_wait_ask`), this computer's page, a paired phone, a box's controller, or a message the tower took that names it. */
12
12
  export type AnsweredBy = "terminal" | "gui" | "phone" | "box" | "tower";
13
13
  /** The `why` each kind may carry; the others carry none. */
14
- const WHYS: Partial<Record<LedgerKind, readonly string[]>> = { wait_closed: ["resolved", "dropped"], thread_close: ["done", "blocked", "abandoned"], call_tower: ["milestone", "shared", "blocked", "route", "fork"], wrap: ["wrapped", "auto-wrapped", "refused", "auto"] };
14
+ const WHYS: Partial<Record<LedgerKind, readonly string[]>> = { wait_closed: ["resolved", "dropped"], thread_close: ["done", "blocked", "abandoned"], call_tower: ["milestone", "shared", "blocked", "route", "fork"], wrap: ["wrapped", "auto-wrapped", "refused", "auto"], handover: ["rotate"] };
15
15
  const BYS: readonly string[] = ["terminal", "gui", "phone", "box", "tower"];
16
16
  export interface LedgerEvent { kind: LedgerKind; id: string; session?: string | null; workspace?: string | null; why?: string; item?: string; by?: AnsweredBy }
17
17
  export interface LedgerRow { v: 1; at: number; kind: LedgerKind; id: string; session: string | null; workspace: string | null; why?: string; item?: string; by?: AnsweredBy }
@@ -63,6 +63,7 @@ import { readTowerRuns } from "./towerruns.ts";
63
63
  import type { CarBook } from "./carbook.ts";
64
64
  import { noteTrains } from "./trainnote.ts";
65
65
  import { createGate } from "./towergate.ts";
66
+ import { rotatedTo } from "../rotationmarks.ts";
66
67
  import { BOOK_KEY, entryLine, markRead, readBook, unreadOf } from "./logbook.ts";
67
68
  import { appendEvent, appendQuiet, bindDir, deleteService, HEAD_KEY, headDir, listServices, purgeAll, purgeQueues, putLedger, queueLength, readHeadService, readQueue, readLedger, readService, type ServiceRecord, towerDir, unbindDir, writeService } from "./towerstore.ts";
68
69
 
@@ -1423,6 +1424,7 @@ export function createTowers(o: TowersOptions): Towers {
1423
1424
  send: (to, text, wait) => l.reach!.post(to, text, "wait_card", "session", false, undefined, undefined, { wait }),
1424
1425
  boss: (text) => void runs.boss(l.record.workspace, text, "the boss (wait card)", { press: true }),
1425
1426
  ...(o.waits ? { linkPress: (card: string, act: string) => o.waits!.pressed(workspace, card, act) } : {}),
1427
+ successor: (id: string) => rotatedTo(slot.stateDir, id), // a raiser that rotated in its own pane (docs/specs/2026-11-30-boss-rotate.md)
1426
1428
  }, workspace, json, via);
1427
1429
  }
1428
1430
  return memoryRequest(slot, workspace, now(), json, log);
@@ -49,7 +49,11 @@ export interface PressDeps {
49
49
  autoOn?(): boolean;
50
50
  /** A card a teammate device raised (`link:<device>`, docs/specs/2026-11-21-box-mac-waits.md §2.4) has no session to tell: the wait router tells the device, and says how that went (undefined: no wait of its own). */
51
51
  linkPress?(card: string, act: string): Promise<Delivery | undefined>;
52
+ /** The session a raiser rotated to in its own pane (rotationmarks.ts `rotatedTo`, docs/specs/2026-11-30-boss-rotate.md): its cards are that session's. Without it the raiser is told by its own id. */
53
+ successor?(id: string): string;
52
54
  }
55
+ /** The session a card's notice goes to: its raiser, or the session the raiser rotated to; a teammate device's card stays the device's. */
56
+ const raiserOf = (d: Pick<PressDeps, "successor">, id: string | undefined) => (id && !id.startsWith("link:") && d.successor ? d.successor(id) : id);
53
57
 
54
58
  /** The `wait_card` message a raiser is sent: the notice, and for a done or a choice, that it is the boss's answer to act on (a secret's notice names its step, a decline leaves the next step to the tower) (main.md no longer says so: docs/specs/2026-11-26-just-in-time-prompts.md). */
55
59
  const cardNotice = (plan: Pick<Plan, "act" | "notice">) => (plan.act === "done" || plan.act === "choose" ? `${plan.notice!} ${ACT_ON_IT}` : plan.notice!);
@@ -158,7 +162,7 @@ export const HELD_MS = 25 * 60_000;
158
162
  export async function lateNotice(d: PressDeps, workspace: string, json: Record<string, unknown>, via: PressDoor = "pi"): Promise<{ status: number; body: Record<string, unknown> }> {
159
163
  const key = `${workspace}\n${String(json.id)}`, hold = held.get(key);
160
164
  if (via !== "ask") return { status: 409, body: { error: "refused", reason: "no notice is held for that session" } };
161
- const raiser = updateMemory(d.slot, workspace, d.now(), () => undefined).memory.entries.find((e) => e.id === json.id)?.card?.from?.id;
165
+ const raiser = raiserOf(d, updateMemory(d.slot, workspace, d.now(), () => undefined).memory.entries.find((e) => e.id === json.id)?.card?.from?.id);
162
166
  const mine = hold !== undefined && raiser !== undefined && json.asker === raiser;
163
167
  // `clear`: the tool's own result came back, so the held notice is not needed. Only the raiser's own call clears it, and the hold stays (marked) until it expires, so a stop that lands during the request can `recover` it.
164
168
  if (json.clear === true) return (mine && (hold.cleared = true), { status: 200, body: { cleared: mine } });
@@ -191,7 +195,7 @@ export async function pressRequest(d: PressDeps, workspace: string, json: Record
191
195
  } catch (cause) {
192
196
  return failure(cause);
193
197
  }
194
- const raiser = plan.card?.from?.id;
198
+ const raiser = raiserOf(d, plan.card?.from?.id);
195
199
  let status: Delivery | undefined;
196
200
  if (raiser?.startsWith("link:") && d.linkPress) status = await d.linkPress(plan.entry.id, plan.act).catch((): Delivery => "failed");
197
201
  else if (plan.notice && raiser) {
package/src/session.ts CHANGED
@@ -19,6 +19,7 @@ import { childRevive } from "./childrevive.ts";
19
19
  import { keyOf, REARM_TEXT, REVIVE_TOKEN } from "./revive.ts";
20
20
  import { armSignals, signalSeen } from "./signalseen.ts";
21
21
  import { restored } from "./restored.ts";
22
+ import { deliverRotation, rotationOf } from "./rotatestart.ts";
22
23
  import { annotateLost } from "./host/lost.ts";
23
24
  import { hostOwnsRuns } from "./host/state.ts";
24
25
  import type { RunMode } from "./runmode.ts";
@@ -258,9 +259,11 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
258
259
  if (s.isMain) roles.remember("main"); // the guard may have crowned it during the join, before the opener was known: the record names it for a Herdr restore (roles.ts)
259
260
  await presence.publish(); // sb_opened_by was cleared at shutdown
260
261
  }
261
- if (!claimed && !resumed) return;
262
+ const rotated = rotationOf(s.saved, event as { reason?: string; previousSessionFile?: string }, s.at, cfg.now()); // boss_rotate's new session in its predecessor's pane (rotatestart.ts)
263
+ if (!claimed && !resumed && !rotated) return;
262
264
  const taken = await membership.promote(false).catch((error) => {
263
265
  if (resumed) keepRestored = true; // the owner may still confirm after the claim timed out, and that refresh must not open a tower
266
+ if (rotated) deliverRotation(pi, s, rotated, (error as Error).message);
264
267
  throw error;
265
268
  });
266
269
  if (!taken.promoted) {
@@ -268,6 +271,7 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
268
271
  if (resumed) roles.forget(); // another main holds the tab, and this session stays a member: its record would claim the next restore
269
272
  } else if (!claimed) await membership.adoptOpener(); // a no-op when the refresh that made it the main did so already (membership.ts)
270
273
  mainDuty.migrate(pi.getSessionName()); // a restored or opened main with the signs of an integrator
274
+ if (rotated) deliverRotation(pi, s, rotated, taken.promoted ? undefined : taken.text); // its first message once it is the tab's main
271
275
  // A standing main a Herdr restart resumed hears what its revive and successor hear: the restart retired its watches, monitors, and loops (T4 review F001).
272
276
  if (resumed && taken.promoted && event.reason === "startup" && mainDuty.now() === "standing") pi.sendMessage({ customType: ARM_MESSAGE, content: `Straw Boss: a Herdr restart resumed this standing main. ${REARM_TEXT}`, display: true }, { triggerTurn: true });
273
277
  };
package/src/state.ts CHANGED
@@ -24,14 +24,16 @@ export const ALLY_ENTRY = "straw-boss-ally";
24
24
  export const REGISTER = "intercom:extension-register";
25
25
 
26
26
  export interface Channel {
27
- snapshot(): { connected: boolean; supported: boolean; owner?: { sessionId: string }; state?: { payload: unknown } };
27
+ snapshot(): { connected: boolean; supported: boolean; owner?: { sessionId: string }; state?: { revision?: number; payload: unknown } };
28
28
  publish(payload: unknown, options?: { audience?: "owner" | "capable" }): void;
29
29
  commitState(payload: unknown, expectedRevision?: number): void;
30
30
  listSessions(): Promise<Session[]>;
31
31
  }
32
32
  export interface SendResult { requestId?: string; status: string; code?: string; detail?: string }
33
33
  /** `duty*`: the main's kind and why it has it, written whole at each switch (docs/specs/2026-11-09-agent-kinds.md §2: entries merge field by field, so every entry carries all four). */
34
- export interface Saved { tower?: boolean; openedBy?: string | null; openedPane?: string; train?: TrainId; duty?: MainKind; dutyFrom?: MainKind | null; dutyWhy?: string; dutyAt?: number; /** When a tower revived this session (docs/specs/2026-11-23-tower-revive.md §6): its inherited subagents are looked at from every start after. */ revived?: number; /** The successor this main opened with boss_handover (handover.ts): its pane, while it lives, refuses a second one. */ successor?: { pane: string; tab: string; at: number; /** Its session id: the role record's `handedOver` mark (roles.ts). */ main?: string; /** When the successor's own extension said it took over (rotclose.ts): this main closes itself once nothing of it runs. */ took?: number; /** When the tower was told this main still could not close 6 hours after (rotclose.ts): it waits no longer. */ blockedTold?: number }; /** A successor: the main that handed over to it (its pane's `sb_handover_from`), until that main heard it took over (rotclose.ts). */ handoverFrom?: string | null }
34
+ export interface Saved { tower?: boolean; openedBy?: string | null; openedPane?: string; train?: TrainId; duty?: MainKind; dutyFrom?: MainKind | null; dutyWhy?: string; dutyAt?: number; /** When a tower revived this session (docs/specs/2026-11-23-tower-revive.md §6): its inherited subagents are looked at from every start after. */ revived?: number; /** The successor this main opened with boss_handover (handover.ts): its pane, while it lives, refuses a second one. */ successor?: { pane: string; tab: string; at: number; /** Its session id: the role record's `handedOver` mark (roles.ts). */ main?: string; /** When the successor's own extension said it took over (rotclose.ts): this main closes itself once nothing of it runs. */ took?: number; /** When the tower was told this main still could not close 6 hours after (rotclose.ts): it waits no longer. */ blockedTold?: number }; /** A successor: the main that handed over to it (its pane's `sb_handover_from`), until that main heard it took over (rotclose.ts). */ handoverFrom?: string | null; /** A session a rotation started in its predecessor's pane (rotate.ts), until it claimed the role and took its first message (rotatestart.ts). */ rotation?: Rotation | null }
35
+ /** What a rotation's `setup` writes into the new session (docs/specs/2026-11-30-boss-rotate.md): the session it replaces, where, when, and the first message. */
36
+ export interface Rotation { from: string; name: string; file?: string; pane: string; tab: string; at: number; prompt: string }
35
37
  export type Role = "tower" | "main" | "member" | "train";
36
38
  export type Scope = "tab" | "workspace" | "towers" | "all";
37
39
  /**
@@ -56,6 +58,8 @@ export interface State {
56
58
  /** The conditional tools, decided at each session start and nowhere else (docs/specs/2026-11-23-lite-main.md §4): a tool list that changes mid-session rewrites the cached prompt. */
57
59
  toolSet: { link: boolean; cars: boolean; carApp: boolean } | undefined;
58
60
  holdsTower: boolean;
61
+ /** This main stepped down for boss_rotate's new session (membership.ts `resign`): its guard crowns no one meanwhile; a rotation that fails before pi's teardown clears it and claims again. */
62
+ rotating?: boolean;
59
63
  /** Why this session cannot join: it sits in a sub workspace, or Herdr could not say whether it does. */
60
64
  barred: string | undefined;
61
65
  /** While the sub workspace check has no definitive answer: asks Herdr again (or joins the one in flight) and settles `barred`. A caller that needs the net waits for it first (membership.ts). */
package/src/stillruns.ts CHANGED
@@ -18,22 +18,28 @@ export interface ProbeDeps {
18
18
  }
19
19
 
20
20
  export function createProbe({ cfg, s, me }: Pick<Kit, "cfg" | "s" | "me">, d: ProbeDeps) {
21
- /** `pane`: a pane Herdr shows blocked counts; `sure`: a watch list that does not answer counts too (T4 review F002), and so does a pane list that fails or lacks this pane. */
22
- const why = async (pane: boolean, sure: boolean): Promise<string[]> => {
21
+ /** The async reads, done first: the sb server's watch list and Herdr's panes (rotate review round 2, F002). */
22
+ const gather = async () => {
23
+ const watches = await d.ask?.({ cmd: "watch-list", session: me() }, { start: "never" }).catch(() => undefined);
24
+ const all = await panes(cfg.run).catch(() => undefined);
25
+ return { watches, all };
26
+ };
27
+ /** The verdict on gathered facts, with the sync blockers (a dialog or monitor, a loop) read now, after every await. `pane`: a pane Herdr shows blocked counts; `sure`: a watch list that does not answer counts too (T4 review F002), and so does a pane list that fails or lacks this pane. */
28
+ const verdict = ({ watches, all }: Awaited<ReturnType<typeof gather>>, pane: boolean, sure: boolean): string[] => {
23
29
  const out: string[] = [];
24
30
  const b = d.blockers();
25
31
  if (b) out.push(b);
26
32
  if (armedLoop(d.loopsDir ?? join(homedir(), ".pi", "loops"), me(), cfg.now())) out.push("a loop is active");
27
- const watches = await d.ask?.({ cmd: "watch-list", session: me() }, { start: "never" }).catch(() => undefined);
28
33
  if (watches?.ok && Array.isArray(watches.watches) && watches.watches.length) out.push(`${watches.watches.length} boss_watch watch${watches.watches.length > 1 ? "es run" : " runs"} (boss_watch stop ends one)`);
29
34
  else if (sure && !(watches?.ok && Array.isArray(watches.watches))) out.push("the watch list does not answer");
30
- const all = await panes(cfg.run).catch(() => undefined), mine = all?.find((p) => p.pane_id === s.at?.paneId);
35
+ const mine = all?.find((p) => p.pane_id === s.at?.paneId);
31
36
  if (sure && !mine) out.push("Herdr's pane list did not answer or lacks this pane"); // its subagents are unknown (RV6-F001)
32
37
  const kids = all ? subagents(mine, all, cfg.now()).filter((r) => !r.ended).length : 0;
33
38
  if (kids) out.push(`${kids} subagent${kids > 1 ? "s are" : " is"} running`);
34
39
  if (pane && mine?.agent_status === "blocked") out.push("this pane waits on a dialog");
35
40
  return out;
36
41
  };
42
+ const why = async (pane: boolean, sure: boolean) => verdict(await gather(), pane, sure);
37
43
  return {
38
44
  /** The idle nudge: a read that fails counts as nothing there. */
39
45
  nudge: () => why(true, false),
@@ -41,6 +47,9 @@ export function createProbe({ cfg, s, me }: Pick<Kit, "cfg" | "s" | "me">, d: Pr
41
47
  strict: () => why(true, true),
42
48
  /** boss_wrap's checks: its own dialog is the pane's, so a blocked pane does not count. */
43
49
  wrap: () => why(false, false),
50
+ /** strict in two halves, for a caller that must act with no await after its verdict (boss_rotate): `gather` awaits, `verdict` does not. */
51
+ gather,
52
+ verdict: (facts: Awaited<ReturnType<typeof gather>>) => verdict(facts, true, true),
44
53
  };
45
54
  }
46
55
  export type Probe = ReturnType<typeof createProbe>;
package/src/teamwork.ts CHANGED
@@ -1,11 +1,14 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  type Registry = Pick<ExtensionAPI, "getAllTools">;
3
3
  export const hasTeamWork = (pi: Registry): boolean => pi.getAllTools().some(({ name }) => name === "team_work");
4
- export function ticketHandoff(pi: Registry, tasks: readonly Record<string, unknown>[] = []): string {
4
+ /** The tickets the open todos are bound to (`metadata.ticket`), once each; none while no `team_work` tool is registered. */
5
+ export function boundTickets(pi: Registry, tasks: readonly Record<string, unknown>[] = []): string[] {
5
6
  const ids = new Set<string>();
6
7
  for (const { status, metadata } of hasTeamWork(pi) ? tasks : []) {
7
8
  if (status !== "pending" && status !== "in_progress") continue;
8
9
  if (metadata && typeof metadata === "object" && "ticket" in metadata && typeof metadata.ticket === "string" && metadata.ticket.trim()) ids.add(metadata.ticket.trim());
9
10
  }
10
- return ids.size ? ` Call team_work handoff for each ticket not yet handed off: ${[...ids].join(", ")}. Posting requires confirmation.` : "";
11
+ return [...ids];
11
12
  }
13
+ export const ticketsLine = (ids: readonly string[]): string => (ids.length ? ` Call team_work handoff for each ticket not yet handed off: ${ids.join(", ")}. Posting requires confirmation.` : "");
14
+ export const ticketHandoff = (pi: Registry, tasks: readonly Record<string, unknown>[] = []): string => ticketsLine(boundTickets(pi, tasks));
package/src/tools.ts CHANGED
@@ -64,7 +64,7 @@ export const towerSendParameters = () => Type.Object({
64
64
  forward: Type.Optional(Type.String({ description: FORWARD_DESCRIPTION })),
65
65
  });
66
66
  /** Every tool sb registers, all of them after the child return (index.ts): a role that lists one fails `/boss roles-check` (rolescheck.ts). tests/roles-check.test.ts pins it to the recorded registry. */
67
- export const PARENT_ONLY: readonly string[] = ["board_read", "board_set", "boss_auto", "boss_broadcast", "boss_close_main", "boss_duty", "boss_fork", "boss_handover", "boss_open_main", "boss_pair", "boss_promote", "boss_rename", "boss_revive_main", "boss_server", "boss_topic", "boss_wait_ask", "boss_watch", "boss_wrap", "call_peer", "call_tower", "ledger_sweep", "link_request", "sb_doctor", "sb_ward", "tower_done", "tower_list", "tower_memory", "tower_reply", "tower_send", "tower_topic", "train_car"];
67
+ export const PARENT_ONLY: readonly string[] = ["board_read", "board_set", "boss_auto", "boss_broadcast", "boss_close_main", "boss_duty", "boss_fork", "boss_handover", "boss_open_main", "boss_pair", "boss_promote", "boss_rename", "boss_revive_main", "boss_rotate", "boss_server", "boss_topic", "boss_wait_ask", "boss_watch", "boss_wrap", "call_peer", "call_tower", "ledger_sweep", "link_request", "sb_doctor", "sb_ward", "tower_done", "tower_list", "tower_memory", "tower_reply", "tower_send", "tower_topic", "train_car"];
68
68
  /** `boss_revive_main` (docs/specs/2026-11-23-tower-revive.md §4): its description and parameters, the same for a tower session and a tower run (runmode.ts proxies the latter to the server). */
69
69
  export const REVIVE_DESCRIPTION = "List the mains and trains of this workspace that have a role record, with their state (live, dead, quit, restoring, stale, invalid), or revive a dead one: the same pi session comes back in a new tab as the same Straw Boss identity (its role, kind, name, board row, todos, and the waits it held), and it picks up its own subagents. Call it when a main_died notice names one and its work is not done, or when a request names a main that died. Revive a quit one only when a request names it. Refused, with the reason, for members, towers, mains opened for a teammate's device, a session a live pane runs, a second try of one death, and a session that died twice in a day after a revive.";
70
70
  export const reviveParameters = () => Type.Object({
@@ -0,0 +1,34 @@
1
+ import { isObject, type Json } from "./spec.ts";
2
+
3
+ // A main's `todo move` batch under the train rules (pi-todo-ledger 0.12.0; MOVE-F005, docs/specs/2026-11-30-boss-fork.md, The train guard on a move). Pure: the ledger's change comes in, the refusal lines go out.
4
+
5
+ const ids = (value: unknown): number[] => (Array.isArray(value) ? value.filter((d): d is number => Number.isInteger(d)) : []);
6
+ const live = (t: Json) => t.status !== "deleted";
7
+ const isTrain = (t: Json) => isObject(t.metadata) && t.metadata.sb !== undefined;
8
+
9
+ /**
10
+ * What the train holds in a move batch, judged on the whole batch before anything moves: a todo that carries `metadata.sb` (only an integrator imports one, and the source cannot see where the batch goes), a todo that
11
+ * waits on one, and a todo one waits on, even when `dropBlockers` would cut the edge. Each is named with its reason, and a last line says nothing moved; none when the batch holds nothing of the train.
12
+ */
13
+ export function heldInMove(change: { params: Record<string, unknown>; before: readonly unknown[]; after: readonly unknown[] }): string[] {
14
+ const tasks = change.before.filter((t): t is Json => isObject(t) && Number.isInteger(t.id));
15
+ const trains = tasks.filter((t) => live(t) && isTrain(t));
16
+ // The batch: the ids the call names, and any task the ledger would take that the call did not name (a tombstone in `after` that `before` had live).
17
+ const batch = new Set(ids(change.params.ids));
18
+ for (const t of change.after) if (isObject(t) && t.status === "deleted" && tasks.some((b) => b.id === t.id && live(b))) batch.add(t.id as number);
19
+ const lines: string[] = [], held: number[] = [];
20
+ for (const t of tasks.filter((x) => live(x) && batch.has(x.id as number)).sort((a, b) => (a.id as number) - (b.id as number))) {
21
+ const id = t.id as number;
22
+ const why = [
23
+ ...(isTrain(t) ? [`sb: todo #${id} is a train todo (metadata.sb): it stays with the integrator that holds it`] : []),
24
+ ...trains.filter((s) => ids(t.blockedBy).includes(s.id as number)).map((s) => `sb: todo #${id} waits on train todo #${String(s.id)}: it stays with the train todo it waits on`),
25
+ ...trains.filter((s) => ids(s.blockedBy).includes(id)).map((s) => `sb: todo #${id} blocks train todo #${String(s.id)}: it stays with the train todo that waits on it`),
26
+ ];
27
+ if (why.length) (lines.push(...why), held.push(id));
28
+ }
29
+ // A train todo the batch would change otherwise (an edge the ledger drops that the rules above did not name): kept whole too.
30
+ const was = new Map(tasks.map((t) => [t.id as number, JSON.stringify(t)] as const));
31
+ const changed = change.after.find((t): t is Json => isObject(t) && isTrain(t) && live(t) && was.get(t.id as number) !== JSON.stringify(t));
32
+ if (!lines.length && changed) lines.push(`sb: todo #${String(changed.id)} is a train todo (metadata.sb): this move would change its edges, and it stays as it is`);
33
+ return lines.length ? [...lines, `sb: nothing moved; move the others without ${held.length ? held.map((id) => `#${id}`).join(", ") : "changing it"}`] : [];
34
+ }
package/src/trainguard.ts CHANGED
@@ -15,6 +15,7 @@ import { type BoardRead, type BoardStep, boardPath, capBoard, type CarRow, facts
15
15
  import { type CarView, coordinatorWord, forwardsFor, forwardsOf, noticeSatisfied, receivedTold, type TerminalState } from "./train/cars.ts";
16
16
  import { fieldsOf } from "./headerfields.ts";
17
17
  import { type Effect, isObject, type Json, shortCode, STEP_REQUIRED, todoEffects, validateStep } from "./train/spec.ts";
18
+ import { heldInMove } from "./train/moves.ts";
18
19
  import { type FactStep, stepWaits, type TrainFacts, type Wait, waitMessage } from "./train/waits.ts";
19
20
  import { type Acceptor, buildBoard, buildYard, freezeStep, type Row } from "./trainboard.ts";
20
21
  import type { MainDuty } from "./mainduty.ts";
@@ -558,16 +559,18 @@ export function createTrainGuard(pi: GuardPi, env: GuardEnv) {
558
559
  if (input.action === "import") {
559
560
  if (me) return ["sb: a train's list is never imported"];
560
561
  if (!env.isMain() || !after) return []; // only the ledger supports import; its check, not tool_call, receives the list
561
- let project: string | undefined;
562
- // An append (a move file's tasks, docs/specs/2026-11-30-boss-fork.md) is judged on what it appends: the tasks from the list's next id on, never those already in it.
562
+ // An append (a move file's tasks, docs/specs/2026-11-30-boss-fork.md) is judged on what it appends: the tasks from the list's next id on, never those already in it. Its train todos must be of the
563
+ // project of the train todos the list holds, as a create of one must (integratorTodo): a train of another project is another integrator's.
564
+ const held = input.append === true ? state().rows.map(sbOf).find((s) => s?.kind === "train")?.project : undefined;
565
+ let project = typeof held === "string" ? held : undefined, carried = false;
563
566
  for (const t of input.append === true ? after.filter((t) => isObject(t) && (t.id as number) >= state().nextId) : after) {
564
567
  if (!isObject(t) || !isObject(t.metadata) || t.metadata.sb === undefined) continue;
565
568
  if (env.duty() !== "integrator") return [NOT_INTEGRATOR];
566
569
  const sb = t.metadata.sb, refusals = trainRefusals(sb, ctx, t.status as string, t.id as number, project);
567
570
  if (refusals.length) return refusals;
568
- if (isObject(sb) && typeof sb.project === "string") project = sb.project;
571
+ if (isObject(sb) && typeof sb.project === "string") (project = sb.project, carried = true);
569
572
  }
570
- return project === undefined ? [] : contractRefusal();
573
+ return carried ? contractRefusal() : [];
571
574
  }
572
575
  const integrators = !me && env.isMain() && (hasSb(input) || changesTrainTodo(input, state));
573
576
  const reasons = me ? await trainTodo(input, ctx, me, state) : integrators ? (env.duty() === "integrator" ? await integratorTodo(input, ctx, state) : [NOT_INTEGRATOR]) : [];
@@ -590,16 +593,13 @@ export function createTrainGuard(pi: GuardPi, env: GuardEnv) {
590
593
  }
591
594
  }
592
595
  /**
593
- * A move batch (pi-todo-ledger 0.12.0; MOVE-F005, docs/specs/2026-11-30-boss-fork.md) under the rules a removal already has: a train's list is never imported and never moves, and a main keeps each todo that carries
594
- * `metadata.sb`, moved or changed by the move (an edge dropped), since only an integrator imports one and the source cannot see where the batch goes. Everything else passes, as the delete of a plain todo does.
596
+ * A move batch (pi-todo-ledger 0.12.0; MOVE-F005, docs/specs/2026-11-30-boss-fork.md) under the rules a removal already has: a train's list is never imported and never moves, and a main keeps what the train holds,
597
+ * judged on the whole batch (train/moves.ts). Everything else passes, as the delete of a plain todo does; a todo whose child still runs is the live-child guard's (`sb-fork`, forkmain.ts).
595
598
  */
596
599
  function moveReasons(change: LedgerChange): string[] {
597
600
  if (env.train()) return [TRAIN_STAYS];
598
601
  if (env.pending?.()) return [UNSETTLED];
599
- if (!env.isMain()) return [];
600
- const was = new Map(change.before.flatMap((t) => (isObject(t) && Number.isInteger(t.id) ? [[t.id as number, JSON.stringify(t)] as const] : [])));
601
- const held = change.after.find((t): t is Json => isObject(t) && isObject(t.metadata) && t.metadata.sb !== undefined && was.get(t.id as number) !== JSON.stringify(t));
602
- return held ? [`sb: todo #${String(held.id)} is a train todo (metadata.sb): it stays with the integrator that holds it, and this move would ${held.status === "deleted" ? "take it away" : "change its edges"}. Move the others without it`] : [];
602
+ return env.isMain() ? heldInMove(change) : [];
603
603
  }
604
604
  const contractRefusal = (): string[] => { const contract = contractNow(); return contract && !contract.ok ? [contract.refusal] : []; };
605
605
  // A guard that fails does not let the call through: the train's checks are enforcement.
package/src/waitask.ts CHANGED
@@ -7,6 +7,7 @@ import { terminalOnlyOpts } from "./intercept.ts";
7
7
  import type { Ask } from "./host.ts";
8
8
  import { every } from "./lanface.ts";
9
9
  import { type Locale as Lang, localeOf } from "./locale.ts";
10
+ import { rotatedFrom } from "./rotationmarks.ts";
10
11
  import type { Kit } from "./state.ts";
11
12
  import { card, type CardEnd, keyOf, read, tabsOf, waitUi, type WaitUi } from "./waitcmd.ts";
12
13
  import { type Listed, pending, pressedWord } from "./waitview.ts";
@@ -23,7 +24,7 @@ export const waitAskParameters = () => Type.Object({
23
24
  });
24
25
 
25
26
  /** Whose cards a session may have shown: the ones it raised (a main, by its session id), one tower's (a local run, by its workspace), or every tower's (the head's run). */
26
- export type Scope = { kind: "raised"; by: string } | { kind: "tower"; workspace: string } | { kind: "all" };
27
+ export type Scope = { kind: "raised"; by: string; /** The sessions that rotated into `by` (rotationmarks.ts): the cards they raised are its own. */ from?: readonly string[] } | { kind: "tower"; workspace: string } | { kind: "all" };
27
28
  type Reply = { ok: boolean; error?: string; [key: string]: unknown };
28
29
  export interface WaitAskDeps {
29
30
  lang: Lang;
@@ -62,7 +63,8 @@ export function createWaitAsk(d: WaitAskDeps) {
62
63
  const scope = d.scope(), only = scope.kind === "tower" ? scope.workspace : undefined, asker = scope.kind === "raised" ? scope.by : undefined;
63
64
  // `ask: true`: a device with no boss at it refuses the read, before anything is drawn (waitpress.ts `askRefused`).
64
65
  const list = () => read({ ask: d.ask, own: undefined }, only, { ask: true });
65
- const listed = await list(), mine = listed.rows.filter((r) => scope.kind !== "raised" || r.wait.card?.from?.id === scope.by);
66
+ const raised = (r: Row) => scope.kind !== "raised" || r.wait.card?.from?.id === scope.by || (scope.from ?? []).includes(r.wait.card?.from?.id ?? "");
67
+ const listed = await list(), mine = listed.rows.filter(raised);
66
68
  const name = (r: Row) => (scope.kind === "all" ? `${r.wait.id} (${r.tower.label})` : r.wait.id);
67
69
  const lines: string[] = [], queue: Row[] = [];
68
70
  const pressedAt: { workspace: string; id: string }[] = [];
@@ -128,7 +130,7 @@ export function createWaitAsk(d: WaitAskDeps) {
128
130
  // A tab may have changed while another one was open. Never draw its cached acts on return.
129
131
  const fresh = await list().catch((e: Error) => ({ error: e.message }));
130
132
  if ("error" in fresh) return { line: `${id}: ${fresh.error}`, stop: "the list could not be read" };
131
- const r = fresh.rows.find((v) => keyOf(v) === key && (scope.kind !== "raised" || v.wait.card?.from?.id === scope.by));
133
+ const r = fresh.rows.find((v) => keyOf(v) === key && raised(v));
132
134
  if (fresh.auto || d.auto.on()) { autoStarted(); return cut!; }
133
135
  if (!r || !pending(r.wait)) return { line: `${id}: answered elsewhere first: ${r ? pressedWord("en", r.wait) : "it is no longer open"}.` };
134
136
  if (d.now() - began >= CAP_MS) { left.set(key, d.now()); return { line: `${id}: no answer (the card stood ${Math.floor((d.now() - began) / 60_000)} min open); ${STAYS}`, stop: "the dialog stood quiet" }; }
@@ -195,7 +197,7 @@ function pressedLine(row: Row, json: Record<string, unknown>, raiser: boolean):
195
197
  /** `boss_wait_ask` of a joined session (tools.ts): only a tab's main agent asks, only the cards it raised, and its own result is the answer (no `wait_card` follows). */
196
198
  export function mainWaitAsk({ pi, cfg, s, me, role, tell, guiDir }: Kit, o: { ask?: Ask; here: Here; auto: WaitAskDeps["auto"] }): void {
197
199
  registerWaitAsk(pi, {
198
- lang: localeOf(cfg.env, guiDir), scope: () => ({ kind: "raised", by: me() }), auto: o.auto, here: o.here, now: cfg.now, every: cfg.face?.every ?? every, tell,
200
+ lang: localeOf(cfg.env, guiDir), scope: () => ({ kind: "raised", by: me(), from: rotatedFrom(guiDir, me()) }), auto: o.auto, here: o.here, now: cfg.now, every: cfg.face?.every ?? every, tell,
199
201
  refusal: () => (role() !== "main" ? "Only a tab's main agent has sb ask the boss its wait cards again (the ones it raised); a member's go through its main, and a train's stay with the tower." : s.remoteOrigin ? "A teammate's turn does not ask the boss of this computer." : undefined),
200
202
  ask: async (request) => (o.ask ? o.ask(request, { start: "never" }) : { ok: false, error: "The sb server is not available in this session." }),
201
203
  });
package/src/wrapup.ts CHANGED
@@ -74,6 +74,8 @@ export function createWrapUp(kit: Kit, d: WrapDeps) {
74
74
  look,
75
75
  /** What still runs for this session: a dialog, monitor, loop, watch, or subagent, or a pane Herdr shows blocked; a read that fails counts as running. */
76
76
  running: probe.strict,
77
+ /** The same reads split for boss_rotate: the awaits, then a verdict with no await (stillruns.ts). */
78
+ probe,
77
79
  /** `boss_wrap`, with the net tools of a joined session that is no tower. */
78
80
  addTool() {
79
81
  pi.registerTool({