pi-straw-boss 0.88.3 → 0.89.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-straw-boss",
3
- "version": "0.88.3",
3
+ "version": "0.89.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",
@@ -0,0 +1,45 @@
1
+ import { rmSync } from "node:fs";
2
+ import { join, parse } from "node:path";
3
+ import { writeJson } from "./server/record.ts";
4
+ import { isSnapshotV1 } from "./todoledger.ts";
5
+
6
+ const empty = "no tasks remain", invalid = "the todo snapshot does not match todo/v1";
7
+ const object = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
8
+
9
+ /** Normalize the raw branch snapshot, never the board's abbreviated view. Task fields unknown to sb pass through. */
10
+ export function handoverSnapshot(snapshot: unknown) {
11
+ if (snapshot === undefined) return { reason: empty };
12
+ if (!object(snapshot) || !Array.isArray(snapshot.tasks) || typeof snapshot.nextId !== "number") return { reason: invalid };
13
+ let nextId = snapshot.nextId;
14
+ const kept: Record<string, unknown>[] = [], seen = new Set<unknown>();
15
+ for (const t of snapshot.tasks as unknown[]) {
16
+ if (!object(t) || seen.has(t.id)) return { reason: invalid };
17
+ seen.add(t.id);
18
+ if (typeof t.id === "number") nextId = Math.max(nextId, t.id + 1);
19
+ if (t.status !== "deleted") kept.push(t);
20
+ }
21
+ if (!kept.length) return { reason: empty };
22
+ const ids = new Set(kept.map((t) => t.id));
23
+ const tasks = kept.map(({ blockedBy, ...task }) => {
24
+ if (!Array.isArray(blockedBy)) return blockedBy === undefined ? task : { ...task, blockedBy };
25
+ const deps = blockedBy.filter((id) => ids.has(id));
26
+ return deps.length ? { ...task, blockedBy: deps } : task;
27
+ });
28
+ const data = { v: 1, tasks, nextId };
29
+ return isSnapshotV1(data) ? { data } : { reason: invalid };
30
+ }
31
+
32
+ /** The successor receives a path only for a file this call wrote. Replace it atomically, before the tab opens. */
33
+ export function writeHandoverTodos(handoff: string, snapshot: unknown) {
34
+ const { dir, name } = parse(handoff), path = join(dir, `${name}.todos.json`);
35
+ const { data, reason } = handoverSnapshot(snapshot);
36
+ if (!data) {
37
+ rmSync(path, { force: true }); // no stale list beside a reused handoff
38
+ return { written: false as const, count: 0, path: null, reason };
39
+ }
40
+ try { writeJson(path, data); } catch (error) {
41
+ rmSync(path, { force: true }); // a failed replacement must not leave the old snapshot for this handoff
42
+ throw error;
43
+ }
44
+ return { written: true as const, count: data.tasks.length, path };
45
+ }
package/src/link/allow.ts CHANGED
@@ -31,7 +31,7 @@ const NAMES = [/^\.env/i, /\.pem$/i, /\.key$/i, /^id_/i, /\.p12$/i];
31
31
  const HOME_DIRS = [".pi", ".ssh", ".aws", ".config", ".gnupg"];
32
32
  /** The tools that look at paths and are allowed inside the project, and the ones allowed whatever their arguments (`tower_done` ends an ally run of the sb server and does nothing else; `ally_escalate` opens a link wait and writes no peer text into a session). */
33
33
  const SEARCH = new Set(["grep", "find", "ls"]);
34
- const FREE = new Set(["tower_list", "board_read", "todo", "tower_done", "ally_escalate"]);
34
+ const FREE = new Set(["tower_list", "board_read", "tower_done", "ally_escalate"]);
35
35
  /** Argument names that hold a path in pi's tools and in the tools of the extensions around it. */
36
36
  const PATH_KEYS = ["path", "file_path", "filePath", "file", "directory", "dir", "cwd", "paths", "files"];
37
37
 
