herdr-gentle-shell 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/DESIGN.md CHANGED
@@ -275,7 +275,7 @@ active (`agentActive`) and clears it (null) the moment the principal
275
275
  settles, keeping the same binding/TTL discipline. This is the principal-only
276
276
  signal: it carries exactly the principal input of `computeNativeState`, never
277
277
  the delegate aggregate, because the native status answers `working` for a
278
- running delegate, a pending launch, or a live job — none of which say the
278
+ running delegate or a pending launch — neither of which says the
279
279
  principal itself works. The native status keeps that aggregate meaning for
280
280
  Herdr's own pane state; the row's working-vs-idle decision reads only
281
281
  `gentle_principal_v1` (§5.2). It carries no count and alters neither the work
@@ -309,8 +309,9 @@ gentle_roles_v1 = role *("," role) ; total <= 512 UTF-8 bytes; null (cle
309
309
  gentle_orchestrating_v1 = sessionHash ":" expiry
310
310
  ; root-only presence marker, no count — fresh while the
311
311
  ; root main session actively works (even with zero subs),
312
- ; retaining running/queued-sub or pending-launch coverage;
313
- ; null (clear) once the main session settles
312
+ ; retaining running/queued-sub, pending-launch, or live
313
+ ; background-job coverage; null (clear) once the main
314
+ ; session settles
314
315
  gentle_principal_v1 = sessionHash ":" expiry
315
316
  ; principal-only activity marker, no count — fresh while
316
317
  ; the principal session's own agent is active
@@ -318,7 +319,20 @@ gentle_principal_v1 = sessionHash ":" expiry
318
319
  ; never its delegate aggregate), null (clear) once the
319
320
  ; principal settles; decides working vs idle in §5.2
320
321
  ; while the native status keeps its aggregate meaning
321
- ; (running delegate / pending launch / live job = working)
322
+ ; (running delegate / pending launch = working)
323
+ gentle_done_v1 = sessionHash ":" expiry
324
+ ; synthesized finish signal, no count — minted ONCE at the
325
+ ; settled-and-empty edge (principal settled, zero
326
+ ; running/queued delegates, zero pending launches, zero
327
+ ; live background jobs, no ask/review/error leg), then
328
+ ; republished with the SAME expiry (never refreshed) until
329
+ ; it lapses; null (clear) whenever work reappears or the
330
+ ; session resets. Its expiry IS the done hold: default
331
+ ; 60 s, overridden by GENTLE_HERDR_DONE_HOLD_MS clamped to
332
+ ; [1000, 300000], and the consumer accepts no expiry beyond
333
+ ; now+300000 at read (the only token whose ceiling is not
334
+ ; the 60 s TTL). A session that never worked never mints
335
+ ; one.
322
336
  gentle_ask_v1 = sessionHash ":" intentId ":" expiry
323
337
  ; durable ask signal, session-bound + TTL-fresh like
324
338
  ; gentle_orchestrating_v1 — emitted on every beat while
@@ -343,7 +357,9 @@ left it.
343
357
 
344
358
  Validation: consumers MUST reject tokens failing the grammar (wrong hash
345
359
  length, `expiry` in the past or `> now+60000` at read, non-numeric counts)
346
- and treat the pane as `unknown → idle` for that signal (§7).
360
+ and treat the pane as `unknown → idle` for that signal (§7). `gentle_done_v1`
361
+ is the one ceiling exception: it is validated against `now+300000` so an
362
+ overridden hold stays readable, and it still fails closed on a past expiry.
347
363
 
348
364
  ### 4.4 Examples
349
365
 
@@ -422,6 +438,8 @@ carry it as a suffix only when above one), `gentle_orchestrating_v1` (root-only
422
438
  + freshness gate for the `orchestrating` display — never rendered as a
423
439
  count), `gentle_principal_v1` (principal-only activity marker + freshness
424
440
  gate for the working-vs-idle decision — never rendered as a count),
441
+ `gentle_done_v1` (synthesized finish signal + its own hold freshness gate
442
+ for the reachable `done` display — the host never reports `done`, §4.3),
425
443
  `gentle_roles_v1` (authoritative activity roles,
426
444
  oldest-first by immutable firstSeen), `gentle_names_v1` (compat transport only — never
427
445
  rendered), `gentle_changes_v2` (normative; a
@@ -440,7 +458,7 @@ review := herdr:blocked has review:* (fresh)
440
458
  principalWorking := fresh gentle_principal_v1 (session-bound, TTL-fresh) —
441
459
  the principal's OWN activity, never the delegate count and
442
460
  never the aggregate native status (which reads working for
443
- any running delegate, pending launch, or live job); renders
461
+ any running delegate or pending launch); renders
444
462
  `orchestrating` while a fresh gentle_orchestrating_v1 is
445
463
  live, otherwise working(main); outranks every delegate role
446
464
  word; stale, foreign, or absent falls through to the
@@ -453,22 +471,30 @@ role := gentle_work_v1 fresh AND gentle_roles_v1 yields a
453
471
  least two delegates run. Tool-only review has no suffix.
454
472
  orchestrating := gentle_orchestrating_v1 fresh with no role word above
455
473
  (root-only per §4.2: fresh while the main session actively
456
- works, even with zero subagents, retaining running/queued-sub
457
- or pending-launch coverage; absent/stale falls through to the
474
+ works, even with zero subagents, retaining running/queued-sub,
475
+ pending-launch, or live background-job coverage; absent/stale
476
+ falls through to the
458
477
  branches below; attention, terminal `done`/native-`blocked`,
459
478
  a working principal, and role words stay higher)
460
479
  working(main) := gentle_work_v1 fresh AND count > 0 with no role word
461
480
  OR (gentle_work_v1 fresh AND count = 0 AND agent not settled)
462
- done := native done AND gentle_work_v1 fresh with count = 0
463
- (no running delegates) AND no roles AND no fresh
464
- gentle_orchestrating_v1 — count 0 alone never implies
465
- empty, since the running-only count excludes queued subs
466
- the fresh marker still covers; a fresh marker or any roles
467
- veto terminal (queued cover, pending-launch hint)
481
+ done := (native done OR fresh gentle_done_v1) AND gentle_work_v1
482
+ fresh with count = 0 (no running delegates) AND no roles AND
483
+ no fresh gentle_orchestrating_v1 AND no fresh
484
+ gentle_principal_v1 — count 0 alone never implies empty,
485
+ since the running-only count excludes queued subs the fresh
486
+ marker still covers; a fresh marker, any roles, or a working
487
+ principal veto terminal (queued cover, pending-launch hint).
488
+ The producer's finish token is the reachable path (the host
489
+ never emits done); its expiry is the hold, so `done` recedes
490
+ to `idle` when it lapses and is never skipped in between
468
491
  idle := otherwise (native fallback; also all-gentle-tokens-missing-or-expired)
469
492
  ```
470
493
 
471
494
  Priority: `error > ask > review > done > principal working > role > orchestrating > working(main) > idle`.
495
+ `done` is matched before the principal/role branches in the reducer; it is
496
+ listed here below the activity branches only so its settled-and-empty
497
+ precondition reads together.
472
498
  `blocked` labels are namespaced, so simultaneous
473
499
  `ask:` + `review:` resolves deterministically to `ask`. Attention states
474
500
  (error/ask/review) and the terminal `done` state always outrank principal
@@ -483,7 +509,8 @@ signal (it stays live while the principal is idle with queued or running
483
509
  delegates), so it never outranks a role word. An in-flight attention `review`
484
510
  (fresh `review:` label or durable `gentle_review_v1` token) overrides the
485
511
  role list; a settled session renders `done` even against a stale-fresh
486
- marker.
512
+ marker, and only after the minted finish hold lapses does it recede to
513
+ `idle` (§4.3).
487
514
 
488
515
  ### 5.3 Publication (sidebar tokens)
489
516
 
@@ -631,9 +658,11 @@ other two). All gentle signals stale/missing → `idle` (native fallback, O5).
631
658
  `intentId`, subtitle `Answer in terminal`, title `Gentle ask: <project>`,
632
659
  message `<project> has a question and is waiting for your answer. Return
