Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
ADR: Recycle media through OS facilities PortOS owns, not the trash package
Date: 2026-10-18
Status: Accepted — macOS and Linux mechanisms proven; the Windows mechanism is specified and must pass its acceptance checks in the implementing PR before any adapter ships. Implemented by issue #12246 (server/lib/nativeTrash.js, server/lib/nativeTrashXdg.js); the POC harnesses now import the production scripts. Windows checks executed on a windows-latest runner: check 2 passed on the DriveType pre-flight; check 3 showed that FOF_WANTNUKEWARNING makes the shell block on a confirmation no unattended process can answer (the deadline kill left the file intact), so the adapter adds the BitBucket MaxCapacity / NukeOnDelete pre-check — the shell-recorded value when present, else the OS default of 10% of the first 40 GB plus 5% of the rest, which matched the values the shell wrote for two fresh volumes; check 6 measured 0.5 s per batch after first use (4.2 s on a cold runner), so the P/Invoke stays and the Microsoft.VisualBasic call is not needed. PowerShell also serialises a redirected error stream as CLIXML, so the report is written to stdout on both paths
Evidence: Native trash feasibility study (issue #12231)
Question
PR #12212 makes gallery image and video-history deletion recoverable by moving
files to the server machine's Trash / Recycle Bin, and reaches that through
[email protected]: 57 lockfile entries, a 726 KB ad-hoc-signed Swift binary for
macOS, an unsigned 28 KB C executable for Windows, and a JavaScript freedesktop
implementation for Linux. Should PortOS keep that dependency behind
moveToNativeTrash(paths), or own the recycling code?
Decision
Own it. server/lib/nativeTrash.js keeps its moveToNativeTrash(paths)
contract and dispatches to three PortOS-owned adapters that use only Node and
components every supported OS already ships:
| OS | Mechanism | Why this one |
|---|---|---|
| macOS | /usr/bin/osascript -l JavaScript running an embedded JXA script that calls NSFileManager.trashItemAtURL, one process per file |
Same Foundation API the package's binary wraps, no binary to ship or sign. One process per file is what gives every file a Finder Put Back record — the OS writes the record only for the first trashItem call in a process (reproduced on macOS 26.6), which is the bug the package's binary patches .DS_Store to hide. ~50 ms per file |
| Windows | Windows PowerShell 5.1 (%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe, resolved like interactiveShellResolver.js) running an -EncodedCommand script that P/Invokes shell32 SHFileOperationW(FO_DELETE) with FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT | FOF_WANTNUKEWARNING, paths delivered in PORTOS_TRASH_PATHS (newline-separated), with a DriveType == Fixed pre-flight |
The same shell machinery the package's IFileOperation helper and Microsoft.VisualBasic's SendToRecycleBin use, without a compiled artifact. The pre-flight closes a hole the package leaves open: under FOF_NOCONFIRMATION the shell permanently deletes what it cannot recycle (network shares, removable media, bin capacity) |
| Linux | server/lib/nativeTrashXdg.js, a freedesktop Trash 1.0 implementation on node:fs (proven as docs/research/assets/native-trash-poc/xdgTrash.mjs) |
Byte-compatible with GLib's gio trash and readable/restorable by trash-cli; keeps original file names (the package uses random UUIDs), escapes Path= per the spec, writes $topdir-relative paths in volume trashes, honours the sticky $topdir/.Trash rule only when root or the caller owns that directory (the sticky bit never binds the owner), refuses a trash directory that is not a caller-owned real directory and a volume root whose entries other users could rename (TRASH_DIR_UNSAFE, so a symlink planted on a shared volume cannot redirect the move), keeps .trashinfo names within NAME_MAX, discovers the volume from the physical parent so a directory symlink cannot misplace the trash, resolves mounts through /proc/self/mountinfo (with a st_dev fallback) so a bind mount sharing the home device gets its own volume trash rather than an EXDEV, and refuses instead of copying across devices |
Nothing above moveToNativeTrash changes: trashFiles.js still filters to
existing literal files, refuses directories, guards test data, verifies each
path is gone afterwards, and callers retire history/index rows only after that
verification. There is still no permanent-delete fallback and no
arbitrary-directory fallback — on macOS and Linux by API contract and by
construction, on Windows by the pre-flight plus the acceptance checks below.
Why
- Parity is not a trade-off here; the owned code is more faithful. Every
file gets Finder Put Back (the package's wrapper-level fallback and
.DS_Storepatching exist to paper over exactly the behaviours we avoid by spawning per file); Linux trash entries carry their real names and spec-correct metadata; Windows gains a guard against silent permanent deletion that the package does not have. - The dependency buys code PortOS disables. Of the 57 packages, the glob
stack serves
{ glob: true }(we passfalse), theexeca/wsl-utilsstack serves WSL, andprocfs/df/mount-pointreimplement a mount lookup that is a few dozen lines ofnode:fs. The remaining value — three OS calls — is what the adapters contain. - No binaries in the supply chain. PortOS updates through
git pullandnpm cion many independent installs (see the distribution model inAGENTS.md). An ad-hoc-signed Mach-O and an unsigned.exeinsidenode_modulesrun today only because npm extraction sets no quarantine attribute; owning a native helper ourselves would mean a Swift/MSVC build, signing/notarization and a committed binary — none of which is needed whenosascriptandpowershell.exeare already on the machine. - Risk is bounded by the existing contract. The adapters fail closed; the
worst case of a wrong adapter is a refused deletion with the file still in
place, which
trashFiles.jsalready reports asMEDIA_TRASH_FAILED(503) without touching history.
Implementation plan
One PR, all three adapters together, after the Windows checks pass. If PR
#12212 is still open when the work starts, land this inside it (drop the
dependency before it ever reaches main); otherwise a follow-up PR that
replaces the adapter and records the removal in docs/DEPS.md.
server/lib/nativeTrash.js— keepmoveToNativeTrash(paths); dispatch onprocess.platform:darwin→foreach pathexecFile( '/usr/bin/osascript', ['-l', 'JavaScript', '-e', MACOS_TRASH_SCRIPT, path], { timeout: 30_000 })viaserver/lib/childProcess.js;win32→ oneexecFile(resolveWindowsPowerShell(), ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', encoded], { timeout: 30_000, env: { ...process.env, PORTOS_TRASH_PATHS: paths.join('\n') } });linux→foreach pathawait trashXdg(path); anything else throws. Export the two script constants for tests. Parse the per-file JSON on stdout/stderr and reject with a boundedErrorcarryingcodeand the per-file report; never consult the report to decide a fallback. Embedded scripts: the JXA and PowerShell bodies indocs/research/assets/native-trash-poc/{mac,windows}-poc.mjs($()typed nil out-params on macOS;[char]10split,Test-Path -LiteralPath,DriveTypepre-flight,exit 1on any failure on Windows).server/lib/nativeTrashXdg.js— movexdgTrash.mjsin astrashXdg(path), unchanged in behaviour; add the barrel export inserver/lib/index.jsand a row inserver/lib/README.md.- Tests — the regression matrix in §5 of the study:
nativeTrash.test.js(mocked dispatch per platform, per-file spawn count, argv shape, env delivery, deadline/killed, non-zero exit, unparsable output, no fallback) andnativeTrashXdg.test.js(real temp filesystem: escaping, date shape, collision +O_EXCLreservation, orphan protection,EXDEVcleanup,ENOENT, topdir chooser with the owner rule,TRASH_DIR_UNSAFEon a symlinked or foreign-owned trash directory or a volume root other users could rename, mountinfo parsing, a bind mount on the home device, NAME_MAX-length names and extensions, directory symlink into another volume,XDG_DATA_HOMEon another device).trashFiles.test.jsand the three caller suites stay as the contract for partial success and history preservation. - Windows validation gate — run
docs/research/assets/native-trash-poc/windows-poc.mjson an interactive Windows session withPORTOS_POC_NO_BIN_DIRandPORTOS_POC_OVER_CAPACITY_BYTESset, and paste the (redacted) report in the PR; the harness exits non-zero for anything butPASS. Checks 2 and 3 (no-bin volume and over-capacity file are refused, never deleted) decide betweenSHFileOperationW+ pre-flight, adding aBitBucketMaxCapacitypre-check, or anIFileOperationinterop withFOFX_RECYCLEONDELETE. Check 6 decides between the P/Invoke and the no-compileMicrosoft.VisualBasiccall. Optionally wire the opt-inPORTOS_NATIVE_TRASH_SMOKEtest into thewindows-latestCI job once the runner is shown to have a usable Recycle Bin. - Manifests and docs — remove
trashfromserver/package.jsonand regenerateserver/package-lock.json(expect the 57 entries listed in the study to disappear; runnpm lsto confirm nothing else pulled them);docs/DEPS.md: delete the row if the dependency never merged, otherwise aREPLACEDrow pointing here (thedeps-doc.test.jsparity guard accepts either); update the recycling paragraph ofdocs/IMAGE_GALLERY.md(per-file Finder Put Back, original names in Linux trash, Windows refusal on volumes without a Recycle Bin); add the Linux adapter to the storage/ops docs only if an operator-visible path is introduced (none is planned — trash locations are the OS defaults). - CI/packaging — nothing new: no native build, no signing, no postinstall. The Windows shard already runs the server suite; the Linux adapter's real-filesystem tests run everywhere.
Alternatives considered
- Keep
trashand accept the footprint. Rejected: it ships two unsigned binaries, 50+ transitive packages mostly serving disabled features, a wrapper fallback the PR already has to bypass, and weaker restore metadata on two of three platforms. - Ship a PortOS-built native helper (Swift / C). Rejected: adds a
toolchain, signing/notarization and a committed binary for behaviour that
the OS exposes through
osascriptandpowershell.exealready. - AppleScript to Finder (
tell application "Finder" to delete). Rejected: Apple Events need an Automation TCC grant for the responsible process, which an unattended PM2 server cannot answer;NSFileManagerneeds none. gio trashon Linux. Not needed as a dependency: the adapter produces identical output;gioremains a fine verification tool and is absent on many servers.Shell.ApplicationCOM on Windows. Rejected: shows confirmation UI depending on user settings.
Consequences
- One fewer direct dependency and 57 fewer lockfile entries; no bundled executables.
- macOS deletes spawn one short-lived
osascriptper file (deletion batches are a handful of files; ~50 ms each). - Windows deletes pay an
Add-Typecompile per batch (about 0.5 s once the runtime is warm); check 6 confirmed that is well inside the deadline. - WSL installs recycle into an XDG trash on the mounted drive rather than the Windows Recycle Bin; documented, recoverable, out of scope.
- If a future macOS release changes the per-process Put Back behaviour, the per-file spawn keeps working (it is correct either way); only the investigation's rationale becomes historical.