pi-odd-worktree 3.14.0 → 3.15.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,64 @@
1
+ 'use strict';
2
+ // The strings this package paints for a peak schedule.
3
+ //
4
+ // Two surfaces, two different freedoms:
5
+ //
6
+ // - The usage panel prints `ProviderUsage.plan` inside its own muted role and never sanitizes it,
7
+ // so the header is plain text: the schedule rides there unconditionally, and red stays reserved
8
+ // for near-limit quota inside the panel. The panel already prints ` · ` before that field, so
9
+ // the field itself carries no leading separator.
10
+ // - The widget line is this package's own row above the editor, so it paints itself: `peak` is
11
+ // amber while the provider is peak-priced and closes that escape right away, so the details
12
+ // after it stay in the terminal's normal foreground instead of inheriting a dimmed amber. The
13
+ // line names the provider from its own registry `label`, so several providers peaking at once
14
+ // are several rows, each telling the human which window it is. Off-peak has no widget line at
15
+ // all.
16
+ //
17
+ // The panel's window labels stay untouched: the rows read `go 5h`, `go week`, `go month`, with
18
+ // the schedule only on the provider line.
19
+ //
20
+ // Nothing here reads a clock; every function takes the instant it must describe.
21
+
22
+ const { formatBoundaryClock, formatPeakState } = require('./peak-schedule.js');
23
+
24
+ /** The key this package owns in pi's widget map. */
25
+ const PEAK_WIDGET_KEY = 'opencode-go-peak-widget';
26
+
27
+ const AMBER = '\x1b[33m';
28
+ const RESET = '\x1b[0m';
29
+
30
+ /**
31
+ * The schedule the panel prints on its provider line, between the provider name and the
32
+ * `updated …` note: `off-peak 3hr 20m`.
33
+ *
34
+ * The panel inserts its own ` · ` before this field, so the field never starts with one: a leading
35
+ * separator here would render as a doubled ` · · `.
36
+ */
37
+ function panelSchedule(state, now) {
38
+ return formatPeakState(state, now);
39
+ }
40
+
41
+ /**
42
+ * One widget line, drawn only while the provider is peak-priced:
43
+ * `peak · 2× deepseek · until 04:00`. There is no off-peak variant; the caller clears the widget
44
+ * instead. The boundary is rendered in the machine's own timezone: `timeZone` is not passed here,
45
+ * only by unit tests that call `formatBoundaryClock` directly.
46
+ *
47
+ * Only the state word carries a color: `peak` is amber and closes it with `\x1b[0m` immediately,
48
+ * so the rest of the line renders in the terminal's own foreground. A dim attribute there would
49
+ * reuse the amber already in effect and paint the details in dull brown-gray, which is neither the
50
+ * amber highlight nor ordinary body text.
51
+ *
52
+ * Everything after the state word comes from the provider's own registry entry, so a provider
53
+ * that publishes a multiplier shows it and one that does not shows nothing invented.
54
+ */
55
+ function peakWidgetLine(provider, state, now) {
56
+ const clock = formatBoundaryClock(state.until, now);
57
+ return `${AMBER}peak${RESET} · ${provider.label} · until ${clock}`;
58
+ }
59
+
60
+ module.exports = {
61
+ PEAK_WIDGET_KEY,
62
+ panelSchedule,
63
+ peakWidgetLine,
64
+ };
@@ -0,0 +1,63 @@
1
+ 'use strict';
2
+ // The peak schedules this package knows about, in the order the `Alert` section draws them.
3
+ //
4
+ // Every provider here is a schedule, not a model: the `Alert` row is gated by its own switch and
5
+ // its own window and by nothing else (never by the session's model, never by a usage key), and
6
+ // one row per peaking provider is drawn from this array in declaration order. Adding a provider
7
+ // is adding an entry — the engine, the labels and the wiring all read `zone`, `windows`,
8
+ // `weekdaysOnly`, `setting` and `label` from the entry itself.
9
+ //
10
+ // The windows are half-open `[startHour, endHour)` pairs of LOCAL wall hours in `zone`:
11
+ //
12
+ // deepseek 01:00-04:00 and 06:00-10:00 UTC, Monday through Friday (published in UTC)
13
+ // claude 05:00-11:00 in America/Los_Angeles, Monday through Friday (published in Pacific)
14
+ //
15
+ // DeepSeek's published price multiplier is `2×`, so its `label` says so. Anthropic publishes no
16
+ // multiplier for Claude's window, so Claude's `label` is just the provider name: a made-up `2×`
17
+ // or `1.4×` there would be a number this package has no source for.
18
+
19
+ /** OpenCode Go's DeepSeek windows, in UTC. Both models share the family's published peak. */
20
+ const DEEPSEEK = Object.freeze({
21
+ id: 'deepseek',
22
+ setting: 'Deepseek peak',
23
+ label: '2× deepseek',
24
+ zone: 'UTC',
25
+ windows: Object.freeze([Object.freeze([1, 4]), Object.freeze([6, 10])]),
26
+ weekdaysOnly: true,
27
+ });
28
+
29
+ /**
30
+ * Anthropic's Claude window, in Pacific time: weekdays 05:00-11:00 PT. It is a zone, not a UTC
31
+ * pair, because the published hours move with PDT/PST — 12:00-18:00 UTC in summer, 13:00-19:00
32
+ * UTC in winter. The row prints no multiplier: Anthropic publishes none for the window.
33
+ */
34
+ const CLAUDE = Object.freeze({
35
+ id: 'claude',
36
+ setting: 'Claude peak',
37
+ label: 'claude',
38
+ zone: 'America/Los_Angeles',
39
+ windows: Object.freeze([Object.freeze([5, 11])]),
40
+ weekdaysOnly: true,
41
+ });
42
+
43
+ /** Every schedule, in the order the `Alert` section draws its rows. Frozen: this is the registry. */
44
+ const PROVIDERS = Object.freeze([DEEPSEEK, CLAUDE]);
45
+
46
+ const BY_ID = new Map(PROVIDERS.map((provider) => [provider.id, provider]));
47
+
48
+ /** The provider with this id, or `undefined`: this is how the wiring resolves a stored setting. */
49
+ function providerById(id) {
50
+ if (typeof id !== 'string') return undefined;
51
+ return BY_ID.get(id);
52
+ }
53
+
54
+ /** The ids, in declaration order. A fresh array, so a caller cannot edit the registry through it. */
55
+ function providerIds() {
56
+ return PROVIDERS.map((provider) => provider.id);
57
+ }
58
+
59
+ module.exports = {
60
+ PROVIDERS,
61
+ providerById,
62
+ providerIds,
63
+ };
@@ -0,0 +1,242 @@
1
+ 'use strict';
2
+ // The peak-schedule engine: when a provider is peak-priced, and when that answer changes.
3
+ //
4
+ // A provider comes from `lib/peak-providers.js` and carries the schedule: `windows` are half-open
5
+ // `[startHour, endHour)` pairs of hours in `zone`, `weekdaysOnly` drops Saturday and Sunday, and
6
+ // `zone` is the zone the provider publishes those hours in. DeepSeek publishes UTC hours, Anthropic
7
+ // publishes Pacific ones, and the difference is not cosmetic: 05:00-11:00 Pacific is 12:00-18:00 UTC
8
+ // under PDT and 13:00-19:00 UTC under PST, so the hours are read in the provider's own zone and the
9
+ // weekdays are the provider's own weekdays.
10
+ //
11
+ // Nothing here knows about DeepSeek or Claude by name; a provider added to the registry is answered
12
+ // with no change to this file. Nothing here reads a clock either: every function takes the instant
13
+ // it must reason about, so the panel and the row never disagree and the schedule is testable
14
+ // without freezing time.
15
+ //
16
+ // Converting a local wall hour to an instant needs the zone's offset AT THAT INSTANT, which is
17
+ // exactly what is unknown before the conversion: the two-pass correction below applies the offset
18
+ // in force at the candidate itself, which is why the answer survives a DST switch instead of
19
+ // landing an hour off.
20
+
21
+ const MS_PER_DAY = 86_400_000;
22
+ const MINUTE_MS = 60_000;
23
+
24
+ // How far ahead to look for the next transition, in local days. A Friday evening puts the next
25
+ // window three days out; the extra margin keeps the search correct without ever approximating the
26
+ // answer.
27
+ const CANDIDATE_DAYS = 10;
28
+
29
+ // One formatter per zone, built once: `Intl.DateTimeFormat` is the only zone database Node has,
30
+ // and building one per call would dominate a schedule that is recomputed on every boundary.
31
+ const PARTS_FORMATTERS = new Map();
32
+
33
+ /** The parts formatter for a zone, or `undefined` when the zone does not resolve. */
34
+ function partsFormatterFor(timeZone) {
35
+ const cached = PARTS_FORMATTERS.get(timeZone);
36
+ if (cached !== undefined) return cached;
37
+ let formatter;
38
+ try {
39
+ formatter = new Intl.DateTimeFormat('en-US', {
40
+ timeZone,
41
+ hourCycle: 'h23',
42
+ year: 'numeric',
43
+ month: '2-digit',
44
+ day: '2-digit',
45
+ hour: '2-digit',
46
+ minute: '2-digit',
47
+ second: '2-digit',
48
+ });
49
+ } catch {
50
+ formatter = null;
51
+ }
52
+ PARTS_FORMATTERS.set(timeZone, formatter);
53
+ return formatter;
54
+ }
55
+
56
+ /**
57
+ * The local calendar fields one instant reads in one zone. `hourCycle: 'h23'` matters: without it
58
+ * midnight can format as `24`, which would land a candidate a day out.
59
+ */
60
+ function localParts(ts, timeZone) {
61
+ const formatter = partsFormatterFor(timeZone);
62
+ if (!formatter) return undefined;
63
+ const fields = {};
64
+ for (const part of formatter.formatToParts(Math.floor(ts / 1000) * 1000)) {
65
+ if (part.type !== 'literal') fields[part.type] = Number(part.value);
66
+ }
67
+ return {
68
+ year: fields.year,
69
+ month: fields.month,
70
+ day: fields.day,
71
+ hour: fields.hour,
72
+ minute: fields.minute,
73
+ second: fields.second,
74
+ };
75
+ }
76
+
77
+ /** A provider this engine can schedule, or `undefined`: a malformed one is never reasoned about. */
78
+ function scheduledProvider(provider) {
79
+ if (provider === null || typeof provider !== 'object') return undefined;
80
+ if (typeof provider.zone !== 'string' || provider.zone.length === 0) return undefined;
81
+ if (!Array.isArray(provider.windows)) return undefined;
82
+ if (!partsFormatterFor(provider.zone)) return undefined;
83
+ return provider;
84
+ }
85
+
86
+ /** The offset of a zone at one instant, as `local wall clock - UTC`, in milliseconds. */
87
+ function zoneOffsetAt(ts, timeZone) {
88
+ const parts = localParts(ts, timeZone);
89
+ const wall = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);
90
+ return wall - Math.floor(ts / 1000) * 1000;
91
+ }
92
+
93
+ /**
94
+ * The instant at which one local wall hour starts in one zone: the two-pass offset correction. The
95
+ * first pass treats the wall clock as UTC, the second applies the offset in force at the instant
96
+ * the first pass landed on, so a wall hour on either side of a DST switch converts exactly.
97
+ */
98
+ function localHourInstant(timeZone, year, month, day, hour) {
99
+ const wall = Date.UTC(year, month - 1, day, hour, 0, 0);
100
+ const firstPass = wall - zoneOffsetAt(wall, timeZone);
101
+ return wall - zoneOffsetAt(firstPass, timeZone);
102
+ }
103
+
104
+ /** The provider's own weekday for a local calendar date. */
105
+ function isLocalWeekday({ year, month, day }) {
106
+ const weekday = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
107
+ return weekday !== 0 && weekday !== 6;
108
+ }
109
+
110
+ function inAnyWindow(windows, minute) {
111
+ return windows.some(([startHour, endHour]) => minute >= startHour * 60 && minute < endHour * 60);
112
+ }
113
+
114
+ /** The schedule predicate itself, evaluated at one instant in the provider's own zone. */
115
+ function isPeakInstant(provider, ts) {
116
+ if (provider.weekdaysOnly === true && !isLocalWeekday(localParts(ts, provider.zone))) return false;
117
+ const parts = localParts(ts, provider.zone);
118
+ return inAnyWindow(provider.windows, parts.hour * 60 + parts.minute);
119
+ }
120
+
121
+ /**
122
+ * Every instant that could be a transition: both edges of every window across the next ten LOCAL
123
+ * days of the provider's zone. Weekends produce candidates too; they are dropped by the transition
124
+ * test in `nextTransitionFor`, which is what keeps a Saturday 05:00 Pacific from being reported as
125
+ * a change.
126
+ */
127
+ function candidateInstants(provider, now) {
128
+ const today = localParts(now, provider.zone);
129
+ const instants = [];
130
+ for (let offset = 0; offset < CANDIDATE_DAYS; offset++) {
131
+ // Normalising through `Date.UTC` is what rolls the local date over a month or a year boundary.
132
+ const date = new Date(Date.UTC(today.year, today.month - 1, today.day + offset));
133
+ const year = date.getUTCFullYear();
134
+ const month = date.getUTCMonth() + 1;
135
+ const day = date.getUTCDate();
136
+ for (const [startHour, endHour] of provider.windows) {
137
+ instants.push(localHourInstant(provider.zone, year, month, day, startHour));
138
+ instants.push(localHourInstant(provider.zone, year, month, day, endHour));
139
+ }
140
+ }
141
+ return instants;
142
+ }
143
+
144
+ /**
145
+ * The next instant at which the schedule actually flips. A candidate counts only when the predicate
146
+ * disagrees across it by one millisecond, so the answer is the end of the current state whether that
147
+ * state is a peak window or an off-peak gap that spans a weekend.
148
+ */
149
+ function nextTransitionFor(provider, now) {
150
+ const scheduled = scheduledProvider(provider);
151
+ if (!scheduled || !Number.isFinite(now)) return 0;
152
+ let next = now + CANDIDATE_DAYS * MS_PER_DAY;
153
+ for (const instant of candidateInstants(scheduled, now)) {
154
+ if (instant <= now || instant >= next) continue;
155
+ if (isPeakInstant(scheduled, instant - 1) !== isPeakInstant(scheduled, instant)) next = instant;
156
+ }
157
+ return next;
158
+ }
159
+
160
+ /**
161
+ * Whether `now` falls in a provider's peak window, and when that answer changes. An instant or a
162
+ * provider that cannot be read is off-peak with no boundary (`until: 0`), never a throw: a schedule
163
+ * is drawn above a live editor and must not be able to break it.
164
+ */
165
+ function peakStateFor(provider, now) {
166
+ const scheduled = scheduledProvider(provider);
167
+ if (!scheduled || !Number.isFinite(now)) return { kind: 'off-peak', until: 0 };
168
+ const kind = isPeakInstant(scheduled, now) ? 'peak' : 'off-peak';
169
+ return { kind, until: nextTransitionFor(scheduled, now) };
170
+ }
171
+
172
+ /**
173
+ * The nearest boundary among several providers' states: the smallest `until` of the states that are
174
+ * peak. `Infinity` when nothing is peaking, so one timer can wait for the first window that closes
175
+ * instead of one timer per provider — which is what lets two rows appear and disappear together
176
+ * without polling between boundaries.
177
+ */
178
+ function earliestUntil(states) {
179
+ let earliest = Number.POSITIVE_INFINITY;
180
+ if (!Array.isArray(states)) return earliest;
181
+ for (const state of states) {
182
+ if (state === null || typeof state !== 'object' || state.kind !== 'peak') continue;
183
+ const until = state.until;
184
+ if (typeof until === 'number' && until < earliest) earliest = until;
185
+ }
186
+ return earliest;
187
+ }
188
+
189
+ /**
190
+ * A compact remaining time, in the same shape the shell uses for quota resets. Rounds up, so a live
191
+ * window never reads as already over.
192
+ */
193
+ function formatCountdown(milliseconds) {
194
+ if (!Number.isFinite(milliseconds) || milliseconds <= 0) return 'now';
195
+ const minutes = Math.ceil(milliseconds / MINUTE_MS);
196
+ if (minutes < 60) return `${minutes}m`;
197
+ const hours = Math.floor(minutes / 60);
198
+ const restMinutes = minutes % 60;
199
+ if (hours < 24) return restMinutes === 0 ? `${hours}hr` : `${hours}hr ${restMinutes}m`;
200
+ const days = Math.floor(hours / 24);
201
+ const restHours = hours % 24;
202
+ return restHours === 0 ? `${days}d` : `${days}d ${restHours}hr`;
203
+ }
204
+
205
+ /**
206
+ * The next transition as a local clock: `04:00` on the same local date, or `Mon 01:00` when the
207
+ * boundary falls on another one. The instant the schedule actually ends is printed, never a
208
+ * countdown. `timeZone` is optional so a test can pin the locale without freezing the machine's
209
+ * clock.
210
+ */
211
+ function formatBoundaryClock(until, now, timeZone) {
212
+ if (!Number.isFinite(until) || !Number.isFinite(now)) return 'now';
213
+ const boundary = new Date(until);
214
+ const clock = new Intl.DateTimeFormat('en-US', {
215
+ hour: '2-digit',
216
+ minute: '2-digit',
217
+ hour12: false,
218
+ timeZone,
219
+ }).format(boundary);
220
+ const localDate = (instant) =>
221
+ new Intl.DateTimeFormat('en-US', { year: 'numeric', month: '2-digit', day: '2-digit', timeZone }).format(instant);
222
+ if (localDate(boundary) === localDate(new Date(now))) return clock;
223
+ const weekday = new Intl.DateTimeFormat('en-US', { weekday: 'short', timeZone }).format(boundary);
224
+ return `${weekday} ${clock}`;
225
+ }
226
+
227
+ /**
228
+ * `peak 20m` or `off-peak 3hr 20m`: the state, then the time left in it, with no word between and no
229
+ * colour.
230
+ */
231
+ function formatPeakState(state, now) {
232
+ return `${state.kind} ${formatCountdown(state.until - now)}`;
233
+ }
234
+
235
+ module.exports = {
236
+ peakStateFor,
237
+ nextTransitionFor,
238
+ earliestUntil,
239
+ formatCountdown,
240
+ formatBoundaryClock,
241
+ formatPeakState,
242
+ };
@@ -28,7 +28,14 @@
28
28
  // rebuilt from its OWN constructor with the user message background dropped
