Skip to content

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

docs: study replacing the trash package with PortOS-owned native recycling (#12231)

Adam Eivy5ede5f17df8b
diff --git a/docs/README.md b/docs/README.md
index 23c31dbcc7..ad9e8e7465 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -89,6 +89,8 @@ Comms & voice: [beeper](./features/beeper.md) · [messages-browser-send](./featu
- [Music Video render-grade validation](validation/9302-music-video-grade.md) — synthetic encoder parity, visual references, and remaining generated-shot acceptance.
- [Explicit Music Video render pools](decisions/2026-10-04-music-video-render-pools.md) — proposed initial shot placement and supplied-audio conditioning; final composition export remains local.
- [CoS agent permission posture](decisions/2026-10-06-cos-agent-permission-posture.md) — why unattended agents keep full-bypass instead of vendor auto-approve modes, and where stricter modes apply.
+- [Native trash feasibility study](research/2026-10-18-native-trash-feasibility.md) — can PortOS recycle media without the `trash` package: per-platform comparison, executed macOS/Linux proofs, the Windows acceptance checks, and the regression matrix.
+- [Recycle media through OS facilities PortOS owns](decisions/2026-10-18-native-trash-without-dependency.md) — replace `[email protected]` with `osascript`/JXA, PowerShell + `SHFileOperationW`, and an owned XDG adapter; implementation plan and Windows validation gate.
- **[plans/](./plans/README.md)** — dated design plans (`YYYY-MM-DD-<slug>.md`), archived on approval before implementation. Historical records, not living docs. See [provider connections and harnesses](./plans/2026-09-06-provider-connections-and-harnesses.md) for stable executable routes, migration and management flows.
- **decisions/** — ADRs (`YYYY-MM-DD-<slug>.md`), e.g. the [Postgres-as-primary-datastore decision](./decisions/2026-06-07-postgres-as-primary-datastore.md) and what may cross the federation layer ([user-controlled federation](./decisions/2026-09-19-user-controlled-federation.md), [Privacy Center storage](./decisions/2026-08-08-privacy-records-machine-local.md), [federated visual prompts](./decisions/2026-08-20-federated-visual-prompts.md), [conditioning crosses to an allowlisted peer](./decisions/2026-08-22-federated-media-input-assets.md), [AI usage metrics federate on by default](./decisions/2026-09-01-federated-usage-metrics.md), [Eidoverse guest chat](./decisions/2026-09-05-eidoverse-guest-chat.md), [numeric PortOS quality federation](./decisions/2026-09-10-portos-quality-federation.md), [federated Eidoverse foundations](./decisions/2026-09-18-federated-eidoverse-foundations.md)), why H3 [ships the draft-decode gates without an asset](./decisions/2026-08-30-h3-draft-decoder-asset.md), and why closed-set decisions run on a [local entailment model that abstains](./decisions/2026-09-18-local-jev-decision-service.md).
diff --git a/docs/decisions/2026-10-18-native-trash-without-dependency.md b/docs/decisions/2026-10-18-native-trash-without-dependency.md
new file mode 100644
index 0000000000..cef7ac2f26
--- /dev/null
+++ b/docs/decisions/2026-10-18-native-trash-without-dependency.md
@@ -0,0 +1,146 @@
+# 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
+**Evidence:** [Native trash feasibility study](../research/2026-10-18-native-trash-feasibility.md) (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, 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_Store` patching 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 pass `false`), the `execa`/`wsl-utils`
+ stack serves WSL, and `procfs`/`df`/`mount-point` reimplement a `st_dev` walk
+ that is ten lines of `node:fs`. The remaining value — three OS calls — is what
+ the adapters contain.
+- **No binaries in the supply chain.** PortOS updates through `git pull` and
+ `npm ci` on many independent installs (see the distribution model in
+ `AGENTS.md`). An ad-hoc-signed Mach-O and an unsigned `.exe` inside
+ `node_modules` run 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 when
+ `osascript` and `powershell.exe` are 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.js` already reports as `MEDIA_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`.
+
+1. **`server/lib/nativeTrash.js`** — keep `moveToNativeTrash(paths)`;
+ dispatch on `process.platform`: `darwin` → `for` each path `execFile(
+ '/usr/bin/osascript', ['-l', 'JavaScript', '-e', MACOS_TRASH_SCRIPT, path],
+ { timeout: 30_000 })` via `server/lib/childProcess.js`; `win32` → one
+ `execFile(resolveWindowsPowerShell(), ['-NoProfile', '-NonInteractive',
+ '-ExecutionPolicy', 'Bypass', '-EncodedCommand', encoded], { timeout:
+ 30_000, env: { ...process.env, PORTOS_TRASH_PATHS: paths.join('\n') } })`;
+ `linux` → `for` each path `await trashXdg(path)`; anything else throws.
+ Export the two script constants for tests. Parse the per-file JSON on
+ stdout/stderr and reject with a bounded `Error` carrying `code` and the
+ per-file report; never consult the report to decide a fallback.
+ Embedded scripts: the JXA and PowerShell bodies in
+ `docs/research/assets/native-trash-poc/{mac,windows}-poc.mjs` (`$()` typed
+ nil out-params on macOS; `[char]10` split, `Test-Path -LiteralPath`,
+ `DriveType` pre-flight, `exit 1` on any failure on Windows).
+2. **`server/lib/nativeTrashXdg.js`** — move `xdgTrash.mjs` in as
+ `trashXdg(path)`, unchanged in behaviour; add the barrel export in
+ `server/lib/index.js` and a row in `server/lib/README.md`.
+3. **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)
+ and `nativeTrashXdg.test.js` (real temp filesystem: escaping, date shape,
+ collision + `O_EXCL` reservation, orphan protection, `EXDEV` cleanup,
+ `ENOENT`, topdir chooser). `trashFiles.test.js` and the three caller suites
+ stay as the contract for partial success and history preservation.
+4. **Windows validation gate** — run
+ `docs/research/assets/native-trash-poc/windows-poc.mjs` on an interactive
+ Windows session and paste the (redacted) report in the PR. Checks 2 and 3
+ (no-bin volume and over-capacity file are refused, never deleted) decide
+ between `SHFileOperationW` + pre-flight, adding a `BitBucket` `MaxCapacity`
+ pre-check, or an `IFileOperation` interop with `FOFX_RECYCLEONDELETE`.
+ Check 6 decides between the P/Invoke and the no-compile
+ `Microsoft.VisualBasic` call. Optionally wire the opt-in
+ `PORTOS_NATIVE_TRASH_SMOKE` test into the `windows-latest` CI job once the
+ runner is shown to have a usable Recycle Bin.
+5. **Manifests and docs** — remove `trash` from `server/package.json` and
+ regenerate `server/package-lock.json` (expect the 57 entries listed in the
+ study to disappear; run `npm ls` to confirm nothing else pulled them);
+ `docs/DEPS.md`: delete the row if the dependency never merged, otherwise a
+ `REPLACED` row pointing here (the `deps-doc.test.js` parity guard accepts
+ either); update the recycling paragraph of `docs/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).
+6. **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 `trash` and 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 `osascript` and `powershell.exe` already.
+- **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; `NSFileManager` needs none.
+- **`gio trash` on Linux.** Not needed as a dependency: the adapter produces
+ identical output; `gio` remains a fine verification tool and is absent on
+ many servers.
+- **`Shell.Application` COM 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 `osascript` per file (deletion batches
+ are a handful of files; ~50 ms each).
+- Windows deletes pay an `Add-Type` compile per batch unless check 6 moves the
+ adapter to the no-compile VisualBasic call.
+- 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.
diff --git a/docs/research/2026-10-18-native-trash-feasibility.md b/docs/research/2026-10-18-native-trash-feasibility.md
new file mode 100644
index 0000000000..94748bce3b
--- /dev/null
+++ b/docs/research/2026-10-18-native-trash-feasibility.md
@@ -0,0 +1,254 @@
+# Native trash feasibility: replacing `[email protected]` with PortOS-owned recycling
+
+**Date:** 2026-10-18 · **Issue:** #12231 · **Context:** PR #12212 (recoverable image/video deletion)
+**Decision:** [ADR 2026-10-18 — recycle media through OS facilities PortOS owns](../decisions/2026-10-18-native-trash-without-dependency.md)
+**Tools and transcripts:** [`assets/native-trash-poc/`](assets/native-trash-poc/README.md)
+
+PR #12212 adds the `trash` package so that deleting a gallery image or a video
+history entry moves the originals, sidecars, thumbnails and audio masters to the
+server machine's Trash / Recycle Bin instead of unlinking them. Its review asked
+whether PortOS could own a smaller implementation with the same native behaviour
+and the same safety contract. This study answers that at the existing
+`moveToNativeTrash(paths)` boundary in `server/lib/nativeTrash.js`; everything
+above it (`trashFiles.js`: literal paths, deduplication, missing-file skips,
+directory refusal, test-data isolation, post-operation `lstat` verification,
+history/index rows retired only after success, no permanent-delete fallback) is
+unchanged by any option below.
+
+**Recommendation: replace the dependency.** Every platform has a recycling
+facility reachable from Node without a shipped binary or a new package, and the
+PortOS-owned version is *more* faithful than the package on two counts the
+package's own source shows (Finder Put Back for every file, original file names
+in the Linux trash). macOS and Linux are proven below with real native
+execution against disposable files; Windows is designed from the package's own
+helper source and from Microsoft's shell API, and is the one piece the
+implementing PR must still execute before it ships (acceptance checks are in the
+Windows section).
+
+## 1. What `[email protected]` actually ships
+
+Inspected from the published tarball (`npm pack [email protected]`, 772 KB unpacked,
+MIT) and the upstream helper repositories it vendors.
+
+| Piece | What it is | Notes for PortOS |
+|-------|------------|------------------|
+| `index.js` | glob expansion (`globby`), nested-path pruning (`is-path-inside`), `lstat` filter, platform dispatch | PortOS passes `{ glob: false }` and already deduplicates / filters, so this layer is dead weight for us |
+| `lib/macos.js` + `lib/macos-trash` | 726 KB universal Mach-O, **ad-hoc signed** (no Team ID), built from [sindresorhus/macos-trash](https://github.com/sindresorhus/macos-trash) 3.x (Swift 6.2 toolchain, macOS 13+) | Calls `FileManager.trashItem(at:resultingItemURL:)`, then rewrites the Trash's `.DS_Store` with `ptbN`/`ptbL` records because, per its own comment, *"FileManager.trashItem has a macOS bug where only the first file gets Put Back metadata"*. On a permission-error **string match** (or `TRASH_FALLBACK=1`) the JS wrapper moves files into `~/.Trash` or **`$PWD/.Trash`** by plain rename — the arbitrary-directory fallback PR #12212 had to bypass by spawning the binary itself |
+| `lib/windows.js` + `lib/windows-trash.exe` | 28 KB C program, version 2.0.0, from [sindresorhus/recycle-bin](https://github.com/sindresorhus/recycle-bin) | `IFileOperation::DeleteItems` with `FOFX_ADDUNDORECORD \| FOFX_RECYCLEONDELETE \| FOF_NOERRORUI \| FOF_NOCONFIRMATION \| FOF_SILENT \| FOFX_EARLYFAILURE`, subst-drive resolution, `SHUpdateRecycleBinIcon`. Built with MSVC/gcc on `windows-latest` in the upstream release workflow; not code-signed |
+| `lib/linux.js` | freedesktop trash written in JS: trash dir from `xdg-trashdir`, mount table from `@stroncium/procfs`, moves via `move-file`, `p-map` concurrency | Trashed files are renamed to a **random UUID** (the original name survives only inside `.trashinfo`, so a file manager's Trash view shows UUIDs); `Path=` uses `encodeURI` (leaves `#`, `?`, `;` … unescaped although the spec requires RFC 2396 escaping); `Path=` is absolute even in a `$topdir` trash; cross-device moves **copy then delete** |
+| `lib/wsl.js` | recycles through Windows PowerShell when running under WSL | needs `wsl-utils` → `powershell-utils` → `execa` |
+
+**Footprint.** The PR's lockfile diff adds **57 entries** for one direct
+dependency: the `globby → fast-glob → micromatch/picomatch/@nodelib` chain (for
+a glob option PortOS disables), `execa → cross-spawn/get-stream/onetime/…` (for
+WSL detection), `@stroncium/procfs`, `xdg-trashdir → @sindresorhus/df /
+mount-point / user-home / xdg-basedir` (two generations of `df`), `move-file`,
+`is-docker`, `is-wsl`, `pify`, `pinkie`, and two bundled executables that
+PortOS's own supply-chain policy would otherwise never admit unsigned.
+
+## 2. Platform comparison
+
+Legend: **pkg** = `[email protected]` as PR #12212 uses it (binary spawned directly on
+macOS/Windows, `trash(paths, { glob: false })` on Linux); **own** = the
+PortOS-owned design proven/specified below.
+
+### macOS
+
+| Concern | pkg (`macos-trash` binary) | own (`/usr/bin/osascript -l JavaScript`, `NSFileManager.trashItemAtURL`) |
+|---------|----------------------------|------------------------------------------------------------------------------|
+| Mechanism | same Foundation API, in a shipped Swift binary | same Foundation API, through the JXA ObjC bridge that ships with every macOS — no binary, no compile step |
+| Restore metadata (Finder *Put Back*) | binary patches `.DS_Store` itself to work around the one-record-per-process bug | **one `osascript` process per file**; the OS then writes `ptbN`/`ptbL` for every file (reproduced, §3.1). ~45–60 ms per file |
+| Collisions | OS renames (`name HH-MM-SS-mmm.ext`) | identical — same API |
+| Literal / Unicode paths | argv | argv; spaces, brackets, NFC/NFD, emoji verified |
+| Volume boundaries | per-volume `.Trashes/<uid>`; a volume without a trash is an API error | identical (RAM-disk volume verified) |
+| Permissions / TCC | the binary inherits the responsible process's TCC posture | identical; verified that the move succeeds and the post-move `lstat` works even when `~/.Trash` cannot be listed |
+| Partial success | per-file loop, exit 1 if any failed | identical; per-file JSON on stdout/stderr |
+| Process lifecycle | `execFile` + 30 s deadline | identical through `server/lib/childProcess.js` |
+| Packaging | 726 KB ad-hoc-signed universal binary inside `node_modules`; Gatekeeper is bypassed only because npm extraction sets no quarantine attribute | nothing to ship |
+| Maintenance | track upstream Swift releases | ~20 lines of JXA owned in-tree |
+| Fallbacks | JS wrapper falls back to `~/.Trash` / `$PWD/.Trash` (bypassed by PR #12212) | none, by construction |
+
+### Windows
+
+| Concern | pkg (`windows-trash.exe`) | own (Windows PowerShell 5.1 + shell32 `SHFileOperationW`) |
+|---------|---------------------------|------------------------------------------------------------|
+| Mechanism | `IFileOperation` COM, flags listed in §1 | `SHFileOperationW(FO_DELETE)` with `FOF_ALLOWUNDO \| FOF_NOCONFIRMATION \| FOF_NOERRORUI \| FOF_SILENT \| FOF_WANTNUKEWARNING` through `Add-Type` P/Invoke; `powershell.exe` is a Windows component at a fixed path, resolved the way `interactiveShellResolver.js` already does |
+| Restore metadata | `$I<id>` record written by the shell; Explorer *Restore* works | identical — same shell machinery (`FileSystem.DeleteFile(…, SendToRecycleBin)` in `Microsoft.VisualBasic` is the same call) |
+| Collisions | shell assigns unique `$I`/`$R` ids | identical |
+| Literal / Unicode paths | argv (UTF-16) | newline-separated env var read by the script, so no path meets PowerShell's parser (precedent: `fileCore.js` `DIRSIZE_TARGET`); `-EncodedCommand` carries the script |
+| Volumes without a Recycle Bin (network shares, removable media, bin size cap) | **not guarded** — the shell permanently deletes under `FOF_NOCONFIRMATION` when it cannot recycle; the helper sets no guard for it | pre-flight `DriveInfo.DriveType == Fixed` refusal plus `FOF_WANTNUKEWARNING`; the bin-capacity case is an explicit acceptance check (§3.3) |
+| Subst drives | resolved by the helper | resolve with `QueryDosDevice` (or refuse) — acceptance check |
+| Partial success | `FOFX_EARLYFAILURE` aborts the batch | per-file loop with per-file result |
+| Process lifecycle | hidden window via `windowsHide`, 30 s deadline | identical; `Add-Type` compiles once per spawn (expected ~1 s, must be measured) |
+| Packaging | 28 KB unsigned `.exe` | nothing to ship |
+| Fallbacks | none | none |
+
+### Linux
+
+| Concern | pkg (`lib/linux.js`) | own (`nativeTrashXdg.js`, `node:fs` only — proven as `assets/native-trash-poc/xdgTrash.mjs`) |
+|---------|----------------------|--------------------------------------------------------------------------------------------|
+| Spec | freedesktop Trash 1.0 | same; output byte-compatible with GLib's `gio trash` (§3.2) |
+| Trash directory | `~/.local/share/Trash` for the home device; `$topdir/.Trash/$uid` (sticky check) or `$topdir/.Trash-$uid` via procfs mountinfo + `df` | same selection; mount point found by walking up until `st_dev` changes — no procfs/df parsing |
+| Name in `files/` | random UUID | original name, `stem.N.ext` on collision; `info/` entry opened `O_EXCL` as the reservation; an orphan in `files/` is never overwritten |
+| `.trashinfo` | `encodeURI`, absolute `Path=` always | RFC 2396 escaping (verified identical to GLib for space, `#`, `%`, `?`, UTF-8), `Path=` relative to `$topdir` in a volume trash as the spec requires |
+| Cross-device | copy + delete | **refuse** (`EXDEV`/`EACCES`) and remove the reservation — same posture as GLib, which also refuses when no per-volume trash can be created |
+| Restore | file manager / `trash-cli` | identical — `trash-list` and `trash-restore` verified against our entries |
+| Fallbacks | none | none |
+
+## 3. Proof of concept
+
+Every transcript below is from **real native execution on disposable
+synthetic files**, not a mocked `process.platform` dispatch. The unit tests in
+PR #12212 (`nativeTrash.test.js`) are mocked dispatch tests and stay that way;
+the smoke scripts here are the native layer.
+
+### 3.1 macOS — executed
+
+Host: macOS 26.6.2, Node 26, `/usr/bin/osascript -l JavaScript`. Script:
+[`assets/native-trash-poc/mac-poc.mjs`](assets/native-trash-poc/mac-poc.mjs).
+Run twice, each time on the home volume (`~/.Trash`) and on a freshly created
+APFS RAM disk (`/Volumes/PortOSTrashPoc/.Trashes/501`, ejected afterwards).
+
+| Check | Result |
+|-------|--------|
+| Batch of 4 files (`a sp ace.txt`, `scene[1].png`, `ünïcödé émoji 🎬.txt`, `plain.txt`) in one process | all moved, originals gone, content intact, 48–61 ms per process |
+| Put Back records after the 4-file batch | **only the first file** had `ptbN`/`ptbL` (the bug the Swift helper patches around) |
+| Same files, **one process per file** | every file had `ptbN` = original name and `ptbL` = original directory (volume-relative on the RAM disk), 44–48 ms each |
+| Missing path | exit 1, `NSCocoaErrorDomain` code 4, message names the file; nothing else touched |
+| Batch with one missing + one real path | real file recycled, missing one reported, exit 1 — partial success is visible per file |
+| Second file with an already-trashed name | OS renamed it `plain.txt 08-01-01-985.txt`; first stayed intact |
+| Restore | `rename()` from the trash path back to the original path restored byte-identical content (what Finder's Put Back does) |
+| TCC | the shell could not list `~/.Trash` (`EPERM` on `readdir`), yet the move, the per-path `lstat` that `trashFiles.js` relies on, and the cleanup `unlink` all worked — so PortOS's existing verification strategy is the right one |
+| Cleanup | every PoC file removed from both trashes; RAM disk ejected |
+
+JXA details that matter for the implementation: out-parameters must be `$()`
+(typed nil) — `Ref()` segfaults `osascript` *after* the move has happened,
+which would look like a failed recycle of a file that is in fact gone. Return
+the JSON from `run()`; on any failure write it to stderr and `$.exit(1)` so the
+exit code and the per-file report agree.
+
+### 3.2 Linux — executed
+
+Container: `node:22-bookworm`, uid 1000, GLib 2.74.6 (`gio`), trash-cli
+0.17.1.14; three tmpfs volumes for the mount-point cases. Scripts:
+[`xdgTrash.mjs`](assets/native-trash-poc/xdgTrash.mjs) (the proposed adapter),
+[`linux-poc.mjs`](assets/native-trash-poc/linux-poc.mjs),
+[`linux-docker-run.sh`](assets/native-trash-poc/linux-docker-run.sh).
+
+| Check | Result |
+|-------|--------|
+| Home-device files (`scene[1].png`, `a sp ace.txt`, `ünïcödé 🎬.txt`, `pct%25.txt`, `hash#q?.txt`, `plain.txt`) | all in `~/.local/share/Trash/files/<original name>` with `info/<name>.trashinfo`; trash dirs created `0700` |
+| `.trashinfo` vs GLib | ours: `Path=/home/<user>/poc-src/hash%23q%3F.txt`; `gio trash` on `ref ü#.txt`: `Path=/home/<user>/poc-src/ref%20%C3%BC%23.txt` — same escaping, same `DeletionDate` shape |
+| Collision | second `plain.txt` → `files/plain.1.txt` + `info/plain.1.txt.trashinfo` |
+| User-owned second volume | `/mnt/vol/.Trash-1000/{files,info}` created `0700`, `Path=clips/clip.mp4` (relative to `$topdir`) |
+| Root-created sticky `$topdir/.Trash` (1777) | used as `/mnt/vol3/.Trash/1000/…` |
+| Root-owned 755 topdir (no trash dir creatable) | `EACCES` refusal, file untouched, no stray `.trashinfo` |
+| Missing path | `ENOENT` before anything is written |
+| Interop | `trash-list` showed all nine entries with decoded original paths across all three trash locations; `trash-restore` restored one back to `~/poc-src/` |
+
+### 3.3 Windows — designed, not executed
+
+No Windows host was available to this run; the macOS/Linux results do not
+transfer. The mechanism is specified in runnable form as
+[`assets/native-trash-poc/windows-poc.mjs`](assets/native-trash-poc/windows-poc.mjs),
+derived from the package's own helper (`recycle-bin.c`) and the documented shell
+flags. Before the Windows adapter ships, that script must pass on a real
+interactive Windows session (the `windows-latest` CI job may or may not expose a
+Recycle Bin to the runner account — establish that first):
+
+1. Recycled files are gone from the original path and have a `$I<id>` record
+ whose embedded path equals the original (the script parses `$Recycle.Bin`).
+2. A file on a volume with no Recycle Bin (mapped share, non-`Fixed`
+ `DriveType`) is refused and left in place — **never permanently deleted**.
+3. A file larger than the bin's `MaxCapacity` is refused and left in place;
+ this is the case where `FOF_NOCONFIRMATION` alone would let the shell
+ "nuke" it, and where `FOF_WANTNUKEWARNING` under `FOF_NOERRORUI` must be
+ observed to abort rather than prompt or proceed. If it does not, the
+ adapter must add a capacity pre-check (per-volume `BitBucket` `MaxCapacity`)
+ or switch to the `IFileOperation` interop with `FOFX_RECYCLEONDELETE` and
+ re-run this check.
+4. A missing path reports a non-zero code without affecting the others.
+5. Spaces, brackets, apostrophes and non-ASCII names round-trip.
+6. Measured end-to-end time including the `Add-Type` compile stays far inside
+ the 30 s deadline; if it exceeds ~3 s, swap the P/Invoke for
+ `Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile(path, 'OnlyErrorDialogs',
+ 'SendToRecycleBin', 'ThrowException')` (no compile) and re-check 2–3, since
+ that wrapper does not set `FOF_NOERRORUI`.
+
+Until that passes, the implementing PR keeps Windows on the current
+`windows-trash.exe` path only if it ships before validation — which the ADR
+advises against: ship all three adapters together once the Windows checks are
+green.
+
+## 4. Safety contract — what each option guarantees
+
+| Guarantee (from `trashFiles.js` / PR #12212) | pkg | own |
+|-----------------------------------------------|-----|-----|
+| Recoverable host recycling, user-restorable with the OS tools | yes | yes (Put Back now for every file; original names on Linux) |
+| No permanent-delete fallback | macOS/Linux yes; **Windows not guaranteed** on non-recyclable volumes | yes on macOS/Linux by API contract and by construction; Windows gated on §3.3 checks 2–3 plus the `DriveType` pre-flight |
+| No arbitrary-directory fallback | only because PR #12212 bypasses the wrapper | by construction |
+| Literal paths, no glob | `{ glob: false }` | no glob layer exists |
+| Partial success visible, history/index rows kept on failure | yes | yes — per-file results; `trashFiles.js` unchanged |
+| Bounded process lifecycle | 30 s deadline | 30 s deadline; Linux adapter has no child process at all |
+
+## 5. Regression coverage the implementation must carry
+
+Mocked-dispatch tests (CI on Linux; `pinPlatform` from `testHelper.js`):
+
+- `nativeTrash.test.js`: darwin spawns `/usr/bin/osascript` **once per path**
+ with `['-l', 'JavaScript', '-e', <script>, path]`, `{ timeout: 30_000 }`, no
+ shell, and the embedded script string is the exported constant (so a test can
+ assert it contains `trashItemAtURLResultingItemURLError` and `$.exit(1)`);
+ win32 spawns the resolved `powershell.exe` with `-NoProfile -NonInteractive
+ -ExecutionPolicy Bypass -EncodedCommand …` and the paths in
+ `env.PORTOS_TRASH_PATHS`; linux calls the XDG adapter per path and spawns
+ nothing; any other platform rejects. Non-zero exit → rejects with the parsed
+ per-file report; `killed` (deadline) → rejects; unparsable stdout → rejects;
+ **no fallback path exists to assert against**.
+- `nativeTrashXdg.test.js` (real temp filesystem, `XDG_DATA_HOME` pointed at a
+ temp dir, `os.homedir` stubbed to a sibling temp dir so `st_dev` matches):
+ names with spaces/brackets/`%`/`#`/`?`/UTF-8 produce the expected `Path=`
+ escaping and a `DeletionDate` matching `^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$`;
+ collision suffixing (`stem.N.ext`) with an `O_EXCL` reservation; an existing
+ `files/<name>` without an info file is skipped, not overwritten; a `rename`
+ failure (inject `EXDEV`) removes the reservation and leaves the original;
+ `ENOENT` for a missing source; the topdir chooser as a pure function over
+ `lstat` shapes (sticky dir → `.Trash/<uid>`; symlink / non-sticky / absent →
+ `.Trash-<uid>`).
+- `trashFiles.test.js` is already the contract for rejected / false-success /
+ unreadable-probe outcomes and needs no change; `deleteImage.test.js`,
+ `deleteHistoryItem.test.js` and `mediaAssetMutationAdmission.test.js` keep
+ proving that history/index entries survive a failed or partial recycle.
+
+Native smoke (opt-in, never on a developer's real Trash by default):
+
+- The three `assets/native-trash-poc` scripts stay the manual recycle/restore
+ proof per platform; the implementing PR re-runs them on macOS and Linux and
+ runs the Windows one on a Windows session, recording results in its
+ description.
+- Optional: a `describe.runIf(process.platform === 'win32' &&
+ process.env.PORTOS_NATIVE_TRASH_SMOKE)` test in the Windows CI job that
+ recycles a temp file and asserts a matching `$I` record, once check 1 of §3.3
+ shows the runner has a usable Recycle Bin.
+
+## 6. Remaining platform validation
+
+- **Windows:** execute `windows-poc.mjs`; checks 2–3 decide whether
+ `SHFileOperationW` + pre-flight is sufficient or the `IFileOperation`
+ interop is needed. This is the only open question in the study.
+- **macOS:** validated on 26.6 only. The JXA bridge and
+ `trashItemAtURL` exist since 10.10/10.8 respectively; the `$()`-vs-`Ref()`
+ behaviour should be re-checked on the oldest macOS PortOS supports when the
+ adapter lands (one `osascript` run of the embedded script).
+- **Linux:** validated on Debian bookworm / GLib 2.74 / trash-cli 0.17; the
+ adapter has no distro-specific dependency. WSL is a documented difference:
+ the package recycles Windows-mounted paths through PowerShell, the adapter
+ trashes into an XDG `.Trash-$uid` on the mounted drive — still recoverable,
+ just not in the Windows Recycle Bin.
+
+## References
+
+- freedesktop.org Trash specification 1.0 — <https://specifications.freedesktop.org/trash-spec/1.0/>
+- Apple `FileManager.trashItem(at:resultingItemURL:)`; JXA ObjC bridge (`ObjC.import`, `$()`)
+- Microsoft `SHFileOperationW` / `SHFILEOPSTRUCT` flags (`FOF_ALLOWUNDO`, `FOF_NOERRORUI`, `FOF_WANTNUKEWARNING`), `IFileOperation::SetOperationFlags` (`FOFX_RECYCLEONDELETE`)
+- Upstream helper sources: sindresorhus/macos-trash (`Sources/trash/main.swift`), sindresorhus/recycle-bin (`recycle-bin.c`), sindresorhus/trash `lib/linux.js`, `xdg-trashdir`
diff --git a/docs/research/assets/native-trash-poc/README.md b/docs/research/assets/native-trash-poc/README.md
new file mode 100644
index 0000000000..6c13e2cfaa
--- /dev/null
+++ b/docs/research/assets/native-trash-poc/README.md
@@ -0,0 +1,17 @@
+# Native trash proof-of-concept assets (issue #12231)
+
+Disposable, self-cleaning smoke tests behind
+[`../../2026-10-18-native-trash-feasibility.md`](../../2026-10-18-native-trash-feasibility.md).
+Each one recycles synthetic files through the mechanism the study proposes for
+that platform, verifies placement and restore metadata, restores one file, and
+removes everything it created, including from the Trash / Recycle Bin.
+
+| File | Platform | Status |
+|------|----------|--------|
+| `mac-poc.mjs` | macOS — `/usr/bin/osascript -l JavaScript` + `NSFileManager.trashItemAtURL` | Executed 2026-10-18 on macOS 26.6 (home volume + RAM-disk volume) |
+| `xdgTrash.mjs` | Linux — proposed PortOS-owned freedesktop Trash 1.0 adapter (`node:fs` only) | Executed 2026-10-18 in Docker (Debian bookworm, GLib 2.74, trash-cli 0.17) |
+| `linux-poc.mjs`, `linux-docker-run.sh` | Linux harness: home trash, `$topdir/.Trash-$uid`, sticky `$topdir/.Trash/$uid`, refusal, `gio trash` / `trash-cli` interop | Executed with the adapter above |
+| `windows-poc.mjs` | Windows — Windows PowerShell 5.1 + shell32 `SHFileOperationW` (`FOF_ALLOWUNDO`) | **Not executed** — no Windows host; its header lists the acceptance checks |
+
+These are investigation tools, not product code: nothing under `server/` imports
+them, and the implementation plan in the ADR owns the production versions.
diff --git a/docs/research/assets/native-trash-poc/linux-docker-run.sh b/docs/research/assets/native-trash-poc/linux-docker-run.sh
new file mode 100755
index 0000000000..e384012e85
--- /dev/null
+++ b/docs/research/assets/native-trash-poc/linux-docker-run.sh
@@ -0,0 +1,24 @@
+#!/bin/bash
+# Runs linux-poc.mjs inside a disposable Debian container as uid 1000 with three
+# extra tmpfs volumes: one owned by the user (-> $topdir/.Trash-1000), one with a
+# root-created sticky .Trash (-> $topdir/.Trash/1000), and one root-owned 755
+# topdir where no trash directory can be created (-> bounded EACCES refusal).
+# GLib's `gio trash` and trash-cli are installed as independent reference
+# implementations. Usage: linux-docker-run.sh <this directory>
+set -u
+POC_DIR="$1"
+docker run --rm \
+ --tmpfs /mnt/vol:uid=1000,gid=1000,mode=755 \
+ --tmpfs /mnt/vol2:uid=0,gid=0,mode=755 \
+ --tmpfs /mnt/vol3:uid=0,gid=0,mode=755 \
+ -v "$POC_DIR:/poc:ro" \
+ node:22-bookworm bash -c '
+set -e
+export DEBIAN_FRONTEND=noninteractive
+apt-get update -qq >/dev/null 2>&1
+apt-get install -y -qq libglib2.0-bin trash-cli >/dev/null 2>&1
+mkdir -m 777 /mnt/vol2/pub /mnt/vol3/pub
+mkdir -m 1777 /mnt/vol3/.Trash
+cp -r /poc /home/node/poc && chown -R node:node /home/node/poc
+su node -c "cd /home/node/poc && HOME=/home/node node linux-poc.mjs"
+'
diff --git a/docs/research/assets/native-trash-poc/linux-poc.mjs b/docs/research/assets/native-trash-poc/linux-poc.mjs
new file mode 100644
index 0000000000..e5967b232a
--- /dev/null
+++ b/docs/research/assets/native-trash-poc/linux-poc.mjs
@@ -0,0 +1,47 @@
+import { trashXdg } from './xdgTrash.mjs';
+import { mkdir, writeFile, readFile, readdir, lstat } from 'node:fs/promises';
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+const run = promisify(execFile);
+const sh = async (cmd, args, opts = {}) => { try { const { stdout, stderr } = await run(cmd, args, opts); return (stdout + stderr).trim(); } catch (e) { return `ERR(${e.code}): ${String(e.stderr || e.message).trim()}`; } };
+const exists = p => lstat(p).then(() => true, () => false);
+const out = { uid: process.getuid(), home: homedir(), node: process.version, glib: await sh('gio', ['version']), trashCli: (await sh('trash-list', ['--version'])).split('\n')[0] };
+const src = join(homedir(), 'poc-src'); await mkdir(src, { recursive: true });
+const names = ['scene[1].png', 'a sp ace.txt', 'ünïcödé 🎬.txt', 'pct%25.txt', 'hash#q?.txt', 'plain.txt'];
+for (const n of names) await writeFile(join(src, n), `payload:${n}`);
+out.homeTrash = [];
+for (const n of names) out.homeTrash.push(await trashXdg(join(src, n)).then(r => ({ n, ...r }), e => ({ n, error: e.code || e.message })));
+out.originalsGone = (await Promise.all(names.map(n => exists(join(src, n))))).every(v => !v);
+out.infoSamples = {};
+for (const n of ['scene[1].png', 'ünïcödé 🎬.txt', 'pct%25.txt', 'hash#q?.txt']) out.infoSamples[n] = await readFile(join(homedir(), '.local/share/Trash/info', `${n}.trashinfo`), 'utf8');
+// Collision: a second plain.txt
+await writeFile(join(src, 'plain.txt'), 'second');
+out.collision = await trashXdg(join(src, 'plain.txt'));
+// Reference implementation: GLib `gio trash`, then compare the info file it writes.
+await writeFile(join(src, 'ref ü#.txt'), 'ref');
+out.gioTrash = await sh('gio', ['trash', join(src, 'ref ü#.txt')]);
+out.gioInfo = await readFile(join(homedir(), '.local/share/Trash/info', 'ref ü#.txt.trashinfo'), 'utf8').catch(e => e.code);
+out.trashDirMode = (await lstat(join(homedir(), '.local/share/Trash'))).mode.toString(8);
+// Other volume (tmpfs owned by this uid) -> $topdir/.Trash-$uid with a topdir-relative Path.
+await mkdir('/mnt/vol/clips', { recursive: true }); await writeFile('/mnt/vol/clips/clip.mp4', 'video');
+out.volume = await trashXdg('/mnt/vol/clips/clip.mp4').catch(e => ({ error: e.code || e.message }));
+out.volumeInfo = out.volume.infoPath ? await readFile(out.volume.infoPath, 'utf8') : null;
+out.volumeTrashMode = out.volume.infoPath ? (await lstat('/mnt/vol/.Trash-' + process.getuid())).mode.toString(8) : null;
+// Shared sticky $topdir/.Trash (root-created 1777) -> $topdir/.Trash/$uid
+await writeFile('/mnt/vol3/pub/item.txt', 'shared');
+out.sharedTrash = await trashXdg('/mnt/vol3/pub/item.txt').catch(e => ({ error: e.code || e.message }));
+// Volume where no trash dir can be created (root-owned 755 topdir) -> bounded refusal, file untouched.
+await writeFile('/mnt/vol2/pub/stuck.txt', 'stuck');
+out.refusal = await trashXdg('/mnt/vol2/pub/stuck.txt').then(r => ({ unexpected: r }), e => ({ code: e.code, message: e.message.replace(/\/home\/[^/]+/, '~') }));
+out.refusalFileIntact = await readFile('/mnt/vol2/pub/stuck.txt', 'utf8');
+out.refusalNoLeftoverInfo = !(await exists('/mnt/vol2/.Trash-' + process.getuid() + '/info/stuck.txt.trashinfo'));
+// Missing file -> ENOENT before anything is written.
+out.missing = await trashXdg(join(src, 'nope.txt')).catch(e => e.code);
+// Interoperability: trash-cli lists our entries with their original paths, and restores one.
+out.trashList = (await sh('trash-list', [])).split('\n').map(l => l.replace(/\/home\/[^/]+/, '~')).sort();
+out.restoreAttempt = await sh('bash', ['-c', `printf '0\\n' | trash-restore ${JSON.stringify(src)} 2>&1 | tail -3`]);
+out.restoredListing = (await readdir(src)).sort();
+out.volumeListing = { files: await readdir('/mnt/vol/.Trash-1000/files').catch(e => e.code), info: await readdir('/mnt/vol/.Trash-1000/info').catch(e => e.code) };
+console.log(JSON.stringify(out, null, 1));
diff --git a/docs/research/assets/native-trash-poc/mac-poc.mjs b/docs/research/assets/native-trash-poc/mac-poc.mjs
new file mode 100644
index 0000000000..c9f8102101
--- /dev/null
+++ b/docs/research/assets/native-trash-poc/mac-poc.mjs
@@ -0,0 +1,157 @@
+// macOS proof (issue #12231 study): recycle synthetic files through
+// /usr/bin/osascript running JXA with the ObjC bridge (NSFileManager.trashItemAtURL),
+// then verify Trash placement, Finder "Put Back" records (ptbN/ptbL in the Trash's
+// .DS_Store), restore, name collisions, the failure matrix, and a second volume
+// (a RAM disk -> /Volumes/<name>/.Trashes/<uid>). Every file it creates is removed
+// again, including from the Trash. Run: node mac-poc.mjs > report.json
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+import { mkdir, writeFile, readFile, lstat, rename, unlink, rm } from 'node:fs/promises';
+import { homedir } from 'node:os';
+import { join, basename, dirname } from 'node:path';
+import { setTimeout as sleep } from 'node:timers/promises';
+
+const execFileAsync = promisify(execFile);
+// The script PortOS would embed. `$()` (typed nil) is the out-parameter idiom that
+// works on macOS 26; `Ref()` crashes osascript after the move succeeds.
+const JXA = `
+ObjC.import('Foundation');
+ObjC.import('stdlib');
+function run(argv) {
+ const fm = $.NSFileManager.defaultManager;
+ const results = [];
+ let failed = false;
+ for (const path of argv) {
+ const trashedUrl = $();
+ const error = $();
+ const ok = fm.trashItemAtURLResultingItemURLError($.NSURL.fileURLWithPath(path), trashedUrl, error);
+ if (ok) results.push({ path, trashedPath: ObjC.unwrap(trashedUrl.path) });
+ else {
+ failed = true;
+ results.push({ path, code: Number(error.code), domain: ObjC.unwrap(error.domain), error: ObjC.unwrap(error.localizedDescription) });
+ }
+ }
+ const out = JSON.stringify(results);
+ if (failed) {
+ $.NSFileHandle.fileHandleWithStandardError.writeData($(out).dataUsingEncoding($.NSUTF8StringEncoding));
+ $.exit(1);
+ }
+ return out;
+}`;
+
+async function osascriptTrash(paths) {
+ const started = Date.now();
+ try {
+ const { stdout } = await execFileAsync('/usr/bin/osascript', ['-l', 'JavaScript', '-e', JXA, ...paths], { timeout: 30_000 });
+ return { ok: true, ms: Date.now() - started, results: JSON.parse(stdout.trim()) };
+ } catch (error) {
+ let results = null;
+ try { results = JSON.parse(String(error.stderr || '').trim()); } catch {}
+ return { ok: false, ms: Date.now() - started, exitCode: error.code, killed: error.killed, results, stderr: results ? undefined : String(error.stderr || '').trim().slice(0, 300) };
+ }
+}
+
+// Finder keeps Put Back data as `ptbN` (original name) / `ptbL` (original directory)
+// `ustr` records keyed by the trashed file name inside the Trash's .DS_Store.
+const utf16be = buf => Buffer.from(buf).swap16().toString('utf16le');
+function ptbRecords(ds) {
+ const out = [];
+ for (const type of ['ptbN', 'ptbL']) {
+ let i = -1;
+ while ((i = ds.indexOf(type, i + 1, 'latin1')) !== -1) {
+ if (ds.toString('latin1', i + 4, i + 8) !== 'ustr') continue;
+ const len = ds.readUInt32BE(i + 8);
+ const value = utf16be(ds.subarray(i + 12, i + 12 + len * 2));
+ let name = null;
+ for (let L = 1; L < 256 && i - 2 * L - 4 >= 0; L++) {
+ if (ds.readUInt32BE(i - 2 * L - 4) === L) { name = utf16be(ds.subarray(i - 2 * L, i)); break; }
+ }
+ out.push({ name, type, value });
+ }
+ }
+ return out;
+}
+async function putBackFor(trashDir, trashedNames) {
+ // ~/.Trash is TCC-protected: a terminal without Full Disk Access can stat and open
+ // known paths but cannot list the directory, and the .DS_Store read may be EPERM.
+ const ds = await readFile(join(trashDir, '.DS_Store')).catch(e => e.code);
+ if (typeof ds === 'string') return { dsStore: ds, records: {} };
+ const recs = ptbRecords(ds);
+ const records = {};
+ for (const n of trashedNames) {
+ const mine = recs.filter(r => r.name === n);
+ const ptbL = mine.find(r => r.type === 'ptbL')?.value ?? null;
+ records[n] = { ptbN: mine.find(r => r.type === 'ptbN')?.value ?? null, ptbL: ptbL === null ? null : redact('/' + ptbL) };
+ }
+ return { dsStore: 'present', records };
+}
+const exists = p => lstat(p).then(() => true, e => { if (e.code === 'ENOENT') return false; throw e; });
+const redact = p => p.replace(homedir(), '~');
+const redactResults = r => ({ ...r, results: r.results?.map(x => ({ ...x, path: redact(x.path), trashedPath: x.trashedPath && redact(x.trashedPath), error: x.error && redact(x.error) })) });
+const trashedOf = r => (r.results || []).filter(x => x.trashedPath);
+
+async function exercise(root, label) {
+ const report = {};
+ await mkdir(root, { recursive: true });
+ const names = ['a sp ace.txt', 'scene[1].png', 'ünïcödé émoji 🎬.txt', 'plain.txt'];
+ const paths = names.map(n => join(root, n));
+ for (const p of paths) await writeFile(p, `payload:${basename(p)}`);
+ // 1. Batch: four files in ONE osascript process.
+ const batch = await osascriptTrash(paths);
+ report.batch = redactResults(batch);
+ const trashed = trashedOf(batch);
+ const trashDir = dirname(trashed[0].trashedPath);
+ report.batchVerify = {
+ originalsGone: (await Promise.all(paths.map(p => exists(p)))).every(v => v === false),
+ trashedExist: (await Promise.all(trashed.map(r => exists(r.trashedPath)))).every(Boolean),
+ trashDir: redact(trashDir),
+ contentIntact: (await readFile(trashed[1].trashedPath, 'utf8')) === `payload:${names[1]}`,
+ };
+ await sleep(1500);
+ report.batchPutBack = await putBackFor(trashDir, trashed.map(r => basename(r.trashedPath)));
+ // 2. One osascript process PER FILE.
+ const perPaths = ['per-1.txt', 'per-2.txt'].map(n => join(root, n));
+ for (const p of perPaths) await writeFile(p, 'per');
+ const per = [];
+ for (const p of perPaths) per.push(await osascriptTrash([p]));
+ report.perFile = per.map(r => ({ ok: r.ok, ms: r.ms }));
+ await sleep(1500);
+ const perTrashed = per.flatMap(trashedOf);
+ report.perFilePutBack = await putBackFor(trashDir, perTrashed.map(r => basename(r.trashedPath)));
+ // 3. Failure matrix: missing file; a batch with one missing path (partial success).
+ report.missing = redactResults(await osascriptTrash([join(root, 'does-not-exist.txt')]));
+ const partialOk = join(root, 'partial-ok.txt'); await writeFile(partialOk, 'p');
+ report.partial = redactResults(await osascriptTrash([join(root, 'nope.txt'), partialOk]));
+ report.partialVerify = { okFileGone: !(await exists(partialOk)) };
+ // 4. Collision: a second file whose name is already in the Trash.
+ await writeFile(paths[3], 'second plain');
+ report.collision = redactResults(await osascriptTrash([paths[3]]));
+ // 5. Restore: move a trashed file back to its original path (what Finder's Put Back does).
+ await rename(trashed[0].trashedPath, trashed[0].path);
+ report.restore = { restored: await exists(trashed[0].path), content: await readFile(trashed[0].path, 'utf8') };
+ // Cleanup: remove every PoC file still in the Trash (content-checked), then the run dir.
+ const leftovers = [...trashed.slice(1), ...perTrashed, ...trashedOf(report.partial), ...trashedOf(report.collision)];
+ let removed = 0;
+ for (const r of leftovers) {
+ const p = r.trashedPath.replace(/^~/, homedir());
+ const body = await readFile(p, 'utf8').catch(() => null);
+ if (body !== null && /^(payload:|per$|p$|second plain$)/.test(body)) { await unlink(p); removed++; }
+ }
+ report.cleanup = { leftovers: leftovers.length, removed };
+ await rm(root, { recursive: true, force: true });
+ return { label, ...report };
+}
+
+const out = { host: { macOS: (await execFileAsync('/usr/bin/sw_vers', ['-productVersion'])).stdout.trim(), node: process.version, osascript: '/usr/bin/osascript -l JavaScript' } };
+const here = dirname(new URL(import.meta.url).pathname);
+out.homeVolume = await exercise(join(here, `run-${Date.now()}`), 'same volume as home (~/.Trash)');
+// Second volume: a RAM disk, so the per-volume .Trashes/<uid> path is exercised and torn down.
+const { stdout: dev } = await execFileAsync('/usr/bin/hdiutil', ['attach', '-nomount', 'ram://65536']);
+const disk = dev.trim();
+try {
+ await execFileAsync('/usr/sbin/diskutil', ['erasevolume', 'APFS', 'PortOSTrashPoc', disk]);
+ out.ramDiskVolume = await exercise('/Volumes/PortOSTrashPoc/poc', 'separate volume (RAM disk)');
+} finally {
+ await execFileAsync('/usr/sbin/diskutil', ['eject', disk]).catch(() => execFileAsync('/usr/bin/hdiutil', ['detach', disk, '-force']));
+}
+console.log(JSON.stringify(out, null, 2));
diff --git a/docs/research/assets/native-trash-poc/windows-poc.mjs b/docs/research/assets/native-trash-poc/windows-poc.mjs
new file mode 100644
index 0000000000..620c283ffc
--- /dev/null
+++ b/docs/research/assets/native-trash-poc/windows-poc.mjs
@@ -0,0 +1,145 @@
+// Windows proof (issue #12231 study) — NOT YET EXECUTED. No Windows host was
+// available to the investigation; this is the proposed mechanism in runnable form
+// so the implementation PR (or a Windows CI job) can validate it. It recycles
+// synthetic files through Windows PowerShell 5.1 (a Windows component) calling
+// shell32 SHFileOperationW with FOF_ALLOWUNDO, the same shell path the retired
+// Microsoft.VisualBasic FileSystem.DeleteFile(..., SendToRecycleBin) wraps, then
+// checks the Recycle Bin's $I<id> metadata records the original path and restores
+// one file by moving its $R<id> twin back. Run from an interactive user session:
+// node windows-poc.mjs > report.json
+// Acceptance (all must hold before the design is adopted):
+// 1. every recycled file is gone from its original path and has a $I record
+// whose embedded path equals the original;
+// 2. a file on a volume with no Recycle Bin (mapped network share, or a
+// non-Fixed DriveType) is REFUSED and left in place — never permanently deleted;
+// 3. a file larger than the bin's MaxCapacity is refused and left in place
+// (FOF_WANTNUKEWARNING + FOF_NOERRORUI must not fall through to a permanent delete);
+// 4. a missing path reports a non-zero code without affecting the other paths;
+// 5. names with spaces, brackets, apostrophes and non-ASCII characters round-trip;
+// 6. the whole batch, including the Add-Type compile, completes well inside the
+// 30-second deadline (record the measured milliseconds).
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+import { mkdir, writeFile, readFile, readdir, lstat, rename, unlink, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join, basename, parse } from 'node:path';
+
+const execFileAsync = promisify(execFile);
+const POWERSHELL = join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
+// Paths travel in an environment variable (newline-separated; newlines are illegal in
+// Windows file names) so no path ever touches PowerShell's parser.
+const SCRIPT = String.raw`
+$ErrorActionPreference = 'Stop'
+Add-Type -TypeDefinition @'
+using System;
+using System.IO;
+using System.Runtime.InteropServices;
+public static class PortOSRecycle {
+ // 64-bit layout (no Pack): PortOS runs under 64-bit Node; Pack=1 is the x86 layout.
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
+ public struct SHFILEOPSTRUCT {
+ public IntPtr hwnd; public uint wFunc;
+ [MarshalAs(UnmanagedType.LPWStr)] public string pFrom;
+ [MarshalAs(UnmanagedType.LPWStr)] public string pTo;
+ public ushort fFlags;
+ [MarshalAs(UnmanagedType.Bool)] public bool fAnyOperationsAborted;
+ public IntPtr hNameMappings;
+ [MarshalAs(UnmanagedType.LPWStr)] public string lpszProgressTitle;
+ }
+ [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
+ static extern int SHFileOperationW(ref SHFILEOPSTRUCT op);
+ const uint FO_DELETE = 3;
+ // FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_WANTNUKEWARNING
+ const ushort FLAGS = 0x0004 | 0x0010 | 0x0040 | 0x0400 | 0x4000;
+ public static int Recycle(string path, out bool aborted) {
+ var op = new SHFILEOPSTRUCT { wFunc = FO_DELETE, pFrom = path + "\0\0", fFlags = FLAGS };
+ int rc = SHFileOperationW(ref op);
+ aborted = op.fAnyOperationsAborted;
+ return rc;
+ }
+ // Pre-flight: only a Fixed drive owns a $Recycle.Bin; shares and removable media
+ // would otherwise be permanently deleted by the shell under FOF_NOCONFIRMATION.
+ public static string DriveType(string path) {
+ return new DriveInfo(Path.GetPathRoot(path)).DriveType.ToString();
+ }
+}
+'@
+$results = @()
+$failed = $false
+foreach ($path in ($env:PORTOS_TRASH_PATHS -split [char]10 | Where-Object { $_ -ne '' })) {
+ if (-not (Test-Path -LiteralPath $path)) { $failed = $true; $results += @{ path = $path; code = 2; error = 'missing' }; continue }
+ $type = [PortOSRecycle]::DriveType($path)
+ if ($type -ne 'Fixed') { $failed = $true; $results += @{ path = $path; code = -1; error = "no recycle bin on $type drive" }; continue }
+ $aborted = $false
+ $rc = [PortOSRecycle]::Recycle($path, [ref]$aborted)
+ if ($rc -ne 0 -or $aborted -or (Test-Path -LiteralPath $path)) { $failed = $true; $results += @{ path = $path; code = $rc; aborted = $aborted } }
+ else { $results += @{ path = $path; recycled = $true } }
+}
+$json = ConvertTo-Json -Compress -InputObject @($results)
+if ($failed) { [Console]::Error.WriteLine($json); exit 1 }
+[Console]::Out.WriteLine($json)
+`;
+
+async function powershellRecycle(paths) {
+ const started = Date.now();
+ const args = ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', Buffer.from(SCRIPT, 'utf16le').toString('base64')];
+ const options = { timeout: 30_000, windowsHide: true, env: { ...process.env, PORTOS_TRASH_PATHS: paths.join('\n') } };
+ try {
+ const { stdout } = await execFileAsync(POWERSHELL, args, options);
+ return { ok: true, ms: Date.now() - started, results: [].concat(JSON.parse(stdout.trim())) };
+ } catch (error) {
+ let results = null;
+ try { results = [].concat(JSON.parse(String(error.stderr || '').trim())); } catch {}
+ return { ok: false, ms: Date.now() - started, exitCode: error.code, killed: error.killed, results, stderr: results ? undefined : String(error.stderr || '').trim().slice(0, 500) };
+ }
+}
+
+// $I<id>.<ext>: 8-byte header, 8-byte size, 8-byte FILETIME, then (Win10+) a 4-byte
+// path length and the UTF-16LE original path. The matching $R<id>.<ext> is the payload.
+async function recycleBinRecords(drive) {
+ const { stdout } = await execFileAsync(POWERSHELL, ['-NoProfile', '-NonInteractive', '-Command', '[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value'], { windowsHide: true });
+ const binDir = join(drive, '$Recycle.Bin', stdout.trim());
+ const records = [];
+ for (const name of await readdir(binDir)) {
+ if (!name.startsWith('$I')) continue;
+ const buf = await readFile(join(binDir, name));
+ const version = buf.readBigUInt64LE(0);
+ const original = version >= 2n
+ ? buf.toString('utf16le', 28, 28 + (buf.readUInt32LE(24) - 1) * 2)
+ : buf.toString('utf16le', 24).replace(/\0.*$/s, '');
+ records.push({ infoFile: join(binDir, name), payloadFile: join(binDir, '$R' + name.slice(2)), original });
+ }
+ return records;
+}
+const exists = p => lstat(p).then(() => true, e => { if (e.code === 'ENOENT') return false; throw e; });
+
+const root = join(tmpdir(), `portos-trash-poc-${Date.now()}`);
+await mkdir(root, { recursive: true });
+const names = ['a sp ace.txt', 'scene[1].png', "it's.txt", 'ünïcödé émoji 🎬.txt', 'plain.txt'];
+const paths = names.map(n => join(root, n));
+for (const p of paths) await writeFile(p, `payload:${basename(p)}`);
+const report = { host: { windows: process.env.OS, node: process.version, powershell: POWERSHELL } };
+report.batch = await powershellRecycle(paths);
+report.batchVerify = { originalsGone: (await Promise.all(paths.map(p => exists(p)))).every(v => v === false) };
+const records = await recycleBinRecords(parse(root).root);
+report.restoreMetadata = Object.fromEntries(paths.map(p => [basename(p), records.some(r => r.original.toLowerCase() === p.toLowerCase())]));
+report.missing = await powershellRecycle([join(root, 'does-not-exist.txt')]);
+const partialOk = join(root, 'partial-ok.txt'); await writeFile(partialOk, 'p');
+report.partial = await powershellRecycle([join(root, 'nope.txt'), partialOk]);
+report.partialVerify = { okFileGone: !(await exists(partialOk)) };
+await writeFile(paths[4], 'second plain');
+report.collision = await powershellRecycle([paths[4]]);
+// Restore: move the $R payload of the first file back where it came from, drop its $I.
+const first = records.find(r => r.original.toLowerCase() === paths[0].toLowerCase());
+if (first) { await rename(first.payloadFile, paths[0]); await unlink(first.infoFile); }
+report.restore = { restored: await exists(paths[0]), content: first ? await readFile(paths[0], 'utf8') : null };
+// Cleanup: remove every PoC payload still in the bin (content-checked), then the run dir.
+let removed = 0;
+for (const r of await recycleBinRecords(parse(root).root)) {
+ if (!r.original.toLowerCase().startsWith(root.toLowerCase())) continue;
+ const body = await readFile(r.payloadFile, 'utf8').catch(() => null);
+ if (body !== null && /^(payload:|p$|second plain$)/.test(body)) { await unlink(r.payloadFile); await unlink(r.infoFile); removed++; }
+}
+report.cleanup = { removed };
+await rm(root, { recursive: true, force: true });
+console.log(JSON.stringify(report, null, 2));
diff --git a/docs/research/assets/native-trash-poc/xdgTrash.mjs b/docs/research/assets/native-trash-poc/xdgTrash.mjs
new file mode 100644
index 0000000000..9281426a03
--- /dev/null
+++ b/docs/research/assets/native-trash-poc/xdgTrash.mjs
@@ -0,0 +1,81 @@
+// Proposed PortOS-owned Linux adapter (issue #12231 study): freedesktop.org Trash specification 1.0,
+// built on node:fs only. One file per call; the caller owns batching and
+// post-operation verification, exactly like the macOS/Windows helpers.
+import { lstat, mkdir, open, rename, unlink } from 'node:fs/promises';
+import { basename, dirname, extname, isAbsolute, join, relative, resolve } from 'node:path';
+import { homedir } from 'node:os';
+
+const homeTrashDir = () => {
+ const dataHome = process.env.XDG_DATA_HOME;
+ return join(dataHome && isAbsolute(dataHome) ? dataHome : join(homedir(), '.local', 'share'), 'Trash');
+};
+
+// Mount point of `path`: the highest ancestor still on the same device.
+async function topDirOf(path, dev) {
+ let dir = dirname(path);
+ for (;;) {
+ const parent = dirname(dir);
+ if (parent === dir) return dir;
+ if ((await lstat(parent)).dev !== dev) return dir;
+ dir = parent;
+ }
+}
+
+// Spec §"Trash directories": prefer $topdir/.Trash/$uid when $topdir/.Trash is a
+// sticky, non-symlink directory; otherwise $topdir/.Trash-$uid. A .Trash that
+// fails the checks MUST NOT be used.
+async function topDirTrash(topDir, uid) {
+ const shared = join(topDir, '.Trash');
+ const info = await lstat(shared).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
+ if (info?.isDirectory() && !info.isSymbolicLink() && (info.mode & 0o1000) !== 0) return join(shared, String(uid));
+ return join(topDir, `.Trash-${uid}`);
+}
+
+async function trashLocation(absPath) {
+ const [fileInfo, homeInfo] = await Promise.all([lstat(absPath), lstat(homedir())]);
+ if (fileInfo.dev === homeInfo.dev) return { dir: homeTrashDir(), topDir: null };
+ const topDir = await topDirOf(absPath, fileInfo.dev);
+ return { dir: await topDirTrash(topDir, process.getuid()), topDir };
+}
+
+// RFC 2396 escaping as the spec requires: every byte outside the unreserved set,
+// keeping '/' as the segment separator.
+const encodePath = path => path.split('/').map(encodeURIComponent).join('/');
+const pad = n => String(n).padStart(2, '0');
+const deletionDate = (d = new Date()) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
+const exists = path => lstat(path).then(() => true, error => { if (error.code === 'ENOENT') return false; throw error; });
+
+export async function trashXdg(path) {
+ const absPath = resolve(path);
+ const { dir, topDir } = await trashLocation(absPath);
+ const filesDir = join(dir, 'files');
+ const infoDir = join(dir, 'info');
+ await mkdir(filesDir, { recursive: true, mode: 0o700 });
+ await mkdir(infoDir, { recursive: true, mode: 0o700 });
+ const base = basename(absPath);
+ const ext = extname(base);
+ const stem = base.slice(0, base.length - ext.length);
+ const recordedPath = topDir ? relative(topDir, absPath) : absPath;
+ for (let attempt = 0; attempt < 1000; attempt++) {
+ const name = attempt === 0 ? base : `${stem}.${attempt}${ext}`;
+ const infoPath = join(infoDir, `${name}.trashinfo`);
+ const target = join(filesDir, name);
+ // The info file is the atomic reservation (O_EXCL); an orphan in files/ also blocks the name.
+ let handle;
+ try { handle = await open(infoPath, 'wx', 0o600); } catch (error) { if (error.code === 'EEXIST') continue; throw error; }
+ try {
+ if (await exists(target)) { await handle.close(); handle = null; await unlink(infoPath); continue; }
+ await handle.writeFile(`[Trash Info]\nPath=${encodePath(recordedPath)}\nDeletionDate=${deletionDate()}\n`);
+ await handle.close();
+ handle = null;
+ await rename(absPath, target);
+ return { trashedPath: target, infoPath };
+ } catch (error) {
+ // Nothing moved: EXDEV (no usable per-volume trash), EACCES, etc. surface as a bounded refusal.
+ if (handle) await handle.close().catch(() => {});
+ await unlink(infoPath).catch(() => {});
+ throw error;
+ }
+ }
+ throw new Error('No free name in the trash directory');
+}