@clothespin/pi-pippi 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/claims.ts ADDED
@@ -0,0 +1,453 @@
1
+ /**
2
+ * The claim board: who is allowed to connect to the pippi, decided by mtime.
3
+ *
4
+ * Two pi windows on one machine can each decide the pippi is theirs, and neither
5
+ * can see it in the radio. BlueZ hands the ACL to whoever asks and leaves the
6
+ * incumbent's connection alone, so a displaced session keeps a green status light,
7
+ * keeps pushing snapshots at a device it is not attached to, and queues approval
8
+ * prompts nobody there will ever answer. The bridge needs to know that for two
9
+ * reasons: an approval that will never be seen should be asked in the terminal
10
+ * instead, and a window that is not the leader has no business reconnecting to the
11
+ * pippi behind anyone's back.
12
+ *
13
+ * The protocol is a directory of files named by pid, with three rules:
14
+ *
15
+ * touch $BOARD/$PPID on human input, unconditionally
16
+ * before claiming am I the newest stamp in there?
17
+ * if not stand down, and wait to be typed at
18
+ *
19
+ * The directory is the state, so a session keeps none: there is no token to hand
20
+ * back, no lease to expire, nothing to clean up after a crash. A dead process
21
+ * cannot touch its file again, so it ages out of contention by itself -- mtime
22
+ * moves one way only, and moving it takes being alive and being typed at. Put the
23
+ * board on a tmpfs and stale stamps are free to accumulate, because a zombie's
24
+ * stamp can never outrank a live session's.
25
+ *
26
+ * Which is why the check reads `mtime` and not birth time: birth time never moves,
27
+ * so a session stamping its file again -- which is the protocol, and the only way a
28
+ * window takes the pippi back -- would be invisible to it, and whoever typed first
29
+ * would win forever. Not because birth time is unavailable: on this machine's tmpfs
30
+ * `stat -c %W` reports a real creation time, so "it reads 0 on tmpfs" is true of
31
+ * some systems and load-bearing on none of them.
32
+ *
33
+ * One implementation, and the worker used to be the second voice that needed it:
34
+ * the radio now lives in this process too, so `command()` is the same check as a
35
+ * shell one-liner for anyone watching from outside -- which is the only way to
36
+ * audit a decision made by four pi windows at once.
37
+ */
38
+
39
+ import { mkdirSync, readdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
40
+ import { join } from "node:path";
41
+ import { tmpdir } from "node:os";
42
+
43
+ /**
44
+ * How far apart two stamps have to be to count as different claims.
45
+ *
46
+ * Zero, which took some being talked into. A one-second tolerance feels safer than
47
+ * a clock that resolves to nanoseconds, and it is -- in the wrong direction. With a
48
+ * tolerance, two windows typed into a second apart are tied, and a tie means
49
+ * neither may claim, so the human's most recent keystroke loses to the older one
50
+ * and the pet sits unclaimed until someone presses Enter a second time. Strict
51
+ * comparison gets that case right, which is the case a human actually creates.
52
+ *
53
+ * What is left is a genuine tie: two `open(O_CREAT|O_TRUNC)` calls close enough to
54
+ * land on the same tick of the clock, which is repeatable from a shell (`touch a &
55
+ * touch b` lands on the same nanosecond here) and not repeatable by a person, who
56
+ * types in one window at a time. Ties go to the higher pid -- arbitrary, because it
57
+ * can afford to be. It needs no negotiation, both sessions read the same answer off
58
+ * the same directory listing, and the next keystroke anywhere reorders the board and
59
+ * corrects whatever it decided.
60
+ */
61
+ const TIE_MS = 0;
62
+
63
+ /**
64
+ * How old a rival's stamp can be and still count as a claim on the pippi.
65
+ *
66
+ * Liveness is the real test -- a process that no longer exists cannot take the pet,
67
+ * and one crash would otherwise freeze every other window out permanently, since
68
+ * nothing is coming to clean a tmpfs and mtime moves one way only. This is the
69
+ * belt to that pair of suspenders: a stamp older than this is not evidence of a
70
+ * claim even if its pid happens to exist, which covers a pid recycled by an
71
+ * unrelated process and a board mounted somewhere that survives reboots.
72
+ */
73
+ const RIVAL_TTL_MS = 300_000;
74
+
75
+ export interface BoardConfig {
76
+ /** Where the stamps live. A tmpfs by default, so nothing needs cleanup. */
77
+ dir: string;
78
+ /** The process a stamp is named for -- the one a human types into. */
79
+ pid: number;
80
+ /** Rival stamps older than this are debris. */
81
+ rivalTtlMs: number;
82
+ /** A rival this close behind, or ahead, beats us. Zero unless testing. */
83
+ tieMs: number;
84
+ /** How to tell a live session from a stale stamp. Injectable for tests, which
85
+ * invent pids and cannot arrange for them to exist. */
86
+ isAlive: (pid: number) => boolean;
87
+ /**
88
+ * How long a mask means anything: the approval timeout, which every party on this
89
+ * machine is configured with and which is therefore the length of the question the
90
+ * mask is standing in for. See MASK_NAME for the subtraction.
91
+ */
92
+ maskTtlMs: number;
93
+ }
94
+
95
+ export function defaultBoardDir(): string {
96
+ // Its own override first, then the directory the bridges already share so a
97
+ // deployment that relocates the pippi's state moves the board with it.
98
+ return (
99
+ process.env.PI_PIPPI_CLAIM_DIR ??
100
+ process.env.PI_PIPPI_STATE_DIR ??
101
+ join(tmpdir(), "pi-pippi-claims")
102
+ );
103
+ }
104
+
105
+ /** Is `pid` a process that could still act? */
106
+ export function alive(pid: number): boolean {
107
+ if (pid === process.pid) return true;
108
+ try {
109
+ process.kill(pid, 0);
110
+ return true;
111
+ } catch (error) {
112
+ // EPERM means it exists and belongs to someone else, which is still alive.
113
+ return (error as NodeJS.ErrnoException).code === "EPERM";
114
+ }
115
+ }
116
+
117
+ /** Who is not allowed to take the link, and why. */
118
+ export type Verdict =
119
+ | { allowed: true }
120
+ | { allowed: false; reason: "masked" | "stale"; beatenBy: number; ageMs: number };
121
+
122
+ /**
123
+ * The mask: one file, not named by pid, held by whichever session has an approval
124
+ * prompt on the screen.
125
+ *
126
+ * An approval is the one claim that cannot wait and the one thing that must not be
127
+ * interrupted: a tool call is parked, the question is drawn on the pet, and a second
128
+ * session taking the link does not merely move the pet -- it moves the question, and
129
+ * the first session finds out its prompt is gone with a tool call that has been
130
+ * waiting a minute for an answer nobody was offered. So while one is open, claims are
131
+ * masked, which is what two windows asking at once needs in order to be one question
132
+ * at a time rather than two fights.
133
+ *
134
+ * Like the stamps it is a fact about a directory and not a lock anyone holds, and it is
135
+ * read the same way every party reads it: the mtime is when the question started, the
136
+ * approval timeout is a constant both processes are configured with, and
137
+ *
138
+ * [ $(($(date +%s) - $(stat -c %Y "$LOCKDIR/APPROVAL"))) -gt $TIMEOUT ]
139
+ *
140
+ * says whether the question is still a question. That is the whole protocol, which is
141
+ * why there is nothing to hand back, nothing to time out on this session's clock, and
142
+ * nothing a crashed session can leave behind: a mask whose owner died stops being a
143
+ * mask by subtraction, and the pippi comes back around by itself.
144
+ *
145
+ * It is also why the mask is written once and never refreshed. Refreshing it moves the
146
+ * start time, and a start time that moves is a deadline that never arrives -- an
147
+ * approval would outlive its own timeout and keep every other window off the pippi for
148
+ * as long as it kept breathing.
149
+ */
150
+ const MASK_NAME = "APPROVAL";
151
+
152
+
153
+ /** One session's stamp: who, and when they were last asked for the pippi. */
154
+ interface Stamp {
155
+ pid: number;
156
+ at: number;
157
+ }
158
+
159
+ /**
160
+ * Is `own` ahead of `rival`? Ties go to the higher pid, which both sessions compute
161
+ * the same way off the same directory listing: the requirement is that a tie has one
162
+ * answer, not which answer it gets. A tie is not expected -- one human types into one
163
+ * window, and two `touch`es landing in the same clock tick would need a keystroke in
164
+ * each of them inside the same millisecond. The rule stays because a comparison that
165
+ * had no answer for its boundary case would be the one place two sessions could
166
+ * disagree, and the whole value of the board is that they cannot.
167
+ */
168
+ function beats(own: Stamp, rival: Stamp, tieMs: number): boolean {
169
+ if (rival.at < own.at + tieMs) return true;
170
+ return rival.at === own.at && own.pid > rival.pid;
171
+ }
172
+
173
+ export class ClaimBoard {
174
+ private dir: string;
175
+ /**
176
+ * How long a mask is believed after its last refresh, which the bridge sets to the
177
+ * approval timeout it is running: that is the longest a question can still be on the
178
+ * screen, so it is the longest a mask without a refresh means anything.
179
+ */
180
+ maskTtlMs: number;
181
+ /** The mtime our own mask was written with, which is how a release knows whose it is. */
182
+ private maskWritten: number | undefined = undefined;
183
+ private pid: number;
184
+ private rivalTtlMs: number;
185
+ private tieMs: number;
186
+ private isAlive: (pid: number) => boolean;
187
+ private warned = false;
188
+
189
+ /** Set by the bridge to surface what the board thinks to a human. */
190
+ onLog: ((level: "info" | "warn", message: string) => void) | undefined = undefined;
191
+
192
+ constructor(config: Partial<BoardConfig> = {}) {
193
+ this.dir = config.dir ?? defaultBoardDir();
194
+ // `approvalTimeoutMs: 0` means the prompt waits forever, so the mask cannot be
195
+ // aged out by that number; the stamp TTL is the next best ceiling, and liveness is
196
+ // what actually retires a mask whose holder is gone.
197
+ this.maskTtlMs = config.maskTtlMs ?? RIVAL_TTL_MS;
198
+ // One pid per process, which is the whole point: the keystroke and the claim
199
+ // are made by the same hand now, and pi's exit is the thing that retires the
200
+ // stamp. Two pi sessions in one terminal are two pids, so they are two lines.
201
+ this.pid = config.pid ?? process.pid;
202
+ this.rivalTtlMs = config.rivalTtlMs ?? RIVAL_TTL_MS;
203
+ this.tieMs = config.tieMs ?? TIE_MS;
204
+ this.isAlive = config.isAlive ?? alive;
205
+ try {
206
+ mkdirSync(this.dir, { recursive: true });
207
+ } catch {
208
+ // Reported by the first touch() that fails, which is the first moment there is
209
+ // somebody listening: onLog is wired after construction, and a board nobody was
210
+ // told about has not cost anyone anything yet.
211
+ }
212
+ }
213
+
214
+ private warn(message: string): void {
215
+ if (this.warned) return;
216
+ this.warned = true;
217
+ this.onLog?.("warn", message);
218
+ }
219
+
220
+ /** Where this board lives, which is how a caller notices it is a different one. */
221
+ get dirPath(): string {
222
+ return this.dir;
223
+ }
224
+
225
+ /**
226
+ * The file this session stamps. Public so a test can age a stamp on purpose --
227
+ * "older than another session's" is the whole protocol, and a test that waited
228
+ * out a real clock to make one would take seconds and still be flaky.
229
+ */
230
+ pathFor(pid: number = this.pid): string {
231
+ return this.file(pid);
232
+ }
233
+
234
+ private file(pid: number): string {
235
+ return join(this.dir, String(pid));
236
+ }
237
+
238
+ // ---------------------------------------------------------------- the mask
239
+
240
+ /**
241
+ * Ask for the mask: this session has a question on the pet, and claims from
242
+ * elsewhere should stop while it is there. There is nothing to win -- a mask is a
243
+ * statement about what is on the screen, and every session reading it sees the same
244
+ * one -- so this is a write, not a negotiation, and two windows that ask in the same
245
+ * instant both see whichever mtime landed last. Neither is wrong: the question that
246
+ * is on the pet is the one the snapshot put there, and both windows compute the same
247
+ * deadline from the same file.
248
+ */
249
+ touchMask(): void {
250
+ try {
251
+ writeFileSync(this.maskFile(), `${this.pid}\n`);
252
+ this.maskWritten = statSync(this.maskFile()).mtimeMs;
253
+ } catch (error) {
254
+ this.warn(`could not take the approval mask (${String(error)})`);
255
+ }
256
+ }
257
+
258
+ /**
259
+ * Put the mask down, if it is still the one we put up. A session that was masked by
260
+ * another, then took over, must not have its mask removed by the first one
261
+ * finishing -- so the match is on the mtime we wrote, not on the name of the file.
262
+ */
263
+ clearMask(): void {
264
+ if (this.maskWritten === undefined) return;
265
+ const written = this.maskWritten;
266
+ this.maskWritten = undefined;
267
+ try {
268
+ if (statSync(this.maskFile()).mtimeMs === written) unlinkSync(this.maskFile());
269
+ } catch {
270
+ // Already gone, which is the same outcome.
271
+ }
272
+ }
273
+
274
+ /** A question open in another session, with how long ago it was refreshed. */
275
+ maskHeld(now: number = Date.now()): { ageMs: number } | undefined {
276
+ let at: number;
277
+ try {
278
+ at = statSync(this.maskFile()).mtimeMs;
279
+ } catch {
280
+ return undefined; // no mask, or no board: either way nothing is masked
281
+ }
282
+ const ageMs = now - at;
283
+ return ageMs <= this.maskTtlMs ? { ageMs } : undefined;
284
+ }
285
+
286
+ /** Is the mask ours? (A holder is never masked by its own question.) */
287
+ holdsMask(): boolean {
288
+ return this.maskWritten !== undefined;
289
+ }
290
+
291
+ maskPath(): string {
292
+ return this.maskFile();
293
+ }
294
+
295
+ /**
296
+ * Who wrote the mask, for a message to a human. Best effort on purpose: the answer
297
+ * is a name in a sentence, the decision above is made from the mtime alone, and a
298
+ * file that is being rewritten as we read it must never be able to change one into
299
+ * the other.
300
+ */
301
+ maskOwner(): number {
302
+ try {
303
+ const pid = Number(readFileSync(this.maskFile(), "utf8").trim());
304
+ return Number.isInteger(pid) && pid > 0 ? pid : -1;
305
+ } catch {
306
+ return -1;
307
+ }
308
+ }
309
+
310
+ private maskFile(): string {
311
+ return join(this.dir, MASK_NAME);
312
+ }
313
+
314
+ /**
315
+ * Say this session wanted the pippi, now. Called on human input, before anything
316
+ * else is known.
317
+ *
318
+ * False means the stamp is not there: the board refused the write. That is not a
319
+ * fault to work around -- a claim *is* this date, so a session that could not write
320
+ * one has failed to acquire the claim and must not act as though it had. The
321
+ * refusal may well be the filesystem doing its job against a concurrent write; the
322
+ * response is the same either way: yield, and let the next keystroke try again.
323
+ */
324
+ touch(): boolean {
325
+ try {
326
+ // Truncate rather than utimensat: it creates the file when missing, and the
327
+ // contents never matter, so there is no half-written state a concurrent reader
328
+ // could mistake for something.
329
+ writeFileSync(this.file(this.pid), "");
330
+ return true;
331
+ } catch (error) {
332
+ this.warn(`could not stamp the claim board (${String(error)}); not claiming`);
333
+ return false;
334
+ }
335
+ }
336
+
337
+ /** Every stamp on the board, newest last. Dead pids are still listed. */
338
+ private stamps(): Stamp[] {
339
+ let names: string[];
340
+ try {
341
+ names = readdirSync(this.dir);
342
+ } catch {
343
+ return [];
344
+ }
345
+ const out: Stamp[] = [];
346
+ for (const name of names) {
347
+ const pid = Number(name);
348
+ if (!Number.isInteger(pid) || pid <= 0) continue; // not a pid, not a claim
349
+ try {
350
+ const stat = statSync(this.file(pid));
351
+ // A directory is not a session, whatever it is named: the board shares a tmpfs
352
+ // with everything else a process leaves behind.
353
+ if (!stat.isFile()) continue;
354
+ out.push({ pid, at: stat.mtimeMs });
355
+ } catch {
356
+ // Retired between listing and stat.
357
+ }
358
+ }
359
+ out.sort((a, b) => a.at - b.at);
360
+ return out;
361
+ }
362
+
363
+ /**
364
+ * May this session claim the pippi? False names the process that got there
365
+ * first: a human decision made in a window this one cannot see, which is exactly
366
+ * the thing no part of the radio stack will report.
367
+ *
368
+ * Our own stamp is the floor, not a tiebreaker, and having no stamp at all is the
369
+ * oldest position on the board rather than a free pass: a session that has never
370
+ * been typed at has no claim on the pippi. Stamps landing on exactly the same
371
+ * instant go to the higher pid -- a case one human cannot produce, kept so that the
372
+ * comparison is total; see `beats`.
373
+ */
374
+ check(): Verdict {
375
+ const now = Date.now();
376
+ // A question on the screen first: it is what the mask is for, and the ordering is
377
+ // the point -- a claim that has to wait for an answer is a claim that would have
378
+ // stolen the answer.
379
+ const mask = this.maskHeld(now);
380
+ if (mask !== undefined && !this.holdsMask()) {
381
+ return { allowed: false, reason: "masked", beatenBy: this.maskOwner(), ageMs: mask.ageMs };
382
+ }
383
+ const stamps = this.stamps();
384
+ const own = stamps.find((s) => s.pid === this.pid);
385
+ const rivals = stamps.filter(
386
+ (s) =>
387
+ s.pid !== this.pid &&
388
+ now - s.at <= this.rivalTtlMs &&
389
+ // A stamp from a dead session is not a claim, and treating it as one is how
390
+ // a window that was killed instead of quit keeps the pippi from everyone.
391
+ this.isAlive(s.pid),
392
+ );
393
+ const newest = rivals[rivals.length - 1];
394
+ if (newest === undefined) return { allowed: true };
395
+ if (own !== undefined && beats(own, newest, this.tieMs)) return { allowed: true };
396
+ return { allowed: false, reason: "stale", beatenBy: newest.pid, ageMs: now - newest.at };
397
+ }
398
+
399
+ /**
400
+ * Who touched last among the living -- what the bridge asks when a reclaim loop
401
+ * has to be broken, since it is the only way to name the window that should be
402
+ * told to stop and the one that should be told to go without either session being
403
+ * inside the other's decision.
404
+ */
405
+ leader(): number | undefined {
406
+ // The same evidence check() uses, so that the answer the bridge reads out of the
407
+ // board -- who to tell to stop, who to tell to go -- is the answer the sessions
408
+ // themselves are acting on. Freshness and liveness both, not either: a stamp in
409
+ // the TTL from a dead process is debris, and a live process that has not been
410
+ // asked for the pippi in five minutes is not claiming it.
411
+ const now = Date.now();
412
+ const live = this.stamps().filter(
413
+ (s) => now - s.at <= this.rivalTtlMs && this.isAlive(s.pid),
414
+ );
415
+ return live[live.length - 1]?.pid;
416
+ }
417
+
418
+ /**
419
+ * Has a human ever asked for the pippi in this session? Not "may I claim" --
420
+ * `check()` answers that -- but whether there is a claim here at all. A session
421
+ * that has never been typed at has nothing to spend on taking the pet back after
422
+ * it fell over by itself, however much it would like to.
423
+ */
424
+ hasOwnStamp(): boolean {
425
+ try {
426
+ return statSync(this.file(this.pid)).isFile();
427
+ } catch {
428
+ return false;
429
+ }
430
+ }
431
+
432
+ /** Stop counting as a rival. Ours only: we have no authority over a stamp we did not make. */
433
+ retire(): void {
434
+ try {
435
+ unlinkSync(this.file(this.pid));
436
+ } catch {
437
+ // Already gone, which is the same outcome.
438
+ }
439
+ }
440
+
441
+ /**
442
+ * The same check as the shell one-liner it was specced as, kept here so the two
443
+ * cannot drift apart on what the protocol means -- and corrected in two places
444
+ * worth knowing about. `find -printf %T@` is mtime, not `%W@` (birth time never
445
+ * moves, so a claim could never be renewed), and `%f` is a basename where
446
+ * `stat -c %n` on a directory would print the directory's own path: written that
447
+ * way the test compares a path to a pid, answers "no" forever, and every session
448
+ * on the machine stands down over a pet nobody is holding.
449
+ */
450
+ command(): string {
451
+ return `[[ $(find ${this.dir} -maxdepth 1 -type f -printf '%T@ %f\n' 2>/dev/null | sort -nr | head -n1 | awk '{print $2}') == $$ ]]`;
452
+ }
453
+ }