cursedbelt 2.6.1 → 2.8.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.
Files changed (90) hide show
  1. package/dist/core/file-tree/fileTreeModel.d.ts +18 -0
  2. package/dist/core/file-tree/fileTreeModel.d.ts.map +1 -1
  3. package/dist/core/file-tree/fileTreeModel.js +24 -0
  4. package/dist/core/file-tree/fileTreeModel.js.map +1 -1
  5. package/dist/react/components/TagsInput.d.ts +8 -1
  6. package/dist/react/components/TagsInput.d.ts.map +1 -1
  7. package/dist/react/components/TagsInput.js +10 -4
  8. package/dist/react/components/TagsInput.js.map +1 -1
  9. package/dist/react/file-tree/FileTree.d.ts +14 -2
  10. package/dist/react/file-tree/FileTree.d.ts.map +1 -1
  11. package/dist/react/file-tree/FileTree.js +3 -9
  12. package/dist/react/file-tree/FileTree.js.map +1 -1
  13. package/dist/react/file-tree/index.d.ts +1 -1
  14. package/dist/react/file-tree/index.d.ts.map +1 -1
  15. package/dist/react/file-tree/index.js +1 -1
  16. package/dist/react/file-tree/index.js.map +1 -1
  17. package/dist/server/sync/alarm.d.ts +35 -0
  18. package/dist/server/sync/alarm.d.ts.map +1 -0
  19. package/dist/server/sync/alarm.js +92 -0
  20. package/dist/server/sync/alarm.js.map +1 -0
  21. package/dist/server/sync/commands.d.ts +88 -0
  22. package/dist/server/sync/commands.d.ts.map +1 -0
  23. package/dist/server/sync/commands.js +242 -0
  24. package/dist/server/sync/commands.js.map +1 -0
  25. package/dist/server/sync/engine.d.ts +63 -0
  26. package/dist/server/sync/engine.d.ts.map +1 -0
  27. package/dist/server/sync/engine.js +185 -0
  28. package/dist/server/sync/engine.js.map +1 -0
  29. package/dist/server/sync/http.d.ts +107 -0
  30. package/dist/server/sync/http.d.ts.map +1 -0
  31. package/dist/server/sync/http.js +244 -0
  32. package/dist/server/sync/http.js.map +1 -0
  33. package/dist/server/sync/index.d.ts +42 -0
  34. package/dist/server/sync/index.d.ts.map +1 -0
  35. package/dist/server/sync/index.js +42 -0
  36. package/dist/server/sync/index.js.map +1 -0
  37. package/dist/server/sync/opLog.d.ts +62 -0
  38. package/dist/server/sync/opLog.d.ts.map +1 -0
  39. package/dist/server/sync/opLog.js +97 -0
  40. package/dist/server/sync/opLog.js.map +1 -0
  41. package/dist/server/sync/planner.d.ts +32 -0
  42. package/dist/server/sync/planner.d.ts.map +1 -0
  43. package/dist/server/sync/planner.js +31 -0
  44. package/dist/server/sync/planner.js.map +1 -0
  45. package/dist/server/sync/status.d.ts +64 -0
  46. package/dist/server/sync/status.d.ts.map +1 -0
  47. package/dist/server/sync/status.js +50 -0
  48. package/dist/server/sync/status.js.map +1 -0
  49. package/dist/server/sync/timer.d.ts +53 -0
  50. package/dist/server/sync/timer.d.ts.map +1 -0
  51. package/dist/server/sync/timer.js +171 -0
  52. package/dist/server/sync/timer.js.map +1 -0
  53. package/dist/server/sync/tokens.d.ts +26 -0
  54. package/dist/server/sync/tokens.d.ts.map +1 -0
  55. package/dist/server/sync/tokens.js +52 -0
  56. package/dist/server/sync/tokens.js.map +1 -0
  57. package/dist/server/sync/types.d.ts +102 -0
  58. package/dist/server/sync/types.d.ts.map +1 -0
  59. package/dist/server/sync/types.js +30 -0
  60. package/dist/server/sync/types.js.map +1 -0
  61. package/package.json +25 -15
  62. package/scripts/verify.ts +292 -0
  63. package/src/core/file-tree/fileTreeModel.spec.ts +23 -0
  64. package/src/core/file-tree/fileTreeModel.ts +33 -0
  65. package/src/demoFixture.spec.ts +11 -1
  66. package/src/react/components/TagsInput.spec.tsx +34 -0
  67. package/src/react/components/TagsInput.tsx +23 -1
  68. package/src/react/file-tree/FileTree.tsx +19 -11
  69. package/src/react/file-tree/index.ts +2 -0
  70. package/src/server/sync/alarm.spec.ts +149 -0
  71. package/src/server/sync/alarm.ts +137 -0
  72. package/src/server/sync/commands.spec.ts +145 -0
  73. package/src/server/sync/commands.ts +361 -0
  74. package/src/server/sync/engine.spec.ts +496 -0
  75. package/src/server/sync/engine.ts +255 -0
  76. package/src/server/sync/http.ts +316 -0
  77. package/src/server/sync/httpRemote.spec.ts +158 -0
  78. package/src/server/sync/index.ts +90 -0
  79. package/src/server/sync/opLog.spec.ts +110 -0
  80. package/src/server/sync/opLog.ts +189 -0
  81. package/src/server/sync/planner.spec.ts +53 -0
  82. package/src/server/sync/planner.ts +62 -0
  83. package/src/server/sync/status.spec.ts +92 -0
  84. package/src/server/sync/status.ts +108 -0
  85. package/src/server/sync/timer.spec.ts +150 -0
  86. package/src/server/sync/timer.ts +207 -0
  87. package/src/server/sync/tokens.spec.ts +38 -0
  88. package/src/server/sync/tokens.ts +94 -0
  89. package/src/server/sync/types.ts +108 -0
  90. package/src/verifyGraph.spec.ts +181 -0
