pi-straw-boss 0.87.0 → 0.87.1

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
@@ -11963,9 +11963,9 @@ var readJson2 = (file3) => {
11963
11963
  return void 0;
11964
11964
  }
11965
11965
  };
11966
- var jobsOf = (v) => Array.isArray(v) ? v.slice(0, JOBS).flatMap((j) => {
11966
+ var jobsOf = (v, max = JOBS) => Array.isArray(v) ? v.slice(0, max).flatMap((j) => {
11967
11967
  const points = num2(j?.points, 0, 10), owner = clean(j?.owner, 64);
11968
- return points === void 0 ? [] : [{ ...owner ? { owner } : {}, points }];
11968
+ return points === void 0 ? [] : [{ ...owner ? { owner } : {}, points, ...num2(j?.until, 0, 864e13) !== void 0 ? { until: j.until } : {} }];
11969
11969
  }) : [];
11970
11970
  var removeCap = (dir, session) => void (safeSession(session) && rmSync7(join30(dir, `${session}.json`), { force: true }));
11971
11971
  function readCaps(dir) {
@@ -11979,7 +11979,7 @@ function readCaps(dir) {
11979
11979
  if (raw?.v !== 1 || raw.session !== session || !safeSession(session) || num2(raw.updated, 0, 864e13) === void 0) return [];
11980
11980
  const p = raw.pause, at = num2(p?.at, 0, 864e13), until = num2(p?.until, 0, 864e13), detail = clean(p?.detail, DETAIL);
11981
11981
  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 } : {} }];
11982
+ 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
11983
  });
11984
11984
  }
