@dench.com/cli 3.12.9-staging.1239 → 3.12.11-staging.1243

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.
@@ -1,4 +1,5 @@
1
1
  import type { DrainStatus } from "./fs-daemon-flush";
2
+
2
3
  const CIRCUIT_BREAKER_LIMIT = 5;
3
4
  const CIRCUIT_BREAKER_WINDOW_MS = 10_000;
4
5
  const CIRCUIT_BREAKER_PAUSE_MS = 60_000;
@@ -19,6 +20,14 @@ export class HashTracker {
19
20
  private timers = new Map<string, NodeJS.Timeout>();
20
21
  private recentSyncs = new Map<string, number[]>();
21
22
  private paused = new Map<string, BreakerState>();
23
+ /**
24
+ * The release timer of each path's current trip. A release ends only the
25
+ * trip that armed it. Before, the timer was fire-and-forget: after
26
+ * `forget()` (the file was deleted) and a new trip of the recreated file,
27
+ * the first trip's timer released the second pause early and wiped its
28
+ * sync history.
29
+ */
30
+ private breakerReleases = new Map<string, NodeJS.Timeout>();
22
31
  private onBreakerTrip?: (state: BreakerState) => void;
23
32
  // Bumped right before each scheduled fn() actually starts; decremented
24
33
  // in the fn()'s `.finally()`. The flush subcommand reads this through
@@ -53,6 +62,11 @@ export class HashTracker {
53
62
  }
54
63
  this.recentSyncs.delete(absPath);
55
64
  this.paused.delete(absPath);
65
+ const release = this.breakerReleases.get(absPath);
66
+ if (release) {
67
+ clearTimeout(release);
68
+ this.breakerReleases.delete(absPath);
69
+ }
56
70
  }
57
71
 
58
72
  knownPaths(): string[] {
@@ -93,13 +107,21 @@ export class HashTracker {
93
107
  `[dench-fs-daemon] CIRCUIT_BREAKER tripped path=${absPath} syncs=${recent.length} pause=${CIRCUIT_BREAKER_PAUSE_MS}ms`,
94
108
  );
95
109
  this.onBreakerTrip?.(state);
96
- setTimeout(() => {
97
- this.paused.delete(absPath);
98
- this.recentSyncs.delete(absPath);
99
- console.warn(
100
- `[dench-fs-daemon] circuit breaker released for ${absPath}`,
101
- );
102
- }, CIRCUIT_BREAKER_PAUSE_MS);
110
+ const previous = this.breakerReleases.get(absPath);
111
+ if (previous) clearTimeout(previous);
112
+ this.breakerReleases.set(
113
+ absPath,
114
+ setTimeout(() => {
115
+ // Only the trip that armed this timer is released by it.
116
+ if (this.paused.get(absPath) !== state) return;
117
+ this.breakerReleases.delete(absPath);
118
+ this.paused.delete(absPath);
119
+ this.recentSyncs.delete(absPath);
120
+ console.warn(
121
+ `[dench-fs-daemon] circuit breaker released for ${absPath}`,
122
+ );
123
+ }, CIRCUIT_BREAKER_PAUSE_MS),
124
+ );
103
125
  return true;
104
126
  }
105
127
  return false;
@@ -1,13 +1,18 @@
1
1
  /** Mounted I/O belongs to a PROCESS, not a worker thread: threads share
2
2
  * libuv's pool. A stuck FUSE stat must not starve parent DNS or /tmp queues. */
3
- import { spawn, type ChildProcess } from "node:child_process";
3
+ import { type ChildProcess, spawn } from "node:child_process";
4
4
  import { EventEmitter } from "node:events";
5
5
  import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
6
6
  import { isAbsolute, join, relative, resolve } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
+ import {
9
+ type WorkspaceWorkerState,
10
+ workspaceWorkerMachine,
11
+ } from "./lib/machines";
8
12
 
