herdr-gentle-shell 1.3.0 → 1.5.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.
@@ -50,6 +50,22 @@
50
50
  // busy. The consumer uses it for the working-vs-idle
51
51
  // decision; the aggregate native status keeps its own
52
52
  // meaning. Never alters the work count or roles CSV.)
53
+ // gentle_pending_v1 = <hash>:<role>:<expiry>
54
+ // (blocking-delegate marker, session-bound + TTL-fresh
55
+ // like gentle_work_v1: the role word of the oldest
56
+ // in-flight `subagent_run`/`subagent_continue` call,
57
+ // republished on every beat while the call blocks, null
58
+ // / clear the beat it settles, the agent settles, or
59
+ // the session resets. A synchronous launch blocks the
60
+ // principal's own turn, so agentActive stays true and
61
+ // the principal marker would paint generic `gentle`
62
+ // while the child runs; this marker is the evidence
63
+ // that the row must show the child's role instead.
64
+ // Background launches resolve their tool call
65
+ // immediately, so they never leave a marker: a running
66
+ // background delegate never changes the principal's
67
+ // own display. Never alters the work count or roles
68
+ // CSV.)
53
69
  // gentle_changes_v2 = <hash>:<files>:<added>:<deleted>:<expiry>
54
70
  // (normative; exact added/deleted totals kept separate)
55
71
  // gentle_changes_v1 = <hash>:<files>:<added+deleted>:<expiry>
@@ -90,6 +106,17 @@
90
106
  // (single effective label, priority error > ask >
91
107
  // review, edge-triggered so the native counter in
92
108
  // herdr-agent-state.ts stays balanced)
109
+ // gentle_error_v1 = <hash>:<code>:<expiry>
110
+ // (durable run-error signal, session-bound + TTL-fresh
111
+ // like gentle_ask_v1: emitted on every beat while the
112
+ // run-error leg stands, null / clear the beat it
113
+ // releases. It is the sidebar's ONLY error carrier —
114
+ // the native pane report never claims `blocked`, so an
115
+ // error raises no host NeedsAttention toast or sound
116
+ // and sends no phone envelope. The consumer reduces a
117
+ // fresh token to `error` (row word `blocked`) with the
118
+ // same error > ask > review priority the label leg
119
+ // uses, independently of work token presence.)
93
120
  //
94
121
  // Event seams (all in-process; this extension imports nothing from
95
122
  // gentle-shell — DESIGN §10 U6 source pin is unresolved, so the producer is
@@ -178,9 +205,17 @@
178
205
  // as user-facing `rdd` (machine key stays `review`).
179
206
  // Fail-safe: no provider verdicts are
180
207
  // invented; the id is a sanitized correlation id only.
181
- // error : subagent task failed status / subagent tool error /
182
- // repeated own-transport failure. Latched until the next
183
- // agent_start (fresh snapshot), TTL-bounded display.
208
+ // error : the agent run itself stopped on an error (an assistant
209
+ // message whose `stopReason` is `error` — the same
210
+ // signal Pi derives `turn_end.outcome === "error"`
211
+ // from). Never a tool-level failure, never a failed
212
+ // delegate record, never our own transport: those are
213
+ // detected and logged, and change no state. Sidebar-only:
214
+ // the pane keeps reporting native `working` while the
215
+ // label stands, so an error never fires the host's
216
+ // NeedsAttention toast or sound. Released by the next
217
+ // non-error beat (agent_start, any tool activity, or a
218
+ // non-error assistant message), never latched.
184
219
  // changes : SESSION_CHANGE_ENTRY facts mirroring the Gentle Shell
185
220
  // SessionChanges model semantics from the session
186
221
  // transcript (write|edit tool outcomes only, never git
@@ -719,6 +754,21 @@ const DONE_HOLD_ENV = "GENTLE_HERDR_DONE_HOLD_MS";
719
754
  // minutes is the generous end of the [30 s, 5 min] band: a job longer than this
720
755
  // fails open early, and a missed exit event delays `done` by at most this long.
721
756
  export const JOBS_SNAPSHOT_TTL_MS = 300000;
757
+ const JOBS_TTL_ENV = "GENTLE_HERDR_JOBS_TTL_MS";
758
+ const JOBS_TTL_MIN_MS = 100;
759
+ const JOBS_TTL_MAX_MS = 3600000;
760
+
761
+ // Same discipline as doneHoldMs: an absent or unparseable value keeps the
762
+ // default and anything outside the band is clamped, so a debugging session (or
763
+ // a test that cannot wait five minutes) can shorten the bound without ever
764
+ // making every snapshot instantly stale.
765
+ export function jobsSnapshotTtlMs(raw = process.env[JOBS_TTL_ENV]) {
766
+ const text = typeof raw === "string" ? raw.trim() : "";
767
+ if (text.length === 0) return JOBS_SNAPSHOT_TTL_MS;
768
+ const parsed = Number(text);
769
+ if (!Number.isFinite(parsed)) return JOBS_SNAPSHOT_TTL_MS;
770
+ return Math.min(JOBS_TTL_MAX_MS, Math.max(JOBS_TTL_MIN_MS, Math.round(parsed)));
771
+ }
722
772
  const MAX_TOKENS_PER_REPORT = 16;
