@dench.com/cli 2.9.7 → 2.9.8

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/fs-daemon.ts CHANGED
@@ -51,13 +51,11 @@
51
51
  * from DENCH_API_KEY via Convex before it starts watching files.
52
52
  */
53
53
  import { createHash } from "node:crypto";
54
- import { mkdirSync } from "node:fs";
55
54
  import {
56
55
  mkdir,
57
56
  readdir,
58
57
  readFile,
59
58
  rename,
60
- stat,
61
59
  unlink,
62
60
  writeFile,
63
61
  } from "node:fs/promises";
@@ -77,7 +75,33 @@ import {
77
75
  type MountInfo,
78
76
  readMountInfo,
79
77
  } from "./fs-daemon-mount";
80
- import { createPullQueueDrain } from "./fs-daemon-pull-queue";
78
+ import {
79
+ createPullQueueDrain,
80
+ createRemoteFileQueue,
81
+ } from "./fs-daemon-pull-queue";
82
+ import { cachedWorkspaceMatches, isDaemonHealthy } from "./fs-daemon-health";
83
+ import { HashTracker, type BreakerState } from "./fs-daemon-sync-tracker";
84
+ import {
85
+ WorkspaceIo,
86
+ shouldIgnore,
87
+ type WorkspaceWorkerStatus,
88
+ } from "./fs-daemon-workspace";
89
+ import {
90
+ downloadRemoteFile,
91
+ parsePullRequest,
92
+ pullTimeRemaining,
93
+ withinPullDeadline,
94
+ type PullRequest,
95
+ } from "./fs-daemon-pull";
96
+
97
+ let activeWorkspaceIo: WorkspaceIo | undefined;
98
+ let daemonMode = false;
99
+ function workspaceIo(workspace: string): WorkspaceIo {
100
+ activeWorkspaceIo ??= new WorkspaceIo(workspace);
101
+ if (activeWorkspaceIo.workspace !== workspace)
102
+ throw new Error("workspace_io_invalid: root changed");
103
+ return activeWorkspaceIo;
104
+ }
81
105
 