633
660
  to Pi to respond.`) and
634
- `task_complete` once per real finish (the native transition into `idle`:
635
- settled plus zero running/queued plus zero pending plus zero live
636
- background jobs plus no human wait),
661
+ `task_complete` once per real finish (the synthesized `done` edge: the beat
662
+ that delivers a fresh minted `gentle_done_v1` — settled plus zero
663
+ running/queued plus zero pending plus zero live background jobs plus no
664
+ human wait — never a raw native `working → idle` transition, which fires
665
+ with work still left and skipped `done` entirely),
637
666
  never per prompt and never per turn. A `session.closed` (`session_ended`)
638
667
  envelope closes the row on shutdown, and the host-awaited handler flushes
639
668
  in-flight sends. `task_complete` carries title `Gentle finished: <project>`
@@ -673,7 +702,7 @@ report after a Pi restart or `/new` (both recreate the extension runtime)
673
702
  lose, freezing the pane's `agent_session` binding at the old session while
674
703
  the producer keeps beating for the new one — the consumer then rejects those
675
704
  fresh tokens as a session-hash mismatch and the pane stays on `idle` until a
676
- report with a higher seq lands. Parity contract: `working` carries the specific working role in the message (oldest running role word from the same roles resolution — known short word, unknown sanitized name, or `gentle` with no delegation; never bare generic `working`; machine keys unchanged); terminal `idle` only on a truly empty settle (principal settled plus zero running/queued plus zero pending plus zero live background jobs plus no human-wait prompt; settle-with-delegates/pending/jobs stays `working`, emitted once with no re-emit on repeat settles). Live background jobs come from Gentle Shell's own bus event `gentle-ai:jobs-sidebar` (`bash_background` / `monitor`), session-scoped; an absent Gentle Shell simply reports none (today's behavior). `blocked` only for a real principal-stopped error or an actual human-wait intervention leg with its label (review/RDD execution stays `working`, silent). The native status keeps its aggregate meaning (it reads `working` while any delegate runs, which is what Herdr's own pane state means): the sidebar row's working-vs-idle decision reads the principal-only `gentle_principal_v1` instead (§5.2), so an idle principal with a running delegate shows the delegate role word rather than `gentle`. Single publisher by design: the managed native extension file is excluded
705
+ report with a higher seq lands. Parity contract: `working` carries the specific working role in the message (oldest running role word from the same roles resolution — known short word, unknown sanitized name, or `gentle` with no delegation; never bare generic `working`; machine keys unchanged); terminal `idle` only on a truly empty settle (principal settled plus zero running/queued plus zero pending plus zero live background jobs plus no human-wait prompt; settle-with-delegates/pending/jobs stays `working`, emitted once with no re-emit on repeat settles). Live background jobs come from Gentle Shell's own bus event `gentle-ai:jobs-sidebar` (`bash_background` / `monitor`), session-scoped and emitted on job edges only, so a snapshot counts only while it is fresh — a stale or foreign snapshot is zero jobs; an absent Gentle Shell simply reports none (today's behavior). While such a job waits with the principal settled and no delegate running or launching, the producer keeps the root marker live so the row stays on the pink generic `gentle` (§5.2) and the finish is held back; the wait ends on the beat the principal resumes, a delegate starts, the last job ends, or the snapshot ages past its staleness bound. `blocked` only for a real principal-stopped error or an actual human-wait intervention leg with its label (review/RDD execution stays `working`, silent). The native status keeps its aggregate meaning (it reads `working` while any delegate runs, which is what Herdr's own pane state means): the sidebar row's working-vs-idle decision reads the principal-only `gentle_principal_v1` instead (§5.2), so an idle principal with a running delegate shows the delegate role word rather than `gentle`. Single publisher by design: the managed native extension file is excluded
677
706
  reversibly (`-extensions/herdr-agent-state.ts` in Pi settings, bytes
678
707
  preserved on disk, never auto-loaded next to ours). `node
679
708
  bin/gentle-sidebar.js (enable|disable|status|toggle)` selects the
@@ -711,13 +740,25 @@ nothing:
711
740
 
712
741
  `/herdr-gentle:customize status` prints one read-only line; an unknown
713
742
  argument, Esc, or a cancelled menu writes nothing. With no argument the
714
- command opens the recovered floating two-pane panel
715
- (`lib/customize-panel.js`, painted through its own palette)
716
- over `ctx.ui.custom`: `←/→` or `Tab` moves between the category and value panes,
717
- `↑/↓` or `j/k` moves the cursor, `Enter` toggles the focused switch and `Esc`
718
- closes without a write. Each switch renders exactly one row that reads its
719
- stored state and carries the opposite value, so `Enter` is the whole toggle.
720
- An inconclusive sidebar verdict (`unknown`) renders as `Unknown` with a note
743
+ command opens the floating panel (`lib/customize-panel.js`, painted through its
744
+ own palette) over `ctx.ui.custom` in Gentle Shell's own layout: one left
745
+ `CATEGORIES` list, one right pane headed `<Category> · n/m` with its setting
746
+ rows, each row painting the stored value with `●` and the other with `○`, and
747
+ the footer
748
+ `Click · ←/→ or Tab panes · ↑/↓ move · Enter apply · Esc close`. There is no
749
+ `Preview · …` band and no `p profiles` key: this plugin owns no profiles
750
+ concept, so the footer advertises nothing it cannot do. `←/→` or `Tab` moves
751
+ between the category and value panes, `↑/↓` or `j/k` moves the cursor, `Enter`
752
+ applies the focused row and `Esc` closes without a write; a click on a category
753
+ selects it, a click on a row applies it, and a click outside the panes is
754
+ ignored (a press only captures the gesture, so a drag never applies a row).
755
+ Each switch is one row that paints the stored state and carries the opposite
756
+ value. The notifications switch appears under both `Herdr Sidebar` (as
757
+ `Notifications`, where the plugin's own switches are looked for) and its own
758
+ `Moshi notifications` category: a row names the switch it drives, so both
759
+ apply the one `gentle-moshi.json` flag through `applyMoshiNotifications` and
760
+ whosever change it was is what both rows read on the next render.
761
+ An inconclusive sidebar verdict (`unknown`) renders as `● Unknown` with a note
721
762
  instead of hiding the row: toggling still attempts the repair and reports the
722
763
  apply step's own error, exactly like the menu. The plain
723
764
  two-step `ctx.ui.select` menu remains the
@@ -730,9 +771,10 @@ exactly one mechanism writes each piece of state.
730
771
  ## 8. Limits
731
772
 
732
773
  - Token budget: ≤ 16 tokens per report per pane (E8 discipline); the
733
- producer emits at most 10 tokens per beat (including the retired-token clear) (`gentle_work_v1`,
774
+ producer emits at most 11 tokens per beat (including the retired
775
+ `gentle_subs_v1` clear) (`gentle_work_v1`,
734
776
  `gentle_roles_v1`, `gentle_names_v1`,
735
- `gentle_orchestrating_v1`, `gentle_principal_v1`,
777
+ `gentle_orchestrating_v1`, `gentle_principal_v1`, `gentle_done_v1`,
736
778
  `gentle_ask_v1`, `gentle_review_v1`, `gentle_changes_v2`,
737
779
  `gentle_changes_v1`) and the daemon publishes its 72-token owned family
738
780
  chunked ≤ 16 per report (row 1 is the 3 native tokens
@@ -766,7 +808,7 @@ exactly one mechanism writes each piece of state.
766
808
 
767
809
  - Additive only in v1: new token names (`gentle_work_v1`,
768
810
  `gentle_roles_v1`, `gentle_names_v1`,
769
- `gentle_orchestrating_v1`, `gentle_principal_v1`,
811
+ `gentle_orchestrating_v1`, `gentle_principal_v1`, `gentle_done_v1`,
770
812
  `gentle_ask_v1`, `gentle_review_v1`, `gentle_changes_v1`, `gentle_changes_v2`,
771
813
  `gentle_state_*`, `gentle_title_*`, `gentle_agent_*`, `gentle_agent`,
772
814
  `gentle_icon_*`,
package/README.md CHANGED
@@ -241,8 +241,8 @@ renders for generic activity (machine key `working`): the main agent when settle
241
241
  retaining running-subagent or pending-launch coverage. The principal's own
242
242
  activity decides the row, never the delegate count and never Herdr's
243
243
  aggregate native status (the work token counts running delegates, and the
244
- native status reads `working` for any running delegate, pending launch, or
245
- live job — so neither can say the principal works): the dedicated
244
+ native status reads `working` for any running delegate or pending launch — so
245
+ neither can say the principal works): the dedicated
246
246
  `gentle_principal_v1` marker is published while the principal session itself
247
247
  works and cleared when it settles. A **working principal** reads `gentle` —
248
248
  pink
@@ -361,13 +361,20 @@ See [DESIGN.md](DESIGN.md) §4 (producer) and §5 (consumer), and
361
361
  managed Herdr rows and records the owned native-extension exclusion;
362
362
  `disable` removes only our owned rows and exclusion, never a user table.
363
363
  See [docs/sidebar-control.md](docs/sidebar-control.md).
364
- - In-Pi switches (`/herdr-gentle:customize`): exactly two toggles, both local
364
+ - In-Pi switches (`/herdr-gentle:customize`): two switches, both local
365
365
  state and both reachable from a plain Pi session outside a Herdr pane. With
366
- no argument the command opens the restored floating two-pane panel
367
- (`Herdr Sidebar` and `Moshi notifications`; `←/→` or `Tab` moves between the
368
- category and value panes, `↑/↓` or `j/k` moves the cursor, `Enter` toggles the
369
- focused switch and `Esc` closes). Each switch is one row that reads its stored
370
- state, so `On` becomes `Off` and back in a single key press. The plain two-step menu stays as the fallback
366
+ no argument the command opens the floating panel in Gentle Shell's own
367
+ layout: one left `CATEGORIES` list (`Herdr Sidebar`, `Moshi notifications`)
368
+ and one right pane headed `<Category> · n/m` with its setting rows, each row
369
+ painting the stored value with `●` and the other with `○`; the footer reads
370
+ `Click · ←/→ or Tab panes · ↑/↓ move · Enter apply · Esc close`, and `←/→` or
371
+ `Tab` moves between the category and value panes, `↑/↓` or `j/k` moves the
372
+ cursor while `Esc` closes. A click on a category selects it and a click on a
373
+ row applies it, exactly like `Enter` on the focused row; clicks outside the
374
+ panes are ignored. The notifications switch appears twice — as its own
375
+ `Moshi notifications` category and as a `Notifications` row inside
376
+ `Herdr Sidebar` — and both rows read the one flag below, so the state they
377
+ show can never disagree. The plain two-step menu stays as the fallback
371
378
  when the TUI helpers or `ctx.ui.custom` are unavailable.
372
379
  `Sidebar agent rows` drives the Herdr plugin's own `bin/configure.js`
373
380
  (`--check` to read, `--apply --reload` / `--uninstall --reload` to change) and
@@ -392,10 +399,11 @@ See [DESIGN.md](DESIGN.md) §4 (producer) and §5 (consumer), and
392
399
  mkdir -p "$dir" && echo '{"enabled":true}' > "$dir/gentle-moshi.json"
393
400
  ```