@@ -0,0 +1,361 @@
1
+ /**
2
+ * The command relay — notes' ask-responder shape generalized: the internet-facing
3
+ * instance PARKS an action it cannot perform (it has no Mac powers), and the Mac's
4
+ * resident worker long-polls for it, executes locally, and posts the outcome back.
5
+ * The Mac dials OUT; the receiving instance never reaches into the house.
6
+ *
7
+ * Delivery is a held GET (default hold 25s) — remember the two fleet traps: the
8
+ * host server needs `idleTimeoutSeconds` ABOVE the hold (Bun's 10s default closed
9
+ * notes' 25s poll and nginx reported a bogus 502), and the routes must be mounted
10
+ * BEFORE any browser-session gate.
11
+ *
12
+ * A command left `claimed` past the stale window is reclaimable — a worker that
13
+ * died mid-execution must not strand the queue. Executors must therefore be
14
+ * idempotent or cheap to re-run.
15
+ */
16
+ import type { Database } from "bun:sqlite";
17
+ import { randomUUID } from "node:crypto";
18
+ import { Hono } from "hono";
19
+
20
+ export type CommandStatus = "queued" | "claimed" | "done" | "failed";
21
+
22
+ export interface SyncCommand {
23
+ uid: string;
24
+ kind: string;
25
+ args: unknown;
26
+ status: CommandStatus;
27
+ requestedBy: string;
28
+ createdAt: number;
29
+ claimedAt: number | null;
30
+ claimedBy: string | null;
31
+ finishedAt: number | null;
32
+ result: unknown;
33
+ error: string | null;
34
+ }
35
+
36
+ const STALE_CLAIM_MS = 5 * 60_000;
37
+
38
+ export interface CommandQueue {
39
+ enqueue(kind: string, args: unknown, requestedBy: string): SyncCommand;
40
+ /** Atomically claim the oldest queued (or stale-claimed) command. */
41
+ claimNext(claimedBy: string, staleMs?: number): SyncCommand | null;
42
+ complete(uid: string, result: unknown): boolean;
43
+ fail(uid: string, error: string): boolean;
44
+ get(uid: string): SyncCommand | null;
45
+ list(limit?: number): SyncCommand[];
46
+ pendingCount(): number;
47
+ }
48
+
49
+ interface Row {
50
+ uid: string;
51
+ kind: string;
52
+ args: string;
53
+ status: CommandStatus;
54
+ requested_by: string;
55
+ created_at: number;
56
+ claimed_at: number | null;
57
+ claimed_by: string | null;
58
+ finished_at: number | null;
59
+ result: string | null;
60
+ error: string | null;
61
+ }
62
+
63
+ const toCommand = (r: Row): SyncCommand => ({
64
+ uid: r.uid,
65
+ kind: r.kind,
66
+ args: JSON.parse(r.args) as unknown,
67
+ status: r.status,
68
+ requestedBy: r.requested_by,
69
+ createdAt: r.created_at,
70
+ claimedAt: r.claimed_at,
71
+ claimedBy: r.claimed_by,
72
+ finishedAt: r.finished_at,
73
+ result: r.result === null ? null : (JSON.parse(r.result) as unknown),
74
+ error: r.error,
75
+ });
76
+
77
+ export function createCommandQueue(db: Database): CommandQueue {
78
+ db.exec(`
79
+ CREATE TABLE IF NOT EXISTS sync_commands (
80
+ uid TEXT PRIMARY KEY,
81
+ kind TEXT NOT NULL,
82
+ args TEXT NOT NULL,
83
+ status TEXT NOT NULL DEFAULT 'queued',
84
+ requested_by TEXT NOT NULL,
85
+ created_at INTEGER NOT NULL,
86
+ claimed_at INTEGER,
87
+ claimed_by TEXT,
88
+ finished_at INTEGER,
89
+ result TEXT,
90
+ error TEXT
91
+ );
92
+ CREATE INDEX IF NOT EXISTS idx_sync_commands_status ON sync_commands(status, created_at);
93
+ `);
94
+ const insert = db.prepare(
95
+ "INSERT INTO sync_commands (uid, kind, args, status, requested_by, created_at) VALUES (?, ?, ?, 'queued', ?, ?)",
96
+ );
97
+ const getStmt = db.prepare("SELECT * FROM sync_commands WHERE uid = ?");
98
+ const listStmt = db.prepare("SELECT * FROM sync_commands ORDER BY created_at DESC LIMIT ?");
99
+ const pendingStmt = db.prepare(
100
+ "SELECT COUNT(*) AS n FROM sync_commands WHERE status IN ('queued','claimed')",
101
+ );
102
+ // The atomic claim: one UPDATE whose WHERE picks the oldest eligible row. sqlite
103
+ // serializes writers, so two workers can never claim the same row.
104
+ const claimStmt = db.prepare(`
105
+ UPDATE sync_commands SET status = 'claimed', claimed_at = ?, claimed_by = ?
106
+ WHERE uid = (
107
+ SELECT uid FROM sync_commands
108
+ WHERE status = 'queued' OR (status = 'claimed' AND claimed_at < ?)
109
+ ORDER BY created_at ASC LIMIT 1
110
+ )
111
+ RETURNING *
112
+ `);
113
+ const finishStmt = db.prepare(
114
+ "UPDATE sync_commands SET status = ?, finished_at = ?, result = ?, error = ? WHERE uid = ? AND status IN ('queued','claimed')",
115
+ );
116
+
117
+ return {
118
+ enqueue(kind, args, requestedBy) {
119
+ const uid = `cmd-${randomUUID().slice(0, 18)}`;
120
+ insert.run(uid, kind, JSON.stringify(args ?? null), requestedBy, Date.now());
121
+ return toCommand(getStmt.get(uid) as Row);
122
+ },
123
+ claimNext(claimedBy, staleMs = STALE_CLAIM_MS) {
124
+ const now = Date.now();
125
+ const row = claimStmt.get(now, claimedBy, now - staleMs) as Row | null;
126
+ return row ? toCommand(row) : null;
127
+ },
128
+ complete: (uid, result) =>
129
+ finishStmt.run("done", Date.now(), JSON.stringify(result ?? null), null, uid).changes > 0,
130
+ fail: (uid, error) => finishStmt.run("failed", Date.now(), null, error, uid).changes > 0,
131
+ get: (uid) => {
132
+ const row = getStmt.get(uid) as Row | null;
133
+ return row ? toCommand(row) : null;
134
+ },
135
+ list: (limit = 100) => (listStmt.all(limit) as Row[]).map(toCommand),
136
+ pendingCount: () => (pendingStmt.get() as { n: number }).n,
137
+ };
138
+ }
139
+
140
+ // ── the receiver routes (mount beside the sync receiver, same token gate) ────────
141
+
142
+ const noStore = { "cache-control": "no-store" } as const;
143
+ export const DEFAULT_HOLD_MS = 25_000;
144
+
145
+ export interface CommandRoutesOptions {
146
+ queue: CommandQueue;
147
+ verifyToken: (presented: string) => boolean;
148
+ /** Cap on the held poll. The HOST SERVER's idleTimeout must exceed this. */
149
+ maxHoldMs?: number;
150
+ pollStepMs?: number;
151
+ }
152
+
153
+ /** GET /pending (held) + POST /pending/:uid — the worker's two verbs. */
154
+ export function createCommandReceiver(options: CommandRoutesOptions): Hono {
155
+ const maxHold = options.maxHoldMs ?? DEFAULT_HOLD_MS;
156
+ const step = options.pollStepMs ?? 1_000;
157
+ const api = new Hono();
158
+ api.use("*", async (c, next) => {
159
+ const header = c.req.header("authorization") ?? "";
160
+ const presented = header.startsWith("Bearer ") ? header.slice(7) : "";
161
+ if (presented.length === 0 || !options.verifyToken(presented)) {
162
+ return c.json({ error: "unauthorized" }, 401, noStore);
163
+ }
164
+ await next();
165
+ });
166
+
167
+ api.get("/pending", async (c) => {
168
+ const worker = c.req.query("worker") ?? "worker";
169
+ const waitRaw = c.req.query("wait");
170
+ const wait = Math.min(
171
+ maxHold,
172
+ waitRaw !== undefined && /^\d+$/.test(waitRaw) ? Number(waitRaw) : maxHold,
173
+ );
174
+ const deadline = Date.now() + wait;
175
+ for (;;) {
176
+ const command = options.queue.claimNext(worker);
177
+ if (command) return c.json({ command }, 200, noStore);
178
+ if (Date.now() >= deadline) return c.json({ command: null }, 200, noStore);
179
+ await new Promise((resolve) =>
180
+ setTimeout(resolve, Math.min(step, Math.max(1, deadline - Date.now()))),
181
+ );
182
+ }
183
+ });
184
+
185
+ api.post("/pending/:uid", async (c) => {
186
+ const uid = c.req.param("uid");
187
+ let body: unknown;
188
+ try {
189
+ body = await c.req.json();
190
+ } catch {
191
+ return c.json({ error: "bad_request" }, 400, noStore);
192
+ }
193
+ const { ok, result, error } = (body ?? {}) as {
194
+ ok?: unknown;
195
+ result?: unknown;
196
+ error?: unknown;
197
+ };
198
+ if (typeof ok !== "boolean") return c.json({ error: "bad_request" }, 400, noStore);
199
+ const changed = ok
200
+ ? options.queue.complete(uid, result ?? null)
201
+ : options.queue.fail(uid, typeof error === "string" ? error : "failed");
202
+ if (!changed) return c.json({ error: "not_found" }, 404, noStore);
203
+ return c.json({ ok: true }, 200, noStore);
204
+ });
205
+
206
+ return api;
207
+ }
208
+
209
+ // ── the dialing worker (runs on the Mac, inside the resident daemon) ─────────────
210
+
211
+ export interface CommandRemote {
212
+ poll(worker: string, waitMs: number): Promise<SyncCommand | null>;
213
+ report(uid: string, outcome: { ok: boolean; result?: unknown; error?: string }): Promise<void>;
214
+ }
215
+
216
+ export function createCommandRemote(options: {
217
+ basePath: string;
218
+ token: string;
219
+ fetchImpl?: typeof fetch;
220
+ /** Host-scoped extras for this peer — see `createHttpRemote`'s note. */
221
+ extraHeaders?: Record<string, string>;
222
+ }): CommandRemote {
223
+ const base = options.basePath.replace(/\/$/, "");
224
+ const doFetch = options.fetchImpl ?? fetch;
225
+ const headers = (extra?: Record<string, string>) => ({
226
+ authorization: `Bearer ${options.token}`,
227
+ ...(options.extraHeaders ?? {}),
228
+ ...(extra ?? {}),
229
+ });
230
+ /** 🔴 `redirect: "manual"`, for the reason in `http.ts`'s header: the relay
231
+ * travels the same road as the sync, so a moved peer hostname must fail here
232
+ * with the destination in the message rather than silently landing on a
233
+ * Cloudflare Access login page and reporting a JSON parse error. */
234
+ const refuseRedirect = (r: Response, path: string): void => {
235
+ if (r.status >= 300 && r.status < 400)
236
+ throw new Error(
237
+ `${path}: ${r.status} — the peer address redirects to ` +
238
+ `${r.headers.get("location") ?? "an unnamed destination"}; the relay URL points at a host that has moved.`,
239
+ );
240
+ };
241
+ return {
242
+ async poll(worker, waitMs) {
243
+ const r = await doFetch(
244
+ `${base}/pending?worker=${encodeURIComponent(worker)}&wait=${waitMs}`,
245
+ {
246
+ headers: headers(),
247
+ redirect: "manual",
248
+ // The abort budget must clear the hold plus network slack.
249
+ signal: AbortSignal.timeout(waitMs + 15_000),
250
+ },
251
+ );
252
+ refuseRedirect(r, "commands/pending");
253
+ if (!r.ok) throw new Error(`commands/pending: ${r.status}`);
254
+ const body = (await r.json()) as { command: SyncCommand | null };
255
+ return body.command;
256
+ },
257
+ async report(uid, outcome) {
258
+ const r = await doFetch(`${base}/pending/${encodeURIComponent(uid)}`, {
259
+ method: "POST",
260
+ headers: headers({ "content-type": "application/json" }),
261
+ redirect: "manual",
262
+ body: JSON.stringify(outcome),
263
+ signal: AbortSignal.timeout(30_000),
264
+ });
265
+ refuseRedirect(r, "commands/report");
266
+ if (!r.ok) throw new Error(`commands/report: ${r.status}`);
267
+ },
268
+ };
269
+ }
270
+
271
+ export interface CommandWorkerDeps {
272
+ /** Re-read every cycle, like the sync timer's peer — null = not linked. */
273
+ resolveRemote: () => CommandRemote | null;
274
+ execute: (command: SyncCommand) => Promise<unknown>;
275
+ worker?: string;
276
+ holdMs?: number;
277
+ /** Idle gap between an empty poll and the next (on top of the hold). */
278
+ idleGapMs?: number;
279
+ backoffMaxMs?: number;
280
+ log?: (msg: string) => void;
281
+ warn?: (msg: string) => void;
282
+ setTimer?: (fn: () => void, ms: number) => unknown;
283
+ clearTimer?: (handle: unknown) => void;
284
+ }
285
+
286
+ export interface CommandWorkerHandle {
287
+ stop(): void;
288
+ }
289
+
290
+ /** The resident long-poll → execute → report loop. Unreachable remote backs off to
291
+ * `backoffMaxMs` and recovers silently — the nightly window rule. */
292
+ export function startCommandWorker(deps: CommandWorkerDeps): CommandWorkerHandle {
293
+ const worker = deps.worker ?? "mac";
294
+ const holdMs = deps.holdMs ?? DEFAULT_HOLD_MS;
295
+ const idleGapMs = deps.idleGapMs ?? 1_000;
296
+ const backoffMax = deps.backoffMaxMs ?? 10 * 60_000;
297
+ const log = deps.log ?? ((m: string) => console.log(m));
298
+ const warn = deps.warn ?? ((m: string) => console.error(m));
299
+ const setTimer = deps.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
300
+ const clearTimer = deps.clearTimer ?? ((h) => clearTimeout(h as ReturnType<typeof setTimeout>));
301
+
302
+ let stopped = false;
303
+ let handle: unknown = null;
304
+ let failures = 0;
305
+ let reportedUnreachable = false;
306
+
307
+ const schedule = (ms: number): void => {
308
+ if (stopped) return;
309
+ if (handle !== null) clearTimer(handle);
310
+ handle = setTimer(cycle, ms);
311
+ (handle as { unref?: () => void })?.unref?.();
312
+ };
313
+
314
+ const cycle = (): void => {
315
+ if (stopped) return;
316
+ const remote = deps.resolveRemote();
317
+ if (remote === null) {
318
+ schedule(60_000);
319
+ return;
320
+ }
321
+ void remote
322
+ .poll(worker, holdMs)
323
+ .then(async (command) => {
324
+ failures = 0;
325
+ reportedUnreachable = false;
326
+ if (command === null) return;
327
+ log(`[commands] executing ${command.kind} (${command.uid})`);
328
+ try {
329
+ const result = await deps.execute(command);
330
+ await remote.report(command.uid, { ok: true, result });
331
+ } catch (err) {
332
+ const message = err instanceof Error ? err.message : String(err);
333
+ warn(`[commands] ${command.kind} failed: ${message}`);
334
+ // Best-effort: a failed report leaves the row claimed; the stale-claim
335
+ // window re-serves it, which is why executors must tolerate a re-run.
336
+ await remote.report(command.uid, { ok: false, error: message }).catch(() => {});
337
+ }
338
+ })
339
+ .then(() => {
340
+ if (!stopped) schedule(idleGapMs);
341
+ })
342
+ .catch((err) => {
343
+ failures += 1;
344
+ const wait = Math.min(backoffMax, 5_000 * 2 ** Math.min(failures - 1, 7));
345
+ if (!reportedUnreachable) {
346
+ const message = err instanceof Error ? err.message : String(err);
347
+ log(`[commands] remote unreachable (${message}) — backing off. This is normal offline.`);
348
+ reportedUnreachable = true;
349
+ }
350
+ schedule(wait);
351
+ });
352
+ };
353
+
354
+ schedule(1_000);
355
+ return {
356
+ stop: () => {
357
+ stopped = true;
358
+ if (handle !== null) clearTimer(handle);
359
+ },
360
+ };
361
+ }