herdr-gentle-shell 1.7.0 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,737 @@
1
+ # Theme sync (Herdr palette follows the active Pi theme)
2
+
3
+ Herdr's palette follows the theme active in Gentle Shell / Pi, or one theme
4
+ pinned while the sync is off. This page covers the switch, the one state file,
5
+ what the writer puts in your own `config.toml`, the refusals, the notices and
6
+ the limits. Protocol context is in [DESIGN.md](../DESIGN.md) §12; the switch is
7
+ described beside the sidebar and Moshi switches in [README.md](../README.md).
8
+
9
+ The writer runs **in process, inside this Pi package**:
10
+ `extensions/herdr-theme-sync.ts` calls `lib/herdr-theme-apply.js`, which plans
11
+ with `lib/herdr-theme-config.js` and rewrites the config file itself. **The
12
+ Herdr plugin is not involved in theme sync and needs no update for it.** The
13
+ 1.8.0 design spawned a `bin/configure-theme.js` shipped by the *separately
14
+ installed* plugin, so a Pi-only update kept running the old plugin's writer, and
15
+ an install that never shipped that file broke the feature outright. Both halves
16
+ of that dependency are gone: there is no plugin-side `configure-theme.js`, no
17
+ plugin-side planner and no 1.8.0 managed block.
18
+
19
+ ## The switch
20
+
21
+ `/herdr-gentle:customize` → `Herdr Theme` holds two settings, laid out like the
22
+ rest of the card (see [Panel](#panel)):
23
+
24
+ - `Theme sync` is **OFF by default**. `On` makes Herdr's palette the palette of
25
+ the theme Pi is showing, and it follows a change of the active theme while Pi
26
+ keeps running. Turning the sync off stops following and leaves Herdr with the
27
+ palette it already has: nothing is removed from Herdr's config, so the last
28
+ applied palette survives Pi closing.
29
+ - `Gentle Shell theme` assigns one Gentle Shell / Pi theme by name from Pi's own
30
+ list (`None` first, then the host's order). While the stored sync is on the
31
+ setting is painted dim, never given the selection band, and pressing Enter on
32
+ it writes nothing: the apply path refuses with
33
+ `Turn Theme sync off to pick a specific theme.` Choosing `None` clears the pin
34
+ (`theme: null`); choosing a name stores it. The stored pin is carried across a
35
+ sync toggle untouched, so turning the sync off restores that choice instead of
36
+ unassigning it.
37
+
38
+ Esc closes the card without writing, and the plain two-step menu stays as the
39
+ fallback when the TUI helpers or `ctx.ui.custom` are unavailable.
40
+
41
+ The notices are fixed strings:
42
+
43
+ | Action | Notice |
44
+ | --- | --- |
45
+ | Sync turned on | `Theme sync on; Herdr's palette follows the theme active in Pi.` |
46
+ | Sync turned off | `Theme sync off; Herdr keeps the palette it was last given.` |
47
+ | Toggle already in that state | `Theme sync already on/off; nothing was changed.` |
48
+ | Theme setting while the sync is on | `Turn Theme sync off to pick a specific theme.` |
49
+ | Theme assigned | `Gentle Shell theme set to <name>.` |
50
+ | Pin cleared | `Gentle Shell theme set to Off; Herdr keeps the palette it was last given.` (the stored value stays `null` and the inline list marks `None`; only this notice — and the fallback menu's `Off (no theme assigned)` entry — spell it `Off`) |
51
+ | Host exposes no theme list | `Could not read Pi's theme list (this host exposes no getAllThemes()); nothing was changed.` |
52
+ | Theme store missing | `Could not reach the theme store (lib/theme-store.js is unavailable); nothing was changed.` |
53
+ | State file not writable | `Could not write the theme store: <detail>; nothing was changed.` |
54
+
55
+ `/herdr-gentle:customize status` prints one read-only line and writes nothing:
56
+
57
+ ```text
58
+ customize status: sidebar=<on|off|unknown> moshi=<on|off> theme-sync=<on|off|unknown> theme=<name|none|unknown>
59
+ ```
60
+
61
+ ## State file
62
+
63
+ One document is the only persisted truth: `gentle-theme.json`.
64
+
65
+ ```json
66
+ {
67
+ "sync": true,
68
+ "theme": null,
69
+ "updatedAt": "2026-09-19T10:00:00.000Z"
70
+ }
71
+ ```
72
+
73
+ It lives in the directory `gentle-moshi.json` already uses: `GENTLE_STATUS_STATE_DIR`
74
+ when set, else `$XDG_STATE_HOME/herdr/plugins/herdr-gentle-agents` (else
75
+ `~/.local/state/herdr/plugins/herdr-gentle-agents`), unless the stored
76
+ directory holds no file of ours and the newer `herdr-gentle-shell` directory
77
+ does — then that one is used. `sync` is the switch, `theme` is the pinned name
78
+ or `null`, and `updatedAt` is stamped by the writer — a caller cannot record a
79
+ timestamp it made up. Writes are atomic (temporary file in the same directory,
80
+ then rename), preserve an existing file's mode and create a new one as `0600`.
81
+
82
+ - **Missing file** is an inert document (`sync: false`, `theme: null`): a fresh
83
+ install writes nothing, so nothing is what it reads.
84
+ - **Unreadable or unparsable file** is a refusal, never a guess: the sync
85
+ setting marks no option and carries `state unknown; Enter turns the sync on`,
86
+ the theme list marks nothing, and the follower does nothing. It is
87
+ written over only when you act — toggling the sync writes a fresh document,
88
+ and the theme setting is refused only by a *stored* `sync: true`.
89
+ - **`sync: false` with `theme: null`** is the default install: the follower
90
+ asks for no palette at all, so nothing is written, nothing is reloaded and
91
+ nothing is removed (S7).
92
+ - A blank or non-string `theme` normalises to `null`; nothing is trimmed into a
93
+ theme name that no install has.
94
+
95
+ ## What gets written
96
+
97
+ The writer edits **your own** `[theme]` and `[theme.custom]` tables in place, in
98
+ the config at `$HERDR_CONFIG_PATH`, else `<XDG_CONFIG_HOME>/herdr/config.toml`,
99
+ else `~/.config/herdr/config.toml`. The planner is a **line splicer, not a TOML
100
+ validator**: it finds table boundaries (a header only counts at a real line
101
+ start — never inside a multi-line string, a multi-line array, an inline table or
102
+ a comment) and treats every line outside those two tables as **opaque bytes**.
103
+ Those lines are never validated and never rewritten — the scanner only looks at
104
+ them far enough to know where a table starts and ends — so invalid TOML there is
105
+ your pre-existing breakage: Herdr already refuses to load such a file, and this
106
+ writer's only promise is that it does not touch those lines. Inside the two theme
107
+ tables it is strict (see [Refusals](#refusals)).
108
+
109
+ Everything it does not own is preserved byte for byte: other tables and keys,
110
+ comments, blank lines, ordering, indentation, spacing around `=`, trailing
111
+ comments on a rewritten line, CRLF or mixed line endings, a leading UTF-8 BOM
112
+ and a missing final newline. Before returning a plan the writer **enforces a
113
+ splice invariant in code**: the non-theme lines of its own output must be
114
+ byte-identical to the input's (plus at most the single line terminator needed to
115
+ append a table after an unterminated last line). A mismatch is an internal
116
+ error, never a silent edit.
117
+
118
+ There are exactly **two ownership classes**, and they are what make leaving a
119
+ theme safe:
120
+
121
+ **1. A value you already had is replaced in place** and remembered. One comment
122
+ line recording **the whole original line** goes directly above it — the first
123
+ original wins, so a later palette change reuses that comment instead of
124
+ stacking a second one:
125
+
126
+ ```toml
127
+ [theme]
128
+ # herdr-gentle-shell: was name = "catppuccin"
129
+ name = "one-dark"
130
+
131
+ [theme.custom]
132
+ # herdr-gentle-shell: was accent = "#7aa2f7" # mine, keep the blue
133
+ accent = "#bb9af7"
134
+ ```
135
+
136
+ The marker records the original line minus its indentation, so trailing spaces
137
+ and an inline comment are part of the record; restoring puts those bytes back
138
+ exactly — with one exception: **the latest edit wins**. If you changed the
139
+ inline comment after the planner wrote its value, a restore keeps the recorded
140
+ key/value and **your current trailing comment**, not the stale one the marker
141
+ remembers. A comment is only a marker when that text parses as a strict
142
+ `key = <string> [comment]` line naming the key under it (`# herdr-gentle-shell:
143
+ was blue = aba`, or a payload carrying a number, is your comment and stays as
144
+ it is). The marker may sit anywhere in the comment block directly above the key,
145
+ so a comment of your own in between does not produce a second one, and two
146
+ markers for the same key are a refusal. A value that already equals the
147
+ projection is not rewritten and gets no comment at all. Literal (single-quoted)
148
+ values and basic (double-quoted) values are compared by their decoded meaning —
149
+ basic strings are escape-decoded, literal strings are exactly the characters
150
+ between their quotes, so `'\u0023123456'` is not the colour `#123456`.
151
+
152
+ **2. A token you did not have lives in ONE marked block** at the end of
153
+ `[theme.custom]`, in Herdr's token order, regenerated on every plan:
154
+
155
+ ```toml
156
+ # herdr-gentle-shell: begin
157
+ text = "#c0caf5"
158
+ subtext0 = "#565f89"
159
+ # herdr-gentle-shell: end
160
+ ```
161
+
162
+ The closing line has one more spelling:
163
+ `# herdr-gentle-shell: end after a missing line ending`. The planner writes it
164
+ when placing the block also **added the file's missing final line ending** to
165
+ the line above it (an unterminated last line). The text alone cannot tell
166
+ whether that terminator was yours, so the block records the fact, and a later
167
+ clear takes back **only what the planner added** — never a byte you wrote.
168
+
169
+ When the planner also has to **create** the `[theme.custom]` table, the opening
170
+ line says so — `# herdr-gentle-shell: begin created` — and the table it created
171
+ is **removed again** when the block empties and the table holds nothing else, so
172
+ a cycle of projections ending in an empty custom projection gives your original
173
+ `[theme.custom]` back byte for byte (a `[theme]` table the planner created keeps
174
+ its `name` line: see [Limits](#limits)). A `[theme.custom]` header **you** wrote
175
+ is never removed, even when it ends up empty.
176
+
177
+ Removing or moving a block is refused when a comment **directly above** `begin`
178
+ would become adjacent to the token key under the block and would read as a
179
+ marker for it — `line N: ambiguous herdr-gentle-shell marker above the managed
180
+ block; no changes proposed.` Your ordinary comment stays the user's text; the
181
+ planner refuses instead of silently promoting it to ownership on the next run.
182
+
183
+ A block whose bytes already match the palette it needs is left where it is; one
184
+ that has to be rewritten is placed after the last key of `[theme.custom]`, or
185
+ right after its header when the table has no keys of its own (or at the end of
186
+ the file, creating the table, when `[theme.custom]` does not exist yet). Inside
187
+ the block only `<token> = "#rrggbb"` lines are allowed; anything else there — a
188
+ comment, a blank line, a malformed value — is a **refusal**, because rewriting
189
+ the block would delete bytes a human wrote.
190
+
191
+ **Leaving a projection never leaves a stale colour.** The plan reconciles
192
+ against what the previous palette owned:
193
+
194
+ - a token you had (so it carries our marker) that the new projection no longer
195
+ carries — or carries again with the value the marker records — is **restored
196
+ from that marker byte for byte** and the marker is dropped: your original
197
+ line, quoting, spacing, trailing spaces and inline comment included (unless you
198
+ edited that trailing comment since — see the exception above);
199
+ - a token that only ever lived inside our block simply disappears with the
200
+ block, and when nothing is left to own, the block is removed entirely;
201
+ - a token you own with no marker is **never touched**, even when the projection
202
+ stops carrying it: it was never ours.
203
+
204
+ Two more rules, stated because they are visible in the file:
205
+
206
+ - An **empty `[theme.custom]` header stays** unless the planner created it (see
207
+ above): it cannot otherwise prove the line is its own, and deleting a line you
208
+ may have written is a bigger intervention than this switch promises.
209
+ - A token that appears both in our block and as your own key in the same
210
+ `[theme.custom]` table is a **refusal**: duplicate keys in one table are not
211
+ valid TOML, so the planner refuses instead of picking a winner. Delete the
212
+ block line to own that token yourself.
213
+
214
+ A key the plan must touch has to be a **strict single-line** form (see
215
+ [Refusals](#refusals)); a key it does not touch is left alone as long as the
216
+ scanner can tell where that line ends, so an untargeted multi-line value keeps
217
+ working. `name` is set to Herdr's base theme (`one-dark`) on the existing line,
218
+ or inserted right after the `[theme]` header when the table has none.
219
+ `auto_switch = false` is accepted and left untouched; every other `auto_switch`
220
+ value is a refusal.
221
+
222
+ ### The golden example
223
+
224
+ This is the user's real config shape from the planner's test suite: an existing
225
+ `[theme]` with `auto_switch = false`, a `[theme.custom]` synced from DMS/Niri
226
+ that carries tokens the projection does not own (`panel_bg`, `blue`, `yellow`)
227
+ and a `[terminal]` table we have no business in. Applying the projection
228
+ `{name: "one-dark", custom: {accent, text, red, green, subtext0, overlay0,
229
+ overlay1, mauve}}` produces exactly these bytes (also asserted as valid TOML by
230
+ the suite's `python3 -m tomllib` oracle):
231
+
232
+ ```toml
233
+ onboarding = false
234
+
235
+ [theme]
236
+ name = "catppuccin"
237
+
238
+ auto_switch = false
239
+ [theme.custom]
240
+ # TokyoNight Night and Moon — synced from DMS/Niri (source: ~/.config/DankMaterialShell/themes/tokyoNightNightMoon/theme.json)
241
+ panel_bg = "#1a1b26"
242
+ accent = "#7aa2f7"
243
+ green = "#9ece6a"
244
+ blue = "#7aa2f7"
245
+ red = "#f7768e"
246
+ yellow = "#e0af68"
247
+
248
+ [terminal]
249
+ new_cwd = "follow"
250
+ ```
251
+
252
+ becomes:
253
+
254
+ ```toml
255
+ onboarding = false
256
+
257
+ [theme]
258
+ # herdr-gentle-shell: was name = "catppuccin"
259
+ name = "one-dark"
260
+
261
+ auto_switch = false
262
+ [theme.custom]
263
+ # TokyoNight Night and Moon — synced from DMS/Niri (source: ~/.config/DankMaterialShell/themes/tokyoNightNightMoon/theme.json)
264
+ panel_bg = "#1a1b26"
265
+ # herdr-gentle-shell: was accent = "#7aa2f7"
266
+ accent = "#bb9af7"
267
+ # herdr-gentle-shell: was green = "#9ece6a"
268
+ green = "#00ff00"
269
+ blue = "#7aa2f7"
270
+ # herdr-gentle-shell: was red = "#f7768e"
271
+ red = "#ff0000"
272
+ yellow = "#e0af68"
273
+ # herdr-gentle-shell: begin
274
+ text = "#c0caf5"
275
+ subtext0 = "#565f89"
276
+ overlay0 = "#565f89"
277
+ overlay1 = "#a9b1d6"
278
+ mauve = "#7dcfff"
279
+ # herdr-gentle-shell: end
280
+
281
+ [terminal]
282
+ new_cwd = "follow"
283
+ ```
284
+
285
+ Note what did not move: `panel_bg`, `blue` and `yellow` keep their bytes,
286
+ `auto_switch = false` and the DMS/Niri comment are untouched, the replaced lines
287
+ keep their positions, and only the tokens the user did not have are in the block.
288
+ Re-running the same projection over this output is a **no-op**: `changed: false`,
289
+ no write, no backup, no reload.
290
+
291
+ ### Projection
292
+
293
+ Exactly the eight Herdr tokens in `HERDR_ROLE_SOURCES`
294
+ (`lib/theme-projection.js`) come from Pi roles:
295
+
296
+ | Herdr token | Pi theme token |
297
+ | --- | --- |
298
+ | `accent` | `accent` |
299
+ | `text` | `text` |
300
+ | `red` | `error` |
301
+ | `green` | `success` |
302
+ | `subtext0` | `muted` |
303
+ | `overlay0` | `muted` |
304
+ | `overlay1` | `thinkingText` |
305
+ | `mauve` | `borderAccent` |
306
+
307
+ `muted` paints two Herdr surfaces on purpose: it is converted once and the pair
308
+ is always emitted together, never half-applied. On top of that come the
309
+ per-theme fixed surfaces in `DOTS_FIXED`, which are the palette the user's own
310
+ Herdr profiles already use:
311
+
312
+ | Pi theme | Fixed tokens |
313
+ | --- | --- |
314
+ | `Gentleman-Cute` | `panel_bg #000000`, `surface0 #241822`, `surface1 #342230`, `surface_dim #20161E`, `overlay0 #B99AA9` |
315
+ | `Gentleman-Sexy` | Cute's surfaces plus `subtext0 #FF4F9A`, `mauve #B99AA9`, `active_row_bg #2E0F1F`, `selection_bg #2E0F1F` |
316
+ | `Gentle` | `panel_bg #06080f` |
317
+
318
+ Values are lower-cased, and the block's tokens follow Herdr's own
319
+ `HERDR_TOKEN_ORDER`, so the same palette always renders the same bytes for the
320
+ same file. A token whose Pi source is empty (Pi's "terminal default", which has
321
+ no hex spelling), absent or not `#rrggbb` is omitted for that apply; the rest of
322
+ the palette still lands. The projection carries no `[theme.custom]` table at all
323
+ when no token survives conversion (an empty table would still be an override), and
324
+ the follower refuses to apply a projection with no concrete token (see
325
+ [Failure modes and notices](#failure-modes-and-notices)).
326
+
327
+ Working/done status colours and notification colours stay with Herdr's base
328
+ theme: `yellow`, `peach`, `blue`, `teal` and the surface tokens above are part
329
+ of Herdr's vocabulary but not of this projection, so a status the user never
330
+ asked to repaint keeps its native colour.
331
+
332
+ ### Ownership
333
+
334
+ The reference implementation this follows is
335
+ [gentle-herdr](https://github.com/MarsSall/gentle-herdr) (MIT License,
336
+ Copyright (c) MarsSall); the guard matrix, bounded snapshot, compare-and-swap
337
+ and reload call are that project's logic ported to plain CommonJS, and the
338
+ projection follows its role table. This package deliberately differs in two
339
+ places: it accepts `auto_switch = false` (the reference refuses that line
340
+ outright, which is why the user's real config was never written), and **the sync
341
+ owns its projected tokens** and gives them back.
342
+
343
+ That ownership rule is the honest one to spell out: while the sync is on, or a
344
+ theme is pinned, the package owns the `name` line and every token it projects.
345
+ The `was` comments and the marked block exist for a clean revert, not for
346
+ arbitration. Another tool that rewrites the same keys — a desktop-theme sync
347
+ such as DMS/Niri writing `[theme.custom]`, for example — will overwrite them on
348
+ its next run, and the next palette change here will overwrite them back. A token
349
+ the package never projected is never written, never merged and never repaired.
350
+
351
+ ### Safe write
352
+
353
+ Writing is bounded and staged: the target must be an absolute, canonical path
354
+ whose parent directory is not a symlink, a regular single-link file of at most
355
+ 256 KiB, strictly valid UTF-8 (a leading BOM is decoded as part of the text, not
356
+ consumed, so a changed write keeps it). The plan is refused **before anything is
357
+ written** if the document would grow past the same 256 KiB limit — a file we
358
+ could read but not write back would make the next run refuse its own output —
359
+ with `Herdr config would grow to <bytes> bytes, past the 262144-byte limit; no
360
+ changes proposed.`
361
+ The bytes are re-read and compared (device, inode, size, mtime, ctime, mode,
362
+ contents) before the backup and again immediately before the swap.
363
+
364
+ The new text is staged at a path chosen **before the file exists**, so every
365
+ failure — open, write, `fsync`, `fchmod` — leaves the writer able to remove it.
366
+ The staged file is exclusive `0600`, `fchmod`-ed to the original mode (`0o7777`,
367
+ so setuid, setgid and sticky bits survive), compared once more, then `rename`d
368
+ over the target.
369
+
370
+ Temporary cleanup is best-effort **and reported**: the writer retries the unlink
371
+ once and then force-removes, and a `.tmp` file that survives is never hidden.
372
+ If the **backup's** temp survives, the apply fails with `Herdr backup temporary
373
+ could not be removed: <path>`, so it can never report `requested` with a stray
374
+ file beside your config; if the **staged** temp survives a failed replace, the
375
+ `partial`/`config` error ends with `; temporary file left behind: <path>`.
376
+
377
+ **Cleanup only ever touches a path this call created.** The temp names are
378
+ random, but if something else already owns that exact name, the exclusive open
379
+ fails with `EEXIST` and the writer does **not** delete it: the apply answers
380
+ `partial` with `stage: 'config'` and that `EEXIST` text, and the foreign file is
381
+ left exactly as it was (the config and the backup are untouched).
382
+
383
+ The one-time backup `<config>.herdr-gentle-shell.bak` is **published atomically
384
+ and never overwritten**: it is written to a temp name and then hard-linked to
385
+ the backup name, so a crash or a full disk leaves no truncated `.bak` that a
386
+ later run would mistake for "already backed up". A regular file that already
387
+ sits at the backup path — whether it was there before this run or appeared in
388
+ the race — **is** the existing backup: it is accepted as it is, never compared
389
+ and never overwritten (it may legitimately be an older original from before you
390
+ edited the config). A backup path that is not a real file (a directory, a
391
+ symlink, a socket) is a refusal with the config untouched.
392
+
393
+ `unchanged` writes nothing and reloads nothing: Herdr already holds that
394
+ palette. A real write is followed by exactly one `herdr server reload-config`
395
+ through `execFile` with `HERDR_BIN_PATH` (default `herdr`), no shell, a 5 s
396
+ timeout and a 4096-byte output cap. `forceReload` is the one exception: it
397
+ reloads even when the plan is unchanged, and it exists for repairing a config
398
+ whose previous reload failed (see the follower below). A missing `config.toml`
399
+ is not created — that is a refusal, not a bootstrap.
400
+
401
+ ## Refusals
402
+
403
+ Every refusal means **no write, no backup, no reload and config bytes
404
+ unchanged**, and it names the line it saw:
405
+ `line <n>: <reason>; no changes proposed.` (The one internal check that has no
406
+ line — the splice invariant — says `internal splice invariant violated; no
407
+ changes proposed.`.)
408
+
409
+ ### What the planner guarantees, and what it does not
410
+
411
+ It guarantees:
412
+
413
+ - **table boundaries** for documents whose multi-line strings, arrays and inline
414
+ tables are terminated — a header is only a header at a real line start, never
415
+ inside a multi-line string, a multi-line array, an inline table or a comment;
416
+ - **every byte outside `[theme]` and `[theme.custom]` preserved**, modulo the one
417
+ line terminator needed to append a table after an unterminated last line, and
418
+ modulo the 1.8.0 markers it wrote itself (below) — checked in code by the
419
+ splice invariant before a plan is returned;
420
+ - **only the strict line forms below inside the two theme tables**;
421
+ - **CRLF or mixed line endings, a leading BOM and a missing final newline**
422
+ survive, and planning is **idempotent and reversible** (a cycle of projections
423
+ ending in an empty custom projection gives the original bytes back, apart from
424
+ the `name` line a cycle cannot remove — see [Limits](#limits)).
425
+
426
+ It does **not** guarantee — deliberately, because this is not a TOML validator:
427
+
428
+ - **nothing is validated outside the theme tables**, escapes included: in a
429
+ single-line or multi-line string there, a backslash is only consumed with the
430
+ character after it, so `note = """x\q"""` is not a refusal (whether that escape
431
+ is legal TOML is a parser's job), and a run of **three or more quotes closes a
432
+ multi-line string** — the boundary scan does not judge the leftover quotes. The
433
+ scan only validates escapes where it must read a value back: a quoted key and a
434
+ theme-table line it parses strictly. **Values, dates, numbers, keys, duplicate
435
+ keys, duplicate tables, dotted-key redeclarations and array-of-tables on other
436
+ tables are not checked** either: an input that is already invalid there is left
437
+ exactly as it is, because Herdr already refuses to load such a file and
438
+ rewriting it was never this writer's job;
439
+ - a projected palette is checked for **shape only** (a known token, `#rrggbb`),
440
+ never for Herdr's own semantics;
441
+ - the config is never locked (see [Limits](#limits)).
442
+
443
+ The **strict grammar inside the theme tables** is: comment lines, blank lines,
444
+ and `key = value [comment]` where the value is a **single-line** string
445
+ (basic or literal), boolean, integer or float. Where the plan must **touch** a
446
+ key (`name`, a projected token, a line the projection is leaving) anything else
447
+ is refused with its line number; a key the plan does **not** touch is left byte
448
+ for byte whenever the scanner can tell where that line ends, so an untargeted
449
+ `yellow = """reset"""` or a multi-line value keeps working.
450
+
451
+ ### Accepted on purpose
452
+
453
+ These are the inputs a real config can carry, and the planner must not reject
454
+ them:
455
+
456
+ - a **leading UTF-8 BOM**: skipped while scanning, put back byte for byte;
457
+ - a **trailing comment on the last line of a file with no final newline** (the
458
+ comment is not swallowed into the value);
459
+ - **anything outside the theme tables**, valid or not, is preserved: multi-line
460
+ strings, arrays, inline tables, dates and numbers, `[ui] theme = "system"`, an
461
+ unquoted dotted key (`theme.custom.accent = …` inside `[other]`). Only a
462
+ `theme` key at the **top level** is a conflict. The scanner only has to *find*
463
+ boundaries there: a header-shaped line must parse and a multi-line construct
464
+ must be terminated, otherwise the plan refuses — that is boundary detection,
465
+ not validation;
466
+ - **`auto_switch = false`**, byte-exact;
467
+ - **quoted spellings of the same thing**: `["theme"]` and `['theme']` are
468
+ `[theme]`; `"name"` / `'accent'` are the same keys; a `\uXXXX` escape in a
469
+ quoted key names the same key. **Quoted segments are literal**:
470
+ `["theme.custom"]` is a *different* root key named `theme.custom` — exactly as
471
+ TOML says — so it is never edited and never confused with our
472
+ `[theme.custom]` table (splitting that dot was the 1.8.0 bug);
473
+ - **literal strings are never escape-decoded**: `'\u0023123456'` is that text,
474
+ not the colour `#123456`; basic (double-quoted) strings are decoded.
475
+
476
+ ### Refused
477
+
478
+ | Cause | Message text |
479
+ | --- | --- |
480
+ | `auto_switch` with any value but `false` | `` `auto_switch` is only supported as `auto_switch = false` `` |
481
+ | `dark_name` / `light_name` in `[theme]` | `` `<key>` in `[theme]` is not supported `` |
482
+ | Top-level `theme` key | ``a top-level `theme` key is user configuration`` |
483
+ | Dotted `theme.custom.<token>` key at the top level | ``a dotted `theme` key cannot be adopted safely`` |
484
+ | A dotted key extending a key the planner owns inside `[theme]` (`name`, `custom`, `auto_switch`, `dark_name`, `light_name`) | ``a dotted key extending `[theme]` cannot be adopted safely`` |
485
+ | A dotted key extending a Herdr token inside `[theme.custom]` | ``a dotted key extending `[theme.custom]` cannot be adopted safely`` |
486
+ | `[theme]` or `[theme.custom]` twice | `` `[theme]` appears more than once `` (same for `[theme.custom]`) |
487
+ | A third `[theme.*]` table | `` `[theme.x]` is not a table this writer owns `` |
488
+ | `[[theme]]` / `[[theme.custom]]` array-of-tables | `` `[[<path>]]` array-of-tables is not supported `` |
489
+ | `name` or `auto_switch` repeated in `[theme]`, a token repeated in `[theme.custom]` | `` `<key>` appears more than once in `[<table>]` `` |
490
+ | A token in our block that is also your key | `` `<key>` appears more than once in `[theme.custom]` `` |
491
+ | Two markers for the same key above it | ``duplicate herdr-gentle-shell marker for `name` `` (per token: ``duplicate herdr-gentle-shell marker for `<token>` ``) |
492
+ | `custom = …` inside `[theme]` | `` `custom` in `[theme]` must be a `[theme.custom]` table `` |
493
+ | `name` or a user-owned token the plan must touch, written in any form but a strict single-line string | `` `name` value is not a plain single-line string `` (per token: `` `<token>` value is not a plain single-line string ``) |
494
+ | A key the plan must touch whose value spans lines (a multi-line string or array) | ``cannot record the original value of `<key>` safely`` |
495
+ | A control character, or a bare carriage return | `unsupported control character` / `a bare carriage return is not a line ending` |
496
+ | The block outside `[theme.custom]`, unterminated, a second begin, or an end with no begin | ``the `# herdr-gentle-shell` block is outside `[theme.custom]` `` / ``… is not terminated`` / ``the `# herdr-gentle-shell: begin` line appears more than once`` / ``the `# herdr-gentle-shell: end` line has no matching begin`` |
497
+ | A line inside our block that is not `<token> = "#rrggbb"` (a comment, a blank line, a malformed value, an unknown token) | `unexpected content inside the herdr-gentle-shell block` |
498
+ | Removing or moving a block whose `begin` is directly under a marker-shaped comment that would become adjacent to the token key below | `ambiguous herdr-gentle-shell marker above the managed block` |
499
+ | A table header the scanner cannot parse, or one with trailing content | `unterminated table header`, `unsupported table header`, `trailing content after the table header`, `unterminated array-of-tables header`, `a quoted key must be on one line`, `unterminated quoted key`, `unsupported escape in a quoted key` |
500
+ | A multi-line string, array or inline table the scanner cannot close (anywhere — boundaries depend on it) | `unterminated string` / `unterminated array or inline table` / `mismatched bracket or brace` |
501
+
502
+ A malformed *projection* (a name outside Herdr's set, an unknown token, a value
503
+ that is not `#rrggbb`, an unknown top-level key) is refused the same way with
504
+ `Invalid Herdr theme projection: …; no changes proposed.` and no line number —
505
+ that one is a package bug, not something your config can cause. So is a
506
+ **splice-invariant violation**: the planner re-derives the non-theme lines of
507
+ its own output and refuses rather than return a document that moved a byte it
508
+ promised not to touch.
509
+
510
+ At the file level the remaining refusals are: a symlinked or non-canonical
511
+ config path, a symlinked parent directory, a directory, hardlink or oversize
512
+ file, invalid UTF-8, a backup path that is not a regular file, a config that
513
+ changed between the snapshot and the replacement (`Herdr config changed before
514
+ replacement`), a planned document past the 256 KiB limit, a backup temp that
515
+ cannot be removed, and a failed rename.
516
+
517
+ ### The 1.8.0 marker pair
518
+
519
+ A config written by 1.8.0 may still carry
520
+ `# BEGIN herdr-gentle-theme (managed; do not edit)` and
521
+ `# END herdr-gentle-theme`. The planner drops them **only** when they are the
522
+ nearest pair (a nested BEGIN is matched to the END that closes it) **and** that
523
+ pair encloses a `[theme]` or `[theme.custom]` table; a stale pair around
524
+ unrelated keys is your text and stays untouched. A pair that closes on an
525
+ unterminated last line migrates too: the surviving last line keeps its own
526
+ terminator state, so the file does not gain or lose a final newline.
527
+
528
+ ## Failure modes and notices
529
+
530
+ The follower (`extensions/herdr-theme-sync.ts`) never reports success of a
531
+ no-op, and every user-visible outcome is a fixed string:
532
+
533
+ - **Applied** — a write and its reload: `Herdr theme applied: <name>; reload requested`
534
+ (`info`). This is only shown when *the user* changed something (the switch or
535
+ the pinned theme, including the first evaluation of a session); a palette-only
536
+ change while the sync is on is silent.
537
+ - **Herdr already has it** (`unchanged`): silent, and an earlier failure memo is
538
+ cleared.
539
+ - **Not available** (`info`, once per session): `Herdr theme sync is inactive:
540
+ this Pi session is not inside a Herdr pane.`, `Herdr theme sync is inactive:
541
+ this is a remote session and Herdr reads its config on another machine.`, or
542
+ `Herdr theme sync is not supported in this environment.`
543
+ - **Pinned theme not installed**: `The Pi theme "<name>" is not installed, so
544
+ Herdr's palette was left unchanged; pick an installed theme in
545
+ /herdr-gentle:customize.` — once per session; a later install of that exact
546
+ theme is picked up without a restart.
547
+ - **Nothing to project**: `Herdr theme not applied: <theme name> has no concrete
548
+ colours to project.` (`the active theme` replaces the name when the active
549
+ theme exposes none) — once per session, `warning`. A palette with no concrete
550
+ token would still rewrite the theme name and announce a success that painted
551
+ nothing, so the follower applies nothing at all: the config is not touched
552
+ (not even the `name` line).
553
+ - **Refused or not written**: `Herdr theme not applied: <reason>` — once per
554
+ distinct failure text. A success clears the memo, so the same refusal after a
555
+ good apply is news again.
556
+ - **Written but not reloaded**: `Herdr theme written; Herdr reload failed:
557
+ <reason>. Run 'herdr server reload-config' to apply it.` — the reason is
558
+ trimmed and terminated by the follower, so a child-process message that ends
559
+ in a newline still reads as one sentence, and an empty reason collapses to
560
+ `Herdr theme written; Herdr reload failed. Run 'herdr server reload-config' to
561
+ apply it.` The config is committed and Herdr's state is unknown.
562
+
563
+ The reload notice is not just prose. `partial/reload` sets an **owed reload** for
564
+ the rest of the session: the next apply attempt is sent with `forceReload`, so
565
+ the reload happens even though the plan is then unchanged, and a success pays
566
+ the debt off. It is session memory on purpose (a tick never reloads while the
567
+ debt stands, so Herdr is not reloaded every 500 ms), which is exactly why the
568
+ notice names the command that repairs it by hand after a restart.
569
+
570
+ Silent by design: a store this package cannot read (nothing is written), a theme
571
+ whose palette cannot be read at all (the tick is skipped rather than writing an
572
+ empty projection), and a subagent child session (`GENTLE_PI_AGENTS_CHILD=1`),
573
+ which never registers the follower at all.
574
+
575
+ A failed apply is never retried automatically: the observation is recorded
576
+ *before* the apply, so the next tick acts only on a new palette or a new switch
577
+ value. One apply is in flight at a time.
578
+
579
+ ### The follower
580
+
581
+ There is no theme-change event in the host, so the palette is a pull-read:
582
+
583
+ - One evaluation immediately on `session_start`, then one every **500 ms** on an
584
+ unreferenced timer, so an idle follower never keeps Pi (or a scripted session)
585
+ alive. The timer is cleared on `session_shutdown` (and a shutdown that lands
586
+ during the first evaluation wins: no tick is armed afterwards), and the
587
+ per-session memo — last requested switch value, last palette fingerprint, last
588
+ failure, once-per-session notices, the owed reload — is reset at session start.
589
+ - Each evaluation computes two identities — the requested `[sync, chosen]` and
590
+ the palette fingerprint `[theme name, sorted token/hex pairs]` — and applies
591
+ only when one differs, so a theme recoloured in place (same name, new colours)
592
+ is noticed without a restart.
593
+ - With the sync off and no theme pinned the follower asks for nothing at all
594
+ **and forgets what it applied**. That reset is what makes **re-enabling the
595
+ sync always re-apply**: without it, the next `On` would look unchanged (same
596
+ switch, same palette) and a config you repaired in between would never be
597
+ written. If the config already matches, the writer answers `unchanged` — no
598
+ write, no reload, no notice.
599
+ - With the sync on it reads `ctx.ui.theme`; with a theme pinned it reads
600
+ `ctx.ui.getTheme(<name>)` and writes the name it was given as the label.
601
+ - Availability (a Herdr pane, not a subagent child, not an SSH session, a
602
+ supported local Linux Herdr) is decided once, by `applyHerdrTheme`, so the
603
+ follower can never disagree with the writer about who may write.
604
+
605
+ ## Environment
606
+
607
+ The availability guard, in order — every one of these is a `unavailable` result
608
+ and none of them reads the config:
609
+
610
+ - `HERDR_ENV=1` **and** a non-empty `HERDR_PANE_ID` **and** a non-empty
611
+ `HERDR_SOCKET_PATH` are what make this a Herdr pane.
612
+ - `GENTLE_PI_AGENTS_CHILD=1` is a subagent child: refused by the writer *and*
613
+ the follower is not registered.
614
+ - `SSH_CONNECTION`, `SSH_CLIENT` or `SSH_TTY` set is a remote session.
615
+ - `HERDR_BIN_PATH` must not be a `herdr-dev` build, the platform must be
616
+ `linux`, and `HERDR_SOCKET_PATH` and the resolved config path must be
617
+ absolute.
618
+
619
+ Paths and binaries:
620
+
621
+ - `HERDR_CONFIG_PATH` — the config file the writer edits.
622
+ - `XDG_CONFIG_HOME`, then `HOME` — default config directory
623
+ (`<xdg>/herdr/config.toml`, else `~/.config/herdr/config.toml`).
624
+ - `HERDR_BIN_PATH` — Herdr binary (default `herdr`) for
625
+ `server reload-config`.
626
+
627
+ Tests and isolated runs:
628
+
629
+ - `GENTLE_THEME_SYNC_LIB_DIR` — the directory the follower requires
630
+ `theme-store.js`, `theme-projection.js` and `herdr-theme-apply.js` from
631
+ (defaults to this package's `lib/`).
632
+ - `GENTLE_CUSTOMIZE_LIB_DIR` — the directory the state sidecar loads the panel
633
+ and the theme store from, so the switch and the follower read the same files.
634
+ - `GENTLE_STATUS_STATE_DIR`, `XDG_STATE_HOME`, `HERDR_PLUGIN_STATE_DIR` — the
635
+ state directory for `gentle-theme.json` and every other file this package
636
+ writes there.
637
+
638
+ ## Limits
639
+
640
+ - **Not proven against a live Pi TUI in this repository's tests.** The automated
641
+ evidence is a stubbed Pi host plus a real binary stand-in on disk; no
642
+ live-TUI run is recorded. `ctx.ui.theme`, `getTheme()`, `getAllThemes()`,
643
+ `notify()` and the panel's host component contract are used as the host
644
+ documents them, and a host that lacks one degrades to "nothing changed" rather
645
+ than to a guess.
646
+ - **The compare-and-swap has one unavoidable window.** The config is compared
647
+ immediately before the rename, so an edit that lands earlier — during the
648
+ snapshot, the plan, the backup or the staging — is detected and the replace
649
+ aborts with `Herdr config changed before replacement`. An edit that lands
650
+ between that final compare and the `rename` itself **cannot be detected
651
+ without holding a lock on the config**, which this writer deliberately does
652
+ not do; the window is as small as a compare followed by a rename.
653
+ - **The planner is a splicer, not a validator** (see
654
+ [What the planner guarantees](#what-the-planner-guarantees-and-what-it-does-not)):
655
+ invalid TOML outside the theme tables is left exactly as it is — Herdr already
656
+ refuses such a file, and this writer never repairs it — while a theme-table line
657
+ it must touch has to be the strict single-line form. Boundary scanning refuses
658
+ only constructs it cannot close (an unterminated multi-line string, array or
659
+ inline table), because table boundaries depend on them; escapes outside the
660
+ theme tables are never validated, and a run of three or more quotes closes a
661
+ multi-line string.
662
+ - **A pre-existing truncated backup is kept, not repaired.** A regular file at
663
+ the backup path is accepted as the existing backup and is never compared or
664
+ overwritten — it may legitimately be an older original — so a `.bak` damaged by
665
+ something else stays damaged, and the `was` comments are the per-value revert
666
+ path.
667
+ - **Remote sessions are inactive.** In SSH the Herdr client reads the config of
668
+ the machine it runs on, so writing the server-side file would change nothing
669
+ on screen; the guard refuses and says so once.
670
+ - **Two writers of the same keys fight.** The sync owns what it projects, so a
671
+ desktop-theme sync and this feature overwrite each other's values on their next
672
+ run. There is no merge, no lock and no arbitration — only the `was` comments,
673
+ the marked block and the one-time backup for a clean revert.
674
+ - **One machine.** A Herdr client on another host reads its own `config.toml`;
675
+ this is a local sync, not a fleet setting.
676
+ - **500 ms is the whole observation granularity.** A theme change is noticed
677
+ within one tick and not sooner.
678
+ - **The revert is per token, not per file.** Restoration comes from the `was`
679
+ markers and the block, plus the `begin created` table the planner removes
680
+ again; a `[theme.custom]` header **you** wrote and the `name` line's marker stay
681
+ behind (the header is yours, and the name is always projected).
682
+ - **There is no "full clear" distinct from an empty custom projection.** A
683
+ projection always carries the theme name, so nothing can ask the planner to
684
+ drop the `name` line: a name line it **inserted** (because `[theme]` had none)
685
+ simply stays, while an existing name is restored to your original. Likewise a
686
+ `[theme]` table the planner created is not removed — only the
687
+ `[theme.custom]` table it created is, once its block empties.
688
+ - **The config must already exist.** A missing `config.toml` is refused, never
689
+ created.
690
+
691
+ ## Panel
692
+
693
+ `/herdr-gentle:customize` with no argument opens the card. It behaves like
694
+ Gentle Shell's own: one left `CATEGORIES` list and one right pane headed
695
+ `<Category> · n/m`, with one line per setting and its options inline —
696
+ `●` the stored option, `›` the cursor while it sits elsewhere, `○` the rest.
697
+
698
+ - The arrows move the option cursor and **only Enter applies**; Enter keeps the
699
+ card open (only a Moshi settings change that needs a Pi reload closes it),
700
+ Esc closes without a write, and
701
+ `Tab` switches panes. `↑/↓` (or `j`/`k`) moves between settings.
702
+ - A click on an option applies exactly that option, a click on a setting's name
703
+ only moves the focus, a click on a category selects it, and anything outside
704
+ the panes is ignored (a press only captures the gesture, so a drag applies
705
+ nothing).
706
+ - When a line's options do not fit, it scrolls sideways: a window that always
707
+ contains the cursored option, muted `‹` / `›` marking hidden options and an
708
+ `n/m` counter. If not even one option fits, the compact `‹ value ›` form takes
709
+ over; a very narrow card drops the counter to keep the cursored value.
710
+ - The Preview block sits below the panes: `Preview · <option> · <title>` in the
711
+ accent role, then the sample lines in the muted role, painted with the host
712
+ theme. A theme option shows its own palette (`source palette` plus an `Aa
713
+ sample text` swatch in that theme's colours); the other options carry a static
714
+ sample. The block is 6, 3, 1 or 0 lines by card height, and the 1-line form
715
+ reads `Preview omitted · enlarge terminal` (`→ controls · Esc close` in a
716
+ narrow card's category list).
717
+ - Three footer legends follow what the keys do right now, after the `Click · `
718
+ prefix, and compact instead of wrapping on a narrow card:
719
+ `↑/↓ categories · → open · Esc close` in a narrow card's category list,
720
+ `←/→ choose · Enter apply · ↑/↓ settings · Tab panes · Esc close` on an option
721
+ row, and `←/→ or Tab panes · ↑/↓ move · Enter apply · Esc close` elsewhere.
722
+ - The theme list is read automatically from the host (`ctx.ui.getAllThemes()`)
723
+ in the host's own order, `None` first; a host that exposes no list shows one
724
+ note (`Themes unavailable; use Pi /settings`) instead of an empty picker, and
725
+ an unreadable store adds `state unknown; Enter pins a theme`.
726
+
727
+ ## Implementation
728
+
729
+ | File | Role |
730
+ | --- | --- |
731
+ | `lib/theme-store.js` | The state document: directory resolution, normalized read, atomic write. |
732
+ | `lib/theme-projection.js` | The pure projection: theme names, token order, `HERDR_ROLE_SOURCES`, `DOTS_FIXED`, `projectPalette`, `paletteFingerprint`, the `Off` label. |
733
+ | `lib/herdr-theme-config.js` | The pure planner — a **line splicer**, not a TOML validator: table-boundary scanning, opaque bytes outside the two theme tables, a strict theme-table grammar, the whole-line `was` marker with byte-exact restoration (the user's latest trailing comment wins), the one regenerated block (`begin` / `begin created` … `end` / `end after a missing line ending`), the ambiguity refusal above a block being removed or moved, the 1.8.0 marker-pair migration, the BOM and the enforced splice invariant. |
734
+ | `lib/herdr-theme-apply.js` | The writer: availability guards, bounded snapshot, compare-and-swap, atomic non-overwriting backup (a regular existing file is accepted as is), retried temp cleanup that reports a survivor and never deletes a temp it did not create, growth limit, `forceReload`, reload. |
735
+ | `extensions/herdr-theme-sync.ts` | The follower: session-start evaluation, 500 ms tick, fingerprint, owed-reload repair, the notices. |
736
+ | `extensions/gentle-herdr-state.ts` | The switch: `applyThemeSync`, `writeThemeChoice`, `applyCustomizePanel`, `customize status`. |
737
+ | `lib/customize-panel.js` | The card: categories, option lines, sideways window, Preview block, legends, pointer hits. |