@@ -125,8 +125,13 @@ export function decide(tool: string, input: Record<string, unknown>, senders: Se
125
125
  if (tool === "link_request") return { kind: "refuse", reason: "a remote turn cannot ask for a link action; link_request is the boss's, so a trust change (for example to dispatch) is asked from a local turn" };
126
126
  const bad = pathArgs(input, s).find((p) => pathDenied(p, s));
127
127
  if (bad) return { kind: "refuse", reason: "that path is on the deny list of remote turns" };
128
- if (FREE.has(tool)) return { kind: "allow" };
129
- if (tool === "read") return typeof input.path === "string" && allowedFile(resolveArg(input.path, s.cwd, s.home), s) ? { kind: "allow" } : { kind: "gate" };
128
+ if (FREE.has(tool) || (tool === "todo" && input.action !== "import")) return { kind: "allow" };
129
+ if (tool === "read" || tool === "todo") {
130
+ if (typeof input.path !== "string") return { kind: "gate" };
131
+ const abs = resolveArg(input.path, s.cwd, s.home);
132
+ // Ledger paths are filenames, not pi read shorthands. Gate an ambiguous spelling rather than approve a different file.
133
+ return (tool === "read" || abs === resolve(s.cwd, input.path)) && allowedFile(abs, s) ? { kind: "allow" } : { kind: "gate" };
134
+ }
130
135
  if (SEARCH.has(tool)) {
131
136
  const roots = pathArgs(input, s);
132
137
  if (roots.length === 0) roots.push(s.cwd);
package/src/reviver.ts CHANGED
@@ -139,13 +139,14 @@ export interface SuccessorEnv {
139
139
  send(to: string, message: string): Promise<{ status: string; code?: string; detail?: string }>;
140
140
  trustDir?: string;
141
141
  }
142
- export interface SuccessorRequest { from: { id: string; name: string }; handoff: string; reason: string; duty?: CoordinatorDuty; openedBy?: string }
142
+ export interface SuccessorRequest { from: { id: string; name: string }; handoff: string; todosPath?: string; reason: string; duty?: CoordinatorDuty; openedBy?: string }
143
143
  export interface Successor { tab: string; pane: string; main: string; name: string }
144
144
 
145
145
  /** The successor's first prompt: the handoff file to read, and who handed over. Facts only; the session-rotation rule says the rest. */
146
146
  export const successorPrompt = (r: SuccessorRequest) => [
147
147
  `Straw Boss: main ${r.from.name} (session ${r.from.id}) opened this tab for you with boss_handover and handed its work over to you; its reason: ${r.reason}.`,
148
- `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, recreate the monitors and loops it lists, drop completed todos, and keep its replies owed.`,
148
+ ...(r.todosPath ? [`First call todo with ${JSON.stringify({ action: "import", path: r.todosPath })} to restore the old main's 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.`] : []),
149
+ `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, recreate the monitors and loops it lists, and keep its replies owed.`,
149
150
  `Your kind is already ${r.duty ?? "coordinator"} and your name is the old main's. Then tell ${r.from.name} by intercom (send, to "${r.from.id}") that you took over; it gives up its role after that.`,
150
151
  ].join("\n");
151
152
 
package/src/tools.ts CHANGED
@@ -23,6 +23,7 @@ import type { Reach } from "./reach.ts";
23
23
  import type { ServerLook } from "./server-look.ts";
24
24
  import { ENTRY, type Kit } from "./state.ts";
25
25
  import { snapshotOfBranch } from "./todo.ts";
26
+ import { writeHandoverTodos } from "./handovertodo.ts";
26
27
  import { todosOf } from "./items.ts";
27
28
  import { integrationOff } from "./trainswitch.ts";
28
29
  import { isRoleLabel, ownsBoard, trainLabel } from "./trainrole.ts";
@@ -245,7 +246,10 @@ export function createTools({ pi, cfg, s, guiDir, me, role }: Kit, { mainDuty, p
245
246
  if (net.ps.some((p) => p.pane_id === held.pane && p.agent)) throw new Error(`Your successor in pane ${held.pane} (tab ${held.tab}) is still live: one at a time. Tell it by intercom, or wait until it took over.`);
246
247
  }
247
248
  const name = pi.getSessionName() || s.ownName || me().slice(0, 8);
248
- const next = await openSuccessor({ run: cfg.run, sleep: cfg.sleep, workspaceId: s.at.workspaceId, cwd, sessions: () => s.c.listSessions(), send: (to, message) => post(to, message, "handoff", "main", true), trustDir: trustDir(guiDir) }, { from: { id: me(), name }, handoff: path, reason: why, ...(s.duty ? { duty: s.duty } : {}), ...(s.openedBy ? { openedBy: s.openedBy } : {}) });
249
+ let todos: ReturnType<typeof writeHandoverTodos>;
250
+ try { todos = writeHandoverTodos(path, snapshotOfBranch(s.branch())); }
251
+ catch (error) { todos = { written: false, path: null, count: 0, reason: String(error) }; }
252
+ const next = await openSuccessor({ run: cfg.run, sleep: cfg.sleep, workspaceId: s.at.workspaceId, cwd, sessions: () => s.c.listSessions(), send: (to, message) => post(to, message, "handoff", "main", true), trustDir: trustDir(guiDir) }, { from: { id: me(), name }, handoff: path, ...(todos.written ? { todosPath: todos.path } : {}), reason: why, ...(s.duty ? { duty: s.duty } : {}), ...(s.openedBy ? { openedBy: s.openedBy } : {}) });
249
253
  s.saved.successor = { pane: next.pane, tab: next.tab, at: cfg.now(), main: next.main };
250
254
  pi.appendEntry(ENTRY, { successor: s.saved.successor });
251
255
  // RVR-F004: the successor took the handoff, so this main's record says so: a later Herdr close of this tab raises no main_died, and no tower revives it.
@@ -254,7 +258,7 @@ export function createTools({ pi, cfg, s, guiDir, me, role }: Kit, { mainDuty, p
254
258
  try { listen(); } catch { /* no pi-intercom channel: the tower's ask goes unanswered and says so; the handover itself stands */ }
255
259
  const told = await openTower(undefined, false).then((tower) => post(tower.id, handedNotice(name, me(), next), "call_tower", "tower", false, undefined, "milestone")).then((r) => r.status === "sent", () => false);
256
260
  const closer = told ? "your workspace's tower was told and closes this session once your successor is live" : "no tower of this workspace took the notice, so the boss closes this session";
257
- return { text: `Opened your successor in tab ${next.tab} (session ${next.main}) and handed it ${path}. When it tells you it took over, give up your role as your rule says: boss_duty coordinator (if you are standing or integrator), boss_rename to "old ${name} (handed over to ${next.main.slice(0, 8)})", stop your monitors and loops, clear your board, and wait to be closed: ${closer}.`, details: { ...next, towerTold: told } };
261
+ return { text: `Opened your successor in tab ${next.tab} (session ${next.main}) and handed it ${path}. ${todos.written ? `Wrote ${todos.count} tasks to ${todos.path}.` : `No todos file written (0 tasks exported): ${todos.reason}.`} When it tells you it took over, give up your role as your rule says: boss_duty coordinator (if you are standing or integrator), boss_rename to "old ${name} (handed over to ${next.main.slice(0, 8)})", stop your monitors and loops, clear your board, and wait to be closed: ${closer}.`, details: { ...next, towerTold: told, todos } };
258
262
  } finally {
259
263
  handing = false;
260
264
  }
package/src/trainguard.ts CHANGED
@@ -421,6 +421,14 @@ export function createTrainGuard(pi: GuardPi, env: GuardEnv) {
421
421
 
422
422
  // ---- the integrator's `train` todo (§7.4)
423
423
 
424
+ /** Checks both new and imported trains. Only a new departure needs receipt forwards from this branch. */
425
+ function trainRefusals(sb: unknown, ctx: Ctx, status: string, id: number, project?: string): string[] {
426
+ const refusals = validateTrainTodo(sb, { status, id, project });
427
+ if (refusals.length || !isObject(sb) || !isObject(sb.spec)) return refusals;
428
+ const cars = sb.spec.cars as CarRow[], app = String(sb.app), config = readAppIntegration(appsDir(ctx), app);
429
+ return config.ok ? [...claimedRefusals(cars), ...evidenceRefusals(cars, ctx, app, config.accept)] : [config.refusal];
430
+ }
431
+
424
432
  async function integratorTodo(input: Json, ctx: Ctx, state: TodoState): Promise<string[]> {
425
433
  if (input.action !== "create" && input.action !== "update") return [];
426
434
  const { rows, nextId } = state();
@@ -430,12 +438,7 @@ export function createTrainGuard(pi: GuardPi, env: GuardEnv) {
430
438
  for (const effect of todoEffects(input, rows, nextId)) {
431
439
  const sb = effect.metadata?.sb;
432
440
  if (sb === undefined || effect.status === "deleted") continue;
433
- const refusals = validateTrainTodo(sb, { status: effect.status, id: effect.id, ...(typeof project === "string" ? { project } : {}) });
434
- if (!refusals.length && isObject(sb) && isObject(sb.spec)) {
435
- // What the app requires is read from its apps.json here and in the train's manifest check, never from a flag a model passes (TB-F001); a file that cannot be read refuses (TB-F002 too: stages that list uat).
436
- const cars = (sb.spec.cars as CarRow[]) ?? [], config = readAppIntegration(appsDir(ctx), String(sb.app));
437
- refusals.push(...(config.ok ? [...claimedRefusals(cars), ...evidenceRefusals(cars, ctx, String(sb.app), config.accept)] : [config.refusal]));
438
- }
441
+ const refusals = trainRefusals(sb, ctx, effect.status, effect.id, typeof project === "string" ? project : undefined);
439
442
  // The manifest goes to the tower only when every car is received, its slip came from the coordinator the tower's forward names, and sb has told that coordinator (§5.5, §7.4).
440
443
  if (!refusals.length && effect.status === "in_progress" && rows.find((r) => r.id === effect.id)?.status !== "in_progress" && isObject(sb) && isObject(sb.spec)) {
441
444
  const got = views ?? (typeof sb.project === "string" ? await fetchViews(sb.project) : "sb: the train todo names no project");
@@ -547,10 +550,23 @@ export function createTrainGuard(pi: GuardPi, env: GuardEnv) {
547
550
  // ---- pi
548
551
 
549
552
  /** The refusals of a `todo` call, judged on the list `state` gives, whichever path asks: the tool_call of rpiv-todo's call, or pi-todo-ledger's check. */
550
- async function todoReasons(input: Json, ctx: Ctx, state: TodoState): Promise<string[]> {
553
+ async function todoReasons(input: Json, ctx: Ctx, state: TodoState, after?: readonly unknown[]): Promise<string[]> {
551
554
  const me = env.train();
552
555
  try {
553
556
  if (!me && env.pending?.()) return [UNSETTLED];
557
+ if (input.action === "import") {
558
+ if (me) return ["sb: a train's list is never imported"];
559
+ if (!env.isMain() || !after) return []; // only the ledger supports import; its check, not tool_call, receives the list
560
+ let project: string | undefined;
561
+ for (const t of after) {
562
+ if (!isObject(t) || !isObject(t.metadata) || t.metadata.sb === undefined) continue;
563
+ if (env.duty() !== "integrator") return [NOT_INTEGRATOR];
564
+ const sb = t.metadata.sb, refusals = trainRefusals(sb, ctx, t.status as string, t.id as number, project);
565
+ if (refusals.length) return refusals;
566
+ if (isObject(sb) && typeof sb.project === "string") project = sb.project;
567
+ }
568
+ return project === undefined ? [] : contractRefusal();
569
+ }
554
570
  const integrators = !me && env.isMain() && (hasSb(input) || changesTrainTodo(input, state));
555
571
  const reasons = me ? await trainTodo(input, ctx, me, state) : integrators ? (env.duty() === "integrator" ? await integratorTodo(input, ctx, state) : [NOT_INTEGRATOR]) : [];
556
572
  // The skills the prompts follow must be the ones they assume; a call that changes nothing (a todo read) is let through.
@@ -591,10 +607,10 @@ export function createTrainGuard(pi: GuardPi, env: GuardEnv) {
591
607
  if (!isObject(change) || !isObject(change.params) || !Array.isArray(change.before) || !Array.isArray(change.after)) return "sb: the train guard got a change it cannot read; try again";
592
608
  const known = typeof change.sessionId === "string" ? seen.get(change.sessionId) : undefined;
593
609
  const ctx: Ctx = { cwd: typeof change.cwd === "string" ? change.cwd : known?.cwd, sessionManager: { getBranch: () => { if (!known) throw new Error(`sb has not seen session ${String(change.sessionId)}`); return known.sessionManager.getBranch(); } } };
594
- const reasons = await todoReasons(change.params, ctx, () => rowsOfSnapshot({ tasks: change.before, nextId: nextIdOf(change.before, change.after) }));
610
+ const reasons = await todoReasons(change.params, ctx, () => rowsOfSnapshot({ tasks: change.before, nextId: nextIdOf(change.before, change.after) }), change.after);
595
611
  return reasons.length ? reasons.join("\n") : undefined;
596
612
  }
597
- const register = () => pi.events?.emit?.(GUARD_EVENT, { v: 1, id: LEDGER_GUARD_ID, check: ledgerCheck });
613
+ const register = () => pi.events?.emit?.(GUARD_EVENT, { v: 1, id: LEDGER_GUARD_ID, imports: true, check: ledgerCheck });
598
614
  register(); // a ledger that loaded first hears it now; one that loads later asks with todo:ready
599
615
  pi.events?.on(READY_EVENT, (d) => {
600
616
  if (!isObject(d) || d.v !== 1) return;