29
29
  // (`bgColor: undefined`), no side padding (the frame is the padding) and the host's own
30
30
  // `options`, so `preserveOrderedListMarkers`, `preserveBackslashEscapes` and every
31
- // extension markdown transformer keep working. Its rows arrive ALREADY PAINTED, so they
31
+ // extension markdown transformer keep working. THE ONE EXCEPTION is the prompt mark an
32
+ // extension transformer prepends to a user message (pi-pretty's ` ❯ ${markdown}`): the
33
+ // clone's `transform` wraps the host's own and drops exactly ONE leading `" ❯ "` from its
34
+ // answer (`undecoratedOptions`), so the body re-wraps at the frame's full inner width
35
+ // instead of carrying a mark nothing indents the lines under — and a person who typed `❯`
36
+ // themselves keeps their own character, because that run arrives after the decoration. The
37
+ // component's own `text` is never rewritten, and a prompt no transformer decorated is drawn
38
+ // byte for byte as before. Its rows arrive ALREADY PAINTED, so they
32
39
  // are placed with `cardPaintedRows` — never `cardBodyRows`, which paints a role over
33
40
  // them and would destroy the ANSI. The text colour stays exactly what the body's own
34
41
  // paint says.
@@ -170,6 +177,45 @@ function readTheme(seam) {
170
177
 
171
178
  // ---- the body: Pi's own Markdown, rebuilt without the user message background (S5) ----
172
179
 
180
+ // The prompt mark an extension markdown transformer prepends to a user message — pi-pretty's
181
+ // ` ❯ ${markdown}` (`@heyhuynhgiabuu/pi-pretty`): one leading space, the mark, and the space after
182
+ // it. It is a decoration of the WHOLE message, not of its first line, and nothing indents the
183
+ // lines under it, so a wrapped prompt reads flush left below a marked first row. This card drops
184
+ // it (the user's decision: "Sacar el ❯ del mensaje").
185
+ const PROMPT_MARK = ' ❯ ';
186
+
187
+ /**
188
+ * The host Markdown `options` the card's clone is built with: the host's own object, untouched,
189
+ * when it carries no `transform`; otherwise a shallow copy whose `transform` is the host's own
190
+ * composed transform with ONE leading prompt mark removed from its answer.
191
+ *
192
+ * WHY A WRAPPER AND NOT TEXT SURGERY: the mark lives in the TRANSFORM's output, not in the
193
+ * component's `text` (`user-message.js` builds the Markdown with `transform:
194
+ * createMarkdownTransform("user", …)`, which is where every `registerMarkdownTransformer`
195
+ * lands), so the clone is the one place the host's text arrives before it is parsed and wrapped.
196
+ * Calling the host transform first and dropping the mark from what it returns keeps every other
197
+ * transformer, every markdown construct and the clone's own re-wrap at the full inner width
198
+ * intact: no ANSI is rewritten and no row is measured twice.
199
+ *
200
+ * ONLY THE DECORATION IS CONSUMED: the extension prepends its mark to the user's own markdown, so
201
+ * the decoration is always the OUTERMOST prefix and a person who typed `❯` themselves keeps
202
+ * their own character — their run arrives AFTER the decoration, and at most one leading run is
203
+ * ever dropped. A prompt the transform did not decorate is handed back exactly as it came, so a
204
+ * host with no transformer (or one that adds no mark) draws the same rows it always did.
205
+ */
206
+ function undecoratedOptions(options) {
207
+ if (typeof asObject(options).transform !== 'function') return options;
208
+ const transform = options.transform;
209
+ return {
210
+ ...options,
211
+ transform: (text, availableWidth) => {
212
+ const transformed = transform(text, availableWidth);
213
+ if (typeof transformed !== 'string' || !transformed.startsWith(PROMPT_MARK)) return transformed;
214
+ return transformed.slice(PROMPT_MARK.length);
215
+ },
216
+ };
217
+ }
218
+
173
219
  /**
174
220
  * The child's own Markdown as a clone with no background and no padding at all, or `undefined`
175
221
  * when the shape is not Pi's Markdown — a missing child, a non-numeric `paddingX`, no theme,
@@ -218,7 +264,7 @@ function promptMarkdown(child, paint) {
218
264
  0,
219
265
  child.theme,
220
266
  { ...asObject(child.defaultTextStyle), bgColor: undefined },
221
- child.options,
267
+ undecoratedOptions(child.options),
222
268
  );
223
269
  } catch {
224
270
  return undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-odd-worktree",
3
- "version": "3.14.0",
3
+ "version": "3.15.1",
4
4
  "description": "Pi package for odd-worktree: the Git worktree tools a Pi session uses (create and list the checkouts the agent works in), the /warp worktree panel, the /odd ODD viewer, and the /issues GitHub issue reader. Needs only Pi and git: no companion app, no extra service.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -0,0 +1,140 @@
1
+ 'use strict';
2
+ // S5/S8 (opencode-usage-alert): the stored booleans behind the `Alert` page. ONE boolean
3
+ // per peak provider, all Off by default, in this package's own bridge store
4
+ // (`odd-worktree` → `alerts` → `{ peaks: { [providerId]: boolean } }`). An absent or
5
+ // unparsable document, a missing or throwing store, no bridge at all and an id that was
6
+ // never written all answer Off, and nothing is written until a line is touched. Nothing
7
+ // here loads the extension.
8
+ const { test, describe } = require('node:test');
9
+ const assert = require('node:assert/strict');
10
+
11
+ const alertMode = require('../lib/alert-mode.js');
12
+
13
+ // The two providers the registry declares today; this module is keyed by plain ids and
14
+ // does not import the registry itself.
15
+ const DEEPSEEK = 'deepseek';
16
+ const CLAUDE = 'claude';
17
+
18
+ // A bridge whose `createStore` keeps one in-memory file per plugin id, like the real one.
19
+ function fakeBridge(initial = {}) {
20
+ const files = new Map(Object.entries(initial));
21
+ const writes = [];
22
+ const createStore = (id) => ({
23
+ get: (key, fallback) => (files.get(id)?.[key] !== undefined ? files.get(id)[key] : fallback),
24
+ set: (key, value) => {
25
+ files.set(id, { ...(files.get(id) ?? {}), [key]: value });
26
+ writes.push([id, key, value]);
27
+ },
28
+ });
29
+ return { api: { createStore }, files, writes };
30
+ }
31
+
32
+ describe('the default', () => {
33
+ test('is Off, exported, and is what a first run reads for every provider', () => {
34
+ assert.equal(alertMode.DEFAULT_PEAK, false);
35
+ const { api } = fakeBridge();
36
+ assert.equal(alertMode.readPeakAlert(api, DEEPSEEK), false);
37
+ assert.equal(alertMode.readPeakAlert(api, CLAUDE), false);
38
+ });
39
+
40
+ test('the store key is exported and is the bridge document the switches share', () => {
41
+ assert.equal(alertMode.ALERTS_KEY, 'alerts');
42
+ });
43
+ });
44
+
45
+ describe('reading one provider', () => {
46
+ test('Off for an absent document, for every malformed one, and for a document without `peaks`', () => {
47
+ assert.equal(alertMode.readPeakAlert(fakeBridge({ 'odd-worktree': {} }).api, DEEPSEEK), false);
48
+ for (const bad of [null, 42, 'off', [], { peaks: 'no' }, { peaks: 7 }, { peaks: [] }, { peaks: null }]) {
49
+ const { api } = fakeBridge({ 'odd-worktree': { alerts: bad } });
50
+ assert.equal(alertMode.readPeakAlert(api, DEEPSEEK), false, JSON.stringify(bad));
51
+ assert.equal(alertMode.readPeakAlert(api, CLAUDE), false, JSON.stringify(bad));
52
+ }
53
+ assert.equal(alertMode.readPeakAlert(fakeBridge({ 'odd-worktree': { alerts: { other: 1 } } }).api, DEEPSEEK), false);
54
+ });
55
+
56
+ test('an id that was never written is Off even when a sibling is On', () => {
57
+ const { api } = fakeBridge({ 'odd-worktree': { alerts: { peaks: { [DEEPSEEK]: true } } } });
58
+ assert.equal(alertMode.readPeakAlert(api, DEEPSEEK), true);
59
+ assert.equal(alertMode.readPeakAlert(api, CLAUDE), false);
60
+ assert.equal(alertMode.readPeakAlert(api, 'anthropic'), false);
61
+ });
62
+
63
+ test('each provider answers its own stored boolean', () => {
64
+ for (const peaks of [{ [DEEPSEEK]: false, [CLAUDE]: true }, { [DEEPSEEK]: true, [CLAUDE]: false }]) {
65
+ const { api } = fakeBridge({ 'odd-worktree': { alerts: { peaks } } });
66
+ assert.equal(alertMode.readPeakAlert(api, DEEPSEEK), peaks[DEEPSEEK], JSON.stringify(peaks));
67
+ assert.equal(alertMode.readPeakAlert(api, CLAUDE), peaks[CLAUDE], JSON.stringify(peaks));
68
+ }
69
+ });
70
+
71
+ test('no bridge, no createStore and a throwing store all read Off and never throw', () => {
72
+ for (const api of [null, undefined, {}, 42, { createStore: () => { throw new Error('disk'); } }]) {
73
+ assert.equal(alertMode.readPeakAlert(api, DEEPSEEK), false);
74
+ assert.equal(alertMode.readPeakAlert(api, CLAUDE), false);
75
+ }
76
+ const throwing = { createStore: () => ({ get: () => { throw new Error('disk'); }, set: () => {} }) };
77
+ assert.equal(alertMode.readPeakAlert(throwing, DEEPSEEK), false);
78
+ });
79
+
80
+ test('nothing is written on a read, not even the default', () => {
81
+ const bridge = fakeBridge();
82
+ alertMode.readPeakAlert(bridge.api, DEEPSEEK);
83
+ alertMode.readPeakAlert(bridge.api, CLAUDE);
84
+ assert.deepEqual(bridge.writes, []);
85
+ assert.equal(bridge.files.has('odd-worktree'), false, 'no document appears at load');
86
+ });
87
+ });
88
+
89
+ describe('writing one provider', () => {
90
+ test('On then Off round-trips under `peaks`, and every read answers the value just written', () => {
91
+ const bridge = fakeBridge();
92
+ assert.equal(alertMode.writePeakAlert(bridge.api, DEEPSEEK, true), true);
93
+ assert.equal(alertMode.readPeakAlert(bridge.api, DEEPSEEK), true);
94
+ assert.deepEqual(bridge.files.get('odd-worktree'), { alerts: { peaks: { [DEEPSEEK]: true } } });
95
+ assert.equal(alertMode.writePeakAlert(bridge.api, DEEPSEEK, false), true);
96
+ assert.equal(alertMode.readPeakAlert(bridge.api, DEEPSEEK), false);
97
+ assert.deepEqual(bridge.files.get('odd-worktree'), { alerts: { peaks: { [DEEPSEEK]: false } } });
98
+ });
99
+
100
+ test('one provider\'s write leaves its sibling id exactly as it was', () => {
101
+ const bridge = fakeBridge({ 'odd-worktree': { alerts: { peaks: { [CLAUDE]: true } } } });
102
+ assert.equal(alertMode.writePeakAlert(bridge.api, DEEPSEEK, true), true);
103
+ assert.equal(alertMode.readPeakAlert(bridge.api, DEEPSEEK), true);
104
+ assert.equal(alertMode.readPeakAlert(bridge.api, CLAUDE), true);
105
+ assert.deepEqual(bridge.files.get('odd-worktree'), {
106
+ alerts: { peaks: { [CLAUDE]: true, [DEEPSEEK]: true } },
107
+ });
108
+ });
109
+
110
+ test('keeps every sibling key of the store and of the alerts document', () => {
111
+ const bridge = fakeBridge({ 'odd-worktree': { modules: { worktrees: false }, alerts: { other: 7 } } });
112
+ assert.equal(alertMode.writePeakAlert(bridge.api, CLAUDE, true), true);
113
+ assert.deepEqual(bridge.files.get('odd-worktree'), {
114
+ modules: { worktrees: false },
115
+ alerts: { other: 7, peaks: { [CLAUDE]: true } },
116
+ });
117
+ });
118
+
119
+ test('a malformed document is replaced rather than thrown at', () => {
120
+ const bridge = fakeBridge({ 'odd-worktree': { alerts: 'nope', other: 1 } });
121
+ assert.equal(alertMode.writePeakAlert(bridge.api, DEEPSEEK, true), true);
122
+ assert.deepEqual(bridge.files.get('odd-worktree'), { alerts: { peaks: { [DEEPSEEK]: true } }, other: 1 });
123
+ });
124
+ });
125
+
126
+ describe('a write that cannot be kept', () => {
127
+ test('reports false and never throws — a missing bridge, a throwing store, a throwing set', () => {
128
+ for (const api of [null, undefined, {}, 42, { createStore: () => { throw new Error('disk'); } }]) {
129
+ assert.equal(alertMode.writePeakAlert(api, DEEPSEEK, true), false);
130
+ }
131
+ const throwing = { createStore: () => ({ get: (_key, fallback) => fallback, set: () => { throw new Error('read-only'); } }) };
132
+ assert.equal(alertMode.writePeakAlert(throwing, CLAUDE, true), false);
133
+ });
134
+
135
+ test('a read after a refused write still answers Off, the way it read before the press', () => {
136
+ const throwing = { createStore: () => ({ get: (_key, fallback) => fallback, set: () => { throw new Error('read-only'); } }) };
137
+ assert.equal(alertMode.writePeakAlert(throwing, DEEPSEEK, true), false);
138
+ assert.equal(alertMode.readPeakAlert(throwing, DEEPSEEK), false);
139
+ });
140
+ });