herdr-gentle-shell 1.5.1 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,9 +17,19 @@
17
17
  // Tokens (§4.3):
18
18
  // gentle_work_v1 = <hash>:<count>:<expiry>
19
19
  // (normative running total — only `running` counts as
20
- // executing; queued/waiting/pending never count. The
21
- // consumer renders the oldest running role plus this
22
- // total in parentheses only when above one.)
20
+ // executing; queued/waiting never count. The total is
21
+ // the UNION of running TaskStore records and the
22
+ // distinct in-flight `subagent_run`/`subagent_continue`
23
+ // launches the store does not list yet, deduplicated so
24
+ // one delegate counts once: a task-mode (synchronous)
25
+ // launch has no record until it returns, so without it
26
+ // two live delegates counted zero. Per agent the union
27
+ // is a MAX (S11b): an announced running record and its
28
+ // own in-flight launch are the same delegate and carry
29
+ // no shared call id, so a record consumes one launch of
30
+ // its own agent. The consumer renders the oldest
31
+ // running role plus this total in parentheses only when
32
+ // above one.)
23
33
  // gentle_roles_v1 = CSV of canonical role slugs from TaskRecord.agent
24
34
  // (oldest-first by immutable firstSeen, e.g.
25
35
  // `worker,explorer` with worker oldest; null /
@@ -731,17 +741,48 @@ const paneId = process.env.HERDR_PANE_ID;
731
741
 
732
742
  const TTL_MS = 60000;
733
743
  const BEAT_MS = 15000;
744
+ const BEAT_MIN_MS = 100;
745
+ const BEAT_MAX_MS = 300000;
746
+ const BEAT_ENV = "GENTLE_HERDR_BEAT_MS";
747
+ // Bounded budget of quiet beats a producer may publish while it has no work
748
+ // evidence and no host truth to settle on (`quietWithoutTruth` in the
749
+ // factory): three beats, one BEAT_MS each. See the comment there.
750
+ const QUIET_BEAT_LIMIT = 3;
751
+ // Consecutive beats a producer must see the lost-settle contradiction (it
752
+ // believes a turn is running, the host answers `isIdle() === true`, and
753
+ // nothing else keeps the session busy) before it applies the settle the host
754
+ // already reports (`reconcileSettled` in the factory). One beat is not enough:
755
+ // the host flips to idle at the very end of a run, so a genuine `agent_settled`
756
+ // can reach the producer one host tick later, and a single sample would repaint
757
+ // a still-settling turn as idle. Two consecutive samples — 30 s of
758
+ // host-confirmed idle at the 15 s beat — cannot be that race, and a lost edge
759
+ // still recovers within one beat period after the window closes.
760
+ const LOST_SETTLE_BEATS = 2;
734
761
  // Synthesized finish signal (DESIGN §4.3, S2/D2). The host never reports
735
762
  // `done`, so the producer mints the finish itself: one session-bound
736
- // `<hash>:<expiry>` token per finish at the settled-and-empty edge, carrying
737
- // the hold as its absolute expiry. The sidebar reads it as `done` while it is
738
- // fresh and recedes to `idle` once it expires — the delay IS that expiry, so
739
- // no timer and no extra idle hold exists. The hold is short on purpose (5 s):
740
- // it exists to make a finish visible, never to pin a settled row, so `idle`
741
- // follows the finish within seconds. Overridden through
742
- // GENTLE_HERDR_DONE_HOLD_MS, clamped to [1 s, 5 min]; the consumer rejects any
743
- // expiry beyond the same ceiling.
763
+ // `<hash>:<expiry>` token per finish at the settled-and-empty edge. Since T3
764
+ // the expiry is the UNSEEN cap, not the visible dwell: the row holds `done`
765
+ // until the human views the pane, then the consumer's own 5 s dwell and
766
+ // `idle`, and a pane nobody looks at recedes at the cap. The producer owns the
767
+ // mint and the cap because it stamps the token; the consumer owns the recede
768
+ // because `focused` rides the snapshot the daemon already reads. The finish
769
+ // signal is never refreshed, so the cap can never be extended.
744
770
  const DONE_TOKEN = "gentle_done_v1";
771
+ // Default unseen cap: 15 minutes (S8). It bounds how long a finish can read
772
+ // `done` without the human ever looking at it, so the marker stays an answer
773
+ // to "which finished panes have I not reviewed yet". Overridden through
774
+ // GENTLE_DONE_UNSEEN_CAP_MS, clamped exactly like JOBS_SNAPSHOT_TTL_MS.
775
+ const DONE_UNSEEN_CAP_MS = 900000;
776
+ const DONE_UNSEEN_CAP_MIN_MS = 100;
777
+ export const DONE_UNSEEN_CAP_MAX_MS = 3600000;
778
+ const DONE_UNSEEN_CAP_ENV = "GENTLE_DONE_UNSEEN_CAP_MS";
779
+ // Settle-time pending hold (T9/S12), NOT the finish token's life: one finish
780
+ // spell in which a stranded `subagent_run` keeps the native state non-terminal
781
+ // and the `done` mint withheld, after which the terminal state lands. Its 5 s
782
+ // default is the time the latch waits on a launch result that may never come;
783
+ // the 5 s dwell after the human views a finish lives consumer-side
784
+ // (`DONE_VIEW_DWELL_MS` in herdr-plugin/lib/gentle-tokens.js). Overridden
785
+ // through GENTLE_HERDR_DONE_HOLD_MS, clamped to [1 s, 5 min].
745
786
  const DONE_HOLD_MS = 5000;
746
787
  const DONE_HOLD_MIN_MS = 1000;
747
788
  export const DONE_HOLD_MAX_MS = 300000;
@@ -931,6 +972,50 @@ export function doneHoldMs(raw = process.env[DONE_HOLD_ENV]) {
931
972
  return Math.min(DONE_HOLD_MAX_MS, Math.max(DONE_HOLD_MIN_MS, Math.round(parsed)));
932
973
  }
933
974
 
975
+ // S12/T9c: the deadline for one settle-time pending episode. A first raise
976
+ // starts the episode at `now`. A re-settle that adds no launch id to the
977
+ // retained union keeps the deadline exactly, so repeated settles can never
978
+ // extend the latch. One that adds a new in-flight launch may extend it from
979
+ // `now` (new work means the pane is not finished), but the whole episode never
980
+ // runs past the hold ceiling measured from its first raise. `holdMs` is clamped
981
+ // by the same band as doneHoldMs.
982
+ export function settleHoldUntil({ now, held, startedAt, until, added, holdMs }) {
983
+ const raw = Number.isFinite(holdMs) ? holdMs : DONE_HOLD_MS;
984
+ const hold = Math.min(DONE_HOLD_MAX_MS, Math.max(DONE_HOLD_MIN_MS, Math.round(raw)));
985
+ if (!held) return { startedAt: now, until: now + hold };
986
+ if (!added) return { startedAt, until };
987
+ return {
988
+ startedAt,
989
+ until: Math.min(startedAt + DONE_HOLD_MAX_MS, Math.max(until, now + hold)),
990
+ };
991
+ }
992
+
993
+ // Unseen-cap override, the same discipline as jobsSnapshotTtlMs: an absent or
994
+ // unparseable value keeps the 15 min default and anything outside the band is
995
+ // clamped, so a debugging session (or a test that cannot wait 15 minutes) can
996
+ // shorten the cap without ever making the finish token instantly stale.
997
+ export function doneUnseenCapMs(raw = process.env[DONE_UNSEEN_CAP_ENV]) {
998
+ const text = typeof raw === "string" ? raw.trim() : "";
999
+ if (text.length === 0) return DONE_UNSEEN_CAP_MS;
1000
+ const parsed = Number(text);
1001
+ if (!Number.isFinite(parsed)) return DONE_UNSEEN_CAP_MS;
1002
+ return Math.min(DONE_UNSEEN_CAP_MAX_MS, Math.max(DONE_UNSEEN_CAP_MIN_MS, Math.round(parsed)));
1003
+ }
1004
+
1005
+ // Beat cadence override, the same discipline as doneHoldMs: an absent or
1006
+ // unparseable value keeps the 15 s default and anything outside the band is
1007
+ // clamped, so a debugging session (or a test that cannot wait 15 s per beat)
1008
+ // can shorten the beat without touching the 60 s token TTL or the transport's
1009
+ // own 500/1500 ms bounds. The 100 ms floor keeps every beat far slower than a
1010
+ // single send.
1011
+ function beatMs(raw = process.env[BEAT_ENV]) {
1012
+ const text = typeof raw === "string" ? raw.trim() : "";
1013
+ if (text.length === 0) return BEAT_MS;
1014
+ const parsed = Number(text);
1015
+ if (!Number.isFinite(parsed)) return BEAT_MS;
1016
+ return Math.min(BEAT_MAX_MS, Math.max(BEAT_MIN_MS, Math.round(parsed)));
1017
+ }
1018
+
934
1019
  // Cap a label at MAX_LABEL_CHARS UTF-16 units — the same unit the consumer's