723
773
  const MAX_LABEL_CHARS = 64;
724
774
  // Herdr's wire ceiling for a single pane-metadata token value, measured in
@@ -734,7 +784,6 @@ const MAX_LABEL_CHARS = 64;
734
784
  const MAX_TOKEN_BYTES = 512;
735
785
  const MAX_TRACKED_TASKS = 128;
736
786
  const MAX_CHANGE_PATHS = 256;
737
- const TRANSPORT_FAIL_LATCH = 3;
738
787
  const CLI_FALLBACK_TIMEOUT_MS = 2500;
739
788
 
740
789
  const ASK_EVENT = "gentle-pi:ask-user-choice:blocked";
@@ -793,12 +842,26 @@ const ASK_TOKEN = "gentle_ask_v1";
793
842
  // review is active (acknowledged capture/group execution only). Null /
794
843
  // clear the beat the last execution resolves — NO GRACE, no timers.
795
844
  const REVIEW_TOKEN = "gentle_review_v1";
845
+ // Durable run-error token name (DESIGN §4.3): session-bound + TTL-fresh
846
+ // `<hash>:<code>:<expiry>`, emitted on every beat while the run-error leg
847
+ // stands and cleared to null the beat it releases. This is the sidebar's only
848
+ // error carrier: the native report stays `working` while the leg stands, so an
849
+ // error never raises the host's NeedsAttention toast, its sound, or a phone
850
+ // envelope (DESIGN §7).
851
+ const ERROR_TOKEN = "gentle_error_v1";
796
852
  // Principal-only activity marker (DESIGN §4.3): session-bound + TTL-fresh
797
853
  // `<hash>:<expiry>`, emitted while this session's own agent is active and
798
854
  // cleared when it settles. It carries the principal input of
799
855
  // computeNativeState alone — the aggregate native status answers `working`
800
856
  // for any delegate, so the consumer cannot use it to decide the row.
801
857
  const PRINCIPAL_TOKEN = "gentle_principal_v1";
858
+ // Blocking-delegate marker: session-bound + TTL-fresh `<hash>:<role>:<expiry>`,
859
+ // the role word of the oldest in-flight synchronous
860
+ // `subagent_run`/`subagent_continue` call. It exists because such a call
861
+ // blocks the principal's turn (agentActive stays true) while the child runs,
862
+ // so the principal marker alone renders generic `gentle`. Recognized roles
863
+ // only; null / clear when no blocking call is in flight.
864
+ const PENDING_TOKEN = "gentle_pending_v1";
802
865
 
803
866
  const HASH_RE = /^[A-Za-z0-9_-]{43}$/;
804
867
  const COUNT_RE = /^(0|[1-9]\d{0,15})$/;
