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