935
1020
  // `parseNames` checks, so a label the producer writes is never one the
936
1021
  // consumer drops — while backing off one unit when the cut would split a
@@ -1140,6 +1225,15 @@ function cliFallback(patch) {
1140
1225
  // unverified) and no new imports (self-contained single file). Do NOT
1141
1226
  // reinstall the native publisher from Herdr: two publishers for the same
1142
1227
  // pane collide (dual-publish).
1228
+ //
1229
+ // T2 (the pane must never freeze at `working`): the settle this owner gates on
1230
+ // is reconciled from the host's own live truth on every beat instead of being
1231
+ // inferred — including when a turn was seen to start but its settle edge was
1232
+ // lost, which needs a bounded window of contradictory beats rather than a
1233
+ // single sample; a quiet producer the host never confirms stops beating after a
1234
+ // bounded budget instead of republishing a count-0 work token forever; and the
1235
+ // settle-time pending latch stops counting once the finish hold that raised it
1236
+ // expires.
1143
1237
  // ---------------------------------------------------------------------------
1144
1238
 
1145
1239
  export const NATIVE_STATES = ["working", "blocked", "idle"];
@@ -1150,9 +1244,10 @@ const NATIVE_MAX_ATTEMPTS = 2;
1150
1244
  // (ask/choice/question/questionnaire/permission — never
1151
1245
  // review/RDD execution, which stays working and silent); working while the
1152
1246
  // principal is active OR running/queued delegates exist OR pending launches
1153
- // exist OR review execution holds; idle ONLY on authoritative principal
1247
+ // exist OR review execution holds OR a fresh session-owned background job
1248
+ // still runs; idle ONLY on authoritative principal
1154
1249
  // settled plus zero running+queued plus zero pending plus no human-wait
1155
- // prompt and no review execution. The producer never sets `hasError`: native
1250
+ // prompt and no review execution and no live job. The producer never sets `hasError`: native
1156
1251
  // `blocked` is what fires the host's NeedsAttention toast and sound, so an
1157
1252
  // `error:` label stays sidebar-only and the pane reports `working` while it
1158
1253
  // stands. Never infer terminal from child
@@ -1160,6 +1255,19 @@ const NATIVE_MAX_ATTEMPTS = 2;
1160
1255
  // done/finished (only working|blocked|idle) and never a notification
1161
1256
  // method — the host owns finished text plus toast/sound, and desktop ask
1162
1257
  // attention (including toast dedup) is host-owned (DESIGN §7).
1258
+ //
1259
+ // The `settled` input is never inferred here: the beat reconciles it from the
1260
+ // host's own live truth (`ctx.isIdle()`), so a missed `agent_settled` cannot
1261
+ // leave this producer unable to reach `idle` — not when no turn was observed,
1262
+ // and not when a turn this producer saw start never delivered its settle edge.
1263
+ //
1264
+ // `liveJobCount` closes the disagreement that `restore-done-idle.md` S4 opened
1265
+ // (this document's L3/L4): the display already waited on a live
1266
+ // `bash_background` / `monitor` job while the native state reported `idle`, and
1267
+ // Herdr presents that `idle` as finished (check circle + notification) on a pane
1268
+ // whose row still read pink `gentle`. The input is the freshness-bounded,
1269
+ // session-owned count (`freshRunningJobCount`), so a stale or foreign snapshot
1270
+ // arrives here as 0 and can never block the terminal state (fail OPEN).
1163
1271
  export function computeNativeState({
1164
1272
  agentActive,
1165
1273
  settled,
@@ -1168,10 +1276,11 @@ export function computeNativeState({
1168
1276
  askActive,
1169
1277
  reviewActive,
1170
1278
  hasError,
1279
+ liveJobCount = 0,
1171
1280
  }) {
1172
1281
  if (hasError) return "blocked";
1173
1282
  if (askActive) return "blocked";
1174
- if (agentActive || activeCount > 0 || pendingCount > 0 || reviewActive) {
1283
+ if (agentActive || activeCount > 0 || pendingCount > 0 || reviewActive || liveJobCount > 0) {
1175
1284
  return "working";
1176
1285
  }
1177
1286
  if (settled && !agentActive && activeCount === 0 && pendingCount === 0 && !askActive && !reviewActive) {
@@ -1566,9 +1675,23 @@ export async function liveSummarizeRoots(roots) {
1566
1675
 
1567
1676
  // Producer state, resolved once for both flag files below. GENTLE_STATUS_STATE_DIR
1568
1677
  // (explicit user override) is used as-is; HERDR_PLUGIN_STATE_DIR is
1569
- // Herdr-injected and changes with the plugin id, so when it holds none of our
1570
- // files while the stored dir does, the stored dir wins. Fresh installs with no
1571
- // stored files converge on the injected dir.
1678
+ // Herdr-injected and changes with the plugin id, so the stored dir wins
1679
+ // whenever it holds any of our files — one stray known file in the injected
1680
+ // dir may never outrank it, because the daemon writes its pidfile into the dir
1681
+ // it resolves and that made the split self-perpetuating.
1682
+ //
1683
+ // S1b: the stored canonical dir is the FINAL fallback. This process never
1684
+ // receives HERDR_PLUGIN_STATE_DIR, so resolving the injected dir on a fresh
1685
+ // install named a directory the daemon never created: the refresh write below
1686
+ // failed and the sidebar fell back to polling. The active-id dir is therefore a
1687
+ // candidate here too, derived from the state home when the variable is absent,
1688
+ // so a legacy install whose live flags sit only there is still found.
1689
+ // Selection order: stored if it holds a known file, else the active-id/injected
1690
+ // dir if it holds one, else stored. An injected path is honoured only when it IS
1691
+ // the directory this package derives for that name under the resolved state home
1692
+ // (S1c): any other basename, and an owned basename under another root, is
1693
+ // ignored, so the daemon and this helper can never be pointed at another
1694
+ // plugin's state or at a second root for the same name.
1572
1695
  //
1573
1696
  // S15 identity rename: the active plugin lookup id is herdr-gentle-shell, but
1574
1697
  // every stored state path keeps the herdr-gentle-agents segment (no migration
@@ -1579,6 +1702,15 @@ export async function liveSummarizeRoots(roots) {
1579
1702
  // writes: an upgraded install still carries them, and a family that differs
1580
1703
  // between consumers splits the state across both dirs.
1581
1704
  const SIDEBAR_STATE_SEGMENT = "herdr-gentle-agents";
1705
+ const SIDEBAR_ACTIVE_PLUGIN_ID = "herdr-gentle-shell";
1706
+ // S1c: an injected path is honoured only when its basename names a directory
1707
+ // this package owns — the active plugin id (what Herdr injects today) or the
1708
+ // stored canonical segment — AND it is the path this package derives for that
1709
+ // name under the resolved state home. Any other path, e.g. a third plugin id or
1710
+ // an owned name under another root, is IGNORED: the daemon receives
1711
+ // HERDR_PLUGIN_STATE_DIR while no producer does, so honouring a directory we do
1712
+ // not own (or the same name under another root) is exactly what splits them.
1713
+ const SIDEBAR_OWNED_DIR_NAMES = [SIDEBAR_ACTIVE_PLUGIN_ID, SIDEBAR_STATE_SEGMENT];
1582
1714
  const SIDEBAR_STATE_KNOWN_FILES = [
1583
1715
  "gentle-sidebar-mode.json",
1584
1716
  "gentle-moshi.json",
@@ -1590,12 +1722,71 @@ const SIDEBAR_STATE_KNOWN_FILES = [
1590
1722
  "gentle-plugin-tools.json",
1591
1723
  ];
1592
1724
 
1593
- function sidebarStoredDir() {
1725
+ function sidebarStatePluginsDir() {
1594
1726
  const env = process.env;
1595
1727
  const base = env.XDG_STATE_HOME
1596
1728
  ? join(env.XDG_STATE_HOME, "herdr")
1597
1729
  : join(homedir(), ".local", "state", "herdr");
1598
- return join(base, "plugins", SIDEBAR_STATE_SEGMENT);
1730
+ return join(base, "plugins");
1731
+ }
1732
+
1733
+ function sidebarStoredDir() {
1734
+ return join(sidebarStatePluginsDir(), SIDEBAR_STATE_SEGMENT);
1735
+ }
1736
+
1737
+ // Two spellings name the same directory when their canonical forms match.
1738
+ // realpath resolves symlinks but throws for a path that does not exist yet, so
1739
+ // walk up to the deepest existing ancestor and re-append the missing tail: that
1740
+ // keeps a symlinked or relative spelling of the derived dir from being rejected
1741
+ // as a different directory (S1c/T12 compares paths, never raw strings).
1742
+ function sidebarCanonicalDir(dir) {
1743
+ const absolute = resolvePath(dir);
1744
+ const tail = [];
1745
+ let current = absolute;
1746
+ for (;;) {
1747
+ try {
1748
+ const real = fs.realpathSync(current);
1749
+ return tail.length ? join(real, ...tail) : real;
1750
+ } catch {
1751
+ const parent = dirname(current);
1752
+ if (parent === current) return absolute;
1753
+ // Prepended so the missing tail is re-appended in its original order.
1754
+ tail.unshift(pathBasename(current));
1755
+ current = parent;
1756
+ }
1757
+ }
1758
+ }
1759
+
1760
+ // The active plugin id dir: what Herdr injects as HERDR_PLUGIN_STATE_DIR for the
1761
+ // current plugin id, or — because this producer never receives that variable —
1762
+ // the same path derived from the state home. An injected path is only honoured
1763
+ // when it IS the directory this package derives for that name under the resolved
1764
+ // state home; any other basename (S1c) or an owned basename under another root —
1765
+ // the exact split, since the daemon receives the variable and this producer
1766
+ // derives its own — falls back to the derived path.
1767
+ function sidebarActiveDir() {
1768
+ const injected = process.env.HERDR_PLUGIN_STATE_DIR;
1769
+ if (typeof injected === "string" && injected.length > 0) {
1770
+ const name = pathBasename(injected);
1771
+ if (
1772
+ SIDEBAR_OWNED_DIR_NAMES.includes(name) &&
1773
+ sidebarCanonicalDir(injected) === sidebarCanonicalDir(join(sidebarStatePluginsDir(), name))
1774
+ ) {
1775
+ return injected;
1776
+ }
1777
+ }
1778
+ return join(sidebarStatePluginsDir(), SIDEBAR_ACTIVE_PLUGIN_ID);
1779
+ }
1780
+
1781
+ function sidebarDirHasKnownFile(dir) {
1782
+ for (const name of SIDEBAR_STATE_KNOWN_FILES) {
1783
+ try {
1784
+ if (fs.existsSync(join(dir, name))) return true;
1785
+ } catch {
1786
+ // A single unreadable entry never decides; keep scanning.
1787
+ }
1788
+ }
1789
+ return false;
1599
1790
  }
1600
1791
 
1601
1792
  function sidebarEffectiveDir() {
@@ -1605,35 +1796,17 @@ function sidebarEffectiveDir() {
1605
1796
  const stored = sidebarStoredDir();
1606
1797
  // HEAD parity: an explicit-but-empty (or otherwise invalid non-nullish)
1607
1798
  // value ignores every override and uses the stored default. Only an
1608
- // omitted (null/undefined) explicit falls through to the injected dir.
1799
+ // omitted (null/undefined) explicit falls through to the active-id dir.
1609
1800
  if (explicit !== undefined && explicit !== null) return stored;
1610
- const injected = env.HERDR_PLUGIN_STATE_DIR;
1611
- if (typeof injected !== "string" || injected.length === 0) return stored;
1612
- if (injected === stored) return injected;
1801
+ const active = sidebarActiveDir();
1802
+ if (active === stored) return stored;
1613
1803
  try {
1614
- let injectedHas = false;
1615
- for (const name of SIDEBAR_STATE_KNOWN_FILES) {
1616
- try {
1617
- if (fs.existsSync(join(injected, name))) {
1618
- injectedHas = true;
1619
- break;
1620
- }
1621
- } catch {
1622
- // A single unreadable entry never decides; keep scanning.
1623
- }
1624
- }
1625
- if (injectedHas) return injected;
1626
- for (const name of SIDEBAR_STATE_KNOWN_FILES) {
1627
- try {
1628
- if (fs.existsSync(join(stored, name))) return stored;
1629
- } catch {
1630
- // A single unreadable entry never decides; keep scanning.
1631
- }
1632
- }
1804
+ if (sidebarDirHasKnownFile(stored)) return stored;
1805
+ if (sidebarDirHasKnownFile(active)) return active;
1633
1806
  } catch {
1634
- // Fall through to the injected dir on unexpected failure.
1807
+ // Fall through to the stored canonical dir on unexpected failure.
1635
1808
  }
1636
- return injected;
1809
+ return stored;
1637
1810
  }
1638
1811
 
1639
1812
  // Status-refresh request file, owned by the consumer daemon: a single
@@ -2588,16 +2761,18 @@ export default function (pi) {
2588
2761
  // exactly the entries whose status is running|queued. Gentle Shell owns
2589
2762
  // lifecycle/status truth: no local age/staleness timeout is applied.
2590
2763
  // pendingCalls holds label correlation state for a later
2591
- // gentleAgents.taskId result plus a role-only display hint (exact pending
2592
- // subagent agent -> gentle_roles_v1 slug) while the tool call is in
2593
- // flight; it never increments the count. Task-mode `subagent_run` stays
2764
+ // gentleAgents.taskId result plus the in-flight launch evidence: its own
2765
+ // contribution to the consolidated `(n)` count (a task-mode `subagent_run`
2766
+ // stays in flight with no TaskStore record until tool_result, so the record
2767
+ // set alone undercounts it) and a role-only display hint (exact pending
2768
+ // subagent agent -> gentle_roles_v1 slug). Task-mode `subagent_run` stays
2594
2769
  // in flight with no TaskStore record until tool_result, so without the
2595
2770
  // hint the active role would be invisible and the sidebar would show
2596
2771
  // generic `working` during execution.
2597
2772
  // Finished/failed/cancelled/waiting entries may linger in the map but
2598
2773
  // never count; the map is cleared only on session reset (plus the
2599
2774
  // bounded-map guard) — never by a local staleness timeout.
2600
- const pendingCalls = new Map(); // toolCallId -> { agent, label, at }; agent/label are undefined when no agent is resolvable
2775
+ const pendingCalls = new Map(); // toolCallId -> { agent, label, at, taskId?, cancelled? }; agent/label are undefined when no agent is resolvable
2601
2776
  const tasks = new Map(); // taskId -> { agent, label, status, at }
2602
2777
 
2603
2778
  // Blocker legs. ask combines choice + native questionnaire + legacy
@@ -2635,6 +2810,10 @@ export default function (pi) {
2635
2810
  // opened the current ask episode.
2636
2811
  let moshiContext;
2637
2812
  let moshiCtxRef;
2813
+ // Last context the host handed us, retained so a beat can ask the host's own
2814
+ // live truth (`isIdle()`) instead of inferring a settle. Kept apart from
2815
+ // `moshiCtxRef`, whose capture leg owns that reference.
2816
+ let settleCtx;
2638
2817
  let lastAskToolName;
2639
2818
 
2640
2819
  // Live background jobs (Gentle Shell `bash_background` / `monitor`) from the
@@ -2694,6 +2873,7 @@ export default function (pi) {
2694
2873
  // freshness bound measures from.
2695
2874
  function onJobsSnapshot(value) {
2696
2875
  if (!isRecord(value) || !isRecord(value.snapshot) || !Array.isArray(value.snapshot.jobs)) return;
2876
+ noteActivity();
2697
2877
  const jobs = value.snapshot.jobs.filter(
2698
2878
  (entry) => isRecord(entry) && typeof entry.id === "string" && entry.id.length > 0,
2699
2879
  );
@@ -2830,6 +3010,13 @@ export default function (pi) {
2830
3010
  let presenceReconciler = createPresenceReconciler();
2831
3011
  let transportFails = 0;
2832
3012
  let beatTimer;
3013
+ // Consecutive quiet beats published without host truth (see
3014
+ // `quietWithoutTruth`); bounded by QUIET_BEAT_LIMIT and reset by work.
3015
+ let quietBeats = 0;
3016
+ // Consecutive beats that contradict a turn this producer saw start (see
3017
+ // `lostSettleContradiction`); bounded by LOST_SETTLE_BEATS and reset by any
3018
+ // activity edge.
3019
+ let lostSettleBeats = 0;
2833
3020
  let publishQueued = false;
2834
3021
  let publishInFlight = false;
2835
3022
  // Native owner queue (always on): monotonic seq per logical report,
@@ -2852,16 +3039,51 @@ export default function (pi) {
2852
3039
  // beat arriving mid-send is describing.
2853
3040
  let nativeSending = null;
2854
3041
  let nativeLastOk = undefined;
3042
+ // T2/S12 terminal guard: agent_settled clears the metadata pending-launch
3043
+ // hint below, but a settle that observes in-flight launches retains pending
3044
+ // evidence here so the terminal state stays held until those launches
3045
+ // resolve. It gates BOTH sides — the native report (via `pendingCount`) and
3046
+ // the display (`done` mint and the `orchestrating` marker) — so a stranded
3047
+ // launch can never leave the row reading `done` beside a native `working`.
3048
+ // Metadata/tasks untouched; the guard clears when the union of the episode's
3049
+ // unresolved launches is empty, on agent_start, with the session, and — when
3050
+ // a launch never reports back — at `nativeSettledPendingUntil`, the
3051
+ // finish-hold deadline of the settle that raised it. Past that hold the
3052
+ // evidence stops counting and the expiry beat below lands the terminal state,
3053
+ // so a lost launch result can never pin the report at `working` for good
3054
+ // (seq itself never resets).
2855
3055
  let nativeSettledPending = false;
2856
- // Finish-hold episode (S2): minted once at the settled-and-empty edge so the
3056
+ let nativeSettledPendingUntil = 0;
3057
+ // When the episode's hold was first raised. The episode ceiling is measured
3058
+ // from here, so repeated re-settles can extend up to it but never past it.
3059
+ let nativeSettledPendingStartedAt = 0;
3060
+ // The exact launches the settling turn left in flight. A result retires only
3061
+ // its own id; a later settle ADDS to this union instead of replacing it, and
3062
+ // the hold stands until the union is empty, so one early result can never
3063
+ // release evidence another launch still owes.
3064
+ let nativeSettledPendingCalls = new Set();
3065
+ // One timer at that deadline, the same discipline as `armJobsExpiry`: the
3066
+ // hold has no other edge behind it, so without this beat neither the native
3067
+ // `idle` nor the `done` mint would ever land. One beat is enough — from that
3068
+ // instant the evidence is zero, so the beat either reports the terminal
3069
+ // state or the real activity that still holds it. Never a poll: a launch
3070
+ // resolution, `agent_start`, and the session reset drop it.
3071
+ let settledPendingExpiryTimer;
3072
+ // Finish episode (S2/T3): minted once at the settled-and-empty edge so the
2857
3073
  // row reads `done`, then republished unchanged (never refreshed) until the
2858
- // hold expires. `donePending` carries the unannounced finish to the beat
2859
- // that actually delivers the token (S3), and `sawActivity` remembers that
2860
- // the session did work, so a session that never ran a turn stays idle. All
2861
- // three clear with the session and the moment any work reappears.
3074
+ // unseen cap expires. `donePending` carries the unannounced finish to the
3075
+ // beat that actually delivers the token (S3), and `sawActivity` remembers
3076
+ // that the session did work, so a session that never ran a turn stays idle.
3077
+ // All three clear with the session and the moment any work reappears.
2862
3078
  let doneExpiry;
2863
3079
  let donePending = false;
2864
3080
  let sawActivity = false;
3081
+ // Whether the settle this row sits in came from an observed turn
3082
+ // (`agent_settled`) rather than from the host-truth reconcile: only an
3083
+ // observed turn can mint a finish, so non-turn activity (an ask, a review, a
3084
+ // job) on a producer that never saw a turn can never announce `done` or the
3085
+ // phone's `task_complete`.
3086
+ let turnSettled = false;
2865
3087
  // LIVE-1 startup latency: the session binding is still INITIATED on
2866
3088
  // session_start (so Herdr can attribute the pane from the first frame), but
2867
3089
  // the host no longer waits for it. The host awaits every session_start
@@ -2871,12 +3093,150 @@ export default function (pi) {
2871
3093
  // unchanged, only the host's startup return is freed. Reset with the session
2872
3094
  // so a stale binding can never gate the next one.
2873
3095
  let sessionReportPending = null;
2874
- // T2 native-only terminal guard: agent_settled clears the metadata
2875
- // pending-launch hint below, but a settle that observes in-flight
2876
- // launches retains pending evidence here so native idle gating stays
2877
- // working until those launches resolve. Metadata/tasks untouched; the
2878
- // guard clears when a launch resolves, on agent_start, and with the
2879
- // session (seq itself never resets).
3096
+
3097
+ // Retain the host context the settle reconcile reads (`isIdle()`), next to
3098
+ // the Moshi capture reference it already replaced. A lifecycle event that
3099
+ // arrives without a context must not erase the last truth we hold.
3100
+ function retainContext(ctx) {
3101
+ moshiCtxRef = ctx;
3102
+ if (ctx) settleCtx = ctx;
3103
+ }
3104
+
3105
+ function clearSettledPending() {
3106
+ nativeSettledPending = false;
3107
+ nativeSettledPendingUntil = 0;
3108
+ nativeSettledPendingStartedAt = 0;
3109
+ nativeSettledPendingCalls.clear();
3110
+ clearSettledPendingExpiry();
3111
+ }
3112
+
3113
+ function clearSettledPendingExpiry() {
3114
+ if (settledPendingExpiryTimer === undefined) return;
3115
+ clearTimeout(settledPendingExpiryTimer);
3116
+ settledPendingExpiryTimer = undefined;
3117
+ }
3118
+
3119
+ function armSettledPendingExpiry(at) {
3120
+ clearSettledPendingExpiry();
3121
+ const delay = Math.max(0, at - Date.now());
3122
+ settledPendingExpiryTimer = setTimeout(() => {
3123
+ settledPendingExpiryTimer = undefined;
3124
+ if (!rootSession) return;
3125
+ schedulePublish();
3126
+ }, delay);
3127
+ if (settledPendingExpiryTimer.unref) settledPendingExpiryTimer.unref();
3128
+ }
3129
+
3130
+ // Past the finish hold of the settle that raised it, the retained pending
3131
+ // evidence stops counting: the hold is the span it exists to cover. This is
3132
+ // the single condition the native report and the display both gate on.
3133
+ function settledPendingHeld() {
3134
+ return nativeSettledPending && Date.now() < nativeSettledPendingUntil;
3135
+ }
3136
+
3137
+ // One launch result retires its own evidence. The hold releases — and the
3138
+ // caller must publish on this edge — only when no launch the settle observed
3139
+ // is still unresolved. An id outside the settling set (an earlier launch, or
3140
+ // one started after the settle) never releases the hold.
3141
+ function resolveSettledPending(callId) {
3142
+ if (!settledPendingHeld()) return false;
3143
+ if (typeof callId !== "string" || !nativeSettledPendingCalls.delete(callId)) return false;
3144
+ if (nativeSettledPendingCalls.size > 0) return false;
3145
+ clearSettledPending();
3146
+ return true;
3147
+ }
3148
+
3149
+ // The settle state `agent_settled` applies, shared with the reconcile below
3150
+ // so both paths agree on every field except the finish episode.
3151
+ function applySettled(fromTurn) {
3152
+ agentActive = false;
3153
+ settled = true;
3154
+ turnSettled = fromTurn === true;
3155
+ lostSettleBeats = 0;
3156
+ clearSettledPending();
3157
+ }
3158
+
3159
+ // Every activity edge restarts the lost-settle window: a tool call, a
3160
+ // delegate, a job, an ask/review/error leg (the contradiction predicate reads
3161
+ // those legs directly) or a new `agent_start`. Only consecutive beats that
3162
+ // still contradict the host may settle.
3163
+ function noteActivity() {
3164
+ lostSettleBeats = 0;
3165
+ }
3166
+
3167
+ // Nothing observable keeps this session busy: no authoritative
3168
+ // running|queued delegate, no launch in flight, no live background job.
3169
+ // `agentActive` is not part of this evidence: it is this producer's own
3170
+ // inference from turn events, so the reconcile guards it separately and
3171
+ // never overrides a turn it saw start.
3172
+ function noWorkEvidence() {
3173
+ return (
3174
+ activeSubs().length === 0 &&
3175
+ pendingCalls.size === 0 &&
3176
+ freshRunningJobCount() === 0
3177
+ );
3178
+ }
3179
+
3180
+ // Live host truth for the settle decision: the retained context's `isIdle()`.
3181
+ // `undefined` means the host offers no truth (no context yet, or one without
3182
+ // the method); `false` means the host still considers the agent busy, which
3183
+ // is never this producer's to override.
3184
+ function hostIdleTruth() {
3185
+ const probe = settleCtx?.isIdle;
3186
+ if (typeof probe !== "function") return undefined;
3187
+ try {
3188
+ return probe.call(settleCtx) === true;
3189
+ } catch {
3190
+ return undefined;
3191
+ }
3192
+ }
3193
+
3194
+ // The lost-settle contradiction: this producer still believes its turn runs,
3195
+ // the host answers that nothing is processing, and no work evidence or
3196
+ // owning leg keeps the session busy. Both sides are live truth re-read on
3197
+ // every beat, so the contradiction is never remembered from a stale sample.
3198
+ function lostSettleContradiction() {
3199
+ return (
3200
+ agentActive &&
3201
+ hostIdleTruth() === true &&
3202
+ noWorkEvidence() &&
3203
+ !askActiveNow() &&
3204
+ !reviewActive &&
3205
+ errorCode === undefined
3206
+ );
3207
+ }
3208
+
3209
+ // Recover a settle this producer missed. `settled` flips only in
3210
+ // `agent_settled`, which early-returns unless the host already reports idle,
3211
+ // so a session first observed while idle — or an aborted or failed run whose
3212
+ // `agent_settled` never arrived — leaves `settled` false: `computeNativeState`
3213
+ // returns undefined and the pane keeps the last native `working`. The host
3214
+ // answers the same question `agent_settled` asks, so read its live truth here
3215
+ // instead of inferring a terminal from a timeout or from a count.
3216
+ function reconcileSettled() {
3217
+ if (!rootSession || settled) return;
3218
+ // No turn edge was ever observed: nothing local contradicts the host, so
3219
+ // its answer settles the producer on the same beat.
3220
+ if (!agentActive) {
3221
+ if (!noWorkEvidence()) return;
3222
+ if (hostIdleTruth() !== true) return;
3223
+ applySettled(false);
3224
+ return;
3225
+ }
3226
+ // A turn the producer itself saw start is local evidence of a running
3227
+ // agent, and `isIdle()` turns true at the end of the run — so a genuine
3228
+ // settle edge can still be in flight. Only a bounded window of consecutive
3229
+ // contradictory beats proves the edge was lost.
3230
+ if (!lostSettleContradiction()) {
3231
+ lostSettleBeats = 0;
3232
+ return;
3233
+ }
3234
+ lostSettleBeats += 1;
3235
+ if (lostSettleBeats < LOST_SETTLE_BEATS) return;
3236
+ // `fromTurn` false: a recovered settle is never a turn, so it can mint no
3237
+ // finish episode (no `gentle_done_v1`, no finish notification).
3238
+ applySettled(false);
3239
+ }
2880
3240
 
2881
3241
  function refreshSessionRef(ctx) {
2882
3242
  try {
@@ -2995,13 +3355,11 @@ export default function (pi) {
2995
3355
  // Authoritative TaskStore projection for liveness/marker coverage:
2996
3356
  // every entry whose status is running|queued is active here (T1
2997
3357
  // epochs/witness unchanged). Display count/roles use runningSubs()
2998
- // below (running only). Pending tool calls never count;
2999
- // finished/failed/cancelled/waiting entries never count.
3000
- // WHY pending calls stay out of the count: task-mode `subagent_run` stays
3001
- // in flight without a TaskStore record until it returns tool_result, so
3002
- // counting pending calls would inflate `gentle_work_v1` with estimates.
3003
- // The count is normative; role display below is the
3004
- // only consumer of the pending hint.
3358
+ // below (running only). Finished/failed/cancelled/waiting entries never
3359
+ // count. The consolidated `(n)` count adds the in-flight launch calls the
3360
+ // record set does not list yet (countSubs below, S11): a task-mode
3361
+ // `subagent_run` has no TaskStore record until it returns tool_result, so
3362
+ // the record set alone counted live synchronous delegates as zero.
3005
3363
  // Order is oldest-first by immutable firstSeen (fallback at): progress
3006
3364
  // reads bump `at` but never move `firstSeen`, so they never reorder.
3007
3365
  function activeSubs() {
@@ -3024,6 +3382,8 @@ export default function (pi) {
3024
3382
  // T2b display projection: only `running` counts as executing.
3025
3383
  // Queued/waiting never count and never supply a role; the total here is
3026
3384
  // the consumer's `(n)` suffix source (suffix only when > 1).
3385
+ // This map is the producer's own evidence, so it is authoritative only
3386
+ // when no presence snapshot can be read: displaySubs() below narrows it.
3027
3387
  function runningSubs() {
3028
3388
  const out = [];
3029
3389
  for (const [id, task] of tasks) {
@@ -3041,18 +3401,108 @@ export default function (pi) {
3041
3401
  return out;
3042
3402
  }
3043
3403
 
3404
+ // Authoritative display projection for the produced count, role words and
3405
+ // names: the ids a VALID presence snapshot lists running. A local record
3406
+ // the upstream store does not list is not running whatever this map still
3407
+ // says, so a record stranded by an epoch bump after its last witnessed
3408
+ // generation contributes no name, no role and no count, and an idle session
3409
+ // reaches `idle` instead of a stale role word. Fallback (never zero): with
3410
+ // no usable snapshot the local map is the only evidence and stands in full
3411
+ // — zero would flip the consumer's `done` gate and hide real running work.
3412
+ // Pending launch hints are deliberately not narrowed: they exist only while
3413
+ // their own tool call is in flight, and their purpose is a record the store
3414
+ // does not carry yet.
3415
+ function displaySubs(snapshot) {
3416
+ const local = runningSubs();
3417
+ if (!isRecord(snapshot) || !Array.isArray(snapshot.tasks)) return local;
3418
+ const listed = new Set();
3419
+ for (const entry of snapshot.tasks) {
3420
+ if (isRecord(entry) && typeof entry.id === "string" && entry.status === "running") {
3421
+ listed.add(entry.id);
3422
+ }
3423
+ }
3424
+ return local.filter((sub) => listed.has(sub.id));
3425
+ }
3426
+
3427
+ // Distinct in-flight launch calls the running record set does not already
3428
+ // list (S11): the second half of the `(n)` union. One delegate is one
3429
+ // entry — the map is keyed by call id, so a call counts at most once, and a
3430
+ // call that resumes a task the records already list running (its `taskId`)
3431
+ // is the SAME delegate and adds nothing. A cancelled call is no longer an
3432
+ // executing delegate; it keeps its pending evidence only for the terminal
3433
+ // gate, which is a separate leg.
3434
+ function inFlightLaunchSubs(listed) {
3435
+ const out = [];
3436
+ for (const pending of pendingCalls.values()) {
3437
+ if (pending.cancelled === true) continue;
3438
+ if (pending.taskId !== undefined && listed.has(pending.taskId)) continue;
3439
+ out.push(pending);
3440
+ }
3441
+ out.sort((a, b) => a.at - b.at);
3442
+ return out;
3443
+ }
3444
+
3445
+ // The consolidated `(n)` source (S11/S11b): the UNION of the running
3446
+ // records the presence snapshot confirms and the distinct in-flight launches
3447
+ // the store does not list yet, deduplicated so one delegate is counted once.
3448
+ // In-flight launches are never narrowed by the snapshot: like the role hint,
3449
+ // they exist only while their own call is in flight, which is exactly the
3450
+ // evidence the store cannot carry yet.
3451
+ // S11b: an announced running record and its own in-flight launch are the SAME
3452
+ // delegate and share no call id — a background launch is acked synchronously
3453
+ // while its START may announce the record on the lifecycle channel before
3454
+ // that ack lands, and the announcement carries only the agent. So per agent
3455
+ // the count is max(running records, unbound in-flight launches): a record
3456
+ // consumes one launch of its own agent (oldest first, which max() expresses
3457
+ // without an arbitrary pairing) and never a launch of another agent, while
3458
+ // two launches beside one record stay two delegates (real work is never
3459
+ // hidden). Only KNOWN agents form a group; an entry with no agent is counted
3460
+ // on its own, because identity is the only evidence that two entries are the
3461
+ // same delegate.
3462
+ function countSubs(snapshot) {
3463
+ const running = displaySubs(snapshot);
3464
+ const listed = new Set(running.map((sub) => sub.id));
3465
+ const launches = inFlightLaunchSubs(listed);
3466
+ const groups = new Map(); // known agent -> { records, launches }
3467
+ let unknown = 0;
3468
+ const groupOf = (agent) => {
3469
+ if (typeof agent !== "string" || agent.length === 0) return undefined;
3470
+ let group = groups.get(agent);
3471
+ if (group === undefined) {
3472
+ group = { records: 0, launches: 0 };
3473
+ groups.set(agent, group);
3474
+ }
3475
+ return group;
3476
+ };
3477
+ for (const sub of running) {
3478
+ const group = groupOf(sub.agent);
3479
+ if (group === undefined) unknown += 1;
3480
+ else group.records += 1;
3481
+ }
3482
+ for (const launch of launches) {
3483
+ const group = groupOf(launch.agent);
3484
+ if (group === undefined) unknown += 1;
3485
+ else group.launches += 1;
3486
+ }
3487
+ let total = unknown;
3488
+ for (const group of groups.values()) total += Math.max(group.records, group.launches);
3489
+ return total;
3490
+ }
3491
+
3044
3492
  // Role-only hint from in-flight `subagent_run`/`subagent_continue` tool
3045
3493
  // calls: task-mode launches stay in flight (no tool_result yet, hence no
3046
3494
  // TaskStore record) even though `tool_call` input already carries the
3047
3495
  // exact agent name. Publishing that agent's role slug keeps the sidebar
3048
- // from showing generic `working` during execution. This is display-only:
3049
- // it never enters `gentle_work_v1` or any displayed count, and each hint
3050
- // is cleared when its tool_result arrives, the call is cancelled, or the
3051
- // agent settles. The hint carries the mapped word or the sanitized
3052
- // passthrough slug (unsalvageable names yield no hint and read gentle).
3496
+ // from showing generic `working` during execution. The hint never adds a
3497
+ // name; its count contribution comes from countSubs above, so the hint
3498
+ // itself stays role-only. Each hint is cleared when its tool_result
3499
+ // arrives, the call is cancelled, or the agent settles. The hint carries
3500
+ // the mapped word or the sanitized passthrough slug (unsalvageable names
3501
+ // yield no hint and read gentle).
3053
3502
  function pendingRoleSubs() {
3054
3503
  const out = [];
3055
3504
  for (const pending of pendingCalls.values()) {
3505
+ if (pending.cancelled === true) continue;
3056
3506
  if (agentToRole(pending.agent) !== undefined) {
3057
3507
  out.push({ agent: pending.agent, label: pending.label, at: pending.at });
3058
3508
  }
@@ -3074,8 +3524,8 @@ export default function (pi) {
3074
3524
  // Merged role sources, oldest-first by first-seen: authoritative running
3075
3525
  // TaskStore subs plus pending role hints. Authoritative entries win on
3076
3526
  // duplicates via rolesCsv dedup (first wins = oldest wins).
3077
- function mergedRoleSubs() {
3078
- const merged = [...runningSubs(), ...pendingRoleSubs()];
3527
+ function mergedRoleSubs(subs) {
3528
+ const merged = [...subs, ...pendingRoleSubs()];
3079
3529
  merged.sort((a, b) => (a.firstSeen ?? a.at) - (b.firstSeen ?? b.at));
3080
3530
  return merged;
3081
3531
  }
@@ -3150,13 +3600,15 @@ export default function (pi) {
3150
3600
  ) {
3151
3601
  return "rdd";
3152
3602
  }
3153
- // The bare visible words `working` and `subagent` are banned: a sanitized
3154
- // unknown slug exactly equal to either degrades to no role (generic
3155
- // `gentle`) in metadata roles and the native message alike. `subagent` is
3156
- // the launch-correlation placeholder, never an agent name, so it must
3157
- // never reach the wire as a role word.
3603
+ // The bare visible words `working`, `subagent`, and `gentle` are banned: a
3604
+ // sanitized unknown slug exactly equal to one of them degrades to no role
3605
+ // (generic `gentle`) in metadata roles and the native message alike.
3606
+ // `subagent` is the launch-correlation placeholder, never an agent name, so
3607
+ // it must never reach the wire as a role word. `gentle` is the pink
3608
+ // generic's own word (S1), so an agent literally named `gentle` must not
3609
+ // become a second one on the amber cell.
3158
3610
  const slug = sanitizeAgentSlug(agent);
3159
- return slug === "working" || slug === "subagent" ? undefined : slug;
3611
+ return slug === "working" || slug === "subagent" || slug === "gentle" ? undefined : slug;
3160
3612
  }
3161
3613
 
3162
3614
  // Bounded CSV of role words, oldest-first (subs already arrive
@@ -3178,15 +3630,17 @@ export default function (pi) {
3178
3630
  return parts.join(",");
3179
3631
  }
3180
3632
 
3181
- function buildTokens() {
3633
+ function buildTokens(snapshot) {
3182
3634
  if (!sessionHash) return {};
3183
3635
  const expiry = Date.now() + TTL_MS;
3184
3636
  // Liveness/marker coverage stays running|queued (T1); the visible
3185
- // count + roles are running-only (T2b executing set).
3637
+ // count + roles are running-only (T2b executing set) narrowed to the ids
3638
+ // the presence snapshot lists running (displaySubs), plus the distinct
3639
+ // in-flight launches the store does not list yet (countSubs, S11/S11b).
3186
3640
  const subs = activeSubs();
3187
- const running = runningSubs();
3641
+ const running = displaySubs(snapshot);
3188
3642
  const tokens = {};
3189
- const count = String(running.length);
3643
+ const count = String(countSubs(snapshot));
3190
3644
  if (COUNT_RE.test(count)) tokens.gentle_work_v1 = `${sessionHash}:${count}:${expiry}`;
3191
3645
  const csv = namesCsv(running);
3192
3646
  // Clear (null) when the authoritative active TaskStore list has no
@@ -3199,11 +3653,12 @@ export default function (pi) {
3199
3653
  // §4.3), merged with the in-flight pending role hint: running TaskStore
3200
3654
  // roles (oldest-first) plus the exact pending subagent agent while its
3201
3655
  // tool call is in flight (task-mode launches have no TaskStore record
3202
- // yet). The hint is role-only — the count above stays running-only —
3203
- // and is cleared with the pending call. Null (clear) when no active
3204
- // recognized roles in either source — unrecognized agents degrade to
3205
- // the consumer's `working` display.
3206
- const roles = rolesCsv(mergedRoleSubs());
3656
+ // yet). The hint is role-only — the count above adds the in-flight call
3657
+ // itself in countSubs, grouped per agent (S11b) — and is cleared with the
3658
+ // pending call. Null (clear) when no active recognized roles in either
3659
+ // source — unrecognized agents degrade to the consumer's `working`
3660
+ // display.
3661
+ const roles = rolesCsv(mergedRoleSubs(running));
3207
3662
  if (roles.length > 0) tokens.gentle_roles_v1 = roles;
3208
3663
  else tokens.gentle_roles_v1 = null;
3209
3664
  // Clear the retired disclosure token left by older producers.
@@ -3254,8 +3709,17 @@ export default function (pi) {
3254
3709
  // fresh marker to the
3255
3710
  // `orchestrating` display only when no recognized role is active (below
3256
3711
  // attention, terminal `done`, and recognized roles; ahead of main
3257
- // `working`).
3258
- if (rootSession && (agentActive || subs.length > 0 || pendingCalls.size > 0 || freshRunningJobCount() > 0)) {
3712
+ // `working`). It answers the same held condition as the native report
3713
+ // (S12): while the settle-time pending evidence stands, the row must read
3714
+ // the pink generic wait, never `done` beside a native `working`.
3715
+ if (
3716
+ rootSession &&
3717
+ (agentActive ||
3718
+ subs.length > 0 ||
3719
+ pendingCalls.size > 0 ||
3720
+ freshRunningJobCount() > 0 ||
3721
+ settledPendingHeld())
3722
+ ) {
3259
3723
  tokens.gentle_orchestrating_v1 = `${sessionHash}:${expiry}`;
3260
3724
  } else {
3261
3725
  tokens.gentle_orchestrating_v1 = null;
@@ -3280,19 +3744,26 @@ export default function (pi) {
3280
3744
  const pending = pendingRole();
3281
3745
  if (pending !== undefined) tokens[PENDING_TOKEN] = `${sessionHash}:${pending}:${expiry}`;
3282
3746
  else tokens[PENDING_TOKEN] = null;
3283
- // Synthesized finish signal (S2/D2): minted once at the settled-and-empty
3284
- // edge — principal settled with no running/queued delegate, no pending
3285
- // launch, no live background job, and no human-wait, review, or error leg
3286
- // — then republished with the SAME expiry so the hold can never be
3287
- // extended. Any work appearing during the hold clears it on that beat, so
3288
- // the row moves straight back to the role state. A session that never
3289
- // worked never mints one. A live background job counts as activity: the
3290
- // finish waits while the session still waits on it.
3747
+ // Synthesized finish signal (S2/D2/T3): minted once at the settled-and-
3748
+ // empty edge — principal settled with no running/queued delegate, no
3749
+ // pending launch, no live background job, and no human-wait, review, or
3750
+ // error leg — then republished with the SAME expiry so the unseen cap can
3751
+ // never be extended. The consumer holds `done` until the pane is viewed
3752
+ // (its own 5 s dwell, then idle) and lets the token expire at the cap when
3753
+ // nobody ever looks. Any work appearing during the episode clears it on
3754
+ // that beat, so the row moves straight back to the role state. A session
3755
+ // that never worked never mints one. A live background job counts as
3756
+ // activity: the finish waits while the session still waits on it.
3757
+ // A stranded settle-time launch is activity too (S12): the same held
3758
+ // condition the native report uses blocks the `done` mint here, so the
3759
+ // display and the native status agree at the settle edge. The settle
3760
+ // hold's expiry releases it through the beat armed at that deadline.
3291
3761
  const activity =
3292
3762
  agentActive ||
3293
3763
  subs.length > 0 ||
3294
3764
  pendingCalls.size > 0 ||
3295
3765
  freshRunningJobCount() > 0 ||
3766
+ settledPendingHeld() ||
3296
3767
  askActiveNow() ||
3297
3768
  reviewActive ||
3298
3769
  !!errorCode;
@@ -3300,9 +3771,9 @@ export default function (pi) {
3300
3771
  sawActivity = true;
3301
3772
  doneExpiry = undefined;
3302
3773
  donePending = false;
3303
- } else if (settled) {
3774
+ } else if (settled && turnSettled) {
3304
3775
  if (doneExpiry === undefined && sawActivity) {
3305
- doneExpiry = Date.now() + doneHoldMs();
3776
+ doneExpiry = Date.now() + doneUnseenCapMs();
3306
3777
  donePending = true;
3307
3778
  sawActivity = false;
3308
3779
  }
@@ -3371,16 +3842,73 @@ export default function (pi) {
3371
3842
  if (beatTimer || !rootSession) return;
3372
3843
  if (!interesting() && settled) return;
3373
3844
  beatTimer = setInterval(() => {
3845
+ // A tick with nothing interesting to publish has nothing to do. Stopping
3846
+ // here (instead of only after a landed publish) is what keeps a slow
3847
+ // send from re-arming the interval through `publishQueued` and spinning
3848
+ // a beat nobody needs.
3849
+ if (!interesting()) {
3850
+ stopBeat();
3851
+ return;
3852
+ }
3853
+ // T2 quiet bound: a beat with no work evidence, no host truth, and no
3854
+ // leg that still owns the row has nothing confirmed to publish — every
3855
+ // such beat republishes a fresh count-0 `gentle_work_v1`, and that
3856
+ // eternal fresh work token is what keeps the row from ever reaching
3857
+ // idle. The beat spends a bounded budget of quiet beats (one BEAT_MS
3858
+ // each) and then stops. Stopping is the honest outcome: a native state
3859
+ // the host never confirmed must not be published in its place. The
3860
+ // bound never applies to a turn this producer saw start (see
3861
+ // `quietWithoutTruth`), so it cannot leave live work unpainted; the
3862
+ // edges that schedule a publish (ask, review, launch, session changes,
3863
+ // jobs) re-arm the beat, while an ordinary tool edge reaches the row
3864
+ // through the host's own truth rather than by re-arming it.
3865
+ if (quietWithoutTruth()) {
3866
+ quietBeats += 1;
3867
+ if (quietBeats >= QUIET_BEAT_LIMIT) {
3868
+ stopBeat();
3869
+ return;
3870
+ }
3871
+ } else {
3872
+ quietBeats = 0;
3873
+ }
3374
3874
  void publishNow();
3375
- }, BEAT_MS);
3875
+ }, beatMs());
3376
3876
  if (beatTimer.unref) beatTimer.unref();
3377
3877
  }
3378
3878
 
3879
+ function stopBeat() {
3880
+ if (!beatTimer) return;
3881
+ clearInterval(beatTimer);
3882
+ beatTimer = undefined;
3883
+ }
3884
+
3379
3885
  function maybeStopBeat() {
3380
- if (beatTimer && !interesting()) {
3381
- clearInterval(beatTimer);
3382
- beatTimer = undefined;
3383
- }
3886
+ if (beatTimer && !interesting()) stopBeat();
3887
+ }
3888
+
3889
+ // T2 quiet bound predicate (see the budget applied inside `ensureBeat`): the
3890
+ // host offers no truth at all, nothing is active by evidence, and no leg
3891
+ // still owns the row. A host that answers `false` is not quiet — it says the
3892
+ // agent is still running — and a host that answers `true` settles through
3893
+ // `reconcileSettled` instead. No native state is ever inferred here.
3894
+ //
3895
+ // `agentActive` is excluded on purpose: a turn this producer saw start is
3896
+ // live work, and the host offers no way to confirm its settle. Bounding that
3897
+ // beat would stop painting a running turn, which is exactly the pin the bound
3898
+ // exists to avoid (S2) — the bound must never trade a truthful "still
3899
+ // working" for a false `idle`. It therefore covers only a producer with no
3900
+ // observed turn behind it and no host truth to settle on.
3901
+ function quietWithoutTruth() {
3902
+ return (
3903
+ !agentActive &&
3904
+ !settled &&
3905
+ hostIdleTruth() === undefined &&
3906
+ noWorkEvidence() &&
3907
+ !askActiveNow() &&
3908
+ !reviewActive &&
3909
+ errorCode === undefined &&
3910
+ doneExpiry === undefined
3911
+ );
3384
3912
  }
3385
3913
 
3386
3914
  // N1 parity report: state + message. Working carries the SPECIFIC
@@ -3407,9 +3935,13 @@ export default function (pi) {
3407
3935
  agentActive,
3408
3936
  settled,
3409
3937
  activeCount: activeSubs().length,
3410
- pendingCount: pendingCalls.size + (nativeSettledPending ? 1 : 0),
3938
+ pendingCount: pendingCalls.size + (settledPendingHeld() ? 1 : 0),
3411
3939
  askActive: askActiveNow(),
3412
3940
  reviewActive,
3941
+ // S4/S5: the same freshness-bounded job count the display `done` mint
3942
+ // waits on, so a live job can never leave a non-terminal row beside a
3943
+ // terminal native status.
3944
+ liveJobCount: freshRunningJobCount(),
3413
3945
  });
3414
3946
  if (!state) return undefined;
3415
3947
  if (state === "blocked") {
@@ -3622,9 +4154,13 @@ export default function (pi) {
3622
4154
  // flight publishes nothing: `rootSession` is re-read after the wait.
3623
4155
  await awaitSessionBinding();
3624
4156
  if (!rootSession || !sidebarPublishingEnabled()) return;
3625
- reconcilePresence();
4157
+ // Host truth first: a settle this producer missed must be visible to both
4158
+ // the native report and the tokens built below.
4159
+ reconcileSettled();
4160
+ const snapshot = readPresence();
4161
+ reconcilePresence(snapshot);
3626
4162
  queueNative();
3627
- const tokens = buildTokens();
4163
+ const tokens = buildTokens(snapshot);
3628
4164
  if (Object.keys(tokens).length === 0) {
3629
4165
  maybeStopBeat();
3630
4166
  return;
@@ -3667,6 +4203,17 @@ export default function (pi) {
3667
4203
  debug("beat", `tokens=${Object.keys(tokens).length} subs=${activeSubs().length}`);
3668
4204
  }
3669
4205
 
4206
+ // One snapshot read per beat, shared by reconciliation and the display
4207
+ // projection, so both legs decide on the same generation.
4208
+ function readPresence() {
4209
+ if (!sessionId) return undefined;
4210
+ try {
4211
+ return readPresenceSnapshot(sessionId, Date.now());
4212
+ } catch {
4213
+ return undefined;
4214
+ }
4215
+ }
4216
+
3670
4217
  // T1 passive presence reconciliation: resolve explicit terminal task
3671
4218
  // statuses (and witnessed absence in a newer complete snapshot) from the
3672
4219
  // Gentle Shell presence files before building tokens, so delegate
@@ -3674,14 +4221,7 @@ export default function (pi) {
3674
4221
  // no timers, no writes, no imported upstream dependencies; any unreadable
3675
4222
  // or inapplicable snapshot leaves tasks untouched. Count, TTL, and
3676
4223
  // transport semantics below are unchanged.
3677
- function reconcilePresence() {
3678
- if (!sessionId) return;
3679
- let snapshot;
3680
- try {
3681
- snapshot = readPresenceSnapshot(sessionId, Date.now());
3682
- } catch {
3683
- return;
3684
- }
4224
+ function reconcilePresence(snapshot) {
3685
4225
  if (!snapshot) return;
3686
4226
  let applied = [];
3687
4227
  try {
@@ -3773,10 +4313,11 @@ export default function (pi) {
3773
4313
  nativePending = null;
3774
4314
  nativeSending = null;
3775
4315
  nativeLastOk = undefined;
3776
- nativeSettledPending = false;
4316
+ clearSettledPending();
3777
4317
  doneExpiry = undefined;
3778
4318
  donePending = false;
3779
4319
  sawActivity = false;
4320
+ turnSettled = false;
3780
4321
  jobsSnapshot = undefined;
3781
4322
  clearJobsExpiry();
3782
4323
  errorCode = undefined;
@@ -3786,9 +4327,13 @@ export default function (pi) {
3786
4327
  liveQueued = false;
3787
4328
  sessionReportPending = null;
3788
4329
  sessionCwd = undefined;
4330
+ settleCtx = undefined;
4331
+ quietBeats = 0;
4332
+ lostSettleBeats = 0;
3789
4333
  changes = { files: 0, added: 0, deleted: 0 };
3790
4334
  agentActive = false;
3791
4335
  settled = false;
4336
+ turnSettled = false;
3792
4337
  }
3793
4338
 
3794
4339
  function clearEmittedLabel() {
@@ -3843,6 +4388,7 @@ export default function (pi) {
3843
4388
 
3844
4389
  pi.on("tool_execution_start", (event) => {
3845
4390
  if (!rootSession || !isRecord(event) || typeof event.toolCallId !== "string") return;
4391
+ noteActivity();
3846
4392
  runningTools.add(event.toolCallId);
3847
4393
  // Structured ask tools open ONLY on genuine execution (never on
3848
4394
  // `tool_call` proposal), keyed by call id so the matching end or
@@ -3951,6 +4497,9 @@ export default function (pi) {
3951
4497
  // role evidence at all — the pending call still covers the blocking/
3952
4498
  // orchestrating marker, but it contributes no role and no name, and it
3953
4499
  // must never publish the launch-correlation placeholder as a role word.
4500
+ // The named `task_id` is retained for the count's dedupe (S11): a resume of
4501
+ // a task the records already list running is the same delegate, and a
4502
+ // cancel of that task ends it.
3954
4503
  function launchInput(input) {
3955
4504
  if (!isRecord(input)) return undefined;
3956
4505
  const taskId = typeof input.task_id === "string" ? input.task_id : undefined;
@@ -3961,13 +4510,18 @@ export default function (pi) {
3961
4510
  const labelSource =
3962
4511
  typeof input.label === "string" && input.label.length > 0 ? input.label : agent;
3963
4512
  const label = labelSource === undefined ? undefined : sanitizeLabel(labelSource, labelSource);
3964
- return { agent: agent === undefined ? undefined : truncateChars(agent, MAX_LABEL_CHARS), label };
4513
+ return {
4514
+ agent: agent === undefined ? undefined : truncateChars(agent, MAX_LABEL_CHARS),
4515
+ label,
4516
+ taskId,
4517
+ };
3965
4518
  }
3966
4519
 
3967
4520
  pi.on("tool_call", (event) => {
3968
4521
  if (!rootSession || !isRecord(event) || typeof event.toolName !== "string") return;
3969
4522
  // A tool starting proves a run is alive: an error left over from a run that
3970
4523
  // already died is released here rather than sticking until the next turn.
4524
+ noteActivity();
3971
4525
  clearRunError();
3972
4526
  // Structured ask proposals never open ask (execution does); subagent
3973
4527
  // launch correlation below is unchanged.
@@ -3987,16 +4541,29 @@ export default function (pi) {
3987
4541
  const taskId = isRecord(event.input) ? event.input.task_id : undefined;
3988
4542
  if (typeof taskId !== "string") return;
3989
4543
  const known = tasks.get(taskId);
4544
+ let changed = false;
4545
+ // A cancelled task's own in-flight launch is no longer an executing
4546
+ // delegate, so it stops counting on this beat (S11: the count
4547
+ // decrements on cancellation). Its pending evidence is NOT dropped: the
4548
+ // pending-call leg still gates the terminal state (S4) and the call's
4549
+ // own result still arrives later.
4550
+ for (const [callId, pending] of pendingCalls) {
4551
+ if (pending.taskId !== taskId || pending.cancelled === true) continue;
4552
+ pendingCalls.set(callId, { ...pending, cancelled: true });
4553
+ changed = true;
4554
+ }
3990
4555
  if (known) {
3991
4556
  // Progress/cancel bumps recency only; firstSeen never moves (T2b).
3992
4557
  tasks.set(taskId, { ...known, status: "cancelled", at: Date.now() });
3993
- schedulePublish();
4558
+ changed = true;
3994
4559
  }
4560
+ if (changed) schedulePublish();
3995
4561
  }
3996
4562
  });
3997
4563
 
3998
4564
  pi.on("tool_result", (event) => {
3999
4565
  if (!rootSession || !isRecord(event) || typeof event.toolName !== "string") return;
4566
+ noteActivity();
4000
4567
  clearRunError();
4001
4568
  if (typeof event.toolCallId === "string" && askToolCalls.delete(event.toolCallId)) {
4002
4569
  updateBlocker();
@@ -4013,7 +4580,11 @@ export default function (pi) {
4013
4580
  // outcome is now covered by the task record (working via activeSubs),
4014
4581
  // the error latch (blocked), or genuine emptiness (idle on next beat).
4015
4582
  if (event.toolName === "subagent_run" || event.toolName === "subagent_continue") {
4016
- nativeSettledPending = false;
4583
+ // A launch resolution retires only its own evidence. When it is the LAST
4584
+ // one the settling turn owed, the hold releases and this edge publishes:
4585
+ // a single result while another launch is still unresolved must keep the
4586
+ // native state non-terminal and announce nothing.
4587
+ if (resolveSettledPending(event.toolCallId)) schedulePublish();
4017
4588
  }
4018
4589
  if (typeof event.toolCallId === "string" ? reviewCalls.delete(event.toolCallId) : false) {
4019
4590
  // The ended id was a known acknowledged execution; remaining tracked
@@ -4123,6 +4694,7 @@ export default function (pi) {
4123
4694
  // never passes through `tool_result` details.
4124
4695
  pi.on("message_end", (event) => {
4125
4696
  if (!rootSession || !isRecord(event)) return;
4697
+ noteActivity();
4126
4698
  const message = event.message;
4127
4699
  if (!isRecord(message)) return;
4128
4700
  if (message.role === "assistant") {
@@ -4185,7 +4757,7 @@ export default function (pi) {
4185
4757
  rootSession = true;
4186
4758
  sessionManager = ctx.sessionManager;
4187
4759
  refreshSessionRef(ctx);
4188
- moshiCtxRef = ctx;
4760
+ retainContext(ctx);
4189
4761
  if (moshiEnabled()) moshiEnsureContext();
4190
4762
  // LIVE-1: bind the session before any state beat so Herdr attributes the
4191
4763
  // pane from the first frame (mirrors the managed publisher). The binding is
@@ -4203,14 +4775,17 @@ export default function (pi) {
4203
4775
  pi.on("agent_start", (_event, ctx) => {
4204
4776
  if (!rootSession) return;
4205
4777
  refreshSessionRef(ctx);
4206
- moshiCtxRef = ctx;
4778
+ retainContext(ctx);
4207
4779
  // LIVE-1: re-bind the session like the managed publisher did, so a
4208
4780
  // restart or re-announcement never leaves the pane binding-less while
4209
4781
  // metadata beats flow.
4210
4782
  void reportSession();
4211
4783
  agentActive = true;
4212
4784
  settled = false;
4213
- nativeSettledPending = false;
4785
+ turnSettled = false;
4786
+ clearSettledPending();
4787
+ quietBeats = 0;
4788
+ noteActivity();
4214
4789
  clearRunError();
4215
4790
  refreshChanges();
4216
4791
  schedulePublish();
@@ -4218,13 +4793,44 @@ export default function (pi) {
4218
4793
 
4219
4794
  pi.on("agent_settled", (_event, ctx) => {
4220
4795
  if (!rootSession || ctx?.isIdle?.() !== true) return;
4221
- moshiCtxRef = ctx;
4222
- agentActive = false;
4223
- settled = true;
4796
+ retainContext(ctx);
4224
4797
  // Retain settle-time pending evidence for native gating before the
4225
- // metadata hint clears (see nativeSettledPending above).
4226
- if (pendingCalls.size > 0) nativeSettledPending = true;
4798
+ // metadata hint clears (see nativeSettledPending above), bounded by the
4799
+ // finish hold this settle opens. A redundant or later settle of the same
4800
+ // episode must never drop an id an earlier settle still owes: evaluate the
4801
+ // live episode before applySettled clears it, then merge.
4802
+ const pendingAtSettle = [...pendingCalls.keys()];
4227
4803
  pendingCalls.clear();
4804
+ const carriedHeld = settledPendingHeld();
4805
+ const carried = carriedHeld ? [...nativeSettledPendingCalls] : [];
4806
+ const carriedUntil = carriedHeld ? nativeSettledPendingUntil : 0;
4807
+ const carriedStart = carriedHeld ? nativeSettledPendingStartedAt : 0;
4808
+ applySettled(true);
4809
+ const union = new Set(carried);
4810
+ let added = false;
4811
+ for (const id of pendingAtSettle) {
4812
+ if (union.has(id)) continue;
4813
+ union.add(id);
4814
+ added = true;
4815
+ }
4816
+ if (union.size > 0) {
4817
+ const next = settleHoldUntil({
4818
+ now: Date.now(),
4819
+ held: carriedHeld,
4820
+ startedAt: carriedStart,
4821
+ until: carriedUntil,
4822
+ added,
4823
+ holdMs: doneHoldMs(),
4824
+ });
4825
+ nativeSettledPending = true;
4826
+ nativeSettledPendingStartedAt = next.startedAt;
4827
+ nativeSettledPendingUntil = next.until;
4828
+ nativeSettledPendingCalls = union;
4829
+ // Nothing else will publish when the last launch resolves or the hold
4830
+ // expires: arm the one beat that lands native `idle` and the single
4831
+ // `done` mint without waiting for an unrelated event.
4832
+ armSettledPendingExpiry(nativeSettledPendingUntil);
4833
+ }
4228
4834
  // S62 turn-end: the working tree may have changed without transcript
4229
4835
  // evidence (external/untracked edits), so re-scan before publishing.
4230
4836
  refreshChanges();