394
401
 
395
- `/herdr-gentle:customize` → `Moshi notifications` writes this flag for you,
396
- and enabling there first requires the `moshi-hook` CLI on `PATH` with
397
- `moshi-hook status --json` reporting `paired: true` (an unpaired host is
398
- refused and nothing is written).
402
+ `/herdr-gentle:customize` → `Moshi notifications` (or the `Notifications` row
403
+ inside `Herdr Sidebar`) writes this flag for you, and enabling there first
404
+ requires the `moshi-hook` CLI on `PATH` with `moshi-hook status --json`
405
+ reporting `paired: true` (an unpaired host is refused and nothing is
406
+ written).
399
407
 
400
408
  With the flag on, this plugin **replaces the
401
409
  Moshi-managed Pi hook**: the same Moshi integration (Chat View, Live Activity,
@@ -693,6 +693,30 @@ const paneId = process.env.HERDR_PANE_ID;
693
693
 
694
694
  const TTL_MS = 60000;
695
695
  const BEAT_MS = 15000;
696
+ // Synthesized finish signal (DESIGN §4.3, S2/D2). The host never reports
697
+ // `done`, so the producer mints the finish itself: one session-bound
698
+ // `<hash>:<expiry>` token per finish at the settled-and-empty edge, carrying
699
+ // the hold as its absolute expiry. The sidebar reads it as `done` while it is
700
+ // fresh and recedes to `idle` once it expires — the delay IS that expiry, so
701
+ // no timer and no extra idle hold exists. The hold defaults to 60 s and is
702
+ // overridden through GENTLE_HERDR_DONE_HOLD_MS, clamped to [1 s, 5 min]; the
703
+ // consumer rejects any expiry beyond the same ceiling.
704
+ const DONE_TOKEN = "gentle_done_v1";
705
+ const DONE_HOLD_MS = 60000;
706
+ const DONE_HOLD_MIN_MS = 1000;
707
+ export const DONE_HOLD_MAX_MS = 300000;
708
+ const DONE_HOLD_ENV = "GENTLE_HERDR_DONE_HOLD_MS";
709
+ // Staleness bound for the background-job snapshot. Gentle Shell emits
710
+ // `gentle-ai:jobs-sidebar` on job EDGES only — start, monitor line batch, stop,
711
+ // exit, session shutdown (`refreshJobStatus` in extensions/gentle-agents.ts has
712
+ // no periodic caller) — so a silent `bash_background` job never refreshes it. A
713
+ // snapshot older than this bound therefore counts as ZERO jobs: fail OPEN.
714
+ // Finishing while a job silently runs is a nuisance; latching the session
715
+ // non-terminal on a snapshot that no longer describes the session is the
716
+ // incident this bound exists to prevent (odd/tasks/restore-done-idle.md). Five
717
+ // minutes is the generous end of the [30 s, 5 min] band: a job longer than this
718
+ // fails open early, and a missed exit event delays `done` by at most this long.
719
+ export const JOBS_SNAPSHOT_TTL_MS = 300000;
696
720
  const MAX_TOKENS_PER_REPORT = 16;
697
721
  const MAX_LABEL_CHARS = 64;
698
722
  // Herdr's wire ceiling for a single pane-metadata token value, measured in
@@ -717,9 +741,7 @@ const QUESTIONNAIRE_EVENT = "rpiv:ask-user:blocked";
717
741
  const PERMISSION_EVENT = "pi-permission-system:permission-request";
718
742
  // Gentle Shell's live background jobs (`bash_background` / `monitor`) are
719
743
  // published on the Pi event bus, session-scoped and display-only:
720
- // `{ sessionId, snapshot: { jobs: [{ id, label, startedAt }] } }`. A live job
721
- // is pending work exactly like a running delegate, so it must keep the
722
- // session non-terminal.
744
+ // `{ sessionId, snapshot: { jobs: [{ id, label, startedAt }] } }`.
723
745
  const JOBS_SIDEBAR_EVENT = "gentle-ai:jobs-sidebar";
724
746
  // Neither `gentle-pi:review:blocked` (reserved hook: no producer exists) nor
725
747
  // `gentle-ai:review-sidebar` snapshots (entry publishes fire before the
@@ -830,6 +852,17 @@ function utf8Bytes(value) {
830
852
  return Buffer.byteLength(value, "utf8");
831
853
  }
832
854
 
855
+ // Finish-hold override: an absent or unparseable value keeps the 60 s
856
+ // default, and anything outside the ceiling is clamped, so the producer can
857
+ // never publish an expiry the consumer reads as foreign.
858
+ export function doneHoldMs(raw = process.env[DONE_HOLD_ENV]) {
859
+ const text = typeof raw === "string" ? raw.trim() : "";
860
+ if (text.length === 0) return DONE_HOLD_MS;
861
+ const parsed = Number(text);
862
+ if (!Number.isFinite(parsed)) return DONE_HOLD_MS;
863
+ return Math.min(DONE_HOLD_MAX_MS, Math.max(DONE_HOLD_MIN_MS, Math.round(parsed)));
864
+ }
865
+
833
866
  // Cap a label at MAX_LABEL_CHARS UTF-16 units — the same unit the consumer's
834
867
  // `parseNames` checks, so a label the producer writes is never one the
835
868
  // consumer drops — while backing off one unit when the cut would split a
@@ -907,7 +940,7 @@ function sendRequestAttempt(request, timeoutMs) {
907
940
  if (timeout) clearTimeout(timeout);
908
941
  try {
909
942
  socket.destroy();
910
- } catch {}
943
+ } catch { /* best effort: a failure here is non-fatal */ }
911
944
  resolve(delivered);
912
945
  };
913
946
  let socket;
@@ -1011,7 +1044,7 @@ function cliFallback(patch) {
1011
1044
  const timer = setTimeout(() => {
1012
1045
  try {
1013
1046
  child.kill();
1014
- } catch {}
1047
+ } catch { /* best effort: a failure here is non-fatal */ }
1015
1048
  finish(false);
1016
1049
  }, CLI_FALLBACK_TIMEOUT_MS);
1017
1050
  if (timer.unref) timer.unref();