@@ -1079,14 +1142,17 @@ function cliFallback(patch) {
1079
1142
  export const NATIVE_STATES = ["working", "blocked", "idle"];
1080
1143
  const NATIVE_MAX_ATTEMPTS = 2;
1081
1144
 
1082
- // Principal-gated native state (pure, testable): blocked on a real
1083
- // principal-stopped error OR an actual human-wait intervention leg
1145
+ // Principal-gated native state (pure, testable): blocked on the `hasError`
1146
+ // input OR an actual human-wait intervention leg
1084
1147
  // (ask/choice/question/questionnaire/permission — never
1085
1148
  // review/RDD execution, which stays working and silent); working while the
1086
1149
  // principal is active OR running/queued delegates exist OR pending launches
1087
1150
  // exist OR review execution holds; idle ONLY on authoritative principal
1088
1151
  // settled plus zero running+queued plus zero pending plus no human-wait
1089
- // prompt and no review execution. Never infer terminal from child
1152
+ // prompt and no review execution. The producer never sets `hasError`: native
1153
+ // `blocked` is what fires the host's NeedsAttention toast and sound, so an
1154
+ // `error:` label stays sidebar-only and the pane reports `working` while it
1155
+ // stands. Never infer terminal from child
1090
1156
  // completion, timeout, or count0 alone (settled required). Never
1091
1157
  // done/finished (only working|blocked|idle) and never a notification
1092
1158
  // method — the host owns finished text plus toast/sound, and desktop ask
@@ -1814,16 +1880,20 @@ function moshiSessionIsChild(file) {
1814
1880
  return child;
1815
1881
  }
1816
1882
 
1817
- let moshiFlagCache = { mtimeMs: -1, enabled: false };
1883
+ let moshiFlagCache = { key: "", enabled: false };
1818
1884
 
1819
1885
  function moshiEnabled() {
1820
1886
  const path = moshiFlagPath();
1821
1887
  try {
1822
1888
  const stat = fs.statSync(path);
1823
- if (stat.mtimeMs === moshiFlagCache.mtimeMs) return moshiFlagCache.enabled;
1824
- moshiFlagCache = { mtimeMs: stat.mtimeMs, enabled: moshiFlagEnabled(path) };
1889
+ // Identity, not just mtime: a rewrite that lands inside the same timestamp
1890
+ // tick (or on a coarse or network filesystem) must still flip the gate. A
1891
+ // stale "enabled" is exactly the notification the user asked not to get.
1892
+ const key = `${stat.mtimeMs}:${stat.size}:${stat.ino}`;
1893
+ if (key === moshiFlagCache.key) return moshiFlagCache.enabled;
1894
+ moshiFlagCache = { key, enabled: moshiFlagEnabled(path) };
1825
1895
  } catch {
1826
- moshiFlagCache = { mtimeMs: -1, enabled: false };
1896
+ moshiFlagCache = { key: "", enabled: false };
1827
1897
  }
1828
1898
  return moshiFlagCache.enabled;
1829
1899
  }
@@ -1932,6 +2002,11 @@ const CUSTOMIZE_OVERLAY_OPTIONS = {
1932
2002
  overlay: true,
1933
2003
  overlayOptions: { anchor: "center", width: "70%", minWidth: 60, maxHeight: "85%" },
1934
2004
  };
2005
+ // The overlay caps its own box at `maxHeight` of the terminal, so the panel's
2006
+ // row budget is that box and never the whole terminal: a card taller than the
2007
+ // box is clipped by the host, and the pointer would then hit-test rows the user
2008
+ // cannot see (the reported "the switch never changes" bug).
2009
+ const CUSTOMIZE_OVERLAY_MAX_HEIGHT = 0.85;
1935
2010
  let customizeTuiLoader = () => import("@earendil-works/pi-tui");
1936
2011
 
1937
2012
  export function setCustomizeTuiLoader(loader) {
@@ -2366,10 +2441,9 @@ async function applyCustomizeSwitch(id, value, ctx) {
2366
2441
  // The single apply path shared by the overlay and the menu fallback. An
2367
2442
  // inconclusive sidebar verdict is never a refusal: choosing On still attempts
2368
2443
  // the repair and reports the apply step's own error, exactly like the baseline
2369
- // menu did. `switchId` names the switch a row drives when it lives under
2370
- // another category — the notifications row inside `Herdr Sidebar` applies the
2371
- // same `moshi` switch as the `Moshi notifications` category, so the one flag
2372
- // file stays the single source of truth.
2444
+ // menu did. `switchId` names the switch a row drives, never the category it is
2445
+ // painted under: each category now owns exactly one switch, so the sidebar rows
2446
+ // can only ever resolve `sidebar` and the notification row only `moshi`.
2373
2447
  async function applyCustomizeChoice(categoryId, valueId, ctx, switchId) {
2374
2448
  const target = switchId === "sidebar" || switchId === "moshi" ? switchId : categoryId;
2375
2449
  if (target !== "sidebar" && target !== "moshi") return;
@@ -2449,7 +2523,10 @@ async function executeCustomize(rawArgs, ctx) {
2449
2523
  theme,
2450
2524
  rowsAvailable: () => {
2451
2525
  try {
2452
- return hostTui && hostTui.terminal ? hostTui.terminal.rows : undefined;
2526
+ const rows = hostTui && hostTui.terminal ? hostTui.terminal.rows : undefined;
2527
+ return Number.isFinite(rows)
2528
+ ? Math.floor(rows * CUSTOMIZE_OVERLAY_MAX_HEIGHT)
2529
+ : undefined;
2453
2530
  } catch {
2454
2531
  return undefined;
2455
2532
  }
@@ -2560,10 +2637,37 @@ export default function (pi) {
2560
2637
  // it is never a display state of its own: no job count is published and no
2561
2638
  // `job` token exists to render (odd/tasks/restore-done-idle.md).
2562
2639
  let jobsSnapshot;
2640
+ // One timer per live snapshot, armed for the instant that snapshot goes
2641
+ // stale. The bus is edge-emitted, so a job whose exit snapshot never arrives
2642
+ // would otherwise leave `freshRunningJobCount()` frozen at its last value
2643
+ // with nothing left to publish the settle that follows: no beat, no `done`,
2644
+ // and the row stays on the pink generic `gentle` for good. One beat at the
2645
+ // expiry is enough — from that instant the hint is zero jobs, so the beat
2646
+ // either mints `done` or reports the real activity that still holds it.
2647
+ // Never a poll: a new snapshot replaces the timer, the session reset and
2648
+ // shutdown drop it, and an empty snapshot drops it immediately.
2649
+ let jobsExpiryTimer;
2650
+
2651
+ function clearJobsExpiry() {
2652
+ if (jobsExpiryTimer === undefined) return;
2653
+ clearTimeout(jobsExpiryTimer);
2654
+ jobsExpiryTimer = undefined;
2655
+ }
2656
+
2657
+ function armJobsExpiry(at) {
2658
+ clearJobsExpiry();
2659
+ const delay = Math.max(0, at + jobsSnapshotTtlMs() - Date.now());
2660
+ jobsExpiryTimer = setTimeout(() => {
2661
+ jobsExpiryTimer = undefined;
2662
+ if (!rootSession) return;
2663
+ schedulePublish();
2664
+ }, delay);
2665
+ if (jobsExpiryTimer.unref) jobsExpiryTimer.unref();
2666
+ }
2563
2667
 
2564
2668
  function freshRunningJobCount() {
2565
2669
  if (!jobsSnapshot) return 0;
2566
- if (Date.now() - jobsSnapshot.at > JOBS_SNAPSHOT_TTL_MS) return 0;
2670
+ if (Date.now() - jobsSnapshot.at > jobsSnapshotTtlMs()) return 0;
2567
2671
  const owner = jobsSnapshot.sessionId;
2568
2672
  const mine = sessionId;
2569
2673
  if (
@@ -2586,11 +2690,23 @@ export default function (pi) {
2586
2690
  const jobs = value.snapshot.jobs.filter(
2587
2691
  (entry) => isRecord(entry) && typeof entry.id === "string" && entry.id.length > 0,
2588
2692
  );
2693
+ // Gentle Shell publishes a FINISHED TAIL: a job that already ended stays in
2694
+ // the array carrying `status: "exited" | "stopped" | "failed"` (its
2695
+ // `RunningJobDisplay`, optional so older publishers that list running jobs
2696
+ // only keep validating). Only an entry with NO status is still running.
2697
+ // Counting a tail entry made `activity` true forever: the row stayed on the
2698
+ // pink generic `gentle` and the `done` mint — hence the finish token, the
2699
+ // host `idle` edge and the Finished toast — never happened, on a panel that
2700
+ // read `none running`. Any status, known or not, therefore stops counting.
2701
+ // `jobs` is only read by freshRunningJobCount, so the filter lives here.
2702
+ const live = jobs.filter((entry) => entry.status === undefined);
2589
2703
  jobsSnapshot = {
2590
2704
  sessionId: typeof value.sessionId === "string" ? value.sessionId : undefined,
2591
- jobs,
2705
+ jobs: live,
2592
2706
  at: Date.now(),
2593
2707
  };
2708
+ if (live.length > 0) armJobsExpiry(jobsSnapshot.at);
2709
+ else clearJobsExpiry();
2594
2710
  schedulePublish();
2595
2711
  }
2596
2712
 
@@ -2619,6 +2735,10 @@ export default function (pi) {
2619
2735
 
2620
2736
  function moshiEmit(eventName, extra = {}) {
2621
2737
  if (!rootSession) return;
2738
+ // THE gate for every envelope path: the opt-in flag is required here, on
2739
+ // every path, with no per-event exception. A context captured while the
2740
+ // channel was on is Chat View prefill only — it never authorizes a send.
2741
+ if (!moshiEnabled()) return;
2622
2742
  if (!moshiContext && !moshiEnsureContext()) return;
2623
2743
  const context = moshiContext;
2624
2744
  if (!context) return;
@@ -2641,6 +2761,15 @@ export default function (pi) {
2641
2761
  moshiSendEnvelope(envelope);
2642
2762
  }
2643
2763
 
2764
+ // The notifications name the project, so they must resolve it the way a send
2765
+ // resolves its context — capturing on demand, which also keeps a channel
2766
+ // enabled mid-session from announcing itself as a bare "Gentle".
2767
+ function moshiNotifyProject() {
2768
+ if (!moshiEnabled()) return "Gentle";
2769
+ moshiEnsureContext();
2770
+ return moshiContext?.project ?? "Gentle";
2771
+ }
2772
+
2644
2773
  // Captures on demand and sends the silent carrier once per session, so
2645
2774
  // enabling Moshi mid-session still opens the Chat View row instead of
2646
2775
  // waiting for the next Pi session.
@@ -2671,8 +2800,14 @@ export default function (pi) {
2671
2800
  function syncReviewActive() {
2672
2801
  reviewActive = reviewCalls.size > 0;
2673
2802
  }
2674
- // Error latch: cleared on the next agent_start (fresh snapshot).
2803
+ // Run-error leg: set ONLY when the agent run itself stops on an error, and
2804
+ // released by the next non-error beat (see setRunError/clearRunError). Tool
2805
+ // failures never touch it, so a failed tool can no longer repaint the row.
2675
2806
  let errorCode;
2807
+ const RUN_ERROR = "run-failed";
2808
+ // Tool-level failures are still detected (the reported defect asked for
2809
+ // detection) but are telemetry: a counter plus a debug line, never state.
2810
+ let toolErrors = 0;
2676
2811
  let emittedLabel;
2677
2812
 
2678
2813
  let changes = { files: 0, added: 0, deleted: 0 };
@@ -2774,6 +2909,26 @@ export default function (pi) {
2774
2909
  return undefined;
2775
2910
  }
2776
2911
 
2912
+ // Detection surface for tool-level failures: recorded, never published. The
2913
+ // state they reach (label, native state, finish hold) is untouched by design
2914
+ // — only a run that stops on an error may show `error:`.
2915
+ function recordToolFailure(site) {
2916
+ toolErrors += 1;
2917
+ debug("tool-error", `${site} count=${toolErrors}`);
2918
+ }
2919
+
2920
+ function setRunError() {
2921
+ if (errorCode) return;
2922
+ errorCode = RUN_ERROR;
2923
+ updateBlocker();
2924
+ }
2925
+
2926
+ function clearRunError() {
2927
+ if (!errorCode) return;
2928
+ errorCode = undefined;
2929
+ updateBlocker();
2930
+ }
2931
+
2777
2932
  function ensureAskIntent() {
2778
2933
  if (askActiveNow() && !askIntentId) {
2779
2934
  askCounter += 1;
@@ -2781,14 +2936,16 @@ export default function (pi) {
2781
2936
  // Moshi replacement (DESIGN §7): a real ask episode is the only
2782
2937
  // intervention that reaches the phone — one approval_required per
2783
2938
  // intentId, exactly like the Herdr toast, and never a speculative ask.
2784
- if (moshiContext || moshiEnabled()) {
2939
+ // `moshiContext` alone never authorizes it: the flag gates every send.
2940
+ if (moshiEnabled()) {
2941
+ const project = moshiNotifyProject();
2785
2942
  moshiEmit("PermissionRequest", {
2786
2943
  category: "approval_required",
2787
2944
  phase: "waitingForApproval",
2788
2945
  actionId: askIntentId,
2789
- title: `Gentle ask: ${moshiContext?.project ?? "Gentle"}`,
2946
+ title: `Gentle ask: ${project}`,
2790
2947
  subtitle: "Answer in terminal",
2791
- message: `${moshiContext?.project ?? "Gentle"} has a question and is waiting for your answer. Return to Pi to respond.`,
2948
+ message: `${project} has a question and is waiting for your answer. Return to Pi to respond.`,
2792
2949
  ...(lastAskToolName ? { toolName: lastAskToolName } : {}),
2793
2950
  });
2794
2951
  }
@@ -2897,6 +3054,16 @@ export default function (pi) {
2897
3054
  return out;
2898
3055
  }
2899
3056
 
3057
+ // Role word of the OLDEST in-flight blocking launch, or undefined when no
3058
+ // recognized role is pending. `pendingRoleSubs` is already oldest-first by
3059
+ // call time, so the first entry is the one the row must show; recognized
3060
+ // filtering there means an unsalvageable agent name yields no role (the
3061
+ // consumer then stays on its own evidence instead of guessing).
3062
+ function pendingRole() {
3063
+ const oldest = pendingRoleSubs()[0];
3064
+ return oldest === undefined ? undefined : agentToRole(oldest.agent);
3065
+ }
3066
+
2900
3067
  // Merged role sources, oldest-first by first-seen: authoritative running
2901
3068
  // TaskStore subs plus pending role hints. Authoritative entries win on
2902
3069
  // duplicates via rolesCsv dedup (first wins = oldest wins).
@@ -3041,6 +3208,16 @@ export default function (pi) {
3041
3208
  if (!reviewActive) reviewId = undefined;
3042
3209
  if (reviewActive && reviewId) tokens[REVIEW_TOKEN] = `${sessionHash}:${reviewId}:${expiry}`;
3043
3210
  else tokens[REVIEW_TOKEN] = null;
3211
+ // Durable run-error signal: session-bound + TTL-fresh
3212
+ // `<hash>:<code>:<expiry>`, republished on every beat while the run-error
3213
+ // leg stands (durable, never edge-only, so a missed beat cannot strand the
3214
+ // row) and cleared to null on the beat the leg releases. It is the only
3215
+ // carrier of the error to the sidebar: the native report stays `working`
3216
+ // while it stands, which is what keeps the host from firing a
3217
+ // NeedsAttention toast or sound for it (DESIGN §7). Tool-level failures
3218
+ // never reach this leg (recordToolFailure is telemetry only).
3219
+ if (errorCode) tokens[ERROR_TOKEN] = `${sessionHash}:${errorCode}:${expiry}`;
3220
+ else tokens[ERROR_TOKEN] = null;
3044
3221
  // Root-only orchestrating marker (DESIGN §4.3): session-bound freshness
3045
3222
  // (<hash>:<expiry>, same binding/TTL style as gentle_work_v1, no count)
3046
3223
  // emitted by the root Pi session while the main session is actively
@@ -3070,6 +3247,17 @@ export default function (pi) {
3070
3247
  // how many delegates keep running.
3071
3248
  if (agentActive) tokens[PRINCIPAL_TOKEN] = `${sessionHash}:${expiry}`;
3072
3249
  else tokens[PRINCIPAL_TOKEN] = null;
3250
+ // Blocking-delegate marker (same binding/TTL discipline): a synchronous
3251
+ // launch keeps the principal's agent active for the whole child run, so
3252
+ // the principal marker above is fresh while the row should instead show
3253
+ // the child's role. This carries that evidence per beat (never
3254
+ // edge-only), so a long child run stays covered by the ordinary beat and
3255
+ // a missed beat cannot strand the row. Cleared to null the beat the call
3256
+ // settles; background launches resolve their tool call immediately and so
3257
+ // never publish it.
3258
+ const pending = pendingRole();
3259
+ if (pending !== undefined) tokens[PENDING_TOKEN] = `${sessionHash}:${pending}:${expiry}`;
3260
+ else tokens[PENDING_TOKEN] = null;
3073
3261
  // Synthesized finish signal (S2/D2): minted once at the settled-and-empty
3074
3262
  // edge — principal settled with no running/queued delegate, no pending
3075
3263
  // launch, no live background job, and no human-wait, review, or error leg
@@ -3148,6 +3336,10 @@ export default function (pi) {
3148
3336
  askToolCalls.size > 0 ||
3149
3337
  uiPromptActive ||
3150
3338
  reviewActive ||
3339
+ // The standing run error keeps a beat alive so its durable token stays
3340
+ // republished (and TTL-fresh) until the leg releases, even after the
3341
+ // session settles.
3342
+ errorCode !== undefined ||
3151
3343
  emittedLabel !== undefined ||
3152
3344
  doneExpiry !== undefined
3153
3345
  );
@@ -3181,15 +3373,22 @@ export default function (pi) {
3181
3373
  // stays consumer-side per DESIGN §7).
3182
3374
  function desiredNativeReport() {
3183
3375
  if (!rootSession) return undefined;
3184
- const state = computeNativeState({
3185
- agentActive,
3186
- settled,
3187
- activeCount: activeSubs().length,
3188
- pendingCount: pendingCalls.size + (nativeSettledPending ? 1 : 0),
3189
- askActive: askActiveNow(),
3190
- reviewActive,
3191
- hasError: !!errorCode,
3192
- });
3376
+ // `error:` is sidebar-only: native `blocked` is exactly what fires the
3377
+ // host's NeedsAttention toast and sound (DESIGN §7), so an error label
3378
+ // never claims it. While the label stands the pane reports `working` —
3379
+ // the only native state that raises no attention — and returns to the
3380
+ // lifecycle state on the next non-error beat. `hasError` stays out of
3381
+ // computeNativeState for this reason.
3382
+ const state = errorCode
3383
+ ? "working"
3384
+ : computeNativeState({
3385
+ agentActive,
3386
+ settled,
3387
+ activeCount: activeSubs().length,
3388
+ pendingCount: pendingCalls.size + (nativeSettledPending ? 1 : 0),
3389
+ askActive: askActiveNow(),
3390
+ reviewActive,
3391
+ });
3193
3392
  if (!state) return undefined;
3194
3393
  if (state === "blocked") {
3195
3394
  ensureAskIntent();
@@ -3306,7 +3505,7 @@ export default function (pi) {
3306
3505
  // live jobs — never off a raw native working->idle transition, which fires
3307
3506
  // with work still left and used to skip `done` entirely.
3308
3507
  function emitFinish() {
3309
- const project = moshiContext?.project ?? "Gentle";
3508
+ const project = moshiNotifyProject();
3310
3509
  const lastLabel = lastFinishedLabel(tasks);
3311
3510
  moshiEmit("AgentEnd", {
3312
3511
  category: "task_complete",
@@ -3408,6 +3607,15 @@ export default function (pi) {
3408
3607
  maybeStopBeat();
3409
3608
  return;
3410
3609
  }
3610
+ // The finish notification is a Moshi envelope, not a Herdr token: it hangs
3611
+ // off the minted done edge above, and announcing it here — before, and
3612
+ // regardless of, the token publish — keeps a transport failure from
3613
+ // swallowing it. Cleared with the announcement, so a retried beat can
3614
+ // never duplicate it.
3615
+ if (donePending) {
3616
+ donePending = false;
3617
+ emitFinish();
3618
+ }
3411
3619
  publishInFlight = true;
3412
3620
  try {
3413
3621
  const ok = await sendTokens(tokens);
@@ -3415,21 +3623,15 @@ export default function (pi) {
3415
3623
  // One coalesced wake per landed beat, after the tokens are in Herdr
3416
3624
  // (a request written first could render a frame over stale tokens).
3417
3625
  requestStatusRefresh();
3418
- if (donePending) {
3419
- donePending = false;
3420
- emitFinish();
3421
- }
3422
- if (transportFails >= TRANSPORT_FAIL_LATCH && errorCode === "transport") {
3423
- errorCode = undefined;
3424
- updateBlocker();
3425
- }
3626
+ if (transportFails > 0) debug("transport-ok", `after ${transportFails} failed beat(s)`);
3426
3627
  transportFails = 0;
3427
3628
  } else {
3629
+ // Our own report transport failing is not the agent failing: it is a
3630
+ // telemetry line, never an `error:` label and never native `blocked`
3631
+ // (that latched a stuck red row on a socket hiccup and fired the
3632
+ // host's toast for it). The next landed beat resets the counter.
3428
3633
  transportFails += 1;
3429
- if (transportFails >= TRANSPORT_FAIL_LATCH && !errorCode) {
3430
- errorCode = "transport";
3431
- updateBlocker();
3432
- }
3634
+ debug("transport-failed", `${transportFails} beat(s) in a row`);
3433
3635
  }
3434
3636
  } finally {
3435
3637
  publishInFlight = false;
@@ -3466,12 +3668,10 @@ export default function (pi) {
3466
3668
  return;
3467
3669
  }
3468
3670
  if (!Array.isArray(applied) || applied.length === 0) return;
3469
- // An explicitly failed delegate latches the error leg exactly like a
3470
- // failed tool_result/message_end; absence-driven completion carries no
3471
- // known terminal state and never latches.
3472
- if (!errorCode && applied.some((entry) => entry && entry.status === "failed")) {
3473
- errorCode = "task-failed";
3474
- updateBlocker();
3671
+ // A delegate that ended failed is a tool-level outcome, not the run
3672
+ // stopping: detected and counted, and no state changes.
3673
+ if (applied.some((entry) => entry && entry.status === "failed")) {
3674
+ recordToolFailure("presence:failed");
3475
3675
  }
3476
3676
  }
3477
3677
 
@@ -3556,7 +3756,9 @@ export default function (pi) {
3556
3756
  donePending = false;
3557
3757
  sawActivity = false;
3558
3758
  jobsSnapshot = undefined;
3759
+ clearJobsExpiry();
3559
3760
  errorCode = undefined;
3761
+ toolErrors = 0;
3560
3762
  liveGen += 1;
3561
3763
  liveInFlight = false;
3562
3764
  liveQueued = false;
@@ -3730,6 +3932,9 @@ export default function (pi) {
3730
3932
 
3731
3933
  pi.on("tool_call", (event) => {
3732
3934
  if (!rootSession || !isRecord(event) || typeof event.toolName !== "string") return;
3935
+ // A tool starting proves a run is alive: an error left over from a run that
3936
+ // already died is released here rather than sticking until the next turn.
3937
+ clearRunError();
3733
3938
  // Structured ask proposals never open ask (execution does); subagent
3734
3939
  // launch correlation below is unchanged.
3735
3940
  if (event.toolName === "subagent_run" || event.toolName === "subagent_continue") {
@@ -3758,12 +3963,18 @@ export default function (pi) {
3758
3963
 
3759
3964
  pi.on("tool_result", (event) => {
3760
3965
  if (!rootSession || !isRecord(event) || typeof event.toolName !== "string") return;
3966
+ clearRunError();
3761
3967
  if (typeof event.toolCallId === "string" && askToolCalls.delete(event.toolCallId)) {
3762
3968
  updateBlocker();
3763
3969
  }
3764
3970
  const pending =
3765
3971
  typeof event.toolCallId === "string" ? pendingCalls.get(event.toolCallId) : undefined;
3766
- if (typeof event.toolCallId === "string") pendingCalls.delete(event.toolCallId);
3972
+ const pendingResolved =
3973
+ typeof event.toolCallId === "string" ? pendingCalls.delete(event.toolCallId) : false;
3974
+ // A resolved launch releases the blocking-delegate marker on THIS beat,
3975
+ // not on the next periodic one: a failed/aborted launch carries no
3976
+ // gentleAgents details, so the record path below never publishes.
3977
+ if (pendingResolved) schedulePublish();
3767
3978
  // A launch resolution retires the settle-time pending guard: the
3768
3979
  // outcome is now covered by the task record (working via activeSubs),
3769
3980
  // the error latch (blocked), or genuine emptiness (idle on next beat).
@@ -3788,10 +3999,9 @@ export default function (pi) {
3788
3999
  }
3789
4000
  const details = isRecord(event.details) ? event.details.gentleAgents : undefined;
3790
4001
  if (!isRecord(details) || typeof details.taskId !== "string") {
3791
- if (event.toolName === "subagent_run" && event.isError === true && !errorCode) {
3792
- errorCode = "task-failed";
3793
- updateBlocker();
3794
- }
4002
+ // A tool that failed is detected and counted, and that is all: no label,
4003
+ // no native state, no finish hold, no notification.
4004
+ if (event.isError === true) recordToolFailure(`tool:${event.toolName}`);
3795
4005
  return;
3796
4006
  }
3797
4007
  const previous = tasks.get(details.taskId);
@@ -3858,10 +4068,7 @@ export default function (pi) {
3858
4068
  const oldest = tasks.keys().next().value;
3859
4069
  tasks.delete(oldest);
3860
4070
  }
3861
- if (status === "failed" && !errorCode) {
3862
- errorCode = "task-failed";
3863
- updateBlocker();
3864
- }
4071
+ if (status === "failed") recordToolFailure(`task:${details.taskId}`);
3865
4072
  schedulePublish();
3866
4073
  });
3867
4074
 
@@ -3880,7 +4087,18 @@ export default function (pi) {
3880
4087
  pi.on("message_end", (event) => {
3881
4088
  if (!rootSession || !isRecord(event)) return;
3882
4089
  const message = event.message;
3883
- if (!isRecord(message) || message.role !== "custom") return;
4090
+ if (!isRecord(message)) return;
4091
+ if (message.role === "assistant") {
4092
+ // The one real error state. Pi derives `turn_end.outcome === "error"`
4093
+ // from exactly this stopReason, so a run that stopped on an error is
4094
+ // visible here without a second handler; any other assistant message
4095
+ // proves the run is alive again (a retry that succeeded) and releases
4096
+ // the label.
4097
+ if (message.stopReason === "error") setRunError();
4098
+ else clearRunError();
4099
+ return;
4100
+ }
4101
+ if (message.role !== "custom") return;
3884
4102
  if (message.customType !== AGENTS_RESULT_TYPE) return;
3885
4103
  const details = isRecord(message.details) ? message.details.gentleAgents : undefined;
3886
4104
  if (!isRecord(details) || typeof details.taskId !== "string") return;
@@ -3908,10 +4126,7 @@ export default function (pi) {
3908
4126
  const oldest = tasks.keys().next().value;
3909
4127
  tasks.delete(oldest);
3910
4128
  }
3911
- if (details.status === "failed" && !errorCode) {
3912
- errorCode = "task-failed";
3913
- updateBlocker();
3914
- }
4129
+ if (details.status === "failed") recordToolFailure(`background:${details.taskId}`);
3915
4130
  schedulePublish();
3916
4131
  });
3917
4132
 
@@ -3956,10 +4171,7 @@ export default function (pi) {
3956
4171
  agentActive = true;
3957
4172
  settled = false;
3958
4173
  nativeSettledPending = false;
3959
- if (errorCode) {
3960
- errorCode = undefined;
3961
- updateBlocker();
3962
- }
4174
+ clearRunError();
3963
4175
  refreshChanges();
3964
4176
  schedulePublish();
3965
4177
  });
@@ -3976,7 +4188,7 @@ export default function (pi) {
3976
4188
  // S62 turn-end: the working tree may have changed without transcript
3977
4189
  // evidence (external/untracked edits), so re-scan before publishing.
3978
4190
  refreshChanges();
3979
- if (activeSubs().length === 0 && !askActiveNow() && !reviewActive) {
4191
+ if (activeSubs().length === 0 && !askActiveNow() && !reviewActive && !errorCode) {
3980
4192
  clearEmittedLabel();
3981
4193
  void publishNow();
3982
4194
  } else {