pi-straw-boss 0.87.0 → 0.87.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -296,7 +296,7 @@ import {
296
296
  } from "./chunk-RZVFQ3L5.mjs";
297
297
 
298
298
  // src/server/main.ts
299
- import { homedir as homedir16 } from "node:os";
299
+ import { homedir as homedir17 } from "node:os";
300
300
  import { join as join60 } from "node:path";
301
301
 
302
302
  // src/boardauto.ts
@@ -11941,6 +11941,15 @@ var JOBS = 50;
11941
11941
  var DETAIL = 120;
11942
11942
  var num2 = (v, lo, hi) => typeof v === "number" && Number.isFinite(v) && v >= lo && v <= hi ? v : void 0;
11943
11943
  var capDir = (boardDir) => join30(dirname10(boardDir), "capacity");
11944
+ function readBudget(stateDir) {
11945
+ let b;
11946
+ try {
11947
+ b = JSON.parse(readFileSync19(join30(stateDir, "config.json"), "utf8")).capacity?.budget;
11948
+ } catch {
11949
+ return void 0;
11950
+ }
11951
+ return typeof b === "number" && Number.isFinite(b) && b > 0 && b <= 1e3 ? b : void 0;
11952
+ }
11944
11953
  var DEVICE = "_device.json";
11945
11954
  var SENT = "_sent.json";
11946
11955
  function writeJson2(dir, name2, value) {
@@ -11963,9 +11972,9 @@ var readJson2 = (file3) => {
11963
11972
  return void 0;
11964
11973
  }
11965
11974
  };
