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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
docs: close the second review round on the native trash proofs (#12231)
Adam Eivy179c0bc34075
diff --git a/docs/decisions/2026-10-18-native-trash-without-dependency.md b/docs/decisions/2026-10-18-native-trash-without-dependency.mdindex 3a17843004..6cbeccac38 100644--- a/docs/decisions/2026-10-18-native-trash-without-dependency.md+++ b/docs/decisions/2026-10-18-native-trash-without-dependency.md@@ -23,7 +23,7 @@ components every supported OS already ships:|----|-----------|--------------|| 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, refuses a trash directory that is not a caller-owned real directory (`TRASH_DIR_UNSAFE`, so a symlink planted on a shared volume cannot redirect the move), keeps `.trashinfo` names within NAME_MAX, and refuses instead of copying across devices |+| 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, refuses a trash directory that is not a caller-owned real directory (`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, and refuses instead of copying across devices |Nothing above `moveToNativeTrash` changes: `trashFiles.js` still filters toexisting literal files, refuses directories, guards test data, verifies each@@ -88,8 +88,8 @@ replaces the adapter and records the removal in `docs/DEPS.md`.and `nativeTrashXdg.test.js` (real temp filesystem: escaping, date shape,collision + `O_EXCL` reservation, orphan protection, `EXDEV` cleanup,`ENOENT`, topdir chooser, `TRASH_DIR_UNSAFE` on a symlinked or- foreign-owned trash directory, NAME_MAX-length names, `XDG_DATA_HOME` on- another device). `trashFiles.test.js` and the three caller suites+ foreign-owned trash directory, NAME_MAX-length names and extensions,+ directory symlink into another volume, `XDG_DATA_HOME` on another device). `trashFiles.test.js` and the three caller suitesstay 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 interactivediff --git a/docs/research/2026-10-18-native-trash-feasibility.md b/docs/research/2026-10-18-native-trash-feasibility.mdindex be96c480e3..94dea57d6f 100644--- a/docs/research/2026-10-18-native-trash-feasibility.md+++ b/docs/research/2026-10-18-native-trash-feasibility.md@@ -88,9 +88,9 @@ PortOS-owned design proven/specified below.| 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, with the home trash serving the device the home trash *directory* lives on (`XDG_DATA_HOME` may sit on another volume; its nearest existing ancestor decides); mount point found by walking up until `st_dev` changes — no procfs/df parsing |+| Trash directory | `~/.local/share/Trash` for the home device; `$topdir/.Trash/$uid` (sticky check) or `$topdir/.Trash-$uid` via procfs mountinfo + `df` | same selection, with the home trash serving the device the home trash *directory* lives on (`XDG_DATA_HOME` may sit on another volume; its nearest existing ancestor decides); mount point found by walking up the *physical* parent (`realpath` of the directory, final component kept as given) until `st_dev` changes — no procfs/df parsing, and a directory symlink into another volume cannot place the trash below that volume's real root || Trash directory validation | `mkdir -p` of whatever is there | the trash dir and its `files/` / `info/` must be non-symlink directories owned by the caller, re-checked after creation; anything else is a `TRASH_DIR_UNSAFE` refusal, so a `.Trash-$uid` symlink planted on a shared volume cannot redirect the move |-| 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; the stem is shortened by code points when `<name>.trashinfo` would exceed NAME_MAX (255 bytes), the full original path staying in the info file |+| 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; when `<name>.trashinfo` would exceed NAME_MAX (255 bytes) the stem is shortened by code points first and then the extension, the full original path staying in the info file || `.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 |@@ -131,7 +131,7 @@ exit code and the per-file report agree.### 3.2 Linux — executedContainer: `node:22-bookworm`, uid 1000, GLib 2.74.6 (`gio`), trash-cli-0.17.1.14; four tmpfs volumes for the mount-point cases. The harness exits 1 on any failed assertion; the run recorded here is the second one, after the review hardening (directory validation, home-trash device rule, NAME_MAX bound): `PASS`, 0 failures. Scripts:+0.17.1.14; four tmpfs volumes for the mount-point cases. The harness exits 1 on any failed assertion; the run recorded here is the second one, after the review hardening (directory validation, home-trash device rule, physical-parent discovery, NAME_MAX bound): `PASS`, 0 failures. 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).@@ -146,9 +146,11 @@ Container: `node:22-bookworm`, uid 1000, GLib 2.74.6 (`gio`), trash-cli| Root-owned 755 topdir (no trash dir creatable) | `EACCES` refusal, file untouched, no stray `.trashinfo` || Root-planted `.Trash-1000 -> /tmp/evil` symlink on a volume | `TRASH_DIR_UNSAFE` refusal, file untouched, link target stays empty || 254-byte basename | recycled under a 241-byte stem + `.txt` so the `.trashinfo` name fits NAME_MAX; the info file carries the complete original path |+| `a.` + 250-character extension; 125 × `ü` + `.txt` (254 bytes) | both recycled within NAME_MAX with valid UTF-8 names (extension shortened for the first, stem by code points for the second) and the full original path recorded |+| `~/linkdir -> /mnt/vol/linked`, file trashed through the link | lands in `/mnt/vol/.Trash-1000/files/`, `Path=linked/via-link.txt` — the volume's own trash, not a `.Trash-1000` under the link || `XDG_DATA_HOME` on the second volume | a file on that volume lands in `/mnt/vol/xdg/Trash` — the home trash directory's device decides, not `$HOME`'s || Missing path | `ENOENT` before anything is written |-| Interop | `trash-list` showed all eleven entries with decoded original paths across the home, `.Trash-1000`, `.Trash/1000` and `XDG_DATA_HOME` trashes; `trash-restore` restored one back to `~/poc-src/` |+| Interop | `trash-list` showed all fourteen entries with decoded original paths across the home, `.Trash-1000`, `.Trash/1000` and `XDG_DATA_HOME` trashes; `trash-restore` restored one back to `~/poc-src/` |### 3.3 Windows — designed, not executed@@ -159,7 +161,10 @@ derived from the package's own helper (`recycle-bin.c`) and the documented shellflags. The harness asserts every check and exits non-zero for anything but`PASS`; the two refusal scenarios need operator-supplied inputs(`PORTOS_POC_NO_BIN_DIR`, `PORTOS_POC_OVER_CAPACITY_BYTES`) and the run reports-`INCOMPLETE` without them — an incomplete run is not a pass. Before the Windows+`INCOMPLETE` without them — an incomplete run is not a pass. Its cleanup runs in a+`finally` block and matches owned `$I`/`$R` pairs by exact original path plus body+or byte size, so a failed run still removes its artifacts without ever reading+the oversized probe. Before the Windowsadapter 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 runneraccount — establish that first):@@ -224,7 +229,9 @@ Mocked-dispatch tests (CI on Linux; `pinPlatform` from `testHelper.js`):`lstat` shapes (sticky dir → `.Trash/<uid>`; symlink / non-sticky / absent →`.Trash-<uid>`); a pre-existing symlink or foreign-owned trash directory (or`files/` / `info/`) → `TRASH_DIR_UNSAFE` with nothing moved; a 255-byte- basename recycled under a shortened name with the full path in `Path=`;+ basename, a 250-character extension and a multibyte stem each recycled under+ a shortened, valid-UTF-8 name with the full path in `Path=`; a source reached+ through a directory symlink into another volume uses that volume's trash;`XDG_DATA_HOME` on a different device than `$HOME` → a file on the data-homedevice uses the home trash.- `trashFiles.test.js` is already the contract for rejected / false-success /diff --git a/docs/research/assets/native-trash-poc/linux-poc.mjs b/docs/research/assets/native-trash-poc/linux-poc.mjsindex aed923a01d..09c0983150 100644--- a/docs/research/assets/native-trash-poc/linux-poc.mjs+++ b/docs/research/assets/native-trash-poc/linux-poc.mjs@@ -2,7 +2,7 @@// linux-docker-run.sh, which provides the extra volumes it expects. Exits 1 when// any assertion fails so a broken adapter cannot produce a passing-looking report.import { trashXdg } from './xdgTrash.mjs';-import { mkdir, writeFile, readFile, readdir, lstat } from 'node:fs/promises';+import { mkdir, writeFile, readFile, readdir, lstat, symlink } from 'node:fs/promises';import { execFile } from 'node:child_process';import { promisify } from 'node:util';import { homedir } from 'node:os';@@ -34,6 +34,17 @@ await writeFile(join(src, longName), 'long');out.longName = await trashXdg(join(src, longName)).then(r => ({ trashedBase: r.trashedPath.split('/').pop(), infoHasFullPath: false, r }), e => ({ error: e.code }));if (out.longName.r) { out.longName.infoHasFullPath = (await readFile(out.longName.r.infoPath, 'utf8')).includes(longName); delete out.longName.r; }check('long name: recycled with full original path recorded', out.longName.infoHasFullPath === true);+// Long extension ('a.' + 250 chars) and a multibyte stem (125 x 'ü' + '.txt' = 254 bytes): both must fit NAME_MAX+// without splitting a code point, with the full original path in the info file.+out.longVariants = {};+for (const [label, n] of [['longExt', 'a.' + 'x'.repeat(250)], ['multibyteStem', 'ü'.repeat(125) + '.txt']]) {+ await writeFile(join(src, n), label);+ out.longVariants[label] = await trashXdg(join(src, n)).then(async r => {+ const trashedBase = r.trashedPath.split('/').pop();+ return { trashedBytes: Buffer.byteLength(trashedBase), validUtf8: Buffer.from(trashedBase).toString() === trashedBase, infoHasFullPath: (await readFile(r.infoPath, 'utf8')).includes(encodeURIComponent(n)) };+ }, e => ({ error: e.code }));+ check(`${label}: recycled within NAME_MAX with full path recorded`, out.longVariants[label].trashedBytes <= 245 && out.longVariants[label].validUtf8 && out.longVariants[label].infoHasFullPath);+}// 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')]);@@ -45,6 +56,13 @@ out.volume = await trashXdg('/mnt/vol/clips/clip.mp4').catch(e => ({ error: e.coout.volumeInfo = out.volume.infoPath ? await readFile(out.volume.infoPath, 'utf8') : null;check('volume: .Trash-uid with relative Path', out.volumeInfo?.includes('Path=clips/clip.mp4') === true);out.volumeTrashMode = out.volume.infoPath ? (await lstat(`/mnt/vol/.Trash-${uid}`)).mode.toString(8) : null;+// Directory symlink from home into the other volume: the trash must be the volume's own, not below the link.+await mkdir('/mnt/vol/linked', { recursive: true });+await symlink('/mnt/vol/linked', join(homedir(), 'linkdir'));+await writeFile(join(homedir(), 'linkdir', 'via-link.txt'), 'linked');+out.dirSymlink = await trashXdg(join(homedir(), 'linkdir', 'via-link.txt')).catch(e => ({ error: e.code || e.message }));+out.dirSymlinkInfo = out.dirSymlink.infoPath ? await readFile(out.dirSymlink.infoPath, 'utf8') : null;+check('directory symlink into another volume: that volume\'s trash, Path relative to its root', out.dirSymlink.trashedPath === `/mnt/vol/.Trash-${uid}/files/via-link.txt` && out.dirSymlinkInfo?.includes('Path=linked/via-link.txt') === true);// XDG_DATA_HOME on that other volume: a file there is now on the home trash's device and goes there.await writeFile('/mnt/vol/clips/same-dev.mp4', 'video');process.env.XDG_DATA_HOME = '/mnt/vol/xdg';diff --git a/docs/research/assets/native-trash-poc/windows-poc.mjs b/docs/research/assets/native-trash-poc/windows-poc.mjsindex 9b1b04d089..68dedeec46 100644--- a/docs/research/assets/native-trash-poc/windows-poc.mjs+++ b/docs/research/assets/native-trash-poc/windows-poc.mjs@@ -127,76 +127,89 @@ 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 } };+// Everything this run may leave in the Recycle Bin, keyed by original path: a small text+// body to compare, or an exact byte size for the oversized probe, which is never read.+const owned = new Map();+const own = async (path, body) => { await writeFile(path, body); owned.set(path.toLowerCase(), { body }); };+const noBinDir = process.env.PORTOS_POC_NO_BIN_DIR;+const overBytes = Number(process.env.PORTOS_POC_OVER_CAPACITY_BYTES);+const bait = noBinDir ? join(noBinDir, `portos-poc-no-bin-${Date.now()}.txt`) : null;+const huge = join(root, 'over-capacity.bin');-// 1 + 5 + 6: batch of awkward names, one PowerShell process.-report.batch = await powershellRecycle(paths);-check('batch: exit 0', report.batch.ok);-check('batch: originals gone', (await Promise.all(paths.map(p => exists(p)))).every(v => v === false));-check('batch: inside deadline with margin (<10 s)', report.batch.ms < 10_000);-let records = await recycleBinRecords(parse(root).root);-report.restoreMetadata = Object.fromEntries(paths.map(p => [basename(p), records.some(r => sameFile(r.original, p))]));-check('batch: every file has a $I record naming its original path', Object.values(report.restoreMetadata).every(Boolean));+try {+ for (const p of paths) await own(p, `payload:${basename(p)}`);-// 4: missing path alone, and beside a real one (partial success).-report.missing = await powershellRecycle([join(root, 'does-not-exist.txt')]);-check('missing: non-zero exit with a per-file code', !report.missing.ok && report.missing.results?.[0]?.code === 2);-const partialOk = join(root, 'partial-ok.txt'); await writeFile(partialOk, 'p');-report.partial = await powershellRecycle([join(root, 'nope.txt'), partialOk]);-check('partial: real file recycled, missing one reported', !report.partial.ok && !(await exists(partialOk)) && report.partial.results?.some(r => r.recycled));+ // 1 + 5 + 6: batch of awkward names, one PowerShell process.+ report.batch = await powershellRecycle(paths);+ check('batch: exit 0', report.batch.ok);+ check('batch: originals gone', (await Promise.all(paths.map(p => exists(p)))).every(v => v === false));+ check('batch: inside deadline with margin (<10 s)', report.batch.ms < 10_000);+ let records = await recycleBinRecords(parse(root).root);+ report.restoreMetadata = Object.fromEntries(paths.map(p => [basename(p), records.some(r => sameFile(r.original, p))]));+ check('batch: every file has a $I record naming its original path', Object.values(report.restoreMetadata).every(Boolean));-// Collision: the shell assigns a fresh $I/$R id; both copies must be in the bin.-await writeFile(paths[4], 'second plain');-report.collision = await powershellRecycle([paths[4]]);-records = await recycleBinRecords(parse(root).root);-check('collision: two $I records for the same original path', records.filter(r => sameFile(r.original, paths[4])).length === 2);+ // 4: missing path alone, and beside a real one (partial success).+ report.missing = await powershellRecycle([join(root, 'does-not-exist.txt')]);+ check('missing: non-zero exit with a per-file code', !report.missing.ok && report.missing.results?.[0]?.code === 2);+ const partialOk = join(root, 'partial-ok.txt'); await own(partialOk, 'p');+ report.partial = await powershellRecycle([join(root, 'nope.txt'), partialOk]);+ check('partial: real file recycled, missing one reported', !report.partial.ok && !(await exists(partialOk)) && report.partial.results?.some(r => r.recycled));-// 2: a volume with no Recycle Bin must be refused, file intact. Requires an operator-supplied directory.-const noBinDir = process.env.PORTOS_POC_NO_BIN_DIR;-if (noBinDir) {- const bait = join(noBinDir, `portos-poc-no-bin-${Date.now()}.txt`);- await writeFile(bait, 'bait');- report.noRecycleBinVolume = await powershellRecycle([bait]);- const intact = (await readFile(bait, 'utf8').catch(() => null)) === 'bait';- check('no-bin volume: refused', !report.noRecycleBinVolume.ok);- check('no-bin volume: file intact (never permanently deleted)', intact);- if (intact) await unlink(bait);-} else {- incomplete.push('no-bin volume (set PORTOS_POC_NO_BIN_DIR)');-}+ // Collision: the shell assigns a fresh $I/$R id; both copies must be in the bin.+ await own(paths[4], 'second plain');+ report.collision = await powershellRecycle([paths[4]]);+ records = await recycleBinRecords(parse(root).root);+ check('collision: two $I records for the same original path', records.filter(r => sameFile(r.original, paths[4])).length === 2);-// 3: a file larger than the bin's MaxCapacity must be refused, file intact.-const overBytes = Number(process.env.PORTOS_POC_OVER_CAPACITY_BYTES);-if (Number.isFinite(overBytes) && overBytes > 0) {- const huge = join(root, 'over-capacity.bin');- await execFileAsync('fsutil', ['file', 'createnew', huge, String(overBytes)], { windowsHide: true });- report.overCapacity = await powershellRecycle([huge]);- const stat = await lstat(huge).catch(() => null);- check('over-capacity: refused', !report.overCapacity.ok);- check('over-capacity: file intact with its full size', stat?.size === overBytes);- if (stat) await unlink(huge);-} else {- incomplete.push('over-capacity file (set PORTOS_POC_OVER_CAPACITY_BYTES)');-}+ // 2: a volume with no Recycle Bin must be refused, file intact. Requires an operator-supplied directory.+ if (bait) {+ await own(bait, 'bait');+ report.noRecycleBinVolume = await powershellRecycle([bait]);+ check('no-bin volume: refused', !report.noRecycleBinVolume.ok);+ check('no-bin volume: file intact (never permanently deleted)', (await readFile(bait, 'utf8').catch(() => null)) === 'bait');+ } else {+ incomplete.push('no-bin volume (set PORTOS_POC_NO_BIN_DIR)');+ }-// Restore: move the $R payload of the first file back where it came from, drop its $I.-const first = records.find(r => sameFile(r.original, paths[0]));-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 };-check('restore: byte-identical content back at the original path', report.restore.content === `payload:${names[0]}`);+ // 3: a file larger than the bin's MaxCapacity must be refused, file intact.+ if (Number.isFinite(overBytes) && overBytes > 0) {+ await execFileAsync('fsutil', ['file', 'createnew', huge, String(overBytes)], { windowsHide: true });+ owned.set(huge.toLowerCase(), { size: overBytes });+ report.overCapacity = await powershellRecycle([huge]);+ const stat = await lstat(huge).catch(() => null);+ check('over-capacity: refused', !report.overCapacity.ok);+ check('over-capacity: file intact with its full size', stat?.size === overBytes);+ } else {+ incomplete.push('over-capacity file (set PORTOS_POC_OVER_CAPACITY_BYTES)');+ }-// 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++; }+ // Restore: move the $R payload of the first file back where it came from, drop its $I.+ const first = records.find(r => sameFile(r.original, paths[0]));+ 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 };+ check('restore: byte-identical content back at the original path', report.restore.content === `payload:${names[0]}`);+} finally {+ // Cleanup runs even when a check threw: remove every owned $I/$R pair (matched by exact+ // original path and by body or by size, never by reading an oversized payload), then+ // whatever is still at the original paths, then the run directory.+ let removed = 0;+ for (const r of await recycleBinRecords(parse(root).root).catch(() => [])) {+ const expected = owned.get(r.original.toLowerCase());+ if (!expected) continue;+ const stat = await lstat(r.payloadFile).catch(() => null);+ if (!stat) continue;+ const mine = 'size' in expected+ ? stat.size === expected.size+ : stat.size < 1024 && (await readFile(r.payloadFile, 'utf8').catch(() => null)) === expected.body;+ if (mine) { await unlink(r.payloadFile); await unlink(r.infoFile); removed++; }+ }+ if (bait) await unlink(bait).catch(() => {});+ await rm(root, { recursive: true, force: true });+ report.cleanup = { removed };+ report.failures = failures;+ report.incomplete = incomplete;+ report.status = failures.length ? 'FAIL' : incomplete.length ? 'INCOMPLETE' : 'PASS';+ console.log(JSON.stringify(report, null, 2));}-report.cleanup = { removed };-await rm(root, { recursive: true, force: true });-report.failures = failures;-report.incomplete = incomplete;-report.status = failures.length ? 'FAIL' : incomplete.length ? 'INCOMPLETE' : 'PASS';-console.log(JSON.stringify(report, null, 2));process.exit(report.status === 'PASS' ? 0 : 1);diff --git a/docs/research/assets/native-trash-poc/xdgTrash.mjs b/docs/research/assets/native-trash-poc/xdgTrash.mjsindex 2b0cde829b..cbe487b5ad 100644--- a/docs/research/assets/native-trash-poc/xdgTrash.mjs+++ b/docs/research/assets/native-trash-poc/xdgTrash.mjs@@ -1,7 +1,7 @@// 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 { lstat, mkdir, open, realpath, rename, unlink } from 'node:fs/promises';import { basename, dirname, extname, isAbsolute, join, relative, resolve } from 'node:path';import { homedir } from 'node:os';@@ -80,20 +80,27 @@ 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; });-// Name inside files/: the original basename, `stem.N.ext` on collision, and the-// stem shortened by whole code points when `<name>.trashinfo` would exceed-// NAME_MAX. The complete original path always survives in the info file.+// Name inside files/: the original basename, `stem.N.ext` on collision, shortened+// by whole code points when `<name>.trashinfo` would exceed NAME_MAX — the stem+// first (the extension keeps the file recognisable), then the extension itself.+// The complete original path always survives in the info file.function trashName(base, attempt) {- const ext = extname(base);const suffix = attempt === 0 ? '' : `.${attempt}`;- const budget = NAME_MAX_BYTES - Buffer.byteLength(INFO_SUFFIX) - Buffer.byteLength(suffix) - Buffer.byteLength(ext);+ const budget = NAME_MAX_BYTES - Buffer.byteLength(INFO_SUFFIX) - Buffer.byteLength(suffix);+ let ext = extname(base);const stem = Array.from(base.slice(0, base.length - ext.length));- while (stem.length > 1 && Buffer.byteLength(stem.join('')) > budget) stem.pop();+ while (stem.length > 1 && Buffer.byteLength(stem.join('') + ext) > budget) stem.pop();+ while (Buffer.byteLength(stem.join('') + ext) > budget) ext = Array.from(ext).slice(0, -1).join('');return `${stem.join('')}${suffix}${ext}`;}export async function trashXdg(path) {- const absPath = resolve(path);+ // Device and mount-point discovery need the physical parent: through a directory+ // symlink into another volume, lexical ancestors would place the volume trash+ // below the real mount root where no trash tool looks. The final component is+ // kept as given so a source that is itself a symlink is what gets recycled.+ const given = resolve(path);+ const absPath = join(await realpath(dirname(given)), basename(given));const { dir, topDir } = await trashLocation(absPath);const uid = process.getuid();const filesDir = join(dir, 'files');