82
106
  type FileTreeSyncRow = {
83
107
  path: string;
@@ -121,34 +145,6 @@ function parseArgs(argv: string[]): Args {
121
145
  return out as Args;
122
146
  }
123
147
 
124
- function shouldIgnore(relPath: string): boolean {
125
- const parts = relPath.split("/").filter(Boolean);
126
- const blockedDirs = new Set([
127
- ".chrome-profile",
128
- ".dench",
129
- ".git",
130
- ".next",
131
- ".vercel",
132
- "build",
133
- "coverage",
134
- "dist",
135
- "node_modules",
136
- ]);
137
- if (parts.some((part) => blockedDirs.has(part))) return true;
138
- const basename = parts.at(-1)?.toLowerCase() ?? "";
139
- if (basename === ".ds_store" || basename === "thumbs.db") return true;
140
- if (basename.startsWith("._")) return true;
141
- if (
142
- basename === ".env" ||
143
- (basename.startsWith(".env.") &&
144
- ![".env.example", ".env.sample", ".env.template"].includes(basename))
145
- ) {
146
- return true;
147
- }
148
- if (basename.endsWith(".pem") || basename.endsWith(".key")) return true;
149
- return false;
150
- }
151
-
152
148
  function sha256(bytes: Uint8Array): string {
153
149
  return createHash("sha256").update(bytes).digest("hex");
154
150
  }
@@ -171,6 +167,7 @@ function sha256(bytes: Uint8Array): string {
171
167
  // racing for the same slot can't clobber each other; the loser gets
172
168
  // EEXIST and advances to the next N.
173
169
  async function stashConflictCopy(args: {
170
+ io: WorkspaceIo;
174
171
  absPath: string;
175
172
  bytes: Uint8Array;
176
173
  hash: string;
@@ -181,7 +178,10 @@ async function stashConflictCopy(args: {
181
178
  const stem = basename(absPath, ext);
182
179
  for (let i = 1; i <= 1000; i++) {
183
180
  const candidate = join(dir, `${stem} (${i})${ext}`);
184
- const existing = await readFile(candidate).catch(() => null);
181
+ const existing = await args.io.readFile(candidate).catch((error) => {
182
+ if (error.code === "ENOENT") return null;
183
+ throw error;
184
+ });
185
185
  if (existing) {
186
186
  // Already holds our bytes → nothing to do. Different content → this
187
187
  // slot belongs to something else, try the next one.
@@ -189,7 +189,7 @@ async function stashConflictCopy(args: {
189
189
  continue;
190
190
  }
191
191
  try {
192
- await writeFile(candidate, bytes, { flag: "wx" });
192
+ await args.io.writeFile(candidate, bytes, { flag: "wx" });
193
193
  return candidate;
194
194
  } catch (error) {
195
195
  if ((error as NodeJS.ErrnoException).code === "EEXIST") continue;
@@ -199,7 +199,7 @@ async function stashConflictCopy(args: {
199
199
  // Every increment up to the cap is taken — fall back to a timestamp, which
200
200
  // is effectively unique, so we still stash the bytes somewhere.
201
201
  const fallback = join(dir, `${stem} (${Date.now()})${ext}`);
202
- await writeFile(fallback, bytes);
202
+ await args.io.writeFile(fallback, bytes);
203
203
  return fallback;
204
204
  }
205
205
 
@@ -216,12 +216,6 @@ function normalizePosixWorkspacePath(input: string): string {
216
216
  : cleaned;
217
217
  }
218
218
 
219
- type PullRequest = {
220
- id: string;
221
- paths: string[];
222
- requestedAt: number;
223
- };
224
-
225
219
  type PullResponse = {
226
220
  errors: Array<{ error: string; path: string }>;
227
221
  id: string;
@@ -232,9 +226,6 @@ type PullResponse = {
232
226
 
233
227
  const SYNC_DEBOUNCE_MS = 300;
234
228
  const MAX_INLINE_TEXT_BYTES = 100_000;
235
- const CIRCUIT_BREAKER_LIMIT = 5;
236
- const CIRCUIT_BREAKER_WINDOW_MS = 10_000;
237
- const CIRCUIT_BREAKER_PAUSE_MS = 60_000;
238
229
  // Reconciliation interval. AWS documents Mountpoint-for-S3's metadata
239
230
  // staleness window at ~1s; polling tighter than 2s wastes round-trips
240
231
  // without catching anything new.
@@ -245,135 +236,6 @@ const RECONCILE_INTERVAL_DEFAULT_MS = 30_000;
245
236
  const DAEMON_STATUS_PATH = "/tmp/dench-fs-daemon.status.json";
246
237
  const PULL_REQUEST_DIR = "/tmp/dench-fs-daemon.pull";
247
238
 
248
- type BreakerState = {
249
- path: string;
250
- trippedAt: number;
251
- resumesAt: number;
252
- syncsInWindow: number;
253
- };
254
-
255
- // `DrainStatus` lives in cli/fs-daemon-flush.ts so the flush subcommand's
256
- // polling helper can import it without dragging in the daemon's main
257
- // entrypoint (which would crash test runners that import this file).
258
-
259
- class HashTracker {
260
- private hashes = new Map<string, string>();
261
- private timers = new Map<string, NodeJS.Timeout>();
262
- private recentSyncs = new Map<string, number[]>();
263
- private paused = new Map<string, BreakerState>();
264
- private onBreakerTrip?: (state: BreakerState) => void;
265
- // Bumped right before each scheduled fn() actually starts; decremented
266
- // in the fn()'s `.finally()`. The flush subcommand reads this through
267
- // `drainStatus()` (mirrored into the status file once per reconcile).
268
- private inFlightUploads = 0;
269
-
270
- get(absPath: string): string | undefined {
271
- return this.hashes.get(absPath);
272
- }
273
-
274
- set(absPath: string, hash: string): void {
275
- this.hashes.set(absPath, hash);
276
- }
277
-
278
- forget(absPath: string): void {
279
- this.hashes.delete(absPath);
280
- const timer = this.timers.get(absPath);
281
- if (timer) {
282
- clearTimeout(timer);
283
- this.timers.delete(absPath);
284
- }
285
- this.recentSyncs.delete(absPath);
286
- this.paused.delete(absPath);
287
- }
288
-
289
- knownPaths(): string[] {
290
- return [...this.hashes.keys()];
291
- }
292
-
293
- activeBreakers(): BreakerState[] {
294
- return [...this.paused.values()];
295
- }
296
-
297
- setBreakerListener(listener: (state: BreakerState) => void): void {
298
- this.onBreakerTrip = listener;
299
- }
300
-
301
- /**
302
- * Returns true if the path is currently throttled by the circuit
303
- * breaker (>5 syncs in the last 10s).
304
- */
305
- recordAndCheckBreaker(absPath: string): boolean {
306
- if (this.paused.has(absPath)) return true;
307
- const now = Date.now();
308
- const recent = (this.recentSyncs.get(absPath) ?? []).filter(
309
- (ts) => now - ts < CIRCUIT_BREAKER_WINDOW_MS,
310
- );
311
- recent.push(now);
312
- this.recentSyncs.set(absPath, recent);
313
- if (recent.length > CIRCUIT_BREAKER_LIMIT) {
314
- const state: BreakerState = {
315
- path: absPath,
316
- trippedAt: now,
317
- resumesAt: now + CIRCUIT_BREAKER_PAUSE_MS,
318
- syncsInWindow: recent.length,
319
- };
320
- this.paused.set(absPath, state);
321
- // Loud enough to land in the supervisor's tail of fs-daemon.log
322
- // (sandbox-bootstrap.ts surfaces the last 50 lines on failure).
323
- console.error(
324
- `[dench-fs-daemon] CIRCUIT_BREAKER tripped path=${absPath} syncs=${recent.length} pause=${CIRCUIT_BREAKER_PAUSE_MS}ms`,
325
- );
326
- this.onBreakerTrip?.(state);
327
- setTimeout(() => {
328
- this.paused.delete(absPath);
329
- this.recentSyncs.delete(absPath);
330
- console.warn(
331
- `[dench-fs-daemon] circuit breaker released for ${absPath}`,
332
- );
333
- }, CIRCUIT_BREAKER_PAUSE_MS);
334
- return true;
335
- }
336
- return false;
337
- }
338
-
339
- schedule(absPath: string, ms: number, fn: () => Promise<void>): void {
340
- const existing = this.timers.get(absPath);
341
- if (existing) clearTimeout(existing);
342
- const timer = setTimeout(() => {
343
- this.timers.delete(absPath);
344
- // Track this work in-flight so `flush` knows to wait for the
345
- // upload to actually finish, not just for the next reconcile
346
- // tick to fire. The decrement runs in `finally` so even a
347
- // throwing upload doesn't strand the counter at non-zero.
348
- this.inFlightUploads += 1;
349
- fn()
350
- .catch((error) => {
351
- console.error(
352
- `[dench-fs-daemon] sync failed for ${absPath}: ${
353
- error instanceof Error ? error.message : String(error)
354
- }`,
355
- );
356
- })
357
- .finally(() => {
358
- this.inFlightUploads = Math.max(0, this.inFlightUploads - 1);
359
- });
360
- }, ms);
361
- this.timers.set(absPath, timer);
362
- }
363
-
364
- /**
365
- * Snapshot of pending sync work. Mirrored into the daemon status
366
- * file once per reconcile tick so `dench-fs-daemon flush` can wait
367
- * on it without an IPC channel.
368
- */
369
- drainStatus(): DrainStatus {
370
- return {
371
- pendingPaths: this.timers.size,
372
- inFlightUploads: this.inFlightUploads,
373
- };
374
- }
375
- }
376
-
377
239
  // Mount detection helpers live in fs-daemon-mount.ts so they can be
378
240
  // unit-tested without pulling chokidar / convex / etc. They are
379
241
  // re-exported here so existing imports of `cli/fs-daemon` keep
@@ -604,18 +466,31 @@ async function pullDownRemoteFile(
604
466
  posixPath: string;
605
467
  expectedHash: string;
606
468
  tracker: HashTracker;
469
+ deadline?: number;
470
+ shouldPublish?: () => boolean;
607
471
  },
608
472
  ): Promise<void> {
609
- const url = await client.getSignedDownloadUrl(args.posixPath);
610
- if (!url) return;
611
- const response = await fetch(url);
612
- if (!response.ok) {
613
- throw new Error(`Download failed (${response.status})`);
614
- }
615
- const buffer = new Uint8Array(await response.arrayBuffer());
473
+ const deadline = args.deadline ?? Date.now() + 30_000;
474
+ const buffer = await downloadRemoteFile({
475
+ resolveUrl: () => client.getSignedDownloadUrl(args.posixPath),
476
+ expectedHash: args.expectedHash,
477
+ deadline,
478
+ });
616
479
  const localPath = `${args.workspace}${args.posixPath}`;
617
- await mkdir(dirname(localPath), { recursive: true });
618
- await writeFile(localPath, buffer);
480
+ if (args.shouldPublish && !args.shouldPublish()) return;
481
+ const io = workspaceIo(args.workspace);
482
+ await io.mkdir(
483
+ dirname(localPath),
484
+ Math.min(8_000, pullTimeRemaining(deadline)),
485
+ );
486
+ if (args.shouldPublish && !args.shouldPublish()) return;
487
+ await io.writeFile(
488
+ localPath,
489
+ buffer,
490
+ undefined,
491
+ Math.min(8_000, pullTimeRemaining(deadline)),
492
+ );
493
+ pullTimeRemaining(deadline);
619
494
  args.tracker.set(localPath, args.expectedHash);
620
495
  console.log(
621
496
  `[dench-fs-daemon] pulled remote ${args.posixPath} (${buffer.byteLength}B, sha256=${args.expectedHash.slice(0, 8)})`,
@@ -636,7 +511,10 @@ async function processPullRequests(args: {
636
511
  const requestPath = `${PULL_REQUEST_DIR}/${entry}`;
637
512
  let request: PullRequest | null = null;
638
513
  try {
639
- request = JSON.parse(await readFile(requestPath, "utf-8")) as PullRequest;
514
+ request = parsePullRequest(
515
+ JSON.parse(await readFile(requestPath, "utf-8")),
516
+ entry,
517
+ );
640
518
  } catch (error) {
641
519
  console.error(
642
520
  `[dench-fs-daemon] invalid pull request ${entry}: ${
@@ -653,10 +531,19 @@ async function processPullRequests(args: {
653
531
  pulled: [],
654
532
  respondedAt: Date.now(),
655
533
  };
534
+ const deadline = Math.min(
535
+ request.deadlineAt ?? request.requestedAt + 10_000,
536
+ Date.now() + 60_000,
537
+ );
656
538
  for (const rawPath of request.paths) {
657
539
  const path = normalizePosixWorkspacePath(rawPath);
658
540
  try {
659
- const row = await args.client.getFileTreeRow(path);
541
+ if (path.split("/").includes("..") || path.includes("\0"))
542
+ throw new Error("pull_invalid_path");
543
+ const row = await withinPullDeadline(
544
+ () => args.client.getFileTreeRow(path),
545
+ deadline,
546
+ );
660
547
  if (!row || row.isDir || !row.contentHash) {
661
548
  throw new Error("File is not present in Convex fileTree.");
662
549
  }
@@ -665,6 +552,7 @@ async function processPullRequests(args: {
665
552
  posixPath: path,
666
553
  tracker: args.tracker,
667
554
  workspace: args.workspace,
555
+ deadline,
668
556
  });
669
557
  response.pulled.push({ contentHash: row.contentHash, path });
670
558
  } catch (error) {
@@ -675,11 +563,11 @@ async function processPullRequests(args: {
675
563
  });
676
564
  }
677
565
  }
678
- await writeFile(
679
- `${PULL_REQUEST_DIR}/response-${request.id}.json`,
680
- JSON.stringify(response),
681
- "utf-8",
682
- );
566
+ response.respondedAt = Date.now();
567
+ const responsePath = `${PULL_REQUEST_DIR}/response-${request.id}.json`;
568
+ const temporaryResponsePath = `${responsePath}.${process.pid}.tmp`;
569
+ await writeFile(temporaryResponsePath, JSON.stringify(response), "utf-8");
570
+ await rename(temporaryResponsePath, responsePath);
683
571
  await unlink(requestPath).catch(() => undefined);
684
572
  }
685
573
  }
@@ -715,10 +603,12 @@ async function runDaemon(daemonArgs: Args): Promise<void> {
715
603
  "[dench-fs-daemon] FUSE backing detected; enabling polling mode (inotify is not delivered through Mountpoint-S3)",
716
604
  );
717
605
  }
718
- mkdirSync(daemonArgs.workspace, { recursive: true });
719
- mkdirSync(daemonArgs.hotCache, { recursive: true });
606
+ daemonMode = true;
607
+ const io = workspaceIo(daemonArgs.workspace);
720
608
 
721
609
  const tracker = new HashTracker();
610
+ let retryRemote: (() => Promise<void>) | undefined;
611
+ let previousWorkerState = io.snapshot().state;
722
612
  const status = new DaemonStatusWriter({
723
613
  workspace: daemonArgs.workspace,
724
614
  organizationId: resolvedOrgId,
@@ -729,6 +619,18 @@ async function runDaemon(daemonArgs: Args): Promise<void> {
729
619
  // captures the current pending/in-flight counts. The flush
730
620
  // subcommand polls these via the status file.
731
621
  status.setDrainSnapshot(() => tracker.drainStatus());
622
+ status.setWorkerSnapshot(() => io.snapshot());
623
+ io.on("status", () => {
624
+ void status.flush();
625
+ const state = io.snapshot().state;
626
+ if (state === "ready" && previousWorkerState !== "ready")
627
+ void retryRemote?.();
628
+ previousWorkerState = state;
629
+ });
630
+ const heartbeat = setInterval(() => {
631
+ void status.flush();
632
+ if (io.snapshot().state === "ready") void retryRemote?.();
633
+ }, 5_000);
732
634
  tracker.setBreakerListener((breakerState) => {
733
635
  status.recordBreakerEvent(breakerState);
734
636
  void status.flush();
@@ -762,43 +664,17 @@ async function runDaemon(daemonArgs: Args): Promise<void> {
762
664
  // request file was written but before it could process the signal.
763
665
  void drainPullRequests();
764
666
 
765
- let chokidar: typeof import("chokidar");
766
- try {
767
- chokidar = (await import("chokidar")) as never;
768
- } catch (error) {
769
- console.error(
770
- `[dench-fs-daemon] chokidar not available; refusing to start (${
771
- error instanceof Error ? error.message : String(error)
772
- })`,
773
- );
774
- process.exit(EXIT_CONFIG_ERROR);
775
- }
776
-
777
- // On FUSE mounts inotify never fires, so we force chokidar's polling
778
- // backend (poll every 2.5s for files / 5s for binary). On non-FUSE
779
- // mounts the inotify backend is fine and saves CPU.
667
+ // The watcher, its polling stat calls, and every mount operation live in
668
+ // the child. Do not wait for it before accepting requests or reporting health.
780
669
  const reconcileIntervalMs = mount.isFuse
781
670
  ? RECONCILE_INTERVAL_FUSE_MS
782
671
  : RECONCILE_INTERVAL_DEFAULT_MS;
783
- const watcher = chokidar.watch(daemonArgs.workspace, {
784
- ignoreInitial: true,
785
- persistent: true,
786
- usePolling: mount.isFuse,
787
- interval: mount.isFuse ? 2_500 : undefined,
788
- binaryInterval: mount.isFuse ? 5_000 : undefined,
789
- awaitWriteFinish: mount.isFuse
790
- ? false
791
- : { stabilityThreshold: 100, pollInterval: 50 },
792
- ignored: (path: string) => {
793
- const rel = relative(daemonArgs.workspace, path);
794
- if (rel.startsWith("..")) return true;
795
- return shouldIgnore(rel);
796
- },
797
- });
798
-
799
- watcher.on("add", (absPath: string) => scheduleSync(absPath));
800
- watcher.on("change", (absPath: string) => scheduleSync(absPath));
801
- watcher.on("unlink", async (absPath: string) => {
672
+ void io
673
+ .watch(mount.isFuse)
674
+ .catch((error) => console.error("[dench-fs-daemon] " + error.message));
675
+ io.on("add", (absPath: string) => scheduleSync(absPath));
676
+ io.on("change", (absPath: string) => scheduleSync(absPath));
677
+ io.on("unlink", async (absPath: string) => {
802
678
  const rel = relative(daemonArgs.workspace, absPath);
803
679
  if (shouldIgnore(rel)) return;
804
680
  try {
@@ -819,9 +695,12 @@ async function runDaemon(daemonArgs: Args): Promise<void> {
819
695
  if (shouldIgnore(rel)) return;
820
696
  if (tracker.recordAndCheckBreaker(absPath)) return;
821
697
  tracker.schedule(absPath, SYNC_DEBOUNCE_MS, async () => {
822
- const stats = await stat(absPath).catch(() => null);
823
- if (!stats || !stats.isFile()) return;
824
- const bytes = await readFile(absPath);
698
+ const stats = await io.stat(absPath).catch((error) => {
699
+ if (error.code === "ENOENT") return null;
700
+ throw error;
701
+ });
702
+ if (!stats || !stats.isFile) return;
703
+ const bytes = await io.readFile(absPath);
825
704
  const hash = sha256(bytes);
826
705
  const previous = tracker.get(absPath);
827
706
  if (previous === hash) return;
@@ -853,7 +732,12 @@ async function runDaemon(daemonArgs: Args): Promise<void> {
853
732
  if (result.versionConflict) {
854
733
  // Stash the local copy in a sibling file, then re-pull the remote
855
734
  // version into the canonical path.
856
- const conflicted = await stashConflictCopy({ absPath, bytes, hash });
735
+ const conflicted = await stashConflictCopy({
736
+ io,
737
+ absPath,
738
+ bytes,
739
+ hash,
740
+ });
857
741
  console.warn(
858
742
  `[dench-fs-daemon] version conflict for ${posixPath}; local copy stashed at ${conflicted}`,
859
743
  );
@@ -873,28 +757,26 @@ async function runDaemon(daemonArgs: Args): Promise<void> {
873
757
 
874
758
  // Subscribe to remote fileTree changes and download anything whose
875
759
  // contentHash differs from our local lastSyncedHash.
876
- const unsubscribe = client.subscribeFileTree(convexUrl, async (rows) => {
877
- for (const row of rows) {
878
- if (row.isDir) continue;
879
- if (!row.contentHash) continue;
880
- const absPath = `${daemonArgs.workspace}${row.path}`;
881
- const local = tracker.get(absPath);
882
- if (local === row.contentHash) continue;
883
- try {
884
- await pullDownRemoteFile(client, {
885
- workspace: daemonArgs.workspace,
886
- posixPath: row.path,
887
- expectedHash: row.contentHash,
888
- tracker,
889
- });
890
- } catch (error) {
891
- console.error(
892
- `[dench-fs-daemon] pull failed for ${row.path}: ${
893
- error instanceof Error ? error.message : String(error)
894
- }`,
895
- );
896
- }
897
- }
760
+ const remoteQueue = createRemoteFileQueue({
761
+ isReady: () => io.snapshot().state === "ready",
762
+ getHash: (path) => tracker.get(`${daemonArgs.workspace}${path}`),
763
+ pull: (row, shouldPublish) =>
764
+ pullDownRemoteFile(client, {
765
+ workspace: daemonArgs.workspace,
766
+ posixPath: row.path,
767
+ expectedHash: row.contentHash,
768
+ tracker,
769
+ shouldPublish,
770
+ }),
771
+ onError: (error, path) =>
772
+ console.error(
773
+ `[dench-fs-daemon] remote pull failed${path ? ` for ${path}` : ""}`,
774
+ error instanceof Error ? error.message : "unknown",
775
+ ),
776
+ });
777
+ retryRemote = remoteQueue.retry;
778
+ const unsubscribe = client.subscribeFileTree(convexUrl, (rows) => {
779
+ void remoteQueue.update(rows);
898
780
  });
899
781
 
900
782
  // Periodic walk + reconciliation. Catches changes chokidar missed
@@ -955,6 +837,10 @@ async function runDaemon(daemonArgs: Args): Promise<void> {
955
837
  );
956
838
  void reconciler
957
839
  .runOneTick()
840
+ .then(() => {
841
+ status.recordFlushCompleted(requestedAt);
842
+ return status.flush();
843
+ })
958
844
  .catch((error) =>
959
845
  console.error(
960
846
  `[dench-fs-daemon] flush tick failed: ${
@@ -962,17 +848,14 @@ async function runDaemon(daemonArgs: Args): Promise<void> {
962
848
  }`,
963
849
  ),
964
850
  )
965
- .then(() => {
966
- status.recordFlushCompleted(requestedAt);
967
- return status.flush();
968
- })
969
851
  .catch(() => undefined);
970
852
  });
971
853
 
972
854
  process.on("SIGTERM", () => {
973
855
  reconciler.stop();
974
856
  unsubscribe();
975
- watcher.close().catch(() => undefined);
857
+ clearInterval(heartbeat);
858
+ io.close();
976
859
  process.exit(0);
977
860
  });
978
861
 
@@ -1002,42 +885,8 @@ type FileSnapshot = {
1002
885
  async function snapshotWorkspace(
1003
886
  workspace: string,
1004
887
  ): Promise<Map<string, FileSnapshot>> {
1005
- const result = new Map<string, FileSnapshot>();
1006
- const queue: string[] = [workspace];
1007
- while (queue.length > 0) {
1008
- const dir = queue.shift()!;
1009
- type DirEntryLike = {
1010
- name: string;
1011
- isDirectory(): boolean;
1012
- isFile(): boolean;
1013
- };
1014
- let entries: DirEntryLike[];
1015
- try {
1016
- entries = (await readdir(dir, {
1017
- withFileTypes: true,
1018
- })) as unknown as DirEntryLike[];
1019
- } catch {
1020
- continue;
1021
- }
1022
- for (const entry of entries) {
1023
- const abs = `${dir.replace(/\/+$/, "")}/${entry.name}`;
1024
- const rel = relative(workspace, abs);
1025
- if (rel.startsWith("..") || shouldIgnore(rel)) continue;
1026
- if (entry.isDirectory()) {
1027
- queue.push(abs);
1028
- continue;
1029
- }
1030
- if (!entry.isFile()) continue;
1031
- const stats = await stat(abs).catch(() => null);
1032
- if (!stats) continue;
1033
- result.set(abs, {
1034
- absPath: abs,
1035
- size: stats.size,
1036
- mtimeMs: stats.mtimeMs,
1037
- });
1038
- }
1039
- }
1040
- return result;
888
+ const files = await workspaceIo(workspace).scan();
889
+ return new Map(files.map((file) => [file.absPath, file]));
1041
890
  }
1042
891
 
1043
892
  type ReconcileLoopHandle = {
@@ -1088,6 +937,7 @@ function startReconcileLoop(args: {
1088
937
  return;
1089
938
  }
1090
939
  const start = Date.now();
940
+ let scanCompleted = false;
1091
941
  let observed = 0;
1092
942
  let scheduled = 0;
1093
943
  let deleted = 0;
@@ -1099,6 +949,7 @@ function startReconcileLoop(args: {
1099
949
  const prev = last.get(absPath);
1100
950
  if (
1101
951
  !prev ||
952
+ args.tracker.needsRetry(absPath) ||
1102
953
  prev.size !== info.size ||
1103
954
  prev.mtimeMs !== info.mtimeMs
1104
955
  ) {
@@ -1113,46 +964,55 @@ function startReconcileLoop(args: {
1113
964
  }
1114
965
  }
1115
966
  last.clear();
967
+ for (const path of args.tracker.retryPaths()) {
968
+ if (!snapshot.has(path)) args.tracker.forget(path);
969
+ }
1116
970
  for (const [absPath, info] of snapshot) {
1117
971
  last.set(absPath, info);
1118
972
  }
973
+ scanCompleted = true;
1119
974
  } catch (error) {
1120
975
  console.error(
1121
976
  `[dench-fs-daemon] reconcile scan failed: ${
1122
977
  error instanceof Error ? error.message : String(error)
1123
978
  }`,
1124
979
  );
980
+ throw error;
1125
981
  } finally {
1126
- const finishedAt = Date.now();
1127
- args.status.recordReconcile({
1128
- finishedAt,
1129
- durationMs: finishedAt - start,
1130
- observed,
1131
- scheduledForSync: scheduled,
1132
- deleted,
1133
- breakers: args.tracker.activeBreakers(),
1134
- });
1135
- await args.status.flush();
1136
- if (args.reportHealth) {
1137
- // Best-effort heartbeat into Convex `fileTreeHealth`. The
1138
- // chat-turn end-of-turn check + sidebar pill key off this
1139
- // row to surface "sync degraded" without polling the
1140
- // sandbox FS directly.
1141
- const drain = args.tracker.drainStatus();
1142
- try {
1143
- await args.reportHealth({
1144
- finishedAt,
1145
- observed,
1146
- activeBreakers: args.tracker.activeBreakers().length,
1147
- pendingDrain: drain.pendingPaths + drain.inFlightUploads,
1148
- });
1149
- } catch (error) {
1150
- console.error(
1151
- `[dench-fs-daemon] reportHealth failed: ${
1152
- error instanceof Error ? error.message : String(error)
1153
- }`,
1154
- );
982
+ if (scanCompleted) {
983
+ const finishedAt = Date.now();
984
+ args.status.recordReconcile({
985
+ finishedAt,
986
+ durationMs: finishedAt - start,
987
+ observed,
988
+ scheduledForSync: scheduled,
989
+ deleted,
990
+ breakers: args.tracker.activeBreakers(),
991
+ });
992
+ await args.status.flush();
993
+ if (args.reportHealth) {
994
+ // Best-effort heartbeat into Convex `fileTreeHealth`. The
995
+ // chat-turn end-of-turn check + sidebar pill key off this
996
+ // row to surface "sync degraded" without polling the
997
+ // sandbox FS directly.
998
+ const drain = args.tracker.drainStatus();
999
+ try {
1000
+ await args.reportHealth({
1001
+ finishedAt,
1002
+ observed,
1003
+ activeBreakers: args.tracker.activeBreakers().length,
1004
+ pendingDrain: drain.pendingPaths + drain.inFlightUploads,
1005
+ });
1006
+ } catch (error) {
1007
+ console.error(
1008
+ `[dench-fs-daemon] reportHealth failed: ${
1009
+ error instanceof Error ? error.message : String(error)
1010
+ }`,
1011
+ );
1012
+ }
1155
1013
  }
1014
+ } else {
1015
+ await args.status.flush();
1156
1016
  }
1157
1017
  }
1158
1018
  })();
@@ -1167,12 +1027,12 @@ function startReconcileLoop(args: {
1167
1027
  // floods on daemon startup.
1168
1028
  const initial = setTimeout(
1169
1029
  () => {
1170
- void tick();
1030
+ void tick().catch(() => undefined);
1171
1031
  },
1172
1032
  Math.min(args.intervalMs, 5_000),
1173
1033
  );
1174
1034
  const interval = setInterval(() => {
1175
- void tick();
1035
+ void tick().catch(() => undefined);
1176
1036
  }, args.intervalMs);
1177
1037
 
1178
1038
  return {
@@ -1193,6 +1053,7 @@ function startReconcileLoop(args: {
1193
1053
  // scanned. Lives on tmpfs so it never lands in the volume itself.
1194
1054
 
1195
1055
  type DaemonStatus = {
1056
+ mountWorker?: WorkspaceWorkerStatus;
1196
1057
  pid: number;
1197
1058
  startedAt: number;
1198
1059
  lastUpdatedAt: number;
@@ -1231,6 +1092,10 @@ class DaemonStatusWriter {
1231
1092
  // Pulled at flush() time so the on-disk drain count tracks the live
1232
1093
  // tracker without forcing every recordX() caller to plumb it through.
1233
1094
  private drainSnapshotFn: (() => DrainStatus) | null = null;
1095
+ private workerSnapshotFn: (() => WorkspaceWorkerStatus) | null = null;
1096
+ setWorkerSnapshot(fn: () => WorkspaceWorkerStatus): void {
1097
+ this.workerSnapshotFn = fn;
1098
+ }
1234
1099
 
1235
1100
  constructor(args: {
1236
1101
  workspace: string;
@@ -1301,6 +1166,7 @@ class DaemonStatusWriter {
1301
1166
  }
1302
1167
 
1303
1168
  async flush(): Promise<void> {
1169
+ if (this.workerSnapshotFn) this.state.mountWorker = this.workerSnapshotFn();
1304
1170
  this.state.lastUpdatedAt = Date.now();
1305
1171
  if (this.drainSnapshotFn) {
1306
1172
  this.state.pendingDrain = this.drainSnapshotFn();
@@ -1518,7 +1384,16 @@ async function runPull(argv: string[]): Promise<void> {
1518
1384
  }
1519
1385
  await mkdir(PULL_REQUEST_DIR, { recursive: true });
1520
1386
  const id = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
1521
- const request: PullRequest = { id, paths, requestedAt: Date.now() };
1387
+ const requestedAt = Date.now();
1388
+ const budget = Number.isFinite(timeoutMs)
1389
+ ? Math.max(1, Math.min(60_000, timeoutMs))
1390
+ : 10_000;
1391
+ const request: PullRequest = {
1392
+ id,
1393
+ paths,
1394
+ requestedAt,
1395
+ deadlineAt: requestedAt + budget,
1396
+ };
1522
1397
  const requestPath = `${PULL_REQUEST_DIR}/request-${id}.json`;
1523
1398
  const temporaryRequestPath = `${requestPath}.${process.pid}.tmp`;
1524
1399
  try {
@@ -1537,8 +1412,7 @@ async function runPull(argv: string[]): Promise<void> {
1537
1412
  }
1538
1413
 
1539
1414
  const responsePath = `${PULL_REQUEST_DIR}/response-${id}.json`;
1540
- const deadline =
1541
- Date.now() + (Number.isFinite(timeoutMs) ? timeoutMs : 10_000);
1415
+ const deadline = requestedAt + budget;
1542
1416
  while (Date.now() < deadline) {
1543
1417
  try {
1544
1418
  const response = JSON.parse(
@@ -1606,10 +1480,9 @@ async function main(): Promise<void> {
1606
1480
  // ── Status subcommand ─────────────────────────────────────────────────────
1607
1481
  //
1608
1482
  // `dench-fs-daemon status [--json] [--workspace /workspace]` prints a
1609
- // quick health readout: process up?, last reconcile tick, active
1610
- // circuit breakers, file count on disk vs Convex tree, and a
1611
- // per-path drift list. Designed to be called from a sandbox shell
1612
- // (or `dench fs status`) without any existing CLI context.
1483
+ // cached health readout: process up?, worker progress, last successful
1484
+ // reconcile, and active circuit breakers. It never scans the mount or
1485
+ // calls Convex, so repeated health probes cannot create stuck workers.
1613
1486
 
1614
1487
  const FS_DAEMON_LOG_PATH = "/var/log/dench/fs-daemon.log";
1615
1488
 
@@ -1626,6 +1499,8 @@ type DriftItem =
1626
1499
 
1627
1500
  type StatusReport = {
1628
1501
  daemon: {
1502
+ healthy: boolean;
1503
+ workspaceMatches: boolean;
1629
1504
  pidAlive: boolean;
1630
1505
  statusFilePath: string;
1631
1506
  statusFileExists: boolean;
@@ -1639,13 +1514,14 @@ type StatusReport = {
1639
1514
  source: string;
1640
1515
  };
1641
1516
  counts: {
1642
- onDisk: number;
1643
- inConvex: number;
1644
- onlyOnDisk: number;
1645
- onlyInConvex: number;
1646
- hashMismatches: number;
1517
+ onDisk: number | null;
1518
+ inConvex: number | null;
1519
+ onlyOnDisk: number | null;
1520
+ onlyInConvex: number | null;
1521
+ hashMismatches: number | null;
1647
1522
  };
1648
1523
  drift: DriftItem[];
1524
+ driftStatus: "not_checked";
1649
1525
  recentLogTail: string[];
1650
1526
  };
1651
1527
 
@@ -1656,148 +1532,43 @@ async function runStatus(argv: string[]): Promise<void> {
1656
1532
  workspaceIndex === -1
1657
1533
  ? process.env.DENCH_VOLUME_PATH?.trim() || "/workspace"
1658
1534
  : (argv[workspaceIndex + 1] ?? "/workspace");
1659
- const driftLimitIndex = argv.indexOf("--drift-limit");
1660
- const driftLimit =
1661
- driftLimitIndex === -1
1662
- ? 50
1663
- : Math.max(0, Number.parseInt(argv[driftLimitIndex + 1] ?? "50", 10));
1664
- const skipHash = argv.includes("--no-hash");
1665
-
1666
- const report = await collectStatus({
1667
- workspace,
1668
- driftLimit,
1669
- hash: !skipHash,
1670
- });
1535
+ // Legacy --no-hash / --drift-limit flags are accepted but status no
1536
+ // longer scans files. Unknown counts stay null, never a healthy zero.
1537
+ const report = await collectStatus({ workspace });
1538
+ if (!report.daemon.healthy) process.exitCode = 1;
1671
1539
  if (json) {
1672
1540
  process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
1673
1541
  return;
1674
1542
  }
1675
1543
  printStatusHuman(report);
1676
- // Exit non-zero when the daemon is missing or has obvious drift —
1677
- // makes it usable in `if dench-fs-daemon status; then …` checks.
1678
- if (!report.daemon.pidAlive || report.counts.hashMismatches > 0) {
1679
- process.exitCode = 1;
1680
- }
1681
1544
  }
1682
1545
 
1683
1546
  async function collectStatus(args: {
1684
1547
  workspace: string;
1685
- driftLimit: number;
1686
- hash: boolean;
1687
1548
  }): Promise<StatusReport> {
1688
1549
  const [statusFile, mount, logTail] = await Promise.all([
1689
1550
  readStatusFile(),
1690
1551
  detectWorkspaceFsType(args.workspace),
1691
1552
  readLogTail(20),
1692
1553
  ]);
1693
-
1554
+ // A status command must never spawn its own mount worker. Repeated probes
1555
+ // against D-state FUSE would otherwise accumulate orphaned children outside
1556
+ // the daemon supervisor's single-worker limit. Report cached health honestly.
1694
1557
  const pidAlive = statusFile.state ? isPidAlive(statusFile.state.pid) : false;
1695
-
1696
- const onDiskList: Array<{ path: string; size: number; mtimeMs: number }> = [];
1697
- let convexRows: Array<{
1698
- path: string;
1699
- contentHash?: string;
1700
- isDir: boolean;
1701
- }> = [];
1702
- try {
1703
- const snapshot = await snapshotWorkspace(args.workspace);
1704
- for (const [absPath, info] of snapshot) {
1705
- const rel = relative(args.workspace, absPath);
1706
- if (rel.startsWith("..")) continue;
1707
- onDiskList.push({
1708
- path: `/${rel}`,
1709
- size: info.size,
1710
- mtimeMs: info.mtimeMs,
1711
- });
1712
- }
1713
- } catch (error) {
1714
- console.error(
1715
- `[dench-fs-daemon] status: could not walk ${args.workspace}: ${
1716
- error instanceof Error ? error.message : String(error)
1717
- }`,
1718
- );
1719
- }
1720
-
1721
- const convexUrl = process.env.CONVEX_URL?.trim();
1722
- const apiKey = process.env.DENCH_API_KEY?.trim();
1723
- if (convexUrl && apiKey) {
1724
- try {
1725
- const client = new DenchFileClient(convexUrl, apiKey);
1726
- convexRows = await collectConvexTree(client);
1727
- } catch (error) {
1728
- console.error(
1729
- `[dench-fs-daemon] status: convex query failed: ${
1730
- error instanceof Error ? error.message : String(error)
1731
- }`,
1732
- );
1733
- }
1734
- }
1735
-
1736
- const diskByPath = new Map(onDiskList.map((item) => [item.path, item]));
1737
- const convexFileRows = convexRows.filter((row) => !row.isDir);
1738
- const convexByPath = new Map(convexFileRows.map((row) => [row.path, row]));
1739
-
1740
- const drift: DriftItem[] = [];
1741
- let onlyDisk = 0;
1742
- let onlyConvex = 0;
1743
- let hashMismatches = 0;
1744
-
1745
- for (const item of onDiskList) {
1746
- const convex = convexByPath.get(item.path);
1747
- if (!convex) {
1748
- onlyDisk++;
1749
- if (drift.length < args.driftLimit) {
1750
- drift.push({
1751
- kind: "only_disk",
1752
- path: item.path,
1753
- size: item.size,
1754
- mtimeMs: item.mtimeMs,
1755
- });
1756
- }
1757
- continue;
1758
- }
1759
- if (!args.hash) continue;
1760
- if (!convex.contentHash) continue;
1761
- try {
1762
- const bytes = await readFile(`${args.workspace}${item.path}`);
1763
- const diskHash = sha256(bytes);
1764
- if (diskHash !== convex.contentHash) {
1765
- hashMismatches++;
1766
- if (drift.length < args.driftLimit) {
1767
- drift.push({
1768
- kind: "hash_mismatch",
1769
- path: item.path,
1770
- diskSize: item.size,
1771
- diskHashShort: diskHash.slice(0, 8),
1772
- convexHashShort: convex.contentHash.slice(0, 8),
1773
- });
1774
- }
1775
- }
1776
- } catch {
1777
- // ignore read failures for a single file
1778
- }
1779
- }
1780
-
1781
- for (const row of convexFileRows) {
1782
- if (!diskByPath.has(row.path)) {
1783
- onlyConvex++;
1784
- if (drift.length < args.driftLimit) {
1785
- drift.push({ kind: "only_convex", path: row.path });
1786
- }
1787
- }
1788
- }
1789
-
1790
- let statusFileAgeMs: number | null = null;
1791
- if (statusFile.exists && statusFile.state) {
1792
- statusFileAgeMs = Date.now() - statusFile.state.lastUpdatedAt;
1793
- }
1794
-
1558
+ const workspaceMatches = cachedWorkspaceMatches(
1559
+ statusFile.state?.workspace,
1560
+ args.workspace,
1561
+ );
1795
1562
  return {
1796
1563
  daemon: {
1564
+ healthy: workspaceMatches && isDaemonHealthy(statusFile.state, pidAlive),
1565
+ workspaceMatches,
1797
1566
  pidAlive,
1798
1567
  statusFilePath: DAEMON_STATUS_PATH,
1799
1568
  statusFileExists: statusFile.exists,
1800
- statusFileAgeMs,
1569
+ statusFileAgeMs: statusFile.state
1570
+ ? Date.now() - statusFile.state.lastUpdatedAt
1571
+ : null,
1801
1572
  state: statusFile.state,
1802
1573
  },
1803
1574
  filesystem: {
@@ -1807,13 +1578,16 @@ async function collectStatus(args: {
1807
1578
  source: mount.source,
1808
1579
  },
1809
1580
  counts: {
1810
- onDisk: onDiskList.length,
1811
- inConvex: convexFileRows.length,
1812
- onlyOnDisk: onlyDisk,
1813
- onlyInConvex: onlyConvex,
1814
- hashMismatches,
1581
+ onDisk: workspaceMatches
1582
+ ? (statusFile.state?.lastReconcile?.observed ?? null)
1583
+ : null,
1584
+ inConvex: null,
1585
+ onlyOnDisk: null,
1586
+ onlyInConvex: null,
1587
+ hashMismatches: null,
1815
1588
  },
1816
- drift,
1589
+ drift: [],
1590
+ driftStatus: "not_checked",
1817
1591
  recentLogTail: logTail,
1818
1592
  };
1819
1593
  }
@@ -1850,33 +1624,12 @@ async function readLogTail(lines: number): Promise<string[]> {
1850
1624
  }
1851
1625
  }
1852
1626
 
1853
- async function collectConvexTree(
1854
- client: DenchFileClient,
1855
- ): Promise<Array<{ path: string; contentHash?: string; isDir: boolean }>> {
1856
- // listTree returns one directory's children; recurse into subdirs.
1857
- const out: Array<{ path: string; contentHash?: string; isDir: boolean }> = [];
1858
- const queue: string[] = ["/"];
1859
- const seen = new Set<string>();
1860
- while (queue.length > 0) {
1861
- const prefix = queue.shift()!;
1862
- if (seen.has(prefix)) continue;
1863
- seen.add(prefix);
1864
- const rows = await client.listTree(prefix);
1865
- for (const row of rows) {
1866
- out.push({
1867
- path: row.path,
1868
- contentHash: row.contentHash,
1869
- isDir: row.isDir,
1870
- });
1871
- if (row.isDir) queue.push(row.path);
1872
- }
1873
- }
1874
- return out;
1875
- }
1876
-
1877
1627
  function printStatusHuman(report: StatusReport): void {
1878
1628
  const lines: string[] = [];
1879
1629
  lines.push("dench-fs-daemon status");
1630
+ lines.push(
1631
+ "Cached daemon health only; live drift/hashes NOT CHECKED (null = unknown).",
1632
+ );
1880
1633
  lines.push("─".repeat(40));
1881
1634
  if (report.daemon.state) {
1882
1635
  const ageSec =
@@ -1886,10 +1639,20 @@ function printStatusHuman(report: StatusReport): void {
1886
1639
  lines.push(
1887
1640
  `daemon: ${report.daemon.pidAlive ? "ALIVE" : "DEAD"} (pid ${report.daemon.state.pid})`,
1888
1641
  );
1642
+ lines.push(
1643
+ `sync health: ${report.daemon.healthy ? "HEALTHY" : "DEGRADED"}`,
1644
+ );
1645
+ lines.push(
1646
+ `mount worker: ${report.daemon.state.mountWorker?.state ?? "unknown"}`,
1647
+ );
1889
1648
  lines.push(
1890
1649
  `status file: ${ageSec !== null ? `${ageSec}s old` : "missing"}`,
1891
1650
  );
1892
1651
  lines.push(`workspace: ${report.filesystem.workspace}`);
1652
+ if (!report.daemon.workspaceMatches)
1653
+ lines.push(
1654
+ `cached workspace: ${report.daemon.state.workspace} (does not match requested root)`,
1655
+ );
1893
1656
  lines.push(
1894
1657
  `filesystem: ${report.filesystem.fsType}${report.filesystem.isFuse ? " (FUSE — polling mode)" : ""}`,
1895
1658
  );
@@ -1994,50 +1757,40 @@ async function runInitialSync(argv: string[]): Promise<void> {
1994
1757
  process.stdout.write(
1995
1758
  `[dench-fs-daemon] initial sync org=${resolvedOrgId} workspace=${workspace}\n`,
1996
1759
  );
1997
- const fs = await import("node:fs/promises");
1998
- const path = await import("node:path");
1760
+ const io = workspaceIo(workspace);
1999
1761
 
2000
1762
  let count = 0;
2001
1763
  let bytes = 0;
2002
1764
  const skip = 0;
2003
- async function walk(dir: string): Promise<void> {
2004
- const entries = await fs.readdir(dir, { withFileTypes: true });
2005
- for (const entry of entries) {
2006
- const abs = path.join(dir, entry.name);
2007
- const rel = path.relative(workspace, abs);
2008
- if (shouldIgnore(rel)) continue;
2009
- if (entry.isDirectory()) {
2010
- await walk(abs);
2011
- continue;
2012
- }
2013
- if (!entry.isFile()) continue;
2014
- const bytesBuf = await fs.readFile(abs);
2015
- const hash = sha256(bytesBuf);
2016
- const posixPath = `/${rel.replace(/\\/g, "/")}`;
2017
- const uploadUrl = await client.generateUploadUrl(posixPath);
2018
- const storageId = await client.putBytes(uploadUrl, bytesBuf);
2019
- await client.commitFileUpload({
2020
- path: posixPath,
2021
- storageId,
2022
- contentHash: hash,
2023
- size: bytesBuf.byteLength,
2024
- // Same binary-aware inlining as scheduleSync — a fresh-volume
2025
- // initial sync that includes screenshots / PDFs / .zip would
2026
- // otherwise plant U+FFFD-corrupted text rows for every blob.
2027
- text:
2028
- bytesBuf.byteLength <= MAX_INLINE_TEXT_BYTES
2029
- ? decodeInlineTextOrUndefined(bytesBuf)
2030
- : undefined,
2031
- lastModifiedBy: "daemon",
2032
- });
2033
- count += 1;
2034
- bytes += bytesBuf.byteLength;
2035
- if (count % 50 === 0) {
2036
- process.stdout.write(`[dench-fs-daemon] synced ${count} files\n`);
2037
- }
1765
+ const files = await io.scan();
1766
+ for (const entry of files) {
1767
+ const abs = entry.absPath;
1768
+ const rel = relative(workspace, abs);
1769
+ const bytesBuf = await io.readFile(abs);
1770
+ const hash = sha256(bytesBuf);
1771
+ const posixPath = `/${rel.replace(/\\/g, "/")}`;
1772
+ const uploadUrl = await client.generateUploadUrl(posixPath);
1773
+ const storageId = await client.putBytes(uploadUrl, bytesBuf);
1774
+ await client.commitFileUpload({
1775
+ path: posixPath,
1776
+ storageId,
1777
+ contentHash: hash,
1778
+ size: bytesBuf.byteLength,
1779
+ // Same binary-aware inlining as scheduleSync — a fresh-volume
1780
+ // initial sync that includes screenshots / PDFs / .zip would
1781
+ // otherwise plant U+FFFD-corrupted text rows for every blob.
1782
+ text:
1783
+ bytesBuf.byteLength <= MAX_INLINE_TEXT_BYTES
1784
+ ? decodeInlineTextOrUndefined(bytesBuf)
1785
+ : undefined,
1786
+ lastModifiedBy: "daemon",
1787
+ });
1788
+ count += 1;
1789
+ bytes += bytesBuf.byteLength;
1790
+ if (count % 50 === 0) {
1791
+ process.stdout.write(`[dench-fs-daemon] synced ${count} files\n`);
2038
1792
  }
2039
1793
  }
2040
- await walk(workspace);
2041
1794
  process.stdout.write(
2042
1795
  `[dench-fs-daemon] initial sync complete: ${count} files, ${bytes}B (skipped ${skip})\n`,
2043
1796
  );
@@ -2051,16 +1804,21 @@ async function runInitialSync(argv: string[]): Promise<void> {
2051
1804
  // more (the test suite imports `fs-daemon-mount.ts` for the FUSE helpers), so
2052
1805
  // the guard is unnecessary and matches the unconditional `main()` call in
2053
1806
  // `cli/dench.ts`.
2054
- main().catch((error) => {
2055
- console.error(
2056
- `[dench-fs-daemon] fatal: ${
2057
- error instanceof Error ? (error.stack ?? error.message) : String(error)
2058
- }`,
2059
- );
2060
- // Always exit with a non-zero code so the supervisor (in
2061
- // src/lib/daytona/sandbox-bootstrap.ts) can decide whether to restart.
2062
- // Previously we parked the process on a noop interval, which made
2063
- // `pgrep dench-fs-daemon` report "alive" for a daemon that had silently
2064
- // given up syncing.
2065
- process.exit(1);
2066
- });
1807
+ main()
1808
+ .finally(() => {
1809
+ if (!daemonMode) activeWorkspaceIo?.close();
1810
+ })
1811
+ .catch((error) => {
1812
+ console.error(
1813
+ `[dench-fs-daemon] fatal: ${
1814
+ error instanceof Error ? (error.stack ?? error.message) : String(error)
1815
+ }`,
1816
+ );
1817
+ // Always exit with a non-zero code so the supervisor (in
1818
+ // src/lib/daytona/sandbox-bootstrap.ts) can decide whether to restart.
1819
+ // Previously we parked the process on a noop interval, which made
1820
+ // `pgrep dench-fs-daemon` report "alive" for a daemon that had silently
1821
+ // given up syncing.
1822
+ activeWorkspaceIo?.close();
1823
+ process.exit(1);
1824
+ });