11966
- var jobsOf = (v) => Array.isArray(v) ? v.slice(0, JOBS).flatMap((j) => {
11975
+ var jobsOf = (v, max = JOBS) => Array.isArray(v) ? v.slice(0, max).flatMap((j) => {
11967
11976
  const points = num2(j?.points, 0, 10), owner = clean(j?.owner, 64);
11968
- return points === void 0 ? [] : [{ ...owner ? { owner } : {}, points }];
11977
+ return points === void 0 ? [] : [{ ...owner ? { owner } : {}, points, ...num2(j?.until, 0, 864e13) !== void 0 ? { until: j.until } : {} }];
11969
11978
  }) : [];
11970
11979
  var removeCap = (dir, session) => void (safeSession(session) && rmSync7(join30(dir, `${session}.json`), { force: true }));
11971
11980
  function readCaps(dir) {
@@ -11979,7 +11988,7 @@ function readCaps(dir) {
11979
11988
  if (raw?.v !== 1 || raw.session !== session || !safeSession(session) || num2(raw.updated, 0, 864e13) === void 0) return [];
11980
11989
  const p = raw.pause, at = num2(p?.at, 0, 864e13), until = num2(p?.until, 0, 864e13), detail = clean(p?.detail, DETAIL);
11981
11990
  const pause = p?.reason === "quota" && at !== void 0 ? { reason: "quota", at, ...until !== void 0 ? { until } : {}, ...detail ? { detail } : {} } : void 0;
11982
- return [{ v: 1, session, updated: raw.updated, doing: jobsOf(raw.doing), ready: jobsOf(raw.ready), open: num2(raw.open, 0, 200) ?? 0, ...pause ? { pause } : {} }];
11991
+ return [{ v: 1, session, updated: raw.updated, doing: jobsOf(raw.doing), ready: jobsOf(raw.ready, 200), ...Array.isArray(raw.deadlines) ? { deadlines: raw.deadlines.slice(0, 200).filter((n) => num2(n, 0, 864e13) !== void 0) } : {}, open: num2(raw.open, 0, 200) ?? 0, ...pause ? { pause } : {} }];
11983
11992
  });
11984
11993
  }
11985
11994
  function purgeCaps(dir, live, now) {
@@ -11988,7 +11997,7 @@ function purgeCaps(dir, live, now) {
11988
11997
  var nameKey = (name2) => name2.trim().toLowerCase();
11989
11998
  var round = (n) => Math.round(n * 100) / 100;
11990
11999
  function staleOf(m, c, unattended, now) {
11991
- if (c?.pause) return false;
12000
+ if (c?.pause || m.background || c && c.open > 0 && (c.deadlines ?? []).filter((at) => at > now).length >= c.open) return false;
11992
12001
  if (unattended) return !m.commanding && !m.workers?.length && !m.points && (c?.open ?? 0) > 0 && Math.max(m.fileMtime ?? 0, m.entryUpdated ?? 0) > 0 && now - Math.max(m.fileMtime ?? 0, m.entryUpdated ?? 0) > STALE_UNATTENDED_MS;
11993
12002
  return m.state === "idle" && !m.commanding && m.duty !== "standing" && m.entryUpdated !== void 0 && now - m.entryUpdated > STALE_MS;
11994
12003
  }
@@ -11996,7 +12005,7 @@ function joinCaps(o) {
11996
12005
  const caps = new Map(o.caps.map((c) => [c.session, c])), trains = o.mains.filter((m) => m.role === "train").map((m) => nameKey(m.name)), named = /* @__PURE__ */ new Set();
11997
12006
  const mains = o.mains.filter((m) => m.role === "main").map((m) => {
11998
12007
  const c = caps.get(m.session), own = new Set(m.workers.map(nameKey)), runs2 = (owner) => owner !== void 0 && (own.has(nameKey(owner)) || trains.includes(nameKey(owner)));
11999
- const doing = (c?.doing ?? []).filter((j) => runs2(j.owner)), ready = (c?.ready ?? []).filter((j) => !runs2(j.owner));
12008
+ const doing = (c?.doing ?? []).filter((j) => runs2(j.owner)), ready = (c?.ready ?? []).filter((j) => j.until === void 0 || j.until <= o.now).slice(0, JOBS).filter((j) => !runs2(j.owner));
12000
12009
  doing.forEach((j) => named.add(nameKey(j.owner)));
12001
12010
  const points = doing.reduce((n, j) => n + j.points, 0) + [...own].filter((w) => !doing.some((j) => nameKey(j.owner) === w)).length * DEFAULT_POINTS;
12002
12011
  const minReady = ready.length ? Math.min(...ready.map((j) => j.points)) : void 0, units = /* @__PURE__ */ new Map();
@@ -22053,7 +22062,7 @@ function startStall(o) {
22053
22062
 
22054
22063
  // src/server/capops.ts
22055
22064
  import { readFileSync as readFileSync36, statSync as statSync13 } from "node:fs";
22056
- import { availableParallelism as availableParallelism2, loadavg as loadavg2 } from "node:os";
22065
+ import { availableParallelism as availableParallelism2, homedir as homedir14, loadavg as loadavg2 } from "node:os";
22057
22066
  import { join as join47 } from "node:path";
22058
22067
 
22059
22068
  // src/server/capwatch.ts
@@ -22125,7 +22134,13 @@ function createCapWatch(d) {
22125
22134
  ...silent.map((a) => ally("silent", a))
22126
22135
  ];
22127
22136
  const next2 = /* @__PURE__ */ new Set();
22128
- for (const e of flagged) if (active.has(markOf3(e)) || await send(e, now)) next2.add(markOf3(e));
22137
+ for (const e of flagged) {
22138
+ const mark2 = markOf3(e), episode2 = `episode:${mark2}`;
22139
+ if (active.has(mark2) || e.kind === "stale" && sent[episode2] !== void 0 || await send(e, now)) {
22140
+ next2.add(mark2);
22141
+ if (e.kind === "stale") sent[episode2] ??= now;
22142
+ }
22143
+ }
22129
22144
  for (const a of silent) {
22130
22145
  if (next2.has(`silent:${a.key}`)) sent[FIRST + a.key] ??= now;
22131
22146
  const first2 = sent[FIRST + a.key];
@@ -22145,7 +22160,7 @@ function createCapWatch(d) {
22145
22160
  untold = new Set(flagged.map(markOf3).filter((m) => untold.has(m)));
22146
22161
  last = rows;
22147
22162
  const spell = (k) => [FIRST, ESCALATED].find((p) => k.startsWith(p)), episode = (k) => [UFIRST, UESCALATED].find((p) => k.startsWith(p));
22148
- sent = Object.fromEntries(Object.entries(sent).filter(([k, at]) => episode(k) ? underKeys.has(k.slice(episode(k).length)) : spell(k) ? silentKeys.has(k.slice(spell(k).length)) : now - at < THROTTLE_MS));
22163
+ sent = Object.fromEntries(Object.entries(sent).filter(([k, at]) => k.startsWith("episode:stale:") ? next2.has(k.slice("episode:".length)) : episode(k) ? underKeys.has(k.slice(episode(k).length)) : spell(k) ? silentKeys.has(k.slice(spell(k).length)) : now - at < THROTTLE_MS));
22149
22164
  try {
22150
22165
  writeSent(d.dir, sent);
22151
22166
  } catch (error) {
@@ -22157,15 +22172,16 @@ function createCapWatch(d) {
22157
22172
  }
22158
22173
 
22159
22174
  // src/server/capops.ts
22160
- function readBudget(stateDir) {
22175
+ function armedLoop(dir, session, now) {
22176
+ if (!safeSession(session)) return false;
22161
22177
  try {
22162
- const b = JSON.parse(readFileSync36(join47(stateDir, "config.json"), "utf8")).capacity?.budget;
22163
- return typeof b === "number" && Number.isFinite(b) && b > 0 && b <= 1e3 ? b : void 0;
22178
+ const { loops } = JSON.parse(readFileSync36(join47(dir, `loops-${session}.json`), "utf8"));
22179
+ return Array.isArray(loops) && loops.some((l) => l?.status === "active" && typeof l.expiresAt === "number" && l.expiresAt > now);
22164
22180
  } catch {
22165
- return void 0;
22181
+ return false;
22166
22182
  }
22167
22183
  }
22168
- function mainFacts(sessions, ps, boardDir, now, mtime) {
22184
+ function mainFacts(sessions, ps, boardDir, now, mtime, background) {
22169
22185
  const kids = subagentsOfAll(ps, now, Infinity), entries3 = new Map(readEntries(boardDir).map((e) => [e.session, e.updated]));
22170
22186
  return netMembers(sessions, ps).filter((m) => m.role === "main" || m.role === "train").map((m) => {
22171
22187
  const pane = ps.find((p) => p.pane_id === m.s.herdrLocation?.paneId), subs = m.role === "main" ? kids(pane).filter((r) => !r.ended) : [], mark2 = sessionMark(m.s, pane), file3 = pane?.agent_session?.value;
@@ -22177,6 +22193,7 @@ function mainFacts(sessions, ps, boardDir, now, mtime) {
22177
22193
  role: m.role === "train" ? "train" : "main",
22178
22194
  state: mark2,
22179
22195
  commanding: commanding(mark2, subs.map((r) => r.mark)) === "commanding",
22196
+ ...m.role === "main" && background?.(m.s.id, pane?.pane_id) ? { background: true } : {},
22180
22197
  ...m.duty ? { duty: m.duty } : {},
22181
22198
  workers: subs.map((r) => r.text),
22182
22199
  ...moved !== void 0 ? { fileMtime: moved } : {},
@@ -22203,13 +22220,23 @@ function startCap(o) {
22203
22220
  unattended: o.unattended,
22204
22221
  allies: o.allies,
22205
22222
  load: () => ({ load1: loadavg2()[0] ?? 0, cores: availableParallelism2() }),
22206
- mains: async () => mainFacts(await o.sessions(), await panes(o.run), boardDir, o.now(), (file3) => {
22207
- try {
22208
- return statSync13(file3).mtimeMs;
22209
- } catch {
22210
- return void 0;
22211
- }
22212
- }),
22223
+ mains: async () => {
22224
+ const sessions = await o.sessions(), panes3 = await panes(o.run), monitors = o.monitorPanes(), now = o.now();
22225
+ return mainFacts(
22226
+ sessions,
22227
+ panes3,
22228
+ boardDir,
22229
+ now,
22230
+ (file3) => {
22231
+ try {
22232
+ return statSync13(file3).mtimeMs;
22233
+ } catch {
22234
+ return void 0;
22235
+ }
22236
+ },
22237
+ (id2, pane) => pane !== void 0 && monitors.has(pane) || o.watching(id2) || armedLoop(join47(homedir14(), ".pi", "loops"), id2, now)
22238
+ );
22239
+ },
22213
22240
  tell: (e) => tellCap(e, o, o.now()),
22214
22241
  ...o.over
22215
22242
  });
@@ -22688,7 +22715,7 @@ import { join as join50 } from "node:path";
22688
22715
 
22689
22716
  // src/server/bossconv.ts
22690
22717
  import { lstatSync as lstatSync11, readFileSync as readFileSync38, realpathSync as realpathSync10, rmSync as rmSync12 } from "node:fs";
22691
- import { homedir as homedir14 } from "node:os";
22718
+ import { homedir as homedir15 } from "node:os";
22692
22719
  import { isAbsolute as isAbsolute10, join as join49, relative as relative5, resolve as resolve8, sep as sep8 } from "node:path";
22693
22720
  var BOSS_FILE_MAX = 4 * 1024 * 1024;
22694
22721
  var BOSS_FILE_DAYS = 7;
@@ -22705,7 +22732,7 @@ function writePointer(slot, workspace, pointer) {
22705
22732
  ensureDir(towerDir(slot, workspace));
22706
22733
  writeDurable(pointerFile(slot, workspace), pointer);
22707
22734
  }
22708
- var sessionsRoot = (env = process.env) => join49(env.PI_CODING_AGENT_DIR || join49(homedir14(), ".pi", "agent"), "sessions");
22735
+ var sessionsRoot = (env = process.env) => join49(env.PI_CODING_AGENT_DIR || join49(homedir15(), ".pi", "agent"), "sessions");
22709
22736
  var real2 = (path) => {
22710
22737
  try {
22711
22738
  return realpathSync10(path);
@@ -23785,7 +23812,7 @@ var clearOrder = (run3, paneIds) => Promise.all(paneIds.map((id2) => report(run3
23785
23812
 
23786
23813
  // src/server/head.ts
23787
23814
  import { chmodSync as chmodSync6, mkdirSync as mkdirSync15 } from "node:fs";
23788
- import { homedir as homedir15 } from "node:os";
23815
+ import { homedir as homedir16 } from "node:os";
23789
23816
  import { join as join53 } from "node:path";
23790
23817
  var HEAD_REFUSAL = "The head tower takes only the boss's words and answers to its own asks.";
23791
23818
  var HEAD_TOKEN = "sb_head";
@@ -23795,7 +23822,7 @@ function refuseHead(client, from, message, log, now) {
23795
23822
  client.sendMessageReceipt?.({ messageId: message.id, status: "expired", timestamp: now(), detail: HEAD_REFUSAL });
23796
23823
  }
23797
23824
  var headLabel = (env, stateDir) => localeOf(env, stateDir) === "zh-TW" ? "\u4E3B\u5854\u53F0" : "Head tower";
23798
- var headFolder = (env) => join53(env.PI_CODING_AGENT_DIR || join53(homedir15(), ".pi", "agent"), "straw-boss-head");
23825
+ var headFolder = (env) => join53(env.PI_CODING_AGENT_DIR || join53(homedir16(), ".pi", "agent"), "straw-boss-head");
23799
23826
  async function makeHead(d) {
23800
23827
  const cwd = headFolder(d.env), label = headLabel(d.env, d.slot?.stateDir);
23801
23828
  mkdirSync15(cwd, { recursive: true, mode: 448 });
@@ -29508,7 +29535,7 @@ async function runServer(o) {
29508
29535
  // The work board's Clear tells a live writer once (boardpanel.ts): one intercom message from the server, under a `board_clear` header.
29509
29536
  tell: tellVia(() => client, serverId(slot)),
29510
29537
  // The primary server holds the link itself (B3), so the GUI asks the holder in this process as the server, which the holder takes GUI requests from; before it runs, the channel reaches the holder's session. A secondary server holds none and its GUI says so (`no_link`, as its `link` request does): the channel would ask the primary's holder as a session that is not the GUI's host.
29511
- link: gui.link ?? (!slot.primary ? elsewhereLink() : inProcessLink(createGuiLink({ events: kit.pi.events, id: () => serverId(slot), stateDir: slot.stateDir, agentDir: env.PI_CODING_AGENT_DIR ?? join60(homedir16(), ".pi", "agent"), log: (text14) => log.line("link", { text: text14 }) }), () => link, () => serverId(slot))),
29538
+ link: gui.link ?? (!slot.primary ? elsewhereLink() : inProcessLink(createGuiLink({ events: kit.pi.events, id: () => serverId(slot), stateDir: slot.stateDir, agentDir: env.PI_CODING_AGENT_DIR ?? join60(homedir17(), ".pi", "agent"), log: (text14) => log.line("link", { text: text14 }) }), () => link, () => serverId(slot))),
29512
29539
  status: () => ({ state: phase === "ready" ? "live" : phase, version, pid, mode, desk, uptimeMs: now() - startedAt, log: fileOf(slot, "log"), ...own.lastError ? { lastError: own.lastError } : {} }),
29513
29540
  restart: gui.restart ?? ((reason) => spawnRestart(cliBeside(), reason, "the GUI", serverEnv(env), slot.dir, void 0, true)),
29514
29541
  failed: (code, text14) => recordError(code, text14),
@@ -29598,7 +29625,7 @@ async function runServer(o) {
29598
29625
  void towers?.takeover().catch((error) => recordError("towers", error.message));
29599
29626
  }, () => (log.line("herdr-lost", { at: Date.now() }), towers?.runs.herdrLost())));
29600
29627
  const stall = startStall({ dir: slot.dir, stateDir: slot.stateDir, pid, platform, now, log: (event, facts2) => log.line(event, facts2), run: cfg.run, sessions: () => client?.isConnected() ? client.listSessions() : Promise.reject(new Error("pi-intercom is not connected")), towers: () => towers, ...o.stall ? { over: o.stall } : {} });
29601
- if (slot.primary) ((stop) => stop && stops.push(stop))(startCap({ stateDir: slot.stateDir, now, log: (event, facts2) => log.line(event, facts2), run: cfg.run, sessions: () => client?.isConnected() ? client.listSessions() : Promise.reject(new Error("pi-intercom is not connected")), towers: () => towers, unattended, allies: () => link?.holder?.allySeen() ?? [], tellSession: tellVia(() => client, serverId(slot), "capacity_notice") }));
29628
+ if (slot.primary) ((stop) => stop && stops.push(stop))(startCap({ stateDir: slot.stateDir, monitorPanes: () => new Set(guiHost.dialogs().hub.monitors().map((m) => m.pane)), watching: (id2) => dog.watches.has(id2), now, log: (event, facts2) => log.line(event, facts2), run: cfg.run, sessions: () => client?.isConnected() ? client.listSessions() : Promise.reject(new Error("pi-intercom is not connected")), towers: () => towers, unattended, allies: () => link?.holder?.allySeen() ?? [], tellSession: tellVia(() => client, serverId(slot), "capacity_notice") }));
29602
29629
  if (auto) ((stop) => stop && stops.push(stop))(startAutoWatch({ auto, slot, env, now, log: (event, facts2) => log.line(event, facts2), run: cfg.run, world: cfg.world, sessions: () => client?.isConnected() ? client.listSessions() : Promise.reject(new Error("pi-intercom is not connected")), towers: () => towers, stalls: () => stall?.list() ?? [], book: () => cars?.book, ...o.autoWatch ? { over: o.autoWatch } : {} }));
29603
29630
  procs = startProcs({ dir: slot.dir, stateDir: slot.stateDir, env, pid, platform, now, log: (event, facts2) => log.line(event, facts2), run: cfg.run, events: cfg.events, ...stall ? { watch: (table) => stall.sample(table) } : {}, ...o.procs ? { over: o.procs } : {}, stops, timers, leaving: () => Boolean(leaving) || phase === "stopping" || phase === "restarting" });
29604
29631
  let downSince;
@@ -29717,8 +29744,8 @@ ${unit}`), note = ws ? readNotes(slot, ws).at(-1) : void 0, sent = ws ? link?.ho
29717
29744
  run: cfg.run,
29718
29745
  towers: () => towers,
29719
29746
  now,
29720
- home: o.link?.home ?? homedir16(),
29721
- agentDir: env.PI_CODING_AGENT_DIR ?? join60(o.link?.home ?? homedir16(), ".pi", "agent"),
29747
+ home: o.link?.home ?? homedir17(),
29748
+ agentDir: env.PI_CODING_AGENT_DIR ?? join60(o.link?.home ?? homedir17(), ".pi", "agent"),
29722
29749
  failed: (from, project, error) => void unitsOut().notify(`tower-open/${from}/${project}/${Math.floor(now() / 6e5)}`, { kind: "tower-open-failed", unit: allyLabel(project), text: `Could not open a tower for ${project}: ${error.message}` }, { device: from })
29723
29750
  })
29724
29751
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-straw-boss",
3
- "version": "0.87.0",
3
+ "version": "0.87.2",
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/prompts/main.md CHANGED
@@ -1,6 +1,6 @@
1
1
  You are the main agent of Herdr tab {{tab}}, of kind {{duty}}: the boss works with you here.
2
2
 
3
- - Dispatch: split work by owning app ({{dir}}/apps-config.md); a task is one worker's end-to-end work in one app, a todo before its worker starts ({{dir}}/planning.md: plan, anchors). Dependent tasks wait (`blockedBy`); parallel writers get worktrees under `~/.herdr/worktrees/<repo>/<branch>` (elsewhere a child hangs on pi's trust prompt); work independent of your chain goes to subagents in parallel, up to the device's capacity budget (`board_read` `capacity`; none set: at most 4 workers at once). Idle with ready todos: dispatch them; none ready: take your next eligible work or report idle (`milestone`). A capacity notice on your work: dispatch its ready work now, or say why not (blocked, shared files, the boss): reply to whoever asked; sb's: board it.
3
+ - Dispatch: split work by owning app ({{dir}}/apps-config.md); a task is one worker's end-to-end work in one app, a todo before its worker starts ({{dir}}/planning.md: plan, anchors). Dependent tasks wait (`blockedBy`); parallel writers get worktrees under `~/.herdr/worktrees/<repo>/<branch>` (elsewhere pi's trust prompt hangs it); work independent of your chain goes to subagents in parallel, on an unattended device within its capacity budget (`board_read` `capacity`; an API-bound worker's todo may set `metadata.points` 0.25). Idle with ready todos: dispatch them; none ready: take your next eligible work or report idle (`milestone`). A capacity notice on your work: dispatch its ready work now, or say why not (blocked, shared files, the boss): reply to whoever asked; sb's: board it.
4
4
  - A result passing brief and anchor: todo `completed`, dispatch what it unblocked. A failed or cancelled task blocks its dependents: report them; settle the next step with the boss.
5
5
  - Write to agents terse, caveman-style: point first; keep negations, numbers, paths, IDs, and quoted decisions verbatim; full sentences where a fragment could mislead; a brief still carries its goal, context, reasons with their cause, scope, what others own, and acceptance check, or workers redo work; a reader unsure restates it or asks.
6
6
  - Brief workers in English: required behavior, the Reality anchor, the boss's authorizations quoted; cause and location are the worker's. End with: "When you need a decision these authorizations do not cover, or a rule you follow says to ask first, call `caller_ping` and stop." Answer pings via the boss; `subagent_resume`. Reviewed change: `boss_pair` worker and reviewer, brief both, dispatch both with `Thread: T<n>`; both results come when the thread closes; relay nothing.
@@ -1,12 +1,12 @@
1
1
  # Planning work
2
2
 
3
- The plan your main prompt's Dispatch rules ask for, and its anchors. Revise it when the work's shape changes.
3
+ Revise the plan when the work changes.
4
4
 
5
5
  ## 1. Name the graph
6
6
 
7
7
  The page shows it beside your kind. Take the first case that matches:
8
8
 
9
- - **single-loop**: one bounded task that you carry yourself, or that one subagent carries. Its plan is one todo whose `metadata.anchor` names its check.
9
+ - **single-loop**: one bounded task for you or one subagent. Its plan is one todo whose `metadata.anchor` names its check.
10
10
  - **fan-out/fan-in**: independent branches run in subagents, and you integrate their results.
11
11
  - **orchestrator-worker**: several workers, each owning one app's task end to end, with dependency edges.
12
12
 
@@ -17,10 +17,11 @@ An independent review is a checkpoint, not a graph.
17
17
  For fan-out and orchestrator-worker, one todo per task:
18
18
 
19
19
  - `subject`: the required outcome.
20
- - `owner`: the subagent's name, or `self` for work you carry yourself.
20
+ - `owner`: the subagent's name, or `self`.
21
21
  - `description`: the app, the worktree branch for a parallel writer, the anchor and who exercises it, and the exact artifact path a dependent will read.
22
- - `blockedBy`: the tasks whose output or landed change this one needs; the rest run in parallel up to the capacity budget (`board_read` `capacity`; else 4). Serialize only on a real dependency or shared files.
23
- - `metadata`: `{ "graph": "<a graph name from section 1, exactly>", "anchor": "...", "checkpoint": "own" | "<checkpoint todo id>", "points": <n> }`: its weight against the budget, as the boss or project weighs it (default 1).
22
+ - `blockedBy`: the tasks whose output or landed change this one needs; the rest run in parallel, on an unattended device within its capacity budget. Serialize only on a real dependency or shared files.
23
+ - `metadata`: `{ "graph": "<a graph name from section 1, exactly>", "anchor": "...", "checkpoint": "own" | "<checkpoint todo id>", "points": <n> }`: its weight against the budget, as the boss or project weighs it (default 1; 0.25 for a light, API-bound worker).
24
+ - Defer: `metadata.until` (ISO) or `metadata.waitsOn` (person). Your monitor, loop or `boss_watch` prevents stale notices.
24
25
 
25
26
  ## 3. Name the anchors
26
27
 
@@ -28,7 +29,7 @@ Each anchor is the lightest check that can fail before the change and still reac
28
29
 
29
30
  - **testing**: the default for code changes. Use the smallest test that goes red first. Repo-wide suites, lint, and type checks run once, at the shared checkpoint or before merge, never inside each task.<!-- integration --> In an `integration` app, see below.<!-- /integration -->
30
31
  - **pseudo-human**: a browser or computer operates the real interface and records screenshots and measurements.
31
- - **human**: the boss operates or judges the delivered result. Use it where the boss's judgment is the real check: UI feel, wording, a business rule.
32
+ - **human**: the boss operates or judges the result: UI feel, wording, a business rule.
32
33
  - **adversarial-review**: a fresh-context agent challenges the result against the requirement. Use it for read-only work that has no executable checkpoint.
33
34
 
34
35
  Tasks that share one anchor share one checkpoint. Give each such group one checkpoint todo, `blockedBy` every task it covers, and tell those workers to hand it their evidence. A task whose check is distinct, or plainly cheaper in place, keeps its own.
package/src/capacity.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  import { clean, safeSession, STALE_MS } from "./board.ts";
4
+ import { todoDeadlines } from "./todoledger.ts";
4
5
  import type { Todo } from "./items.ts";
5
6
 
6
7
  // Device capacity on the work board (docs/specs/2026-11-24-capacity.md): what each main has running and ready in points, and the device row the sb server writes once a minute from them, the
@@ -20,21 +21,23 @@ const JOBS = 50, DETAIL = 120;
20
21
  /** A main stopped on its model quota: `until` (epoch ms) when it expects to resume, if known. */
21
22
  export interface Pause { reason: "quota"; at: number; until?: number; detail?: string }
22
23
  /** A todo as capacity counts it: its owner, when it names one, and its points. */
23
- export interface Job { owner?: string; points: number }
24
+ export interface Job { owner?: string; points: number; until?: number }
24
25
  /** What a main writes: its in-progress todos that have an owner (`doing`), its pending todos whose blockers are all done (`ready`), its open todos, and its pause. */
25
- export interface MainCap { v: 1; session: string; updated: number; doing: Job[]; ready: Job[]; open: number; pause?: Pause }
26
+ export interface MainCap { v: 1; session: string; updated: number; doing: Job[]; ready: Job[]; open: number; deadlines?: number[]; pause?: Pause }
26
27
 
27
28
  const num = (v: unknown, lo: number, hi: number) => (typeof v === "number" && Number.isFinite(v) && v >= lo && v <= hi ? v : undefined);
28
29
  const pointsOf = (t: Pick<Todo, "points">) => t.points ?? DEFAULT_POINTS;
29
30
  const job = (t: Pick<Todo, "owner" | "points">): Job => ({ ...(t.owner ? { owner: t.owner } : {}), points: pointsOf(t) });
30
31
 
31
32
  /** A todo list's capacity facts. A blocker the list no longer holds (deleted) blocks nothing. */
32
- export function capOfTodos(list: readonly Todo[]): Pick<MainCap, "doing" | "ready" | "open"> {
33
+ export function capOfTodos(list: readonly Todo[], snapshot?: unknown): Pick<MainCap, "doing" | "ready" | "open" | "deadlines"> {
34
+ const dates = todoDeadlines(snapshot), deadlines = list.flatMap((t) => t.status !== "completed" && dates.has(t.id) ? [dates.get(t.id)!] : []);
33
35
  const done = new Set(list.filter((t) => t.status === "completed").map((t) => t.id)), known = new Set(list.map((t) => t.id));
34
36
  const free = (t: Todo) => (t.blockedBy ?? []).every((id) => done.has(id) || !known.has(id));
35
37
  return {
36
38
  doing: list.filter((t) => t.status === "in_progress" && t.owner).slice(0, JOBS).map(job),
37
- ready: list.filter((t) => t.status === "pending" && free(t)).slice(0, JOBS).map(job),
39
+ ready: list.filter((t) => t.status === "pending" && free(t)).slice(0, deadlines.length ? 200 : JOBS).map((t) => ({ ...job(t), ...(dates.has(t.id) ? { until: dates.get(t.id)! } : {}) })),
40
+ ...(deadlines.length ? { deadlines } : {}),
38
41
  open: list.filter((t) => t.status !== "completed").length,
39
42
  };
40
43
  }
@@ -51,6 +54,12 @@ export function pauseOf(data: unknown, now: number): { state: "paused"; pause: P
51
54
 
52
55
  /** `<state dir>/capacity`, beside the board folder (whose listing the board's readers and purge own). */
53
56
  export const capDir = (boardDir: string) => join(dirname(boardDir), "capacity");
57
+ /** `capacity.budget` of `<state dir>/config.json`: a number of points over 0 (at most 1000); none when it is unset or not such a number. Read at each call, so a change applies at once. */
58
+ export function readBudget(stateDir: string): number | undefined {
59
+ let b: unknown;
60
+ try { b = (JSON.parse(readFileSync(join(stateDir, "config.json"), "utf8")) as { capacity?: { budget?: unknown } }).capacity?.budget; } catch { return undefined; }
61
+ return typeof b === "number" && Number.isFinite(b) && b > 0 && b <= 1000 ? b : undefined;
62
+ }
54
63
  const DEVICE = "_device.json", SENT = "_sent.json";
55
64
  function writeJson(dir: string, name: string, value: unknown): void {
56
65
  mkdirSync(dir, { recursive: true, mode: 0o700 });
@@ -71,9 +80,9 @@ const readJson = (file: string): Record<string, unknown> | undefined => {
71
80
  return undefined;
72
81
  }
73
82
  };
74
- const jobsOf = (v: unknown): Job[] => (Array.isArray(v) ? v.slice(0, JOBS).flatMap((j: Record<string, unknown> | null) => {
83
+ const jobsOf = (v: unknown, max = JOBS): Job[] => (Array.isArray(v) ? v.slice(0, max).flatMap((j: Record<string, unknown> | null) => {
75
84
  const points = num(j?.points, 0, 10), owner = clean(j?.owner, 64);
76
- return points === undefined ? [] : [{ ...(owner ? { owner } : {}), points }];
85
+ return points === undefined ? [] : [{ ...(owner ? { owner } : {}), points, ...(num(j?.until, 0, 8.64e15) !== undefined ? { until: j!.until as number } : {}) }];
77
86
  }) : []);
78
87
 
79
88
  export function writeCap(dir: string, cap: MainCap): void {
@@ -90,7 +99,7 @@ export function readCaps(dir: string): MainCap[] {
90
99
  if (raw?.v !== 1 || raw.session !== session || !safeSession(session) || num(raw.updated, 0, 8.64e15) === undefined) return [];
91
100
  const p = raw.pause as Record<string, unknown> | undefined, at = num(p?.at, 0, 8.64e15), until = num(p?.until, 0, 8.64e15), detail = clean(p?.detail, DETAIL);
92
101
  const pause = p?.reason === "quota" && at !== undefined ? { reason: "quota" as const, at, ...(until !== undefined ? { until } : {}), ...(detail ? { detail } : {}) } : undefined;
93
- return [{ v: 1, session, updated: raw.updated as number, doing: jobsOf(raw.doing), ready: jobsOf(raw.ready), open: num(raw.open, 0, 200) ?? 0, ...(pause ? { pause } : {}) }];
102
+ return [{ v: 1, session, updated: raw.updated as number, doing: jobsOf(raw.doing), ready: jobsOf(raw.ready, 200), ...(Array.isArray(raw.deadlines) ? { deadlines: raw.deadlines.slice(0, 200).filter((n) => num(n, 0, 8.64e15) !== undefined) } : {}), open: num(raw.open, 0, 200) ?? 0, ...(pause ? { pause } : {}) }];
94
103
  });
95
104
  }
96
105
  /** The files of sessions that are not live and older than a day go. */
@@ -99,7 +108,7 @@ export function purgeCaps(dir: string, live: ReadonlySet<string>, now: number):
99
108
  }
100
109
 
101
110
  /** A live main as the server sees it: its workers are the names of the subagents of its pane that run now (and, for any main, the device's live trains). */
102
- export interface MainFacts { session: string; name: string; workspace: string; role: "main" | "train"; state: string; commanding?: boolean; duty?: string; workers: string[]; fileMtime?: number; entryUpdated?: number }
111
+ export interface MainFacts { session: string; name: string; workspace: string; role: "main" | "train"; state: string; commanding?: boolean; duty?: string; workers: string[]; fileMtime?: number; entryUpdated?: number; background?: boolean }
103
112
  /** One main's row of the device: points in use, its ready todos (the smallest's points), its open todos, its pause, and whether it is stale. */
104
113
  export interface MainRow { session: string; name: string; workspace: string; points: number; ready: number; minReady?: number; open: number; paused?: { until?: number; detail?: string }; stale?: true; standing?: true; /** The running workers sampled, folded (workercap.ts matches a launch to them); the local file only, never on the wire. */ workers?: string[]; /** The deployed units by name and points (the head page's supply tray); local only, like `workers`. */ units?: { name: string; points: number }[] }
105
114
  /** The device row. `under`: since when the device has had room for its smallest ready todo (held 10 minutes before it is flagged). */
@@ -112,8 +121,8 @@ const round = (n: number) => Math.round(n * 100) / 100;
112
121
  * Whether a main is stale. On an unattended device: it has open todos, runs nothing (no running worker or train, no points in use: a main commanding work is never stale), is not paused, and neither its session file nor its board entry moved for 30 minutes (whatever its state). Elsewhere the board's own rule: idle,
113
122
  * commanding nothing, not standing, and its entry over 2 hours old. A paused main is never stale.
114
123
  */
115
- export function staleOf(m: Pick<MainFacts, "state" | "commanding" | "duty" | "fileMtime" | "entryUpdated"> & { workers?: readonly string[]; points?: number }, c: Pick<MainCap, "open" | "pause"> | undefined, unattended: boolean, now: number): boolean {
116
- if (c?.pause) return false;
124
+ export function staleOf(m: Pick<MainFacts, "state" | "commanding" | "duty" | "fileMtime" | "entryUpdated" | "background"> & { workers?: readonly string[]; points?: number }, c: Pick<MainCap, "open" | "pause" | "deadlines"> | undefined, unattended: boolean, now: number): boolean {
125
+ if (c?.pause || m.background || (c && c.open > 0 && (c.deadlines ?? []).filter((at) => at > now).length >= c.open)) return false;
117
126
  if (unattended) return !m.commanding && !m.workers?.length && !m.points && (c?.open ?? 0) > 0 && Math.max(m.fileMtime ?? 0, m.entryUpdated ?? 0) > 0 && now - Math.max(m.fileMtime ?? 0, m.entryUpdated ?? 0) > STALE_UNATTENDED_MS;
118
127
  return m.state === "idle" && !m.commanding && m.duty !== "standing" && m.entryUpdated !== undefined && now - m.entryUpdated > STALE_MS;
119
128
  }
@@ -126,7 +135,7 @@ export function joinCaps(o: { mains: MainFacts[]; caps: MainCap[]; budget?: numb
126
135
  const caps = new Map(o.caps.map((c) => [c.session, c])), trains = o.mains.filter((m) => m.role === "train").map((m) => nameKey(m.name)), named = new Set<string>();
127
136
  const mains = o.mains.filter((m) => m.role === "main").map((m): MainRow => {
128
137
  const c = caps.get(m.session), own = new Set(m.workers.map(nameKey)), runs = (owner?: string) => owner !== undefined && (own.has(nameKey(owner)) || trains.includes(nameKey(owner)));
129
- const doing = (c?.doing ?? []).filter((j) => runs(j.owner)), ready = (c?.ready ?? []).filter((j) => !runs(j.owner));
138
+ const doing = (c?.doing ?? []).filter((j) => runs(j.owner)), ready = (c?.ready ?? []).filter((j) => j.until === undefined || j.until <= o.now).slice(0, JOBS).filter((j) => !runs(j.owner));
130
139
  doing.forEach((j) => named.add(nameKey(j.owner!)));
131
140
  const points = doing.reduce((n, j) => n + j.points, 0) + [...own].filter((w) => !doing.some((j) => nameKey(j.owner!) === w)).length * DEFAULT_POINTS;
132
141
  const minReady = ready.length ? Math.min(...ready.map((j) => j.points)) : undefined, units = new Map<string, { name: string; points: number }>();
package/src/capfill.ts CHANGED
@@ -19,7 +19,7 @@ export function createCapFill({ pi, cfg, guiDir, me, role }: Kit): { refresh():
19
19
  try {
20
20
  // A /reload keeps the pause its file holds (the model is still stopped); read once, when the session's id is known (pi-intercom may set it after the start).
21
21
  if (!restored) (restored = true), (pause ??= readCaps(dir).find((x) => x.session === id)?.pause);
22
- const facts = capOfTodos(todosOf(snapshotOf(branch())) ?? []), key = JSON.stringify([facts, pause ?? null]);
22
+ const snapshot = snapshotOf(branch()), facts = capOfTodos(todosOf(snapshot) ?? [], snapshot), key = JSON.stringify([facts, pause ?? null]);
23
23
  if (key === last && wrote === id) return;
24
24
  const cap: MainCap = { v: 1, session: id, updated: cfg.now(), ...facts, ...(pause ? { pause } : {}) };
25
25
  writeCap(dir, cap);
package/src/index.ts CHANGED
@@ -108,7 +108,7 @@ export function createStrawBoss({ run: given, world: reading, api = herdrApi(),
108
108
  closeSelf = createClosing(kit);
109
109
  const control = createCloseMain(kit, { closeSelf, check: bridge.stashCheck, turn: bridge.turn });
110
110
  const watch = createBossWatch(kit, { ask: cfg.ask ?? look?.ask, control, openTower: reach.openTower, remote: () => Boolean(link.remoteScope()) });
111
- registerSession(kit, { mainDuty, integration: createIntegrationWatch(kit), runMode, briefing, roles, presence, membership, guard, host, reach, digest, control, startTower: createTower(kit, { membership, presence, tools, control, digest, roles, reach }) });
111
+ 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, control, digest, roles, reach }) });
112
112
  trainGuard = registerTrainGuard(kit, cars.client, mainDuty);
113
113
  mainDuty.trainOn(() => Boolean(trainGuard)); // a train's todo and MonitorCreate calls, and the integrator's train todos (nothing loads with the merge train off)
114
114
  registerBoss(kit, { runMode, host, membership, reach, closeSelf, stashing: createStashing(kit, { host }), server: look, paths: createBossPaths(kit, { host, server: look, closeSelf, here: host.here }) });
@@ -1,8 +1,8 @@
1
1
  import { readFileSync, statSync } from "node:fs";
2
- import { availableParallelism, loadavg } from "node:os";
2
+ import { availableParallelism, homedir, loadavg } from "node:os";
3
3
  import { join } from "node:path";
4
- import { readEntries } from "../board.ts";
5
- import { capDir, type MainFacts } from "../capacity.ts";
4
+ import { readEntries, safeSession } from "../board.ts";
5
+ import { capDir, type MainFacts, readBudget } from "../capacity.ts";
6
6
  import { type HerdrRun, panes as herdrPanes, type Session, workspaces as herdrWorkspaces } from "../herdr.ts";
7
7
  import { commanding, sessionMark, subagentsOfAll } from "../netdata.ts";
8
8
  import { nameOf, netMembers } from "../reach.ts";
@@ -14,25 +14,24 @@ import type { Towers } from "./towers.ts";
14
14
  // The server's side of the capacity watch (capwatch.ts): what it reads of this machine (pi-intercom's list, Herdr's panes, the board and capacity files, the load, `capacity.budget`), and whom it tells:
15
15
  // the tower of the main's workspace (as the stall watch finds it), this device's standing main, and for `under` and `stale` the main itself. Kept out of main.ts, which carries a line budget.
16
16
 
17
- /** `capacity.budget` of `<state dir>/config.json`: a number of points over 0 (at most 1000); none when it is unset or not such a number. */
18
- export function readBudget(stateDir: string): number | undefined {
17
+ /** pi-loop-monitor persists loops-<pi-session-id>.json. No mutating store import; consume only the active flag and expiry. */
18
+ export function armedLoop(dir: string, session: string, now: number): boolean {
19
+ if (!safeSession(session)) return false;
19
20
  try {
20
- const b = (JSON.parse(readFileSync(join(stateDir, "config.json"), "utf8")) as { capacity?: { budget?: unknown } }).capacity?.budget;
21
- return typeof b === "number" && Number.isFinite(b) && b > 0 && b <= 1000 ? b : undefined;
22
- } catch {
23
- return undefined;
24
- }
21
+ const { loops } = JSON.parse(readFileSync(join(dir, `loops-${session}.json`), "utf8"));
22
+ return Array.isArray(loops) && loops.some((l) => l?.status === "active" && typeof l.expiresAt === "number" && l.expiresAt > now);
23
+ } catch { return false; }
25
24
  }
26
25
 
27
26
  /** The live mains and trains of one reading, with every running subagent of each main's pane (no dashboard limit), when its session file last moved, and when its board entry was written. */
28
- export function mainFacts(sessions: Session[], ps: Awaited<ReturnType<typeof herdrPanes>>, boardDir: string, now: number, mtime: (file: string) => number | undefined): MainFacts[] {
27
+ export function mainFacts(sessions: Session[], ps: Awaited<ReturnType<typeof herdrPanes>>, boardDir: string, now: number, mtime: (file: string) => number | undefined, background?: (session: string, pane: string | undefined) => boolean): MainFacts[] {
29
28
  const kids = subagentsOfAll(ps, now, Infinity), entries = new Map(readEntries(boardDir).map((e) => [e.session, e.updated]));
30
29
  return netMembers(sessions, ps).filter((m) => m.role === "main" || m.role === "train").map((m): MainFacts => {
31
30
  const pane = ps.find((p) => p.pane_id === m.s.herdrLocation?.paneId), subs = m.role === "main" ? kids(pane).filter((r) => !r.ended) : [], mark = sessionMark(m.s, pane), file = pane?.agent_session?.value;
32
31
  const moved = file ? mtime(file) : undefined, written = entries.get(m.s.id);
33
32
  return {
34
33
  session: m.s.id, name: nameOf(m.s), workspace: m.workspace.id, role: m.role === "train" ? "train" : "main", state: mark, commanding: commanding(mark, subs.map((r) => r.mark)) === "commanding",
35
- ...(m.duty ? { duty: m.duty } : {}), workers: subs.map((r) => r.text), ...(moved !== undefined ? { fileMtime: moved } : {}), ...(written !== undefined ? { entryUpdated: written } : {}),
34
+ ...(m.role === "main" && background?.(m.s.id, pane?.pane_id) ? { background: true } : {}), ...(m.duty ? { duty: m.duty } : {}), workers: subs.map((r) => r.text), ...(moved !== undefined ? { fileMtime: moved } : {}), ...(written !== undefined ? { entryUpdated: written } : {}),
36
35
  };
37
36
  });
38
37
  }
@@ -45,6 +44,8 @@ export interface StartCap {
45
44
  sessions(): Promise<Session[]>;
46
45
  towers(): Pick<Towers, "status" | "head" | "runs"> | undefined;
47
46
  unattended(): boolean;
47
+ monitorPanes(): Set<string>;
48
+ watching(session: string): boolean;
48
49
  /** The ally devices the link holder has heard of (none without Straw Link). */
49
50
  allies(): AllySeen[];
50
51
  /** One intercom message from the server to a live session (boardpanel.ts `tellVia`). */
@@ -72,7 +73,11 @@ export function startCap(o: StartCap): (() => void) | undefined {
72
73
  const watch = createCapWatch({
73
74
  dir: capDir(boardDir), now: o.now, log: o.log, budget: () => readBudget(o.stateDir), unattended: o.unattended, allies: o.allies,
74
75
  load: () => ({ load1: loadavg()[0] ?? 0, cores: availableParallelism() }),
75
- mains: async () => mainFacts(await o.sessions(), await herdrPanes(o.run), boardDir, o.now(), (file) => { try { return statSync(file).mtimeMs; } catch { return undefined; } }),
76
+ mains: async () => {
77
+ const sessions = await o.sessions(), panes = await herdrPanes(o.run), monitors = o.monitorPanes(), now = o.now();
78
+ return mainFacts(sessions, panes, boardDir, now, (file) => { try { return statSync(file).mtimeMs; } catch { return undefined; } },
79
+ (id, pane) => (pane !== undefined && monitors.has(pane)) || o.watching(id) || armedLoop(join(homedir(), ".pi", "loops"), id, now));
80
+ },
76
81
  tell: (e) => tellCap(e, o, o.now()),
77
82
  ...o.over,
78
83
  });
@@ -91,7 +91,13 @@ export function createCapWatch(d: CapDeps) {
91
91
  ...silent.map((a) => ally("silent", a)),
92
92
  ];
93
93
  const next = new Set<string>();
94
- for (const e of flagged) if (active.has(markOf(e)) || (await send(e, now))) next.add(markOf(e));
94
+ for (const e of flagged) {
95
+ const mark = markOf(e), episode = `episode:${mark}`;
96
+ if (active.has(mark) || (e.kind === "stale" && sent[episode] !== undefined) || (await send(e, now))) {
97
+ next.add(mark);
98
+ if (e.kind === "stale") sent[episode] ??= now;
99
+ }
100
+ }
95
101
  // A silence is escalated once, 2 hours after its first notice was told, and routed as that notice; it ends when the device is no longer flagged.
96
102
  for (const a of silent) {
97
103
  if (next.has(`silent:${a.key}`)) sent[FIRST + a.key] ??= now;
@@ -114,7 +120,7 @@ export function createCapWatch(d: CapDeps) {
114
120
  untold = new Set(flagged.map(markOf).filter((m) => untold.has(m)));
115
121
  last = rows;
116
122
  const spell = (k: string) => [FIRST, ESCALATED].find((p) => k.startsWith(p)), episode = (k: string) => [UFIRST, UESCALATED].find((p) => k.startsWith(p));
117
- sent = Object.fromEntries(Object.entries(sent).filter(([k, at]) => (episode(k) ? underKeys.has(k.slice(episode(k)!.length)) : spell(k) ? silentKeys.has(k.slice(spell(k)!.length)) : now - at < THROTTLE_MS)));
123
+ sent = Object.fromEntries(Object.entries(sent).filter(([k, at]) => (k.startsWith("episode:stale:") ? next.has(k.slice("episode:".length)) : episode(k) ? underKeys.has(k.slice(episode(k)!.length)) : spell(k) ? silentKeys.has(k.slice(spell(k)!.length)) : now - at < THROTTLE_MS)));
118
124
  try { writeSent(d.dir, sent); } catch (error) { d.log("capacity-error", { text: (error as Error).message.slice(0, 200) }); }
119
125
  return dev;
120
126
  },
@@ -690,7 +690,7 @@ export async function runServer(o: ServerOptions): Promise<ServerHandle> {
690
690
  // The stall watch (stallwatch.ts): a pi that froze is told to its workspace's tower from the registry's tick; it signals nothing.
691
691
  const stall = startStall({ dir: slot.dir, stateDir: slot.stateDir, pid, platform, now, log: (event, facts) => log.line(event, facts), run: cfg.run, sessions: () => (client?.isConnected() ? client.listSessions() : Promise.reject(new Error("pi-intercom is not connected"))), towers: () => towers, ...(o.stall ? { over: o.stall } : {}) });
692
692
  // The capacity watch (capops.ts, docs/specs/2026-11-24-capacity.md): the device row once a minute and its flags told to the towers and the standing main; the primary server's, as the link holder is.
693
- if (slot.primary) ((stop) => stop && stops.push(stop))(startCap({ stateDir: slot.stateDir, now, log: (event, facts) => log.line(event, facts), run: cfg.run, sessions: () => (client?.isConnected() ? client.listSessions() : Promise.reject(new Error("pi-intercom is not connected"))), towers: () => towers, unattended, allies: () => link?.holder?.allySeen() ?? [], tellSession: tellVia(() => client, serverId(slot), "capacity_notice") }));
693
+ if (slot.primary) ((stop) => stop && stops.push(stop))(startCap({ stateDir: slot.stateDir, monitorPanes: () => new Set(guiHost!.dialogs().hub.monitors().map((m) => m.pane)), watching: (id) => dog!.watches.has(id), now, log: (event, facts) => log.line(event, facts), run: cfg.run, sessions: () => (client?.isConnected() ? client.listSessions() : Promise.reject(new Error("pi-intercom is not connected"))), towers: () => towers, unattended, allies: () => link?.holder?.allySeen() ?? [], tellSession: tellVia(() => client, serverId(slot), "capacity_notice") }));
694
694
  // The auto watch (autowatch.ts): while auto mode is on, the head tower is woken about every 15 minutes with what the server's own state shows of each workspace; the primary server's, as auto mode is.
695
695
  if (auto) ((stop) => stop && stops.push(stop))(startAutoWatch({ auto, slot, env, now, log: (event, facts) => log.line(event, facts), run: cfg.run, world: cfg.world, sessions: () => (client?.isConnected() ? client.listSessions() : Promise.reject(new Error("pi-intercom is not connected"))), towers: () => towers, stalls: () => stall?.list() ?? [], book: () => cars?.book, ...(o.autoWatch ? { over: o.autoWatch } : {}) }));
696
696
  procs = startProcs({ dir: slot.dir, stateDir: slot.stateDir, env, pid, platform, now, log: (event, facts) => log.line(event, facts), run: cfg.run, events: cfg.events, ...(stall ? { watch: (table) => stall.sample(table) } : {}), ...(o.procs ? { over: o.procs } : {}), stops, timers, leaving: () => Boolean(leaving) || phase === "stopping" || phase === "restarting" });
@@ -11,7 +11,7 @@ import { createWatches, type Watches, type WatchesDeps } from "./watches.ts";
11
11
  // (watchread.ts). Kept out of main.ts, which carries a line budget. `watch-read` is still answered for one release (0.83.0), for a watchdog child of an older build; `watch-report` is retired.
12
12
 
13
13
  export const REPORT_RETIRED = "watch-report is retired in pi-straw-boss 0.83.0 with the watchdog: the main watches with boss_watch, and the sb server wakes it";
14
- export interface WatchRoutes { read: { read(q: WatchQuery): Promise<Reply> }; watches: Pick<Watches, "add" | "stop" | "list"> }
14
+ export interface WatchRoutes { read: { read(q: WatchQuery): Promise<Reply> }; watches: Pick<Watches, "add" | "stop" | "list" | "has"> }
15
15
  const no = (error: string): Promise<Reply> => Promise.resolve({ ok: false, error });
16
16
  const number = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);
17
17
  const text = (v: unknown, max: number) => (typeof v === "string" && v.length > 0 && v.length <= max ? v : undefined);
package/src/session.ts CHANGED
@@ -33,7 +33,7 @@ const CHECKING = "Straw Boss is still asking Herdr whether this is a sub workspa
33
33
  const UNPLACED = (why: string) => `Straw Boss could not tell whether this is a sub workspace: ${why}; it asks again`;
34
34
 
35
35
  /** What the session does at its start, around each run, and at its end. */
36
- export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles, presence, membership, guard, host, reach, digest, control, integration, startTower }: { mainDuty: MainDuty; runMode: RunMode; briefing: Briefing; roles: Roles; presence: Presence; membership: Membership; guard: Guard; host: ReturnType<typeof createHost>; reach: Reach; digest: Digest; control: Control; integration: IntegrationWatch; startTower(): Promise<void> }) {
36
+ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles, presence, membership, guard, host, reach, digest, control, integration, startTower, attended }: { mainDuty: MainDuty; runMode: RunMode; briefing: Briefing; roles: Roles; presence: Presence; membership: Membership; guard: Guard; host: ReturnType<typeof createHost>; reach: Reach; digest: Digest; control: Control; integration: IntegrationWatch; startTower(): Promise<void>; /** Whether a person is at this device (the link's policy): the worker cap holds only on an unattended one. */ attended(): boolean }) {
37
37
  const { pi, cfg, s, guiDir, me, role, tell } = kit;
38
38
  const { run, env, version } = cfg;
39
39
  const who = () => pi.getSessionName() || s.ownName || me().slice(0, 8);
@@ -325,7 +325,7 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
325
325
 
326
326
  // A member that dispatches or resumes a subagent without promoting is promoted here, before the subagent starts, unless the tab already has a main.
327
327
  // A tower only coordinates: it dispatches no subagent (one would outlive it with no one to take its result), and opens a main for the work instead.
328
- const cap = createWorkerCap(undefined, deviceRoom(guiDir, me));
328
+ const cap = createWorkerCap(deviceRoom(guiDir, me, attended));
329
329
  pi.on("turn_end", () => cap.settle());
330
330
  pi.on("tool_call", async (event, ctx) => {
331
331
  if (!SUBAGENT_TOOLS.includes(event.toolName) || runMode.active()) return;
@@ -346,7 +346,7 @@ export function registerSession(kit: Kit, { mainDuty, runMode, briefing, roles,
346
346
  tell(`Straw Boss: ${(error as Error).message}`, "warning");
347
347
  }
348
348
  mainDuty.migrate(pi.getSessionName()); // the promotion above may have just made this an `integ <project>` main whose migration had not run
349
- // No plan gates a worker (docs/specs/2026-11-23-lite-main.md §1); the cap does (§3): at most 4 workers of this session run at once, or, with a capacity budget, as many as the device's points allow (docs/specs/2026-11-24-capacity.md, The cap).
349
+ // No plan gates a worker (docs/specs/2026-11-23-lite-main.md §1) and no count does: only an unattended device with a capacity budget holds one back, by its points (docs/specs/2026-11-24-capacity.md, The cap).
350
350
  if (event.toolName === "subagent") return cap.admit(event.toolCallId, event.input, () => ctx.sessionManager.getBranch()); // the todo its `name` owns weighs it
351
351
  });
352
352
 
package/src/todoledger.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  // pi-todo-ledger's public contract, version 1 (its CONTRACT.md and schema/todo-v1.schema.json; docs/specs/2026-11-24-todo-ledger.md): the names and shapes sb reads and registers through, with no import of that package.
2
2
  // A session's list is the newest valid `todo/v1` entry on its branch; the ledger asks registered guards before a change commits.
3
-
4
3
  export const TODO_V1 = "todo/v1";
5
4
  export const READY_EVENT = "todo:ready", CHANGED_EVENT = "todo:changed", GUARD_EVENT = "todo:guard";
6
5
 
@@ -9,6 +8,18 @@ export interface LedgerChange { op: "create" | "update" | "delete" | "clear"; pa
9
8
 
10
9
  type Json = Record<string, unknown>;
11
10
  const isObject = (v: unknown): v is Json => typeof v === "object" && v !== null && !Array.isArray(v);
11
+ /** Capacity-only deadlines by todo id. Date-only means midnight UTC; reject dates Date.parse would roll into the following month. */
12
+ export function todoDeadlines(snapshot: unknown): Map<number, number> {
13
+ const dates = new Map<number, number>();
14
+ if (isObject(snapshot) && Array.isArray(snapshot.tasks)) for (const t of snapshot.tasks.slice(0, 200)) {
15
+ const s = t?.metadata?.until, who = t?.metadata?.waitsOn;
16
+ if (typeof who === "string" && who.trim()) { dates.set(t.id, 8.64e15); continue; } // No scheduled return: last representable instant.
17
+ if (typeof s !== "string" || !/^\d{4}-\d\d-\d\d(?:T(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|[+-](?:[01]\d|2[0-3]):?[0-5]\d)?)?$/.test(s)) continue;
18
+ const at = Date.parse(s), day = s.slice(0, 10), midnight = Date.parse(day);
19
+ if (Number.isFinite(at) && Number.isFinite(midnight) && new Date(midnight).toISOString().startsWith(day)) dates.set(t.id, at);
20
+ }
21
+ return dates;
22
+ }
12
23
  const STATUSES = new Set(["pending", "in_progress", "completed", "deleted"]);
13
24
  const id = (v: unknown) => Number.isInteger(v) && (v as number) >= 1;
14
25
  const opt = (v: unknown, ok: (v: unknown) => boolean) => v === undefined || ok(v);
package/src/workercap.ts CHANGED
@@ -1,46 +1,43 @@
1
1
  import { join } from "node:path";
2
- import { capDir, DEFAULT_POINTS, nameKey, readDevice } from "./capacity.ts";
2
+ import { capDir, DEFAULT_POINTS, nameKey, readBudget, readDevice } from "./capacity.ts";
3
3
  import { createReservations, type Holder, type Reservations } from "./capres.ts";
4
4
  import { dutyOfAgent } from "./duty.ts";
5
5
  import { todosOf } from "./items.ts";
6
6
  import { snapshotScan } from "./todo.ts";
7
7
 
8
- // The cap on a session's concurrent workers (docs/specs/2026-11-23-lite-main.md §3): at most 4 `worker` subagents run at once, counted from pi-herdr-agents' registry of the children this process
9
- // launched and is still waiting on (orphan.ts `tracked` reads the same slot), plus the worker calls admitted in the message being prepared: pi prepares every tool call of an assistant message before any
10
- // runs, so the registry holds none of them yet. Scouts, planners, reviewers, and resumes are not workers and are never held. A registry that cannot be read holds nothing back.
8
+ // Worker admission (docs/specs/2026-11-24-capacity.md, The cap). sb holds back no worker by count: on an attended device (the boss's own, who watches it) nothing gates a worker, and its
9
+ // `capacity.budget` only feeds the board and the capacity notices. On an unattended device the device's points gate `worker` subagents against `capacity.budget`, read from config.json at
10
+ // each admission (a change applies at once; none set: no cap, and no built-in figure). Scouts, planners, reviewers, and resumes are not workers and are never held.
11
11
 
12
- export const WORKER_CAP = 4;
13
12
  const REGISTRY = Symbol.for("pi-subagents/runtime");
14
13
 
15
- /** The workers pi-herdr-agents runs for this process, or undefined when its registry cannot be read. */
16
- function runningWorkers(): number | undefined {
14
+ /** The names of the workers pi-herdr-agents runs for this process (its registry of the children it still waits on), or undefined when the registry cannot be read. */
15
+ function runningWorkers(): string[] | undefined {
17
16
  const map = (globalThis as Record<symbol, { runningSubagents?: unknown } | undefined>)[REGISTRY]?.runningSubagents;
18
17
  if (!(map instanceof Map)) return undefined;
19
- let n = 0;
20
- for (const run of map.values()) if (dutyOfAgent((run as { agent?: unknown } | null)?.agent as string | undefined) === "worker") n++;
21
- return n;
18
+ return [...map.values()].flatMap((run) => (dutyOfAgent((run as { agent?: string } | null)?.agent) === "worker" ? [String((run as { name?: unknown }).name ?? "")] : []));
22
19
  }
23
20
 
24
- /** The device's capacity as the sb server last wrote it (capacity.ts `readDevice`): points in use, the budget when one is set, when the row was sampled, and the mains it sampled with their running workers. */
25
- export interface Room { points: number; budget?: number | undefined; at?: number; mains?: readonly { session: string; workers?: readonly string[] }[] }
26
- /** What the cap reads of the device: its row, the reservations every main of it shares (capres.ts), and this main's session id. */
27
- export interface DeviceSide { room(): Room | undefined; store: Reservations; session(): string | undefined }
21
+ /** The device's capacity as the sb server last wrote it (capacity.ts `readDevice`): points in use, when the row was sampled, and the mains it sampled with their running workers. */
22
+ export interface Room { points: number; at?: number; mains?: readonly { session: string; workers?: readonly string[] }[] }
23
+ /** What the cap reads of the device: its fresh row, the reservations every main of it shares (capres.ts), this main's session id, the budget now, and whether a person is at it. */
24
+ export interface DeviceSide { room(): Room | undefined; store: Reservations; session(): string | undefined; budget(): number | undefined; attended(): boolean }
28
25
 
29
- // With a capacity budget (docs/specs/2026-11-24-capacity.md, The cap) the device's points decide instead of the count of 4: a worker starts while the points in use, the points the device's
30
- // reservations hold (launches of any main that no row shows yet), and its own fit the budget. Its reservation is written before the row and the sum are read, so two mains that launch at once
31
- // see each other. Only a main the row lists takes this path: the server samples the mains of its own Herdr slot, so a main of another slot, or one not sampled yet, keeps the count of 4 and
32
- // holds nothing device-wide. A device row that is missing or stale falls back to the count.
33
- /** The device row and reservations beside the board folder under `guiDir`, for the main whose session id `me` gives. */
34
- export const deviceRoom = (guiDir: string, me: () => string | undefined): DeviceSide => {
35
- const dir = capDir(join(guiDir, "board"));
36
- return { room: () => readDevice(dir, Date.now()), store: createReservations(dir, Date.now), session: me };
26
+ // A worker starts while the points in use, the points the device's reservations hold (launches of any main that no row shows yet), and its own fit the budget. Its reservation is written
27
+ // before the row and the sum are read, so two mains that launch at once see each other. The server samples only the mains of its own Herdr slot: a main the row does not list (another slot,
28
+ // not sampled yet) or any main while no fresh row exists still reserves device-wide, and adds its own running workers from its registry, which no row counts, in place of its own launched reservations.
29
+ /** The device row, reservations, and budget of the state folder `stateDir`, for the main whose session id `me` gives; `attended` says whether a person is at the device (the link's policy). */
30
+ export const deviceRoom = (stateDir: string, me: () => string | undefined, attended: () => boolean): DeviceSide => {
31
+ const dir = capDir(join(stateDir, "board"));
32
+ return { room: () => readDevice(dir, Date.now()), store: createReservations(dir, Date.now), session: me, budget: () => readBudget(stateDir), attended };
37
33
  };
38
34
  /** The row shows a launch: it lists the main's session with a running worker of the launch's (folded) name. */
39
35
  const shows = (r: Room, h: Holder) => h.worker !== "" && (r.mains?.find((m) => m.session === h.session)?.workers ?? []).some((w) => nameKey(w) === h.worker);
36
+ const sum = (xs: readonly number[]) => xs.reduce((n, x) => n + x, 0);
40
37
 
41
- export function createWorkerCap(cap = WORKER_CAP, device?: DeviceSide) {
42
- /** Worker calls admitted whose tool has not returned yet: the registry may not hold them. With a budget, each holds a reservation (its id). */
43
- const admitted = new Map<string, string | undefined>();
38
+ export function createWorkerCap(device?: DeviceSide) {
39
+ /** Worker calls admitted whose tool has not returned yet, each with its reservation's id. */
40
+ const admitted = new Map<string, string>();
44
41
  const snapshotOf = snapshotScan();
45
42
  /** The `metadata.points` of the main's own open todo whose `owner` is the subagent's `name` (read as capfill.ts reads the list), as the board's headroom weighs a ready todo; 1 without one. */
46
43
  const weight = (name: unknown, branch?: () => readonly unknown[]): number => {
@@ -51,32 +48,30 @@ export function createWorkerCap(cap = WORKER_CAP, device?: DeviceSide) {
51
48
  return (mine.find((t) => t.status === "in_progress") ?? mine[0])?.points ?? DEFAULT_POINTS;
52
49
  };
53
50
  return {
54
- /** pi's `tool_call` for `subagent`: a refusal when `input.agent` is a worker and the budget, or `cap` workers already run or are admitted, leave no room. `branch`: the main's session entries, for the todo's weight. */
51
+ /** pi's `tool_call` for `subagent`: on an unattended device with a budget, a refusal when `input.agent` is a worker the device's points leave no room for. `branch`: the main's session entries, for the todo's weight. */
55
52
  admit(toolCallId: string, input: unknown, branch?: () => readonly unknown[]): { block: true; reason: string } | undefined {
56
53
  const { agent, name } = (input ?? {}) as { agent?: unknown; name?: unknown };
57
- if (typeof agent !== "string" || dutyOfAgent(agent) !== "worker") return undefined;
58
- const me = device?.session(), listed = (r: Room | undefined): r is Room & { budget: number } => r?.budget !== undefined && me !== undefined && (r.mains ?? []).some((m) => m.session === me);
59
- if (device && listed(device.room())) {
60
- const need = weight(name, branch);
61
- let id: string | undefined, r: Room | undefined, held = 0;
62
- try {
63
- id = device.store.add(need, { session: me!, worker: typeof name === "string" ? nameKey(name) : "" });
64
- r = device.room(); // read after the reservation is published
65
- if (listed(r)) held = device.store.live(r.at ?? -Infinity, (h) => shows(r!, h)).filter((x) => x.id !== id).reduce((n, x) => n + x.points, 0);
66
- } catch (error) {
67
- try { if (id !== undefined) device.store.drop(id); } catch { /* it expires */ }
68
- return { block: true, reason: `sb: the device's capacity reservation could not be written (${(error as Error).message}): no worker starts until it can.` };
69
- }
70
- if (!listed(r)) device.store.drop(id); // the row went stale or no longer lists this main: the count of 4 below
71
- else if (r.points + held + need > r.budget) {
72
- device.store.drop(id);
73
- return { block: true, reason: `sb: the device runs ${r.points} of its ${r.budget} capacity points, ${Math.round(held * 100) / 100} more held by launches it does not count yet: this worker needs ${need}. Wait for a result, then dispatch the next; a scout, a planner, or a reviewer may run now.` };
74
- } else return void admitted.set(toolCallId, id);
54
+ if (typeof agent !== "string" || dutyOfAgent(agent) !== "worker" || !device || device.attended()) return undefined;
55
+ const budget = device.budget();
56
+ if (budget === undefined) return undefined;
57
+ const me = device.session() ?? "", need = weight(name, branch);
58
+ let id: string | undefined, used = 0, held = 0;
59
+ try {
60
+ id = device.store.add(need, { session: me, worker: typeof name === "string" ? nameKey(name) : "" });
61
+ const r = device.room(); // read after the reservation is published
62
+ const own = r?.mains?.some((m) => m.session === me) ? undefined : runningWorkers(); // no row counts this main's workers: its registry does
63
+ used = (r?.points ?? 0) + sum((own ?? []).map((w) => weight(w, branch)));
64
+ held = sum(device.store.live(r?.at ?? -Infinity, (h) => r !== undefined && shows(r, h)).filter((x) => x.id !== id && !(own && x.session === me && x.launched)).map((x) => x.points));
65
+ } catch (error) {
66
+ try { if (id !== undefined) device.store.drop(id); } catch { /* it expires */ }
67
+ return { block: true, reason: `sb: the device's capacity reservation could not be written (${(error as Error).message}): no worker starts until it can.` };
75
68
  }
76
- const running = runningWorkers();
77
- if (running === undefined) return undefined;
78
- if (running + admitted.size >= cap) return { block: true, reason: `sb: ${cap} workers run for this main already (${running} running, ${admitted.size} starting in this message): wait for a result, then dispatch the next; a scout, a planner, or a reviewer may run now.` };
79
- admitted.set(toolCallId, undefined);
69
+ if (used + held + need > budget) {
70
+ device.store.drop(id);
71
+ const pts = (n: number) => Math.round(n * 100) / 100;
72
+ return { block: true, reason: `sb: the device runs ${pts(used)} of its ${budget} capacity points, ${pts(held)} more held by launches it does not count yet: this worker needs ${need}. Wait for a result, then dispatch the next; a scout, a planner, or a reviewer may run now.` };
73
+ }
74
+ admitted.set(toolCallId, id);
80
75
  return undefined;
81
76
  },
82
77
  /** pi's `tool_result` for `subagent`: the launch ended, and the registry holds the worker if it started. A reservation stays for a launch that returned, and goes for one that failed. */
@@ -87,7 +82,7 @@ export function createWorkerCap(cap = WORKER_CAP, device?: DeviceSide) {
87
82
  },
88
83
  /** The turn ended: every call of it has run, or was blocked by another extension, which leaves no result: its reservation goes. */
89
84
  settle(): void {
90
- for (const id of admitted.values()) if (id !== undefined && device) try { device.store.drop(id); } catch { /* it expires */ }
85
+ for (const id of admitted.values()) if (device) try { device.store.drop(id); } catch { /* it expires */ }
91
86
  admitted.clear();
92
87
  },
93
88
  };