@@ -1061,25 +1094,16 @@ export function computeNativeState({
1061
1094
  settled,
1062
1095
  activeCount,
1063
1096
  pendingCount,
1064
- jobCount = 0,
1065
1097
  askActive,
1066
1098
  reviewActive,
1067
1099
  hasError,
1068
1100
  }) {
1069
1101
  if (hasError) return "blocked";
1070
1102
  if (askActive) return "blocked";
1071
- if (agentActive || activeCount > 0 || pendingCount > 0 || jobCount > 0 || reviewActive) {
1103
+ if (agentActive || activeCount > 0 || pendingCount > 0 || reviewActive) {
1072
1104
  return "working";
1073
1105
  }
1074
- if (
1075
- settled &&
1076
- !agentActive &&
1077
- activeCount === 0 &&
1078
- pendingCount === 0 &&
1079
- jobCount === 0 &&
1080
- !askActive &&
1081
- !reviewActive
1082
- ) {
1106
+ if (settled && !agentActive && activeCount === 0 && pendingCount === 0 && !askActive && !reviewActive) {
1083
1107
  return "idle";
1084
1108
  }
1085
1109
  return undefined;
@@ -1388,7 +1412,7 @@ function liveRunGit(root, args) {
1388
1412
  }
1389
1413
  let stdout = "";
1390
1414
  const timer = setTimeout(() => {
1391
- try { child.kill(); } catch {}
1415
+ try { child.kill(); } catch { /* best effort: a failure here is non-fatal */ }
1392
1416
  finish({ stdout, code: 1, error: `timed out after ${LIVE_GIT_TIMEOUT_MS}ms` });
1393
1417
  }, LIVE_GIT_TIMEOUT_MS + 500);
1394
1418
  if (timer.unref) timer.unref();
@@ -1643,7 +1667,7 @@ function moshiSendEnvelope(envelope) {
1643
1667
  sock.on("error", () => {
1644
1668
  try {
1645
1669
  sock.destroy();
1646
- } catch {}
1670
+ } catch { /* best effort: a failure here is non-fatal */ }
1647
1671
  });
1648
1672
  sock.once("connect", () => {
1649
1673
  sock.write(`${JSON.stringify(envelope)}\n`);
@@ -1758,7 +1782,7 @@ function moshiSessionIsChild(file) {
1758
1782
  } finally {
1759
1783
  try {
1760
1784
  fs.closeSync(fd);
1761
- } catch {}
1785
+ } catch { /* best effort: a failure here is non-fatal */ }
1762
1786
  }
1763
1787
  moshiChildCache.set(file, child);
1764
1788
  return child;
@@ -1836,8 +1860,9 @@ function lastFinishedLabel(taskMap) {
1836
1860
  }
1837
1861
 
1838
1862
  // ---------------------------------------------------------------------------
1839
- // `/herdr-gentle:customize`: exactly two switches, offered in the former
1840
- // floating two-pane panel (odd/tasks/restore-customize-panel.md T1).
1863
+ // `/herdr-gentle:customize`: exactly two switches, offered in the floating panel
1864
+ // shaped like Gentle Shell's own card (odd/tasks/restore-customize-panel.md T1;
1865
+ // odd/tasks/customize-parity-done-idle.md T1/T3).
1841
1866
  //
1842
1867
  // The command is registered BEFORE the `enabled()` gate in the factory below,
1843
1868
  // so it stays reachable from a plain Pi session outside a Herdr pane; the
@@ -2118,7 +2143,7 @@ function writeSettingsDoc(path, doc) {
2118
2143
  } catch (error) {
2119
2144
  try {
2120
2145
  fs.rmSync(temp, { force: true });
2121
- } catch {}
2146
+ } catch { /* best effort: a failure here is non-fatal */ }
2122
2147
  throw error;
2123
2148
  }
2124
2149
  }
@@ -2315,11 +2340,15 @@ async function applyCustomizeSwitch(id, value, ctx) {
2315
2340
  // The single apply path shared by the overlay and the menu fallback. An
2316
2341
  // inconclusive sidebar verdict is never a refusal: choosing On still attempts
2317
2342
  // the repair and reports the apply step's own error, exactly like the baseline
2318
- // menu did.
2319
- async function applyCustomizeChoice(categoryId, valueId, ctx) {
2320
- if (categoryId !== "sidebar" && categoryId !== "moshi") return;
2343
+ // menu did. `switchId` names the switch a row drives when it lives under
2344
+ // another category — the notifications row inside `Herdr Sidebar` applies the
2345
+ // same `moshi` switch as the `Moshi notifications` category, so the one flag
2346
+ // file stays the single source of truth.
2347
+ async function applyCustomizeChoice(categoryId, valueId, ctx, switchId) {
2348
+ const target = switchId === "sidebar" || switchId === "moshi" ? switchId : categoryId;
2349
+ if (target !== "sidebar" && target !== "moshi") return;
2321
2350
  if (valueId !== "on" && valueId !== "off") return;
2322
- await applyCustomizeSwitch(categoryId, valueId, ctx);
2351
+ await applyCustomizeSwitch(target, valueId, ctx);
2323
2352
  }
2324
2353
 
2325
2354
  // The former plain menu, kept as the fallback when the TUI helpers or
@@ -2416,7 +2445,7 @@ async function executeCustomize(rawArgs, ctx) {
2416
2445
  // Esc (null) does nothing at all: no notification, no write, no reload.
2417
2446
  // Anything else runs the single apply path once the overlay is disposed.
2418
2447
  if (!choice || typeof choice !== "object") return;
2419
- await applyCustomizeChoice(choice.categoryId, choice.valueId, ctx);
2448
+ await applyCustomizeChoice(choice.categoryId, choice.valueId, ctx, choice.switchId);
2420
2449
  return;
2421
2450
  }
2422
2451
  await runCustomizeFallback(ctx);
@@ -2498,13 +2527,17 @@ export default function (pi) {
2498
2527
  let moshiCtxRef;
2499
2528
  let lastAskToolName;
2500
2529
 
2501
- // Live background jobs (Gentle Shell `bash_background` / `monitor`), from
2502
- // the bus snapshot. Session-scoped: a snapshot owned by another session
2503
- // never counts here.
2530
+ // Live background jobs (Gentle Shell `bash_background` / `monitor`) from the
2531
+ // bus snapshot: session-scoped, edge-emitted, and therefore a hint with a
2532
+ // freshness bound rather than proof. A live job is PENDING WORK — it holds
2533
+ // the finish mint and keeps the row on the pink generic `gentle` wait — but
2534
+ // it is never a display state of its own: no job count is published and no
2535
+ // `job` token exists to render (odd/tasks/restore-done-idle.md).
2504
2536
  let jobsSnapshot;
2505
2537
 
2506
- function runningJobCount() {
2538
+ function freshRunningJobCount() {
2507
2539
  if (!jobsSnapshot) return 0;
2540
+ if (Date.now() - jobsSnapshot.at > JOBS_SNAPSHOT_TTL_MS) return 0;
2508
2541
  const owner = jobsSnapshot.sessionId;
2509
2542
  const mine = sessionId;
2510
2543
  if (
@@ -2520,8 +2553,8 @@ export default function (pi) {
2520
2553
  }
2521
2554
 
2522
2555
  // A job starting or ending is a state change: publish immediately so the
2523
- // sidebar and the native report follow it, and keep the beat alive while
2524
- // jobs run (the marker has its own TTL).
2556
+ // `gentle` wait and the finish gate follow it. `at` is the arrival time the
2557
+ // freshness bound measures from.
2525
2558
  function onJobsSnapshot(value) {
2526
2559
  if (!isRecord(value) || !isRecord(value.snapshot) || !Array.isArray(value.snapshot.jobs)) return;
2527
2560
  const jobs = value.snapshot.jobs.filter(
@@ -2530,14 +2563,14 @@ export default function (pi) {
2530
2563
  jobsSnapshot = {
2531
2564
  sessionId: typeof value.sessionId === "string" ? value.sessionId : undefined,
2532
2565
  jobs,
2566
+ at: Date.now(),
2533
2567
  };
2534
2568
  schedulePublish();
2535
2569
  }
2536
2570
 
2537
2571
  // Subscribed before the `enabled()` guard would matter: the bus event is
2538
- // session-scoped display data, so it is safe to observe anywhere. Hosts
2539
- // whose runtime has no event bus simply never see it (jobs stay at zero,
2540
- // which is today's behavior).
2572
+ // session-scoped display data, so it is safe to observe anywhere. Hosts whose
2573
+ // runtime has no event bus never see it (jobs stay at zero).
2541
2574
  if (typeof pi?.events?.on === "function") pi.events.on(JOBS_SIDEBAR_EVENT, onJobsSnapshot);
2542
2575
 
2543
2576
  function moshiCapture(ctx) {
@@ -2652,6 +2685,15 @@ export default function (pi) {
2652
2685
  let nativeSending = null;
2653
2686
  let nativeLastOk = undefined;
2654
2687
  let nativeSettledPending = false;
2688
+ // Finish-hold episode (S2): minted once at the settled-and-empty edge so the
2689
+ // row reads `done`, then republished unchanged (never refreshed) until the
2690
+ // hold expires. `donePending` carries the unannounced finish to the beat
2691
+ // that actually delivers the token (S3), and `sawActivity` remembers that
2692
+ // the session did work, so a session that never ran a turn stays idle. All
2693
+ // three clear with the session and the moment any work reappears.
2694
+ let doneExpiry;
2695
+ let donePending = false;
2696
+ let sawActivity = false;
2655
2697
  // LIVE-1 startup latency: the session binding is still INITIATED on
2656
2698
  // session_start (so Herdr can attribute the pane from the first frame), but
2657
2699
  // the host no longer waits for it. The host awaits every session_start
@@ -2672,7 +2714,7 @@ export default function (pi) {
2672
2714
  try {
2673
2715
  const cwd = ctx?.cwd;
2674
2716
  if (typeof cwd === "string" && cwd.length > 0) sessionCwd = cwd;
2675
- } catch {}
2717
+ } catch { /* best effort: a failure here is non-fatal */ }
2676
2718
  try {
2677
2719
  const file = ctx?.sessionManager?.getSessionFile?.();
2678
2720
  if (typeof file === "string" && file.length > 0) {
@@ -2685,7 +2727,7 @@ export default function (pi) {
2685
2727
  try {
2686
2728
  const id = ctx?.sessionManager?.getSessionId?.();
2687
2729
  if (typeof id === "string" && id.length > 0) sessionId = id;
2688
- } catch {}
2730
+ } catch { /* best effort: a failure here is non-fatal */ }
2689
2731
  }
2690
2732
 
2691
2733
  function askActiveNow() {
@@ -2737,7 +2779,7 @@ export default function (pi) {
2737
2779
  emittedLabel = undefined;
2738
2780
  try {
2739
2781
  pi.events.emit(BLOCKED_EVENT, { active: false });
2740
- } catch {}
2782
+ } catch { /* best effort: a failure here is non-fatal */ }
2741
2783
  }
2742
2784
  return;
2743
2785
  }
@@ -2978,14 +3020,17 @@ export default function (pi) {
2978
3020
  // emitted by the root Pi session while the main session is actively
2979
3021
  // working (agentActive, even with zero subagents), retaining coverage
2980
3022
  // while an authoritative running|queued subagent exists or a
2981
- // subagent_run/subagent_continue launch is pending; null (clear) once
2982
- // the main session settles (or any non-root session) so a settled
2983
- // session never retains it. Carries no count and never alters the work
2984
- // total or the roles CSV — the consumer reduces a fresh marker to the
3023
+ // subagent_run/subagent_continue launch is pending, or while a fresh
3024
+ // background-job snapshot shows a live job (the settled wait on a
3025
+ // `bash_background` / `monitor` job renders the same pink generic
3026
+ // `gentle`); null (clear) once the main session settles (or any non-root
3027
+ // session) so a settled session never retains it. Carries no count and
3028
+ // never alters the work total or the roles CSV — the consumer reduces a
3029
+ // fresh marker to the
2985
3030
  // `orchestrating` display only when no recognized role is active (below
2986
3031
  // attention, terminal `done`, and recognized roles; ahead of main
2987
3032
  // `working`).
2988
- if (rootSession && (agentActive || subs.length > 0 || pendingCalls.size > 0 || runningJobCount() > 0)) {
3033
+ if (rootSession && (agentActive || subs.length > 0 || pendingCalls.size > 0 || freshRunningJobCount() > 0)) {
2989
3034
  tokens.gentle_orchestrating_v1 = `${sessionHash}:${expiry}`;
2990
3035
  } else {
2991
3036
  tokens.gentle_orchestrating_v1 = null;
@@ -2999,6 +3044,41 @@ export default function (pi) {
2999
3044
  // how many delegates keep running.
3000
3045
  if (agentActive) tokens[PRINCIPAL_TOKEN] = `${sessionHash}:${expiry}`;
3001
3046
  else tokens[PRINCIPAL_TOKEN] = null;
3047
+ // Synthesized finish signal (S2/D2): minted once at the settled-and-empty
3048
+ // edge — principal settled with no running/queued delegate, no pending
3049
+ // launch, no live background job, and no human-wait, review, or error leg
3050
+ // — then republished with the SAME expiry so the hold can never be
3051
+ // extended. Any work appearing during the hold clears it on that beat, so
3052
+ // the row moves straight back to the role state. A session that never
3053
+ // worked never mints one. A live background job counts as activity: the
3054
+ // finish waits while the session still waits on it.
3055
+ const activity =
3056
+ agentActive ||
3057
+ subs.length > 0 ||
3058
+ pendingCalls.size > 0 ||
3059
+ freshRunningJobCount() > 0 ||
3060
+ askActiveNow() ||
3061
+ reviewActive ||
3062
+ !!errorCode;
3063
+ if (activity) {
3064
+ sawActivity = true;
3065
+ doneExpiry = undefined;
3066
+ donePending = false;
3067
+ } else if (settled) {
3068
+ if (doneExpiry === undefined && sawActivity) {
3069
+ doneExpiry = Date.now() + doneHoldMs();
3070
+ donePending = true;
3071
+ sawActivity = false;
3072
+ }
3073
+ if (doneExpiry !== undefined && Date.now() >= doneExpiry) {
3074
+ doneExpiry = undefined;
3075
+ donePending = false;
3076
+ }
3077
+ } else {
3078
+ doneExpiry = undefined;
3079
+ donePending = false;
3080
+ }
3081
+ tokens[DONE_TOKEN] = doneExpiry === undefined ? null : `${sessionHash}:${doneExpiry}`;
3002
3082
  if (changes.files > 0) {
3003
3083
  const files = String(changes.files);
3004
3084
  const added = String(changes.added);
@@ -3030,16 +3110,20 @@ export default function (pi) {
3030
3110
  // holds the beat the same way while its span is open. Effective
3031
3111
  // review (executing acknowledged capture/group calls) keeps the beat
3032
3112
  // alive so `review:` and the durable review token publish — NO GRACE:
3033
- // the leg drops when the last execution ends or resolves.
3113
+ // the leg drops when the last execution ends or resolves. A live
3114
+ // background job keeps the beat alive too: that is what lets the wait end
3115
+ // on its own when the snapshot goes stale instead of the beat stopping
3116
+ // with the row still painted `gentle`.
3034
3117
  return (
3035
3118
  agentActive ||
3036
3119
  activeSubs().length > 0 ||
3037
3120
  pendingCalls.size > 0 ||
3038
- runningJobCount() > 0 ||
3121
+ freshRunningJobCount() > 0 ||
3039
3122
  askToolCalls.size > 0 ||
3040
3123
  uiPromptActive ||
3041
3124
  reviewActive ||
3042
- emittedLabel !== undefined
3125
+ emittedLabel !== undefined ||
3126
+ doneExpiry !== undefined
3043
3127
  );
3044
3128
  }
3045
3129
 
@@ -3076,7 +3160,6 @@ export default function (pi) {
3076
3160
  settled,
3077
3161
  activeCount: activeSubs().length,
3078
3162
  pendingCount: pendingCalls.size + (nativeSettledPending ? 1 : 0),
3079
- jobCount: runningJobCount(),
3080
3163
  askActive: askActiveNow(),
3081
3164
  reviewActive,
3082
3165
  hasError: !!errorCode,
@@ -3143,7 +3226,9 @@ export default function (pi) {
3143
3226
  params.session_start_source = sessionStartSource;
3144
3227
  }
3145
3228
  const base = `${SOURCE}:session:${seq}`;
3146
- await sendRequestAttempt(
3229
+ // The result is deliberately discarded: this is the fire-and-forget
3230
+ // session binding, and `void` states that intent for the linter.
3231
+ void (await sendRequestAttempt(
3147
3232
  {
3148
3233
  id: `${base}:0:${randomUUID()}`,
3149
3234
  method: "pane.report_agent_session",
@@ -3158,7 +3243,7 @@ export default function (pi) {
3158
3243
  params,
3159
3244
  },
3160
3245
  1500,
3161
- ).catch(() => false));
3246
+ ).catch(() => false)));
3162
3247
  }
3163
3248
 
3164
3249
  // Start the session binding without waiting for it (see
@@ -3189,6 +3274,24 @@ export default function (pi) {
3189
3274
  }
3190
3275
  }
3191
3276
 
3277
+ // Moshi replacement (DESIGN §7, S3): the finish notification hangs off the
3278
+ // synthesized `done` edge — the beat that delivered the finish token, minted
3279
+ // only when the principal settled with zero delegates, pending launches, and
3280
+ // live jobs — never off a raw native working->idle transition, which fires
3281
+ // with work still left and used to skip `done` entirely.
3282
+ function emitFinish() {
3283
+ const project = moshiContext?.project ?? "Gentle";
3284
+ const lastLabel = lastFinishedLabel(tasks);
3285
+ moshiEmit("AgentEnd", {
3286
+ category: "task_complete",
3287
+ title: `Gentle finished: ${project}`,
3288
+ message:
3289
+ lastLabel !== undefined
3290
+ ? `${project} finished \u2014 ${lastLabel}. Return to Pi for what\u2019s next.`
3291
+ : `${project} finished and is waiting for your next instruction.`,
3292
+ });
3293
+ }
3294
+
3192
3295
  async function drainNative() {
3193
3296
  if (!enabled()) return;
3194
3297
  if (nativeInFlight) return;
@@ -3233,25 +3336,7 @@ export default function (pi) {
3233
3336
  // transition (attempt loop above, then beats — never a re-queue here).
3234
3337
  if (nativeSending === next) nativeSending = null;
3235
3338
  }
3236
- if (ok) {
3237
- const wasWorking = nativeLastOk?.state === "working";
3238
- nativeLastOk = next;
3239
- // Moshi replacement (DESIGN §7): the real finish is the native
3240
- // transition into `idle` — settled plus zero running/queued plus
3241
- // zero pending plus no human wait — never a settle with work left.
3242
- if (wasWorking && next.state === "idle") {
3243
- const project = moshiContext?.project ?? "Gentle";
3244
- const lastLabel = lastFinishedLabel(tasks);
3245
- moshiEmit("AgentEnd", {
3246
- category: "task_complete",
3247
- title: `Gentle finished: ${project}`,
3248
- message:
3249
- lastLabel !== undefined
3250
- ? `${project} finished \u2014 ${lastLabel}. Return to Pi for what\u2019s next.`
3251
- : `${project} finished and is waiting for your next instruction.`,
3252
- });
3253
- }
3254
- }
3339
+ if (ok) nativeLastOk = next;
3255
3340
  }
3256
3341
  } finally {
3257
3342
  nativeInFlight = false;
@@ -3301,6 +3386,10 @@ export default function (pi) {
3301
3386
  try {
3302
3387
  const ok = await sendTokens(tokens);
3303
3388
  if (ok) {
3389
+ if (donePending) {
3390
+ donePending = false;
3391
+ emitFinish();
3392
+ }
3304
3393
  if (transportFails >= TRANSPORT_FAIL_LATCH && errorCode === "transport") {
3305
3394
  errorCode = undefined;
3306
3395
  updateBlocker();
@@ -3398,7 +3487,7 @@ export default function (pi) {
3398
3487
  const top = probe.stdout.trim();
3399
3488
  if (top.length > 0) cwdRoot = top;
3400
3489
  }
3401
- } catch {}
3490
+ } catch { /* best effort: a failure here is non-fatal */ }
3402
3491
  }
3403
3492
  const roots = liveResolveScopeRoots(entries, sessionId, cwdRoot);
3404
3493
  const summary = await liveSummarizeRoots(roots);
@@ -3434,6 +3523,10 @@ export default function (pi) {
3434
3523
  nativeSending = null;
3435
3524
  nativeLastOk = undefined;
3436
3525
  nativeSettledPending = false;
3526
+ doneExpiry = undefined;
3527
+ donePending = false;
3528
+ sawActivity = false;
3529
+ jobsSnapshot = undefined;
3437
3530
  errorCode = undefined;
3438
3531
  liveGen += 1;
3439
3532
  liveInFlight = false;
@@ -3450,7 +3543,7 @@ export default function (pi) {
3450
3543
  emittedLabel = undefined;
3451
3544
  try {
3452
3545
  pi.events.emit(BLOCKED_EVENT, { active: false });
3453
- } catch {}
3546
+ } catch { /* best effort: a failure here is non-fatal */ }
3454
3547
  }
3455
3548
 
3456
3549
  // -- ask legs -------------------------------------------------------------
@@ -3883,7 +3976,7 @@ export default function (pi) {
3883
3976
  emittedLabel = undefined;
3884
3977
  try {
3885
3978
  pi.events.emit(BLOCKED_EVENT, { active: false });
3886
- } catch {}
3979
+ } catch { /* best effort: a failure here is non-fatal */ }
3887
3980
  }
3888
3981
  resetSessionState();
3889
3982
  return moshiFlushSends(1000);
@@ -1,22 +1,23 @@
1
1
  'use strict';
2
2
 
3
3
  // The `/herdr-gentle:customize` floating panel, recovered from commit 0e92869
4
- // (odd/tasks/restore-customize-panel.md T1, S1/S2).
4
+ // (odd/tasks/restore-customize-panel.md T1, S1/S2) and shaped like Gentle
5
+ // Shell's own customize card (odd/tasks/customize-parity-done-idle.md T1, S1).
5
6
  //
6
- // It is the former two-pane card with the same layout, palette, keyboard
7
- // semantics and overlay behaviour, reduced to the two switches this package
8
- // still owns: the managed Herdr sidebar rows and the Moshi notification
9
- // channel. The removed worktree / ODD / Issues / Reset sections are gone, and
10
- // the panel reads the current state handed in by the extension instead of a
11
- // cross-extension provider slot.
7
+ // One left `CATEGORIES` list, one right pane headed `<Category> · n/m` holding
8
+ // the setting rows, and the Shell's footer keys. Each switch is ONE row that
9
+ // paints the stored value with `●` and the other with `○`, so Enter (or a click
10
+ // on the row) is still the whole toggle. The removed worktree / ODD / Issues /
11
+ // Reset sections are gone, and the panel reads the current state handed in by
12
+ // the extension instead of a cross-extension provider slot.
12
13
  //
13
14
  // The host component contract (pi-coding-agent `custom`): the factory receives
14
15
  // (hostTui, theme, keybindings, done) and returns
15
- // { render(width), handleInput(data), invalidate() }. Selection keys only move
16
- // local state and ask the host to repaint through hostTui.requestRender(); Esc
17
- // finishes with done(null) and Enter with done({categoryId, valueId}). This
18
- // module never writes, notifies, or reloads: the extension's single apply path
19
- // runs after the overlay resolves.
16
+ // { render(width), handleInput(data), handleMouse(event), invalidate() }.
17
+ // Selection keys and pointer hits only move local state and ask the host to
18
+ // repaint; Esc finishes with done(null) and Enter (or a row click) with
19
+ // done({categoryId, switchId, valueId}). This module never writes, notifies, or
20
+ // reloads: the extension's single apply path runs after the overlay resolves.
20
21
 
21
22
  const ROLE = Object.freeze({
22
23
  key: "accent",
@@ -85,6 +86,10 @@ function label(theme, text) {
85
86
  return paint(theme, ROLE.label, text);
86
87
  }
87
88
 
89
+ function accent(theme, text) {
90
+ return paint(theme, ROLE.key, text);
91
+ }
92
+
88
93
  function value(theme, text) {
89
94
  return paint(theme, ROLE.value, text);
90
95
  }
@@ -138,74 +143,79 @@ function legendRow(theme, entries, width, measure) {
138
143
  return selection.entries.map((entry) => entryCell(theme, entry, selection.field)).join(separator);
139
144
  }
140
145
 
141
- const palette = { ROLES: ROLE, count, description, key, label, legendRow, paint, title, value };
146
+ const palette = { ROLES: ROLE, accent, count, description, key, label, legendRow, paint, title, value };
142
147
 
143
148
  const CUSTOMIZE_TITLE = "Customize · Herdr Gentle Shell";
144
149
  const CUSTOMIZE_CARD_PADDING = 4;
145
150
  const CUSTOMIZE_NARROW_WIDTH = 60;
146
151
  const CUSTOMIZE_MAX_HEIGHT = 24;
152
+ // The Shell's row vocabulary: `●` is the stored value, `○` the other one.
153
+ const CUSTOMIZE_PILL_CURRENT = "●";
154
+ const CUSTOMIZE_PILL_OTHER = "○";
155
+
156
+ // The switches this package owns. `id` is the apply target the extension knows
157
+ // (the sidebar rows go through the Herdr plugin's own configure step,
158
+ // notifications through the `gentle-moshi.json` flag and its Pi settings
159
+ // exclusion) and `setting` is the row name the panel paints.
160
+ const CUSTOMIZE_SWITCHES = [
161
+ { id: "sidebar", setting: "Sidebar agent rows" },
162
+ { id: "moshi", setting: "Notifications" },
163
+ ];
147
164
 
148
- // The two surviving switches. `id` is the value the extension applies: the
149
- // sidebar rows go through the Herdr plugin's own configure step, Moshi through
150
- // its flag file and Pi settings exclusion. Each switch is ONE row: it reads the
151
- // stored state and the row's id is the opposite value, so Enter is the toggle.
165
+ // Categories only group rows for display. Notifications appears under both
166
+ // headings on purpose: `Herdr Sidebar` is where the plugin's own switches are
167
+ // looked for, and `Moshi notifications` keeps the switch the user already
168
+ // knows. Both rows read the one flag, so they can never disagree.
152
169
  const CUSTOMIZE_CATEGORIES = [
153
- {
154
- id: "sidebar",
155
- title: "Herdr Sidebar",
156
- onDetail: "adds the managed agent rows to Herdr's plugin config",
157
- offDetail: "removes the managed rows and hands the pane back to Herdr",
158
- unknownDetail: "state unreadable; On re-runs the managed rows and reports the result",
159
- },
160
- {
161
- id: "moshi",
162
- title: "Moshi notifications",
163
- onDetail: "notifies ask and finish episodes through Moshi",
164
- offDetail: "leaves notifications to the host",
165
- unknownDetail: "state unreadable; On runs the moshi-hook check and reports the result",
166
- },
170
+ { id: "sidebar", title: "Herdr Sidebar", switches: ["sidebar", "moshi"] },
171
+ { id: "moshi", title: "Moshi notifications", switches: ["moshi"] },
167
172
  ];
168
173
 
169
- // One row per switch: it shows the CURRENT state and carries the value Enter
170
- // applies. `Unknown` keeps the row actionable instead of blocking the repair,
171
- // so an inconclusive check can always be re-run from here.
172
- function toggleRow(category, active) {
173
- const label = active === "on" ? "On" : active === "off" ? "Off" : "Unknown";
174
- const detail =
175
- active === "on" ? category.onDetail : active === "off" ? category.offDetail : category.unknownDetail;
176
- return { id: active === "on" ? "off" : "on", label, detail, mark: "→ " };
174
+ // One row per switch: it paints the stored value and carries the value Enter
175
+ // applies, so a single key press is the whole toggle. `Unknown` keeps the row
176
+ // actionable instead of blocking the repair, so an inconclusive check can
177
+ // always be re-run from here.
178
+ function toggleRow(definition, active) {
179
+ const current = active === "on" || active === "off" ? active : null;
180
+ return {
181
+ id: current === "on" ? "off" : "on",
182
+ switchId: definition.id,
183
+ setting: definition.setting,
184
+ current,
185
+ currentLabel: current === "on" ? "On" : current === "off" ? "Off" : "Unknown",
186
+ otherLabel: current === "on" ? "Off" : "On",
187
+ note: current === null ? "state unknown; Enter re-runs the managed rows" : undefined,
188
+ };
177
189
  }
178
190
 
179
191
  // The current stored values as the extension read them. A sidebar state of
180
192
  // `unknown` (unresolvable plugin root or inconclusive `--check`) is never a
181
193
  // guessed value and never blocks the repair: the row stays selectable and a
182
- // note explains that On re-runs the managed rows. Moshi is always a readable
183
- // local flag.
194
+ // note explains that On re-runs the managed rows. Notifications are always a
195
+ // readable local flag.
184
196
  function customizePanelModel({ sidebar, moshi } = {}) {
185
197
  const stored = (value) => (value === "on" || value === "off" ? value : null);
186
- const byId = (id) => CUSTOMIZE_CATEGORIES.find((entry) => entry.id === id);
187
- const sidebarActive = stored(sidebar);
188
- const moshiActive = stored(moshi) === "on" ? "on" : "off";
189
- const sidebarCategory = byId("sidebar");
190
- const moshiCategory = byId("moshi");
191
- return [
192
- {
193
- ...sidebarCategory,
194
- active: sidebarActive,
195
- note: sidebarActive === null ? "state unknown; Enter re-runs the managed rows" : undefined,
196
- rows: [toggleRow(sidebarCategory, sidebarActive)],
197
- },
198
- { ...moshiCategory, active: moshiActive, rows: [toggleRow(moshiCategory, moshiActive)] },
199
- ];
198
+ const current = { sidebar: stored(sidebar), moshi: stored(moshi) === "on" ? "on" : "off" };
199
+ return CUSTOMIZE_CATEGORIES.map((category) => ({
200
+ id: category.id,
201
+ title: category.title,
202
+ rows: category.switches.map((switchId) => toggleRow(
203
+ CUSTOMIZE_SWITCHES.find((entry) => entry.id === switchId),
204
+ current[switchId],
205
+ )),
206
+ }));
200
207
  }
201
208
 
202
209
  // The key legend is ONE terminal row: the `key` spelling paints as the key
203
210
  // role and the rest as its description. `short` is the compact form, and
204
211
  // `priority` is the drop order, so the close key outlives every other hint.
212
+ // There is no `p profiles` entry: this plugin owns no profiles concept, and a
213
+ // dead key in the footer would be a lie.
205
214
  const CUSTOMIZE_FOOTER_KEYS = [
215
+ { text: "Click", short: "Click", priority: 10 },
206
216
  { key: "←/→", text: "←/→ or Tab panes", short: "←/→ panes", priority: 60 },
207
- { key: "↑/↓", text: "↑/↓ or j/k move", short: "↑/↓ move", priority: 70 },
208
- { key: "Enter", text: "Enter toggle", short: "Enter toggle", priority: 80 },
217
+ { key: "↑/↓", text: "↑/↓ move", short: "↑/↓ move", priority: 70 },
218
+ { key: "Enter", text: "Enter apply", short: "Enter apply", priority: 80 },
209
219
  { key: "Esc", text: "Esc close", short: "Esc close", priority: 100 },
210
220
  ];
211
221
 
@@ -345,14 +355,43 @@ function customizeIsKeyRelease(helpers, data) {
345
355
  return false;
346
356
  }
347
357
 
358
+ // One setting line: the name column, then the Shell's pill pair — `●` on the
359
+ // stored value and `○` on the other. A pair wider than the pane falls back to
360
+ // the stored pill alone, so the narrow width keeps showing the real state.
361
+ function customizeSettingLine(helpers, theme, row, nameWidth, size, focused) {
362
+ const name = String(row.setting);
363
+ const namePad = " ".repeat(Math.max(0, nameWidth - customizeMeasure(helpers, name)));
364
+ const prefix = focused ? "▸ " : " ";
365
+ const lead = `${prefix}${name}${namePad} `;
366
+ const stored = `${CUSTOMIZE_PILL_CURRENT} ${row.currentLabel}`;
367
+ const other = `${CUSTOMIZE_PILL_OTHER} ${row.otherLabel}`;
368
+ const pair = `${stored} ${other}`;
369
+ const showPair = customizeMeasure(helpers, `${lead}${pair}`) <= size;
370
+ const body = showPair ? pair : stored;
371
+ if (focused && theme && typeof theme.bg === "function") {
372
+ try {
373
+ const plain = customizeFit(helpers, `${lead}${body}`, Math.max(0, size));
374
+ const band = theme.bg("selectedBg", plain + " ".repeat(Math.max(0, size - customizeMeasure(helpers, plain))));
375
+ if (typeof band === "string") return band;
376
+ } catch {
377
+ // Fall through to the composed form below.
378
+ }
379
+ }
380
+ const segments = [
381
+ { kind: focused ? "key" : "label", text: prefix },
382
+ { kind: focused ? "value" : "description", text: `${name}${namePad} ` },
383
+ { kind: row.current === null ? "error" : "accent", text: stored },
384
+ ];
385
+ if (showPair) segments.push({ kind: "description", text: ` ${other}` });
386
+ return customizeCompose(helpers, theme, segments, size);
387
+ }
388
+
348
389
  function createCustomizePanel({ helpers, hostTui, theme, rowsAvailable, model, done }) {
349
390
  const state = {
350
391
  pane: "categories",
351
392
  cat: 0,
352
- row: model.map((category) => {
353
- const at = category.rows.findIndex((row) => row.id === category.active);
354
- return at >= 0 ? at : 0;
355
- }),
393
+ row: model.map(() => 0),
394
+ frame: null,
356
395
  };
357
396
  function availableRows() {
358
397
  try {
@@ -371,6 +410,7 @@ function createCustomizePanel({ helpers, hostTui, theme, rowsAvailable, model, d
371
410
  }
372
411
  function render(width) {
373
412
  const w = typeof width === "number" && Number.isFinite(width) ? Math.floor(width) : 0;
413
+ state.frame = null;
374
414
  if (w <= 0) return [];
375
415
  const height = availableRows();
376
416
  if (!height) return [];
@@ -394,25 +434,20 @@ function createCustomizePanel({ helpers, hostTui, theme, rowsAvailable, model, d
394
434
  const rightWidth = inner - leftWidth - (leftWidth ? 3 : 0);
395
435
  const category = model[state.cat];
396
436
  const rows = category.rows;
397
- const previewLines = height >= 11 ? 3 : height >= 8 ? 1 : 0;
398
437
  const showHeading = height >= 6;
399
- // Right pane: LABELS ONLY. Each choice's detail lives exactly once in the
400
- // preview block below, never under the rows.
401
- const rightLines = [];
402
- for (let index = 0; index < rows.length; index += 1) {
403
- const row = rows[index];
404
- const focusedValue = !navOnly && state.pane === "values" && index === state.row[state.cat];
405
- const mark = typeof row.mark === "string" ? row.mark : (row.id === category.active ? "→ " : " ");
406
- rightLines.push({ label: `${mark}${row.label}`, focused: focusedValue });
407
- }
408
- if (category.note) {
409
- rightLines.push({ label: category.note, mark: " ", focused: false, muted: true });
410
- }
411
- const contentHeight = Math.max(1, height - 2 - 1 - (showHeading ? 1 : 0) - previewLines - (showHeading ? 1 : 0));
438
+ // Right pane: one line per setting (name column plus the pill pair) and,
439
+ // when the stored state is unreadable, one muted note under it.
440
+ const rightLines = rows.map((row, index) => ({ kind: "row", index, row }));
441
+ for (const row of rows) if (row.note) rightLines.push({ kind: "note", text: row.note });
442
+ const contentHeight = Math.max(1, height - 2 - 1 - (showHeading ? 2 : 0));
412
443
  const position = navOnly ? state.cat : state.row[state.cat];
413
444
  const listLength = navOnly ? model.length : rightLines.length;
414
445
  const start = Math.min(Math.max(0, position - contentHeight + 1), Math.max(0, listLength - contentHeight));
415
446
  const navStart = Math.min(Math.max(0, state.cat - contentHeight + 1), Math.max(0, model.length - contentHeight));
447
+ const nameWidth = rows.reduce(
448
+ (need, row) => Math.max(need, customizeMeasure(helpers, row.setting)),
449
+ 0,
450
+ );
416
451
  const paint = (text, size, kind) => customizePaint(helpers, theme, kind, text, size);
417
452
  const compose = (segments, size) => customizeCompose(helpers, theme, segments, size);
418
453
  const divider = palette.paint(theme, "border", "│");
@@ -420,6 +455,7 @@ function createCustomizePanel({ helpers, hostTui, theme, rowsAvailable, model, d
420
455
  ? `${left}${" ".repeat(Math.max(0, leftWidth - customizeMeasure(helpers, left)))} ${divider} ${right}`
421
456
  : right;
422
457
  const lines = [];
458
+ const hits = [];
423
459
  // Title row doubles as the esc hint: same row, right-aligned.
424
460
  const escGap = Math.max(1, inner - customizeMeasure(helpers, title) - 3);
425
461
  lines.push(compose([
@@ -436,58 +472,52 @@ function createCustomizePanel({ helpers, hostTui, theme, rowsAvailable, model, d
436
472
  { kind: "count", text: rows.length ? `${state.row[state.cat] + 1}/${rows.length}` : "empty" },
437
473
  ];
438
474
  lines.push(join(
439
- leftWidth ? paint("CATEGORIES", leftWidth, "label") : "",
475
+ leftWidth ? paint("CATEGORIES", leftWidth, "key") : "",
440
476
  compose(heading, rightWidth),
441
477
  ));
442
478
  }
443
- const current = focused();
444
479
  for (let i = 0; i < contentHeight; i += 1) {
445
- const nav = model[navStart + i];
480
+ const navIndex = navStart + i;
481
+ const nav = model[navIndex];
482
+ const at = start + i;
483
+ const item = navOnly ? (model[at] || null) : (rightLines[at] || null);
484
+ // The card paints the top border above content line 0, so a content row's
485
+ // rendered row is its index + 1.
486
+ const y = lines.length + 1;
446
487
  const left = nav
447
- ? customizeSelect(helpers, theme, nav.title, leftWidth, navOnly || (navStart + i === state.cat && state.pane === "categories"))
488
+ ? customizeSelect(helpers, theme, nav.title, leftWidth, navOnly ? at === state.cat : navIndex === state.cat && state.pane === "categories")
448
489
  : "";
449
- const item = navOnly ? (model[start + i] || null) : (rightLines[start + i] || null);
450
490
  let right = "";
451
- if (item) {
452
- // Labels sit under a 4-column mark gutter (▸/→): the stored label
453
- // carries its → mark, focus adds ▸ in front and the rest pad two
454
- // spaces.
455
- if (navOnly) {
456
- right = customizeSelect(helpers, theme, item.title, rightWidth, start + i === position);
457
- } else if (item.muted) {
458
- right = paint(` ${item.label}`, rightWidth, "description");
459
- } else if (item.focused) {
460
- right = customizeSelect(helpers, theme, item.label, rightWidth, true);
461
- } else {
462
- right = paint(` ${item.label}`, rightWidth, "value");
463
- }
464
- } else if (!navOnly && rightLines.length === 0) {
491
+ if (navOnly) {
492
+ right = item ? customizeSelect(helpers, theme, item.title, rightWidth, at === state.cat) : "";
493
+ } else if (item && item.kind === "row") {
494
+ right = customizeSettingLine(
495
+ helpers,
496
+ theme,
497
+ item.row,
498
+ nameWidth,
499
+ rightWidth,
500
+ at === state.row[state.cat] && state.pane === "values",
501
+ );
502
+ } else if (item && item.kind === "note") {
503
+ right = paint(item.text, rightWidth, "description");
504
+ } else if (rightLines.length === 0) {
465
505
  right = paint("No settings available", rightWidth, "description");
466
506
  }
467
507
  lines.push(join(left, right));
468
- }
469
- // Bottom block: the FOCUSED choice's label in the preview title plus its
470
- // description on the next line — exactly once.
471
- const previewLabel = current.row
472
- ? (typeof current.row.preview === "string" ? current.row.preview : current.row.label)
473
- : current.category.title;
474
- const previewTitle = `Preview · ${previewLabel}`;
475
- const previewSample = current.row ? current.row.detail : "unavailable";
476
- if (previewLines === 3) {
477
- lines.push("");
478
- lines.push(compose([
479
- { kind: "label", text: "Preview" },
480
- { kind: "label", text: " · " },
481
- { kind: "value", text: previewLabel },
482
- ], inner));
483
- lines.push(paint(previewSample, inner, "description"));
484
- } else if (previewLines === 1) {
485
- lines.push(paint(previewTitle, inner, "description"));
508
+ // Pointer hits cover the pane text only: a click on a border, the title,
509
+ // the heading or the footer hits nothing and is ignored.
510
+ const rightStart = 2 + (leftWidth ? leftWidth + 3 : 0);
511
+ if (leftWidth && nav) hits.push({ kind: "category", index: navIndex, y, x: 2, end: 2 + leftWidth });
512
+ if (navOnly && item) hits.push({ kind: "category", index: at, y, x: rightStart + 2, end: rightStart + rightWidth });
513
+ else if (item && item.kind === "row") hits.push({ kind: "row", index: item.index, y, x: rightStart + 2, end: rightStart + rightWidth });
486
514
  }
487
515
  if (showHeading) {
488
516
  lines.push(customizePad(helpers, customizeFooter(helpers, theme, CUSTOMIZE_FOOTER_KEYS, inner), inner));
489
517
  }
490
- return customizeCard(helpers, theme, lines.slice(0, Math.max(0, height - 2)), w);
518
+ const shown = lines.slice(0, Math.max(0, height - 2));
519
+ state.frame = { width: w, height: shown.length + 2, hits: hits.filter((hit) => hit.y <= shown.length) };
520
+ return customizeCard(helpers, theme, shown, w);
491
521
  }
492
522
  function requestPaint() {
493
523
  try {
@@ -527,11 +557,45 @@ function createCustomizePanel({ helpers, hostTui, theme, rowsAvailable, model, d
527
557
  }
528
558
  if (customizeKeyMatches(helpers, data, ["enter", "return"])) {
529
559
  const current = focused();
530
- done({ categoryId: current.category.id, valueId: current.row ? current.row.id : null });
560
+ done({
561
+ categoryId: current.category.id,
562
+ switchId: current.row ? current.row.switchId : current.category.id,
563
+ valueId: current.row ? current.row.id : null,
564
+ });
565
+ }
566
+ }
567
+ // Pointer contract: x/y are local to this component's rendered frame, the
568
+ // card border included. A press only captures the gesture; the click that
569
+ // follows activates the hit, so a drag never applies a row by accident.
570
+ // Anything outside a pane's text is ignored, which is also the answer for a
571
+ // click on a border, the title, the heading or the footer.
572
+ function handleMouse(event) {
573
+ if (!event || event.button !== "left") return undefined;
574
+ if (event.type !== "press" && event.type !== "click") return undefined;
575
+ const frame = state.frame;
576
+ if (!frame) return undefined;
577
+ if (!Number.isFinite(event.x) || !Number.isFinite(event.y)) return undefined;
578
+ const sized = (!Number.isFinite(event.width) || event.width === frame.width)
579
+ && (!Number.isFinite(event.height) || event.height === frame.height);
580
+ if (!sized) return undefined;
581
+ const hit = frame.hits.find((entry) => entry.y === event.y && event.x >= entry.x && event.x < entry.end);
582
+ if (!hit) return undefined;
583
+ if (event.type === "press") return { handled: true, capture: true, render: false };
584
+ const target = model[state.cat];
585
+ if (hit.kind === "category") {
586
+ state.cat = hit.index;
587
+ state.pane = "categories";
588
+ return { handled: true, render: true };
531
589
  }
590
+ const row = target ? target.rows[hit.index] : null;
591
+ if (!row) return undefined;
592
+ state.pane = "values";
593
+ state.row[state.cat] = hit.index;
594
+ done({ categoryId: target.id, switchId: row.switchId, valueId: row.id });
595
+ return { handled: true, render: true };
532
596
  }
533
597
  function invalidate() {}
534
- return { render, handleInput, invalidate, state };
598
+ return { render, handleInput, handleMouse, invalidate, state };
535
599
  }
536
600
 
537
601
  module.exports = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "herdr-gentle-shell",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "Pi package for Herdr sidebar states: the Pi extension sidecar that publishes session facts as Herdr pane-metadata tokens, the optional Moshi notification channel, and the Pi-side helpers the Herdr Gentle Shell plugin drives.",
5
5
  "keywords": [
6
6
  "pi-package",