cursedbelt-server 4.50.0 → 4.51.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.
@@ -8,7 +8,11 @@
8
8
  *
9
9
  * Consumers (2026-08-13): `apps/music`, `apps/family`, `apps/collections` in
10
10
  * cursed-satellites. Each supplies a `DropHandler` and nothing else.
11
+ *
12
+ * A symlink in a drop folder is a LINKED source when the sweep is asked to follow it
13
+ * (`followLinks`): ingested in place, never deleted (`links.ts`, forge task 3752).
11
14
  */
12
- export { describeSweep, isJunkName, isStable, pruneEmptyDirs, scanDropzone, sweepDropzone, type DropHandler, type DropOutcome, type DroppedFile, type ScanOptions, type SweepReport, } from "./scan.js";
15
+ export { describeSweep, isJunkName, isStable, pruneEmptyDirs, scanDropzone, sweepDropzone, walkDropzone, type DropHandler, type DropzoneScan, type DropOutcome, type DroppedFile, type ScanOptions, type SweepReport, type UnreachableLink, } from "./scan.js";
16
+ export { adoptFinderAliases, DROPZONE_LINK, ensureDropzoneLink, isFinderAlias, isMountPoint, LINKED_FREE_FLOOR_BYTES, LINKED_OWED_WINDOW_MS, linkedRoomBytes, linkSource, linkTarget, resolveFinderAlias, type AliasAdoption, type LinkSource, } from "./links.js";
13
17
  export { askBinaryServerAboutDuplicate, hashFile, type DuplicateVerdict, type DuplicateQuestion, } from "./duplicates.js";
14
18
  export { createIngestReporter, FILES_JOURNAL, type FileOutcome, type IngestReporter, type ReportFile, type SourceDrive, } from "./report.js";
@@ -8,7 +8,11 @@
8
8
  *
9
9
  * Consumers (2026-08-13): `apps/music`, `apps/family`, `apps/collections` in
10
10
  * cursed-satellites. Each supplies a `DropHandler` and nothing else.
11
+ *
12
+ * A symlink in a drop folder is a LINKED source when the sweep is asked to follow it
13
+ * (`followLinks`): ingested in place, never deleted (`links.ts`, forge task 3752).
11
14
  */
12
- export { describeSweep, isJunkName, isStable, pruneEmptyDirs, scanDropzone, sweepDropzone, } from "./scan.js";
15
+ export { describeSweep, isJunkName, isStable, pruneEmptyDirs, scanDropzone, sweepDropzone, walkDropzone, } from "./scan.js";
16
+ export { adoptFinderAliases, DROPZONE_LINK, ensureDropzoneLink, isFinderAlias, isMountPoint, LINKED_FREE_FLOOR_BYTES, LINKED_OWED_WINDOW_MS, linkedRoomBytes, linkSource, linkTarget, resolveFinderAlias, } from "./links.js";
13
17
  export { askBinaryServerAboutDuplicate, hashFile, } from "./duplicates.js";
14
18
  export { createIngestReporter, FILES_JOURNAL, } from "./report.js";
