cursedbelt-server 4.50.0 → 4.52.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.
@@ -16,4 +16,5 @@ carrying one goes red until it is removed. Inherited from `cursedbelt` at the
16
16
  | `src/server/storage/imageThumbnail.spec.ts` | `ffmpeg` on `PATH` |
17
17
  | `src/server/storage/videoProcessor.posterOnly.spec.ts` | `ffmpeg` on `PATH` |
18
18
  | `src/server/storage/files/adapter.photo.display.spec.ts` | `ffmpeg` on `PATH` |
19
+ | `src/server/dropzone/links.spec.ts` | macOS — a real Finder alias is written and resolved through `osascript` and Foundation; runs on every `bun run test` on this Mac (green 2026-10-26) |
19
20
  | `src/server/storage/fileUploadClient-chunked.integration.spec.ts` | a real `binary-server` checkout — set `BINARY_SERVER_DIR` to its path (`apps/binary-server` in this generation). No default by design: a published package must not go looking in one machine's directory layout. Moved here from `cursedbelt` at the 2026-09-15 split, with the storage internals it drives. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursedbelt-server",
3
- "version": "4.50.0",
3
+ "version": "4.52.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.",
@@ -8,6 +8,9 @@
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
15
  export {
13
16
  describeSweep,
@@ -16,12 +19,30 @@ export {
16
19
  pruneEmptyDirs,
17
20
  scanDropzone,
18
21
  sweepDropzone,
22
+ walkDropzone,
19
23
  type DropHandler,
24
+ type DropzoneScan,
20
25
  type DropOutcome,
21
26
  type DroppedFile,
22
27
  type ScanOptions,
23
28
  type SweepReport,
29
+ type UnreachableLink,
24
30
  } from "./scan.js";
31
+ export {
32
+ adoptFinderAliases,
33
+ DROPZONE_LINK,
34
+ ensureDropzoneLink,
35
+ isFinderAlias,
36
+ isMountPoint,
37
+ LINKED_FREE_FLOOR_BYTES,
38
+ LINKED_OWED_WINDOW_MS,
39
+ linkedRoomBytes,
40
+ linkSource,
41
+ linkTarget,
42
+ resolveFinderAlias,
43
+ type AliasAdoption,
44
+ type LinkSource,
45
+ } from "./links.js";
25
46
  export {
26
47
  askBinaryServerAboutDuplicate,
27
48
  hashFile,
@@ -0,0 +1,225 @@
1
+ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2
+ import { existsSync, lstatSync, mkdirSync, mkdtempSync, readlinkSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { adoptFinderAliases, DROPZONE_LINK, ensureDropzoneLink, isFinderAlias, isMountPoint, linkedRoomBytes, linkSource, resolveFinderAlias } from "./links.js";
6
+ import { scanDropzone, sweepDropzone, walkDropzone, type DropOutcome } from "./scan.js";
7
+
8
+ /**
9
+ * LINKED sources (forge task 3752). Every test here is about the owner's OWN drive: a link in a
10
+ * drop folder points at folders and files that are not the sweep's to delete, prune or move.
11
+ */
12
+
13
+ let base: string;
14
+ /** The drop folder. */
15
+ let root: string;
16
+ /** Stands in for the owner's drive — everything here must survive every sweep. */
17
+ let drive: string;
18
+
19
+ const write = (at: string, bytes = 8): string => {
20
+ mkdirSync(join(at, ".."), { recursive: true });
21
+ writeFileSync(at, Buffer.alloc(bytes, 7));
22
+ return at;
23
+ };
24
+
25
+ beforeEach(() => {
26
+ base = mkdtempSync(join(tmpdir(), "dropzone-links-spec-"));
27
+ root = join(base, "drop");
28
+ drive = join(base, "drive");
29
+ mkdirSync(root);
30
+ mkdirSync(drive);
31
+ });
32
+ afterEach(() => rmSync(base, { recursive: true, force: true }));
33
+
34
+ describe("walkDropzone with followLinks", () => {
35
+ test("a link is skipped unless asked — no consumer changes behavior unasked", async () => {
36
+ write(join(drive, "a.mp3"));
37
+ symlinkSync(drive, join(root, "linked"));
38
+ expect(await scanDropzone(root)).toEqual([]);
39
+ });
40
+
41
+ test("a linked folder is walked, a linked file is one file, and each carries its real path", async () => {
42
+ write(join(drive, "Album", "a.mp3"));
43
+ const loose = write(join(base, "loose.mp3"));
44
+ write(join(root, "dropped.mp3"));
45
+ symlinkSync(drive, join(root, "Drive"));
46
+ symlinkSync(loose, join(root, "single.mp3"));
47
+
48
+ const { files, unreachable } = await walkDropzone(root, { followLinks: true });
49
+ const byPath = Object.fromEntries(files.map((f) => [f.relativePath, f.linked?.realPath ?? null]));
50
+ expect(byPath).toEqual({
51
+ "Drive/Album/a.mp3": realpathSync(join(drive, "Album", "a.mp3")),
52
+ "single.mp3": realpathSync(loose),
53
+ "dropped.mp3": null,
54
+ });
55
+ expect(unreachable).toEqual([]);
56
+ });
57
+
58
+ test("🔴 a loop, two links to one folder, and a link back into the drop folder are each walked once", async () => {
59
+ write(join(drive, "a.mp3"));
60
+ symlinkSync(drive, join(drive, "loop"));
61
+ symlinkSync(drive, join(root, "first"));
62
+ symlinkSync(drive, join(root, "second"));
63
+ write(join(root, "Own", "b.mp3"));
64
+ symlinkSync(join(root, "Own"), join(root, "back"));
65
+
66
+ const { files } = await walkDropzone(root, { followLinks: true });
67
+ const reals = files.map((f) => f.linked?.realPath ?? realpathSync(f.path));
68
+ expect(reals.filter((p) => p.endsWith("a.mp3"))).toHaveLength(1);
69
+ expect(reals.filter((p) => p.endsWith("b.mp3"))).toHaveLength(1);
70
+ });
71
+
72
+ test("an unplugged drive and a deleted folder are told apart, and only the drop folder's own links are its", async () => {
73
+ symlinkSync("/Volumes/no-such-drive-3752/tod", join(root, "unplugged"));
74
+ symlinkSync(join(base, "gone"), join(root, "deleted"));
75
+ symlinkSync(join(base, "also-gone"), join(drive, "dangling"));
76
+ symlinkSync(drive, join(root, "Drive"));
77
+
78
+ const { unreachable } = await walkDropzone(root, { followLinks: true });
79
+ const by = Object.fromEntries(unreachable.map((u) => [u.relativePath, [u.source.state, u.inDropzone]]));
80
+ expect(by).toEqual({
81
+ unplugged: ["unmounted", true],
82
+ deleted: ["deleted", true],
83
+ "Drive/dangling": ["deleted", false],
84
+ });
85
+ expect(unreachable.find((u) => u.relativePath === "unplugged")?.source).toMatchObject({ volume: "/Volumes/no-such-drive-3752" });
86
+ });
87
+
88
+ test("skipTopDirs skips a folder only directly under the root, case as APFS compares it", async () => {
89
+ write(join(root, "Dups", "x.mp3"));
90
+ write(join(drive, "dups", "y.mp3"));
91
+ symlinkSync(drive, join(root, "Drive"));
92
+ const { files } = await walkDropzone(root, { followLinks: true, skipTopDirs: ["dups"] });
93
+ expect(files.map((f) => f.relativePath)).toEqual(["Drive/dups/y.mp3"]);
94
+ });
95
+
96
+ test("skipHiddenDirs leaves another tool's state alone at every depth — a linked drive's `.Spotlight-V100` too (forge task 3754)", async () => {
97
+ write(join(root, ".cache", "x.mp3"));
98
+ write(join(drive, ".Spotlight-V100", "store.db"));
99
+ write(join(drive, "Album", "a.mp3"));
100
+ symlinkSync(drive, join(root, "Drive"));
101
+ const asked = await walkDropzone(root, { followLinks: true, skipHiddenDirs: true });
102
+ expect(asked.files.map((f) => f.relativePath)).toEqual(["Drive/Album/a.mp3"]);
103
+ // Off by default: no consumer changes behavior unasked.
104
+ expect((await walkDropzone(root, { followLinks: true })).files).toHaveLength(3);
105
+ });
106
+
107
+ test("each file carries its inode and change time, from the one stat — a replaced file is told from a kept one", async () => {
108
+ const at = write(join(drive, "a.mp3"));
109
+ symlinkSync(drive, join(root, "Drive"));
110
+ const [file] = (await walkDropzone(root, { followLinks: true })).files;
111
+ expect(file).toMatchObject({ ino: statSync(at).ino, ctimeMs: statSync(at).ctimeMs });
112
+ });
113
+ });
114
+
115
+ describe("sweepDropzone never deletes a linked file", () => {
116
+ for (const kind of ["stored", "duplicate", "discard"] as const)
117
+ test(`🔴 "${kind}" leaves the owner's copy where it lives`, async () => {
118
+ const owned = write(join(drive, "Album", "a.mp3"));
119
+ write(join(root, "dropped.mp3"));
120
+ symlinkSync(drive, join(root, "Drive"));
121
+
122
+ const report = await sweepDropzone(root, async (): Promise<DropOutcome> => ({ kind }), { stabilityMs: 0, followLinks: true });
123
+
124
+ expect(existsSync(owned)).toBe(true);
125
+ expect(existsSync(join(root, "dropped.mp3"))).toBe(false); // a dropped file still goes
126
+ expect(report.leftInPlace).toBe(1);
127
+ expect(report.bytesRemoved).toBe(8);
128
+ expect(lstatSync(join(root, "Drive")).isSymbolicLink()).toBe(true);
129
+ expect(report.remaining).toBe(0); // a link not followed is not "left in the folder"
130
+ });
131
+
132
+ test("a sweep reports the links it could not reach", async () => {
133
+ symlinkSync("/Volumes/no-such-drive-3752/tod", join(root, "unplugged"));
134
+ const report = await sweepDropzone(root, async () => ({ kind: "stored" }), { stabilityMs: 0, followLinks: true });
135
+ expect(report.unreachable.map((u) => u.source.state)).toEqual(["unmounted"]);
136
+ });
137
+ });
138
+
139
+ describe("Finder aliases", () => {
140
+ const alias = (at: string): string => {
141
+ mkdirSync(join(at, ".."), { recursive: true });
142
+ writeFileSync(at, Buffer.concat([Buffer.from("book\0\0\0\0mark\0\0\0\0", "latin1"), Buffer.alloc(400, 1)]));
143
+ return at;
144
+ };
145
+
146
+ test("the bookmark magic is an alias; content is not", async () => {
147
+ expect(await isFinderAlias(alias(join(root, "tod alias")), 416)).toBe(true);
148
+ expect(await isFinderAlias(write(join(root, "a.mp3"), 416), 416)).toBe(false);
149
+ });
150
+
151
+ test("each alias becomes a symlink to its target; one that will not resolve, and a skipped folder, are left alone", async () => {
152
+ alias(join(root, "tod alias"));
153
+ alias(join(root, "nested", "offline alias"));
154
+ alias(join(root, "done", "old alias"));
155
+ const resolve = (path: string): string | null => (path.endsWith("tod alias") ? drive : null);
156
+
157
+ const result = await adoptFinderAliases(root, { resolve, skipTopDirs: ["done"] });
158
+
159
+ expect(result).toEqual({ linked: [`tod alias → ${drive}`], unresolved: ["nested/offline alias"] });
160
+ expect(readlinkSync(join(root, "tod alias"))).toBe(drive);
161
+ expect(lstatSync(join(root, "done", "old alias")).isFile()).toBe(true);
162
+ });
163
+
164
+ // Waiting for macOS: skipped elsewhere, because only osascript and Foundation write and resolve a real alias.
165
+ test.skipIf(process.platform !== "darwin")("🔴 a REAL alias becomes a symlink to its target — headless, through Foundation (from collections, forge task 3754)", async () => {
166
+ const at = join(root, "Videos", "tod alias");
167
+ mkdirSync(join(root, "Videos"));
168
+ // Written through Foundation the way Finder writes one.
169
+ const script =
170
+ 'function run(argv){ObjC.import("Foundation");const t=$.NSURL.fileURLWithPath(argv[0]);' +
171
+ "const d=t.bookmarkDataWithOptionsIncludingResourceValuesForKeysRelativeToURLError(1<<10,$(),$(),null);" +
172
+ "return $.NSURL.writeBookmarkDataToURLOptionsError(d,$.NSURL.fileURLWithPath(argv[1]),1<<10,null);}";
173
+ const child = Bun.spawn(["osascript", "-l", "JavaScript", "-e", script, drive, at], { stdout: "ignore", stderr: "pipe" });
174
+ if ((await child.exited) !== 0) throw new Error(await new Response(child.stderr).text());
175
+ expect(resolveFinderAlias(at)).toBe(realpathSync(drive));
176
+
177
+ expect(await adoptFinderAliases(root)).toEqual({ linked: [`Videos/tod alias → ${realpathSync(drive)}`], unresolved: [] });
178
+ expect(lstatSync(at).isSymbolicLink()).toBe(true);
179
+ expect(readlinkSync(at)).toBe(realpathSync(drive));
180
+ });
181
+
182
+ test("a dry run says what it would do and changes nothing", async () => {
183
+ alias(join(root, "tod alias"));
184
+ const result = await adoptFinderAliases(root, { dryRun: true, resolve: () => drive });
185
+ expect(result.linked).toHaveLength(1);
186
+ expect(lstatSync(join(root, "tod alias")).isFile()).toBe(true);
187
+ });
188
+ });
189
+
190
+ describe("linkSource and the link beside the code", () => {
191
+ test("missing under a mounted volume is deleted; under an unmounted one, unmounted; off /Volumes, deleted", () => {
192
+ expect(linkSource(drive).state).toBe("ok");
193
+ expect(linkSource("/Volumes/X/a", () => true).state).toBe("deleted");
194
+ expect(linkSource("/Volumes/X/a", () => false)).toEqual({ state: "unmounted", target: "/Volumes/X/a", volume: "/Volumes/X" });
195
+ expect(linkSource(join(base, "gone")).state).toBe("deleted");
196
+ // A plain folder — what macOS can leave in /Volumes after an unclean eject — is not a mount point.
197
+ expect(isMountPoint(drive)).toBe(false);
198
+ expect(isMountPoint("/")).toBe(false);
199
+ });
200
+
201
+ test("linkedRoomBytes is what statfs says minus the floor and what is owed; a store that is not there holds nothing back", () => {
202
+ const room = linkedRoomBytes(base);
203
+ expect(typeof room).toBe("number");
204
+ expect(linkedRoomBytes(base, 1024)).toBe((room as number) - 1024);
205
+ expect(linkedRoomBytes(join(base, "no", "such", "store"))).toBeNull();
206
+ });
207
+
208
+ test("ensureDropzoneLink makes the folder and the link, is quiet when right, and never replaces a real file", async () => {
209
+ const app = join(base, "app");
210
+ mkdirSync(app);
211
+ const target = join(base, "state", "inbox");
212
+ expect(await ensureDropzoneLink(app, target)).toContain("linked");
213
+ expect(readlinkSync(join(app, DROPZONE_LINK))).toBe(target);
214
+ expect(existsSync(target)).toBe(true);
215
+ expect(await ensureDropzoneLink(app, target)).toBeNull();
216
+ const moved = join(base, "state", "moved");
217
+ expect(await ensureDropzoneLink(app, moved)).toContain("linked");
218
+ expect(readlinkSync(join(app, DROPZONE_LINK))).toBe(moved);
219
+
220
+ const other = join(base, "other");
221
+ mkdirSync(other);
222
+ write(join(other, DROPZONE_LINK));
223
+ expect(await ensureDropzoneLink(other, target)).toContain("left alone");
224
+ });
225
+ });
@@ -0,0 +1,219 @@
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
+ // ── A drive that went away ───────────────────────────────────────────────────────────────
22
+
23
+ /*
24
+ * Owner, 2026-10-21: *"ensure there is graceful handling if the drive gets ejected early and
25
+ * plugged back in later. It should start from where it left off unless the source folder was
26
+ * deleted."* A link whose target is not there is one of two things, and they want opposite
27
+ * answers: the drive is unplugged (wait, quietly) or the folder is gone (say so).
28
+ */
29
+
30
+ /** Where a link points and why it cannot be followed right now. */
31
+ export type LinkSource =
32
+ | { state: "ok"; target: string }
33
+ | { state: "unmounted"; target: string; volume: string }
34
+ | { state: "deleted"; target: string };
35
+
36
+ /**
37
+ * Is `dir` a mounted volume rather than the empty folder macOS can leave in `/Volumes` after an
38
+ * unclean eject? A mount point lives on a different device than the folder holding it.
39
+ */
40
+ export function isMountPoint(dir: string): boolean {
41
+ try {
42
+ return statSync(dir).dev !== statSync(dirname(dir)).dev;
43
+ } catch {
44
+ return false;
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Why a link's target is not there: its volume is not mounted (the drive is unplugged — wait), or
50
+ * the volume is there and the folder is not (it was deleted or moved — stop). A target outside
51
+ * `/Volumes` is on the boot disk, so missing means deleted.
52
+ */
53
+ export function linkSource(target: string, mounted: (dir: string) => boolean = isMountPoint): LinkSource {
54
+ if (existsSync(target)) return { state: "ok", target };
55
+ const parts = target.split("/");
56
+ if (parts[1] === "Volumes" && parts[2]) {
57
+ const volume = `/Volumes/${parts[2]}`;
58
+ if (!mounted(volume)) return { state: "unmounted", target, volume };
59
+ }
60
+ return { state: "deleted", target };
61
+ }
62
+
63
+ /** 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. */
64
+ export async function linkTarget(path: string): Promise<string | null> {
65
+ const to = await readlink(path).catch(() => null);
66
+ if (to === null) return null;
67
+ return to.startsWith("/") ? to : join(dirname(path), to);
68
+ }
69
+
70
+ // ── Finder aliases ───────────────────────────────────────────────────────────────────────
71
+
72
+ /** Every alias file (bookmark data) starts with these 16 bytes. Checked on this Mac, 2026-10-21. */
73
+ const ALIAS_MAGIC = "book\0\0\0\0mark\0\0\0\0";
74
+ /** Alias files are a few KB; nothing bigger is read to find out. */
75
+ const ALIAS_MAX_BYTES = 4 * 1024 * 1024;
76
+
77
+ /**
78
+ * Is this file a Finder alias rather than content? Finder's "Make Alias" (⌘⌥-drag) does not make
79
+ * a symlink: it makes an ordinary FILE of bookmark data, which a sweep would otherwise upload as
80
+ * content and delete.
81
+ */
82
+ export async function isFinderAlias(path: string, size: number): Promise<boolean> {
83
+ if (size < ALIAS_MAGIC.length || size > ALIAS_MAX_BYTES) return false;
84
+ const handle = await open(path, "r").catch(() => null);
85
+ if (!handle) return false;
86
+ try {
87
+ const head = Buffer.alloc(ALIAS_MAGIC.length);
88
+ await handle.read(head, 0, head.length, 0);
89
+ return head.toString("latin1") === ALIAS_MAGIC;
90
+ } finally {
91
+ await handle.close();
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Resolve an alias to the path it points at, or `null`. Foundation through JXA: no Finder, no
97
+ * Apple Events permission, no UI, and it never mounts a volume (a launchd job must not).
98
+ */
99
+ export function resolveFinderAlias(path: string): string | null {
100
+ const script =
101
+ 'function run(argv){ObjC.import("Foundation");' +
102
+ "const u=$.NSURL.URLByResolvingAliasFileAtURLOptionsError($.NSURL.fileURLWithPath(argv[0]),(1<<8)|(1<<9),null);" +
103
+ 'return u.isNil()?"":u.path.js;}';
104
+ const proc = Bun.spawnSync(["osascript", "-l", "JavaScript", "-e", script, path], { stdout: "pipe", stderr: "pipe" });
105
+ const target = proc.exitCode === 0 ? proc.stdout.toString().trim() : "";
106
+ return target && target !== path ? target : null;
107
+ }
108
+
109
+ export interface AliasAdoption {
110
+ /** `<relative path> → <target>` for each alias now a symlink. */
111
+ linked: string[];
112
+ /** Aliases that could not be resolved (the drive is not mounted) — left as they are; a walk must not ingest them. */
113
+ unresolved: string[];
114
+ }
115
+
116
+ /** Is `name` one of `names`, as APFS compares — a dropped `Dups/` IS `dups/`? */
117
+ export const namedIn = (names: readonly string[] | undefined, name: string): boolean =>
118
+ names?.some((n) => n.toLowerCase() === name.toLowerCase()) ?? false;
119
+
120
+ /**
121
+ * Swap each Finder alias under `root` for a symlink to its target, so a walk with `followLinks`
122
+ * takes it as a linked source. Never looks in a hidden folder, through an existing link, or in a
123
+ * folder `skipTopDirs` names directly under `root` (an app's quarantine, its `done/`).
124
+ */
125
+ export async function adoptFinderAliases(
126
+ root: string,
127
+ opts: { dryRun?: boolean; resolve?: (path: string) => string | null; skipTopDirs?: readonly string[] } = {},
128
+ ): Promise<AliasAdoption> {
129
+ const resolve = opts.resolve ?? resolveFinderAlias;
130
+ const result: AliasAdoption = { linked: [], unresolved: [] };
131
+ const walk = async (dir: string): Promise<void> => {
132
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
133
+ for (const entry of entries) {
134
+ const full = join(dir, entry.name);
135
+ if (entry.name.startsWith(".")) continue;
136
+ if (entry.isDirectory()) {
137
+ if (dir === root && namedIn(opts.skipTopDirs, entry.name)) continue;
138
+ await walk(full);
139
+ continue;
140
+ }
141
+ if (!entry.isFile()) continue;
142
+ const info = await lstat(full).catch(() => null);
143
+ if (!info || !(await isFinderAlias(full, info.size))) continue;
144
+ const rel = relative(root, full);
145
+ const target = resolve(full);
146
+ if (!target) {
147
+ result.unresolved.push(rel);
148
+ continue;
149
+ }
150
+ if (!opts.dryRun) {
151
+ await rm(full);
152
+ await symlink(target, full);
153
+ }
154
+ result.linked.push(`${rel} → ${target}`);
155
+ }
156
+ };
157
+ await walk(root);
158
+ return result;
159
+ }
160
+
161
+ // ── The link beside the app's code ───────────────────────────────────────────────────────
162
+
163
+ /** What the owner opens next to an app's code — a link to its drop folder, never the files. */
164
+ export const DROPZONE_LINK = "dropzone";
165
+
166
+ /**
167
+ * The link next to the app's code that opens the drop folder — the place the owner will look.
168
+ *
169
+ * 🔴 A LINK, and the files stay in `$FORGE_STATE`. A drop is data, often gigabytes of it, and a
170
+ * code tree is walked by every check, bundler and test its repo runs; the link is gitignored, and
171
+ * `tools/check-paths.ts` never follows a link into a directory. Something real already at that
172
+ * name is left alone and said. Returns what it did, or `null` when the link was already right.
173
+ */
174
+ export async function ensureDropzoneLink(appDir: string, root: string): Promise<string | null> {
175
+ const at = join(appDir, DROPZONE_LINK);
176
+ const info = await lstat(at).catch(() => null);
177
+ if (info && !info.isSymbolicLink()) return `${at} exists and is not a link — left alone`;
178
+ if (info && (await readlink(at)) === root) return null;
179
+ if (info) await rm(at);
180
+ await mkdir(root, { recursive: true });
181
+ await symlink(root, at);
182
+ return `linked ${at} → ${root}`;
183
+ }
184
+
185
+ // ── Pacing: the store is the boot disk ───────────────────────────────────────────────────
186
+
187
+ /*
188
+ * A link can put far more behind it than the Mac has room for. Measured 2026-10-21: collections'
189
+ * `tod` folder was 196 GiB with 212 GiB free on the boot volume, while binary-server's bytes land
190
+ * on this Mac and leave for B2 at most 50 GB a day (binary-server `src/b2Sweep.ts`). A linked file
191
+ * is only taken while the store would keep {@link LINKED_FREE_FLOOR_BYTES} free after it and its
192
+ * derivatives — and derivatives are built AFTER the upload, so free space alone lies for a while:
193
+ * what was linked in the last {@link LINKED_OWED_WINDOW_MS} counts as still owing them. Dropped
194
+ * files are not paced: they are already on this disk.
195
+ */
196
+
197
+ /** The store keeps at least this much free after a linked file and its derivatives land. */
198
+ export const LINKED_FREE_FLOOR_BYTES = 40 * 1024 ** 3;
199
+
200
+ /**
201
+ * How long a linked file is assumed to still owe its derivatives after it was filed. A day: the
202
+ * ladders for a ~50 GB batch took ~17 h at the measured 3.2 GB an hour, and past that they are on
203
+ * the disk, where free space already counts them — a longer window counts them twice.
204
+ */
205
+ export const LINKED_OWED_WINDOW_MS = 24 * 60 * 60 * 1000;
206
+
207
+ /**
208
+ * Bytes a linked file may still use on the store's volume, or `null` when it cannot be told
209
+ * (which holds nothing back — binary-server keeps its own floor). `owedBytes` is what the
210
+ * derivatives of recently linked files still have to take.
211
+ */
212
+ export function linkedRoomBytes(storeDir: string, owedBytes = 0): number | null {
213
+ try {
214
+ const fs = statfsSync(storeDir);
215
+ return Number(fs.bavail) * Number(fs.bsize) - LINKED_FREE_FLOOR_BYTES - owedBytes;
216
+ } catch {
217
+ return null;
218
+ }
219
+ }
@@ -1,5 +1,5 @@
1
1
  import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2
- import { existsSync, mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
2
+ import { existsSync, lstatSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import {
@@ -253,3 +253,34 @@ describe("pruneEmptyDirs", () => {
253
253
  expect(existsSync(join(root, "a/b/keep.txt"))).toBe(true);
254
254
  });
255
255
  });
256
+
257
+ describe("pruneEmptyDirs never enters a link (forge task 3752)", () => {
258
+ let drive: string;
259
+ beforeEach(() => {
260
+ drive = mkdtempSync(join(tmpdir(), "dropzone-spec-drive-"));
261
+ });
262
+ afterEach(() => rmSync(drive, { recursive: true, force: true }));
263
+
264
+ test("🔴 an empty folder behind a link survives a prune", async () => {
265
+ mkdirSync(join(drive, "Empty Album", "Disc 2"), { recursive: true });
266
+ symlinkSync(drive, join(root, "linked"));
267
+ mkdirSync(join(root, "dropped", "empty"), { recursive: true });
268
+
269
+ await pruneEmptyDirs(root);
270
+
271
+ expect(existsSync(join(drive, "Empty Album", "Disc 2"))).toBe(true);
272
+ expect(lstatSync(join(root, "linked")).isSymbolicLink()).toBe(true);
273
+ expect(existsSync(join(root, "dropped"))).toBe(false); // the drop folder's own empties still go
274
+ });
275
+
276
+ test("a folder holding only Finder's bookkeeping is empty, and goes", async () => {
277
+ write("watched/.DS_Store");
278
+ write("watched/._a.jpg");
279
+ write("kept/.DS_Store");
280
+ write("kept/held.mp3");
281
+ await pruneEmptyDirs(root);
282
+ expect(existsSync(join(root, "watched"))).toBe(false);
283
+ expect(existsSync(join(root, "kept", "held.mp3"))).toBe(true);
284
+ expect(existsSync(join(root, "kept", ".DS_Store"))).toBe(true);
285
+ });
286
+ });