9
13
  export type WorkspaceWorkerStatus = {
10
- state: "starting" | "ready" | "stalled" | "backoff" | "stopped";
14
+ /** Moves only through `workspaceWorkerMachine` (lib/machines.ts). */
15
+ state: WorkspaceWorkerState;
11
16
  pid: number | null;
12
17
  lastProgressAt: number | null;
13
18
  restarts: number;
@@ -83,7 +88,6 @@ export class WorkspaceIo extends EventEmitter {
83
88
  private child: ChildProcess | null = null;
84
89
  private sequence = 0;
85
90
  private closed = false;
86
- private ready = false;
87
91
  private restartTimes: number[] = [];
88
92
  private restartTimer?: ReturnType<typeof setTimeout>;
89
93
  private watching: boolean | null = null;
@@ -124,10 +128,22 @@ export class WorkspaceIo extends EventEmitter {
124
128
  private changed() {
125
129
  this.emit("status", this.snapshot());
126
130
  }
131
+ /** The only writer of `health.state`. */
132
+ private moveTo(to: WorkspaceWorkerState): "moved" | "same" | "refused" {
133
+ const decision = workspaceWorkerMachine.decide(this.health.state, to);
134
+ if (decision.kind === "apply") {
135
+ this.health.state = to;
136
+ return "moved";
137
+ }
138
+ return decision.kind === "same" ? "same" : "refused";
139
+ }
140
+ private get ready(): boolean {
141
+ return this.health.state === "ready";
142
+ }
127
143
  private launch() {
128
144
  if (this.closed || this.child) return;
129
- this.ready = false;
130
- this.health.state = "starting";
145
+ // backoff → starting (the constructor's first launch is already starting).
146
+ if (this.moveTo("starting") === "refused") return;
131
147
  this.health.lastProgressAt = null;
132
148
  const child =
133
149
  this.options.spawnWorker?.() ??
@@ -154,8 +170,7 @@ export class WorkspaceIo extends EventEmitter {
154
170
  if (this.child !== child || this.health.state === "stalled") return;
155
171
  if (message.event === "ready") {
156
172
  clearTimeout(bootTimer);
157
- this.ready = true;
158
- this.health.state = "ready";
173
+ if (this.moveTo("ready") !== "moved") return;
159
174
  this.health.error = null;
160
175
  this.changed();
161
176
  for (const item of this.pending.values()) this.send(item.request);
@@ -193,11 +208,11 @@ export class WorkspaceIo extends EventEmitter {
193
208
  clearTimeout(bootTimer);
194
209
  if (this.child !== child) return;
195
210
  this.child = null;
196
- this.ready = false;
197
211
  this.health.pid = null;
198
212
  this.rejectPending(new Error("workspace_io_unavailable: worker exited"));
199
213
  if (this.closed) return;
200
- this.health.state = "backoff";
214
+ // The OS confirmed the exit: the only way out of `stalled`.
215
+ this.moveTo("backoff");
201
216
  const now = Date.now();
202
217
  this.restartTimes = this.restartTimes.filter((at) => now - at < 60_000);
203
218
  // At most two replacements per minute, and ONLY after observed exit.
@@ -245,8 +260,7 @@ export class WorkspaceIo extends EventEmitter {
245
260
  this.pending.clear();
246
261
  }
247
262
  private stall(message: string) {
248
- if (this.closed || this.health.state === "stalled") return;
249
- this.health.state = "stalled";
263
+ if (this.closed || this.moveTo("stalled") !== "moved") return;
250
264
  this.health.error = message;
251
265
  this.rejectPending(new Error(message));
252
266
  this.changed();
@@ -278,22 +292,28 @@ export class WorkspaceIo extends EventEmitter {
278
292
  const livenessTimeout = stallOnTimeout
279
293
  ? usedTimeout
280
294
  : (this.options.timeoutMs ?? IO_TIMEOUT_MS);
281
- const timer = setTimeout(() => {
282
- if (this.pending.has(id))
283
- this.stall("workspace_io_timeout: " + method);
284
- }, Math.max(1, livenessTimeout));
295
+ const timer = setTimeout(
296
+ () => {
297
+ if (this.pending.has(id))
298
+ this.stall("workspace_io_timeout: " + method);
299
+ },
300
+ Math.max(1, livenessTimeout),
301
+ );
285
302
  const callerTimer = stallOnTimeout
286
303
  ? undefined
287
- : setTimeout(() => {
288
- const item = this.pending.get(id);
289
- if (!item) return;
290
- if (!item.sent) {
291
- // Expired startup work must never be sent after ready.
292
- this.pending.delete(id);
293
- clearTimeout(item.timer);
294
- }
295
- item.reject(new Error("workspace_io_timeout: " + method));
296
- }, Math.max(1, usedTimeout));
304
+ : setTimeout(
305
+ () => {
306
+ const item = this.pending.get(id);
307
+ if (!item) return;
308
+ if (!item.sent) {
309
+ // Expired startup work must never be sent after ready.
310
+ this.pending.delete(id);
311
+ clearTimeout(item.timer);
312
+ }
313
+ item.reject(new Error("workspace_io_timeout: " + method));
314
+ },
315
+ Math.max(1, usedTimeout),
316
+ );
297
317
  this.pending.set(id, {
298
318
  request,
299
319
  resolve: (value) => resolveValue(value as T),
@@ -340,7 +360,7 @@ export class WorkspaceIo extends EventEmitter {
340
360
  close() {
341
361
  this.closed = true;
342
362
  clearTimeout(this.restartTimer);
343
- this.health.state = "stopped";
363
+ this.moveTo("stopped");
344
364
  this.rejectPending(new Error("workspace_io_unavailable: stopped"));
345
365
  try {
346
366
  this.child?.kill("SIGKILL");
package/home-sync-lib.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { mkdir, readdir, rm, stat } from "node:fs/promises";
2
2
  import { join, relative } from "node:path";
3
+ import { type HomeSnapshotState, homeSnapshotMachine } from "./lib/machines";
3
4
 
4
5
  export const DEFAULT_LIVE_HOME = "/tmp/.dench-home";
5
6
  export const DEFAULT_SNAPSHOT_DIR = "/workspace/.dench/home/snapshots";
@@ -183,3 +184,133 @@ export async function pruneHomeSnapshots(args: {
183
184
  await Promise.all(stale.map((path) => rm(path, { force: true })));
184
185
  return stale;
185
186
  }
187
+
188
+ export type HomeSnapshotStatus = { pending: boolean; inFlight: boolean };
189
+
190
+ export type HomeSnapshotSchedulerOptions = {
191
+ debounceMs: number;
192
+ /** Takes one snapshot and records its own errors. */
193
+ snapshot: (reason: string) => Promise<void>;
194
+ /** Called after every state change (the daemon writes its status file). */
195
+ onChange?: (status: HomeSnapshotStatus) => void;
196
+ setTimer?: (callback: () => void, ms: number) => unknown;
197
+ clearTimer?: (timer: unknown) => void;
198
+ };
199
+
200
+ /**
201
+ * One home snapshot at a time, debounced, moved only through
202
+ * `homeSnapshotMachine`. Replaces the daemon's `pending` / `inFlight` /
203
+ * `pendingTimer` fields and its separately written status copies.
204
+ */
205
+ export class HomeSnapshotScheduler {
206
+ private state: HomeSnapshotState = "idle";
207
+ private timer: unknown = null;
208
+ private running: Promise<void> | null = null;
209
+ private stopping: Promise<void> | null = null;
210
+
211
+ constructor(private readonly options: HomeSnapshotSchedulerOptions) {}
212
+
213
+ get current(): HomeSnapshotState {
214
+ return this.state;
215
+ }
216
+
217
+ status(): HomeSnapshotStatus {
218
+ return {
219
+ pending: this.state === "pending" || this.state === "in_flight_dirty",
220
+ inFlight:
221
+ this.state === "in_flight" ||
222
+ this.state === "in_flight_dirty" ||
223
+ this.running !== null,
224
+ };
225
+ }
226
+
227
+ /** The watcher saw a change under the live home. */
228
+ changed(reason: string): void {
229
+ if (this.state === "pending") {
230
+ // Explicit same-state path: a later change restarts the debounce.
231
+ this.arm(reason);
232
+ return;
233
+ }
234
+ if (this.state === "idle") {
235
+ if (this.move("pending")) this.arm(reason);
236
+ return;
237
+ }
238
+ if (this.state === "in_flight") this.move("in_flight_dirty");
239
+ // in_flight_dirty already owes a follow-up; stopping/stopped ignore it.
240
+ }
241
+
242
+ /** Take one snapshot right away (`--once`). */
243
+ async runNow(reason: string): Promise<void> {
244
+ if (!this.move("in_flight")) return;
245
+ this.clearTimer();
246
+ await this.run(reason);
247
+ }
248
+
249
+ /**
250
+ * Wait for the running snapshot, take a final one if the tree changed
251
+ * since the last snapshot started, then stop for good. Idempotent.
252
+ */
253
+ shutdown(): Promise<void> {
254
+ if (this.stopping) return this.stopping;
255
+ const from = this.state;
256
+ this.stopping = (async () => {
257
+ this.clearTimer();
258
+ if (!this.move("stopping")) return;
259
+ if (this.running) await this.running;
260
+ if (from === "pending" || from === "in_flight_dirty") {
261
+ await this.track(this.options.snapshot("shutdown"));
262
+ }
263
+ this.move("stopped");
264
+ })();
265
+ return this.stopping;
266
+ }
267
+
268
+ private move(to: HomeSnapshotState): boolean {
269
+ if (homeSnapshotMachine.decide(this.state, to).kind !== "apply") {
270
+ return false;
271
+ }
272
+ this.state = to;
273
+ this.options.onChange?.(this.status());
274
+ return true;
275
+ }
276
+
277
+ private arm(reason: string): void {
278
+ this.clearTimer();
279
+ this.timer = (this.options.setTimer ?? setTimeout)(() => {
280
+ this.timer = null;
281
+ if (this.move("in_flight")) void this.run(reason);
282
+ }, this.options.debounceMs);
283
+ }
284
+
285
+ private clearTimer(): void {
286
+ if (this.timer === null) return;
287
+ (
288
+ this.options.clearTimer ??
289
+ ((timer) => clearTimeout(timer as ReturnType<typeof setTimeout>))
290
+ )(this.timer);
291
+ this.timer = null;
292
+ }
293
+
294
+ private async track(snapshot: Promise<void>): Promise<void> {
295
+ const running = snapshot.catch(() => undefined);
296
+ this.running = running;
297
+ this.options.onChange?.(this.status());
298
+ try {
299
+ await running;
300
+ } finally {
301
+ this.running = null;
302
+ }
303
+ }
304
+
305
+ private async run(reason: string): Promise<void> {
306
+ await this.track(this.options.snapshot(reason));
307
+ if (this.state === "in_flight") {
308
+ this.move("idle");
309
+ } else if (this.state === "in_flight_dirty") {
310
+ if (this.move("pending")) this.arm(`queued:${reason}`);
311
+ } else {
312
+ // `stopping`: shutdown() is waiting for this snapshot.
313
+ this.options.onChange?.(this.status());
314
+ }
315
+ }
316
+ }
package/home-sync.ts CHANGED
@@ -18,6 +18,7 @@ import {
18
18
  buildSnapshotName,
19
19
  buildTarCreateArgs,
20
20
  ensureHomeSyncDirs,
21
+ HomeSnapshotScheduler,
21
22
  type HomeSyncArgs,
22
23
  parseHomeSyncArgs,
23
24
  pruneHomeSnapshots,
@@ -80,11 +81,20 @@ async function writeStatus(
80
81
  await writeFile(path, `${JSON.stringify(status, null, 2)}\n`);
81
82
  }
82
83
 
84
+ function isAlreadyExists(error: unknown): boolean {
85
+ return (
86
+ typeof error === "object" &&
87
+ error !== null &&
88
+ (error as NodeJS.ErrnoException).code === "EEXIST"
89
+ );
90
+ }
91
+
83
92
  class HomeSyncDaemon {
84
- private pendingTimer: NodeJS.Timeout | null = null;
85
- private pending = false;
86
- private inFlight = false;
87
93
  private status: HomeSyncStatus;
94
+ /** Snapshot lifecycle (`homeSnapshotMachine` in lib/machines.ts). */
95
+ private readonly scheduler: HomeSnapshotScheduler;
96
+ /** Status writes go out one at a time so the file is never interleaved. */
97
+ private statusWrites: Promise<void> = Promise.resolve();
88
98
 
89
99
  constructor(private readonly args: HomeSyncArgs) {
90
100
  this.status = {
@@ -97,6 +107,23 @@ class HomeSyncDaemon {
97
107
  pending: false,
98
108
  inFlight: false,
99
109
  };
110
+ this.scheduler = new HomeSnapshotScheduler({
111
+ debounceMs: args.debounceMs,
112
+ snapshot: (reason) => this.takeSnapshot(reason),
113
+ onChange: ({ pending, inFlight }) => {
114
+ this.status.pending = pending;
115
+ this.status.inFlight = inFlight;
116
+ void this.flushStatus();
117
+ },
118
+ });
119
+ }
120
+
121
+ private flushStatus(): Promise<void> {
122
+ const snapshot = { ...this.status };
123
+ this.statusWrites = this.statusWrites
124
+ .then(() => writeStatus(this.args.statusPath, snapshot))
125
+ .catch(() => undefined);
126
+ return this.statusWrites;
100
127
  }
101
128
 
102
129
  async start(): Promise<void> {
@@ -104,7 +131,8 @@ class HomeSyncDaemon {
104
131
  await writeStatus(this.args.statusPath, this.status);
105
132
 
106
133
  if (this.args.once) {
107
- await this.snapshotNow("once");
134
+ await this.scheduler.runNow("once");
135
+ await this.statusWrites;
108
136
  return;
109
137
  }
110
138
 
@@ -141,7 +169,7 @@ class HomeSyncDaemon {
141
169
  watcher.on("error", (error) => {
142
170
  console.error(`[dench-home-sync] watcher error: ${String(error)}`);
143
171
  this.status.lastError = String(error);
144
- void writeStatus(this.args.statusPath, this.status);
172
+ void this.flushStatus();
145
173
  });
146
174
 
147
175
  process.on("SIGTERM", () => {
@@ -157,40 +185,27 @@ class HomeSyncDaemon {
157
185
  }
158
186
 
159
187
  private scheduleSnapshot(reason: string): void {
160
- this.pending = true;
161
- this.status.pending = true;
162
- void writeStatus(this.args.statusPath, this.status);
163
-
164
- if (this.pendingTimer) clearTimeout(this.pendingTimer);
165
- this.pendingTimer = setTimeout(() => {
166
- this.pendingTimer = null;
167
- void this.snapshotNow(reason);
168
- }, this.args.debounceMs);
188
+ this.scheduler.changed(reason);
169
189
  }
170
190
 
171
- private async snapshotNow(reason: string): Promise<void> {
172
- if (this.inFlight) {
173
- this.scheduleSnapshot(`queued:${reason}`);
174
- return;
175
- }
176
-
177
- this.pending = false;
178
- this.inFlight = true;
179
- this.status.pending = false;
180
- this.status.inFlight = true;
181
- await writeStatus(this.args.statusPath, this.status);
182
-
183
- const tempDir = await mkdtemp(join(tmpdir(), "dench-home-sync-"));
184
- const archivePath = join(tempDir, "home.tar");
191
+ /** One snapshot. Never throws: the scheduler only sequences them. */
192
+ private async takeSnapshot(reason: string): Promise<void> {
185
193
  const snapshotName = buildSnapshotName(new Date());
186
194
  const durablePath = join(this.args.snapshotDir, snapshotName);
195
+ let tempDir: string | undefined;
196
+ let copyStarted = false;
197
+ let copied = false;
187
198
 
188
199
  try {
200
+ tempDir = await mkdtemp(join(tmpdir(), "dench-home-sync-"));
201
+ const archivePath = join(tempDir, "home.tar");
189
202
  await runCommand(
190
203
  "tar",
191
204
  buildTarCreateArgs({ liveHome: this.args.liveHome, archivePath }),
192
205
  );
206
+ copyStarted = true;
193
207
  await copyBytesOnly(archivePath, durablePath);
208
+ copied = true;
194
209
  await pruneHomeSnapshots({
195
210
  snapshotDir: this.args.snapshotDir,
196
211
  keepSnapshots: this.args.keepSnapshots,
@@ -202,28 +217,32 @@ class HomeSyncDaemon {
202
217
  `[dench-home-sync] snapshotted home (${reason}) -> ${durablePath}`,
203
218
  );
204
219
  } catch (error) {
220
+ if (copyStarted && !copied && !isAlreadyExists(error)) {
221
+ // A partial archive under a final name would be the newest snapshot,
222
+ // which is the one a new sandbox restores. (The durable volume has no
223
+ // rename, so the copy cannot go to a temporary name first.)
224
+ await rm(durablePath, { force: true }).catch(() => undefined);
225
+ }
205
226
  this.status.lastError =
206
227
  error instanceof Error ? error.message : String(error);
207
228
  console.error(
208
229
  `[dench-home-sync] snapshot failed: ${this.status.lastError}`,
209
230
  );
210
231
  } finally {
211
- await rm(tempDir, { recursive: true, force: true });
212
- this.inFlight = false;
213
- this.status.inFlight = false;
214
- this.status.pending = this.pending;
215
- await writeStatus(this.args.statusPath, this.status);
232
+ if (tempDir) {
233
+ await rm(tempDir, { recursive: true, force: true }).catch(
234
+ () => undefined,
235
+ );
236
+ }
216
237
  }
217
238
  }
218
239
 
219
240
  private async shutdown(exitCode: number): Promise<void> {
220
- if (this.pendingTimer) {
221
- clearTimeout(this.pendingTimer);
222
- this.pendingTimer = null;
223
- }
224
- if (this.pending || this.inFlight) {
225
- await this.snapshotNow("shutdown");
226
- }
241
+ // Waits for a running snapshot instead of exiting mid-copy. Before, a
242
+ // shutdown during a snapshot only re-armed the debounce timer and exited,
243
+ // leaving a truncated newest snapshot behind.
244
+ await this.scheduler.shutdown();
245
+ await this.flushStatus();
227
246
  process.exit(exitCode);
228
247
  }
229
248
  }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * In-process state machines of the CLI daemons, written down once.
3
+ *
4
+ * The CLI is published to npm from `cli/` alone, so it cannot import
5
+ * `convex/lib/stateMachine.ts`; `./state-machine.ts` is a byte-identical copy
6
+ * (cli/__tests__/vendored-state-machine.test.ts fails when it drifts).
7
+ * Inventory and history: docs/agent-notes/state-machines/gateway-workflows.md
8
+ * and docs/agent-notes/state-machines/batch-5.md.
9
+ */
10
+ import { defineMachine } from "./state-machine";
11
+
12
+ // ── fs-daemon mounted-workspace worker (fs-daemon-workspace.ts) ─────────────
13
+
14
+ export type WorkspaceWorkerState =
15
+ | "starting"
16
+ | "ready"
17
+ | "stalled"
18
+ | "backoff"
19
+ | "stopped";
20
+
21
+ /**
22
+ * The child process that does all mounted-workspace I/O.
23
+ *
24
+ * - `stalled` leaves only through the OS-confirmed exit of the child
25
+ * (`→ backoff`) or shutdown. By design: SIGKILL is not proof of exit for a
26
+ * process stuck in an uninterruptible (D-state) FUSE syscall, and a
27
+ * replacement would get stuck on the same mount. A stalled worker makes the
28
+ * daemon unhealthy (`isDaemonHealthy` requires `ready`), so recovery is the
29
+ * supervisor's restart of the daemon or sandbox.
30
+ * - Readiness is this state alone. Before, a separate `ready` boolean was not
31
+ * reset by a stall.
32
+ * - `stopped` is terminal.
33
+ */
34
+ export const workspaceWorkerMachine = defineMachine<WorkspaceWorkerState>(
35
+ "fs-daemon workspace worker",
36
+ {
37
+ starting: ["ready", "stalled", "backoff", "stopped"],
38
+ ready: ["stalled", "backoff", "stopped"],
39
+ stalled: ["backoff", "stopped"],
40
+ backoff: ["starting", "stopped"],
41
+ stopped: [],
42
+ },
43
+ { initial: ["starting"] },
44
+ );
45
+
46
+ // ── home-sync snapshots (home-sync-lib.ts HomeSnapshotScheduler) ────────────
47
+
48
+ export type HomeSnapshotState =
49
+ | "idle"
50
+ | "pending"
51
+ | "in_flight"
52
+ | "in_flight_dirty"
53
+ | "stopping"
54
+ | "stopped";
55
+
56
+ /**
57
+ * The home overlay snapshotter: one tar snapshot at a time, debounced.
58
+ *
59
+ * - `in_flight_dirty`: the tree changed while a snapshot was running, so
60
+ * another one follows it (`→ pending`, debounced) instead of a second
61
+ * snapshot racing the first.
62
+ * - `stopping` waits for the running snapshot and then takes one final
63
+ * snapshot if the tree changed since the last one started. Before, shutdown
64
+ * during a snapshot only re-armed the debounce timer and exited mid-copy,
65
+ * leaving a truncated archive as the newest snapshot, which is the one a new
66
+ * sandbox restores.
67
+ * - `stopped` is terminal: no change is scheduled after shutdown.
68
+ */
69
+ export const homeSnapshotMachine = defineMachine<HomeSnapshotState>(
70
+ "home sync snapshot",
71
+ {
72
+ idle: ["pending", "in_flight", "stopping"],
73
+ pending: ["in_flight", "stopping"],
74
+ in_flight: ["idle", "in_flight_dirty", "stopping"],
75
+ in_flight_dirty: ["pending", "stopping"],
76
+ stopping: ["stopped"],
77
+ stopped: [],
78
+ },
79
+ { initial: ["idle"] },
80
+ );