@@ -0,0 +1,79 @@
1
+ /** Where a link points and why it cannot be followed right now. */
2
+ export type LinkSource = {
3
+ state: "ok";
4
+ target: string;
5
+ } | {
6
+ state: "unmounted";
7
+ target: string;
8
+ volume: string;
9
+ } | {
10
+ state: "deleted";
11
+ target: string;
12
+ };
13
+ /**
14
+ * Is `dir` a mounted volume rather than the empty folder macOS can leave in `/Volumes` after an
15
+ * unclean eject? A mount point lives on a different device than the folder holding it.
16
+ */
17
+ export declare function isMountPoint(dir: string): boolean;
18
+ /**
19
+ * Why a link's target is not there: its volume is not mounted (the drive is unplugged — wait), or
20
+ * the volume is there and the folder is not (it was deleted or moved — stop). A target outside
21
+ * `/Volumes` is on the boot disk, so missing means deleted.
22
+ */
23
+ export declare function linkSource(target: string, mounted?: (dir: string) => boolean): LinkSource;
24
+ /** A link's target as an absolute path (a relative link is relative to its own folder), or `null` when it is not a link. */
25
+ export declare function linkTarget(path: string): Promise<string | null>;
26
+ /**
27
+ * Is this file a Finder alias rather than content? Finder's "Make Alias" (⌘⌥-drag) does not make
28
+ * a symlink: it makes an ordinary FILE of bookmark data, which a sweep would otherwise upload as
29
+ * content and delete.
30
+ */
31
+ export declare function isFinderAlias(path: string, size: number): Promise<boolean>;
32
+ /**
33
+ * Resolve an alias to the path it points at, or `null`. Foundation through JXA: no Finder, no
34
+ * Apple Events permission, no UI, and it never mounts a volume (a launchd job must not).
35
+ */
36
+ export declare function resolveFinderAlias(path: string): string | null;
37
+ export interface AliasAdoption {
38
+ /** `<relative path> → <target>` for each alias now a symlink. */
39
+ linked: string[];
40
+ /** Aliases that could not be resolved (the drive is not mounted) — left as they are; a walk must not ingest them. */
41
+ unresolved: string[];
42
+ }
43
+ /** Is `name` one of `names`, as APFS compares — a dropped `Dups/` IS `dups/`? */
44
+ export declare const namedIn: (names: readonly string[] | undefined, name: string) => boolean;
45
+ /**
46
+ * Swap each Finder alias under `root` for a symlink to its target, so a walk with `followLinks`
47
+ * takes it as a linked source. Never looks in a hidden folder, through an existing link, or in a
48
+ * folder `skipTopDirs` names directly under `root` (an app's quarantine, its `done/`).
49
+ */
50
+ export declare function adoptFinderAliases(root: string, opts?: {
51
+ dryRun?: boolean;
52
+ resolve?: (path: string) => string | null;
53
+ skipTopDirs?: readonly string[];
54
+ }): Promise<AliasAdoption>;
55
+ /** What the owner opens next to an app's code — a link to its drop folder, never the files. */
56
+ export declare const DROPZONE_LINK = "dropzone";
57
+ /**
58
+ * The link next to the app's code that opens the drop folder — the place the owner will look.
59
+ *
60
+ * 🔴 A LINK, and the files stay in `$FORGE_STATE`. A drop is data, often gigabytes of it, and a
61
+ * code tree is walked by every check, bundler and test its repo runs; the link is gitignored, and
62
+ * `tools/check-paths.ts` never follows a link into a directory. Something real already at that
63
+ * name is left alone and said. Returns what it did, or `null` when the link was already right.
64
+ */
65
+ export declare function ensureDropzoneLink(appDir: string, root: string): Promise<string | null>;
66
+ /** The store keeps at least this much free after a linked file and its derivatives land. */
67
+ export declare const LINKED_FREE_FLOOR_BYTES: number;
68
+ /**
69
+ * How long a linked file is assumed to still owe its derivatives after it was filed. A day: the
70
+ * ladders for a ~50 GB batch took ~17 h at the measured 3.2 GB an hour, and past that they are on
71
+ * the disk, where free space already counts them — a longer window counts them twice.
72
+ */
73
+ export declare const LINKED_OWED_WINDOW_MS: number;
74
+ /**
75
+ * Bytes a linked file may still use on the store's volume, or `null` when it cannot be told
76
+ * (which holds nothing back — binary-server keeps its own floor). `owedBytes` is what the
77
+ * derivatives of recently linked files still have to take.
78
+ */
79
+ export declare function linkedRoomBytes(storeDir: string, owedBytes?: number): number | null;
@@ -0,0 +1,190 @@
1
+ /**
2
+ * LINKED sources in a drop folder — a symlink (or a Finder alias) the owner puts there so a
3
+ * folder on another drive is ingested IN PLACE, never moved and never deleted.
4
+ *
5
+ * Owner, 2026-10-21 (collections): *"I want to copy all the files in /Volumes/databundle/tod to
6
+ * collections app account 1, and not delete the copies at that path. Can I make a symlink to it …
7
+ * without copying the files from the volume into that folder?"* — and 2026-10-25 (photos): *"Make a
8
+ * dropzone in photos app for me to symlink to folders to ingest like we do in collections app."*
9
+ * Both apps wrote this file's contents for themselves, byte for byte (forge task 3752); it lives
10
+ * here so the third app that takes a link does not fork a third copy.
11
+ *
12
+ * What {@link scanDropzone} does with a link is in `scan.ts` (`followLinks`). This file is what it
13
+ * leans on, and what an app's own walk can use: telling an UNPLUGGED drive from a DELETED folder,
14
+ * turning Finder's aliases into symlinks, the link beside the app's code, and pacing a linked
15
+ * folder against the disk the bytes land on.
16
+ */
17
+ import { existsSync, statSync, statfsSync } from "node:fs";
18
+ import { lstat, mkdir, open, readdir, readlink, rm, symlink } from "node:fs/promises";
19
+ import { dirname, join, relative } from "node:path";
20
+ /**
21
+ * Is `dir` a mounted volume rather than the empty folder macOS can leave in `/Volumes` after an
22
+ * unclean eject? A mount point lives on a different device than the folder holding it.
23
+ */
24
+ export function isMountPoint(dir) {
25
+ try {
26
+ return statSync(dir).dev !== statSync(dirname(dir)).dev;
27
+ }
28
+ catch {
29
+ return false;
30
+ }
31
+ }
32
+ /**
33
+ * Why a link's target is not there: its volume is not mounted (the drive is unplugged — wait), or
34
+ * the volume is there and the folder is not (it was deleted or moved — stop). A target outside
35
+ * `/Volumes` is on the boot disk, so missing means deleted.
36
+ */
37
+ export function linkSource(target, mounted = isMountPoint) {
38
+ if (existsSync(target))
39
+ return { state: "ok", target };
40
+ const parts = target.split("/");
41
+ if (parts[1] === "Volumes" && parts[2]) {
42
+ const volume = `/Volumes/${parts[2]}`;
43
+ if (!mounted(volume))
44
+ return { state: "unmounted", target, volume };
45
+ }
46
+ return { state: "deleted", target };
47
+ }
48
+ /** A link's target as an absolute path (a relative link is relative to its own folder), or `null` when it is not a link. */
49
+ export async function linkTarget(path) {
50
+ const to = await readlink(path).catch(() => null);
51
+ if (to === null)
52
+ return null;
53
+ return to.startsWith("/") ? to : join(dirname(path), to);
54
+ }
55
+ // ── Finder aliases ───────────────────────────────────────────────────────────────────────
56
+ /** Every alias file (bookmark data) starts with these 16 bytes. Checked on this Mac, 2026-10-21. */
57
+ const ALIAS_MAGIC = "book\0\0\0\0mark\0\0\0\0";
58
+ /** Alias files are a few KB; nothing bigger is read to find out. */
59
+ const ALIAS_MAX_BYTES = 4 * 1024 * 1024;
60
+ /**
61
+ * Is this file a Finder alias rather than content? Finder's "Make Alias" (⌘⌥-drag) does not make
62
+ * a symlink: it makes an ordinary FILE of bookmark data, which a sweep would otherwise upload as
63
+ * content and delete.
64
+ */
65
+ export async function isFinderAlias(path, size) {
66
+ if (size < ALIAS_MAGIC.length || size > ALIAS_MAX_BYTES)
67
+ return false;
68
+ const handle = await open(path, "r").catch(() => null);
69
+ if (!handle)
70
+ return false;
71
+ try {
72
+ const head = Buffer.alloc(ALIAS_MAGIC.length);
73
+ await handle.read(head, 0, head.length, 0);
74
+ return head.toString("latin1") === ALIAS_MAGIC;
75
+ }
76
+ finally {
77
+ await handle.close();
78
+ }
79
+ }
80
+ /**
81
+ * Resolve an alias to the path it points at, or `null`. Foundation through JXA: no Finder, no
82
+ * Apple Events permission, no UI, and it never mounts a volume (a launchd job must not).
83
+ */
84
+ export function resolveFinderAlias(path) {
85
+ const script = 'function run(argv){ObjC.import("Foundation");' +
86
+ "const u=$.NSURL.URLByResolvingAliasFileAtURLOptionsError($.NSURL.fileURLWithPath(argv[0]),(1<<8)|(1<<9),null);" +
87
+ 'return u.isNil()?"":u.path.js;}';
88
+ const proc = Bun.spawnSync(["osascript", "-l", "JavaScript", "-e", script, path], { stdout: "pipe", stderr: "pipe" });
89
+ const target = proc.exitCode === 0 ? proc.stdout.toString().trim() : "";
90
+ return target && target !== path ? target : null;
91
+ }
92
+ /** Is `name` one of `names`, as APFS compares — a dropped `Dups/` IS `dups/`? */
93
+ export const namedIn = (names, name) => names?.some((n) => n.toLowerCase() === name.toLowerCase()) ?? false;
94
+ /**
95
+ * Swap each Finder alias under `root` for a symlink to its target, so a walk with `followLinks`
96
+ * takes it as a linked source. Never looks in a hidden folder, through an existing link, or in a
97
+ * folder `skipTopDirs` names directly under `root` (an app's quarantine, its `done/`).
98
+ */
99
+ export async function adoptFinderAliases(root, opts = {}) {
100
+ const resolve = opts.resolve ?? resolveFinderAlias;
101
+ const result = { linked: [], unresolved: [] };
102
+ const walk = async (dir) => {
103
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
104
+ for (const entry of entries) {
105
+ const full = join(dir, entry.name);
106
+ if (entry.name.startsWith("."))
107
+ continue;
108
+ if (entry.isDirectory()) {
109
+ if (dir === root && namedIn(opts.skipTopDirs, entry.name))
110
+ continue;
111
+ await walk(full);
112
+ continue;
113
+ }
114
+ if (!entry.isFile())
115
+ continue;
116
+ const info = await lstat(full).catch(() => null);
117
+ if (!info || !(await isFinderAlias(full, info.size)))
118
+ continue;
119
+ const rel = relative(root, full);
120
+ const target = resolve(full);
121
+ if (!target) {
122
+ result.unresolved.push(rel);
123
+ continue;
124
+ }
125
+ if (!opts.dryRun) {
126
+ await rm(full);
127
+ await symlink(target, full);
128
+ }
129
+ result.linked.push(`${rel} → ${target}`);
130
+ }
131
+ };
132
+ await walk(root);
133
+ return result;
134
+ }
135
+ // ── The link beside the app's code ───────────────────────────────────────────────────────
136
+ /** What the owner opens next to an app's code — a link to its drop folder, never the files. */
137
+ export const DROPZONE_LINK = "dropzone";
138
+ /**
139
+ * The link next to the app's code that opens the drop folder — the place the owner will look.
140
+ *
141
+ * 🔴 A LINK, and the files stay in `$FORGE_STATE`. A drop is data, often gigabytes of it, and a
142
+ * code tree is walked by every check, bundler and test its repo runs; the link is gitignored, and
143
+ * `tools/check-paths.ts` never follows a link into a directory. Something real already at that
144
+ * name is left alone and said. Returns what it did, or `null` when the link was already right.
145
+ */
146
+ export async function ensureDropzoneLink(appDir, root) {
147
+ const at = join(appDir, DROPZONE_LINK);
148
+ const info = await lstat(at).catch(() => null);
149
+ if (info && !info.isSymbolicLink())
150
+ return `${at} exists and is not a link — left alone`;
151
+ if (info && (await readlink(at)) === root)
152
+ return null;
153
+ if (info)
154
+ await rm(at);
155
+ await mkdir(root, { recursive: true });
156
+ await symlink(root, at);
157
+ return `linked ${at} → ${root}`;
158
+ }
159
+ // ── Pacing: the store is the boot disk ───────────────────────────────────────────────────
160
+ /*
161
+ * A link can put far more behind it than the Mac has room for. Measured 2026-10-21: collections'
162
+ * `tod` folder was 196 GiB with 212 GiB free on the boot volume, while binary-server's bytes land
163
+ * on this Mac and leave for B2 at most 50 GB a day (binary-server `src/b2Sweep.ts`). A linked file
164
+ * is only taken while the store would keep {@link LINKED_FREE_FLOOR_BYTES} free after it and its
165
+ * derivatives — and derivatives are built AFTER the upload, so free space alone lies for a while:
166
+ * what was linked in the last {@link LINKED_OWED_WINDOW_MS} counts as still owing them. Dropped
167
+ * files are not paced: they are already on this disk.
168
+ */
169
+ /** The store keeps at least this much free after a linked file and its derivatives land. */
170
+ export const LINKED_FREE_FLOOR_BYTES = 40 * 1024 ** 3;
171
+ /**
172
+ * How long a linked file is assumed to still owe its derivatives after it was filed. A day: the
173
+ * ladders for a ~50 GB batch took ~17 h at the measured 3.2 GB an hour, and past that they are on
174
+ * the disk, where free space already counts them — a longer window counts them twice.
175
+ */
176
+ export const LINKED_OWED_WINDOW_MS = 24 * 60 * 60 * 1000;
177
+ /**
178
+ * Bytes a linked file may still use on the store's volume, or `null` when it cannot be told
179
+ * (which holds nothing back — binary-server keeps its own floor). `owedBytes` is what the
180
+ * derivatives of recently linked files still have to take.
181
+ */
182
+ export function linkedRoomBytes(storeDir, owedBytes = 0) {
183
+ try {
184
+ const fs = statfsSync(storeDir);
185
+ return Number(fs.bavail) * Number(fs.bsize) - LINKED_FREE_FLOOR_BYTES - owedBytes;
186
+ }
187
+ catch {
188
+ return null;
189
+ }
190
+ }
@@ -19,7 +19,8 @@
19
19
  * 1. **A file is deleted only after the destination CONFIRMS it.** The dropzone is the one