11985
11985
  function purgeCaps(dir, live, now) {
@@ -11988,7 +11988,7 @@ function purgeCaps(dir, live, now) {
11988
11988
  var nameKey = (name2) => name2.trim().toLowerCase();
11989
11989
  var round = (n) => Math.round(n * 100) / 100;
11990
11990
  function staleOf(m, c, unattended, now) {
11991
- if (c?.pause) return false;
11991
+ if (c?.pause || m.background || c && c.open > 0 && (c.deadlines ?? []).filter((at) => at > now).length >= c.open) return false;
11992
11992
  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
11993
  return m.state === "idle" && !m.commanding && m.duty !== "standing" && m.entryUpdated !== void 0 && now - m.entryUpdated > STALE_MS;
11994
11994
  }
@@ -11996,7 +11996,7 @@ function joinCaps(o) {
11996
11996
  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
11997
  const mains = o.mains.filter((m) => m.role === "main").map((m) => {
11998
11998
  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));
11999
+ 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
12000
  doing.forEach((j) => named.add(nameKey(j.owner)));
12001
12001
  const points = doing.reduce((n, j) => n + j.points, 0) + [...own].filter((w) => !doing.some((j) => nameKey(j.owner) === w)).length * DEFAULT_POINTS;
12002
12002
  const minReady = ready.length ? Math.min(...ready.map((j) => j.points)) : void 0, units = /* @__PURE__ */ new Map();
@@ -22053,7 +22053,7 @@ function startStall(o) {
22053
22053
 
22054
22054
  // src/server/capops.ts
22055
22055
  import { readFileSync as readFileSync36, statSync as statSync13 } from "node:fs";
22056
- import { availableParallelism as availableParallelism2, loadavg as loadavg2 } from "node:os";
22056
+ import { availableParallelism as availableParallelism2, homedir as homedir14, loadavg as loadavg2 } from "node:os";
22057
22057
  import { join as join47 } from "node:path";
22058
22058
 
22059
22059
  // src/server/capwatch.ts
@@ -22125,7 +22125,13 @@ function createCapWatch(d) {
22125
22125
  ...silent.map((a) => ally("silent", a))
22126
22126
  ];
22127
22127
  const next2 = /* @__PURE__ */ new Set();
22128
- for (const e of flagged) if (active.has(markOf3(e)) || await send(e, now)) next2.add(markOf3(e));
22128
+ for (const e of flagged) {
22129
+ const mark2 = markOf3(e), episode2 = `episode:${mark2}`;
22130
+ if (active.has(mark2) || e.kind === "stale" && sent[episode2] !== void 0 || await send(e, now)) {
22131
+ next2.add(mark2);
22132
+ if (e.kind === "stale") sent[episode2] ??= now;
22133
+ }
22134
+ }
22129
22135
  for (const a of silent) {
22130
22136
  if (next2.has(`silent:${a.key}`)) sent[FIRST + a.key] ??= now;
22131
22137
  const first2 = sent[FIRST + a.key];
@@ -22145,7 +22151,7 @@ function createCapWatch(d) {
22145
22151
  untold = new Set(flagged.map(markOf3).filter((m) => untold.has(m)));
22146
22152
  last = rows;
22147
22153
  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));
22154
+ 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
22155
  try {
22150
22156
  writeSent(d.dir, sent);
22151
22157
  } catch (error) {
@@ -22165,7 +22171,16 @@ function readBudget(stateDir) {
22165
22171
  return void 0;
22166
22172
  }
22167
22173
  }
22168
- function mainFacts(sessions, ps, boardDir, now, mtime) {
22174
+ function armedLoop(dir, session, now) {
22175
+ if (!safeSession(session)) return false;
22176
+ try {
22177
+ const { loops } = JSON.parse(readFileSync36(join47(dir, `loops-${session}.json`), "utf8"));
22178
+ return Array.isArray(loops) && loops.some((l) => l?.status === "active" && typeof l.expiresAt === "number" && l.expiresAt > now);
22179
+ } catch {
22180
+ return false;
22181
+ }
22182
+ }
22183
+ function mainFacts(sessions, ps, boardDir, now, mtime, background) {
22169
22184
  const kids = subagentsOfAll(ps, now, Infinity), entries3 = new Map(readEntries(boardDir).map((e) => [e.session, e.updated]));
22170
22185
  return netMembers(sessions, ps).filter((m) => m.role === "main" || m.role === "train").map((m) => {
22171
22186
  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 +22192,7 @@ function mainFacts(sessions, ps, boardDir, now, mtime) {
22177
22192
  role: m.role === "train" ? "train" : "main",
22178
22193
  state: mark2,
22179
22194
  commanding: commanding(mark2, subs.map((r) => r.mark)) === "commanding",
22195
+ ...m.role === "main" && background?.(m.s.id, pane?.pane_id) ? { background: true } : {},
22180
22196
  ...m.duty ? { duty: m.duty } : {},
22181
22197
  workers: subs.map((r) => r.text),
22182
22198
  ...moved !== void 0 ? { fileMtime: moved } : {},
@@ -22203,13 +22219,23 @@ function startCap(o) {
22203
22219
  unattended: o.unattended,
22204
22220
  allies: o.allies,
22205
22221
  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
- }),
22222
+ mains: async () => {
22223
+ const sessions = await o.sessions(), panes3 = await panes(o.run), monitors = o.monitorPanes(), now = o.now();
22224
+ return mainFacts(
22225
+ sessions,
22226
+ panes3,
22227
+ boardDir,
22228
+ now,
22229
+ (file3) => {
22230
+ try {
22231
+ return statSync13(file3).mtimeMs;
22232
+ } catch {
22233
+ return void 0;
22234
+ }
22235
+ },
22236
+ (id2, pane) => pane !== void 0 && monitors.has(pane) || o.watching(id2) || armedLoop(join47(homedir14(), ".pi", "loops"), id2, now)
22237
+ );
22238
+ },
22213
22239
  tell: (e) => tellCap(e, o, o.now()),
22214
22240
  ...o.over
22215
22241
  });
@@ -22688,7 +22714,7 @@ import { join as join50 } from "node:path";
22688
22714
 
22689
22715
  // src/server/bossconv.ts
22690
22716
  import { lstatSync as lstatSync11, readFileSync as readFileSync38, realpathSync as realpathSync10, rmSync as rmSync12 } from "node:fs";
22691
- import { homedir as homedir14 } from "node:os";
22717
+ import { homedir as homedir15 } from "node:os";
22692
22718
  import { isAbsolute as isAbsolute10, join as join49, relative as relative5, resolve as resolve8, sep as sep8 } from "node:path";
22693
22719
  var BOSS_FILE_MAX = 4 * 1024 * 1024;
22694
22720
  var BOSS_FILE_DAYS = 7;
@@ -22705,7 +22731,7 @@ function writePointer(slot, workspace, pointer) {
22705
22731
  ensureDir(towerDir(slot, workspace));
22706
22732
  writeDurable(pointerFile(slot, workspace), pointer);
22707
22733
  }
22708
- var sessionsRoot = (env = process.env) => join49(env.PI_CODING_AGENT_DIR || join49(homedir14(), ".pi", "agent"), "sessions");
22734
+ var sessionsRoot = (env = process.env) => join49(env.PI_CODING_AGENT_DIR || join49(homedir15(), ".pi", "agent"), "sessions");
22709
22735
  var real2 = (path) => {
22710
22736
  try {
22711
22737
  return realpathSync10(path);
@@ -23785,7 +23811,7 @@ var clearOrder = (run3, paneIds) => Promise.all(paneIds.map((id2) => report(run3
23785
23811
 
23786
23812
  // src/server/head.ts
23787
23813
  import { chmodSync as chmodSync6, mkdirSync as mkdirSync15 } from "node:fs";
23788
- import { homedir as homedir15 } from "node:os";
23814
+ import { homedir as homedir16 } from "node:os";
23789
23815
  import { join as join53 } from "node:path";
23790
23816
  var HEAD_REFUSAL = "The head tower takes only the boss's words and answers to its own asks.";
23791
23817
  var HEAD_TOKEN = "sb_head";
@@ -23795,7 +23821,7 @@ function refuseHead(client, from, message, log, now) {
23795
23821
  client.sendMessageReceipt?.({ messageId: message.id, status: "expired", timestamp: now(), detail: HEAD_REFUSAL });
23796
23822
  }
23797
23823
  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");
23824
+ var headFolder = (env) => join53(env.PI_CODING_AGENT_DIR || join53(homedir16(), ".pi", "agent"), "straw-boss-head");
23799
23825
  async function makeHead(d) {
23800
23826
  const cwd = headFolder(d.env), label = headLabel(d.env, d.slot?.stateDir);
23801
23827
  mkdirSync15(cwd, { recursive: true, mode: 448 });
@@ -29508,7 +29534,7 @@ async function runServer(o) {
29508
29534
  // The work board's Clear tells a live writer once (boardpanel.ts): one intercom message from the server, under a `board_clear` header.
29509
29535
  tell: tellVia(() => client, serverId(slot)),
29510
29536
  // 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))),
29537
+ 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
29538
  status: () => ({ state: phase === "ready" ? "live" : phase, version, pid, mode, desk, uptimeMs: now() - startedAt, log: fileOf(slot, "log"), ...own.lastError ? { lastError: own.lastError } : {} }),
29513
29539
  restart: gui.restart ?? ((reason) => spawnRestart(cliBeside(), reason, "the GUI", serverEnv(env), slot.dir, void 0, true)),
29514
29540
  failed: (code, text14) => recordError(code, text14),
@@ -29598,7 +29624,7 @@ async function runServer(o) {
29598
29624
  void towers?.takeover().catch((error) => recordError("towers", error.message));
29599
29625
  }, () => (log.line("herdr-lost", { at: Date.now() }), towers?.runs.herdrLost())));
29600
29626
  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") }));
29627
+ 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
29628
  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
29629
  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
29630
  let downSince;
@@ -29717,8 +29743,8 @@ ${unit}`), note = ws ? readNotes(slot, ws).at(-1) : void 0, sent = ws ? link?.ho
29717
29743
  run: cfg.run,
29718
29744
  towers: () => towers,
29719
29745
  now,
29720
- home: o.link?.home ?? homedir16(),
29721
- agentDir: env.PI_CODING_AGENT_DIR ?? join60(o.link?.home ?? homedir16(), ".pi", "agent"),
29746
+ home: o.link?.home ?? homedir17(),
29747
+ agentDir: env.PI_CODING_AGENT_DIR ?? join60(o.link?.home ?? homedir17(), ".pi", "agent"),
29722
29748
  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
29749
  })
29724
29750
  }
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.1",
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",
@@ -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
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
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).
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
  }
@@ -71,9 +74,9 @@ const readJson = (file: string): Record<string, unknown> | undefined => {
71
74
  return undefined;
72
75
  }
73
76
  };
74
- const jobsOf = (v: unknown): Job[] => (Array.isArray(v) ? v.slice(0, JOBS).flatMap((j: Record<string, unknown> | null) => {
77
+ const jobsOf = (v: unknown, max = JOBS): Job[] => (Array.isArray(v) ? v.slice(0, max).flatMap((j: Record<string, unknown> | null) => {
75
78
  const points = num(j?.points, 0, 10), owner = clean(j?.owner, 64);
76
- return points === undefined ? [] : [{ ...(owner ? { owner } : {}), points }];
79
+ return points === undefined ? [] : [{ ...(owner ? { owner } : {}), points, ...(num(j?.until, 0, 8.64e15) !== undefined ? { until: j!.until as number } : {}) }];
77
80
  }) : []);
78
81
 
79
82
  export function writeCap(dir: string, cap: MainCap): void {
@@ -90,7 +93,7 @@ export function readCaps(dir: string): MainCap[] {
90
93
  if (raw?.v !== 1 || raw.session !== session || !safeSession(session) || num(raw.updated, 0, 8.64e15) === undefined) return [];
91
94
  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
95
  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 } : {}) }];
96
+ 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
97
  });
95
98
  }
96
99
  /** The files of sessions that are not live and older than a day go. */
@@ -99,7 +102,7 @@ export function purgeCaps(dir: string, live: ReadonlySet<string>, now: number):
99
102
  }
100
103
 
101
104
  /** 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 }
105
+ 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
106
  /** 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
107
  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
108
  /** 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 +115,8 @@ const round = (n: number) => Math.round(n * 100) / 100;
112
115
  * 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
116
  * commanding nothing, not standing, and its entry over 2 hours old. A paused main is never stale.
114
117
  */
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;
118
+ 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 {
119
+ if (c?.pause || m.background || (c && c.open > 0 && (c.deadlines ?? []).filter((at) => at > now).length >= c.open)) return false;
117
120
  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
121
  return m.state === "idle" && !m.commanding && m.duty !== "standing" && m.entryUpdated !== undefined && now - m.entryUpdated > STALE_MS;
119
122
  }
@@ -126,7 +129,7 @@ export function joinCaps(o: { mains: MainFacts[]; caps: MainCap[]; budget?: numb
126
129
  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
130
  const mains = o.mains.filter((m) => m.role === "main").map((m): MainRow => {
128
131
  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));
132
+ 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
133
  doing.forEach((j) => named.add(nameKey(j.owner!)));
131
134
  const points = doing.reduce((n, j) => n + j.points, 0) + [...own].filter((w) => !doing.some((j) => nameKey(j.owner!) === w)).length * DEFAULT_POINTS;
132
135
  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);
@@ -1,7 +1,7 @@
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";
4
+ import { readEntries, safeSession } from "../board.ts";
5
5
  import { capDir, type MainFacts } 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";
@@ -24,15 +24,24 @@ export function readBudget(stateDir: string): number | undefined {
24
24
  }
25
25
  }
26
26
 
27
+ /** pi-loop-monitor persists loops-<pi-session-id>.json. No mutating store import; consume only the active flag and expiry. */
28
+ export function armedLoop(dir: string, session: string, now: number): boolean {
29
+ if (!safeSession(session)) return false;
30
+ try {
31
+ const { loops } = JSON.parse(readFileSync(join(dir, `loops-${session}.json`), "utf8"));
32
+ return Array.isArray(loops) && loops.some((l) => l?.status === "active" && typeof l.expiresAt === "number" && l.expiresAt > now);
33
+ } catch { return false; }
34
+ }
35
+
27
36
  /** 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[] {
37
+ 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
38
  const kids = subagentsOfAll(ps, now, Infinity), entries = new Map(readEntries(boardDir).map((e) => [e.session, e.updated]));
30
39
  return netMembers(sessions, ps).filter((m) => m.role === "main" || m.role === "train").map((m): MainFacts => {
31
40
  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
41
  const moved = file ? mtime(file) : undefined, written = entries.get(m.s.id);
33
42
  return {
34
43
  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 } : {}),
44
+ ...(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
45
  };
37
46
  });
38
47
  }
@@ -45,6 +54,8 @@ export interface StartCap {
45
54
  sessions(): Promise<Session[]>;
46
55
  towers(): Pick<Towers, "status" | "head" | "runs"> | undefined;
47
56
  unattended(): boolean;
57
+ monitorPanes(): Set<string>;
58
+ watching(session: string): boolean;
48
59
  /** The ally devices the link holder has heard of (none without Straw Link). */
49
60
  allies(): AllySeen[];
50
61
  /** One intercom message from the server to a live session (boardpanel.ts `tellVia`). */
@@ -72,7 +83,11 @@ export function startCap(o: StartCap): (() => void) | undefined {
72
83
  const watch = createCapWatch({
73
84
  dir: capDir(boardDir), now: o.now, log: o.log, budget: () => readBudget(o.stateDir), unattended: o.unattended, allies: o.allies,
74
85
  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; } }),
86
+ mains: async () => {
87
+ const sessions = await o.sessions(), panes = await herdrPanes(o.run), monitors = o.monitorPanes(), now = o.now();
88
+ return mainFacts(sessions, panes, boardDir, now, (file) => { try { return statSync(file).mtimeMs; } catch { return undefined; } },
89
+ (id, pane) => (pane !== undefined && monitors.has(pane)) || o.watching(id) || armedLoop(join(homedir(), ".pi", "loops"), id, now));
90
+ },
76
91
  tell: (e) => tellCap(e, o, o.now()),
77
92
  ...o.over,
78
93
  });
@@ -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/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);