20
20
  * place the owner's copy may be the only copy: they dragged it in expecting it to be taken.
21
21
  * A sweep that deletes on "the upload didn't throw" turns any catalog failure into data
22
- * loss. The handler returns `stored`/`duplicate` and only then does the original go.
22
+ * loss. The handler returns `stored`/`duplicate` and only then does the original go. A file
23
+ * reached through a LINK is never deleted at all: it is the owner's copy where it lives.
23
24
  *
24
25
  * 2. **A file must measure the same size twice before it is touched.** Dropping a 4 GB video
25
26
  * into a folder is not atomic. Without this the sweep ingests a truncated file, reports
@@ -31,6 +32,7 @@
31
32
  * should not stall uploading the rest of the in progress uploads"* — and it generalizes: a
32
33
  * dropzone with one unreadable file in it must still drain the other 4,000.
33
34
  */
35
+ import { type LinkSource } from "./links.js";
34
36
  import type { IngestReporter, ReportResult } from "./report.js";
35
37
  /** A file the sweep found, with everything a handler needs to decide about it. */
36
38
  export interface DroppedFile {
@@ -46,9 +48,17 @@ export interface DroppedFile {
46
48
  mtimeMs: number;
47
49
  /** Every other FILE name in the same directory — see {@link ScanOptions.captureSiblings}. */
48
50
  siblings: string[];
51
+ /**
52
+ * Reached through a symlink (`followLinks`): the owner's own copy, where it lives. A sweep
53
+ * never deletes one, whatever the handler answers — see rule 1. `realPath` is what an app keys
54
+ * it on, so renaming the link neither re-reads the drive nor files anything twice.
55
+ */
56
+ linked?: {
57
+ realPath: string;
58
+ };
49
59
  }
50
60
  export type DropOutcome =
51
- /** Filed successfully. The original is deleted. */
61
+ /** Filed successfully. The original is deleted — unless it is `linked`, which stays where it is. */
52
62
  {
53
63
  kind: "stored";
54
64
  detail?: string;
@@ -87,7 +97,11 @@ export interface SweepReport {
87
97
  unstable: string[];
88
98
  bytesRemoved: number;
89
99
  emptyDirsRemoved: number;
90
- /** Anything left in the root when the sweep finished. Empty is the goal. */
100
+ /** Linked files dealt with and LEFT IN PLACE — the owner's copy on their own drive (`followLinks`). */
101
+ leftInPlace: number;
102
+ /** Links whose target is not there this sweep — a drive unplugged, or a folder gone (`followLinks`). */
103
+ unreachable: UnreachableLink[];
104
+ /** Anything left in the root when the sweep finished, links not followed. Empty is the goal. */
91
105
  remaining: number;
92
106
  }
93
107
  export interface ScanOptions {
@@ -107,11 +121,41 @@ export interface ScanOptions {
107
121
  captureSiblings?: boolean;
108
122
  /** Directory names to skip entirely at any depth (another app's queue, our own state). */
109
123
  skipDirs?: string[];
124
+ /**
125
+ * Directory names skipped only directly under the root, compared as APFS does (case-insensitive)
126
+ * — an app's quarantine or `done/`, a name that is the owner's own inside a linked folder.
127
+ */
128
+ skipTopDirs?: readonly string[];
129
+ /**
130
+ * Walk THROUGH symlinks: a linked folder is ingested in place (`links.ts`). Off by default, so
131
+ * no consumer changes behavior unasked. See {@link walkDropzone}.
132
+ */
133
+ followLinks?: boolean;
110
134
  /** Stop after this many files. Absent means everything. */
111
135
  limit?: number;
112
136
  }
113
137
  /** A name that is OS noise, editor scratch, or a copy still in flight. */
114
138
  export declare function isJunkName(name: string): boolean;
139
+ /** A symlink the walk met whose target is not there this pass. */
140
+ export interface UnreachableLink {
141
+ /** The link, relative to the dropzone root. */
142
+ relativePath: string;
143
+ /** The link, absolute. */
144
+ path: string;
145
+ /**
146
+ * The link is in the dropzone's OWN tree (the owner put it there), not one met inside a linked
147
+ * folder on the owner's drive. Only an app's own link is ever its to act on.
148
+ */
149
+ inDropzone: boolean;
150
+ source: Exclude<LinkSource, {
151
+ state: "ok";
152
+ }>;
153
+ }
154
+ /** One walk: the files, and — with `followLinks` — the links that could not be followed. */
155
+ export interface DropzoneScan {
156
+ files: DroppedFile[];
157
+ unreachable: UnreachableLink[];
158
+ }
115
159
  /**
116
160
  * Every candidate file under `root`, deepest-last, with each one's sibling listing.
117
161
  *
@@ -120,6 +164,17 @@ export declare function isJunkName(name: string): boolean;
120
164
  * {@link isJunkName} is exported so a handler can classify without re-deriving the list.
121
165
  */
122
166
  export declare function scanDropzone(root: string, opts?: ScanOptions): Promise<DroppedFile[]>;
167
+ /**
168
+ * {@link scanDropzone}, with the links it could not follow.
169
+ *
170
+ * Without `followLinks` a symlink is skipped, as it always was. With it, a link to a directory is
171
+ * walked — once per REAL path, so a loop, or two links to one folder, or a link back into the
172
+ * dropzone, is not walked twice — and a link to a file is one file; everything reached through a
173
+ * link carries `linked`. A link whose target is missing is returned under `unreachable`, told
174
+ * apart by {@link linkSource}: `unmounted` (wait) or `deleted` (say so). A dangling link INSIDE a
175
+ * linked folder is the owner's drive's business; it is returned too, with `inDropzone: false`.
176
+ */
177
+ export declare function walkDropzone(root: string, opts?: ScanOptions): Promise<DropzoneScan>;
123
178
  /**
124
179
  * How old an EMPTY file has to be before it is believed. See {@link isStable}.
125
180
  *
@@ -148,6 +203,11 @@ export declare function isStable(file: DroppedFile, stabilityMs?: number): Promi
148
203
  * recursive delete here would take a file the sweep deliberately chose not to ingest — a held
149
204
  * duplicate, a failure left in place for the owner to look at — which is precisely the set of
150
205
  * files that must survive.
206
+ *
207
+ * 🔴 `lstat`, never `stat`: a symlink is a linked source, and following it would `rmdir` every
208
+ * empty folder on the owner's own drive (collections met exactly this, 2026-10-21). The one thing
209
+ * removed first is Finder's bookkeeping (`.DS_Store`, `._*`): Finder writes one into every folder
210
+ * the owner LOOKS at, and without this a tree they watched go in stays behind as empty shells.
151
211
  */
152
212
  export declare function pruneEmptyDirs(root: string, dir?: string): Promise<number>;
153
213
  /**
@@ -19,7 +19,8 @@
19
19
  * 1. **A file is deleted only after the destination CONFIRMS it.** The dropzone is the one
20
20
  * place the owner's copy may be the only copy: they dragged it in expecting it to be taken.
21
21
  * A sweep that deletes on "the upload didn't throw" turns any catalog failure into data
22
- * loss. The handler returns `stored`/`duplicate` and only then does the original go.
22
+ * loss. The handler returns `stored`/`duplicate` and only then does the original go. A file
23
+ * reached through a LINK is never deleted at all: it is the owner's copy where it lives.
23
24
  *
24
25
  * 2. **A file must measure the same size twice before it is touched.** Dropping a 4 GB video
25
26
  * into a folder is not atomic. Without this the sweep ingests a truncated file, reports
@@ -31,8 +32,9 @@
31
32
  * should not stall uploading the rest of the in progress uploads"* — and it generalizes: a
32
33
  * dropzone with one unreadable file in it must still drain the other 4,000.
33
34
  */
34
- import { readdir, rm, rmdir, stat } from "node:fs/promises";
35
+ import { lstat, readdir, realpath, rm, rmdir, stat } from "node:fs/promises";
35
36
  import { join, relative } from "node:path";
37
+ import { linkSource, linkTarget, namedIn } from "./links.js";
36
38
  /** OS bookkeeping and editor scratch. Never content, in any app. */
37
39
  const OS_JUNK = new Set([
38
40
  ".DS_Store",
@@ -67,10 +69,54 @@ const extOf = (name) => {
67
69
  * {@link isJunkName} is exported so a handler can classify without re-deriving the list.
68
70
  */
69
71
  export async function scanDropzone(root, opts = {}) {
72
+ return (await walkDropzone(root, opts)).files;
73
+ }
74
+ /**
75
+ * {@link scanDropzone}, with the links it could not follow.
76
+ *
77
+ * Without `followLinks` a symlink is skipped, as it always was. With it, a link to a directory is
78
+ * walked — once per REAL path, so a loop, or two links to one folder, or a link back into the
79
+ * dropzone, is not walked twice — and a link to a file is one file; everything reached through a
80
+ * link carries `linked`. A link whose target is missing is returned under `unreachable`, told
81
+ * apart by {@link linkSource}: `unmounted` (wait) or `deleted` (say so). A dangling link INSIDE a
82
+ * linked folder is the owner's drive's business; it is returned too, with `inDropzone: false`.
83
+ */
84
+ export async function walkDropzone(root, opts = {}) {
70
85
  const skip = new Set(opts.skipDirs ?? []);
71
86
  const out = [];
72
- const walk = async (dir) => {
73
- if (opts.limit !== undefined && out.length >= opts.limit)
87
+ const unreachable = [];
88
+ const walked = new Set();
89
+ const full = (n) => opts.limit !== undefined && n >= opts.limit;
90
+ const push = async (path, name, siblings, linked) => {
91
+ try {
92
+ const info = await stat(path);
93
+ out.push({
94
+ path,
95
+ relativePath: relative(root, path),
96
+ name,
97
+ ext: extOf(name),
98
+ size: info.size,
99
+ mtimeMs: info.mtimeMs,
100
+ siblings,
101
+ ...(linked ? { linked: { realPath: await realpath(path) } } : {}),
102
+ });
103
+ }
104
+ catch {
105
+ /* gone between readdir and stat */
106
+ }
107
+ };
108
+ /** `false` when this directory's real path was already walked — the one way a link loops. */
109
+ const firstVisit = async (dir) => {
110
+ if (!opts.followLinks)
111
+ return true;
112
+ const real = await realpath(dir).catch(() => null);
113
+ if (!real || walked.has(real))
114
+ return false;
115
+ walked.add(real);
116
+ return true;
117
+ };
118
+ const walk = async (dir, linked) => {
119
+ if (full(out.length))
74
120
  return;
75
121
  let entries;
76
122
  try {
@@ -83,36 +129,44 @@ export async function scanDropzone(root, opts = {}) {
83
129
  ? entries.filter((e) => e.isFile()).map((e) => e.name)
84
130
  : [];
85
131
  for (const entry of entries) {
86
- if (opts.limit !== undefined && out.length >= opts.limit)
132
+ if (full(out.length))
87
133
  return;
88
- const full = join(dir, entry.name);
89
- if (entry.isDirectory()) {
90
- if (skip.has(entry.name))
134
+ const path = join(dir, entry.name);
135
+ let isDir = entry.isDirectory();
136
+ let isFile = entry.isFile();
137
+ let viaLink = linked;
138
+ if (entry.isSymbolicLink()) {
139
+ if (!opts.followLinks)
91
140
  continue;
92
- await walk(full);
93
- continue;
141
+ const target = await stat(path).catch(() => null);
142
+ if (!target) {
143
+ const source = linkSource((await linkTarget(path)) ?? path);
144
+ if (source.state !== "ok")
145
+ unreachable.push({ relativePath: relative(root, path), path, inDropzone: !linked, source });
146
+ continue;
147
+ }
148
+ isDir = target.isDirectory();
149
+ isFile = target.isFile();
150
+ viaLink = true;
94
151
  }
95
- if (!entry.isFile())
152
+ if (isDir) {
153
+ if (skip.has(entry.name))
154
+ continue;
155
+ if (dir === root && namedIn(opts.skipTopDirs, entry.name))
156
+ continue;
157
+ if (!(await firstVisit(path)))
158
+ continue;
159
+ await walk(path, viaLink);
96
160
  continue;
97
- try {
98
- const info = await stat(full);
99
- out.push({
100
- path: full,
101
- relativePath: relative(root, full),
102
- name: entry.name,
103
- ext: extOf(entry.name),
104
- size: info.size,
105
- mtimeMs: info.mtimeMs,
106
- siblings,
107
- });
108
- }
109
- catch {
110
- /* gone between readdir and stat */
111
161
  }
162
+ if (isFile)
163
+ await push(path, entry.name, siblings, viaLink);
112
164
  }
113
165
  };
114
- await walk(root);
115
- return out;
166
+ if (opts.followLinks)
167
+ await firstVisit(root);
168
+ await walk(root, false);
169
+ return { files: out, unreachable };
116
170
  }
117
171
  /**
118
172
  * How old an EMPTY file has to be before it is believed. See {@link isStable}.
@@ -155,6 +209,11 @@ export async function isStable(file, stabilityMs = 750) {
155
209
  * recursive delete here would take a file the sweep deliberately chose not to ingest — a held
156
210
  * duplicate, a failure left in place for the owner to look at — which is precisely the set of
157
211
  * files that must survive.
212
+ *
213
+ * 🔴 `lstat`, never `stat`: a symlink is a linked source, and following it would `rmdir` every
214
+ * empty folder on the owner's own drive (collections met exactly this, 2026-10-21). The one thing
215
+ * removed first is Finder's bookkeeping (`.DS_Store`, `._*`): Finder writes one into every folder
216
+ * the owner LOOKS at, and without this a tree they watched go in stays behind as empty shells.
158
217
  */
159
218
  export async function pruneEmptyDirs(root, dir = root) {
160
219
  let removed = 0;
@@ -168,7 +227,7 @@ export async function pruneEmptyDirs(root, dir = root) {
168
227
  for (const name of entries) {
169
228
  const full = join(dir, name);
170
229
  try {
171
- if ((await stat(full)).isDirectory())
230
+ if ((await lstat(full)).isDirectory())
172
231
  removed += await pruneEmptyDirs(root, full);
173
232
  }
174
233
  catch {
@@ -178,6 +237,10 @@ export async function pruneEmptyDirs(root, dir = root) {
178
237
  if (dir === root)
179
238
  return removed;
180
239
  try {
240
+ const left = await readdir(dir);
241
+ if (left.length > 0 && left.every(isFinderBookkeeping))
242
+ for (const name of left)
243
+ await rm(join(dir, name)).catch(() => undefined);
181
244
  await rmdir(dir);
182
245
  return removed + 1;
183
246
  }
@@ -185,6 +248,7 @@ export async function pruneEmptyDirs(root, dir = root) {
185
248
  return removed; // not empty — the right outcome, and not an error
186
249
  }
187
250
  }
251
+ const isFinderBookkeeping = (name) => name === ".DS_Store" || name.startsWith("._");
188
252
  /**
189
253
  * A sweep's outcome in the words station's Uploads page reads (`report.ts`) — `null` for `held`, which
190
254
  * is a standing state rather than an event: the file stays where it is and every sweep meets it
@@ -237,10 +301,13 @@ async function sweep(root, handle, opts, reporter) {
237
301
  unstable: [],
238
302
  bytesRemoved: 0,
239
303
  emptyDirsRemoved: 0,
304
+ leftInPlace: 0,
305
+ unreachable: [],
240
306
  remaining: 0,
241
307
  };
242
308
  reporter?.walking();
243
- const files = await scanDropzone(root, opts);
309
+ const { files, unreachable } = await walkDropzone(root, opts);
310
+ report.unreachable = unreachable;
244
311
  reporter?.found(files.map(as));
245
312
  for (const [index, file] of files.entries()) {
246
313
  report.scanned++;
@@ -281,6 +348,12 @@ async function sweep(root, handle, opts, reporter) {
281
348
  report.discarded++;
282
349
  if (opts.dryRun)
283
350
  break;
351
+ // Rule 1, for a link: the destination confirming it is not permission to delete the
352
+ // owner's copy on their own drive. Stored, and left where it lives.
353
+ if (file.linked) {
354
+ report.leftInPlace++;
355
+ break;
356
+ }
284
357
  try {
285
358
  await rm(file.path);
286
359
  report.bytesRemoved += file.size;
@@ -305,12 +378,14 @@ async function sweep(root, handle, opts, reporter) {
305
378
  }
306
379
  if (!opts.dryRun)
307
380
  report.emptyDirsRemoved = await pruneEmptyDirs(root);
308
- report.remaining = (await scanDropzone(root, { skipDirs: opts.skipDirs })).length;
381
+ report.remaining = (await scanDropzone(root, { skipDirs: opts.skipDirs, skipTopDirs: opts.skipTopDirs })).length;
309
382
  return report;
310
383
  }
311
384
  /** A one-line summary — every consumer prints one, and they should read alike. */
312
385
  export const describeSweep = (report) => `${report.stored} added, ${report.duplicate} already had, ${report.discarded} discarded, ` +
313
386
  `${report.held} held, ${report.failed.length} failed, ${report.unstable.length} still copying` +
387
+ (report.leftInPlace > 0 ? ` · ${report.leftInPlace} linked file(s) left in place` : "") +
388
+ (report.unreachable.length > 0 ? ` · ${report.unreachable.length} link(s) not reachable` : "") +
314
389
  (report.bytesRemoved > 0
315
390
  ? ` · ${(report.bytesRemoved / 1024 ** 3).toFixed(2)} GB freed from the queue`
316
391
  : "") +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursedbelt-server",
3
- "version": "4.50.0",
3
+ "version": "4.51.0",
4
4
  "license": "ISC",
5
5
  "type": "module",
6
6
  "description": "The app-facing Bun/Hono server tier of the cursedbelt split — storage, sharing, activity, guard, sync. React-free; cursedbelt-core below it.",